Title: JAXB
1JAXB
- The Java Architecture for XML Binding
- Bibliography
- - JAXB Users Guide from Sun
- Microsystems
- - Java and XML Data Binding by
- McLaughlin
2JAXB
- Like SAX and DOM in that the application
developer does not have to parse the XML - Unlike SAX and DOM it is tied to a particular
document schema - Fast like SAX
- In memory representation like DOM but without all
the general tree manipulation facilities
3JAXB
- An XML Document is an instance of a schema
- A Java object is an instance of a class
- JAXB reads a schema and produces a class
- Previously, the only schema supported was the
Document Type Definition (DTD) - Currently, the only schema supported is XSDL
4In general - Data Binding involves
- Source generation
- From constraints to code
- Unmarshalling
- Reading
- Marshalling
- Writing
- Binding Schemas
- Details about how the XML is to be mapped
to - Java classes (very important with DTDs)
5JAXB
- Augments the standard DTD by providing type
conversion - lt!ELEMENT notional (PCDATA)gt
-
-
- ltnotionalgt100.00lt/notionalgt
- With JAXB we can make sure that Java converts
this to a BigDecimal automatically
6The Binding Schema
- JAXB requires that we use a DTD AND a Binding
Schema - The Binding Schema is an XML document
JAXB
.java file(s)
DTD
Binding Schema
javac
javac
.class files
7The Binding Schema
- The binding schema contains instructions on how
to bind a schema to classes. - It might say that
- this attribute (in the XML document) should be
treated as an int - this elements content is a BigDecimal
- this elements content is a String
- this element should be treated as a class
- and so on
8Running Old JAXB with DTDs
C\McCarthy\www\95-733\examples\jaxbgtjava -jar
D\jaxb\jaxb-1.0-ea\lib\jaxb-xjc-1.0-ea.jar
-help Usage xjc ltschemagt ltbinding-schemagt
-d ltdirectorygt -roots
ltelement-listgt Options -d ltdirectorygt
Specify the destination directory for the
Java output
-roots ltelement-listgt Designate one or more root
elements
(comma separated) -version
Print the compiler's version number and exit
-help Print this
message and exit
9Book.xml
- lt?xml version"1.0" encoding"UTF-8"
standalone"no"?gt - lt!DOCTYPE book SYSTEM "book.dtd"gt
- ltbookgt
- lttitlegtThe Catcher in the Rye lt/titlegt
- ltauthorgtJ.D. Salinger lt/authorgt
- ltchaptergtIf you really want to hear about
it... lt/chaptergt - lt/bookgt
10Book.dtd
lt!ELEMENT book (title,author, chapter)gt lt!ELEMENT
title (PCDATA)gt lt!ELEMENT author
(PCDATA)gt lt!ELEMENT chapter (PCDATA)gt
11A minimal binding schema Book.xjc
ltxml-java-binding-schemagt ltelement name
"book" type "class" root "true"
/gt lt/xml-java-binding-schemagt
12Run old JAXB
C\McCarthy\www\95-733\examples\jaxbgtjava -jar
D\jaxb\jaxb-1.0-ea\lib\jaxb-xjc-1.0-ea.jar
book0.dtd book.xjc .\Book.java C\McCarthy\www\9
5-733\examples\jaxbgt
13Resulting Book.java file
- import java.io.IOException
- import java.io.InputStream
- import javax.xml.bind.ConversionException
- import javax.xml.bind.Dispatcher
- import javax.xml.bind.InvalidAttributeException
- import javax.xml.bind.LocalValidationException
- import javax.xml.bind.MarshallableRootElement
- import javax.xml.bind.Marshaller
- import javax.xml.bind.MissingContentException
- import javax.xml.bind.RootElement
- import javax.xml.bind.StructureValidationException
- import javax.xml.bind.UnmarshalException
- import javax.xml.bind.Unmarshaller
- import javax.xml.bind.Validator
- import javax.xml.marshal.XMLScanner
- import javax.xml.marshal.XMLWriter
14 public class Book extends
MarshallableRootElement implements
RootElement private String _Title
private String _Author private String
_Chapter public String getTitle()
return _Title public void
setTitle(String _Title) this._Title
_Title if (_Title null)
invalidate()
15public String getAuthor() return
_Author public void setAuthor(String
_Author) this._Author _Author
if (_Author null)
invalidate() public String
getChapter() return _Chapter
public void setChapter(String _Chapter)
this._Chapter _Chapter if (_Chapter
null) invalidate()
16public void validateThis() throws
LocalValidationException if (_Title
null) throw new
MissingContentException("title")
if (_Author null) throw new
MissingContentException("author")
if (_Chapter null) throw new
MissingContentException("chapter")
public void validate(Validator v)
throws StructureValidationException
17public void marshal(Marshaller m) throws
IOException XMLWriter w
m.writer() w.start("book")
w.leaf("title", _Title.toString())
w.leaf("author", _Author.toString())
w.leaf("chapter", _Chapter.toString())
w.end("book") public void
unmarshal(Unmarshaller u) throws
UnmarshalException XMLScanner xs
u.scanner() Validator v
u.validator() xs.takeStart("book")
while (xs.atAttribute()) String
an xs.takeAttributeName() throw
new InvalidAttributeException(an)
18if (xs.atStart("title"))
xs.takeStart("title") String s
if (xs.atChars(XMLScanner.WS_COLLAPSE))
s xs.takeChars(XMLScanner.WS_COLL
APSE) else s
"" try
_Title String.valueOf(s) catch
(Exception x) throw new
ConversionException("title", x)
xs.takeEnd("title")
if (xs.atStart("author"))
xs.takeStart("author") String s
if (xs.atChars(XMLScanner.WS_COLLAPSE))
s xs.takeChars(XMLScanner.WS_C
OLLAPSE) else s
""
19try _Author
String.valueOf(s) catch (Exception
x) throw new ConversionException
("author", x)
xs.takeEnd("author") if
(xs.atStart("chapter"))
xs.takeStart("chapter") String s
if (xs.atChars(XMLScanner.WS_COLLAPSE))
s xs.takeChars(XMLScanner.WS_C
OLLAPSE) else s
"" try
_Chapter String.valueOf(s)
catch (Exception x) throw new
ConversionException("chapter", x)
xs.takeEnd("chapter")
20xs.takeEnd("book") public static Book
unmarshal(InputStream in) throws
UnmarshalException return
unmarshal(XMLScanner.open(in)) public
static Book unmarshal(XMLScanner xs)
throws UnmarshalException return
unmarshal(xs, newDispatcher()) public
static Book unmarshal(XMLScanner xs, Dispatcher
d) throws UnmarshalException
return ((Book) d.unmarshal(xs, (Book.class)))
21public boolean equals(Object ob) if
(this ob) return true
if (!(ob instanceof Book))
return false Book tob
((Book) ob) if (_Title! null)
if (tob._Title null)
return false if
(!_Title.equals(tob._Title))
return false else
if (tob._Title! null)
return false
22if (_Author! null) if (tob._Author
null) return false
if (!_Author.equals(tob._Author))
return false
else if (tob._Author! null)
return false
if (_Chapter! null)
if (tob._Chapter null)
return false if
(!_Chapter.equals(tob._Chapter))
return false
23 else if (tob._Chapter! null)
return false
return true public int
hashCode() int h 0 h ((127
h)((_Title! null)?_Title.hashCode() 0))
h ((127 h)((_Author! null)?_Author.hashCod
e() 0)) h ((127 h)((_Chapter!
null)?_Chapter.hashCode() 0)) return
h
24public String toString() StringBuffer
sb new StringBuffer("ltltbook") if
(_Title! null) sb.append("
title") sb.append(_Title.toString())
if (_Author! null)
sb.append(" author")
sb.append(_Author.toString())
if (_Chapter! null) sb.append("
chapter") sb.append(_Chapter.toStrin
g()) sb.append("gtgt")
return sb.toString()
25public static Dispatcher newDispatcher()
Dispatcher d new Dispatcher()
d.register("book", (Book.class))
d.freezeElementNameMap() return d
26A Driver Program
// demo JAXB import java.io. public class
TestJaxb public static void main(String
args) throws
java.io.FileNotFoundException,
javax.xml.bind.UnmarshalException,
java.io.IOException
DataInputStream in new
DataInputStream( new
BufferedInputStream(
new FileInputStream(args0)))
DataOutputStream out new
DataOutputStream( new
FileOutputStream(args1))
27 // read in the book
Book catcher Book.unmarshal(in)
// change its title
catcher.setTitle("Gone With The Wind")
// write out the book
catcher.marshal(out)
28Compile and Run
C\McCarthy\www\95-733\examples\jaxbgtjavac
Book.java C\McCarthy\www\95-733\examples\jaxbgtja
vac TestJaxb.java C\McCarthy\www\95-733\examples
\jaxbgtjava TestJaxb
book.xml
out.xml
29Out.xml
lt?xml version"1.0" encoding"UTF-8"?gt ltbookgt
lttitlegtGone With The Windlt/titlegt ltauthorgtJ.D.
Salingerlt/authorgt ltchaptergtIf you really want
to hear about it...lt/chaptergtlt/bookgt
30Using the new JAXB
31An XSDL Document for an ItemList
- lt?xml version"1.0" encoding"utf-8"?gt
- ltxsdschema xmlnsxsd'http//www.w3.org/2001/XMLS
chema'gt - ltxsdelement name"itemList"gt
- ltxsdcomplexTypegt
- ltxsdsequencegt
- ltxsdelement ref"item"
- minOccurs"0"
maxOccurs"3"/gt - lt/xsdsequencegt
- lt/xsdcomplexTypegt
- lt/xsdelementgt
32ltxsdelement name"item"gt ltxsdcomplexTypegt
ltxsdsequencegt ltxsdelement
ref"name"/gt ltxsdelement
ref"quantity"/gt lt/xsdsequencegt
lt/xsdcomplexTypegt lt/xsdelementgt ltxsdelement
name"name" type"xsdstring"/gt ltxsdelement
name"quantity" type"xsdshort"/gt lt/xsdschemagt
33A Document Instance
- lt?xml version"1.0" encoding"utf-8"?gt
- ltitemList
- xmlnsxsi'http//www.w3.org/2001/XMLSchema-inst
ance' - xsinoNamespaceSchemaLocation"itemList.xsd"gt
- ltitemgt
- ltnamegtpenlt/namegt
- ltquantitygt5lt/quantitygt
- lt/itemgt
- ltitemgt
- ltnamegteraserlt/namegt
- ltquantitygt7lt/quantitygt
- lt/itemgt
- ltitemgt
- ltnamegtstaplerlt/namegt
- ltquantitygt2lt/quantitygt
- lt/itemgt
- lt/itemListgt
34An Ant Build file
- lt?xml version"1.0"?gt
- lt! adapted from Suns jaxb build file ?
- ltproject basedir"." default"run"gt
-
- ltpath id"classpath"gt
- ltfileset dir"D\jwsdp-1.2\jaxb\lib"
includes".jar"/gt - ltfileset dir"D\jwsdp-1.2\common\lib"
includes".jar"/gt - ltfileset dir"D\jwsdp-1.2\jaxp\lib\endors
ed" includes".jar"/gt - ltfileset dir"D\jwsdp-1.2\jwsdp-shared\li
b" includes".jar"/gt - ltfileset dir"D\jwsdp-1.2\jaxp\lib"
includes".jar"/gt - ltpathelement location"."/gt
- lt/pathgt
-
35 lttaskdef name"xjc" classname"com.sun.tools.
xjc.XJCTask"gt ltclasspath
refid"classpath" /gt lt/taskdefgt lt!--
generate Java source files --gt lttarget
name"generate"gt lt!-- generate the
Java content classes from the schema --gt
ltecho message"Compiling the schema..."/gt
ltxjc schema"itemList.xsd" target"."
package"itemListAPI"/gt lt!-- generate
the javadocs from the content classes --gt
ltmkdir dir"docs/api"/gt ltjavadoc
packagenames"itemListAPI"
sourcepath"."
destdir"docs/api"
windowtitle"Generated Interfaces for
itemList.xsd"gt ltclasspath
refid"classpath" /gt lt/javadocgt
36 lt!-- compile all of the java sources --gt
ltecho message"Compiling the java source
files..."/gt ltjavac srcdir"." destdir"."
debug"on"gt ltclasspath
refid"classpath" /gt lt/javacgt
lt/targetgt lttarget name"JustJava"gt
lt!-- compile all of the java sources --gt
ltecho message"Compiling the java source
files..."/gt ltjavac srcdir"." destdir"."
debug"on"gt ltclasspath
refid"classpath" /gt lt/javacgt
lt/targetgt
37 lttarget name"JustJavaRun"gt ltecho
message"java runtime"/gt ltjava
classname"Main" fork"true"gt
ltclasspath refid"classpath" /gt lt/javagt
lt/targetgt lttarget name"run"
depends"generate"gt ltecho
message"Running the sample application..."/gt
ltjava classname"Main" fork"true"gt
ltclasspath refid"classpath" /gt
lt/javagt lt/targetgt lt/projectgt
38Running the build
- D\McCarthy\www\95-733\examples\struts1\src\VOgtant
generate - Buildfile build.xml
- generate
- echo Compiling the schema...
- xjc Compiling file/D/McCarthy/www/95-733
/examples/struts1/src/VO/itemL - ist.xsd
- xjc Writing output to D\McCarthy\www\95-7
33\examples\struts1\src\VO - javadoc Generating Javadoc
- javadoc Javadoc execution
- javadoc Loading source files for package
itemListAPI... - javadoc Constructing Javadoc information...
- javadoc Standard Doclet version 1.4.2
- javadoc Building tree for all the packages
and classes... - javadoc Building index for all the packages
and classes... - javadoc Building index for all classes...
- echo Compiling the java source files...
- javac Compiling 42 source files to
D\McCarthy\www\95-733\examples\struts1 - \src\VO
39Viewing the docs
40Write the client
- import java.io.File
- import java.io.IOException
- import java.math.BigDecimal
- import javax.xml.bind.JAXBContext
- import javax.xml.bind.JAXBException
- import javax.xml.bind.Marshaller
- import javax.xml.bind.UnmarshalException
- import javax.xml.bind.Unmarshaller
- import javax.xml.bind.ValidationEvent
- import javax.xml.bind.util.ValidationEventCollecto
r - // import java content classes generated by
binding compiler - import itemListAPI.
41 public class Main // This sample
application demonstrates how to enable validation
during // the unmarshal operations.
public static void main( String args )
try // create a JAXBContext
capable of handling classes generated into
// the itemListAPI package
JAXBContext jc JAXBContext.newInstance(
"itemListAPI" ) //
create an Unmarshaller Unmarshaller u
jc.createUnmarshaller() // enable
validation u.setValidating( true )
42 // in this example, we will allow the
Unmarshaller's default //
ValidationEventHandler to receive notification of
warnings // and errors which will be
sent to System.out. The default //
ValidationEventHandler will cause the unmarshal
operation // to fail with an
UnmarshalException after encountering the
// first error or fatal error.
// unmarshal an invalid itemList
instance document into a tree of Java
// content objects composed of classes from the
itemListAPI package. ItemList
itemList (ItemList)u.unmarshal(
new File( "itemList.xml" ) )
java.util.List list
itemList.getItem()
System.out.println("The length of the list is "
list.size())
43 int n list.size()
for(int k 0 k lt n k)
ItemType it (ItemType)list.get(k)
String st it.getName()
System.out.println(st)
catch( UnmarshalException ue )
// The JAXB specification does not
mandate how the JAXB provider // must
behave when attempting to unmarshal invalid XML
data. In // those cases, the JAXB
provider is allowed to terminate the
// call to unmarshal with an UnmarshalException.
System.out.println( "Caught
UnmarshalException" ) catch(
JAXBException je )
je.printStackTrace()
44Running the Client
- D\McCarthy\www\95-733\examples\struts1\src\VOgtant
JustJavaRun - Buildfile build.xml
- JustJavaRun
- echo java runtime
- java The length of the list is 3
- java pen
- java eraser
- java stapler
- BUILD SUCCESSFUL
- Total time 2 seconds