jaxb transparency no. 1 jaxb (java api for xml data binding) cheng-chia chen
TRANSCRIPT
JAXB
Transparency No. 1
JAXB(Java API for
XML Data Binding)
Cheng-Chia Chen
JAXB
Transparency No. 2
Agenda
What is and Why JAXB?How to use JAXB?JAXB architectureBinding processCustom bindingRuntime operationsJAXB Roadmap
JAXB
Transparency No. 3
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,…
JAXB
Transparency No. 4
<!--document instance--><?xml version="1.0"?><trade action="buy"> <symbol>ABC</symbol> <quantity>30</quantity></trade>
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"/> <xsd:enumeration value = "sell"/> </xsd:restriction> </xsd:simpleType> </xsd:attribute> </xsd:complexType> <xsd:element name = "trade" type="tradeType"/></xsd:schema>
JAXB
Transparency No. 5
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
JAXB
Transparency No. 1
What is & WhyJAXB?
JAXB
Transparency No. 7
instanceOf instanceOf
What Is JAXB?
A system providing API, tools, and a framework that automate the mapping between XML documents and Java objects
JAXB
Transparency No. 8
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.
JAXB
Transparency No. 9
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 datagetPerson() method as opposed to getAttributes()
In a sense JAXB is high-level language while JAXP/SAX/DOM are assembly language for XML document management
JAXB
Transparency No. 10
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
JAXB
Transparency No. 11
JAXB versus DOM
Both JAXB and DOM create in-memory content treeIn JAXB,
Content tree is specific to a specific source schemaDoes 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
JAXB
Transparency No. 12
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 schema-derived classes
Allows keeping pace with schema evolution
JAXB
Transparency No. 13
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
schemaClean “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
JAXB
Transparency No. 1
How to Use JAXB?
JAXB
Transparency No. 15
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
compilerDevelop 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.
JAXB
Transparency No. 16
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 dataOptionally validate the modifications to the data relative
to the constraints expressed in the XML Schema Marshal in-memory data to a new XML document
JAXB
Transparency No. 17
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.
JAXB
Transparency No. 1
JAXB Architecture
JAXB
Transparency No. 19
JAXB Architecture
source: JAXB User's Guide
JAXB
Transparency No. 20
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 componentBinding Runtime API
Provide runtime XML-enabling operations (unmarshalling, marshalling, validating) on content trees through schema-derived classes
Implementation of javax.xml.bind
JAXB
Transparency No. 21
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
JAXB
Transparency No. 1
Binding Process
JAXB
Transparency No. 23
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
JAXB
Transparency No. 24
The Binding Life Cycle
Schema
XMLDocumen
t
Derived Classes
unmarshal
marshal
validate
compile
Instances of
Objects
follows
JAXB
Transparency No. 1
Binding Process : Design Time Binding
Process
JAXB
Transparency No. 26
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
Schema
BindingSchema
(optional)
BindingCompiler
DerivedClass
Property
Property
package
JAXB
Transparency No. 27
Binding Rules
Default rules Specified in the JAXB spec xjc uses default rules for components of source schema
not mentioned explicitly in custom binding declarationCustom rules (Custom Binding Declaration)
Can be “inline”'ed in XML schema document or Separate custom binding declaration file
JAXB
Transparency No. 1
Binding Process:Default Binding
JAXB
Transparency No. 29
Default XML to Java Binding
Simple Type Definitions
Default Data Type Bindings
Default Binding Rules Summary
JAXB
Transparency No. 31
Default Data Type Binding
● 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.Q
Name
XML Schema Type Java Data Type
JAXB
Transparency No. 32
Default Data Type Binding
● xsd:dataTime● xsd:base64Binary● xsd:hexBinary● xsd:unsignedInt● xsd:unsignedShor
t● xsd:unsignedByte● xsd:time● xsd:date● xsd:anySimpleTy
pe
● java.util.Calendar● byte[]● byte[]● long● int● short● java.util.Date● java.util.Date● java.lang.String
XML Schema Type Java Data Type
JAXB
Transparency No. 1
Binding Process:Default Binding Rules &
Examples
JAXB
Transparency No. 34
Default Binding Rules:Global Element
● global element declaration
● Local element declaration that can be inserted into a general content list
● Attribute
● Java Element interface
● Java Element interface
● Java property
From To
JAXB
Transparency No. 35
Default Binding Example: Global Element
● <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
● <xsd:element name="purchaseOrder" type="PurchaseOrderType"/>
● <xsd:element name="comment" type="xsd:string"/>
● (nothing)
● PurchaseOrder.java
● Comment.java
XML Schema JAXB Binding
JAXB
Transparency No. 36
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>
* <element name= "purchaseOrder"
* type = "{}PurchaseOrderType“ />
* </pre>
*
*/
public interface PurchaseOrder
extends javax.xml.bind.Element, primer.po.PurchaseOrderType { }
JAXB
Transparency No. 37
Default Binding Rules:Named ComplexType
● XML Namespace URI
● (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
From To
JAXB
Transparency No. 38
Default Binding Example: Named ComplexType
<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>
PurchaseOrderType.java
XML Schema JAXB Binding
property name
property type
JAXB
Transparency No. 39
PurchaseOrderType.java
package primer.po;public interface PurchaseOrderType { primer.po.Items getItems(); void setItems(primer.po.Items value);
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);}
Schema type does not
implement Element interface
JAXB
Transparency No. 40
Default Binding Example: ComplexType
XML Schema<xsd:complexType name="USAddress"> <xsd:sequence> <xsd:element name="name"
type="xsd:string"/> <xsd:element name="street"
type="xsd:string"/> <xsd:element name="city"
type="xsd:string"/> <xsd:element name="state"
type="xsd:string"/> <xsd:element name="zip"
type="xsd:decimal"/> </xsd:sequence><xsd:attribute name="country"
type="xsd:NMTOKEN" fixed="US"/></xsd:complexType>
JAXB Binding UMLClass :
name: String
street: String
city: String
state:String
zip: BigDecimal
country: String = “US”
USAddress
JAXB
Transparency No. 41
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);}
JAXB
Transparency No. 42
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 schemaSchema 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]
JAXB
Transparency No. 43
<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;
…}
JAXB
Transparency No. 44
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>
JAXB
Transparency No. 45
The mapped class
public class USState {// Constructorprotected 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 valuepublic 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() { ... }
}
JAXB
Transparency No. 46
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(); …
}
JAXB
Transparency No. 47
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);}Note1. Object is the least common super type of Integer &
String.
JAXB
Transparency No. 48
Default Binding Rules: Attribute
● 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
From To
JAXB
Transparency No. 49
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
JAXB
Transparency No. 50
Example: Default XML Binding
<xsd:complexType name="trade"> <xsd:sequence> <xsd:element name="symbol" type ="xsd:string"/> </sequence> <xsd:attribute name="quantity" type ="xsd:int"/> </xsd:complexType>
public interface Trade {
String getSymbol(); void setSymbol(String);
int getQuantity(); void setQuantity(int);}
XML Schema Derived Class
JAXB
Transparency No. 51
Property Basics
Invoking setX(null) discard property's set valuegetter 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
JAXB
Transparency No. 52
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>
JAXB
Transparency No. 53
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);
}
JAXB
Transparency No. 54
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>
JAXB
Transparency No. 55
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);
}
JAXB
Transparency No. 56
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>
JAXB
Transparency No. 57
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);
};
JAXB
Transparency No. 58
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);
};
JAXB
Transparency No. 59
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>
JAXB
Transparency No. 60
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();};
JAXB
Transparency No. 61
<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);
}
JAXB
Transparency No. 62
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 generatedfrom 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 {};
JAXB
Transparency No. 63
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";...}
JAXB
Transparency No. 1
Custom Binding
JAXB
Transparency No. 65
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 adequateResolve name collisions
Caused by XML Schema symbol spaces and foreign element/attributes references
User provides semantically meaningful and deterministic name resolution
JAXB
Transparency No. 66
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
JAXB
Transparency No. 67
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)
JAXB
Transparency No. 68
Name Collision Resolution
In Package X import javax.xml.bind.Element; public interface Trade {}; // ERROR: collision public interface Trade implements Element {}
<xs:schema xmlns=”X” targetNamespace=”X”> <xs:complexType name=”trade”/> <xs:element name=”trade” type=”trade”/>
In Package X import javax.xml.bind.Element; public interface Trade {}; public interface TradeElement implements Element {}
<xs:schema xmlns=”X” targetNamespace=”X” xmlns:jxb=”http://java.sun.com/xml/ns/jaxb” jxb:version=”1” > <xs:annotation><xs:appinfo> <jxb:schemaBindings> <jxb:nameXmlTransform> <jxb:elementName suffix="Element"/> </jxb:nameXmlTransform> </jxb:schemaBindings> </xs:appinfo></xs:annotation> <xs:complexType name=”trade”/> <xs:element name=”trade” type=”trade”/>
JAXB
Transparency No. 69
External Binding Declaration
Schema(PotentiallyRead-Only)
<jaxb:bindings schemaLocation=”xs:anyURI” node=”XPATH”> <jaxb:anyBindingDeclaration ...> ... </jaxb:anyBindingDeclaration></jaxb:binding>
JAXB
Transparency No. 70
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
JAXB
Transparency No. 71
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)
JAXB
Transparency No. 72
Best Practice Guidelines
In most cases, default binding should be sufficientUse default binding rules whenever possible
Better maintainability when Schema changes
JAXB
Transparency No. 73
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
JAXB
Transparency No. 1
JAXBRuntime Operations
JAXB
Transparency No. 75
JAXB Runtime Operations
Provide the following functionality for schema-derived 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
JAXB
Transparency No. 76
Runtime Framework
packagejavax.xml.bind
Application Code
Interfacesand
Factories
Implementionof
javax.xml.bind
Implementation,
Helper classes
BindingCompiler generate
s
PortabilityLayer
ImplementationValue Add
JAXB
Transparency No. 1
JAXB Runtime Operations
Unmarshalling
JAXB
Transparency No. 78
UnMarshalling Architecture
source: JAXB User's Guide
JAXB
Transparency No. 79
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
JAXB
Transparency No. 80
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
JAXB
Transparency No. 81
javax.xml.bind.Unmarshaller
Java InterfaceGoverns the process of deserializing XML data (XML
document instance) into newly created Java content tree
Optionally validates XML data as it is unmarshalled
JAXB
Transparency No. 82
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" ) );
JAXB
Transparency No. 83
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 );
JAXB
Transparency No. 84
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 );
JAXB
Transparency No. 85
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() ) ) );
JAXB
Transparency No. 86
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 );
JAXB
Transparency No. 87
Unmarshalling from a javax.xml.transform.sax.SAXSource
XMLReader xmlReader = saxParser.getXMLReader();SAXSource source = new SAXSource( xmlReader, new
InputSource( "http://..." ) );
// Setup JAXB to unmarshalJAXBContext 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 validationu.setValidating( false )
// unmarshalObject o = u.unmarshal( source );
JAXB
Transparency No. 88
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
JAXB
Transparency No. 89
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" ) );
JAXB
Transparency No. 1
JAXB Runtime Operations
Creating In-memory Content Programmatically
JAXB
Transparency No. 91
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
JAXB
Transparency No. 92
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() );
JAXB
Transparency No. 1
JAXB Runtime Operations
Processing: Accessing &Modification
JAXB
Transparency No. 94
Processing
AccessModify
JAXB
Transparency No. 95
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" ) );
JAXB
Transparency No. 1
JAXB Runtime OperationsMarshalling
JAXB
Transparency No. 97
Marshalling
source: JAXB User's Guide
JAXB
Transparency No. 98
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
JAXB
Transparency No. 99
javax.xml.bind.Marshaller
InterfaceGoverns the process of serializing Java content
trees back into XML data
JAXB
Transparency No. 100
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 );
JAXB
Transparency No. 101
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() );
JAXB
Transparency No. 102
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 );
JAXB
Transparency No. 103
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 );
JAXB
Transparency No. 104
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 ) );
JAXB
Transparency No. 105
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 );
JAXB
Transparency No. 106
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 );
JAXB
Transparency No. 107
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 );
JAXB
Transparency No. 1
JAXB Runtime OperationsValidation
JAXB
Transparency No. 109
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 numberProcess as many errors as possible in one
validation step.
JAXB
Transparency No. 110
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
JAXB
Transparency No. 111
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 10On-Demand Validation
All 3 types of validation performed on the tree Applications can call Validator.validate(content-tree)
Validation during Unmarshalling
JAXB
Transparency No. 112
javax.xml.bind.Validator
InterfaceControls the validation of content trees during
runtimeResponsible for On-demand validation
JAXB
Transparency No. 113
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);
JAXB
Transparency No. 1
JAXB Summary,Resources
JAXB
Transparency No. 115
JAXB Releases
JAXB 1.0 in March 2003JAXB 1.0.1 in JWSDP 1.2 released June 2003JAXB 1.0.2 in JWSDP 1.3 released Oct. 2003JAXB included in J2EE 1.4 SDK
JAXB itself is not part of J2EE 1.4 standard
JAXB 1.0.4 in JWSDP 1.5
JAXB
Transparency No. 116
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 schema-
derived code Investigate Design Patterns
JAXB
Transparency No. 117
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
JAXB
Transparency No. 118
Leveraging Generics and Autoboxing
<xs:complexType name=”Student”> <xs:sequence> <xs:element name=”grades” type=”xs:int” maxOccurs=”unbounded”/> ...
Public interface Student {
/** List of java.lang.Integer */ List getGrades(); ...
Generated by JAXB 1.0
Public interface Student {
/** List of Integer. */ List<Integer> getGrades(); ...
Generated by JAXB 2.0
JAXB
Transparency No. 119
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
JAXB
Transparency No. 120
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.html 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
JAXB
Transparency No. 121
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 child-parent relation is preserved before and after the mapping.
JAXB
Transparency No. 122
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.
JAXB
Transparency No. 123
X2O (XML2OBJ)系統架構
產生出來的物件
文件的輸入
解譯引擎
JAXB
Transparency No. 1
JABX20 Tutorials
JAXB
Transparency No. 125
JAXB architecture overview
JAXB
Transparency No. 126
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.
JAXB
Transparency No. 127
JAXB Building process
JAXB
Transparency No. 128
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.
JAXB
Transparency No. 129
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.
JAXB
Transparency No. 130
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.
JAXB
Transparency No. 131
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 typeCollection type, if anyPredicateThe rest of the Java property attributes are specified
in the schema component using the simple type definition.
JAXB
Transparency No. 132
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
JAXB
Transparency No. 133
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
JAXB
Transparency No. 134
JAXB
Transparency No. 135
Table F-1 Simple Type Definition Schema Components
Component Description {name}? An NCName {target namespace} absent or a namespace name. {base type definition} A simple type definition (STD) {facets} A set of constraining facets. {fundamental facets} A set of fundamental facets. {final} A subset of {extension, list, restriction, union}. {variety} 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.
JAXB
Transparency No. 136
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.
JAXB
Transparency No. 137
{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.
JAXB
Transparency No. 138
Table F-4 Element Declaration Schema Components
Component Description {name} NCName {target namespace} absent | namespace name {type definition} STD | CTD {scope}? global | CTD {value constraint}? ( a value, default |fixed) pair {nillable} boolean. {identity-constraint definitions} A set of constraint definitions. {substitution group affiliation}? A top-level element definition. {substitution group exclusions} {extension, restriction}.⊆ {disallowed substitution} {substitution,extension,restriction}.⊆ {abstract} boolean. {annotation}? An annotation
JAXB
Transparency No. 139
Table F-5 Attribute Declaration Schema Components
Component Description{name} NCName {target namespace} absent | namespace name
form=“qualified”, or @attributeFormDefault = “qualified” in schema, => schema’s {targetNamespace},
O/W => absent·{type definition} STD{scope}? global | CTD{value constraint}? (a value, default | fixed ){annotation}? An annotation.