October 1, 2014
Hot Topics:
RSS RSS feed Download our iPhone app

Castor Cures Your Data Binding Ills

  • February 27, 2003
  • By Thomas Hammell
  • Send Email »
  • More Articles »

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.





Page 1 of 2



Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Sitemap | Contact Us

Rocket Fuel