SlideShare une entreprise Scribd logo
1  sur  52
JAXB - Java Architecture for XML
            Binding


                 ●
                     Preface
                 ●
                     Architecture
                 ●
                     Generate JavaBeans
                 ●
                     Generate XML Schema
                 ●
                     Runtime transformation



Heiko Scherrer
JAXB - Preface

●
    JAXB – Java Architecture for XML Binding
●
    Another XML-API for Java ?
    ●
        No! Different to JAXP, StAX, SAX or DOM
●
    Binding not Parsing!
●
    JAXB driven by the JCP
●
    RI is Java WSDP (Web Service Developer
    Packages)
●
    Validation within binding process (optional)

Heiko Scherrer
JAXB - Goals


●
    Simplicity
    JAXB simplifies the handling with XML and
    provides data with POJOs
●
    Abstraction
    Prevents from low-level file parsing and
    processing
●
    Standardization
    API is part of JavaSE6 javax.xml.bind

Heiko Scherrer
JAXB – History (JAXB 1.0)



●
    JAXB 1.0 → JSR-31 (2003)
    ●
        Only one-way binding from XML-Schema->Java
        classes
    ●
        Generated code was not completely portable
    ●
        W3C schema not entirely supported
    ●
        Already support for validation (strict!)



Heiko Scherrer
JAXB – History (JAXB 2.0)

●
    JAXB 2.0 → JSR-222 (2006)
    ●
        Uses Java5 core concepts: Annotations,
        Generics, Enumerations
    ●
        Fundamental changes to simplify usability
    ●
        It's a real binding framework not a one-way
        mapper only
    ●
        No dependencies to implementation classes
    ●
        Full support of W3C XML Schema 1.0
    ●
        Major changes in validation process: more
        efficient, standardized (JAXP) and flexible
Heiko Scherrer
JAXB – History (JAXB 2.1)



●
    JAXB 2.1 → JSR-222 (2006)
    ●
        Only a small maintenance release
    ●
        One change to mention: Separate compilation
        feature. To extend a generated schema and
        reuse originally generated class files
    ●
        Integration in JDK6 is a manual step!
    ●
        Not worth to update



Heiko Scherrer
JAXB – History (JAXB 2.2)


●
    JAXB 2.2 → JSR-222 (Q4/2009)
    ●
        Small maintenance release
    ●
        Simplifies marshaling/unmarshaling
    ●
        Simplifies globalBindings and schemaBindings
    ●
        Other minor improvements and bug fixes
    ●
        JDK6 upgrade is a manual step, version 2.0 is
        pinned!



Heiko Scherrer
JAXB – Affinities (I)

●   DOM API: Document Object Model (W3C)
    ●   XML is read/writeable
    ●   Object tree represents the XML file
    ●   Memory consumptive
    ●   Random data access
    ●   See also JDOM, dom4j and Jaxen
●   SAX API: Simple API for XML
    ●   XML only readable
    ●   Sequential event-driven document scanner
    ●   Fast file parsing (compared to DOM)
    ●   Integrated in JavaSE1.4


Heiko Scherrer
JAXB – Affinities (II)

●
    StAX: Streaming API for XML
    ●
        XML is read/writeable
    ●
        Serial document scanner:
         –   Parser is calling handler directly
         –   Parser and handler are decoupled with events
    ●
        Included in JavaSE6 (avail for 1.4/5)
●
    JAXP: Java API for XML Processing
    ●
        Abstracts DOM, SAX, StaX, Xpath and XSLT
    ●
        Integrated since JavaSE1.4

Heiko Scherrer
JAXB – XML API Classification


                              Data Binding Frameworks
                                                                          Client application
                    Castor                         JAXB                   uses Java objects
                  Castor Impl
                                                Java WSDP


    Abstraction
                                                                          XML
                                         JAXP
    Layer


                   DOM            JDOM           SAX           StAX       Client application
                                                                           has to deal with
                                                                             objects that
                             Apache        Sun                             represents XML
                                                            Codehaus RI
                             Xerces      Crimson
                              Parser API and Implementations
                                                                          XML
Heiko Scherrer
JAXB Java Architecture for XML
           Binding


                 ●
                     Preface
                 ●
                     Architecture
                 ●
                     Generate JavaBeans
                 ●
                     Generate XML Schema
                 ●
                     Runtime transformation



Heiko Scherrer
JAXB – Architecture

 @ compiletime:
  ●
      Use JAXB Schema compiler to generate
      annotated Java classes from XML schema or
      DTD
       contract-driven approach (WSDL)
  ●
      Or use JAXB schema generator to generate a
      XML Schema from annotated Java classes
       model-driven approach (domain model)


Heiko Scherrer
JAXB – Architecture


       Write or generate
                                              Write or generate
       the XML Schema,
                                                Java classes
         the “contract”

                               Compile Time
             XML Schema with                  POJO classes with
                 binding                      JAXB annotations
               declarations



                 XML

                          Use schema compiler
                          or schema generator



Heiko Scherrer
JAXB – Architecture

 @ Runtime:
  ●
      XML Schema instance (XML file) is
      transformed into a Java object model
      instance – or backwards
  ●
      XML files don't have to be valid
  ●
      Binding and runtime validation is done
      using JAXB binding framework



Heiko Scherrer
JAXB – Architecture


                             Compile time                          Generation during
        XML Schema                            Java classes
                                                                  compile time
                                                                   Transformation
           XML                 Generation                         during runtime
                                                                     Marshalling
                                                  instantiation     Transformation from Java
             instantiation




                               Runtime
                                                                    to XML data
                                                                    Unmarshalling
           XML                Marshalling /
                             Unmarshalling
                                                                   Transformation from XML
                                                                   data to Java objects



Heiko Scherrer
JAXB Java Architecture for XML
           Binding


                 ●
                     Preface
                 ●
                     Architecture
                 ●
                     Generate JavaBeans
                 ●
                     Generate XML Schema
                 ●
                     Runtime transformation



Heiko Scherrer
JAXB – Generate JavaBeans


●
    Schema compiler (xjc)
    ●   command line tool (bin/xjc.sh)
    ●
        ANT task
    ●
        Maven plugin
●
    Generated resources: JavaBeans, factory
    class (ObjectFactory), package-info
●   Example, see ./30a-JAXB_example


Heiko Scherrer
JAXB – Code Generation:Example


            Java Package:
       org.openwms.examples




                                XJC



          targetNamespace=
       ”examples.openwms.org”




Heiko Scherrer
JAXB – Class Generation:Overview

●   Generated classes follow the JavaBeans specification
●   Default binding configuration
     “Convention over Configuration”
●   Custom binding configuration
     Override the default generation rules
●   A binding configuration contains 1..* binding declarations
●   Expressed with XML
    ●   Inline configuration: within same XML Schema
    ●   External configuration: separate XML file




Heiko Scherrer
JAXB – Assignment / Customization

●
    Default binding configuration
    ●
        Namespace is mapped to Java package
    ●
        Datatype is mapped to Java class
    ●
        Element is mapped to Class property
●
    Reasons to customize binding configuration
    ●
        Override standard datatype conversion
    ●
        Customize standard name conversion
    ●
        Add JavaDoc comments

Heiko Scherrer
JAXB – Inline declaration


●   annotation/appinfo
    are defined
    elements of
    XMLSchema
●
    XJC recognizes
    appinfo element
●
    Bindings in different
    scopes

Heiko Scherrer
JAXB – External declaration



●
    Separate XML file
●   Use xsd:import to
    import schemas
●
    Reference the base
    schema:
    schemaLocation



Heiko Scherrer
JAXB – Binding declaration scopes

●
    Possible scopes for binding declarations:
    ●   <globalBindings>:Global declarations are valid
        for all schemes, even included and imported ones
    ●   <schemaBindings>:All elements in the current
        schema
    ●   <class>:Valid for global type and element
        definitions
    ●   <property>:Valid for sub-elements of a type or
        element


Heiko Scherrer
JAXB – Override declarations




●
    Inner defined binding configuration override
    the ones defined in outer scope (e.g.
    declaration in property scope overrides
    property in class, schema or global scope)




Heiko Scherrer
JAXB – Popular binding declarations
          <jaxb:collectionType>
●
    <jaxb:collectionType>:Map an implementation class to
    Collections
●
    Binding declaration (example):
    <jaxb:globalBindings
           collectionType=”java.util.Vector”>
●
    XML Schema element definition
    <xs:element name=”locations” minOccurs=”0”
        maxOccurs=”unbounded” type=”xs:string”/>
●
    Results in:
    protected List<String> = new Vector<String>();




Heiko Scherrer
JAXB – Popular binding declarations
         <jaxb:package>

●   <jaxb:package>:Define the name of the
    Java package
●
    Binding declaration (example):
    <jaxb:schemaBindings>
       <jaxb:package name=”org.openwms”/>
    </jaxb:schemaBindings>
●
    All elements within this schema are bound
    to classes in the named package

Heiko Scherrer
JAXB – Popular binding declarations
          <jaxb:class>

●   <jaxb:class>:Override the default
    classname for a given element
●
    Declare binding for a chosen element. Use
    XPath to identify the node:
    <jaxb:bindings
    node=”//xsd:complexType[@name='location']”>
            <jaxb:class name=”WMSLocation”/>
    </jaxb:bindings>
●   The name of the generated class is WMSLocation


Heiko Scherrer
JAXB – Popular binding declarations
         <jaxb:property>

●   <jaxb:property>:Valid for sub-elements of
    a type or element
●
    Used to customize generated Java class
    properties
●
    Declare binding for a chosen element. Use
    XPath to identify the node:
    <jaxb:bindings
    node=”//xsd:element[@name='id']”>
            <jaxb:property name=”identifier”/>
    </jaxb:bindings>

Heiko Scherrer
JAXB – Popular binding declarations
         <jaxb:javadoc>

●   <jaxb:javadoc>:Document generated
    packages, classes and methods
●
    Document the source of data! (XML)
●   Used as child of jaxb:package/jaxb:class/
    jaxb:property
●
    Use <![CDATA[..]]> inside to document
    <jaxb:class name=”WMSLocation”>
       <![CDATA[class documentation]]>
    </jaxb:class>

Heiko Scherrer
JAXB Java Architecture for XML
           Binding




                 LAB


Heiko Scherrer
JAXB Java Architecture for XML
           Binding


                 ●
                     Preface
                 ●
                     Architecture
                 ●
                     Generate JavaBeans
                 ●
                     Generate XML Schema
                 ●
                     Runtime transformation



Heiko Scherrer
JAXB – XML Schema Generation


●
    Schema generator (schemagen)
    ●   command line tool (bin/schemagen.sh)
    ●
        ANT task
    ●
        Maven plugin
●
    Input data: Java source or class files
●
    Generated resources: XML Schema file
●   Example, see ./30a-JAXB_example

Heiko Scherrer
JAXB – XML Schema Generation

                   Simplest case! POJO
                   without JAXB related
                       annotations




       schemagen




Heiko Scherrer
JAXB – XML Schema Generation


●
    Java classes must follow the JavaBeans
    specification
●
    Don't has to be annotated with JAXB
    annotations
     Convention over Configuration
●   Example, see ./30a-JAXB_example
●   Lots of javax.xml.bind.annotation.* to
    customize schema generation!

Heiko Scherrer
JAXB – XML Schema Generation
      Define namespace

●   Standard package-info.java documents
    package content and defines XML
    namespace:


●
    Use FQCN and do not import class type!
●
    Can be overridden on class-level:



Heiko Scherrer
JAXB – XML Schema Generation
       @XmlRootElement



●
    Annotated classes can be used as root
    elements in XML Schema instances and
    marshalled directly (see Transformation)
●
    An XML Schema element is generated, too
●
    On type level: classes and enumerations



Heiko Scherrer
JAXB – XML Schema Generation
            @XmlAccessType
●
    Defined which instance variables or properties to
    use for schema generation
●
    Possible values:
    ●   NONE: No variables are bound to the schema
    ●   PROPERTY: All JavaBeans properties are used
    ●   FIELD: All instance variables are bound to the schema
    ●   PUBLIC_MEMBER: All instance variables and properties
        are used
●
    Package or class level annotation


Heiko Scherrer
JAXB – XML Schema Generation
             @XmlElement
●   Customize mapping from properties/variables to
    elements (similar JPA @Column)
●   Possible parameters:
    ●   name: Name of the XML element
    ●   required: true if the element must be set, else false
    ●   defaultValue: Default value when no value set during
        marshalling
    ●   PUBLIC_MEMBER: All instance variables and properties are
        used




Heiko Scherrer
JAXB – XML Schema Generation
        @XmlAttribute



●
    Annotated properties occur as attributes of
    an element
●
    Possible parameters:
    ●   name: Name of the XML attribute
    ●   required: true if the attribute must be set, else
        false



Heiko Scherrer
JAXB – XML Schema Generation
          @XmlValue




●
    Variable is used as plain-text content of the
    element
●
    If used no other sub-elements are permitted




Heiko Scherrer
JAXB – XML Schema Generation
        @XmlTransient



●
    Binding is omitted
●   Comparable to JPA's @Transient and Java's
    transient
●
    If used no other sub-elements are permitted
●
    Allowed on field and method level



Heiko Scherrer
JAXB Java Architecture for XML
           Binding




                 LAB


Heiko Scherrer
JAXB Java Architecture for XML
           Binding


                 ●
                     Preface
                 ●
                     Architecture
                 ●
                     Generate JavaBeans
                 ●
                     Generate XML Schema
                 ●
                     Runtime transformation



Heiko Scherrer
JAXB – Runtime transformation

●
    Reading and writing XML files with JAXB
●   JAXBContext: All you need to access data
    binding (threadsafe but expensive!)
●
    Binding Java packages with:
    JAXBContext.newInstance
                 (“package1:package2:...”)
●
    Binding Java classes with:
    JAXBContext.newInstance
                 (“class1:class2:...”)

Heiko Scherrer
JAXB – Runtime transformation -
            Unmarshalling
●   Unmarshalling: Transforming a XML file into a Java
    object tree instance
●   Create an Unmarshaller from the context object:
    Unmarshaller u = ctx.createUnmarshaller();
●   Validation against XML Schema or with
    ValidationHandler (see Validation)
●
    Unmarshal:
    <Root> root = u.unmarshal(<Resource>);




Heiko Scherrer
JAXB – Runtime transformation -
        Unmarshalling
●
    Method parameters of unmarshal(..):
    ●   java.io.File
    ●   java.net.URL
    ●   java.io.InputStream
    ●   java.xml.stream.XMLStreamReader
    ●   java.xml.stream.XMLEventReader
    ●   java.xml.transform.Source
    ●   org.w3c.dom.Node
    ●   org.xml.sax.InputSource

Heiko Scherrer
JAXB – Runtime transformation -
        Unmarshalling
●
    Return value of unmarshal(..):
    ●   java.lang.Object
●
    Cast into Java object that represents the XML
    root element:
    Location loc =
          (Location) u.unmarshal(
                new File(“locations.xml”));
●
    Simplest case: Unmarshal the whole XML file;
    map between XML root element and Java class
    @XMLRootElement

Heiko Scherrer
JAXB – Runtime transformation -
         Marshalling
●
    Marshalling: Transforming a Java object tree
    instance into a XML file
●
    Create an Marshaller from the context object:
    Marshaller m = ctx.createMarshaller();
●
    Validation against XML Schema or with
    ValidationHandler (see Validation)
●
    Marshal:
    m.marshal(obj, <Resource>);



Heiko Scherrer
JAXB – Runtime transformation -
             Marshalling
●
    Method parameters of marshal(obj, res):
     ●   obj: POJO annotated with @XMLRootElement
     ●   res: java.io.OutputStream
     ●   res: java.io.Writer
     ●   res: java.io.File
     ●   res: org.w3c.dom.Node
     ●   res: org.xml.sax.ContentHandler
     ●   res: java.xml.stream.XMLStreamReader
     ●   res: java.xml.stream.XMLEventReader

Heiko Scherrer
JAXB – Runtime transformation -
         Marshalling



●
    Write directly into XML file:
    m.marshal(locations,
                 new File(“locations.xml”));
●
    Write to System.out:
    m.marshal(locations,
                System.out);



Heiko Scherrer
JAXB Java Architecture for XML
           Binding




                 LAB


Heiko Scherrer
JAXB Java Architecture for XML
           Binding




       Next time:
       Validation
       Customizing Marshalling & Unmarshalling




Heiko Scherrer

Contenu connexe

Tendances

Real World Experience With Oracle Xml Database 11g An Oracle Ace’s Perspectiv...
Real World Experience With Oracle Xml Database 11g An Oracle Ace’s Perspectiv...Real World Experience With Oracle Xml Database 11g An Oracle Ace’s Perspectiv...
Real World Experience With Oracle Xml Database 11g An Oracle Ace’s Perspectiv...Marco Gralike
 
Advance java session 5
Advance java session 5Advance java session 5
Advance java session 5Smita B Kumar
 
Session 38 - Core Java (New Features) - Part 1
Session 38 - Core Java (New Features) - Part 1Session 38 - Core Java (New Features) - Part 1
Session 38 - Core Java (New Features) - Part 1PawanMM
 
Jdbc presentation
Jdbc presentationJdbc presentation
Jdbc presentationnrjoshiee
 
JDBC Basics (In 20 Minutes Flat)
JDBC Basics (In 20 Minutes Flat)JDBC Basics (In 20 Minutes Flat)
JDBC Basics (In 20 Minutes Flat)Craig Dickson
 
SQL, Embedded SQL, Dynamic SQL and SQLJ
SQL, Embedded SQL, Dynamic SQL and SQLJSQL, Embedded SQL, Dynamic SQL and SQLJ
SQL, Embedded SQL, Dynamic SQL and SQLJDharita Chokshi
 
Jdom how it works & how it opened the java process
Jdom how it works & how it opened the java processJdom how it works & how it opened the java process
Jdom how it works & how it opened the java processHicham QAISSI
 
Java Database Connectivity (JDBC)
Java Database Connectivity (JDBC)Java Database Connectivity (JDBC)
Java Database Connectivity (JDBC)Pooja Talreja
 
Database Programming Techniques
Database Programming TechniquesDatabase Programming Techniques
Database Programming TechniquesRaji Ghawi
 
Java ain't scary - introducing Java to PL/SQL Developers
Java ain't scary - introducing Java to PL/SQL DevelopersJava ain't scary - introducing Java to PL/SQL Developers
Java ain't scary - introducing Java to PL/SQL DevelopersLucas Jellema
 

Tendances (20)

Real World Experience With Oracle Xml Database 11g An Oracle Ace’s Perspectiv...
Real World Experience With Oracle Xml Database 11g An Oracle Ace’s Perspectiv...Real World Experience With Oracle Xml Database 11g An Oracle Ace’s Perspectiv...
Real World Experience With Oracle Xml Database 11g An Oracle Ace’s Perspectiv...
 
Advance java session 5
Advance java session 5Advance java session 5
Advance java session 5
 
Session 38 - Core Java (New Features) - Part 1
Session 38 - Core Java (New Features) - Part 1Session 38 - Core Java (New Features) - Part 1
Session 38 - Core Java (New Features) - Part 1
 
JDBC – Java Database Connectivity
JDBC – Java Database ConnectivityJDBC – Java Database Connectivity
JDBC – Java Database Connectivity
 
Database Access With JDBC
Database Access With JDBCDatabase Access With JDBC
Database Access With JDBC
 
java jdbc connection
java jdbc connectionjava jdbc connection
java jdbc connection
 
Java XML Parsing
Java XML ParsingJava XML Parsing
Java XML Parsing
 
Jdbc ppt
Jdbc pptJdbc ppt
Jdbc ppt
 
Jdbc presentation
Jdbc presentationJdbc presentation
Jdbc presentation
 
55 New Features in Java 7
55 New Features in Java 755 New Features in Java 7
55 New Features in Java 7
 
3 jdbc api
3 jdbc api3 jdbc api
3 jdbc api
 
JDBC ppt
JDBC pptJDBC ppt
JDBC ppt
 
JDBC Basics (In 20 Minutes Flat)
JDBC Basics (In 20 Minutes Flat)JDBC Basics (In 20 Minutes Flat)
JDBC Basics (In 20 Minutes Flat)
 
SQL, Embedded SQL, Dynamic SQL and SQLJ
SQL, Embedded SQL, Dynamic SQL and SQLJSQL, Embedded SQL, Dynamic SQL and SQLJ
SQL, Embedded SQL, Dynamic SQL and SQLJ
 
Jdom how it works & how it opened the java process
Jdom how it works & how it opened the java processJdom how it works & how it opened the java process
Jdom how it works & how it opened the java process
 
Java Database Connectivity (JDBC)
Java Database Connectivity (JDBC)Java Database Connectivity (JDBC)
Java Database Connectivity (JDBC)
 
Database Programming Techniques
Database Programming TechniquesDatabase Programming Techniques
Database Programming Techniques
 
Jdbc
JdbcJdbc
Jdbc
 
4 jdbc step1
4 jdbc step14 jdbc step1
4 jdbc step1
 
Java ain't scary - introducing Java to PL/SQL Developers
Java ain't scary - introducing Java to PL/SQL DevelopersJava ain't scary - introducing Java to PL/SQL Developers
Java ain't scary - introducing Java to PL/SQL Developers
 

Similaire à JSR-222 Java Architecture for XML Binding

Java architecture for xml binding
Java architecture for xml bindingJava architecture for xml binding
Java architecture for xml bindingKiran Gajbhiye
 
Iasi code camp 12 october 2013 jax-rs-jee-ecosystem - catalin mihalache
Iasi code camp 12 october 2013   jax-rs-jee-ecosystem - catalin mihalacheIasi code camp 12 october 2013   jax-rs-jee-ecosystem - catalin mihalache
Iasi code camp 12 october 2013 jax-rs-jee-ecosystem - catalin mihalacheCodecamp Romania
 
Expertezed 2012 Webcast - XML DB Use Cases
Expertezed 2012 Webcast - XML DB Use CasesExpertezed 2012 Webcast - XML DB Use Cases
Expertezed 2012 Webcast - XML DB Use CasesMarco Gralike
 
Scotas - Oracle Open World Sao Pablo
Scotas - Oracle Open World Sao PabloScotas - Oracle Open World Sao Pablo
Scotas - Oracle Open World Sao PabloJulian Arocena
 
Soa 29 jaxb data binding
Soa 29 jaxb data bindingSoa 29 jaxb data binding
Soa 29 jaxb data bindingVaibhav Khanna
 
BGOUG 2012 - Design concepts for xml applications that will perform
BGOUG 2012 - Design concepts for xml applications that will performBGOUG 2012 - Design concepts for xml applications that will perform
BGOUG 2012 - Design concepts for xml applications that will performMarco Gralike
 
Java EE 6 workshop at Dallas Tech Fest 2011
Java EE 6 workshop at Dallas Tech Fest 2011Java EE 6 workshop at Dallas Tech Fest 2011
Java EE 6 workshop at Dallas Tech Fest 2011Arun Gupta
 
Java Web Services [4/5]: Java API for XML Web Services
Java Web Services [4/5]: Java API for XML Web ServicesJava Web Services [4/5]: Java API for XML Web Services
Java Web Services [4/5]: Java API for XML Web ServicesIMC Institute
 
Introduction To J Boss Seam
Introduction To J Boss SeamIntroduction To J Boss Seam
Introduction To J Boss Seamashishkulkarni
 
Content Storage With Apache Jackrabbit
Content Storage With Apache JackrabbitContent Storage With Apache Jackrabbit
Content Storage With Apache JackrabbitJukka Zitting
 
The Java Content Repository
The Java Content RepositoryThe Java Content Repository
The Java Content Repositorynobby
 
Enterprise Java Web Application Frameworks Sample Stack Implementation
Enterprise Java Web Application Frameworks   Sample Stack ImplementationEnterprise Java Web Application Frameworks   Sample Stack Implementation
Enterprise Java Web Application Frameworks Sample Stack ImplementationMert Çalışkan
 
Soa 12 jax ws-xml Java API for web services
Soa 12 jax ws-xml Java API for web servicesSoa 12 jax ws-xml Java API for web services
Soa 12 jax ws-xml Java API for web servicesVaibhav Khanna
 
Rollin onj Rubyv3
Rollin onj Rubyv3Rollin onj Rubyv3
Rollin onj Rubyv3Oracle
 
An Intense Overview of the React Ecosystem
An Intense Overview of the React EcosystemAn Intense Overview of the React Ecosystem
An Intense Overview of the React EcosystemRami Sayar
 
Make easier Integration of your services with Fuse Solutions - RedHat 2013
Make easier Integration of your services with Fuse Solutions - RedHat 2013Make easier Integration of your services with Fuse Solutions - RedHat 2013
Make easier Integration of your services with Fuse Solutions - RedHat 2013Charles Moulliard
 
Hotsos 2013 - Creating Structure in Unstructured Data
Hotsos 2013 - Creating Structure in Unstructured DataHotsos 2013 - Creating Structure in Unstructured Data
Hotsos 2013 - Creating Structure in Unstructured DataMarco Gralike
 

Similaire à JSR-222 Java Architecture for XML Binding (20)

Java architecture for xml binding
Java architecture for xml bindingJava architecture for xml binding
Java architecture for xml binding
 
Iasi code camp 12 october 2013 jax-rs-jee-ecosystem - catalin mihalache
Iasi code camp 12 october 2013   jax-rs-jee-ecosystem - catalin mihalacheIasi code camp 12 october 2013   jax-rs-jee-ecosystem - catalin mihalache
Iasi code camp 12 october 2013 jax-rs-jee-ecosystem - catalin mihalache
 
Expertezed 2012 Webcast - XML DB Use Cases
Expertezed 2012 Webcast - XML DB Use CasesExpertezed 2012 Webcast - XML DB Use Cases
Expertezed 2012 Webcast - XML DB Use Cases
 
Scotas - Oracle Open World Sao Pablo
Scotas - Oracle Open World Sao PabloScotas - Oracle Open World Sao Pablo
Scotas - Oracle Open World Sao Pablo
 
Soa 29 jaxb data binding
Soa 29 jaxb data bindingSoa 29 jaxb data binding
Soa 29 jaxb data binding
 
BGOUG 2012 - Design concepts for xml applications that will perform
BGOUG 2012 - Design concepts for xml applications that will performBGOUG 2012 - Design concepts for xml applications that will perform
BGOUG 2012 - Design concepts for xml applications that will perform
 
Java EE 6 workshop at Dallas Tech Fest 2011
Java EE 6 workshop at Dallas Tech Fest 2011Java EE 6 workshop at Dallas Tech Fest 2011
Java EE 6 workshop at Dallas Tech Fest 2011
 
Java Web Services [4/5]: Java API for XML Web Services
Java Web Services [4/5]: Java API for XML Web ServicesJava Web Services [4/5]: Java API for XML Web Services
Java Web Services [4/5]: Java API for XML Web Services
 
Karaf ee-apachecon eu-2012
Karaf ee-apachecon eu-2012Karaf ee-apachecon eu-2012
Karaf ee-apachecon eu-2012
 
Introduction To J Boss Seam
Introduction To J Boss SeamIntroduction To J Boss Seam
Introduction To J Boss Seam
 
Content Storage With Apache Jackrabbit
Content Storage With Apache JackrabbitContent Storage With Apache Jackrabbit
Content Storage With Apache Jackrabbit
 
The Java Content Repository
The Java Content RepositoryThe Java Content Repository
The Java Content Repository
 
Enterprise Java Web Application Frameworks Sample Stack Implementation
Enterprise Java Web Application Frameworks   Sample Stack ImplementationEnterprise Java Web Application Frameworks   Sample Stack Implementation
Enterprise Java Web Application Frameworks Sample Stack Implementation
 
GlassFish and JavaEE, Today and Future
GlassFish and JavaEE, Today and FutureGlassFish and JavaEE, Today and Future
GlassFish and JavaEE, Today and Future
 
Soa 12 jax ws-xml Java API for web services
Soa 12 jax ws-xml Java API for web servicesSoa 12 jax ws-xml Java API for web services
Soa 12 jax ws-xml Java API for web services
 
Rollin onj Rubyv3
Rollin onj Rubyv3Rollin onj Rubyv3
Rollin onj Rubyv3
 
Oracle History #5
Oracle History #5Oracle History #5
Oracle History #5
 
An Intense Overview of the React Ecosystem
An Intense Overview of the React EcosystemAn Intense Overview of the React Ecosystem
An Intense Overview of the React Ecosystem
 
Make easier Integration of your services with Fuse Solutions - RedHat 2013
Make easier Integration of your services with Fuse Solutions - RedHat 2013Make easier Integration of your services with Fuse Solutions - RedHat 2013
Make easier Integration of your services with Fuse Solutions - RedHat 2013
 
Hotsos 2013 - Creating Structure in Unstructured Data
Hotsos 2013 - Creating Structure in Unstructured DataHotsos 2013 - Creating Structure in Unstructured Data
Hotsos 2013 - Creating Structure in Unstructured Data
 

Dernier

Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 

Dernier (20)

Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 

JSR-222 Java Architecture for XML Binding

  • 1. JAXB - Java Architecture for XML Binding ● Preface ● Architecture ● Generate JavaBeans ● Generate XML Schema ● Runtime transformation Heiko Scherrer
  • 2. JAXB - Preface ● JAXB – Java Architecture for XML Binding ● Another XML-API for Java ? ● No! Different to JAXP, StAX, SAX or DOM ● Binding not Parsing! ● JAXB driven by the JCP ● RI is Java WSDP (Web Service Developer Packages) ● Validation within binding process (optional) Heiko Scherrer
  • 3. JAXB - Goals ● Simplicity JAXB simplifies the handling with XML and provides data with POJOs ● Abstraction Prevents from low-level file parsing and processing ● Standardization API is part of JavaSE6 javax.xml.bind Heiko Scherrer
  • 4. JAXB – History (JAXB 1.0) ● JAXB 1.0 → JSR-31 (2003) ● Only one-way binding from XML-Schema->Java classes ● Generated code was not completely portable ● W3C schema not entirely supported ● Already support for validation (strict!) Heiko Scherrer
  • 5. JAXB – History (JAXB 2.0) ● JAXB 2.0 → JSR-222 (2006) ● Uses Java5 core concepts: Annotations, Generics, Enumerations ● Fundamental changes to simplify usability ● It's a real binding framework not a one-way mapper only ● No dependencies to implementation classes ● Full support of W3C XML Schema 1.0 ● Major changes in validation process: more efficient, standardized (JAXP) and flexible Heiko Scherrer
  • 6. JAXB – History (JAXB 2.1) ● JAXB 2.1 → JSR-222 (2006) ● Only a small maintenance release ● One change to mention: Separate compilation feature. To extend a generated schema and reuse originally generated class files ● Integration in JDK6 is a manual step! ● Not worth to update Heiko Scherrer
  • 7. JAXB – History (JAXB 2.2) ● JAXB 2.2 → JSR-222 (Q4/2009) ● Small maintenance release ● Simplifies marshaling/unmarshaling ● Simplifies globalBindings and schemaBindings ● Other minor improvements and bug fixes ● JDK6 upgrade is a manual step, version 2.0 is pinned! Heiko Scherrer
  • 8. JAXB – Affinities (I) ● DOM API: Document Object Model (W3C) ● XML is read/writeable ● Object tree represents the XML file ● Memory consumptive ● Random data access ● See also JDOM, dom4j and Jaxen ● SAX API: Simple API for XML ● XML only readable ● Sequential event-driven document scanner ● Fast file parsing (compared to DOM) ● Integrated in JavaSE1.4 Heiko Scherrer
  • 9. JAXB – Affinities (II) ● StAX: Streaming API for XML ● XML is read/writeable ● Serial document scanner: – Parser is calling handler directly – Parser and handler are decoupled with events ● Included in JavaSE6 (avail for 1.4/5) ● JAXP: Java API for XML Processing ● Abstracts DOM, SAX, StaX, Xpath and XSLT ● Integrated since JavaSE1.4 Heiko Scherrer
  • 10. JAXB – XML API Classification Data Binding Frameworks Client application Castor JAXB uses Java objects Castor Impl Java WSDP Abstraction XML JAXP Layer DOM JDOM SAX StAX Client application has to deal with objects that Apache Sun represents XML Codehaus RI Xerces Crimson Parser API and Implementations XML Heiko Scherrer
  • 11. JAXB Java Architecture for XML Binding ● Preface ● Architecture ● Generate JavaBeans ● Generate XML Schema ● Runtime transformation Heiko Scherrer
  • 12. JAXB – Architecture @ compiletime: ● Use JAXB Schema compiler to generate annotated Java classes from XML schema or DTD  contract-driven approach (WSDL) ● Or use JAXB schema generator to generate a XML Schema from annotated Java classes  model-driven approach (domain model) Heiko Scherrer
  • 13. JAXB – Architecture Write or generate Write or generate the XML Schema, Java classes the “contract” Compile Time XML Schema with POJO classes with binding JAXB annotations declarations XML Use schema compiler or schema generator Heiko Scherrer
  • 14. JAXB – Architecture @ Runtime: ● XML Schema instance (XML file) is transformed into a Java object model instance – or backwards ● XML files don't have to be valid ● Binding and runtime validation is done using JAXB binding framework Heiko Scherrer
  • 15. JAXB – Architecture Compile time  Generation during XML Schema Java classes compile time  Transformation XML Generation during runtime  Marshalling instantiation Transformation from Java instantiation Runtime to XML data  Unmarshalling XML Marshalling / Unmarshalling Transformation from XML data to Java objects Heiko Scherrer
  • 16. JAXB Java Architecture for XML Binding ● Preface ● Architecture ● Generate JavaBeans ● Generate XML Schema ● Runtime transformation Heiko Scherrer
  • 17. JAXB – Generate JavaBeans ● Schema compiler (xjc) ● command line tool (bin/xjc.sh) ● ANT task ● Maven plugin ● Generated resources: JavaBeans, factory class (ObjectFactory), package-info ● Example, see ./30a-JAXB_example Heiko Scherrer
  • 18. JAXB – Code Generation:Example Java Package: org.openwms.examples XJC targetNamespace= ”examples.openwms.org” Heiko Scherrer
  • 19. JAXB – Class Generation:Overview ● Generated classes follow the JavaBeans specification ● Default binding configuration  “Convention over Configuration” ● Custom binding configuration  Override the default generation rules ● A binding configuration contains 1..* binding declarations ● Expressed with XML ● Inline configuration: within same XML Schema ● External configuration: separate XML file Heiko Scherrer
  • 20. JAXB – Assignment / Customization ● Default binding configuration ● Namespace is mapped to Java package ● Datatype is mapped to Java class ● Element is mapped to Class property ● Reasons to customize binding configuration ● Override standard datatype conversion ● Customize standard name conversion ● Add JavaDoc comments Heiko Scherrer
  • 21. JAXB – Inline declaration ● annotation/appinfo are defined elements of XMLSchema ● XJC recognizes appinfo element ● Bindings in different scopes Heiko Scherrer
  • 22. JAXB – External declaration ● Separate XML file ● Use xsd:import to import schemas ● Reference the base schema: schemaLocation Heiko Scherrer
  • 23. JAXB – Binding declaration scopes ● Possible scopes for binding declarations: ● <globalBindings>:Global declarations are valid for all schemes, even included and imported ones ● <schemaBindings>:All elements in the current schema ● <class>:Valid for global type and element definitions ● <property>:Valid for sub-elements of a type or element Heiko Scherrer
  • 24. JAXB – Override declarations ● Inner defined binding configuration override the ones defined in outer scope (e.g. declaration in property scope overrides property in class, schema or global scope) Heiko Scherrer
  • 25. JAXB – Popular binding declarations <jaxb:collectionType> ● <jaxb:collectionType>:Map an implementation class to Collections ● Binding declaration (example): <jaxb:globalBindings collectionType=”java.util.Vector”> ● XML Schema element definition <xs:element name=”locations” minOccurs=”0” maxOccurs=”unbounded” type=”xs:string”/> ● Results in: protected List<String> = new Vector<String>(); Heiko Scherrer
  • 26. JAXB – Popular binding declarations <jaxb:package> ● <jaxb:package>:Define the name of the Java package ● Binding declaration (example): <jaxb:schemaBindings> <jaxb:package name=”org.openwms”/> </jaxb:schemaBindings> ● All elements within this schema are bound to classes in the named package Heiko Scherrer
  • 27. JAXB – Popular binding declarations <jaxb:class> ● <jaxb:class>:Override the default classname for a given element ● Declare binding for a chosen element. Use XPath to identify the node: <jaxb:bindings node=”//xsd:complexType[@name='location']”> <jaxb:class name=”WMSLocation”/> </jaxb:bindings> ● The name of the generated class is WMSLocation Heiko Scherrer
  • 28. JAXB – Popular binding declarations <jaxb:property> ● <jaxb:property>:Valid for sub-elements of a type or element ● Used to customize generated Java class properties ● Declare binding for a chosen element. Use XPath to identify the node: <jaxb:bindings node=”//xsd:element[@name='id']”> <jaxb:property name=”identifier”/> </jaxb:bindings> Heiko Scherrer
  • 29. JAXB – Popular binding declarations <jaxb:javadoc> ● <jaxb:javadoc>:Document generated packages, classes and methods ● Document the source of data! (XML) ● Used as child of jaxb:package/jaxb:class/ jaxb:property ● Use <![CDATA[..]]> inside to document <jaxb:class name=”WMSLocation”> <![CDATA[class documentation]]> </jaxb:class> Heiko Scherrer
  • 30. JAXB Java Architecture for XML Binding LAB Heiko Scherrer
  • 31. JAXB Java Architecture for XML Binding ● Preface ● Architecture ● Generate JavaBeans ● Generate XML Schema ● Runtime transformation Heiko Scherrer
  • 32. JAXB – XML Schema Generation ● Schema generator (schemagen) ● command line tool (bin/schemagen.sh) ● ANT task ● Maven plugin ● Input data: Java source or class files ● Generated resources: XML Schema file ● Example, see ./30a-JAXB_example Heiko Scherrer
  • 33. JAXB – XML Schema Generation Simplest case! POJO without JAXB related annotations schemagen Heiko Scherrer
  • 34. JAXB – XML Schema Generation ● Java classes must follow the JavaBeans specification ● Don't has to be annotated with JAXB annotations  Convention over Configuration ● Example, see ./30a-JAXB_example ● Lots of javax.xml.bind.annotation.* to customize schema generation! Heiko Scherrer
  • 35. JAXB – XML Schema Generation Define namespace ● Standard package-info.java documents package content and defines XML namespace: ● Use FQCN and do not import class type! ● Can be overridden on class-level: Heiko Scherrer
  • 36. JAXB – XML Schema Generation @XmlRootElement ● Annotated classes can be used as root elements in XML Schema instances and marshalled directly (see Transformation) ● An XML Schema element is generated, too ● On type level: classes and enumerations Heiko Scherrer
  • 37. JAXB – XML Schema Generation @XmlAccessType ● Defined which instance variables or properties to use for schema generation ● Possible values: ● NONE: No variables are bound to the schema ● PROPERTY: All JavaBeans properties are used ● FIELD: All instance variables are bound to the schema ● PUBLIC_MEMBER: All instance variables and properties are used ● Package or class level annotation Heiko Scherrer
  • 38. JAXB – XML Schema Generation @XmlElement ● Customize mapping from properties/variables to elements (similar JPA @Column) ● Possible parameters: ● name: Name of the XML element ● required: true if the element must be set, else false ● defaultValue: Default value when no value set during marshalling ● PUBLIC_MEMBER: All instance variables and properties are used Heiko Scherrer
  • 39. JAXB – XML Schema Generation @XmlAttribute ● Annotated properties occur as attributes of an element ● Possible parameters: ● name: Name of the XML attribute ● required: true if the attribute must be set, else false Heiko Scherrer
  • 40. JAXB – XML Schema Generation @XmlValue ● Variable is used as plain-text content of the element ● If used no other sub-elements are permitted Heiko Scherrer
  • 41. JAXB – XML Schema Generation @XmlTransient ● Binding is omitted ● Comparable to JPA's @Transient and Java's transient ● If used no other sub-elements are permitted ● Allowed on field and method level Heiko Scherrer
  • 42. JAXB Java Architecture for XML Binding LAB Heiko Scherrer
  • 43. JAXB Java Architecture for XML Binding ● Preface ● Architecture ● Generate JavaBeans ● Generate XML Schema ● Runtime transformation Heiko Scherrer
  • 44. JAXB – Runtime transformation ● Reading and writing XML files with JAXB ● JAXBContext: All you need to access data binding (threadsafe but expensive!) ● Binding Java packages with: JAXBContext.newInstance (“package1:package2:...”) ● Binding Java classes with: JAXBContext.newInstance (“class1:class2:...”) Heiko Scherrer
  • 45. JAXB – Runtime transformation - Unmarshalling ● Unmarshalling: Transforming a XML file into a Java object tree instance ● Create an Unmarshaller from the context object: Unmarshaller u = ctx.createUnmarshaller(); ● Validation against XML Schema or with ValidationHandler (see Validation) ● Unmarshal: <Root> root = u.unmarshal(<Resource>); Heiko Scherrer
  • 46. JAXB – Runtime transformation - Unmarshalling ● Method parameters of unmarshal(..): ● java.io.File ● java.net.URL ● java.io.InputStream ● java.xml.stream.XMLStreamReader ● java.xml.stream.XMLEventReader ● java.xml.transform.Source ● org.w3c.dom.Node ● org.xml.sax.InputSource Heiko Scherrer
  • 47. JAXB – Runtime transformation - Unmarshalling ● Return value of unmarshal(..): ● java.lang.Object ● Cast into Java object that represents the XML root element: Location loc = (Location) u.unmarshal( new File(“locations.xml”)); ● Simplest case: Unmarshal the whole XML file; map between XML root element and Java class @XMLRootElement Heiko Scherrer
  • 48. JAXB – Runtime transformation - Marshalling ● Marshalling: Transforming a Java object tree instance into a XML file ● Create an Marshaller from the context object: Marshaller m = ctx.createMarshaller(); ● Validation against XML Schema or with ValidationHandler (see Validation) ● Marshal: m.marshal(obj, <Resource>); Heiko Scherrer
  • 49. JAXB – Runtime transformation - Marshalling ● Method parameters of marshal(obj, res): ● obj: POJO annotated with @XMLRootElement ● res: java.io.OutputStream ● res: java.io.Writer ● res: java.io.File ● res: org.w3c.dom.Node ● res: org.xml.sax.ContentHandler ● res: java.xml.stream.XMLStreamReader ● res: java.xml.stream.XMLEventReader Heiko Scherrer
  • 50. JAXB – Runtime transformation - Marshalling ● Write directly into XML file: m.marshal(locations, new File(“locations.xml”)); ● Write to System.out: m.marshal(locations, System.out); Heiko Scherrer
  • 51. JAXB Java Architecture for XML Binding LAB Heiko Scherrer
  • 52. JAXB Java Architecture for XML Binding Next time: Validation Customizing Marshalling & Unmarshalling Heiko Scherrer