gamelan
Search EarthWeb
CodeGuru | Gamelan | Jars | Wireless | Discussions
Navigate developer.com
Architecture & Design  
Database  
Java
Languages & Tools
Microsoft & .NET
Open Source  
Project Management  
Security  
Techniques  
Voice  
Web Services  
Wireless/Mobile
XML  
Technology Jobs  

   Developer.com Webcasts:
  The Impact of Coding Standards and Code Reviews

  Project Management for the Developer

  Defining Your Own Software Development Methodology

  more Webcasts...




See the Winners!


Developer Jobs

Be a Commerce Partner
KVM Switches
Prepaid Phone Card
Career Education
Remote Online Backup
Compare Prices
Data Center Solutions
Hurricane Shutters
Condos For Sale
Online Universities
Promotional Products
Home Improvement
Phone Cards
Imprinted Promotions
GPS

 


  Rethinking the Datacenter
Sponsored by HP
Today's datacenters need to increase utilization, get control over power and cooling costs, and align with business objectives. Download this eBook to learn about the challenges facing the data center in a world where digital information is growing at a torrid pace and costs are being held in check. Learn more. »
 
  Putting the Green into IT
Sponsored by HP
Electricity use in data centers is skyrocketing, sending energy bills through the roof, creating environmental concerns and generating negative publicity. "Going Green" means looking to technologies like virtualization, energy-efficient chips and racks, and implementing policies that extend beyond the data center. Learn more. »
 
  Managing the Modern Network
Sponsored by HP
In a global economy where information crosses the globe in an instant, and where Web-based applications power business, it's more important than ever to ensure your network is safe from threats and optimized to deliver the data your business needs. »
 
  Evaluating Software as a Service for Your Business
Sponsored by Webroot
Is Software as a Service just hype, or is something really going on here? See if your company can benefit as SaaS tries to change the face of the enterprise. »
 
  Is Your Disaster Recovery Plan Good Enough?
Sponsored by HP
Preparing for a disaster is more often than not part of the storage planning process, and it is one of the most difficult tasks, since it includes local hardware and software, networking equipment, and a test plan. Learn how to get disaster recovery right. »
 
Related Article -
Introduction to Java Data Objects (JDO)
Developer News -
SaaS Tool Offers Custom Database Development    May 9, 2008
Microsoft’s Automated Agent: Can We Talk?    May 7, 2008
Borland Finally Sells CodeGear    May 7, 2008
Red Hat Heads For The JON 2.0    May 7, 2008
Free Tech Newsletter -

Project Management Guide: Developing a Web Site. Best Practices, Tips and Strategies. Download Exclusive eBook Now.

Castor Cures Your Data Binding Ills
By Thomas Hammell

Go to page: 1  2  Next  

Castor oil was once billed as a miracle cure. Even today, there are many Web sites that extol the amazing healing properties of Castor oil. Whether this was the inspiration for the name for Exolab's open source data binding framework or not remains a mystery. In fact, Exolab goes out of their way in the documentation to hide the origin of the name.

No matter what the inspiration, Castor is a valuable tool that every Java developer should be familiar with. Castor is a data-binding framework. It provides a simple API that can be used by developers to convert Java objects to XML files and to bind Java objects to database tables. Castor implements most of the functionality of Sun's JAXB (Java XML Binding) and JDO (Java Data Objects) specifications although it is not fully compliant with either of them.

Java XML Binding

Converting Java objects to XML files usually involves writing a lot of custom code using the SAX (Simple API for XML) or DOM (Document Object Model) API. Writing this code involves creating a custom parser that converts a Java object to and from an XML file. This is a very tedious process and is hard to maintain.

Castor eliminates the need to write any custom code by providing methods that can introspect a Java object and using a set of rules convert it to and from an XML file. The process Castor uses is very similar to serialization. The Castor XML API provides two main classes for Java to XML binding: Marshaller and Unmarshaller. Marshaller is the main class used to convert a Java object to an XML file. The Unmarshaller class is used to convert an XML file to a Java object.

In order for Castor to do this automatic conversion, the Java objects must implement a Java bean interface that has setter and getter methods for all its member variables.

Consider the following classes that are used to represent directory and file nodes in a file system. The UML diagram for these classes is shown in Figure 1. There are four classes. The FileSystemNode is the base class for all nodes in a file system. It contains the properties that are common to both file and directory nodes. Two classes extend the FileSystemNode class, DirectoryNode and FileNode, and implement methods that are specific to the file and directory nodes. The NodeTypeConst class is used to encapsulate storing and comparing of the different node types. The full source code for these classes and all examples in this article can be downloaded here.


Figure 1: UML diagram of File System classes

To demonstrate how Castor can be used to convert Java objects to and from an XML file, let's create a set of file and directory nodes and save them to an XML file. The code snippet below shows the creation of the various objects. The top level of the hierarchy is:

    // Create a few nodes of  a file system
    DirectoryNode rootNode = new DirectoryNode("Root");
    DirectoryNode srcDir = new DirectoryNode("src");
    DirectoryNode classDir = new DirectoryNode("classes");

    FileNode srcFile = new FileNode("XMLConverter.java", 5);
    FileNode xmlFile = new FileNode("rootNode.xml", 1);
    FileNode classFile = new FileNode("XMLConverter.class", 3);
    classFile.setLock(true);

    classDir.addChild(classFile);
    srcDir.addChild(srcFile);
    srcDir.addChild(xmlFile);
    rootNode.addChild(srcDir);
    rootNode.addChild(classDir);

a "Root" node that contains two sub directories "src" and "classes". The src directory contains two files: "XMLConverter.java and "rootNode.xml". The class's directory contains one file: "XMLConverter.class".

To save the root node and all its descendants, you would use the Marshaller class as follows:

     // Create a File to marshal to
     FileWriter writer = new FileWriter("rootNode.xml");

     // Create a marshaller
     Marshaller marshaller = new Marshaller(writer);

     // marshal the object to an xml file
     marshaller.marshal(rootNode);

That's all there is to it. Castor introspects the rootNode object and all its associated classes and creates an XML file. The important thing to remember is that the rootNode object and all the associated classes need getter methods for each member variable. If a member variable does not have a getter method, it will not be save to the XML file.

The resultant XML file from the marshal operation is shown below. As you can see, it contains all the information contained in the rootNode object including its descendants.

<directory-node node-type-int="1">
  <node-type node-type="1"/>
  <name>Root</name>
  <child-list node-type-int="1" xsi:type="java:DirectoryNode"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <node-type node-type="1"/>
    <name>src</name>
    <child-list locked="false" lock="false" filesize="5"
                node-type-int="0" xsi:type="java:FileNode">
      <name>XMLConverter.java</name>
      <node-type node-type="0"/>
    </child-list>
    <child-list locked="false" lock="false" filesize="1"
                node-type-int="0" xsi:type="java:FileNode">
      <name>rootNode.xml</name>
      <node-type node-type="0"/>
    </child-list>
  </child-list>
  <child-list node-type-int="1" xsi:type="java:DirectoryNode"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <node-type node-type="1"/>
    <name>classes</name>
    <child-list locked="true" lock="true" filesize="3"
                node-type-int="0" xsi:type="java:FileNode">
      <name>XMLConverter.class</name>
      <node-type node-type="0"/>
    </child-list>
  </child-list>
</directory-node>

To convert an XML file to a Java object, you would use Castor's Unmarshaller class, as shown in the following code snippet .

    // Create a Reader to the file to unmarshal from
    FileReader reader = new FileReader("rootNode.xml");

    // Create the unmarshaller
    Unmarshaller unmarshaller = new Unmarshaller
                                (FileSystemNode.class);

     // Unmarshal the object
     FileSystemNode rootNode = (FileSystemNode)
                               unmarshaller.unmarshal(reader);

Again, it's a simple operation. Castor parses the XML file and creates all the objects defined in the file. For the unmarshalling to work correctly, each associated class has to have setter methods for each of the attributes and/or nodes in the XML file. Also, each class must have a zero argument constructor. If a class has a member variable that is a collection, such as the FileSystemNode's m_childList, it also helps to have an add method that is used to add individual members to the collection.

It's important to point out that Castor uses a naming convention to find the correct getter and setter methods for the member variables. If there are problems with the marshalling and unmarshalling, they are usually caused by improperly named setter and getter methods.

If you want more control over the format and content of the XML file, you can use a mapping file to better control the conversion between the object and XML file. The mapping file is an XML file that has elements for each class. These elements are used to map the class to a specific XML tag . The class elements contain field elements that are used to define the individual properties of each of the member variables of the class. Each field element contains a bind-xml element, which is used to define the field to XML mapping.

The mapping file for our file system classes is shown below.

<mapping>
  <class name="FileSystemNode" auto-complete="false">
    <description>Default mapping for class
                         FileSystemNode</description>
    <map-to xml="FileSystemNode"/>
    <field name="type" type="NodeTypeConst" required="false"
                       direct="false" transient="false"
                       get-method="getNodeType">
      <bind-xml name="node-type" node="element"/>
    </field>
    <field name="name" type="string" required="false"
                       direct="false" transient="false">
      <bind-xml name="name" node="element"/>
    </field>
  </class>
  <class name="DirectoryNode" auto-complete="false">
    <description>Default mapping for class
                         DirectoryNode</description>
    <map-to xml="directory-node"/>
    <field name="type" type="NodeTypeConst" required="false"
                       direct="false" transient="false"
                       get-method="getNodeType">
      <bind-xml name="node-type" node="element"/>
    </field>
    <field name="name" type="string" required="false"
                       direct="false" transient="false">
      <bind-xml name="name" node="element"/>
    </field>
    <field name="ChildList" type="FileSystemNode"
                            required="false" direct="false"
                            transient="false" collection="vector">
      <bind-xml name="child-list" node="element"/>
    </field>
  </class>
  <class name="FileNode" auto-complete="false">
    <description>Default mapping for class FileNode</description>
    <map-to xml="file-node"/>
    <field name="type" type="NodeTypeConst" required="false"
                       direct="false" transient="false"
                       get-method="getNodeType">
      <bind-xml name="node-type" node="element"/>
    </field>
    <field name="name" type="string" required="false"
                       direct="false" transient="false">
      <bind-xml name="name" node="element"/>
    </field>
    <field name="locked" type="boolean" required="false"
                         direct="false" transient="false">
      <bind-xml name="locked" node="element" get-method="getLock"/>
    </field>
    <field name="filesize" type="integer" required="false"
                           direct="false" transient="false">
      <bind-xml name="filesize" node="attribute"/>
    </field>
  </class>
  <class name="NodeTypeConst" auto-complete="false">
    <description>Default mapping for class
                         NodeTypeConst</description>
    <map-to xml="lock-info"/>
    <field name="nodeType" type="integer" required="false"
                           direct="false" transient="false">>
      <bind-xml name="type" node="attribute"/>
    </field>
  </class>
</mapping>

As you can see, there are entries for each of our four classes and each class has a field and bind-xml element for each of the member variables. Field elements can reference other classes in the mapping file so that a class definition can be a combination of other classes. For classes that have member variables that are collections, a field element must be used to specify the type of collection. For a complete explanation of all the tags in the mapping file, see the Castor documentation.

To save an object to an XML file using the mapping file, you would use the Mashaller class as before, with one minor change, as shown below.

    // Create a File to marshal to
    FileWriter writer = new FileWriter("rootNodeUsingMap.xml");

    //Create and load mapping file
    Mapping xmlMap = new Mapping();
    xmlMap.loadMapping("FileSystemMap.xml");

    //Create Marshaller
    Marshaller marshaller = new Marshaller(writer);

    //Set the mapping file
    marshaller.setMapping(xmlMap);

    //Save the object to the xml file
    marshaller.marshal(rootNode);

To unmarshall data from an XML file to a Java object using a mapping file, you would use the Unmarshaller class as before, with one minor change.

    //Create and load mapping file
    Mapping mapping = new Mapping();
    mapping.loadMapping("FileSystemMap.xml");

    // Create unmarshaller and read xml file
    Unmarshaller unmar = new Unmarshaller(mapping);
    Object obj = unmar.unmarshal(new InputSource
                 (new FileReader(fileName)));

Although there are a number of nuances associated with Castor's Marshaller and Unmarshaller class, once you use them a few times they become easy to use and will save a lot of time and coding.

Go to page: 1  2  Next  


Tools:
Add www.developer.com to your favorites
Add www.developer.com to your browser search box
IE 7 | Firefox 2.0 | Firefox 1.5.x
Receive news via our XML/RSS feed


Data & Java Archives

Work With InterSystems. Not Separate Systems. Rapidly develop and deploy connectable applications.
Is it time to make your move to the multi-threaded and parallel processing world? Find out!
Learn about expanding business opportunities for the reseller channel. Visit IT Channel Planet.
Whitepaper: Embeddable Content Platform for OEM's
Flash Demo: Learn how IBM Information Server Blade is easy to manage, highly scalable and efficient.



JupiterOnlineMedia

internet.comearthweb.comDevx.commediabistro.comGraphics.com

Search:

Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

Jupitermedia Corporate Info


Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers

Solutions
Whitepapers and eBooks
Microsoft Article: HyperV-The Killer Feature in WinServer ‘08
Avaya Article: How to Feed Data into the Avaya Event Processor
Microsoft Article: Install What You Need with Win Server ‘08
HP eBook: Putting the Green into IT
Whitepaper: HP Integrated Citrix XenServer for HP ProLiant Servers
Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 1
Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 2--The Future of Concurrency
Avaya Article: Setting Up a SIP A/S Development Environment
IBM Article: How Cool Is Your Data Center?
Microsoft Article: Managing Virtual Machines with Microsoft System Center
HP eBook: Storage Networking , Part 1
Microsoft Article: Solving Data Center Complexity with Microsoft System Center Configuration Manager 2007
MORE WHITEPAPERS, EBOOKS, AND ARTICLES
Webcasts
Intel Video: Are Multi-core Processors Here to Stay?
On-Demand Webcast: Five Virtualization Trends to Watch
HP Video: Page Cost Calculator
Intel Video: APIs for Parallel Programming
HP Webcast: Storage Is Changing Fast - Be Ready or Be Left Behind
Microsoft Silverlight Video: Creating Fading Controls with Expression Design and Expression Blend 2
MORE WEBCASTS, PODCASTS, AND VIDEOS
Downloads and eKits
Sun Download: Solaris 8 Migration Assistant
Sybase Download: SQL Anywhere Developer Edition
Red Gate Download: SQL Backup Pro and free DBA Best Practices eBook
Red Gate Download: SQL Compare Pro 6
Iron Speed Designer Application Generator
MORE DOWNLOADS, EKITS, AND FREE TRIALS
Tutorials and Demos
How-to-Article: Preparing for Hyper-Threading Technology and Dual Core Technology
eTouch PDF: Conquering the Tyranny of E-Mail and Word Processors
IBM Article: Collaborating in the High-Performance Workplace
HP Demo: StorageWorks EVA4400
Intel Featured Algorhythm: Intel Threading Building Blocks--The Pipeline Class
Microsoft How-to Article: Get Going with Silverlight and Windows Live
MORE TUTORIALS, DEMOS AND STEP-BY-STEP GUIDES