Customizing JAXB Bindings

The remainder of this chapter describes several examples that build on the concepts demonstrated in the basic examples.

The goal of this section is to illustrate how to customize JAXB bindings by means of custom binding declarations made in either of two ways:

As annotations made inline in an XML schema

As statements in an external file passed to the JAXB binding compiler

Unlike the examples in Basic Examples, which focus on the Java code in the respective Main.java class files, the examples here focus on customizations made to the XML schema before generating the schema-derived Java binding classes.

Note: Although JAXB binding customizations must currently be made by hand, it is envisioned that a tool/wizard may eventually be written by Sun or a third party to make this process more automatic and easier in general. One of the goals of the JAXB technology is to standardize the format of binding declarations, thereby making it possible to create customization tools and to provide a standard interchange format between JAXB implementations.

This section just begins to scratch the surface of customizations you can make to JAXB bindings and validation methods. For more information, please refer to the JAXB Specification (http://java.sun.com/xml/downloads/jaxb.html).

Why Customize?

In most cases, the default bindings generated by the JAXB binding compiler will be sufficient to meet your needs. There are cases, however, in which you may want to modify the default bindings. Some of these include:

To resolve name collisions (as described in Appendix C.2.1 of the JAXB Specification). Note that the JAXB binding compiler detects and reports all name conflicts.

To provide names for typesafe enumeration constants that are not legal Java identifiers; for example, enumeration over integer values.

To provide better names for the Java representation of unnamed model groups when they are bound to a Java property or class.

To provide more meaningful package names than can be derived by default from the target namespace URI.

Overriding default bindings; for example:

Specify that a model group should be bound to a class rather than a list.

Specify that a fixed attribute can be bound to a Java constant.

Override the specified default binding of XML Schema built-in datatypes to Java datatypes. In some cases, you might want to introduce an alternative Java class that can represent additional characteristics of the built-in XML Schema datatype.

Inline and External Customizations

Customizations to the default JAXB bindings are made in the form of binding declarations passed to the JAXB binding compiler. These binding declarations can be made in either of two ways:

As inline annotations in a source XML schema

As declarations in an external binding customizations file

For some people, using inline customizations is easier because you can see your customizations in the context of the schema to which they apply. Conversely, using an external binding customization file enables you to customize JAXB bindings without having to modify the source schema, and enables you to easily apply customizations to several schema files at once.

Note: You can combine the two types of customizations--for example, you could include a reference to an external binding customizations file in an inline annotation--but you cannot declare both an inline and external customization on the same schema element.

Each of these types of customization is described in more detail below.

Inline Customizations

Customizations to JAXB bindings made by means of inline binding declarations in an XML schema file take the form of <xsd:appinfo> elements embedded in schema <xsd:annotation> elements (xsd: is the XML schema namespace prefix, as defined in W3C XML Schema Part 1: Structures). The general form for inline customizations is shown below.

Customizations are applied at the location at which they are declared in the schema. For example, a declaration at the level of a particular element would apply to that element only. Note that the XMLSchema namespace prefix must be used with the <annotation> and <appinfo> declaration tags. In the example above, xs: is used as the namespace prefix, so the declarations are tagged <xs:annotation> and <xs:appinfo>.

External Binding Customization Files

Customizations to JAXB bindings made by means of an external file containing binding declarations take the general form shown below.

The remote schema to which the binding declaration applies must be identified explicitly in XPath notation by means of a jxb:bindings declaration specifying schemaLocation and node attributes:

schemaLocation - URI reference to the remote schema

node - XPath 1.0 expression that identifies the schema node within schemaLocation to which the given binding declaration is associated; in the case of the initial jxb:bindings declaration in the binding customization file, this node is typically "/xs:schema"

collectionType can be either indexed or any fully qualified class name that implements java.util.List.

fixedAttributeAsConstantProperty can be either true, false, 1, or 0. The default value is false.

generateIsSetMethod can be either true, false, 1, or 0. The default value is false.

enableFailFastCheck can be either true, false, 1, or 0. If enableFailFastCheck is true or 1 and the JAXB implementation supports this optional checking, type constraint checking is performed when setting a property. The default value is false. Please note that the JAXB implementation does not support failfast validation.

choiceContentProperty can be either true, false, 1, or 0. The default value is false. choiceContentProperty is not relevant when the bindingStyle is elementBinding. Therefore, if bindingStyle is specified as elementBinding, then the choiceContentProperty must result in an invalid customization.

underscoreBinding can be either asWordSeparator or asCharInWord. The default value is asWordSeparator.

enableJavaNamingConventions can be either true, false, 1, or 0. The default value is true.

typesafeEnumBase can be a list of QNames, each of which must resolve to a simple type definition. The default value is xs:NCName. See Typesafe Enumeration Binding Declarations for information about localized mapping of simpleType definitions to Java typesafe enum classes.

typesafeEnumMemberName can be either generateError or generateName. The default value is generateError.

bindingStyle can be either elementBinding, or modelGroupBinding. The default value is elementBinding.

<globalBindings> declarations are only valid in the annotation element of the top-level schema element. There can only be a single instance of a <globalBindings> declaration in any given schema or binding declarations file. If one source schema includes or imports a second source schema, the <globalBindings> declaration must be declared in the first source schema.

name is the name of the derived Java interface. It must be a legal Java interface name and must not contain a package prefix. The package prefix is inherited from the current value of package.

implClass is the name of the implementation class for className and must include the complete package name.

The <javadoc> element specifies the Javadoc tool annotations for the schema-derived Java interface. The string entered here must use CDATA or < to escape embedded HTML tags.

Property Binding Declarations

The <property> binding declaration enables you to customize the binding of an XML schema element to its Java representation as a property. The scope of customization can either be at the definition level or component level depending upon where the <property> binding declaration is specified.

name defines the customization value propertyName; it must be a legal Java identifier.

collectionType defines the customization value propertyCollectionType, which is the collection type for the property. propertyCollectionType if specified, can be either indexed or any fully-qualified class name that implements java.util.List.

fixedAttributeAsConstantProperty defines the customization value fixedAttributeAsConstantProperty. The value can be either true, false, 1, or 0.

generateIsSetMethod defines the customization value of generateIsSetMethod. The value can be either true, false, 1, or 0.

enableFailFastCheck defines the customization value enableFailFastCheck. The value can be either true, false, 1, or 0. Please note that the JAXB implementation does not support failfast validation.

<javaType> Binding Declarations

The <javaType> declaration provides a way to customize the translation of XML datatypes to and from Java datatypes. XML provides more datatypes than Java, and so the <javaType> declaration lets you specify custom datatype bindings when the default JAXB binding cannot sufficiently represent your schema.

The target Java datatype can be a Java built-in datatype or an application-specific Java datatype. If an application-specific datatype is used as the target, your implementation must also provide parse and print methods for unmarshalling and marshalling data. To this end, the JAXB specification supports a parseMethod and printMethod:

The parseMethod is called during unmarshalling to convert a string from the input document into a value of the target Java datatype.

The printMethod is called during marshalling to convert a value of the target type into a lexical representation.

If you prefer to define your own datatype conversions, JAXB defines a static class, DatatypeConverter, to assist in the parsing and printing of valid lexical representations of the XML Schema built-in datatypes.

xmlType is the name of the XML Schema datatype to which javaType is to bound; this attribute is required when the parent of the <javaType> declaration is <globalBindings>.

parseMethod is the name of the parse method to be called during unmarshalling.

printMethod is the name of the print method to be called during marshalling.

hasNsContext allows a namespace context to be specified as a second parameter to a print or a parse method; can be either true, false, 1, or 0. By default, this attribute is false, and in most cases you will not need to change it.

<typesafeEnumMember> lets you map just selected members of a simpleType class to typesafe enum classes.

In both cases, there are two primary limitations on this type of customization:

Only simpleType definitions with enumeration facets can be customized using this binding declaration.

This customization only applies to a single simpleType definition at a time. To map sets of similar simpleType definitions on a global level, use the typesafeEnumBase attribute in a <globalBindings> declaration, as described Global Binding Declarations.

<javadoc> customizes the Javadoc tool annotations for the enumeration constant.

For inline annotations, the <typesafeEnumClass> declaration must be specified in the annotation element of the <simpleType> element. The <typesafeEnumMember> must be specified in the annotation element of the enumeration member. This allows the enumeration member to be customized independently from the enumeration class.

For information about typesafe enum design patterns, see the sample chapter of Joshua Bloch's Effective Java Programming on the Java Developer Connection.

<javadoc> Binding Declarations

The <javadoc> declaration lets you add custom Javadoc tool annotations to schema-derived JAXB packages, classes, interfaces, methods, and fields. Note that <javadoc> declarations cannot be applied globally--that is, they are only valid as a sub-elements of other binding customizations.

The syntax for the <javadoc> customization is:

<javadoc>
Contents in &lt;b>Javadoc&lt;\b> format.
</javadoc>

or

<javadoc>
<<![CDATA[
Contents in <b>Javadoc<\b> format
]]>
</javadoc>

Note that documentation strings in <javadoc> declarations applied at the package level must contain <body> open and close tags; for example:

Customization Namespace Prefix

All standard JAXB binding declarations must be preceded by a namespace prefix that maps to the JAXB namespace URI (http://java.sun.com/xml/ns/jaxb). For example, in this sample, jxb: is used. To this end, any schema you want to customize with standard JAXB binding declarations must include the JAXB namespace declaration and JAXB version number at the top of the schema file. For example, in po.xsd for the Customize Inline example, the namespace declaration is as follows:

Note that in this example, the globalBindings and schemaBindings declarations are used to specify, respectively, global scope and schema scope customizations. These customization scopes are described in more detail in Scope, Inheritance, and Precedence.

Customize Inline Example

The Customize Inline example illustrates some basic customizations made by means of inline annotations to an XML schema named po.xsd. In addition, this example implements a custom datatype converter class, MyDatatypeConverter.java, which illustrates print and parse methods in the <javaType> customization for handling custom datatype conversions.

To summarize this example:

po.xsd is an XML schema containing inline binding customizations.

MyDatatypeConverter.java is a Java class file that implements print and parse methods specified by <javaType> customizations in po.xsd.

Main.java is the primary class file in the Customize Inline example, which uses the schema-derived classes generated by the JAXB compiler.

Key customizations in this sample, and the custom MyDatatypeConverter.java class, are described in more detail below.

Customized Schema

The customized schema used in the Customize Inline example is in the file <JAVA_HOME>/jaxb/samples/inline-customize/po.xsd. The customizations are in the <xsd:annotation> tags.

In this example, all values are set to the defaults except for collectionType.

Setting collectionType to java.util.Vector specifies that all lists in the generated implementation classes should be represented internally as vectors. Note that the class name you specify for collectionType must implement java.util.List and be callable by newInstance.

Setting fixedAttributeAsConstantProperty to true indicates that all fixed attributes should be bound to Java constants. By default, fixed attributes are just mapped to either simple or collection property, which ever is more appropriate.

Please note that the JAXB implementation does not support the enableFailFastCheck attribute.

If typesafeEnumBase to xsd:string it would be a global way to specify that all simple type definitions deriving directly or indirectly from xsd:string and having enumeration facets should be bound by default to a typesafe enum. If typesafeEnumBase is set to an empty string, "", no simple type definitions would ever be bound to a typesafe enum class by default. The value of typesafeEnumBase can be any atomic simple type definition except xsd:boolean and both binary types.

Note: Using typesafe enums enables you to map schema enumeration values to Java constants, which in turn makes it possible to do compares on Java constants rather than string values.

<jxb:package name="primer.myPo"/> specifies the primer.myPo as the package in which the schema-derived classes should be generated.

<jxb:nameXmlTransform> specifies that all generated Java element interfaces should have Element appended to the generated names by default. For example, when the JAXB compiler is run against this schema, the element interfaces CommentElement and PurchaseOrderElement will be generated. By contrast, without this customization, the default binding would instead generate Comment and PurchaseOrder.

This customization is useful if a schema uses the same name in different symbol spaces; for example, in global element and type definitions. In such cases, this customization enables you to resolve the collision with one declaration rather than having to individually resolve each collision with a separate binding declaration.

<jxb:javadoc> specifies customized Javadoc tool annotations for the primer.myPo package. Note that, unlike the <javadoc> declarations at the class level, below, the opening and closing <body> tags must be included when the <javadoc> declaration is made at the package level.

The Javadoc tool annotations for the schema-derived POType class will contain the description "A &lt;b>Purchase Order&lt;/b> consists of addresses and items." The &lt; is used to escape the opening bracket on the <b> HTML tags.

Note: When a <class> customization is specified in the appinfo element of a complexType definition, as it is here, the complexType definition is bound to a Java content interface.

Later in po.xsd, another <javadoc> customization is declared at this class level, but this time the HTML string is escaped with CDATA:

<xsd:annotation>
<xsd:appinfo>
<jxb:class>
<jxb:javadoc>
<![CDATA[ First line of documentation for a
<b>USAddress</b>.]]>
</jxb:javadoc>
</jxb:class>
</xsd:appinfo>
</xsd:annotation>

Property Binding Declarations

Of particular interest here is the generateIsSetMethod customization, which causes two additional property methods, isSetQuantity and unsetQuantity, to be generated. These methods enable a client application to distinguish between schema default values and values occurring explicitly within an instance document.

The @generateIsSetMethod applies to the quantity element, which is bound to a property within the Items.ItemType interface. unsetQuantity and isSetQuantity methods are generated in the Items.ItemType interface.

MyDatatypeConverter Class

The <JWSDP_HOME>/jaxb/samples/inline-customize/MyDatatypeConverter class, shown below, provides a way to customize the translation of XML datatypes to and from Java datatypes by means of a <javaType> customization.

In this example, the jxb:javaType binding declaration overrides the default JAXB binding of this type to java.math.BigInteger. For the purposes of the Customize Inline example, the restrictions on ZipCodeType--specifically that legal US ZIP codes are limited to five digits--make it so all valid values can easily fit within the Java primitive datatype int. Note also that, because <jxb:javaType name="int"/> is declared within ZipCodeType, the customization applies to all JAXB properties that reference this simpleType definition, including the getZip and setZip methods.

Datatype Converter Example

The Datatype Converter example is very similar to the Customize Inline example. As with the Customize Inline example, the customizations in the Datatype Converter example are made by using inline binding declarations in the XML schema for the application, po.xsd.

The global, schema, and package, and most of the class customizations for the Customize Inline and Datatype Converter examples are identical. Where the Datatype Converter example differs from the Customize Inline example is in the parseMethod and printMethod used for converting XML data to the Java int datatype.

Specifically, rather than using methods in the custom MyDataTypeConverter class to perform these datatype conversions, the Datatype Converter example uses the built-in methods provided by javax.xml.bind.DatatypeConverter:

External Customize Example

The External Customize example is identical to the Datatype Converter example, except that the binding declarations in the External Customize example are made by means of an external binding declarations file rather than inline in the source XML schema.

The binding customization file used in the External Customize example is <JWSDP_HOME>/jaxb/samples/external-customize/binding.xjb.

This section compares the customization declarations in bindings.xjb with the analogous declarations used in the XML schema, po.xsd, in the Datatype Converter example. The two sets of declarations achieve precisely the same results.

JAXB Version Number

An XML file with a root element of <jaxb:bindings> is considered an external binding file. The root element must specify the JAXB version attribute with which its binding declarations must comply; specifically the root <jxb:bindings> element must contain either a <jxb:version> declaration or a version attribute. By contrast, when making binding declarations inline, the JAXB version number is made as attribute of the <xsd:schema> declaration:

Namespace Declarations

As shown in JAXB Version, Namespace, and Schema Attributes, the namespace declarations in the external binding declarations file include both the JAXB namespace and the XMLSchema namespace. Note that the prefixes used in this example could in fact be anything you want; the important thing is to consistently use whatever prefixes you define here in subsequent declarations in the file.

Schema Name and Schema Node

The fourth line of the code in JAXB Version, Namespace, and Schema Attributes specifies the name of the schema to which this binding declarations file will apply, and the schema node at which the customizations will first take effect. Subsequent binding declarations in this file will reference specific nodes within the schema, but this first declaration should encompass the schema as a whole; for example, in bindings.xjb:

<jxb:bindings schemaLocation="po.xsd" node="/xs:schema">

Global and Schema Binding Declarations

The global schema binding declarations in bindings.xjb are the same as those in po.xsd for the Datatype Converter example. The only difference is that because the declarations in po.xsd are made inline, you need to embed them in <xs:appinfo> elements, which are in turn embedded in <xs:annotation> elements. Embedding declarations in this way is unnecessary in the external bindings file.

Note in this example that USAddress is the parent of the child elements name and zip, and therefore a </jxb:bindings> tag encloses the bindings declarations for the child elements as well as the class-level javadoc declaration.

Fix Collides Example

The Fix Collides example illustrates how to resolve name conflicts--that is, places in which a declaration in a source schema uses the same name as another declaration in that schema (namespace collisions), or places in which a declaration uses a name that does translate by default to a legal Java name.

Note: Many name collisions can occur because XSD Part 1 introduces six unique symbol spaces based on type, while Java only has only one. There is a symbols space for type definitions, elements, attributes, and group definitions. As a result, a valid XML schema can use the exact same name for both a type definition and a global element declaration.

For the purposes of this example, it is recommended that you run the ant fail command in the <JWSDP_HOME>/jaxb/samples/fix-collides directory to display the error output generated by the xjc compiler. The XML schema for the Fix Collides, example.xsd, contains deliberate name conflicts.

The example.xsd Schema

The XML schema, <JWSDP_HOME>/jaxb/samples/fix-collides/example.xsd, used in the Fix Collides example illustrates common name conflicts encountered when attempting to bind XML names to unique Java identifiers in a Java package. The schema declarations that result in name conflicts are highlighted in bold below.

[xjc] [ERROR] A property with the same name "Zip" is
generated from more than one schema component.
[xjc] line 22 of example.xsd
[xjc] [ERROR] (Relevant to above error) another one is
generated from this schema component.
[xjc] line 20 of example.xsd

The third conflict is that there are an element and an attribute both named zip:

[xjc] [ERROR] A property with the same name "Zip" is
generated from more than one schema component.
[xjc] line 22 of example.xsd
[xjc] [ERROR] (Relevant to above error) another one is
generated from this schema component.
[xjc] line 20 of example.xsd

Output From ant fail

Here is the complete output returned by running ant fail in the <JWSDP_HOME>/jaxb/samples/fix-collides directory:

[echo] Compiling the schema w/o external binding file
(name collision errors expected)...
[xjc] Compiling file:/C:/Sun/jwsdp-1.5/jaxb/samples/
fix-collides/example.xsd
[xjc] [ERROR] Attempt to create a property having the same
name as the reserved word "Class".
[xjc] line 14 of example.xsd
[xjc] [ERROR] A property with the same name "Zip" is
generated from more than one schema component.
[xjc] line 17 of example.xsd
[xjc] [ERROR] (Relevant to above error) another one is
generated from this schema component.
[xjc] line 15 of example.xsd
[xjc] [ERROR] A class/interface with the same name
"generated.FooBar" is already in use.
[xjc] line 9 of example.xsd
[xjc] [ERROR] (Relevant to above error) another one is
generated from here.
[xjc] line 18 of example.xsd

The binding.xjb Declarations File

The <JWSDP_HOME>/jaxb/samples/fix-collides/binding.xjb binding declarations file resolves the conflicts in examples.xsd by means of several customizations.

Resolving the Conflicts in example.xsd

The first conflict in example.xsd, using the Java reserved name Class for an element name, is resolved in binding.xjb with the <class> and <property> declarations on the schema element node Class:

The second conflict in example.xsd, the namespace collision between the element FooBar and the complexType FooBar, is resolved in binding.xjb by using a <nameXmlTransform> declaration at the <schemaBindings> level to append the suffix Element to all element definitions.

This customization handles the case where there are many name conflicts due to systemic collisions between two symbol spaces, usually named type definitions and global element declarations. By appending a suffix or prefix to every Java identifier representing a specific XML symbol space, this single customization resolves all name collisions:

Running ant in the <JWSDP_HOME>/jaxb/samples/fix-collides directory will pass the customizations in binding.xjb to the xjc binding compiler, which will then resolve the conflicts in example.xsd in the schema-derived Java classes.

Bind Choice Example

The Bind Choice example shows how to bind a choice model group to a Java interface. Like the External Customize and Fix Collides examples, the Bind Choice example uses an external binding declarations file, binding.xjb, to define the JAXB binding customization.

The schema declarations in <JWSDP_HOME>/jaxb/samples/bind-choice/example.xsd that will be globally changed are highlighted in bold below.

Customizing a choice Model Group

The <JWSDP_HOME>/jaxb/samples/bind-choice/binding.xjb binding declarations file demonstrates one way to override the default derived names for choice model groups in example.xsd by means of a <jxb:globalBindings> declaration:

Calling getContent returns the current value of the Choice content. The setters of this choice are just like radio buttons; setting one unsets the previously set one. This class represents the data representing the choice.