Download JAXB

Document related concepts
no text concepts found
Transcript
JAXB
JAXB
(Java API for
XML Data Binding)
Cheng-Chia Chen
Transparency No. 1
JAXB
Agenda
 What is and Why JAXB?
 How to use JAXB?
 JAXB architecture
 Binding process
 Custom binding
 Runtime operations
 JAXB Roadmap
Transparency No. 2
JAXB
Languages for XML Schemas
 XML 1.0 Document Type Definitions (DTDs)
 Fairly weak constraints
 No data types or complex structural relationships
 W3C XML Schema Definition Language
Recommendation (2, May, 01)
 Many Others
 RELAXNG,…
Transparency No. 3
JAXB
W3C XML Schema Definition for Sample Document Instance
<xsd:schema xmlns:xsd =
"http://www.w3.org/2001/XMLSchema">
<xsd:complexType name="tradeType">
<xsd:sequence>
<xsd:element name = "symbol" type = "xsd:string"/>
<xsd:element name = "quantity" type = "xsd:int"/>
</xsd:sequence>
<xsd:attribute name = "action" use = "required">
<xsd:simpleType>
<xsd:restriction base = "xsd:NMTOKEN">
<xsd:enumeration value = "buy"/> <!--document instance-->
<xsd:enumeration value = "sell"/> <?xml version="1.0"?>
<trade action="buy">
</xsd:restriction>
<symbol>ABC</symbol>
</xsd:simpleType>
<quantity>30</quantity>
</xsd:attribute>
</trade>
</xsd:complexType>
<xsd:element name = "trade" type="tradeType"/>
</xsd:schema>
Transparency No. 4
JAXB
XML Processing Options
 SAX
 (push sax) Stateless event driven
 Pull SAX
 StAX (JSR-173 in JCP public review): Streaming API for XML
 XML Pull parsing
 DOM (language neutral)
 Memory intensive parse tree
 XOM, JDOM, DOM4J
 DOM-like APIs for Java
 JAXB , Castor, XMLBeans
 XML to Java objects binding
 document  object and schema  class
 digester
 rule-based XML processing
 Jelly, ant
 Executable XML
 RelaxNGCC
 syntax-directed approach
Transparency No. 5
JAXB
What is & Why
JAXB?
Transparency No. 1
JAXB
What Is JAXB?
 A system providing API, tools, and a framework that
automate the mapping between XML documents and
Java objects
instanceOf
instanceOf
Transparency No. 7
JAXB
Things You can do during Runtime
 Unmarshal XML content (XML document instance)
to Java representations
 XML documents  Java Objects
 Access, update and validate the Java representation
against schema constraints
 create/manipulat java objects
 Marshal the Java representation of the XML content
into XML content
 java objects  XML documents
 advantage:
 Use domain object model instead of DOM/XML model
to manipulate data.
Transparency No. 8
JAXB
Why JAXB?
 An efficient and standard way of mapping between
XML and Java code
 Programmers don't have to create application specific
Java objects anymore themselves
 Programmers do not have to deal with XML structure,
instead deal with meaning business data
getPerson() method as opposed to getAttributes()
 In a sense JAXB is high-level language while
JAXP/SAX/DOM are assembly language for XML
document management
Transparency No. 9
JAXB
Why JAXB?
 Issues with DOM/SAX model
 Why do I have to walk a Parse Tree containing much
more than just application data?
getNodeName(), getNodeType(), getNodeValue()
 Why do I have to write Event Handlers to map XML
content to Java™ classes?
 Value proposition of JAXB
 JAXB automates XML to Java™ binding so you can
easily access your data
Transparency No. 10
JAXB
JAXB versus DOM
 Both JAXB and DOM create in-memory content tree
 In JAXB,
 Content tree is specific to a specific source schema
Does not contain extra tree-manipulation functionality
 Allows access to its data with the derived classes'
accessor methods
“Data-driven” as opposed to “XML document driven”
 Content tree is not created dynamically, thus uses
memory efficiently
Transparency No. 11
JAXB
JAXB Design Goals
 Easy to use
 Lower “barrier to entry” to manipulating XML
documents within Java programs
 Don't have to deal with complexities of SAX and DOM
 Customizable
 Sophisticated applications sometimes require fine
control over the structure and content of schemaderived classes
 Allows keeping pace with schema evolution
Transparency No. 12
JAXB
JAXB Design Goals
 Portable
 JAXB components can be replaced without having to
make significant changes to the rest of the source
code
 Validation on demand
 Validate the tree against the constraints in the source
schema
 Clean “round-tripping”
 Converting a Java content tree to XML content and
back to Java content again should result in equivalent
Java content trees before and after the conversion
Transparency No. 13
JAXB
How to Use JAXB?
Transparency No. 1
JAXB
Steps of Building & Using JAXB Applications (Compile time)
 Develop or obtain XML schema/DTD
 Optionally annotate the schema with binding
customizations if necessary (or place them in an external
binding file)
 Generate the Java source files
 By compiling the XML Schema through the binding
compiler
 Develop JAXB client application
 Using the Java content classes generated by the binding
compiler along with the javax.xml.bind JAXB interfaces
 Compile the Java source codes
 client application +
 API code generated by jaxb compiler.
Transparency No. 15
JAXB
Steps of Building & Using JAXB Applications (Runtime)
 With the classes and the binding framework, write
Java applications that:
 Build object trees representing XML data
that is valid against the XML Schema by either
unmarshalling the data from an XML document or
instantiating the classes you created
 Access and modify the data
Optionally validate the modifications to the data relative
to the constraints expressed in the XML Schema
 Marshal in-memory data to a new XML document
Transparency No. 16
JAXB
Schema Languages that JAXB Supports
 JAXB RI 1.0.4
 (compliant with JAXB spec 1.0) from Java WSDP 1.5
 Support XML Schema, DTD and RELAX NG.
Transparency No. 17
JAXB
JAXB Architecture
Transparency No. 1
JAXB
JAXB Architecture
source: JAXB User's Guide
Transparency No. 19
JAXB
XML Data Binding Facility
 Binding compiler (xjc)
 Binds schema components to derived classes
 Schema derived interfaces and classes
 A content tree is a tree of in-memory instances
 The methods provide access to the content
of the corresponding schema component
 Binding Runtime API
 Provide runtime XML-enabling operations
(unmarshalling, marshalling, validating) on content
trees through schema-derived classes
 Implementation of javax.xml.bind
Transparency No. 20
JAXB
Binding runtime API (in package javax.xml.binding
 The basic binding operations provided are:
 Unmarshal XML document to a content tree
 Validate a content tree based on constraints
expressed within the original schema
 Marshal a content tree to an XML document
Transparency No. 21
JAXB
Binding Process
Transparency No. 1
JAXB
Binding Process: 2 Phases
 Design time
 Generate JAXB classes from a source schema
 Compile the JAXB classes
 Build an application that uses these classes
 Run time (Binding runtime)
 Unmarshal XML content tree + create xml content tree
fro the generated java classes.
 Process (Access & Modify) XML content tree
 Validate XML content tree
 Marshal XML content tree
Transparency No. 23
JAXB
The Binding Life Cycle
compile
Schema
Derived
Classes
validate
Instances of
follows
XML
Document
unmarshal
Objects
marshal
Transparency No. 24
JAXB
Binding Process :
Design Time Binding
Process
Transparency No. 1
JAXB
Role of Binding Compiler
 principles:
 Bind target XML namespace to package
 Bind element or complex type to derived class
 Bind attribute or leaf element to a property
package
Derived
Class
Schema
Binding
Schema
(optional)
Binding
Compiler
Property
Property
Transparency No. 26
JAXB
Binding Rules
 Default rules
 Specified in the JAXB spec
 xjc uses default rules for components of source schema
not mentioned explicitly in custom binding declaration
 Custom rules (Custom Binding Declaration)
 Can be “inline”'ed in XML schema document or
 Separate custom binding declaration file
Transparency No. 27
JAXB
Binding Process:
Default Binding
Transparency No. 1
JAXB
Default XML to Java Binding
 Simple Type Definitions
 Default Data Type Bindings
 Default Binding Rules Summary
Transparency No. 29
JAXB
Default Data Type Binding
Java Data Type
XML Schema Type
●
●
●
●
●
●
●
●
●
●
●
xsd:string
xsd:integer
xsd:int
xsd:long
xsd:short
xsd:decimal
xsd:float
xsd:double
xsd:boolean
xsd:byte
xsd:QName
●
●
●
●
●
●
●
●
●
●
●
java.lang.String
java.math.BigInteger
int
long
short
java.math.BigDecimal
float
double
boolean
byte
javax.xml.namespace.QNa
me
Transparency No. 31
JAXB
Default Data Type Binding
Java Data Type
XML Schema Type
●
●
●
●
●
●
●
●
●
xsd:dataTime
xsd:base64Binary
xsd:hexBinary
xsd:unsignedInt
xsd:unsignedShort
xsd:unsignedByte
xsd:time
xsd:date
xsd:anySimpleType
●
●
●
●
●
●
●
●
●
java.util.Calendar
byte[]
byte[]
long
int
short
java.util.Date
java.util.Date
java.lang.String
Transparency No. 32
JAXB
Binding Process:
Default Binding Rules &
Examples
Transparency No. 1
JAXB
Default Binding Rules:Global Element
To
From
●
●
●
global element
declaration
Local element
declaration that can
be inserted into a
general content list
●
●
Java Element
interface
Java Element
interface
Attribute
●
Java property
Transparency No. 34
JAXB
Default Binding Example:
Global Element
JAXB Binding
XML Schema
●
●
●
<xsd:schema
xmlns:xsd="http://ww
w.w3.org/2001/XMLS
chema">
<xsd:element
name="purchaseOrd
er"
type="PurchaseOrder
Type"/>
<xsd:element
name="comment"
type="xsd:string"/>
●
(nothing)
●
PurchaseOrder.java
●
Comment.java
Transparency No. 35
JAXB
PurchaseOrder.java
package primer.po;  from target namespace
/**
* Java content class for purchaseOrder element declaration.
* <p>The following schema fragment specifies the expected
* content contained within this java content object.
* <p>
* <pre>
* &lt;element name= "purchaseOrder"
*
type = "{}PurchaseOrderType“ />
* </pre>
*
*/
public interface PurchaseOrder
extends javax.xml.bind.Element,
primer.po.PurchaseOrderType { }
Transparency No. 36
JAXB
Default Binding Rules:
Named ComplexType
From
●
XML Namespace
URI
To
●
●
●
●
●
(global) Named
complexType
Anonymous inlined
type definition of an
element declaration
A named simple
type definition with a
basetype that
derives from
"xsd:NCName" and
has enumeration
facet
●
●
Java package
Java content
interface
Java content
interface
typesafe enum class
Transparency No. 37
JAXB
Default Binding Example: Named ComplexType
XML Schema
<xsd:complexType
name="PurchaseOrderType">
<xsd:sequence>
<xsd:element name="shipTo"
type="USAddress"/>
<xsd:element name="billTo"
type="USAddress"/>
<xsd:element ref="comment"
minOccurs="0"/>
<xsd:element name="items"
type="Items"/>
</xsd:sequence>
<xsd:attribute name="orderDate"
type="xsd:date"/>
</xsd:complexType>
JAXB Binding
PurchaseOrderType.java
property name
property type
Transparency No. 38
JAXB
PurchaseOrderType.java
package primer.po;
public interface PurchaseOrderType {
primer.po.Items getItems();
void setItems(primer.po.Items value);
Schema type does not
implement Element interface
java.util.Calendar getOrderDate();
void setOrderDate(java.util.Calendar value);
java.lang.String getComment();
void setComment(java.lang.String value);
primer.po.USAddress getBillTo();
void setBillTo(primer.po.USAddress value);
primer.po.USAddress getShipTo();
void setShipTo(primer.po.USAddress value);
}
Transparency No. 39
JAXB
Default Binding Example: ComplexType
 XML Schema
 JAXB Binding
<xsd:complexType name="USAddress">
 UMLClass :
<xsd:sequence>
<xsd:element name="name"
type="xsd:string"/>
USAddress
<xsd:element name="street"
type="xsd:string"/>
name: String
<xsd:element name="city"
street: String
type="xsd:string"/>
city: String
<xsd:element name="state"
state:String
type="xsd:string"/>
zip: BigDecimal
country: String = “US”
<xsd:element name="zip"
type="xsd:decimal"/>
</xsd:sequence>
<xsd:attribute name="country"
type="xsd:NMTOKEN" fixed="US"/>
</xsd:complexType>
Transparency No. 40
JAXB
USAddress.java
package primer.po;
public interface USAddress {
java.lang.String getState();
void setState(java.lang.String value);
java.math.BigDecimal getZip();
void setZip(java.math.BigDecimal value);
java.lang.String getCountry();
void setCountry(java.lang.String value);
java.lang.String getCity();
void setCity(java.lang.String value);
java.lang.String getStreet();
void setStreet(java.lang.String value);
java.lang.String getName();
void setName(java.lang.String value);}
Transparency No. 41
JAXB
Derived Interfaces
 Each (global) complex type definition (Named
ComplexType) mapped to
 a derived interface and
 an implementation class
 Enable user implementation of derived interface via
binding schema
 Schema Type definition hierarchy mapped to Java
inheritance class/interface hierarchy
 Natural mapping of "derivation by extension“
SchemaTypeB  SchemaTypeB (by extension)
 => JavaTypeB extends JavaTypeA
 No plans to enforce "derivation by restriction“
SchemaTypeB  SchemaTypeB (by restriction)
 => JavaTypeB = JavaTypeA [+ constraint predicate]
Transparency No. 42
JAXB
<xs:simpleType name="productCode">
<xs:restriction base="xs:string">
<xs:length value="8" fixed="true"/>
</xs:restriction>
</xs:simpleType>
<element name= “A” type=“productCode” />
The type productCode has {
base type = String
predicate (constraint) length = 8. }
Then
 public interface A extends Element {
public String getValue() ;
// will throws exception if |value| != 8.
pulic void setValue(String value) throws Exception;
…}
Transparency No. 43
JAXB
Enumeration  type safe enumeration class
 Enumeration Class
<xs:simpleType name="USState">
<xs:restriction base="xs:NCName">
<xs:enumeration value="AK"/>
<xs:enumeration value="AL"/>
</xs:restriction>
</xs:simpleType>
Transparency No. 44
JAXB
The mapped class
public class USState {
// Constructor
protected USSate(String value) { ... }
// one enumeration constant for each enumeration value
public static final String _AK="AK";
public static final USState AK= new USState(_AK);
public static final String _AL="AL";
public static final USState AL= new USState(_AL);
// Gets the value for an enumerated value
public String getValue();
// Gets enumeration with a specific value
// Required to throw java.lang.IllegalArgumentException if
// any invalid value is specified
public static USState fromValue(String value) {...}
// Gets enumeration from a String
// Required to throw java.lang.IllegalArgumentException if
// any invalid value is specified
public static USState fromString(String value){ ... }
// Returns String representation of the enumerated value
public String toString() { ... }
public boolean equals(Object obj) { ... }
public int hashCode() { ... }
}
Transparency No. 45
JAXB
Simple List type
<xs:simpleType name="xs:USStateList">
<xs:list itemType="xs:string"/>
</xs:simpleType>
<xs:element name= “A” type=“xs:USStateList”/>
=> basetype = String
collectionType = default to java.uitl.List
predicate allows only String to be added .
public interface A extends Element {
List getValue() ; // List is a list of Strings
List setValue(); …
}
Transparency No. 46
JAXB
Union type
<xs:complexType name="CTType">
<xs:attribute name="state" type="ZipOrName"/>
</xs:complexType>
<xs:simpleTypename="ZipOrName"
memberTypes="xs:integer xs:string"/>
=> public interface CTType {
Object getState();
void setState(Object value);
}
Note
1. Object is the least common super type of Integer &
String.
Transparency No. 47
JAXB
Default Binding Rules: Attribute
To
From
●
●
●
A global element
declaration
Local element
declaration that can
be inserted into a
general content list
Attribute
●
●
●
Java Element
interface
Nested Java Element
interface
Java property
Transparency No. 48
JAXB
Derived Classes: Properties
 Fine-grained XML components bound to
a property
 Accessed by setter and getter methods similar to
JavaBeans™ property accessors
 Optional validation checking by setter
 Three Core Property types
 Simple
Bean design pattern
 Indexed
Bean design pattern
 Collection Map to java.util.List types
Transparency No. 49
JAXB
Example: Default XML Binding
XML Schema
Derived Class
<xsd:complexType
name="trade">
<xsd:sequence>
<xsd:element name="symbol"
type
="xsd:string"/>
</sequence>
<xsd:attribute name="quantity"
type ="xsd:int"/>
public interface Trade
{
String getSymbol();
void
setSymbol(String);
int getQuantity();
void setQuantity(int);
}
</xsd:complexType>
Transparency No. 50
JAXB
Property Basics
 Invoking setX(null) discard property's set value
 getter method returns
 property's set value, if it is set with non-null
 schema specified default value, if existed
 Java default initial value for property's base type
 Additional Property methods
 isSetX() returns true if property's value is set
 Not generated by default, not all apps need this
Transparency No. 51
JAXB
Complex Type binding (derived by extension)
<xs:complexType name="Address">
<xs:sequence>
<xs:element name="name" type="xs:string"/>
<xs:element name="street" type="xs:string"/>
<xs:element name="city" type="xs:string"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="USAddress">
<xs:complexContent>
<xs:extension base="ipo:Address">
<xs:sequence>
<xs:element name="state" type="xs:string"/>
<xs:element name="zip" type="xs:integer"/>
</xs:sequence>
</xs:extension>
</xs:complexContent>
</xs:complexType>
Transparency No. 52
JAXB
generated interfaces
public interface Address {
String getName();
void setName(String);
String getStreet();
void setStreet(String);
void getCity();
void setCity(String);
}
public interface USAdress extends Address {
String getState();
void setState(String);
BigInteger getZip();
void setZip(BigInteger);
}
Transparency No. 53
JAXB
Simple Content Binding
 XML Schema fragment:
<xs:complexType name="internationalPrice">
<xs:simpleContent>
<xs:extension base="xs:decimal">
<xs:attribute name="currency" type="xs:string"/>
</xs:extension>
</xs:simpleContent>
</xs:complexType>
Transparency No. 54
JAXB
 Default Java binding:
interface InternationalPrice {
/** Java property for simple content */
java.math.BigDecimal getValue();
void setValue(java.math.BigDecimal value);
/** Java property for attribute*/
String getCurrency();
void setCurrency(String);
}
Transparency No. 55
JAXB
Bind to a list proeprty
 Bind to a list property
<xs:group name="AModelGroup">
<xs:choice>
<xs:element name="A" type="xs:int"/>
<xs:element name="B" type="xs:float"/>
</xs:choice>
</xs:group>
<xs:complexType name="foo">
<xs:sequence>
<xs:group ref="AModelGroup" maxOccurs="unbounded"/>
<xs:element name="C" type="xs:float"/>
</xs:sequence>
</xs:complexType>
Transparency No. 56
JAXB
 Derived Java representation:
interface AModelGroupA {
int getValue(); void setValue(int); }
interface AModelGroupB {
float getValue(); void setValue(float);}
interface Foo {
/** A valid general content property that contains
instances of AModelGroupA and AModelGroupB.*/
java.util.List getAModelGroup();
float getC();
void setC(float value);
};
Transparency No. 57
JAXB
What if maxoccurs = “1”
interface Foo {
/** A valid general content property that contains
instances of AModelGroupA and AModelGroupB.*/
AModelGroupA getAModelGroupA();
void setAModelGroupA(int ) ;
boolean isSetAModelGroupA();
/** similar for AModelGroupB **/
float getC();
void setC(float value);
};
Transparency No. 58
JAXB
ModelGroup as a interface
<xs:group name="AModelGroup">
<xs:sequence>
<xs:element name="A" type="xs:int"/>
<xs:element name="B" type="xs:float"/>
</xs:sequence>
</xs:group>
<xs:complexType name="foo">
<xs:sequence>
<xs:group ref="AModelGroup"/>
<xs:element name="C" type="xs:float"/>
</xs:sequence>
</xs:complexType>
Transparency No. 59
JAXB
public interface AModelGroup {
void setA(int value);
int getA();
void setB(float value);
float getB();
};
public interface Foo {
AModelGroup getAModelGroup();
void setAModelGroup(AModelGroup value);
float getC();
void setC(float value);
};
class ObjectFactory {
Foo createFoo();
AModelGroup createAModelGroup();
};
Transparency No. 60
JAXB
<xs:complexType name="chair_kind">
<xs:sequence>
<xs:any/>
</xs:sequence>
</xs:complexType>
public interface ChairKind {
java.lang.Object getAny();
void setAny(java.lang.Object elementOrValue);
}
Transparency No. 61
JAXB
Anonymous complex type
Given XML Schema fragment:
<xs:element name="foo">
<xs:complexType>
<xs:sequence>
<xs:element name="bar" type="xs:int"/>
</xs:sequence>
</xs:complexType>
</xs:element>
Derived Java code:
/** Java content interface generated
from anonymous complex type definition of element foo. */
interface FooType {
int getBar();
void setBar(int value);
}
/** Java Element interface. */
interface Foo extends javax.xml.bind.Element, FooType {};
Transparency No. 62
JAXB
binding to constant type
<xs:annotation><xs:appinfo>
<jaxb:globalBindings
fixedAttributeAsConstantProperty="true"/>
</xs:appinfo></xs:annotation>
<xs:complexType name="USAddress">
<xs:attribute name="country" type="xs:NMTOKEN"
fixed="US"/>
</xs:complexType>
public interface USAddress {
public static final String COUNTRY="US";
...
}
Transparency No. 63
JAXB
Custom Binding
Transparency No. 1
JAXB
Why Custom Binding?
 Customize your generated JAXB classes beyond
the XML-specific constraints in an XML schema
 Java-specific refinements such as class and package
name mapping if default name-mapping is not adequate
 Resolve name collisions
 Caused by XML Schema symbol spaces and foreign
element/attributes references
 User provides semantically meaningful and deterministic
name resolution
Transparency No. 65
JAXB
Things you want customize
 Configuration level
 Override built-in datatype bindings
 Property
 Collection as indexed or java.util.List
 Manipulate property's default value
 Class
 Bind nested model group to a JavaBean component
 Complete JavaBean component binding
Event notification model
Transparency No. 66
JAXB
Customization Mechanism
 One standard customization language
xmlns:jaxb=”http:/java.sun.com/xml/ns/jaxb”
 Customize a schema using either
 Inline annotation
 External binding declaration
 Extensible
 Uses same technique as XLST 1.0 to introduce vendor
extension customization namespace(s)
Transparency No. 67
JAXB
Name Collision Resolution
<xs:schema xmlns=”X” targetNamespace=”X”
xmlns:jxb=”http://java.sun.com/xml/ns/jaxb”
jxb:version=”1” >
<xs:annotation><xs:appinfo>
<jxb:schemaBindings>
<xs:schema
xmlns=”X” targetNamespace=”X”>
<jxb:nameXmlTransform>
<xs:complexType
name=”trade”/>
<jxb:elementName
suffix="Element"/>
<xs:element
name=”trade”
type=”trade”/>
</jxb:nameXmlTransform>
</jxb:schemaBindings>
</xs:appinfo></xs:annotation>
<xs:complexType name=”trade”/>
<xs:element name=”trade” type=”trade”/>
In Package
Package XX
In
importjavax.xml.bind.Element;
javax.xml.bind.Element;
import
publicinterface
interfaceTrade
Trade{};
{}; // ERROR: collision
public
publicinterface
interfaceTradeElement
Trade implements
Element
{}
public
implements
Element
{}
Transparency No. 68
JAXB
External Binding Declaration
Schema
(Potentially
Read-Only)
<jaxb:bindings schemaLocation=”xs:anyURI”
node=”XPATH”>
<jaxb:anyBindingDeclaration ...>
...
</jaxb:anyBindingDeclaration>
</jaxb:binding>
Transparency No. 69
JAXB
Scope of Custom Binding
 When a customization value is defined in a binding
declaration, it is associated with a scope
 4 scopes
 Global: A customization value defined in
<globalBindings>
 Schema: A customization value defined in
<schemaBindings>
 Definition: A customization value in binding
declarations of a type definition and global
declaration
 Component: A customization value applied only to the
schema element
Transparency No. 70
JAXB
Customization Scopes
<jaxb:globalBindings> - Applies to All XML namespaces
<jaxb:schemaBindings> - One per XML
namespace
Definition scope – Per component define
Component Scope (Particle and refs)
Binding declaration(s)
Transparency No. 71
JAXB
Best Practice Guidelines
 In most cases, default binding should be sufficient
 Use default binding rules whenever possible
 Better maintainability when Schema changes
Transparency No. 72
JAXB
Vendor Extensions
 Why?
 Satisfy app requirements not met by spec yet
 Allows for experimentation
 Enabled by <jaxb:extensionBindingPrefixes>
 JAXB v1.0.1 RI Implementation
 <xjc:serializable>
Generated classes can be passed via RMI
 <xjc:superClass>
Application-level base class for schema-derived
classes
 <xjc:dom>
Bind schema component to a DOM tree
Transparency No. 73
JAXB
JAXB
Runtime Operations
Transparency No. 1
JAXB
JAXB Runtime Operations
 Provide the following functionality for schemaderived classes




Unmarshal
Process (access or modify)
Marshal
Validation
 A factory generates Unmarshaller, Marshaller and
Validator instances for JAXB technology-based
applications
 Pass content tree as parameter to Marshaller and
Validator instances
Transparency No. 75
JAXB
Runtime Framework
Application Code
Portability
Layer
Binding
Compiler
Implementation
Value Add
Interfaces
and
Factories
package
javax.xml.bind
Implementation,
Helper classes
Implemention
of
javax.xml.bind
generates
Transparency No. 76
JAXB
JAXB Runtime
Operations
Unmarshalling
Transparency No. 1
JAXB
UnMarshalling Architecture
source: JAXB User's Guide
Transparency No. 78
JAXB
UnMarshalling
 Generates content tree from XML document
instance through JAXB binding framework
 Sources for unMarshalling can be





Files/documents
InputStream
String buffers
DOM nodes
SAX Sources
Transparency No. 79
JAXB
javax.xml.bind.JAXBContext
 Provides entry point to the JAXB API
 Provides an abstraction for managing the XML/Java
binding information necessary to implement the
unmarshal, marshal and validate operations
 Created via newInstance(contextPath)
 contextPath contains a list of Java package names that
contain schema derived interfaces and classes
JAXBContext jc = JAXBContext.newInstance
( "com.acme.foo:com.acme.bar" );
 Unmarshaller, Marshaller, Validator object are
created from JAXBContext object
Transparency No. 80
JAXB
javax.xml.bind.Unmarshaller
 Java Interface
 Governs the process of deserializing XML data (XML
document instance) into newly created Java content
tree
 Optionally validates XML data as it is unmarshalled
Transparency No. 81
JAXB
Unmarshalling from a File
// Create JAXBContext object
JAXBContext jc =
JAXBContext.newInstance( "com.acme.foo" );
// Create Unmarshaller object
Unmarshaller u = jc.createUnmarshaller();
// Unmarshall a XML document which is in the form of File
// o is an instance of the interface which the root
// element of example.xml binds to.
Object o = u.unmarshal( new File( "example.xml" ) );
Transparency No. 82
JAXB
Unmarshalling from an InputStream
InputStream is = new FileInputStream( "example.xml" );
JAXBContext jc =
JAXBContext.newInstance( "com.acme.foo" );
Unmarshaller u = jc.createUnmarshaller();
Object o = u.unmarshal( is );
Transparency No. 83
JAXB
Unmarshalling from a URL
JAXBContext jc =
JAXBContext.newInstance( "com.acme.foo" );
Unmarshaller u = jc.createUnmarshaller();
URL url = new URL( "http://beaker.east/example.xml" );
Object o = u.unmarshal( url );
Transparency No. 84
JAXB
Unmarshalling from a StringBuffer
JAXBContext jc =
JAXBContext.newInstance( "com.acme.foo" );
Unmarshaller u = jc.createUnmarshaller();
StringBuffer xmlStr = new StringBuffer( "<?xml
version="1.0"?>..." );
Object o = u.unmarshal( new InputSource( new
StringReader(xmlStr.toString() ) ) );
Transparency No. 85
JAXB
Unmarshalling from a org.w3c.dom.Node
JAXBContext jc =
JAXBContext.newInstance( "com.acme.foo" );
Unmarshaller u = jc.createUnmarshaller();
DocumentBuilderFactory dbf =
DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new File( "example.xml"));
Object o = u.unmarshal( doc );
Transparency No. 86
JAXB
Unmarshalling from a javax.xml.transform.sax.SAXSource
XMLReader xmlReader = saxParser.getXMLReader();
SAXSource source = new SAXSource( xmlReader, new
InputSource( "http://..." ) );
// Setup JAXB to unmarshal
JAXBContext jc = JAXBContext.newInstance( "com.acme.foo" );
Unmarshaller u = jc.createUnmarshaller();
ValidationEventCollector vec = new ValidationEventCollector();
u.setEventHandler( vec );
// turn off the JAXB provider's default validation mechanism to
// avoid duplicate validation
u.setValidating( false )
// unmarshal
Object o = u.unmarshal( source );
Transparency No. 87
JAXB
Validation During Unmarshalling
 Flexibility to enable/disable validation
 It is a waste of time to validate valid documents
 No longer required to terminate upon encountering
first validation failure
 Implementation decision when to terminate
 Enable fixing minor validation constraint errors
 Increased flexibility comes with a cost, less
deterministic behavior
Transparency No. 88
JAXB
Example: Turn off Validation During Unmarshalling
JAXBContext jc =
JAXBContext.newInstance( "com.acme.foo" );
Unmarshaller u = jc.createUnmarshaller();
u.setValidating(false);
Object o = u.unmarshal( new File( "example.xml" ) );
Transparency No. 89
JAXB
JAXB Runtime
Operations
Creating In-memory
Content
Programmatically
Transparency No. 1
JAXB
Creating Content Tree via Programmatic Factory
 Another way of creating a content tree
 You don't need XML document
 Application needs to have access and knowledge
about each of the schema derived ObjectFactory
classes that exist in each of java packages contained
in the contextPath
 For each schema derived java class, there will be a
static factory method that produces objects of that
type
 Once the client application has an instance of the the
schema derived class, it can use the mutator methods
to set content on it
Transparency No. 91
JAXB
Example Code: Programmatic generation of Content Tree
// Assume that after compiling a schema, you have a package
// com.acme.foo that contains a schema derived interface
// named PurchaseOrder.
// Create content tree from factory object
com.acme.foo.PurchaseOrder po =
com.acme.foo.ObjectFactory.createPurchaseOrder();
// Once the client application has an instance of the the schema
derived
// object, it can use the mutator methods to set content on it.
// Set attribute per constraint specified in XML schema
po.setOrderDate( Calendar.getInstance() );
Transparency No. 92
JAXB
JAXB Runtime
Operations
Processing: Accessing &
Modification
Transparency No. 1
JAXB
Processing
 Access
 Modify
Transparency No. 94
JAXB
Example Code: Processing
Unmarshaller u = jc.createUnmarshaller();
PurchaseOrder po = (PurchaseOrder) u.unmarshal
( new FileInputStream( "po.xml" ) );
USAddress address = po.getBillTo();
address.setName( "John Bob" );
address.setStreet( "242 Main Street" );
address.setCity( "Beverly Hills" );
address.setState( "CA" );
address.setZip( new BigDecimal( "90210" ) );
Transparency No. 95
JAXB
JAXB Runtime
Operations
Marshalling
Transparency No. 1
JAXB
Marshalling
source: JAXB User's Guide
Transparency No. 97
JAXB
Binding Runtime: Marshalling
 Content tree may be marshalled by passing
it to marshal method of Marshaller object
 Content trees are no longer required
to be valid before marshalling
 User discretion on whether validation desirable
 Marshalling ambiguities handled
in an implementation specific manner
Transparency No. 98
JAXB
javax.xml.bind.Marshaller
 Interface
 Governs the process of serializing Java content
trees back into XML data
Transparency No. 99
JAXB
Marshalling to a File
JAXBContext jc =
JAXBContext.newInstance( "com.acme.foo" );
Unmarshaller u = jc.createUnmarshaller();
FooObject obj = (FooObject)u.unmarshal
( new File( "foo.xml" ) );
Marshaller m = jc.createMarshaller();
OutputStream os = new FileOutputStream( “foo1.xml" );
m.marshal( obj, os );
Transparency No. 100
JAXB
Marshalling to a SAX Content Handler
JAXBContext jc =
JAXBContext.newInstance( "com.acme.foo" );
Unmarshaller u = jc.createUnmarshaller();
FooObject obj = (FooObject)u.unmarshal( new
File( "foo.xml" ) );
Marshaller m = jc.createMarshaller();
// assume MyContentHandler instanceof ContentHandler
m.marshal( obj, new MyContentHandler() );
Transparency No. 101
JAXB
Marshalling to a DOM Node
JAXBContext jc =
JAXBContext.newInstance( "com.acme.foo" );
Unmarshaller u = jc.createUnmarshaller();
FooObject obj = (FooObject)u.unmarshal( new
File( "foo.xml" ) );
Marshaller m = jc.createMarshaller();
DocumentBuilderFactory dbf =
DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.newDocument();
m.marshal(obj, doc );
Transparency No. 102
JAXB
Marshalling to a java.io.OutputStream
JAXBContext jc =
JAXBContext.newInstance( "com.acme.foo" );
Unmarshaller u = jc.createUnmarshaller();
FooObject obj = (FooObject)u.unmarshal( new
File( "foo.xml" ) );
Marshaller m = jc.createMarshaller();
m.marshal( obj, System.out );
Transparency No. 103
JAXB
Marshalling to a java.io.Writer
JAXBContext jc =
JAXBContext.newInstance( "com.acme.foo" );
Unmarshaller u = jc.createUnmarshaller();
FooObject obj = (FooObject)u.unmarshal( new
File( "foo.xml" ) );
Marshaller m = jc.createMarshaller();
m.marshal( obj, new PrintWriter( System.out ) );
Transparency No. 104
JAXB
Marshalling to a javax.xml.transform.SAXResult
JAXBContext jc =
JAXBContext.newInstance( "com.acme.foo" );
Unmarshaller u = jc.createUnmarshaller();
FooObject obj = (FooObject)u.unmarshal( new
File( "foo.xml" ) );
Marshaller m = jc.createMarshaller();
// assume MyContentHandler instanceof ContentHandler
SAXResult result = new SAXResult( new
MyContentHandler() );
m.marshal( obj, result );
Transparency No. 105
JAXB
Marshalling to a javax.xml.transform.DOMResult
JAXBContext jc =
JAXBContext.newInstance( "com.acme.foo" );
Unmarshaller u = jc.createUnmarshaller();
FooObject obj = (FooObject)u.unmarshal( new
File( "foo.xml" ) );
Marshaller m = jc.createMarshaller();
// assume aNode is a dom node used to store the result
// aNode should accept children. Hence only Document,
Element and DocumentFragment are allowed.
DOMResult result = new DOMResult(aNode);
m.marshal( obj, result );
Transparency No. 106
JAXB
Marshalling to a javax.xml.transform.StreamResult
JAXBContext jc =
JAXBContext.newInstance( "com.acme.foo" );
Unmarshaller u = jc.createUnmarshaller();
FooObject obj = (FooObject)u.unmarshal( new
File( "foo.xml" ) );
Marshaller m = jc.createMarshaller();
StreamResult result = new StreamResult( System.out );
m.marshal( obj, result );
Transparency No. 107
JAXB
JAXB Runtime
Operations
Validation
Transparency No. 1
JAXB
Validation Goals
 Provide seamless access to XML validation in the
Java programming environment
 Make convenient to use in the Java environment
 Relate validation error to instance involved, not file name
and line number
 Process as many errors as possible in one
validation step.
Transparency No. 109
JAXB
Varieties of Validation
 A (simple) type constraint imposes requirements
upon the values that may be given to
 Attributes
 Simple type constraint facets in XML Schema
 A local structural constraint imposes requirements
on every instance of a given element type
 A global structural constraint imposes requirements
on an entire document
Transparency No. 110
JAXB
3 Forms of Validation
 Fail-fast Validation
 Simple runtime type constraint check that can be
performed by Property setter method
 Example:
Bounds check that an integer is between 1 and 10
 On-Demand Validation
 All 3 types of validation performed on the tree
 Applications can call Validator.validate(content-tree)
 Validation during Unmarshalling
Transparency No. 111
JAXB
javax.xml.bind.Validator
 Interface
 Controls the validation of content trees during
runtime
 Responsible for On-demand validation
Transparency No. 112
JAXB
code Example
import javax.xml.bind.*; import generated.packageName.*;
{
JaxbContext jaxbCtx =
JaxbContext.newInstance("generated.packageName");
Unmarshaller um = jaxbCtx.createUnmarshaller();
Trade trade = (Trade)um.unmarshal(<inputStream>);
String symbol = trade.getSymbol();
float price = trace.getPrice();
if (symbol.equals("WIDGETS") && price > 10.00){
trade.setQuantity(30);
}
Validator validator = jaxbCtx.createValidator();
validator.validate(trade);
Marshaller m = jaxbCtx.createMarshaller();
m.marshal(<outputStream>, trade);
Transparency No. 113
JAXB
JAXB Summary,
Resources
Transparency No. 1
JAXB
JAXB Releases
 JAXB 1.0 in March 2003
 JAXB 1.0.1 in JWSDP 1.2 released June 2003
 JAXB 1.0.2 in JWSDP 1.3 released Oct. 2003
 JAXB included in J2EE 1.4 SDK
 JAXB itself is not part of J2EE 1.4 standard
 JAXB 1.0.4 in JWSDP 1.5
Transparency No. 115
JAXB
Future: JAXB 2.0
 Feature List continued
 JAX-RPC and JAXB Alignment
JAX-RPC 2.0 will leverage JAXB 2.0 databinding
 Association of application behavior with schemaderived code
Investigate Design Patterns
Transparency No. 116
JAXB
Future: JAXB 2.0
 Generate J2SE 1.5 Language Extensions
 Builtin Typesafe Enum construct
 More functionality than design pattern
 Generics and Autoboxing
 Typesafety for homogenuous lists
 JSR 175: Java Source Code Annotations
 e.g Customize binding of
existing JavaBean source code to XML Schema
Transparency No. 117
JAXB
Leveraging Generics and Autoboxing
<xs:complexType name=”Student”>
<xs:sequence>
<xs:element name=”grades” type=”xs:int”
maxOccurs=”unbounded”/>
...
Generated by JAXB 1.0
Public interface Student {
/** List of java.lang.Integer */
List getGrades();
...
Generated by JAXB 2.0
Public interface Student {
/** List of Integer. */
List<Integer> getGrades();
...
Transparency No. 118
JAXB
Summary
 A brief introduction to XML Data Binding concepts
and terminology
 Schema-derived Interfaces and Classes
 Default binding and customizable binding
 Unmarshalling, Marshalling, Validation
 XML and Java™ technology go together
 Portable data + portable code
 The Java API for XML Binding (JAXB)
is the glue
Transparency No. 119
JAXB
Resources
 The public JAXB development site.
 http://jaxb.dev.java.net
 Download Java WSDP 1.5 containing JAXB 1.0.4:
 http://java.sun.com/webservices/downloads/webservicespack.ht
ml
 Overview:
 “Java Architecture for XML Binding ” By Scott Fordin, October
2004
 Java Architecture for XML Binding (JAXB) March 2003.
 This article offers a technical summary and examples of how to
work with JAXB.
 Tutorials: The Java Web Services Tutorial
 chapter 1: Binding XML Schema to Java Classes with JAXB
 Chapter 2: Using JAXB
 Specification :
 JSR 31: XML Data Binding Specification (V1.0)
 JSR 222: Java Architecture for XML Binding (JAXB) 2.0
Transparency No. 120
JAXB
Supplementary
Problems with JAXB:
1. Too tightly-coupled between schema and mapped java
classes. Hence


Its hard to bind a schema to existing java classes.
e.g. : map Purchase Order document to Java Jtree object or
java2d graphical objects for rendering.
2. 1-1 and onto mapping b/t schema components and java
classes.



necessary for reverse mapping (marshalling).
but many applications do not need such feature (and the
unnecessary code/complication it induces).
e.g.: in Model/View applications, we may use XML as the global
model and view objects need only part of info the model
contains.
3. JAXB binding is structure preserving in the sense that childparent relation is preserved before and after the mapping.
Transparency No. 121
JAXB
The remedy
 X2O : A system for direct transformation of XML
documents into native objects.
 Ideas:
 1. Define a canonical XML schema ObjectSchema for
java/C#/… objects. 2. Define a runtime utility for
mapping b/t ObjectSchema instances and java
objects.
there exist many such utilities : XMLEncoder/Decoder,
IBM BML, Koala Bean Markup Language (KBML),..
 Define transformation stylesheet/script (using XSLT
or XQuery ) for mapping b/t objectSchema instnces
and specific XML Schema instances.
Transparency No. 122
JAXB
X2O (XML2OBJ)系統架構
文件的輸入
解譯引擎
產生出來的物件
Transparency No. 123
JAXB
JABX20
Tutorials
Transparency No. 1
JAXB
JAXB architecture overview
Transparency No. 125
JAXB
JAXB components
 Schema compiler:
 Binds a source schema to a set of schema-derived
program elements. The binding is described by an
XML-based binding language.
 Schema generator:
 Maps a set of existing program elements to a derived
schema. The mapping is described by program
annotations.
 Binding runtime framework:
 Provides unmarshalling (reading) and marshalling
(writing) operations for accessing, manipulating, and
validating XML content using either schema-derived
or existing program elements.
Transparency No. 126
JAXB
JAXB Building process
Transparency No. 127
JAXB
General steps in the JAXB data binding process
 Generate classes: (from XML Schema/DTD/RelaxNG )
 An XML schema is used as input to the JAXB binding compiler to generate JAXB
classes based on that schema.
 Compile classes:
 All of the generated classes, source files, and application code must be
compiled.
 Unmarshal: (XML document  Java objects)
 XML documents written according to the constraints in the source schema are
unmarshalled by the JAXB binding framework. Note that JAXB also supports
unmarshalling XML data from sources other than files/documents, such as DOM
nodes, string buffers, SAX Sources, and so forth.
 Generate content tree:
 The unmarshalling process generates a content tree of data objects instantiated
from the generated JAXB classes; this content tree represents the structure and
content of the source XML documents.
 Validate (optional):
 The unmarshalling process optionally involves validation of the source XML
documents before generating the content tree. Note that if you modify the
content tree in Step 6, below, you can also use the JAXB Validate operation to
validate the changes before marshalling the content back to an XML document.
 Process content:
 The client application can modify the XML data represented by the Java content
tree by means of interfaces generated by the binding compiler.
 Marshal: (Java Objects  XML Documents)
 The processed content tree is marshalled out to one or more XML output
documents. The content may be validated before marshalling.
Transparency No. 128
JAXB
Representing XML Content
 Java Representation of XML Schema
 JAXB supports the grouping of generated classes in
Java packages.
 A package consists of the following:
 A Java class name that is derived from the XML
element name, or specified by a binding
customization.
 An ObjectFactory class, which is a factory that is
used to return instances of a bound Java class.
Transparency No. 129
JAXB
default XML Schemas –to-Java bindings
 describes the default XML-to-Java bindings used by
JAXB.
 All of these bindings can be overridden on global or
case-by-case levels by means of a custom binding
declaration.
 See the JAXB Specification for complete
information about the default JAXB bindings.
Transparency No. 130
JAXB
Simple Type Definitions
 A schema component using a simple type definition
typically binds to a Java property.
 Since there are different kinds of such schema
components, the following Java property attributes
(common to the schema components) include:
 Base type
 Collection type, if any
 Predicate
 The rest of the Java property attributes are specified
in the schema component using the simple type
definition.
Transparency No. 131
JAXB
JAXB Mapping of XML Schema Built-in Data Types
XML Schema Type
Java Data Type
xs:string
String
xs:integer
BigInteger
xs:int
int
xs:long
long
xs:short
short
xs:decimal
BigDecimal
xs:float
float
xs:double
double
xs:boolean
boolean
xs:byte
byte
xs:QName
javax.xml.namespace.QName
xs:dateTime
datatype.XMLGregorianCalendar
Transparency No. 132
JAXB
JAXB Mapping of XML Schema Built-in Data Types
XML Schema Type
Java Data Type
base64Binary
byte[]
hexBinary
byte[]
unsignedInt
long
unsignedShort
int
unsignedByte
short
time
datatype.XMLGregorianCalendar
date
datatype.XMLGregorianCalendar
g*
datatype.XMLGregorianCalendar
anySimpleType
Object (for element)
anySimpleType
String (for attribute)
duration
datatype.Duration
NOTATION
javax.xml.namespace.QName
Transparency No. 133
JAXB
Transparency No. 134
JAXB
Table F-1 Simple Type Definition Schema Components







Component
{name}?
{target namespace}
{base type definition}
{facets}
{fundamental facets}
{final}
 {variety}
Description
An NCName
absent or a namespace name.
A simple type definition (STD)
A set of constraining facets.
A set of fundamental facets.
A subset of {extension, list,
restriction, union}.
one of { atomic, list, union }
 additional properties depending on {variety}
 atomic {atomic primitive type} a built-in primitive type
def.
 list
{item type definition} a STD
 union {member type definitions } a seq of STDs.
 {annotation}?
An annotation.
Transparency No. 135
JAXB
Table F-3 Complex Type Definition (CTD) Schema Components
 Component
Description
 {name}?
An NCName.
 {target namespace} absent | a namespace name.
 {base type definition} STD | CTD
 {scope}
global |CTD
 {derivation method} extension | restriction
 {final}
⊆ {extension, restriction}.
 {abstract}
boolean
 {attribute uses}
A set of attribute uses.
 {attribute wildcard}? A wildcard.
 {prohibited substitutions}
⊆ {extension, restriction}.
 {annotations}?
A set of annotations.
Transparency No. 136
JAXB
 {content type}
 empty | a simple type definition | (content model, mixed |
element-only ) pair
 {substitution group affiliation}? (x)
 If exists, this element declaration belongs to a
substitution group and this specified element name is the
QName of the substitution head.
Transparency No. 137
JAXB
Table F-4 Element Declaration Schema Components
















Component
{name}
{target namespace}
{type definition}
{scope}?
{value constraint}?
{nillable}
{identity-constraint
definitions}
{substitution group
affiliation}?
{substitution group
exclusions}
{disallowed
substitution}
{abstract}
{annotation}?
Description
NCName
absent | namespace name
STD | CTD
global | CTD
( a value, default |fixed) pair
boolean.
A set of constraint definitions.
A top-level element definition.
⊆{extension, restriction}.
⊆{substitution,extension,restriction}.
boolean.
An annotation
Transparency No. 138
JAXB
Table F-5 Attribute Declaration Schema Components
 Component
 {name}
 {target namespace}
Description
NCName
absent | namespace name
 form=“qualified”, or @attributeFormDefault = “qualified” in
schema, => schema’s {targetNamespace},
 O/W => absent·
 {type definition}
 {scope}?
 {value constraint}?
 {annotation}?
STD
global | CTD
(a value, default | fixed )
An annotation.
Transparency No. 139