<?xml version="1.0"?>

<document url="http://castor.org/sourcegen.xml">

  <properties>
    <title>The Source Code Generator</title>
    <author email="keith AT kvisco DOT com">Keith Visco</author>
    <author email="blandin@intalio.com">Arnaud Blandin</author>
    <abstract>
       Describes how to use the Source Code Generator, and what
       is currently supported.
    </abstract>
    <status>Draft</status>
  </properties>



  <body>

    <title>Using the Source Code Generator</title>
    <header>
      <p>API Reference: <api package="org.exolab.castor.builder">The Source Builder API</api></p>
    </header>

    <section title="Introduction">


      <p>Castor's Source Code Generator creates a set of Java classes
         which represent an object model for an XML Schema
         (W3C XML Schema, 20010502 Recommendation)<sup>1</sup>, as well as the
         necessary Class Descriptors used by the <a href="xml-framework.xml">marshalling framework</a>
         to obtain information about the generated classes.
         <note>
            Currently the generated source files will need to be compiled. We
            will be adding an Ant taskdef eventually to handle this automatically.
         </note>
     </p>

        <code-panel top-caption="Example:">
java org.exolab.castor.builder.SourceGenerator -i foo-schema.xsd \
    -package com.xyz
        </code-panel>

      <p>This will generate a set of source files from the the XML Schema, foo-schema.xsd,

         and place them in the com/xyz/* package.</p>



      <p>To compile the generated classes simply run javac, or your favorite compiler:

         <code-panel>javac com/xyz/*.java</code-panel>
      </p>

      <p>Created class will have marshal and unmarshal methods which are used to go back

         and forth between XML and an Object instance.</p>

    </section>

    <section title="Castor source generator Ant task">

        <p>An alternative to using the command line as shown in the previous section,
           the Castor Source Generator Ant Task can be used to call the source
           generator for class generation. Below is an example of how to use this task
           from within an Ant target definition named 'castor:gen:src':</p>

        <code-panel>
  &lt;target name="castor:gen:src" depends="init"
             description="Generate Java source files from XSD."&gt;

    &lt;taskdef name="castor-srcgen"
                classname="org.exolab.castor.tools.ant.taskdefs.CastorSourceGenTask"
                classpathref="castor.class.path" /&gt;
    &lt;mkdir dir="generated" /&gt;
    &lt;castor-srcgen file="src/schema/sample.xsd"
                      todir="generated-source"
                      package="org.castor.example.schema"
                      types="j2"
                      warnings="false" /&gt;
  &lt;/target&gt;
        </code-panel>

        <p>The only requirement is that the castor-&lt;version&gt;-srcgen-ant-task.jar 
           must be on the CLASSPATH.</p>
        
    </section>
    
    <section title="Source Generator Options">
      <tip>For additional information about the Source Generator and
          options, You can download the
      <a href="./SourceGeneratorUser.pdf">Source Generator User Document(PDF).
        </a>
        Note: The binding-file is not dicussed in that document.
      </tip>

       <p>
          The source code generator has a number of different options which
          may be set. Some of these are done using the command line, and others
          are done using a properties file located at <pre>"org/exolab/castor/builder/castorbuilder.properties"</pre>.
       </p>
       <section title="Command Line Options">
          <table border="1" cellspacing="0">
             <tr>
               <th align="center">Option</th><th>Args</th><th>Description</th><th>Optional?</th>
             </tr>
             <tr>
               <td align="center">i</td><td><i>filename</i></td>
               <td>The input XML Schema file</td>
               <td>Required</td>
             </tr>
             <tr>
               <td align="center">package</td><td><i>package-name</i></td>
               <td>The package for the generated source</td>
               <td>Optional</td>
             </tr>
             <tr>
               <td align="center">dest</td><td><i>path</i></td>
               <td>The destination in which to put the generated source</td>
               <td>Optional</td>
             </tr>
             <tr>
               <td align="center">line-separator</td><td><i>unix | mac | win</i></td>
               <td>
                  Sets the line separator style for the desired platform. This is
                  useful if you are generating source on one platform, but will
                  be compiling/modifying on another platform.
               </td>
               <td>Optional</td>
             </tr>
             <tr>
               <td align="center">types</td><td><i>type-factory</i></td>
               <td>Sets which type factory to use. This is useful if you
                   you want JDK 1.2 collections instead of JDK 1.1 or if you want
                   to pass in your own FieldInfoFactory.
                   (see <a href="#Collection Types">Collection types</a>)
               </td>
               <td>Optional</td>
             </tr>
             <tr>
               <td align="center">h</td><td><br/></td>
               <td>Shows the help/usage screen</td>
               <td>Optional</td>
             </tr>
             <tr>
               <td align="center">f</td><td><br/></td>
               <td>
                  Forces the source generator to supress all non-fatal errors, such
                  as overwriting of pre-existing files.
               </td>
               <td>Optional</td>
             </tr>
             <tr>
               <td align="center">nodesc</td><td><br/></td>
               <td>
                  Do not generate the class descriptors
                </td>
               <td>Optional</td>
             </tr>
             <tr>
               <td align="center">nomarshall</td><td><br/></td>
               <td>
                  Do not generate the marshalling framework methods (marshall, unmarshall, validate)
                </td>
               <td>Optional</td>
             </tr>
			 <tr>
               <td align="center">testable</td><td><br/></td>
               <td>
                  Generate the specific methods used by the Castor Marshalling Framework
                </td>
               <td>Optional</td>
             </tr>
             <tr>
               <td align="center">sax1</td><td><br/></td>
               <td>
                  Generate marshalling methods that are using SAX1 framework (default is false).
                </td>
               <td>Optional</td>
             </tr>
             <tr>
               <td align="center">binding-file</td><td>The binding file name.</td>
               <td>
                  Allows the setting of a Binding File to allow a fine-grained control the classes generated
                </td>
               <td>Optional</td>
             </tr>
             <tr>
               <td align="center">generateImportedSchemas</td><td><br/></td>
               <td>
                  Generates automatically sources for imported XML Schemas (default is false).
                </td>
               <td>Optional</td>
             </tr>
          </table>

         <section title="Collection Types">
         <p>
            The source code generator has the ability to use the following
            types of collections when generating source code:
            <ul>
               <li>Java 1.1 (default): java.util.Vector</li>
               <li>Java 1.2: use the option <tt>-types j2</tt>, collection type is java.util.Collection</li>
               <li>ODMG 3.0: use the option <tt>-types odmg</tt>, collection tyoe is odmg.DArray</li>
            </ul>
            You can also write your own FieldInfoFactory to handle specific collection types. All you have to do is to
            pass in the fully qualified name of that FieldInfoFactory: <tt>-types com.personal.MyCoolFactory</tt>

         </p>
         </section>

       </section>

       <!-- Builder.propteries -->
       <section title="Advanced Options">
         <section title="Bound Properties">
            <p>Since version: 0.8.9</p>
            <p>
               Bound properties are "properties" of a class, which when updated the
               class will send out a java.beans.PropertyChangeEvent to all
               registered java.beans.PropertyChangeListeners.
            </p>
            <p>To enable bound properties uncomment the appropriate line in the
               "org/exolab/castor/builder/castorbuilder.properties" file:
               <code-panel>
# To enable bound properties uncomment the following line. Please
# note that currently *all* fields will be treated as bound properties
# when enabled. This will change in the future when we introduce
# fine grained control over each class and it's properties.
#
#org.exolab.castor.builder.boundproperties=true</code-panel>
               <p>
                  When enabled, <b>all</b> properties will be treated as bound properties.
                  For each class that is generated a <b>setPropertyChangeListener</b>
                  method is created as follows:
                 <code>
    <comment>
    /**
     * Registers a PropertyChangeListener with this class.
     * @param pcl The PropertyChangeListener to register.
    **/
    </comment>
    public void addPropertyChangeListener
        (java.beans.PropertyChangeListener pcl)
    {
        propertyChangeListeners.addElement(pcl);
    } //-- void addPropertyChangeListener
                 </code>
                 Whenever a property of the class is changed, a <b>PropertyChangeEvent</b>
                 will be sent to all registered listeners. The property name, the old
                 value, and the new value will be set in the <b>PropertyChangeEvent</b>.
                 <p>
                    <b>
                       Note: To prevent unnecessary overhead, if the property is a
                       collection, the old value will be <i>null</i>.
                    </b>
                 </p>

               </p>
            </p>
         </section>
         <section title="Class Creation/Mapping">
            <p>Since version: 0.8.9</p>
            <p>
               The source generator can treat the XML Schema structures such
               as complexType and element in two main ways. The first, and
               currently default method is called the "element" method. The
               other is called the "type" method.
            </p>
            <section title="The 'element' method">
               <p>
                  The "element" method creates classes for all elements whose
                  type is a complexType. Abstract classes are created for all
                  top-level complexTypes. Any elements whose type is a top-level
                  type will have a new class create that extends the abstract class
                  which was generated for that top-level complexType.
               </p>
               <p>
                  Classes are not created for elements whose type is a simpleType.
               </p>
            </section>
            <section title="The 'type' method">
               <p>
                  The "type" method creates classes for all top-level complexTypes, or
                  elements that contain an "anonymous" (in-lined) complexType.
               </p>
               <p>
                  Classes will not be generated for elements whose type is a top-level
                  type.
               </p>
            </section>
            <p>
               More information on this is forth coming.
            </p>
            <p>
              To change the "method" of class creation simple edit the
                <b>castorbuilder.properties</b> file:
              <code-panel>
# Java class mapping of &lt;xsd:element&gt;'s and &lt;xsd:complexType&gt;'s
#
#org.exolab.castor.builder.javaclassmapping=element</code-panel>
            </p>
         </section>

         <section title="Setting a super class">
            <p>Since version: 0.8.10</p>
            <p>
                The source generator enables the user to set a super class to <b>all</b> the
                generated classes (of course class descriptors are not concerned by this option)
            </p>
            <p> To set up the super class, edit the castorbuilder.properties file :
            <code-panel>
# This property allows one to specify the super class of *all*
# generated classes
#
#org.exolab.castor.builder.superclass=com.xyz.BaseObject</code-panel>
            </p>
        </section>


        <section title="Mapping XML namespaces to Java packages" sub-title="Schema Imports">
            <p>Since version: 0.9.0</p>
            <p>
                An XML Schema instance is identified by a namespace. For data-binding purposes,
                especially code generation it may be necessary to map namespaces to Java packages.
            </p>
            <p>
                This is needed for imported schema in order for Castor to generate the
                correct imports during code generation for the primary schema.
            </p>
            <p> To allow the mapping between namespaces and Java packages , edit the castorbuilder.properties file :
            <code-panel>
# XML namespace mapping to Java packages
#
#org.exolab.castor.builder.nspackages=\
   http://www.xyz.com/schemas/project=com.xyz.schemas.project,\
   http://www.xyz.com/schemas/person=com.xyz.schemas.person</code-panel>
            </p>
        </section>

        <section title="Generate equals() method">
            <p>Since version: 0.9.1</p>
            <p>
                The Source Generator can override the 'equals()' method for the
                generated objects.
            </p>
            <p>Note: hashcode() is not currently overriden.</p>
            <p> To generate the equals() method , edit the castorbuilder.properties file :
            <code-panel>
# Set to true if you want to generate the equals method
# for each generated class.
# false by default
#org.exolab.castor.builder.equalsmethod=true</code-panel>
            </p>
        </section>

        <section title="Maps java primitive types to wrapper object">
             <p>Since version 0.9.4</p>
             <p>
		It may be convenient to use java objects instead of primitives,
		the Source Generator provides a way to do it. Thus the following mapping can be used:
		<ul>
			<li>boolean to java.lang.Boolean</li>
			<li>byte to java.lang.Byte</li>
			<li>double to java.lang.Double</li>
			<li>float to java.lang.Float</li>
			<li>int and integer to java.lang.Integer</li>
			<li>long to java.lang.Long</li>
			<li>short to java.lang.Short</li>
		</ul>
	     </p>
 	     <p>To enable this property, edit the castor builder.properties file:
        <code-panel>
# Set to true if you want to use Object Wrappers instead
# of primitives (e.g Float instead of float).
# false by default.
#org.exolab.castor.builder.primitivetowrapper=false</code-panel>
	     </p>
	</section>

       </section>
    </section>

    <section title="Binding File">
       <p>It may appear that the default binding used to generate the Java Object Model from an XML schema doesn't
       meet one's expectation. For instance, the default binding won't deal with naming collision problems that can appear since XML Schema allows
       an element declaration and a complexType definition to both share the same name. From a Java standpoint, it will result in the creation of
       two classes with the same qualified name: the second class generated will simply overwrite the first one.
       Another example is when one user wants to change the default datatype binding provided by Castor or to add validation rules by implementing his own validator
       and passing it to the SourceGenerator.</p>

       <p>The Binding declaration is an XML based language that allows the user to define such control on the generated classes.
       The aim of this section is to provide an overview of the binding file as well as a definition of the several XML components used to define this binding file.
       A more in-depth presentation  will be available soon in the
      <a href="./SourceGeneratorUser.pdf">Source Generator User Document(PDF).</a></p>

      <section title="&lt;binding> element">
         <code-panel>
&lt;binding
    defaultBindingType = (element|type)>
    (include*,
     package*,
     namingXML?,
     elementBinding*,
     attributeBinding,
     complexTypeBinding,
     groupBinding)
&lt;/binding></code-panel>
          <p>The binding element is the root element and contains the binding information. The attribute <code>defaultBindingType</code> controls the
          <a href="#Class-Creation/Mapping">Class creation type</a></p>
          <tip>
             Be careful when using <b>defaultBindingType</b> attribute
             as it will override the binding type specified in the
             <i>castorbuilder.properties</i> file.
          </tip>
      </section>

      <section title="&lt;include> element">
         <code-panel>
&lt;include
    URI = xsd:anyURI/></code-panel>
          <ul>
             <li><b>URI:</b>The URI of the binding file to include.</li>
          </ul>
          <p>This element allows one to include the binding declaration defined in another file. This allows re-usability of Binding files defined for various
          XML Schemas.</p>
      </section>

      <section title="&lt;package> element">
         <code-panel>
&lt;package>
    name = xsd:string
    (namespace|schemaLocation) = xsd:string>
&lt;/package></code-panel>
          <ul>
             <li><b>name:</b>A fully qualified java package name.</li>
             <li><b>namespace:</b>An XML namespace that will be mapped to the package name defined by the <i>name</i> element.</li>
             <li><b>schemaLocation:</b>A URL that locates the schema to be mapped to the package name defined by the <i>name</i> element.</li>
          </ul>
          <p>The <i>targetNamespace</i> attribute of an XML Schema identifies the namespace in which the XML language is defined. Such language namespace is defined
          in the java language as package declaration. The &lt;package/> element allows you to define the mapping between an XML namespace and a Java package.
          Moreover XML Schema allows you to factorize the definition of an XML Schema identified by a unique namespace by including several XML Schemas to build
          one XML Schema using the &lt;xsd:include/> element (Please make sure you understand the difference between &lt;xsd:include/> and &lt;xsd:import/>).
          &lt;xsd:include/> relies on the URI of the included XML schema and it can be needed to keep the structure hierarchy defined in XML Schema in the Java
          package generated. Thus the binding file allows to define the mapping between a schemaLocation attribute and a Java package.</p>
      </section>

     <section title="&lt;namingXML> element">
        <code-panel>
&lt;namingXML>
   (elementName,complexTypeName,modelGroupName)
&lt;/namingXML>

&lt;elementName|complexTypeName|modelGroupName>
    (prefix?, suffix?) = xsd:string
&lt;/elementName|complexTypeName|modelGroupName></code-panel>
         <ul>
            <li><b>prefix:</b>The prefix to add to the names of the generated classes.</li>
            <li><b>suffix:</b>The suffix to append to the the names of the generated classes</li>
         </ul>
         <p>One of the aim of the binding file is to avoid naming collisions. Indeed XML Schema allows elements and complexTypes to share the same name which
         results in name collisions when generated the sources. Defining a binding for every element and complexType that share the same name is sometimes not
         a convenient solution (for instance the BPML XML Schema or the UDDI v2.0 XML Schema use the same names for top-level complexTypes and top-level elements).
         The aim of the &lt;naming/> XML element is to define a prefix and a suffix for the names of the classes generated for an element,
         a complexType or a model group definition.<br/>
         <b>Note:</b>It is not possible to control the names of the classes generated to represent nested model groups (all, choice, sequence).</p>
      </section>

       <section title="&lt;componentBinding> element">
         <code-panel>
&lt;elementBinding|attributeBinding|complexTypeBinding|groupBinding
    name = xsd:string>
   ((java-class|interface|member),
     elementBinding*,
     attributeBinding*,
     complexTypeBinding*,
     groupBinding*)
&lt;/elementBinding|attributeBinding|complexTypeBinding|groupBinding></code-panel>
         <ul>
            <li><b>name:</b>The name of the XML schema component for which we are defining a binding.</li>
         </ul>
         <p>These elements are the tenets of the binding file since they contain the binding definition for an XML Schema element, attribute, complexType
         and modelGroup definition. The first child element (&lt;java-class/>, &lt;interface> or &lt;member>) will determine the type of binding one is defining.
         Please note that defining a &lt;java-class> binding on an XML Schema attribute will have absolutely no <b>effect</b>.</p>
         <p>The binding file being written from an XML Schema point of view; there are two distinct ways to define the XML Schema component for which we are
         defining a binding. First we can define it throught the <tt>name</tt> attribute.</p>
         <p>The value of the name attribute uniquely identifies the XML Schema Component. It can refer to the top-level component using the NCName of that component or
         it can use a location language based on <a href="http://www.w3.org/TR/xpath">XPath</a><sup>3</sup>.
         The grammar of that language can be defined by the following BNF:</p>
         <pre>
            [1]Path         ::= LocationPath('/'LocationPath)*
            [2]LocationPath ::= (Complex|ModelGroup|Attribute|Element)
            [3]Complex      ::= 'complexType:'<a href="http://www.w3.org/TR/2001/REC-xmlschema-2-20010502/datatypes.html#NCName">NCName</a>
            [4]ModelGroup   ::= 'group:'<a href="http://www.w3.org/TR/2001/REC-xmlschema-2-20010502/datatypes.html#NCName">NCName</a>
            [5]Attribute    ::= '@'<a href="http://www.w3.org/TR/2001/REC-xmlschema-2-20010502/datatypes.html#NCName">NCName</a>
            [6]Element      ::= <a href="http://www.w3.org/TR/2001/REC-xmlschema-2-20010502/datatypes.html#NCName">NCName</a>
         </pre>
         <p>The second option to identify a XML Schema Component is to embed its binding definition inside its parent binding definition.</p>
         <p>For instance, the following
         binding definition will be equivalent and will identify the element 'foo' defined in the top-level complexType 'fooType'.</p>

         <code-panel>
&lt;elementBinding name="complexType:fooType/foo>
   &lt;member name="MyFoo" handler="mypackage.myHandler"/>
&lt;/elementBinding>

&lt;complexTypeBinding name="fooType">
   &lt;elementBinding name="foo>
      &lt;member name="MyFoo" handler="mypackage.myHandler"/>
   &lt;/elementBinding>
&lt;complexTypeBinding></code-panel>
       </section>

       <section title="&lt;java-class> element">
         <code-panel>
&lt;java-class
    name? = xsd:string
    package? = xsd:string
    final? = xsd:boolean
    abstract? = xsd:boolean
    equals? = xsd:boolean
    bound? = xsd:boolean >
    (implements*,extends?)
&lt;/java-class></code-panel>
         <ul>
            <li><b>name:</b>The name of the class that will be generated.</li>
            <li><b>package:</b>The package of the class to be generated. if set, this option overrides the mapping defined in the &lt;package/> element.</li>
            <li><b>final:</b>If true, the generated class will be final.</li>
            <li><b>abstract:</b>If true, the generated class will be abstract.</li>
            <li><b>equals:</b>If true, the generated class will implement the equals method.</li>
            <li><b>bound:</b>If true, the generated class will implement the bound properties.</li>
         </ul>
         <p>This element defines all the options for the class to be generated.</p>
       </section>


       <section title="&lt;interface> element">
         <code-panel>
&lt;interface>
    name = xsd:string
&lt;/interface></code-panel>
         <ul>
            <li><b>name:</b>The name of the interface that will be generated.</li>
         </ul>
         <p>This element specifies the name of the interface to be generated for an XML schema component.</p>

         <p><b>NOTE: this element is not yet implemented.</b></p>
       </section>

       <section title="&lt;member> element">
         <code-panel>
 &lt;member
  name? = xsd:string
  java-type? = xsd:string
  wrapper? = xsd:boolean
  handler? = xsd:string
  collection? = (array|vector|arraylist|hashtable|collection|odmg|set|map)
  validator? = xsd:string/></code-panel>
         <ul>
            <li><b>name:</b>The name of the class member that will be generated.</li>
            <li><b>java-type:</b>the fully qualified name of the java type.</li>
            <li><b>wrapper:</b>If true, a wrapper object will be generated in case the java type is a java primitive.</li>
            <li><b>handler:</b>The fully qualified name of the FieldHandler to use.</li>
            <li><b>collection:</b>If the schema component can occur more than once then this attribute allows to specify the collection to use
            to represent the component in Java.</li>
            <li><b>validator:</b>The fully qualified name of the FieldValidator to use.</li>
         </ul>
            <p>This element represents the binding for class member. It allows the definition
            of its name and java type as well as an implementation of FieldHandler
            to help the Marshalling framework in handling that member. Defining a validator is also
            possible. The names given for the validator and the fieldHandler must be fully qualified.</p>
       </section>

       <section title="todo">
          <ul>
            <li>
                  <code-panel>
 &lt;enumBinding>
    (enumClassName|enumMemberName)
 &lt;/enumBinding></code-panel>
             <p>This element will allow more control on the type safe enumerations generated to represent an XML Schema simpleType enumeration</p>
          </li>
          <li>
            <table>
               <tr>
                  <code>&lt;javadoc/></code>
               </tr>
            </table>
            <p>the javadoc element will allow one to enter the necessary javadoc that represents the generated classes or members.</p>
          </li>
       </ul>


       </section>

    </section>

    <section title="XML Schema">

       <p>
          The input file to the source code generator is an XML Schema<sup>2</sup>.
          The current supported version is the <b>W3C XML Schema Recommendation</b><sup>1</sup>.
          For more information about XML Schema Support, check the <a href="xmlschema.xml">XML Schema page</a>
       </p>


    </section>

   <section>
      <body-note><sup>1</sup>Castor 0.9.4.1 uses <a href="http://www.w3.org/TR/XMLschema-1"> XML Schema Recommendation 20010502</a></body-note>
      <body-note>
         <sup>2</sup>XML Schema is a <a href="http://www.w3.org">W3C</a> Recommendation
      </body-note>
      <body-note>
         <sup>3</sup>XPath is a <a href="http://www.w3.org">W3C</a> Recommendation
      </body-note>

   </section>

  </body>

</document>

