Presentation is loading. Please wait.

Presentation is loading. Please wait.

JAXB (Java API for XML Data Binding)

Similar presentations


Presentation on theme: "JAXB (Java API for XML Data Binding)"— Presentation transcript:

1 JAXB (Java API for XML Data Binding)
Cheng-Chia Chen Now let's talk a bit on Web services tools for J2EE.

2 What is and Why JAXB? How to use JAXB? JAXB architecture
Agenda What is and Why JAXB? How to use JAXB? JAXB architecture Binding process Custom binding Runtime operations JAXB Roadmap

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

4 W3C XML Schema Definition for Sample Document Instance
<xsd:schema xmlns:xsd = " <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> <!--document instance--> <?xml version="1.0"?> <trade action="buy"> <symbol>ABC</symbol> <quantity>30</quantity> </trade>

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 No conversions from string to appropriate java datatype. Convert runtime failures to compile time checks.

6 What is & Why JAXB? Now let's talk a bit on Web services tools for J2EE.

7 What Is JAXB? A system providing API, tools, and a framework that automate the mapping between XML documents and Java objects instanceOf

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.

9 An efficient and standard way of mapping between XML and Java code
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

10 Issues with DOM/SAX model
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

11 Both JAXB and DOM create in-memory content tree In 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

12 Easy to use Customizable
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

13 Clean “round-tripping”
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

14 How to Use JAXB? Now let's talk a bit on Web services tools for J2EE.

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

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

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.

18 JAXB Architecture Now let's talk a bit on Web services tools for J2EE.

19 JAXB Architecture source: JAXB User's Guide

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 component Binding Runtime API Provide runtime XML-enabling operations (unmarshalling, marshalling, validating) on content trees through schema-derived classes Implementation of javax.xml.bind

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

22 Binding Process N

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

24 Derived Classes compile Schema validate Instances of follows Objects
The Binding Life Cycle Schema Derived Classes compile Instances of validate follows XML Document Objects unmarshal marshal

25 Binding Process : Design Time Binding Process

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 Binding (optional) Compiler Derived Class Property package

27 Custom rules (Custom Binding Declaration)
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

28 Binding Process: Default Binding

29 Default XML to Java Binding
Simple Type Definitions Default Data Type Bindings Default Binding Rules Summary

30 Simple Type Definitions
Typically binds to Java bean Property Java Property attributes Base type Collection type Predicate

31 Default Data Type Binding
XML Schema Type Java Data 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.QName Just to give you a sense on the differences between Web application which is the second generation distributed computing we saw and web service model. Web application in its current form is typically focused on between an end user and program while under web services model, program to program communication would be much more common form of communication. Also under web application model, things are pretty much in static mode. That is, in order to integrate various applications, you have to statically configure them to talk each other. Under web services model, things could be a lot more dynamic, that is, service users will find service provider and use the services of those providers more dynamically. Also under Web services model, services can be aggregated again in a ad-hoc and dynamic fashion.

32 Default Data Type Binding
XML Schema Type Java Data Type xsd:dataTime xsd:base64Binary xsd:hexBinary xsd:unsignedInt xsd:unsignedShort xsd:unsignedByte xsd:time xsd:date xsd:anySimpleType java.util.Calendar byte[] long int short java.util.Date java.lang.String Just to give you a sense on the differences between Web application which is the second generation distributed computing we saw and web service model. Web application in its current form is typically focused on between an end user and program while under web services model, program to program communication would be much more common form of communication. Also under web application model, things are pretty much in static mode. That is, in order to integrate various applications, you have to statically configure them to talk each other. Under web services model, things could be a lot more dynamic, that is, service users will find service provider and use the services of those providers more dynamically. Also under Web services model, services can be aggregated again in a ad-hoc and dynamic fashion.

33 Binding Process: Default Binding Rules & Examples

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 property From To Just to give you a sense on the differences between Web application which is the second generation distributed computing we saw and web service model. Web application in its current form is typically focused on between an end user and program while under web services model, program to program communication would be much more common form of communication. Also under web application model, things are pretty much in static mode. That is, in order to integrate various applications, you have to statically configure them to talk each other. Under web services model, things could be a lot more dynamic, that is, service users will find service provider and use the services of those providers more dynamically. Also under Web services model, services can be aggregated again in a ad-hoc and dynamic fashion.

35 Default Binding Example: Global Element
XML Schema JAXB Binding <xsd:schema xmlns:xsd=" <xsd:element name="purchaseOrder" type="PurchaseOrderType"/> <xsd:element name="comment" type="xsd:string"/> (nothing) PurchaseOrder.java Comment.java Just to give you a sense on the differences between Web application which is the second generation distributed computing we saw and web service model. Web application in its current form is typically focused on between an end user and program while under web services model, program to program communication would be much more common form of communication. Also under web application model, things are pretty much in static mode. That is, in order to integrate various applications, you have to statically configure them to talk each other. Under web services model, things could be a lot more dynamic, that is, service users will find service provider and use the services of those providers more dynamically. Also under Web services model, services can be aggregated again in a ad-hoc and dynamic fashion.

36 package primer.po;  from target namespace /**
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 { } One binding does not fit all. Play on common phrase “one size fits all”. Bathrobes that are sold with the one size fits all drag on the ground for short people, are too small for large people and generally no one is happy with clothes that states “one size fits all”.

37 Default Binding Rules: Named ComplexType
From To 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 typesafe enum class Just to give you a sense on the differences between Web application which is the second generation distributed computing we saw and web service model. Web application in its current form is typically focused on between an end user and program while under web services model, program to program communication would be much more common form of communication. Also under web application model, things are pretty much in static mode. That is, in order to integrate various applications, you have to statically configure them to talk each other. Under web services model, things could be a lot more dynamic, that is, service users will find service provider and use the services of those providers more dynamically. Also under Web services model, services can be aggregated again in a ad-hoc and dynamic fashion.

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 Just to give you a sense on the differences between Web application which is the second generation distributed computing we saw and web service model. Web application in its current form is typically focused on between an end user and program while under web services model, program to program communication would be much more common form of communication. Also under web application model, things are pretty much in static mode. That is, in order to integrate various applications, you have to statically configure them to talk each other. Under web services model, things could be a lot more dynamic, that is, service users will find service provider and use the services of those providers more dynamically. Also under Web services model, services can be aggregated again in a ad-hoc and dynamic fashion.

39 implement Element interface
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 One binding does not fit all. Play on common phrase “one size fits all”. Bathrobes that are sold with the one size fits all drag on the ground for short people, are too small for large people and generally no one is happy with clothes that states “one size fits all”.

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 Just to give you a sense on the differences between Web application which is the second generation distributed computing we saw and web service model. Web application in its current form is typically focused on between an end user and program while under web services model, program to program communication would be much more common form of communication. Also under web application model, things are pretty much in static mode. That is, in order to integrate various applications, you have to statically configure them to talk each other. Under web services model, things could be a lot more dynamic, that is, service users will find service provider and use the services of those providers more dynamically. Also under Web services model, services can be aggregated again in a ad-hoc and dynamic fashion.

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);} One binding does not fit all. Play on common phrase “one size fits all”. Bathrobes that are sold with the one size fits all drag on the ground for short people, are too small for large people and generally no one is happy with clothes that states “one size fits all”.

42 Each (global) complex type definition (Named ComplexType) mapped to
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]

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; …}

44 Enumeration  type safe enumeration class
<xs:simpleType name="USState"> <xs:restriction base="xs:NCName"> <xs:enumeration value="AK"/> <xs:enumeration value="AL"/> </xs:restriction> </xs:simpleType>

45 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 public static USState fromString(String value){ ... } // Returns String representation of the enumerated value public String toString() { ... } public boolean equals(Object obj) { ... } public int hashCode() { ... } }

46 <xs:simpleType name="xs:USStateList">
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(); … }

47 <xs:complexType name="CTType">
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.

48 Default Binding Rules: Attribute
From To 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 Just to give you a sense on the differences between Web application which is the second generation distributed computing we saw and web service model. Web application in its current form is typically focused on between an end user and program while under web services model, program to program communication would be much more common form of communication. Also under web application model, things are pretty much in static mode. That is, in order to integrate various applications, you have to statically configure them to talk each other. Under web services model, things could be a lot more dynamic, that is, service users will find service provider and use the services of those providers more dynamically. Also under Web services model, services can be aggregated again in a ad-hoc and dynamic fashion.

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

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

51 Invoking setX(null) discard property's set value getter method returns
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

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:element name="state" type="xs:string"/> <xs:element name="zip" type="xs:integer"/> </xs:extension> </xs:complexContent>

53 public interface Address { String getName(); void setName(String);
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);

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>

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); }

56 <xs:group name="AModelGroup"> <xs:choice>
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>

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); };

58 /** A valid general content property that contains
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); };

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:group ref="AModelGroup"/> <xs:element name="C" type="xs:float"/> </xs:complexType>

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();

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); }

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 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 {};

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"; ... }

64 Custom Binding Now let's talk a bit on Web services tools for J2EE.

65 Resolve name collisions
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 One binding does not fit all. Play on common phrase “one size fits all”. Bathrobes that are sold with the one size fits all drag on the ground for short people, are too small for large people and generally no one is happy with clothes that states “one size fits all”.

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

67 Customization Mechanism
One standard customization language xmlns: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)

68 Name Collision Resolution
In Package X import javax.xml.bind.Element; public interface Trade {}; public interface TradeElement implements Element {} <xs:schema xmlns=”X” targetNamespace=”X” xmlns:jxb=” 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”/> <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 {}; // ERROR: collision public interface Trade implements Element {}

69 External Binding Declaration
Schema (Potentially Read-Only) <jaxb:bindings schemaLocation=”xs:anyURI” node=”XPATH”> <jaxb:anyBindingDeclaration ...> ... </jaxb:anyBindingDeclaration> </jaxb:binding>

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

71 <jaxb:globalBindings> - Applies to All XML namespaces
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)

72 Best Practice Guidelines
In most cases, default binding should be sufficient Use default binding rules whenever possible Better maintainability when Schema changes

73 JAXB v1.0.1 RI Implementation
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

74 JAXB Runtime Operations
Now let's talk a bit on Web services tools for J2EE.

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

76 Interfaces and Factories
Runtime Framework Application Code Portability Layer Interfaces and Factories package javax.xml.bind Binding Compiler Implementation Value Add generates Implemention of javax.xml.bind Implementation, Helper classes

77 JAXB Runtime Operations Unmarshalling

78 UnMarshalling Architecture
source: JAXB User's Guide

79 Sources for unMarshalling can be
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

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

81 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

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" ) );

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

84 Unmarshalling from a URL
JAXBContext jc = JAXBContext.newInstance( "com.acme.foo" ); Unmarshaller u = jc.createUnmarshaller(); URL url = new URL( " ); Object o = u.unmarshal( url );

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() ) ) );

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

87 Unmarshalling from a javax.xml.transform.sax.SAXSource
XMLReader xmlReader = saxParser.getXMLReader(); SAXSource source = new SAXSource( xmlReader, new InputSource( " ) ); // 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 );

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

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" ) );

90 JAXB Runtime Operations Creating In-memory Content Programmatically

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

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() );

93 JAXB Runtime Operations Processing: Accessing & Modification

94 Processing Access Modify

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" ) );

96 JAXB Runtime Operations Marshalling

97 Marshalling source: JAXB User's Guide

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

99 javax.xml.bind.Marshaller
Interface Governs the process of serializing Java content trees back into XML data

100 JAXBContext jc = JAXBContext.newInstance( "com.acme.foo" );
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 );

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() );

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

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

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

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

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

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

108 JAXB Runtime Operations Validation

109 Make convenient to use in the Java environment
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.

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

111 Validation during Unmarshalling
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

112 javax.xml.bind.Validator
Interface Controls the validation of content trees during runtime Responsible for On-demand validation

113 import javax.xml.bind.*; import generated.packageName.*; {
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);

114 JAXB Summary, Resources
Now let's talk a bit on Web services tools for J2EE.

115 JAXB 1.0.1 in JWSDP 1.2 released June 2003
JAXB Releases JAXB 1.0 in March 2003 JAXB in JWSDP 1.2 released June 2003 JAXB 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 in JWSDP 1.5

116 Feature List continued
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

117 Generate J2SE 1.5 Language Extensions Builtin Typesafe Enum construct
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

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

119 A brief introduction to XML Data Binding concepts and terminology
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

120 The public JAXB development site.
Resources The public JAXB development site. Download Java WSDP 1.5 containing JAXB 1.0.4: 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

121 1. Too tightly-coupled between schema and mapped java classes. Hence
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. 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.

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.

123 X2O (XML2OBJ)系統架構 文件的輸入 解譯引擎 產生出來的物件

124 JABX20 Tutorials

125 JAXB architecture overview

126 Binding runtime framework:
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.

127 JAXB Building process

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.

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.

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.

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 type Collection type, if any Predicate The rest of the Java property attributes are specified in the schema component using the simple type definition.

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

133 JAXB Mapping of XML Schema Built-in Data Types
XML Schema Type Java Data Type base64Binary byte[] hexBinary unsignedInt long unsignedShort int unsignedByte short time datatype.XMLGregorianCalendar date g* anySimpleType Object (for element) String (for attribute) duration datatype.Duration NOTATION javax.xml.namespace.QName

134

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.

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.

137 {substitution group affiliation}? (x)
{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.

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. exclusions} ⊆{extension, restriction}. {disallowed substitution} ⊆{substitution,extension,restriction}. {abstract} boolean. {annotation}? An annotation {substitution group exclusions} specifies all elements whose types are derived by extension or restriction as specifies are prohibited from attending the substitution group headed by this element. {disallowed substitution} specifies the elements whose types are derived by restriction or extension from the type of this element or are member of the substitution group as given in this property are not allowed to replace this element in all document instances. An abstract element cannot appear in document instance; it must be replaced by substitution group member element. Comparison: An element with empty disallowed substitution property may has its actual content filled in by one conformed to some of its subtypes (via xsi:type ). However, in such case, it is the content but not the name of the element that is changed.

139 Table F-5 Attribute Declaration Schema Components
Component Description {name} NCName {target namespace} absent | namespace name form=“qualified”, = “qualified” in schema, => schema’s {targetNamespace}, O/W => absent· {type definition} STD {scope}? global | CTD {value constraint}? (a value, default | fixed ) {annotation}? An annotation.


Download ppt "JAXB (Java API for XML Data Binding)"

Similar presentations


Ads by Google