Movatterモバイル変換


[0]ホーム

URL:


Document Information

Preface

Part I Introduction

1.  Overview

2.  Using the Tutorial Examples

Part II The Web Tier

3.  Getting Started with Web Applications

4.  Java Servlet Technology

5.  JavaServer Pages Technology

6.  JavaServer Pages Documents

7.  JavaServer Pages Standard Tag Library

8.  Custom Tags in JSP Pages

9.  Scripting in JSP Pages

10.  JavaServer Faces Technology

11.  Using JavaServer Faces Technology in JSP Pages

12.  Developing with JavaServer Faces Technology

13.  Creating Custom UI Components

14.  Configuring JavaServer Faces Applications

15.  Internationalizing and Localizing Web Applications

Part III Web Services

16.  Building Web Services with JAX-WS

17.  Binding between XML Schema and Java Classes

JAXB Architecture

Architectural Overview

The JAXB Binding Process

More about Unmarshalling

More about Marshalling

More about Validation

Representing XML Content

Java Representation of XML Schema

Binding XML Schemas

Simple Type Definitions

Default Data Type Bindings

Schema-to-Java Mapping

JAXBElement Object

Java-to-Schema Mapping

Customizing Generated Classes and Java Program Elements

Schema-to-Java

Java-to-Schema

JAXB Examples

JAXB Compiler Options

JAXB Schema Generator Option

About the Schema-to-Java Bindings

Schema-Derived JAXB Classes

Comment Class

Items Class

ObjectFactory Class

PurchaseOrder Class

PurchaseOrderType Class

USAddress Class

Basic JAXB Examples

Modify Marshal Example

Building and Running the Modify Marshal Example Using NetBeans IDE

Building and Running the Modify Marshal Example Using Ant

Unmarshal Validate Example

Building and Running the Unmarshal Validate Example Using NetBeans IDE

Building and Running the Unmarshal Validate Example Using Ant

Customizing JAXB Bindings

Why Customize?

Customization Overview

Inline and External Customizations

Scope, Inheritance, and Precedence

Customization Syntax

Customization Namespace Prefix

Customize Inline Example

Building and Running the Customize Inline Example Using NetBeans IDE

Building and Running the Customize Inline Example Using Ant

Customized Schema

Global Binding Declarations

Schema Binding Declarations

Class Binding Declarations

Property Binding Declarations

MyDatatypeConverter Class

Datatype Converter Example

Building and Running the Datatype Converter Example Using NetBeans IDE

Building and Running the Datatype Converter Example Using Ant

Binding Declaration Files

JAXB Version, Namespace, and Schema Attributes

Global and Schema Binding Declarations

Class Declarations

External Customize Example

Building and Running the External Customize Example Using NetBeans IDE

Building and Running the External Customize Example Using Ant

Java-to-Schema Examples

Create Marshal Example

Building and Running the Create Marshal Example Using NetBeans IDE

Building and Running the Create Marshal Example Using Ant

XmlAccessorOrder Example

Using the@XmlAccessorOrder Annotation to Define Schema Element Ordering

Using the@XmlType Annotation to Define Schema Element Ordering

Schema Content Ordering in the Example

Building and Running the XmlAccessorOrder Example Using NetBeans IDE

Building and Running the XmlAccessorOrder Example Using Ant

XmlAdapter Field Example

Building and Running the XmlAdapter Field Example Using NetBeans IDE

Building and Running the XmlAdapter Field Example Using Ant

XmlAttribute Field Example

Building and Running the XmlAttribute Field Example Using NetBeans IDE

Building and Running the XmlAttribute Field Example Using Ant

XmlRootElement Example

Building and Running the XmlRootElement Example Using NetBeans IDE

Building and Running the XmlRootElement Example Using Ant

XmlSchemaType Class Example

Building and Running the XmlSchemaType Class Example Using NetBeans IDE

Building and Running the XmlSchemaType Class Example Using Ant

XmlType Example

Building and Running the XmlType Example Using NetBeans IDE

Building and Running the XmlType Example Using Ant

Further Information about JAXB

18.  Streaming API for XML

19.  SOAP with Attachments API for Java

Part IV Enterprise Beans

20.  Enterprise Beans

21.  Getting Started with Enterprise Beans

22.  Session Bean Examples

23.  A Message-Driven Bean Example

Part V Persistence

24.  Introduction to the Java Persistence API

25.  Persistence in the Web Tier

26.  Persistence in the EJB Tier

27.  The Java Persistence Query Language

Part VI Services

28.  Introduction to Security in the Java EE Platform

29.  Securing Java EE Applications

30.  Securing Web Applications

31.  The Java Message Service API

32.  Java EE Examples Using the JMS API

33.  Transactions

34.  Resource Connections

35.  Connector Architecture

Part VII Case Studies

36.  The Coffee Break Application

37.  The Duke's Bank Application

Part VIII Appendixes

A.  Java Encoding Schemes

B.  About the Authors

Index

 

The Java EE 5 Tutorial

Java Coffee Cup logo
PreviousContentsNext

Customizing JAXB Bindings

The next part of this chapter describes several examples that build on theconcepts demonstrated in the Basic examples.

The goal of this section is to illustrate how to customize JAXBbindings 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 inBasic JAXB Examples, which focus on the Java code in therespectiveMain.java class files, the examples here focus on customizations made to theXML schemabefore generating the schema-derived Java binding classes.


Note -Although JAXB binding customizations must currently be made by hand, it is envisionedthat a tool/wizard might eventually be written by Sun or a third partyto make this process more automatic. One of the goals of the JAXBtechnology is to standardize the format of binding declarations, thereby making it possibleto create customization tools and to provide a standard interchange format between JAXBimplementations.


This section just begins to scratch the surface of customizations you can maketo JAXB bindings and validation methods. For more information, refer to theJAXB Specification.

Why Customize?

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

  • Creating API documentation for the schema-derived JAXB packages, classes, methods and constants; by adding custom Javadoc tool annotations to your schemas, you can explain concepts, guidelines, and rules specific to your implementation.

  • Providing semantically meaningful customized names for cases that the default XML name-to-Java identifier mapping cannot handle automatically; for example:

    • To resolve name collisions (as described in Appendix D.2.1 of theJAXB 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 data types to Java data types. In some cases, you might want to introduce an alternative Java class that can represent additional characteristics of the built-in XML Schema data type.

Customization Overview

This section explains some core JAXB customization concepts:

  • Inline and external customizations

  • Scope, inheritance, and precedence

  • Customization syntax

  • Customization namespace prefix

Inline and External Customizations

Customizations to the default JAXB bindings are made in the form ofbinding declarations passed to the JAXB binding compiler. These binding declarations can be madein 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 yourcustomizations in the context of the schema to which they apply. Conversely, usingan external binding customization file enables you to customize JAXB bindings without havingto modify the source schema, and enables you to easily apply customizations toseveral schema files at once.


Note -You can combine the two types of customizations. For example, you could includea reference to an external binding customizations file in an inline annotation. However,you cannot declare both an inline and external customization on the same schemaelement.


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

Inline Customizations

Customizations to JAXB bindings made by means of inlinebinding declarations in anXML 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 W3CXML Schema Part 1: Structures).The general form for inline customizations is shown below.

<xs:annotation>   <xs:appinfo>      .      .binding declarations      .      .   </xs:appinfo></xs:annotation>

Customizations are applied at the location at which they are declared in theschema. For example, a declaration at the level of a particular element wouldapply to that element only. Note that the XMLSchema namespace prefix must beused 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 bindingdeclarations take the general form shown below.

<jxb:bindings schemaLocation = "xs:anyURI">   <jxb:bindings node = "xs:string">*      <binding declaration>   <jxb:bindings></jxb:bindings>
  • schemaLocation is a URI reference to the remote schema.

  • node is an XPath 1.0 expression that identifies the schema node withinschemaLocation to which the given binding declaration is associated.

For example, the firstschemaLocation/node declaration in a JAXB binding declarations file specifiesthe schema name and the root schema node:

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

A subsequentschemaLocation/node declaration, say for asimpleType element namedZipCodeType in the aboveschema, would take the form:

<jxb:bindings node="//xs:simpleType[@name=’ZipCodeType’]">
Binding Customization File Format

Binding customization files should be straight ASCII text. The name or extension doesnot matter, although a typical extension, used in this chapter, is.xjb.

Passing Customization Files to the JAXB Binding Compiler

Customization files containing binding declarations are passed to the JAXB Binding compiler,xjc,using the following syntax:

xjc -bfileschema

wherefile is the name of binding customization file, andschema is thename of the schema or schemas you want to pass to the bindingcompiler.

You can have a single binding file that contains customizations for multiple schemas,or you can break the customizations into multiple bindings files; for example:

xjc schema1.xsd schema2.xsd schema3.xsd -b bindings123.xjbxjc schema1.xsd schema2.xsd schema3.xsd -b bindings1.xjb -b bindings2.xjb -b bindings3.xjb

Note that the ordering of schema files and binding files on thecommand line does not matter, although each binding customization file must be preceded byits own-b switch on the command line.

For more information aboutxjc compiler options in general, seeJAXB Compiler Options.

Restrictions for External Binding Customizations

There are several rules that apply to binding declarations made in an externalbinding customization file that do not apply to similar declarations made inline ina source schema:

  • The binding customization file must begin with thejxb:bindings version attribute, plus attributes for the JAXB and XMLSchema namespaces:

    <jxb:bindings version="1.0" xmlns:jxb="http://java.sun.com/xml/ns/jaxb" xmlns:xs="http://www.w3.org/2001/XMLSchema">
  • The remote schema to which the binding declaration applies must be identified explicitly in XPath notation by means of ajxb:bindings declaration specifyingschemaLocation andnode attributes:

    • schemaLocation specifies a URI reference to the remote schema.

    • node specifies an XPath 1.0 expression that identifies the schema node withinschemaLocation to which the given binding declaration is associated; in the case of the initialjxb:bindings declaration in the binding customization file, this node is typically"/xs:schema".

    Similarly, individual nodes within the schema to which customizations are to be applied must be specified using XPath notation; for example:

    <jxb:bindings node="//xs:complexType[@name=’USAddress’]">

    In such cases, the customization is applied to the node by the binding compiler as if the declaration was embedded inline in the node’s<xs:appinfo> element.

To summarize these rules, the external binding element<jxb:bindings> is only recognizedfor processing by a JAXB binding compiler in three cases:

  • When its parent is an<xs:appinfo> element.

  • When it is an ancestor of another<jxb:bindings> element.

  • When it is the root element of a document. An XML document that has a<jxb:bindings> element as its root is referred to as an external binding declaration file.

Scope, Inheritance, and Precedence

Default JAXB bindings can be customized or overridden at four different levels, orscopes.

Figure 17-3 illustrates the inheritance and precedence of customization declarations. Specifically, declarations towards the topof the pyramid inherit and supersede declarations below them. For example, Component declarationsinherit from and supersede Definition declarations; Definition declarations inherit and supersede Schema declarations; andSchema declarations inherit and supersede Global declarations.

Figure 17-3 Customization Scope Inheritance and Precedence

Diagram of scope inheritance. Top to bottom: Component Scope, Definition Scope, Schema Scope, and Global Scope.
Customization Syntax

The syntax for the four types of JAXB binding declarations, as well asthe syntax for the XML-to-Java data type binding declarations and the customization namespaceprefix, are described below.

Global Binding Declarations

Global scope customizations are declared with<globalBindings>. The syntax for global scope customizationsis as follows:

<globalBindings>    [ collectionType = "collectionType" ]    [ fixedAttributeAsConstantProperty    = "true" | "false" | "1" | "0" ]    [ generateIsSetMethod    = "true" | "false" | "1" | "0" ]    [ enableFailFastCheck = "true" | "false" | "1" | "0" ]    [ choiceContentProperty = "true" | "false" | "1" | "0" ]    [ underscoreBinding = "asWordSeparator" | "asCharInWord" ]    [ typesafeEnumBase = "typesafeEnumBase" ]    [ typesafeEnumMemberName = "generateName" | "generateError" ]    [ enableJavaNamingConventions = "true" | "false" | "1" | "0" ]    [ bindingStyle = "elementBinding" | "modelGroupBinding" ]    [ <javaType> ... </javaType> ]*</globalBindings>
  • collectionType can be eitherindexed or any fully qualified class name that implementsjava.util.List.

  • fixedAttributeAsConstantProperty can be eithertrue,false,1, or0. The default value isfalse.

  • generateIsSetMethod can be eithertrue,false,1, or0. The default value isfalse.

  • enableFailFastCheck can be eithertrue,false,1, or0. IfenableFailFastCheck istrue or1 and the JAXB implementation supports this optional checking, type constraint checking is performed when setting a property. The default value isfalse. Please note that the JAXB implementation does not support failfast validation.

  • choiceContentProperty can be eithertrue,false,1, or0. The default value isfalse.choiceContentProperty is not relevant when thebindingStyle iselementBinding. Therefore, ifbindingStyle is specified aselementBinding, then thechoiceContentProperty must result in an invalid customization.

  • underscoreBinding can be eitherasWordSeparator orasCharInWord. The default value isasWordSeparator.

  • typesafeEnumBase can be a list of QNames, each of which must resolve to a simple type definition. The default value isxs:NCName. SeeTypesafe Enumeration Binding Declarations for information about localized mapping ofsimpleType definitions to Javatypesafe enum classes.

  • typesafeEnumMemberName can be eithergenerateError orgenerateName. The default value isgenerateError.

  • enableJavaNamingConventions can be eithertrue,false,1, or0. The default value istrue.

  • bindingStyle can be eitherelementBinding, ormodelGroupBinding. The default value iselementBinding.

  • <javaType> can be zero or more javaType binding declarations. For more information, seejavaType Binding Declarations.

<globalBindings> declarations are only valid in theannotation element of the top-levelschemaelement. There can only be a single instance of a<globalBindings> declaration in anygiven schema or binding declarations file. If one source schema includes or importsa second source schema, the<globalBindings> declaration must be declared in the firstsource schema.

Schema Binding Declarations

Schema scope customizations are declared with<schemaBindings>. The syntax for schema scope customizationsis:

<schemaBindings>    [ <package> package </package> ]    [ <nameXmlTransform> ... </nameXmlTransform> ]*</schemaBindings>    <package [ name = "packageName" ]    [ <javadoc> ... </javadoc> ]</package><nameXmlTransform>    [ <typeName [ suffix="suffix" ]                [ prefix="prefix" ] /> ]    [ <elementName [ suffix="suffix" ]                   [ prefix="prefix" ] /> ]    [ <modelGroupName [ suffix="suffix" ]                      [ prefix="prefix" ] /> ]    [ <anonymousTypeName [ suffix="suffix" ]                         [ prefix="prefix" ] /> ]</nameXmlTransform>

As shown above,<schemaBinding> declarations include two subcomponents:

  • <package>...</package> specifies the name of the package and, if desired, the location of the API documentation for the schema-derived classes.

  • <nameXmlTransform>...</nameXmlTransform> specifies customizations to be applied.

Class Binding Declarations

The<class> binding declaration enables you to customize the binding of a schemaelement to a Java content interface or a JavaElement interface.<class> declarations canbe used to customize:

  • A name for a schema-derived Java interface

  • An implementation class for a schema-derived Java content interface

The syntax for<class> customizations is:

<class [ name = "className"]   [ implClass= "implClass" ] >   [ <javadoc> ... </javadoc> ]</class>
  • 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 forclassName 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 useCDATA or< to escape embedded HTML tags.

Property Binding Declarations

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

The syntax for<property> customizations is:

<property    [ name = "propertyName"]    [ collectionType = "propertyCollectionType" ]    [ fixedAttributeAsConstantProperty = "true" | "false" | "1" | "0" ]    [ generateIsSetMethod = "true" | "false" | "1" | "0" ]    [ enableFailFastCheck ="true" | "false" | "1" | "0" ]    [ <baseType> ... </baseType> ]    [ <javadoc> ... </javadoc> ]</property><baseType>    <javaType> ... </javaType></baseType>
  • name defines the customization valuepropertyName; it must be a legal Java identifier.

  • collectionType defines the customization valuepropertyCollectionType, which is the collection type for the property.propertyCollectionType. If specified, can be eitherindexed or any fully-qualified class name that implementsjava.util.List.

  • fixedAttributeAsConstantProperty defines the customization valuefixedAttributeAsConstantProperty. The value can be eithertrue,false,1, or0.

  • generateIsSetMethod defines the customization value ofgenerateIsSetMethod. The value can be eithertrue,false,1, or0.

  • enableFailFastCheck defines the customization valueenableFailFastCheck. The value can be eithertrue,false,1, or0. Please note that the JAXB implementation does not support failfast validation.

  • <javadoc> customizes the Javadoc tool annotations for the property’s getter method.

javaType Binding Declarations

The<javaType> declaration provides a way to customize the translation of XML datatypes to and from Java data types. XML provides more data types thanJava, and so the<javaType> declaration lets you specify custom data type bindingswhen the default JAXB binding cannot sufficiently represent your schema.

The target Java data type can be a Java built-in data typeor an application-specific Java data type. If an application-specific data type is usedas the target, your implementation must also provide parse and print methods forunmarshalling and marshalling data. To this end, the JAXB specification supports aparseMethodandprintMethod:

  • TheparseMethod is called during unmarshalling to convert a string from the input document into a value of the target Java data type.

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

If you prefer to define your own data type conversions, JAXB defines astatic class,DatatypeConverter, to assist in the parsing and printing of valid lexicalrepresentations of the XML Schema built-in data types.

The syntax for the<javaType> customization is:

<javaType name= "javaType"    [ xmlType= "xmlType" ]    [ hasNsContext = "true" | "false" ]    [ parseMethod= "parseMethod" ]    [ printMethod= "printMethod" ]>
  • name is the Java data type to whichxmlType is to be bound.

  • xmlType is the name of the XML Schema data type to whichjavaType is to be bound; this attribute is required when the parent of the<javaType> declaration is<globalBindings>.

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

  • 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.

The<javaType> declaration can be used in:

  • A<globalBindings> declaration

  • An annotation element for simple type definitions,GlobalBindings, and<basetype> declarations

  • A<property> declaration

SeeMyDatatypeConverter Class for an example of how<javaType> declarations and theDatatypeConverterInterface interfaceare implemented in a custom data type converter class.

Typesafe Enumeration Binding Declarations

The typesafe enumeration declarations provide a localized way to map XMLsimpleType elementsto Javatypesafe enum classes. There are two types of typesafe enumeration declarations youcan make:

  • <typesafeEnumClass> lets you map an entiresimpleType class totypesafe enum classes.

  • <typesafeEnumMember> lets you map just selected members of asimpleType class totypesafe enum classes.

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

  • OnlysimpleType definitions with enumeration facets can be customized using this binding declaration.

  • This customization only applies to a singlesimpleType definition at a time. To map sets of similarsimpleType definitions on a global level, use thetypesafeEnumBase attribute in a<globalBindings> declaration, as described inGlobal Binding Declarations.

The syntax for the<typesafeEnumClass> customization is:

<typesafeEnumClass    [ name = "enumClassName" ]    [ <typesafeEnumMember> ... </typesafeEnumMember> ]*    [ <javadoc> enumClassJavadoc </javadoc> ]</typesafeEnumClass>
  • name must be a legal Java Identifier, and must not have a package prefix.

  • You can have zero or more<typesafeEnumMember> declarations embedded in a<typesafeEnumClass> declaration.

  • <javadoc> customizes the Javadoc tool annotations for the enumeration class.

The syntax for the<typesafeEnumMember> customization is:

<typesafeEnumMember name = "enumMemberName">                    [ value = "enumMemberValue" ]    [ <javadoc> enumMemberJavadoc </javadoc> ]</typesafeEnumMember>
  • name must always be specified and must be a legal Java identifier.

  • value must be the enumeration value specified in the source schema.

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

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

For information about typesafe enum design patterns, see thesample chapter of Joshua Bloch’sEffective Java Programming on the Java Developer Connection.

javadoc Binding Declarations

The<javadoc> declaration lets you add custom Javadoc tool annotations to schema-derived JAXBpackages, classes, interfaces, methods, and fields. Note that<javadoc> declarations cannot be applied globally;they are only valid as 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 mustcontain<body> open and close tags; for example:

<jxb:package name="primer.myPo">  <jxb:javadoc>    <![CDATA[<body>Package level documentation for generated package primer.myPo.</body>]]>  </jxb:javadoc></jxb:package>
Customization Namespace Prefix

All standard JAXB binding declarations must be preceded by a namespace prefix thatmaps 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 standardJAXB binding declarationsmust include the JAXB namespace declaration and JAXB version numberat the top of the schema file. For example, inpo.xsd for theCustomize Inline example, the namespace declaration is as follows:

<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"            xmlns:jxb="http://java.sun.com/xml/ns/jaxb"            jxb:version="1.0">

A binding declaration with thejxb namespace prefix would then take the form:

<xsd:annotation>   <xsd:appinfo>      <jxb:globalBindingsbinding declarations />      <jxb:schemaBindings>         .         .binding declarations         .         .      </jxb:schemaBindings>   </xsd:appinfo></xsd:annotation>

Note that in this example, theglobalBindings andschemaBindings declarations are usedto specify, respectively, global scope and schema scope customizations. These customization scopes aredescribed in more detail inScope, Inheritance, and Precedence.

Customize Inline Example

The Customize Inline example illustrates some basic customizations made by means of inlineannotations to an XML schema namedpo.xsd. In addition, this example implements acustom data type converter class,MyDatatypeConverter.java, which illustrates print and parse methods inthe<javaType> customization for handling custom data type conversions.

To summarize this example:

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

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

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

Building and Running the Customize Inline Example Using NetBeans IDE

Follow these instructions to build and run the Customize Inline example on yourApplication Server instance using NetBeans IDE.

  1. In NetBeans IDE, select File→Open Project.

  2. In the Open Project dialog, navigate totut-install/javaeetutorial5/examples/jaxb/.

  3. Select theinline-customize folder.

  4. Select the Open as Main Project check box.

  5. Click Open Project.

  6. Right-click theinline-customize project and select Run.

Building and Running the Customize Inline Example Using Ant

To compile and run the Customize Inline example using Ant, in aterminal window, go to thetut-install/javaeetutorial5/examples/jaxb/inline-customize/ directory and type the following:

ant runapp

Key customizations in this sample, and the customMyDatatypeConverter.java class, are describedin more detail below.

Customized Schema

The customized schema used in the Customize Inline example is in the filetut-install/javaeetutorial5/examples/jaxb/inline-customize/po.xsd. The customizations are in the<xsd:annotation> tags.

Global Binding Declarations

The code below shows theglobalBindings declarations inpo.xsd:

<jxb:globalBindings        fixedAttributeAsConstantProperty="true"        collectionType="java.util.Vector"        typesafeEnumBase="xsd:NCName"        choiceContentProperty="false"        typesafeEnumMemberName="generateError"        bindingStyle="elementBinding"        enableFailFastCheck="false"        generateIsSetMethod="false"        underscoreBinding="asCharInWord"/>

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

  • SettingfixedAttributeAsConstantProperty 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, whichever is more appropriate.

  • SettingcollectionType tojava.util.Vector specifies that all lists in the generated implementation classes should be represented internally as vectors. Note that the class name you specify forcollectionType must implementjava.util.List and be callable bynewInstance.

  • IftypesafeEnumBase is set toxsd:string, it would be a global way to specify that allsimple type definitions deriving directly or indirectly fromxsd:string and having enumeration facets should be bound by default to atypesafe enum. IftypesafeEnumBase is set to an empty string,"", nosimple type definitions would ever be bound to atypesafe enum class by default. The value oftypesafeEnumBase can be any atomic simple type definition exceptxsd:boolean and both binary types.

  • The JAXB implementation does not support theenableFailFastCheck attribute.


    Note -Usingtypesafe enum classes 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.


Schema Binding Declarations

The following code shows the schema binding declarations inpo.xsd:

<jxb:schemaBindings>  <jxb:package name="primer.myPo">    <jxb:javadoc>      <![CDATA[<body> Package level documentation for generated package primer.myPo.</body>]]>    </jxb:javadoc>  </jxb:package>  <jxb:nameXmlTransform>    <jxb:elementName suffix="Element"/>  </jxb:nameXmlTransform></jxb:schemaBindings>
  • <jxb:package name="primer.myPo"/> specifies theprimer.myPo as the package in which the schema-derived classes should be generated.

  • <jxb:nameXmlTransform> specifies that all generated Java element interfaces should haveElement appended to the generated names by default. For example, when the JAXB compiler is run against this schema, the element interfacesCommentElement andPurchaseOrderElement will be generated. By contrast, without this customization, the default binding would instead generateComment andPurchaseOrder.

    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 theprimer.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.

Class Binding Declarations

The following code shows the class binding declarations inpo.xsd:

<xsd:complexType name="PurchaseOrderType">      <xsd:annotation>      <xsd:appinfo>         <jxb:class name="POType">            <jxb:javadoc>            A &lt;b>Purchase Order&lt;/b> consists of addresses and items.            </jxb:javadoc>         </jxb:class>      </xsd:appinfo>      </xsd:annotation>      .      .      .</xsd:complexType>

The Javadoc tool annotations for the schema-derivedPOType 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 theappinfo element of acomplexTypedefinition, as it is here, thecomplexType definition is bound to a Java contentinterface.


Later inpo.xsd, another<javadoc> customization is declared at this class level, butthis time the HTML string is escaped withCDATA:

<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>

Note -If you want to include HTML markup tags in a<jaxb:javadoc> customization,you must enclose the data within aCDATA section or escape all leftangle brackets using&lt;. SeeXML 1.0 2nd Edition for more information.


Property Binding Declarations

Of particular interest here is thegenerateIsSetMethod customization, which causes two additional propertymethods,isSetQuantity andunsetQuantity, to be generated. These methods enable a clientapplication to distinguish between schema default values and values occurring explicitly within an instancedocument.

For example, inpo.xsd:

<xsd:complexType name="Items">   <xsd:sequence>      <xsd:element name="item" minOccurs="1" maxOccurs="unbounded">         <xsd:complexType>            <xsd:sequence>            <xsd:element name="productName" type="xsd:string"/>            <xsd:element name="quantity" default="10">            <xsd:annotation>               <xsd:appinfo>                  <jxb:property generateIsSetMethod="true"/>               </xsd:appinfo>            </xsd:annotation>         ...         </xsd:complexType>      </xsd:element>   </xsd:sequence></xsd:complexType>

The@generateIsSetMethod applies to thequantity element, which is bound to aproperty within theItems.ItemType interface.unsetQuantity andisSetQuantity methods are generated intheItems.ItemType interface.

MyDatatypeConverter Class

The classtut-install/javaeetutorial5/examples/jaxb/inline-customize/src/inlinecustomize/primer/MyDatatypeConverter, shown below, provides a way to customize the translationof XML data types to and from Java data types by means ofa<javaType> customization.

package primer;import java.math.BigInteger;import javax.xml.bind.DatatypeConverter;public class MyDatatypeConverter {    public static short parseIntegerToShort(String value) {        BigInteger result = DatatypeConverter.parseInteger(value);        return (short)(result.intValue());    }    public static String printShortToInteger(short value) {        BigInteger result = BigInteger.valueOf(value);        return DatatypeConverter.printInteger(result);    }    public static int parseIntegerToInt(String value) {        BigInteger result = DatatypeConverter.parseInteger(value);        return result.intValue();    }    public static String printIntToInteger(int value) {        BigInteger result = BigInteger.valueOf(value);        return DatatypeConverter.printInteger(result);    }};

The following code shows how theMyDatatypeConverter class is referenced in a<javaType>declaration inpo.xsd:

<xsd:simpleType name="ZipCodeType"><xsd:annotation><xsd:appinfo><jxb:javaType name="int"parseMethod="primer.MyDatatypeConverter.parseIntegerToInt"printMethod="primer.MyDatatypeConverter.printIntTo Integer" /></xsd:appinfo></xsd:annotation>    <xsd:restriction base="xsd:integer">    <xsd:minInclusive value="10000"/>    <xsd:maxInclusive value="99999"/>  </xsd:restriction></xsd:simpleType>

In this example, thejxb:javaType binding declaration overrides the default JAXB binding ofthis type tojava.math.BigInteger. For the purposes of the Customize Inline example, therestrictions onZipCodeType (specifically, that legal United States ZIP codes are limitedto five digits) make it so all valid values can easily fit withinthe Java primitive data typeint. Note also that, because<jxb:javaType name="int"/> is declaredwithinZipCodeType, the customization applies to all JAXB properties that reference thissimpleTypedefinition, including thegetZip andsetZip methods.

Datatype Converter Example

The Datatype Converter example is very similar to the Customize Inline example. Aswith the Customize Inline example, the customizations in the Datatype Converter example aremade 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 theCustomize Inline and Datatype Converter examples are identical. Where the Datatype Converter examplediffers from the Customize Inline example is in theparseMethod andprintMethod used forconverting XML data to the Javaint data type.

Specifically, rather than using methods in the customMyDataTypeConverter class to performthese data type conversions, the Datatype Converter example uses the built-in methods providedbyjavax.xml.bind.DatatypeConverter:

<xsd:simpleType name="ZipCodeType">  <xsd:annotation>      <xsd:appinfo>        <jxb:javaType name="int"            parseMethod="javax.xml.bind.DatatypeConverter.parseInt"            printMethod="javax.xml.bind.DatatypeConverter.printInt"/>     </xsd:appinfo>  </xsd:annotation>  <xsd:restriction base="xsd:integer">    <xsd:minInclusive value="10000"/>    <xsd:maxInclusive value="99999"/>  </xsd:restriction></xsd:simpleType>
Building and Running the Datatype Converter Example Using NetBeans IDE

Follow these instructions to build and run the Datatype Converter example on yourApplication Server instance using NetBeans IDE.

  1. In NetBeans IDE, select File→Open Project.

  2. In the Open Project dialog, navigate totut-install/javaeetutorial5/examples/jaxb/.

  3. Select thedatatypeconverter folder.

  4. Select the Open as Main Project check box.

  5. Click Open Project.

  6. Right-click thedatatypeconverter project and select Run.

Building and Running the Datatype Converter Example Using Ant

To compile and run the Datatype Converter example using Ant, in aterminal window, go to thetut-install/javaeetutorial5/examples/jaxb/datatypeconverter/ directory and type the following:

ant runapp

Binding Declaration Files

The following sections provide information about binding declaration files:

JAXB Version, Namespace, and Schema Attributes

All JAXB binding declarations files must begin with:

  • JAXB version number

  • Namespace declarations

  • Schema name and node

The version, namespace, and schema declarations inbindings.xjb are as follows:

<jxb:bindings version="1.0"              xmlns:jxb="http://java.sun.com/xml/ns/jaxb"              xmlns:xs="http://www.w3.org/2001/XMLSchema">  <jxb:bindings schemaLocation="po.xsd" node="/xs:schema">        ...binding-declarations        ...  </jxb:bindings><!-- schemaLocation="po.xsd" node="/xs:schema" --></jxb:bindings>
JAXB Version Number

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

<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"            xmlns:jxb="http://java.sun.com/xml/ns/jaxb"            jxb:version="1.0">
Namespace Declarations

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

Schema Name and Schema Node

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

<jxb:bindings schemaLocation="po.xsd" node="/xs:schema">
Global and Schema Binding Declarations

The global schema binding declarations inbindings.xjb are the same as those inpo.xsd for the Datatype Converter example. The only difference is that because thedeclarations inpo.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 thisway is unnecessary in the external bindings file.

<jxb:globalBindings  fixedAttributeAsConstantProperty="true"  collectionType="java.util.Vector"  typesafeEnumBase="xs:NCName"  choiceContentProperty="false"  typesafeEnumMemberName="generateError"  bindingStyle="elementBinding"  enableFailFastCheck="false"  generateIsSetMethod="false"  underscoreBinding="asCharInWord"/><jxb:schemaBindings>  <jxb:package name="primer.myPo">    <jxb:javadoc>      <![CDATA[<body>Package level documentation for generated package primer.myPo.</body>]]>    </jxb:javadoc>  </jxb:package>  <jxb:nameXmlTransform>    <jxb:elementName suffix="Element"/>  </jxb:nameXmlTransform></jxb:schemaBindings>

By comparison, the syntax used inpo.xsd for the Datatype Converter example is:

<xsd:annotation>  <xsd:appinfo>    <jxb:globalBindings        ...binding-declarations        ...    <jxb:schemaBindings>        ...binding-declarations        ...    </jxb:schemaBindings>  </xsd:appinfo></xsd:annotation>
Class Declarations

The class-level binding declarations inbindings.xjb differ from the analogous declarations inpo.xsdfor the Datatype Converter example in two ways:

  • As with all other binding declarations inbindings.xjb, you do not need to embed your customizations in schema<xsd:appinfo> elements.

  • You must specify the schema node to which the customization will be applied. The general syntax for this type of declaration is:

    <jxb:bindings node="//node-type[@name=’node-name’]">

For example, the following code shows binding declarations for thecomplexType namedUSAddress.

<jxb:bindings node="//xs:complexType[@name=’USAddress’]">  <jxb:class>    <jxb:javadoc>      <![CDATA[First line of documentation for a <b>USAddress</b>.]]>    </jxb:javadoc>  </jxb:class>  <jxb:bindings node=".//xs:element[@name=’name’]">    <jxb:property name="toName"/>  </jxb:bindings>  <jxb:bindings node=".//xs:element[@name=’zip’]">    <jxb:property name="zipCode"/>  </jxb:bindings></jxb:bindings><!-- node="//xs:complexType[@name=’USAddress’]" -->

Note in this example thatUSAddress is the parent of the child elementsname andzip, and therefore a</jxb:bindings> tag encloses thebindings declarations forthe child elements as well as the class-leveljavadoc declaration.

External Customize Example

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

The binding customization file used in the External Customize example istut-install/javaeetutorial5/examples/jaxb/external-customize/binding.xjb.

This section compares the customization declarations inbindings.xjb with the analogous declarationsused in the XML schema,po.xsd, in the Datatype Converter example. Thetwo sets of declarations achieve precisely the same results.

Building and Running the External Customize Example Using NetBeans IDE

Follow these instructions to build and run the External Customize example on yourApplication Server instance using NetBeans IDE.

  1. In NetBeans IDE, select File→Open Project.

  2. In the Open Project dialog, navigate totut-install/javaeetutorial5/examples/jaxb/.

  3. Select theexternal-customize folder.

  4. Select the Open as Main Project check box.

  5. Click Open Project.

  6. Right-click theexternal-customize project and select Run.

Building and Running the External Customize Example Using Ant

To compile and run the External Customize example using Ant, in aterminal window, go to thetut-install/javaeetutorial5/examples/jaxb/external-customize/ directory and type the following:

ant runapp
PreviousContentsNext

Copyright © 2010, Oracle and/or its affiliates. All rights reserved.Legal Notices


[8]ページ先頭

©2009-2025 Movatter.jp