July 27, 2004

Using Castor with Ant

If you ever had a need to generate Java beans from the XSD by Castor, you probably have used Castor's SourceGenerator class (org.exolab.castor.builder.SourceGenerator). Unfortunately, this main style class can not be easily integrated into the Ant driven build process (and, from my experience, 90% of projects out there use Ant). For example, SourceGenerator can process only one XSD schema at a time, and can't generate Java beans from multiple files.

This problem can be solved by using custom Ant task, which provides convinient way of running Castor's SourceGenerator on single file, directory, or a fileset:

<castor file="schema.xsd" todir="build/src"
        warnings="false" types="j2"/>

<castor dir="schemas" todir="build/src"
        warnings="false" types="j2"/>

<castor todir="build/src"
        warnings="false" types="j2">
  <fileset dir="schemas">
    <include name="*.xsd"/>

Don't forget to declare the task with:

<path id="class.path">
  <pathelement location="ant-optional-castor-20040412.jar"/>
  <pathelement location="castor-"/>
  <pathelement path="${java.class.path}"/>
<taskdef name="castor"

Source for the Castor Ant task can be found as attachement to the Bug# 885 in Castor's Bugzilla. Task accepts following parameters (they mostly correspond to SourceGenerator's arguments):

  • file: Input file name
  • dir: Directory name with input files
  • fileset: Fileset with input files
  • package: Destination Java package name
  • todir: Destination directory
  • lineseparator
  • types: setting to j2 makes Castor use Java2 collections
  • verbose
  • warnings
  • nodesc
  • nomarshall
  • testable
Posted by Vadim at July 27, 2004 9:05 PM