Download as pdf or txt
Download as pdf or txt
You are on page 1of 79

Binding between XML Schema

and Java Classes (JAXB)

Introduction
Architecture
Binding Process
Schema Validation Framework

#JAXB #Validation
Objectives
• How to convert XML Schema to Java Object
Class?
• How to binding XML document to Java Object
and Java Object to XML document?
– Binding Process
• How to validate XML in Java Application
– Schema Validation Framework
JAXB
Need for JAXB
• To parse XML using DOM API, the developer must be required to
discover and understand the XML structure in the owner’s
meaning
– The developer is required to understand and get more experiences in using
DOM API
– However, the JAXP supporting XPath API has already reduced the
developer‘s burden in programming (but developer must also understand the
XML document’s structure to write Xpath Expression)
• To reduce the programming burden of XML processing, the
framework in automatically generating the mapping is needed
• There are two major approaches to data binding
– One is to deduce a Java data structure from a given XML schema
• If an XML schema is given and developer are required to write a program to read
XML data according to the schema, a data binding tool of the former type is useful
– The other is to deduce an XML structure from a given Java program
• If developers already have their application program and they are requested to
externalize the application data in some XML format, one of the reflection-based
tools is a better choice
JAXB
Introduction
• Is briefly the Java Architecture for XML Binding
• Binds the XML schemas/DTD and Java representations in a fast
and convenient way (e.g. comparing with DOM & SAX).
• Converts XML instance documents into Java content trees
(unmarshaller)
• Converts Java content trees back into XML instance documents
(marshaller).
• Can make it easier to access XML documents from applications
written in the Java programming language.
– To achieve this, binding the schema for the XML document into a set of Java
classes that represents the schema
• The JAXB API
– Defined in the javax.xml.bind package
– Consists of a set of interfaces through which client applications with code
generated from a schema
– Provides a good quality XML data-binding facility for the J2EE/JavaEE
platform.
JAXB
Limitations
• JAXB requires a DTD and a subset of XML
Schemas.
– Hence, it cannot be used to process generic XML, such
as writing an XML editor or other tool.
• Additional work is required to tell JAXB what
kind of tree it should construct to simplify the
application.
• JAXB does not support the legal DTD constructs
such as Internal subsets, NOTATIONs, ENTITY
and ENTITIES, and Enumerated NOTATION
types.
JAXB
Architecture

IBM,
http://pic.dhe.ibm.com/infocenter/wasinfo/v7r0/index.jsp?topic=%2Fcom.ibm.websphere.express.doc%2Finfo
%2Fexp%2Fae%2Fcwbs_jaxb.html
JAXB
Architecture
• Consists of three components:
– Schema compiler
• Binds a source schema to a set of schema derived program
elements using an XML-based binding language.
– Binding language: describes schema binding of Java classes which
enables a developer to override the default binding rules
→ Generates Java classes from a given schema
– Schema generator
• Maps a set of existing program elements to a derived
schema.
– Binding runtime framework
• Provides runtime services such as marshalling (writing),
unmarshalling (reading), and validation to be performed on
the contents classes
JAXB
Binding Process
1. JAXB binding compiler 2.
Compiling
src code

4.
4.1 5. Process

4.2 Content
3.
6. tree
JAXB
Binding Process
• Generate classes
– First, the JAXB binding compiles the XML schema to generate JAXB
classes based on that schema.
• Compile classes
– All the generated classes, sources files/codes should be compiled.
• Unmarshal
– Unmarshal the XML documents with the help of JAXB binding framework.
• Generate content tree
– The unmarshalling process generates tree of data objects which represents
the structure and content of the source XML documents.
• Validate (optional)
– The unmarshalling process validates the source XML documents before
generating the content tree.
• Process content
– The client application modifies the XML data represented by the Java content
tree.
• Marshal
– The processed content tree is marshaled into XML documents which may be
further validated before marshalling.
JAXB
Generating Java Class from XML Schema – Example
JAXB
Generating Java Class from XML Schema – Example
• In the netbeans ide,
– Choose the XML categories, then choose JAXB Binding
– Choose Next
JAXB
Generating Java Class from XML Schema – Example

Fill your Binding Name

Choose type file, then


type or browse source
file

Choose the schema type


Type the package name
that will be represented
as context path

Click Finish
JAXB
Generating Java Class from XML Schema – Example
JAXB
Generating Java Class from XML Schema with
Console – Example
JAXB
Dynamically Generating Java Class from XML
Schema with Java API – Example
JAXB
Dynamically Generating Java Class from XML
Schema with Java API – Example
JAXB
Dynamically Generating Java Class from XML
Schema with Java API – Example
JAXB
APIs – JAXBContext class
• Provides a client program’s entry point to the JAXB API
• Provides a set of methods for implementing the JAXB Binding framework
operations
Methods Descriptions
-public abstract Marshaller createMarshaller() throws
JAXBException
createMarshaller
-Creates a Marshaller object that converts a Java content tree
into XML data
-public abstract Unmarshaller createUnmarshaller() throws
JAXBException
createUnmarshaller
-Creates a Unmarshaller object that converts XML data into
a Java content tree
-public static JAXBContext newInstance (Class…
classesToBeBound) throws JAXBException
newInstance -Returns a new instance of a JAXBContext class
-May throw IllegalArgumentException if null argument is
passed
JAXB
Unmarshalling

• Is the process of converting an XML document


into a content tree (DOM).
• Steps to unmarshal an XML document
– First create a JAXBContext object that provides the
entry point to the JAXB API.
– Specify a context path which contains the list of one or
more package names that contain interfaces generated
by the binding complier.
JAXB
Unmarshalling – Process

Figure 4-4, Java & XML Data Binding, Brett McLaughlin


JAXB
Unmarshalling
• A Process
– An object of JAXBContext class is created in context path that
is a package containing the interfaces generated for the
particular schema (or root class with JAXB Annotation).
– An object of unmarshaller class is created that controls the
process of unmarshalling. In particular, it contains methods that
perform the actual unmarshalling operation.
– The unmarshal method is invoked which performs the actual
unmarshalling of the XML document.
– The get method in the schema-derived classes is used to access
the XML data.
• Steps for implementation
– Develop the database schema or structure.
– Using tools to generate the Java Classes from above schema
JAXB
APIs – Unmarshaller Interfaces
• Controls the deserialization process of a XML data into a Java
object tree.
• It provides a set of overloaded unmarshal methods and optionally
validate the XML
Methods Descriptions
-Object getProperty (String name) throws PropertyException
getProperty
-Retrieves a JAXB specified property given by name
-Object unmarshal (File f) throws JAXBException
-Object unmarshal (InputStream is) throws JAXBException
-Object unmarshal (URL url) throws JAXBException
-Object unmarshal (Node node) throws JAXBException
unmarshal -Object unmarshal (Source src) throws JAXBException
-…
-Unmarshals XML data from the specified file|url or
InputStream object or specified DOM tree object or XML
Source, and return the content tree
JAXB
APIs – JAXB Annotation
• Are defined in the javax.xml.bind.annotation packages that support to
marshal a Java object to an XML document
Annotations Descriptions
-Maps a Java class or an enum type to an XML Schema
XmlValue
complex type
-Maps a Java class to an XML Schema type, which can be a
XmlType
simple type or a complex type
XmlSchema -Maps a package name to an XML namespace
XmlRootElement -Maps a Java class or enum type to an XML element
XmlList -Maps a property to a simple list type
XmlEnum -Maps a Java enum data type to XML representation
XmlElement -Maps a JavaBean property to an element
XmlAttribute -Maps a JavaBean property to an attribute
XmlRegistry -Creates an XML Registry in which Java objects can be stored
JAXB
Unmarshalling – Example
JAXB
Unmarshalling – Example – 1st Alternative way
JAXB
Unmarshalling – Example – 2nd Alternative way
JAXB
Unmarshalling – Example
JAXB
Marshalling

• Is the process of building an XML document using the


content (DOM) tree (can apply to use transformer)
• To marshalling
– Modify the existing content tree, or create a new tree from the
business logic output.
– Optionally perform validation of the content tree in-memory,
against the source schema.
– Marshal the content tree into an XML document.
JAXB
• Process
Marshalling
– An object of JAXBContext class is created and the appropriate
context path of the package that contains the classes and
interfaces for the bound schema is specified.
– An object of Marshaller class is created which controls the
process of marshalling.
– The Marshaller object sets its properties using the setProperty
method. Here, the code turns the output format property on line
breaks and indentation will appear in the output format.
– The marshal method is invoked by specifying an object that
contains the root of the content tree, and the output target.
• Here, the code marshals the content tree whose root is in the collection
object and writes it as an output stream to the XML file Output_File.xml.
• Steps for implementation
– Import the JAXB API library in projects
– Define the root of the Java Object with annotation
@XmlRootElement
– Write the Java Class that call the JAXB API to process
JAXB
Marshalling
• Created an annotated class
– Create a simple Java class
– Import the javax.xml.bind.annotation package with its
annotation types
– Create the root element of an XML document with
@XmlRootElement annotation
– Create a complex Type using @XmlType annotation
• Define the child elements or component in this annotation
– The root element may have attributes. Define the
attributes using @XmlAttribute annotation
JAXB
Unmarshalling – Example
JAXB
APIs – Marshaller Interfaces
• Controls the serialization process of a Java object tree back into XML data.
• It provides the basic marshaling methods
Methods Descriptions
-Node getNode (Object tree) throws JAXBException
getNode -Returns a DOM tree representation of the content tree
-Accepts specified Java object representation of an XML document
-void marshal(Object root,ContentHandler h)throws JAXBException
-void marshal (Object root, Node node) throws JAXBException
-void marshal (Object jaxbElement, XMLStreamWriter|file writer)
marshal
throws JAXBException
-Marshals the content tree into SAX2 events or DOM trees or
XMLStreamWriter object or OutputStreams
-Object getProperty (String name) throws PropertyException.
getProperty
-Retrieves a JAXB specified property given by name
-void setProperty(String name, Object value) throws
setProperty PropertyException
-Can be used to set a specified JAXB properties
JAXB
Marshalling – Example
JAXB
Marshalling – Example
JAXB
Marshalling – Example
JAXB
Marshalling – Example
JAXB
Marshalling – Example
JAXB
Marshalling – Example
JAXB
Marshalling – Example
JAXB
Un/Marshalling with Namespace – Example
JAXB
Un/Marshalling with Namespace – Example
JAXB
Un/Marshalling with Namespace – Example
JAXB
Un/Marshalling with Namespace – Example
JAXB
Marshalling with Namespace – Example
JAXB
Marshalling with Namespace – Example
JAXB
Binding Process – Summary
JAXB
Need for validation – Example
JAXB
Need for validation – Example
JAXB
Data validation – Example
JAXB
Data validation – Example
Schema Validation Framework
Introduction
• The Validation APIs
– Introduced in JAXP 1.3, are schema-independent
Validation Frameworks.
• Previously, validation was considered as a part of XML parsing.
– Separates parsing from validation to make validation
efficient, easy, and secure
– Enables to parse only the schema and check the syntax
and semantics on the basis of the imposed schema
language
– The javax.xml.validation API helps to validate the
XML document
Schema Validation Framework
javax.xml.validation Packages
Classes Descriptions
- Represents a set of constraints against which an XML
document is validated.
- This set of constraints should not change once the
Schema
document has been created.
- The result of the validation should be the same every time
the document is validated
- Is responsible for creating Schema objects. It is the first
step for the Validation API.
- The external representation of schemas is read and
SchemaFactory
prepared for validation by SchemaFactory. It is required on
application’s part to ensure that at least one thread is using
SchemaFactory object at any given point of time
Schema Validation Framework
Data validation
• JAXB supports to validate the source data against its
schema.
• The source data can be validated against
– The associated schema as part of the unmarshalling operation
– The setValidating() or setSchema() method is used
• The JAXB specification allows developer implementing
report validation errors
– During validation, whenever the errors are encountered, a
validation error should be reported but with/without stopping
the data processing.
→The JAXB application is successfully unmarshal an invalid XML
document and built a Java content tree, although the result won’t be
valid.
• The marshalling operation is not supported
Schema Validation Framework
Data validation – Example
Schema Validation Framework
Data validation – Example
Schema Validation Framework
Data validation – Example
Schema Validation Framework
Data validation – Example
Schema Validation Framework
javax.xml.validation Packages
Classes Descriptions
- Checks the XML document against an XML schema.
- Must ensure that it uses only one validator object at any given
Validator instance of time. This object cannot be used from multiple
threads created within the application. Also, a single thread
should not reenter the code recursively
- Uses the Schema object to validate that the SAX events follow
the set of constraints described in the associated schema and
sometimes may modify SAX events.
- Is thread-unsafe. By this is means that there can be unwanted
ValidatorHandler
interaction between the threads.
- Is also a non-re-entrant object. The validating application is
required to check that not more than one thread at any given point
of time
Schema Validation Framework
Data validation
• The ValidationEventHandler
– Will be called by the JAXB Provider if any validation errors are
encountered.
– If the client application does not register a
ValidationEventHandler before invoking the unmarshal
methods, then ValidationEvents will be handled by the default
event handler.
• The JAXB allows developer customizing validation error
handling by overriding the default event handler.
– The customized handler must implement the
ValidationEventHandler interface and the method
handleEvent.
• The boolean return value should be set to true if the JAXB application
attempts to continue the current unmarshal even the errors encountered
• If the return value should be set to false, the operation is terminated with
the appropriate UnmarshalException, ValidationException
– The setEventHandler(ValidationEventHandler) method is used
to set the customizing handler to JAXB Application
Schema Validation Framework
Data validation – Example
Schema Validation Framework
Data validation – Example
Schema Validation Framework
Data validation – Example
Schema Validation Framework
Data validation – Example
Schema Validation Framework
Schema compiling
Schema Validation Framework
XML Validation against a Schema
• Step 1 – Creating a Parser Instance
– Creating an instance of the DOM/SAX parser factory.
• Step 2 – Configuring the Parser Instance
– Configuring the DOM/SAX parser factory instance to support
schema validation
• Step 3 – Obtaining DOM/SAX Parser
– Obtaining a DOM/SAX parser from the configured DOM/SAX
parser factory
• Step 4 – Configuring the Parser for Errors
– For DOM, a parser instance is configured with an error handler
so that the parser can report validation errors.
– For SAX, the instance should be configured to specify the
schema location and error handler.
• Step 5 – Parsing of Document
– Document is parsed using configured DOM/SAX parser.
Schema Validation Framework
XML validation against a complied schema
Schema Validation Framework
XML validation against a complied schema
• SAXParser
– Its schemaLanguage and schemasource properties are set by the
user following statements
parser.setProperty(“http://java.sun.com/xml/properties/jaxp/schemaLanguage”,
“http://www.w3.org/2001/XMLSchema”)
parser.setProperty(“http://java.sun.com/xml/properties/jaxp/schemaSource”,
“parsing_Schema_name.xsd”)
– And, its validation property is also set to true
• In new Validation APIs
– Only Schema instance is set on the factory to validate XML
– There is no need to set the validation to true.
– The setting of schemaLanguage or schemaSource property is
also not required.
Schema Validation Framework
XML validation against SAX/DOM Source
• Create a
ValidatorHandler
object, which can
validate a SAX
stream
• A stand-alone
Validator object
can also be created
• The validation of
SAXSource, a
DOMSource, or an
XML document
against any
schema can be
done by a stand-
alone Validator
object
Schema Validation Framework
XML validation against SAX/DOM Source
Schema Validation Framework
Example
Schema Validation Framework
Example
Schema Validation Framework
Example
Schema Validation Framework
Example
Schema Validation Framework
Example
Schema Validation Framework
Example
Summary
• How to convert XML Schema to Java Object Class?
• How to binding XML document to Java Object and
Java Object to XML document?
– Need for JAXB
– Binding Process
• How to validate XML in Java Application
– Schema Validation Framework

Q&A
Next Lecture
• How to parse XML document to process in
application
– Simple API for XML (SAX)
– Streaming API for XML (StAX)
Appendix
JAXB APIs
• Are implemented in 3 main Java Packages
Packages Descriptions
-Defines abstract classes and interfaces that can be
used in applications
javax.xml.bind -Defines a hierarchy of validation event and
exception classes
-Defines Unmarshaller, Validator, and Marshaller
-Contains a set of utility classes that can be used by a
javax.xml.bind.util client application for handling marshalling,
unmarshalling, and validation events
-Provides default implementations for some of the
javax.xml.bind interfaces.
javax.xml.bind.helper
-Implementations of JAXB can further extend these
classes, and implement the abstract method
JAXB
APIs – JAXBException class
• Is the root exception class for all JAXB Exceptions that
may occur during JAXB operations
Methods Descriptions
-public Throwable getCause()
getCause -Returns the cause of an exception or null if the
cause is unknown or does not exist
-public String getErrorCode()
getErrorCode
-Retrieves a vendor specific error code
-public void printStackTrace (PrintWriter pw)
printStackTrace -Displays the stack trace of an exception to the
PrintWriter object

You might also like