JAXB – AN INTRODUCTION By R.S.RAMASWAMY
 

JAXB

Part 2

In the second part of this tutorial on JAXB, the author gives a lab-oriented example to demonstrate the practical method of using the JAXB API.Two demos , one for Unmarshalling & the other for creating and marshalling , are  given

It is always very important to learn a new concept , by hands-on-experimentation,after getting a bird's eye view.So, we now take up a very simple example and see the step by step procedure.

We are  using jwsdp1.4   &   jdk1.4.2

We have installed jwsdp1.4 in E: DRIVE. & installed jdk1.4.2 also in E: DRIVE.Our working folder is: g:\jaxbdemo

In this working folder (g:\jaxbdemo), let us first create a dtd file , named , library.dtd, as follows:

<?xml version="1.0" encoding="US-ASCII" ?>
<!ELEMENT library (fiction , biography ,science)>
<!ELEMENT fiction (book)+>
<!ELEMENT biography (book)+>
<!ELEMENT science (book)+>
<!ELEMENT book (#PCDATA)>

The following file (g:\jaxbdemo\library.xml) conforms to the above DTD.

<<?xml version="1.0" ?>
<!DOCTYPE library SYSTEM "library.dtd">
<library>

  <fiction>
    <book>IVANHOE</book>
<book>DAVID COPPERFIELD</book>
<book>WAR AND PEACE</book>
  </fiction>
  <biography>
    <book>LIFE OF GANDHI</book>
<book>ABRAHAM LINCOLN</book>
<book>MARX AND ENGELS</book>
  </biography>
  <science>
    <book>MAN THE UNKNOWN</book>
<book>EXPANDING UNIVERSE</book>
<book>ORIGIN OF SPECIES</book>
  </science>
</library>

Documentation by SUN & a number of tutorials in the web,( cited as reference at the end of this tutorial) assume that we are using ANT build file. It is desirable that any tutorial illustrates the procedure without using ANT first, because understanding ANT scripts ,is difficult for beginners. It is easier to understand the script ,after doing it the path/classpath way.This will give us a clearer picture.

We begin by setting HOME as follows:
SET JAVA_HOME=E:\JDK1.4.2
SET JWSDP_HOME=E:\JWSDP1.4

In this window, we give path as follows:
( one continuous line).
g:\jaxbdemo\setpath.bat
c:\windows\command;
e:\jdk1.4.2\bin;
e:\jwsdp1.4\jaxb\bin;
e:\jwsdp1.4\jwsdp-shared\bin

We find the following files in:
e:\jwsdp1.4\jaxb\lib.

jaxb-api.jar
jaxb-impl.jar
jaxb-libs.jar
jaxb-xjc.jar

We have to set classpath very carefully. as , directed by Sun's documentation. So, we create a batch file for this purpose.Let us call this batchfile 'setcpath.bat'

g:\jaxbdemo>edit setcpath.bat
>set classpath=g:\jaxbdemo;
e:\jwsdp1.4\jaxb\lib\jaxb-api.jar;
e:\jwsdp1.4\jaxb\lib\jaxb-impl.jar;
e:\jwsdp1.4\jaxb\lib\jaxb-libs.jar;
e:\jwsdp1.4\jaxb\lib\jaxb-xjc.jar;
e:\jwsdp1.4\jswdp-shared\lib\namespace.jar;
e:\jwsdp1.4\jwsdp-shared\lib\jax-qname.jar;
e:\jwsdp1.4\jwsdp-shared\lib\xsdlib.jar
d:\jdk1.4\lib\tools.jar;
e:\jwsdp1.4\jwsdp-shared\lib\relaxngDatatype.jar
e:\jwsdp1.4\jaxp\lib\jaxp.jar
e:\jwsdp1.4\jaxp\lib\endorsed\dom.jar;
e:\jwsdp1.4\jaxp\lib\endorsed\sax.jar;
e:\jwsdp1.4\jaxp\lib\endorsed\xalan.jar;
e:\jwsdp1.4\jaxp\lib\endorsed\xercesImpl.jar;

(this is as per Sun documentation given at the end of this file).
(all these typed in a single line).

We set classpath for our dos window by running the setcpath.bat file.After this, we run the following command:
g:\jaxbdemo>xjc -dtd library.dtd

{ we may get a message that dom4j.jar is required and it should be placed in lib folder. dom4j is available in jwsdp1.0\common\lib So, we copy dom4j.jar from jwsdp1.0\common\lib to jwsdp1.4\jaxb\lib folder) We can now run the command without any problem. }


we get the following display in the console:

parsing a schema...
compiling a schema...
generated\impl\runtime\UnmarshallingContext.java
generated\impl\runtime\SAXUnmarshallerHandler.java
generated\impl\runtime\PrefixCallback.java
generated\impl\runtime\Util.java
generated\impl\runtime\GrammarInfoFacade.java
generated\impl\runtime\UnmarshallerImpl.java
generated\impl\runtime\UnmarshallableObject.java
generated\impl\runtime\SAXMarshaller.java
generated\impl\runtime\ValidatableObject.java
generated\impl\runtime\ValidatingUnmarshaller.java
generated\impl\runtime\GrammarInfo.java
generated\impl\runtime\Discarder.java
generated\impl\runtime\SAXUnmarshallerHandlerImpl.java
generated\impl\runtime\InterningUnmarshallerHandler.java
generated\impl\runtime\MarshallerImpl.java
generated\impl\runtime\UnmarshallingEventHandler.java
generated\impl\runtime\ContentHandlerAdaptor.java
generated\impl\runtime\ErrorHandlerAdaptor.java
generated\impl\runtime\UnmarshallingEventHandlerAdaptor.java
generated\impl\runtime\NamespaceContextImpl.java
generated\impl\runtime\GrammarInfoImpl.java
generated\impl\runtime\NamespaceContext2.java
generated\impl\runtime\DefaultJAXBContextImpl.java
generated\impl\runtime\MSVValidator.java
generated\impl\runtime\AbstractUnmarshallingEventHandlerImpl.java
generated\impl\runtime\XMLSerializable.java
generated\impl\runtime\ValidatorImpl.java
generated\impl\runtime\XMLSerializer.java
generated\impl\runtime\ValidationContext.java
generated\impl\BiographyImpl.java
generated\impl\BookImpl.java
generated\impl\FictionImpl.java
generated\impl\JAXBVersion.java
generated\impl\LibraryImpl.java
generated\impl\ScienceImpl.java
generated\Biography.java
generated\Book.java
generated\Fiction.java
generated\Library.java
generated\ObjectFactory.java
generated\Science.java
generated\bgm.ser
generated\jaxb.properties

This is as should be.  No problem here.

This is as should be.  No problem here.

We need not give any package name, when giving the above command.
We need not give any -d directive( for output folder), either.So we get default package name as 'generated'.
We get all the generated files in subfolders of our working directory.cd to g:\jaxbdemo\generated.Let us list the files there.

G:\jaxbdemo\generated>dir
Directory of G:\jaxbdemo\generated
Biography.java
Book.java
Fiction.java
Library.java
ObjectFactory.java
Science.java
bgm.ser
jaxb.properties

  10 File(s) 15,323 bytes

What is found in g:\jaxbdemo\generated\Library.java?

package generated;
public interface Library {
/*
* {@link generated.Fiction}
* {@link generated.Biography}
* {@link generated.Science}
*/

java.lang.Object getContent();
void setContent(java.lang.Object value);
}

Thus, we understand that the 'generated'  folder  contains 'interface' files.

What do we find in  'generated\impl'  folder?

G:\jaxbdemo\GENERA~1\impl>dir
Directory of G:\jaxbdemo\GENERA~1\impl

BiographyImpl.java
BookImpl.java
FictionImpl.java
JAXBVersion.java
LibraryImpl.java
ScienceImpl.java

We now cd to 'generated\impl\runtime' folder.and list the files there.

G:\jaxbdemo\GENERA~1\impl\runtime>dir
Directory of G:\jaxbdemo\GENERA~1\impl\runtime

GrammarInfo.java
Discarder.java
SAXUnmarshallerHandlerImpl.java
InterningUnmarshallerHandler.java
MarshallerImpl.java
UnmarshallingEventHandler.java
ContentHandlerAdaptor.java
ErrorHandlerAdaptor.java
UnmarshallingEventHandlerAdaptor.java
NamespaceContextImpl.java
GrammarInfoImpl.java
NamespaceContext2.java
DefaultJAXBContextImpl.java
MSVValidator.java
AbstractUnmarshallingEventHandlerImpl.java
XMLSerializable.java
ValidatorImpl.java
XMLSerializer.java
ValidationContext.java
UnmarshallingContext.java
SAXUnmarshallerHandler.java
PrefixCallback.java
Util.java
GrammarInfoFacade.java
UnmarshallerImpl.java
UnmarshallableObject.java
SAXMarshaller.java
ValidatableObject.java
ValidatingUnmarshaller.java

  29 File(s) 177,213 bytes

So far, as it should be,as mentioned in the documentation by SUN.! The files in 'runtime' folder are common to all applications. But, 'generated' and 'impl' folders contain a mixture of example-specific as well as general source files.

Now, we should compile all these source files. Note the command very carefully.
g:\jaxbdemo>javac
generated\*.java generated\impl\*.java
generated\impl\runtime\*.java
( in a continuous line)

If there are any error messages, it can only be due to non-inclusion of any of the jar files mentioned above. Sometimes ( as the author did) , we make spelling mistakes in typing the name of the jar files or in their folder names. Unless we are able to compile these classes successfully, we CANNOT proceed further. It was found that we were able to compile without any problem,if we follow the steps meticulously.

Now, we are ready to write and test a simple demo for utilising these classes.

Let us create lesson.java as follows:
// g:\jaxbdemo\lesson.java
import java.util.*;
import javax.xml.bind.*;
import java.io.*;
import generated.*;
class lesson
{
publicstaticvoidmain(Stringargs[])
{
try
{
JAXBContextjContext=JAXBContext.newInstance("generated");
System.out.println("contextok");
Unmarshallerunmarshaller=Context.createUnmarshaller();
System.out.println("unmarshallerok");
Librarylib=(Library)unmarshaller.unmarshal(newFileInputStream("library.xml"));
System.out.println("libraryobjectready");
Fictionfiction=lib.getFiction();
System.out.println("fictiongroupisready");
Listlist1=fiction.getBook();
System.out.println("fiction-listisready!");
intn=list1.size();
System.out.println(""+n);
ListIteratork=list1.listIterator(0);
//becarefulaboutthecase!ListIterator
while(k.hasNext())
{
Objectob=k.next();
Bookbook1=(Book)ob;
System.out.println(book1.getContent());
}
}
catch(Exceptione1)
{System.out.println(""+e1);}
}
}

We can now compile lesson.java.
g:\jaxbdemo>javac lesson.java
(We are able to compile without hitch).
All that remains to be done is to run the program!We get the following result in the console.
G:\jaxbdemo>java lesson
context ok
unmarshaller ok
library object ready
fiction is ready
fiction-list is ready!
3
IVANHOE
DAVID COPPERFIELD
WAR AND PEACE

Thus, our effort in using JAXB is a SUCCESS!

If we go to e:\jwsdp1.4\jaxb\samples folder, we will find that there are 25 demo examples, for various situations.Source code for each example also has been given.

Readers are encouraged to study the samples and experiment. We can follow exactly same procedure

This release of JAXB is contained in several JAR files:
JAXB jar files (contained in jwsdp1.4/jaxb/lib) jaxb-api.jar
The javax.xml.bind interfaces and helper classes jaxb-xjc.jar
The JAXB RI binding compiler classes jaxb-impl.jar (formerly named jaxb-ri.jar)
The JAXB RI binding runtime framework classes jaxb-libs.jar
Supporting classes for the binding compiler and the binding runtime framework
JAXP jar files (contained in jwsdp-1.4/jaxp/lib and jwsdp-1.4/jaxp/lib/endorsed) jaxp-api.jar
The javax.xml.parsers and javax.xml.transform components of JAXP
sax.jar - The APIs and helper classes for the Simple API for XML (SAX)
dom.jar- The APIs and helper classes for the Document Object Model (DOM)
xercesImpl.jar (v2.3.0) - The implementation classes for the SAX and DOM parsers, as well as Xerces-specific implementations of the JAXP APIs
xalan.jar - Xalan is an XSLT processor for transforming XML documents into other document types
Other JAR files
jax-qname.jar (contained in jwsdp-1.4/jwsdp-shared/lib) - A class for handling QNames shared by several JAX* technologies
namespace.jar (contained in jwsdp-1.4/jwsdp-shared/lib) - Classes for handling XML namespace contexts shared by several JAX* technologies
xsdlib.jar (contained in jwsdp-1.4/jwsdp-shared/lib) - XML Schema type library shared by several JAX* technologies (formerly contained in jaxb-libs.jar)
relaxngDatatype.jar (contained in jwsdp-1.4/jwsdp-shared/lib) - RELAX NG datatype library shared by several JAX* technologies (formerly contained in jaxb-libs.jar)
ant.jar (contained in apache-ant/lib) - Ant 1.5.4

DTD

The JAXB RI is shipped with experimental DTD support, which lets you compile XML DTDs.
To compile a DTD test.dtd, run the XJC binding compiler as follows:
$ xjc.sh -dtd test.dtd - All the other command-line options of the XJC binding compiler can be applied, no matter what schema language you use. Similarly, the XJC ant <http://jakarta.apache.org/ant/> task supports DTD. No matter what schema language you use, the generated code will be no different. You'll use the same JAXB API to access the generated code.

As mentioned earlier, the recommended schema now is XML-SCHEMA. So, it will be useful if we consider a simple example in that category.

Let us now create a folder as g:\jaxbdem
In that folder, copy home.bat,setpath.bat from g:\jaxbdemo of previous lesson.
Then copy setcpath.bat from g:\jaxbdemo.
Change it to begin with g:\jaxbdem; instead of g:\jaxbdemo as our working directory now is g:\jaxbdem.
We will use the example given by Deepak Vohra in a recent web tutorial(with crucial corrections!.)
We edit catalog.xsd as follows:
g:\jaxbdem\catalog.xsd

<xsd:schemaxmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:elementname="catalog"type="catalogType"/>
<xsd:complexTypename="catalogType">
<xsd:sequence>
<xsd:elementref="journal"minOccurs="0"maxOccurs="unbounded"/>
</xsd:sequence>
<xsd:attributename="section"type="xsd:string"/>
<xsd:attributename="publisher"type="xsd:string"/>
</xsd:complexType>
<xsd:elementname="journal"type="journalType"/>
<xsd:complexTypename="journalType">
<xsd:sequence>
<xsd:elementref="article"minOccurs="0"maxOccurs="unbounded"/>
</xsd:sequence>
</xsd:complexType>
<xsd:elementname="article"type="articleType"/>
<xsd:complexTypename="articleType">
<xsd:sequence>
<xsd:elementname="title"type="xsd:string"/>
<xsd:elementname="author"type="xsd:string"/>
</xsd:sequence>
<xsd:attributename="level"type="xsd:string"/>
<xsd:attributename="date"type="xsd:string"/>
</xsd:complexType>
</xsd:schema>

Let us now generate the java source files> >xjc catalog.xsd It will be noticed that we did not specify the option -schema . It is the default. As we have given correct home,path & classpath, the source files are generated as before and we get a list of all the files thus created in the console. Now also we have 'generated', 'generated\impl' and 'generated\impl\runtime' folders under g:\jaxbdem folder. We now compile the source files. g:\jaxbdem>javac generated\*.java generated\impl\*.java generated\impl\runtime\*.java. We get compilation without any problem atall.
We are now ready to use these classes. We will create a java object tree and then send it to a file as xml document. The generated xml file will satisfy the schema specified in catalog.xsd.

//g:\jaxbdem>editlesson.java
importjava.util.*;
importjavax.xml.bind.*;
importjava.io.*;
importgenerated.*;
classlesson
{publicstaticvoidmain(Stringargs[])
{
try
{
JAXBContextJContext=JAXBContext.newInstance("generated");
System.out.println("contextok");
ObjectFactoryfactory=newObjectFactory();
System.out.println("objectfactoryready");
Catalogcatalog=(Catalog)(factory.createCatalog());
System.out.println("catalogready");
catalog.setSection("JavaTechnology");
catalog.setPublisher("IBMdeveloperWorks");
System.out.println
("catalogattributesset");
Journaljournal=(Journal)(factory.createJournal());
java.util.ListjournalList=catalog.getJournal();
journalList.add(journal);
Articlearticle=(Article)(factory.createArticle());
article.setLevel("Intermediate");
article.setDate("January-2004");
article.setTitle("ServiceOrientedArchitectureFrameworks");
article.setAuthor("NaveenBalani");
java.util.ListarticleList=journal.getArticle();
articleList.add(article);
System.out.println("treeready");
Marshallermarshaller=jContext.createMarshaller();
System.out.println("marshallerready");
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,Boolean.TRUE);
marshaller.marshal(catalog,newFileOutputStream("catalog.xml"));
System.out.println("javatreeconvertedintoxml&filed");
}
catch(Exceptione1)
{System.out.println(""+e1);}
}
}

Wecannowcompilelesson.java
>javaclesson.java
Ifweexecutewegetthefollowingmessagesintheconsole.
<consolemessage>
contextok
marshallerok
objectfactoryready
catalogready
catalogattributesset
ok
javatreeconvertedintoxml&filed


We can now verify by editing the catalog.xml file.( g:\jaxbdem\catalog.xml)
We find it as shown below.

<?xmlversion="1.0"encoding="UTF-8"standalone="yes"?>
<catalogpublisher="IBMdeveloperWorks"section="JavaTechnology">
<journal>
<articledate="January-2004"level="Intermediate">
<title>ServiceOrientedArchitectureFrameworks</title>
<author>NaveenBalani</author>
</article>
</journal>
</catalog>

That completes our tutorial.

SUN-DOCUMENT FOR REFERENCE:
List of Sample Apps
Many of the sample applications have been given more descriptive names in this release.

samples/bind-choice (formerly part of SampleApp9)
This sample application illustrates how a choice model group is bound to a Java interface by the <jaxb:globalBindings bindingStyle="modelGroupBinding"/> customization.

samples/catalog-resolver
This example demonstrates how to use the new "-catalog" compiler switch for resolving external entity references.

samples/create-marshal (formerly SampleApp3)
This sample application demonstrates how to use the ObjectFactory class to create a Java content tree from scratch and marshal it to XML data. It also demonstrates how to add content to a JAXB List property.

samples/datatypeconverter (formerly SampleApp7)
This sample application is very similar to the inline-customize sample application (formerly SampleApp6), but illustrates an easier, but not as robust, <jaxb:javaType> customization.

samples/external-customize (formerly SampleApp8)
This sample application is identical to the datatypeconverter sample application (formerly SampleApp7) except that the binding customizations are contained in an external binding file.

samples/fix-collides (formerly part of SampleApp9)
Another binding customization example that illustrates how to resolve name conflicts. Run "ant fail" first to see the compiler output and then look at binding.xjb to see how the errors were resolved. Running "ant" will use the binding customizations to resolve the name conflicts while compiling the schema.

samples/inline-customize (formerly SampleApp6)
This sample application demonstrates how to customize the default binding produced by the XJC binding compiler.

samples/modify-marshal (formerly SampleApp2)
This sample application demonstrates how to modify a java content tree and marshal it back to XML data.

samples/namespace-prefix
This sample application demonstrates how to use the new JAXB RI Marshaller property "com.sun.xml.bind.namespacePrefixMapper" to customize the namespace prefixes generated during marshalling.

samples/ondemand-validate (formerly SampleApp5)
This sample application demonstrates how to validate a Java content tree at runtime.

samples/partial-unmarshalling
In this example, the input document will be unmarshalled a small chunk at a time, instead of unmarshalling the whole document at once.

samples/pull-parser
This sample app demonstrates how a pull-parser can be used with JAXB to increase the flexibility of processing.

samples/subgroup-extend
This example shows how the use of the jxb:implClass customization and substitution groups can be used to inject virtual functions into the derived Java hierarchy. It compares two equivalent ways of achieving the same processing, but one is much simpler than the other (search for the "enlightened" boolean flag in the code).
samples/ubl
This sample application processes a UBL order instance and writes a report to the screen.

samples/unmarshal-read (formerly SampleApp1)
This sample application demonstrates how to unmarshal an instance document into a Java content tree and access data contained within it.

samples/unmarshal-validate (formerly SampleApp4)
This sample application demonstrates how to enable validation during the unmarshal operations.

samples/xml-channel
This example demonstrates how to use one communication channel (such as a socket) to send multiple XML messages, and how that channel can be combined with JAXB.

samples/xml-stylesheet
This example demonstrates how the behavior of the marshalling process can be customized. In this example, an <?xml-stylesheet ... ?> processing instruction is inserted into the marshalled document.
Sample applications that illustrate JAXB RI vendor extensions <vendor.html>.

samples/character-escape
This example shows how you can use the new JAXB RI Marshaller property "com.sun.xml.bind.characterEscapeHandler" to change the default character escaping behavior.

samples/dtd
This sample application illustrate some of the DTD support available in the JAXB RI's extension mode. Please refer to the Vendor Extensions <vendor.html> page for more detail.

samples/element-substitution
This sample application illustrates how W3C XML Schema substitution groups are supported in JAXB RI's extension mode. Please refer to the Vendor Extensions <vendor.html> page for more detail.

samples/locator-support
This sample shows how to use the new non-standard locator support. By following the instructions in the readme.txt file, you can cause all of the generated impl classes to implement a new interface that provides more information about error locations. When a ValidationEvent happens on your content tree, simply retrieve the object and cast it down to com.sun.xml.bind.extra.Locatable.

samples/relaxng
This example shows how you can use experimental RELAX NG support.

samples/synchronized-methods
This sample shows how to use the new non-standard synchronized method support. By following the instructions in the readme.txt, you can cause all of the generated impl class methods signatures to contain the "synchronized" keyword.

samples/type-substitution
This sample app demonstrates type substitution using the W3C XML Schema Part 0: Primer international purchase order schema.

samples/vendor-extensions
This example demonstrates how to use the <jxb:serializable> and <jxb:superClass> vendor extensions provided by Sun's JAXB RI.

JAXB Part 1

Other Tutorials by R.S. RAMASWAMY

JAVA SECURITY- PACKAGES JCA/JCE



Use of this website constitutes acceptance of the AllAppLabs.com Terms and Conditions