JAXB 2.0

Overview

* JAXB = Java Architecture for XML Binding.
* Reference implementation is available at http://jaxb.java.net/
* JAXB 2.0 is part of
– J2EE 5
– JDK 6
* JAXB 2.0 requires
– JDK 1.5

JAXB 2.0 vs JAXB 1.0

* Schema compiler generates annotated POJOs instead of separate interface and implementation classes for each component of an XML schema.
* Any Java class can be bound to an XML representation via annotations.
* All generated classes are portable among different implementations. In JAXB 1.0, only interfaces are portable.
* JAXB 2.0 does not include validation capabilities. Validation is delegated to JAXP 1.3.
* JAXB 2.0 has complete support for W3C XML Schema. JAXB 1.0 not.
* Integration with StAX to support

javax.xml. stream. XMLStreamWriter
javax.xml.stream.XMLStreamReader
javax.xml.stream.XMLEventWriter
javax.xml.stream.XMLEventReader

* JAXB 2.0 supports callback methods for Marshaller and Unmarshaller objects.

Data Binding: XML <-> Java

* A data binding facility contains:
– schema compiler: xml -> Java
– schema generator: Java -> xml
* A data binding framework (i.e. runtime API) supports:
– unmarshalling: xml -> Java
– marshalling: Java -> xml
– binding is done via a binder: XML schema <-> JAXB classes

Goals

* Full XML Schema support
* Allow binding existing Java classes to generated XML schema, i.e. support from Java approach
* Full JAX-WS 2.0 data binding support
* Support container managed environments
* Support schema evolution
* Application specific behavior
* Support partial mapping of XML document
* Clarify integration with StAX (Streaming API for XML)
* Clarify relationship to other XML related specs
* JAXB mapped classes should be portable
* Support round trippings,
– Java -> xml -> Java
– xml -> Java -> xml
* Support unmarshalling invalid XML content
* Ease of use
– no need to know xml in order to use
* Support customization of
– xml -> Java
– Java -> xml
* Schema derived classes should be
– natural/readable
– match conceptual level of source schema

Non-Goals

* No backward support for J2SE 4.0 or earlier
* No DTD support
* No support for schema extensions
* No support for SOAP encoding
* No support for validation on demand by schema derived classes
* No support for object graph traversal
* No support for mapping any existing Java classes to any existing XML schema

Reference Implementations (JAXB RI)

* Is an open source project located at https://jaxb.dev.java.net
* Included in Java Web Services Developer Pack (JWSDP)

Download and Install

* Download a desired version from http://jaxb.java.net.
* Unpack

java -jar JAXB2_<release date>.jar

* For example,
– Download JAXB 2.2 jar file named JAXB2_20091104.jar from http://jaxb.java.net/2.2/
– Unpack with

java -jar JAXB2_20091104.jar

– jaxb-ri-20091104 directory is created.

Core Classes

* JAXBContext
* Marshaller
* Unmarshaller

Compile Schema

* Generates annotated POJOs
* Use xjc command line utility

C:\jaxb-ri-20091104\bin>xjc -help
Usage: xjc [-options ...] <schema file/URL/dir/jar> ... [-b <bindinfo>] ...
If dir is specified, all schema files in it will be compiled.
If jar is specified, /META-INF/sun-jaxb.episode binding file will be compiled.
Options:
  -nv                :  do not perform strict validation of the input schema(s)
  -extension         :  allow vendor extensions - do not strictly follow the
                        Compatibility Rules and App E.2 from the JAXB Spec
  -b <file/dir>      :  specify external bindings files (each <file> must have its own -b)
                        If a directory is given, **/*.xjb is searched
  -d <dir>           :  generated files will go into this directory
  -p <pkg>           :  specifies the target package
  -httpproxy <proxy> :  set HTTP/HTTPS proxy. Format is [user[:password]@]proxyHost:proxyPort
  -httpproxyfile <f> :  Works like -httpproxy but takes the argument in a file to protect password
  -classpath <arg>   :  specify where to find user class files
  -catalog <file>    :  specify catalog files to resolve external entity references
                        support TR9401, XCatalog, and OASIS XML Catalog format.
  -readOnly          :  generated files will be in read-only mode
  -npa               :  suppress generation of package level annotations (**/package-info.java)
  -no-header         :  suppress generation of a file header with timestamp
  -target 2.0        :  behave like XJC 2.0 and generate code that doesnt use any 2.1 features.
  -xmlschema         :  treat input as W3C XML Schema (default)
  -relaxng           :  treat input as RELAX NG (experimental,unsupported)
  -relaxng-compact   :  treat input as RELAX NG compact syntax (experimental,unsupported)
  -dtd               :  treat input as XML DTD (experimental,unsupported)
  -wsdl              :  treat input as WSDL and compile schemas inside it (experimental,unsupported)
  -verbose           :  be extra verbose
  -quiet             :  suppress compiler output
  -help              :  display this help message
  -version           :  display version information
 
Extensions:
  -Xinject-code      :  inject specified Java code fragments into the generated code
  -Xlocator          :  enable source location support for generated code
  -Xsync-methods     :  generate accessor methods with the 'synchronized' keyword
  -mark-generated    :  mark the generated code as @javax.annotation.Generated
  -episode <FILE>    :  generate the episode file for separate compilation

* Use xjc Ant task (See sample below)

JAXB Annotations

Class-level Annotations

* XmlRootElement
* XmlAccessorType.
PUBLIC_MEMBER // Default. Marshals all public getter/setter pairs
FIELD // Marshals all nonstatic and nontransient field in the class
PROPERTY // Like PUBLIC_MEMBER, but also marshals private, protected, or package-only getter/setter pairs
NONE // NO child elements will be marshalled automatically
* XmlType
* Example

@XmlAccessorType(XmlAccessType. FIELD)
@XmlType(name = "", propOrder = {
    "firstName",
    "lastName"
})
@XmlRootElement(name = "person")
public class Person {
}

Filed-level Annotations

* XmlElement
required
nillable
defaultValue
* Example

@XmlElement(required = true)
protected String firstName;
@XmlElement(required = true)
protected String lastName;

Package-level annotations

* Howto
– Create a file called package-info.java
– Add a regular Java package declaration to it
– Add annotations to it
* Example

@javax. xml. bind. annotation. XmlSchema(
    namespace = "http: //www. example. com/person",
    elementFormDefault = javax. xml. bind. annotation. XmlNsForm. QUALIFIED
)
package javaxml3;

– declare namespace prefixes:

@javax. xml. bind. annotation. XmlSchema(
    namespace = "http: //www. example. com/person",
    elementFormDefault = javax. xml. bind. annotation. XmlNsForm. QUALIFIED,
    xmlns = {
        @javax. xml. bind. annotation. XmlNs(prefix = "p",
            namespaceURI="http: //www. example. com/person")
    }
)
package javaxml3;

Schema Compilation Customization

* Conceptually similar to annotation
* Can be contained in
– schema file
– external binding file
– both
* Customization are for elements within the namespace http://java.sun.com/xml/ns/jaxb

Inline Declarations

Schema Generation

* Use schemagen command line utility to generate XML schema from annotated Java classes.

 

Marshalling

UnMarshalling

Examples

Books Example

* http://www.oracle.com/technetwork/articles/javase/index-140168.html
* Generate Java with Ant
– copy books.xsd to src directory
– binding classes are generated in the src directory in package test.jaxb

  <property environment="env"/>
  <property name="jaxws.lib.dir" value="${env.JAXWS_HOME}/lib"/>
 
<path id="jaxws.classpath">
      <fileset dir="${jaxws.lib.dir}">
          <include name="*.jar"/>
      </fileset>
  </path>
 
<taskdef name="xjc" classname="com.sun.tools.xjc.XJCTask">
      <classpath refid="jaxws.classpath"/>
</taskdef>
 
<target name="generate-java" 
      description="Generate Java from xml schema">
  <xjc schema="src/books.xsd" 
     destdir="src" 
     package="test.jaxb"/>
</target>

* Marshalling/Unmarshalling

try {
  System.out.println("Getting JAXBContext...");
  JAXBContext ctx = JAXBContext.newInstance("test.jaxb");
  System.out.println("Got JAXBContext.");
 
  System.out.println("Getting Unmarshaller...");
  Unmarshaller um = ctx.createUnmarshaller();
 
  // Validate against schema
  Schema schema = 
    SchemaFactory.newInstance(
      XMLConstants.W3C_XML_SCHEMA_NS_URI).newSchema(
          new File("src" + File.separator + "books.xsd"));
  um.setSchema(schema);
  System.out.println("Got Unmarshaller.");
 
  System.out.println("Getting book colleciton...");
  Collection bookcol = (Collection)
    um.unmarshal(new File("src" + File.separator + "books.xml"));
  System.out.println("Got book colleciton.");
 
  List<BookType> booklist = bookcol.getBooks().getBook();
  for (int i = 0; i < booklist.size(); i++){
    BookType book = booklist.get(i);
    System.out.println("Got book: " + book.getName());
  }
 
  // Marshal back
  System.out.println("Getting Marshaller...");
  Marshaller m = ctx.createMarshaller();
    m.setProperty( Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE );
  System.out.println("Got Marshaller.");
 
  System.out.println("Marshalling to screen...");
  m.marshal(bookcol, System.out);
} catch (JAXBException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
} catch (SAXException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
}

References

* JSR-222 JAXB
* JAXB 2.0 API
* java.net jaxb tutorial
* http://www.oracle.com/technetwork/articles/javase/index-140168.html
* Java and XML, Third Edition By: Brett McLaughlin; Justin Edelson

This entry was posted in jaxb. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *


*

This site uses Akismet to reduce spam. Learn how your comment data is processed.