http://in.geocities.com/rsramsam/jaxb.htm

       

                JAXB

          AN INTRODUCTION

             Java Architecture for  XML-BINDING

------------------------------------------------------------

by 

R.S.RAMASWAMY

(rsramsam@yahoo.co.in)

 

------------------------------------------------------------

(First published in DeveloperIQ..MAY-2005)

 (available  in  http://www.roseindia.net/   also)

 

 

                        (part-1)

    JAX-pack, now being referred to as JWSDP,is a very important development in J2EE.In the previous editions (July,August,October-2004)  we had covered the basics of JAXP( Java -API for XML Processing), dealing with  DOM,SAX,JDOM,TrAX etc. Part-1 of this tutorial deals with general theory of JAXB and its importance in binding XML to Java classes.

 

     JAXB  is a component  part of JAX set of API's.  SUN MICRO SYSTEMS is giving a lot of importance to XML WebServices and within a short span, has released a number of revisions of JWSDP ( Java WebService Development pack). It began with JWSDP1.0 and now is running JWSDP1.5. (Version numbers have become very important in modern software field, because, there is so much development taking place almost every month.

This is true in J2EE/OpenSource & DotNet  too. )

 

It appears that JAXB is available for downloading,  as a part of JWSDP only, and cannot be downloaded as such. So, we should download JWSDP , to gain access to JAXB for experimentation.We are using JWSDP1.4.

 

     JWSDP is essentially for XML-WebService work. The constituent parts of this package are  JAX-RPC, JAXM(Messaging)& JAXR(Registry).There is also SAAJ ( SOAP with Attachment)not to be confused with JAAS ( Java security). (Hopefully, we will cover these topics , in coming editions).JAXP takes care of DOM,SAX  & XSLT .

  JAXB allows Java developers to access and process XML data without having to know XML or XML processing. For example, there's no need to create or use a SAX parser or write callback methods. It makes use of a  given schema of an XML document and automatically generates the required Java classes, corresponding to that schema.( DeveloperIQ is now providing a detailed workshop on DTD, a form of Schema).Modern trend focuses on XML representation of Data, for ease of exchange in web-service and otherwise. If we have an xml representation of a database, we can use JAXB to create a tree of Java objects  and work with them in Java idiom..This is known as XML-Databinding. .

    Validation is an important part of any XML document. Unlike  HTML, XML tags are user-defined. This is what gives XML its power and utility. But, at the same time, to make it really useful, each such XML document should have a 'schema'....Something like Data Definition in SQL. It should be carefully noted that 'schema' is a general term. In the earlier days of XML, the only schema that was known and used was DTD (Document-type-definition). Even today, DTD is said to be the most prevalent 'schema' in use and best known, among developers.

    However, DTD was found to have a number of limitations.Microsoft is credited with the proposal for an alternative to DTD in the very early days of XML.It was known as 'XML Schema'.The proposal was submitted to the W3C (World-wide Web Consortium), which is the standards body for XML , HTML and related topics and was later adopted by W3C with some modifications.

    'XML-Schema' is considered to be better than DTD, for a number of reasons. First, unlike a DTD, an XML-Schema is itself an XML document. Secondly, it has provision for greater variety of data-types than are available in DTD.It supports Name-space.

********************************************

 

 JAXB Mapping of XML Schema Built-in Data Types 

XML Schema Type

Java Data Type

xsd:string

java.lang.String

xsd:integer

java.math.BigInteger

xsd:int

int

xsd.long

long

xsd:short

short

xsd:decimal

java.math.BigDecimal

xsd:float

float

xsd:double

Double

xsd:boolean

boolean

xsd:byte

byte

xsd:QName

javax.xml.namespace.QName

xsd:dateTime

java.util.Calendar

xsd:base64Binary

byte[]

xsd:hexBinary

byte[]

xsd:unsignedInt

long

xsd:unsignedShort

int

xsd:unsignedByte

short

xsd:time

java.util.Calendar

xsd:date

java.util.Calendar

xsd:anySimpleType

java.lang.String

 

********************************************

 

However, an XML-Schema is of rather large size compared to the corresponding DTD representation .

     Because of this 'limitation' of XML-Schema, another validation scheme , known as Relax-NG , developed by another standards organization, known as OASIS  ,is also prevalent.This schema is comparatively compact. Be it DTD or XML-Schema or Relax-NG, all these topics are heavy reading and belong properly to the study of XML by itself rather than as applied XML in Java.Though , XML webservice is built entirely on XML and SOAP, it is possible for a developer to build an effective webservice application in ASP.net & AXIS, without going into the details of XML.It may be said to be the main merit of ASP.net,that it hides the details of implementation and allows the Application developer to concentrate on the business-logic on hand.So does, Apache's AXIS.But, at some stage, a good understanding  of the inner working details becomes useful, for trouble-shooting and advanced work.But, the danger of 'missing the forest for the trees' , also is there , if we get into implementation details, too deeply.

 

   The problem in JAXB, is that it originally dealt with DTD and later switched over to XML-Schema (And many books were written about this earliest version of JAXB and are not suitable now).. SUN  promotes  an alternative to the SOAP standard , known  as Eb-XML , being developed under the auspices of UNESCO & OASIS.This is said to be more attuned to the needs of Vericals ( specific industries ). JAXB attempts to incorporate support for Relax-NG also, as it is from OASIS..

 

When JAXB work started, it  dealt with  DTD only, because at that time the XML-Schema had not been standardized.Later versions ,are primarily meant to work with XML-schema and DTD support  is  only experimental. Same for Relax-NG,but for an entirely different reason, because work on that is still progressing.  These areas are developing so fast that books and articles become out-dated, very quickly, but they are not withdrawn from the web/market, thus  confusing the readers. Information is getting 'dated', rapidly.With so many acronyms around, it is better  that we try to understand what they mean and their context , before diving in.Hence, the present tutorial attempts to give such an overview.

 

(The JWSDP1.4 package has the sub-folders for

JAXP,JAXB,JAXR,JAX-RPC,JSTL,SAAJ,XWS-SECURITY,XMLDSIG-xml digital signature).

 

------

   The latest release of JWSDP is JWSDP1.5.

( Jan-2005).The following three items can be said to be new or  special improvements  the JWSDP pack.

     a)  Java Streaming XML Parser

     b)  XML Digital Signature

     c)  JAXB(1.04)

--------------------------------------

a)  (SJSXP)(Sun Java Streaming XML Parser ).

------------------------------

The Streaming API for XML (StAX)provides a stream-based API for reading and writing XML documents. The StAX approach is also known as "pull" parsing. This sounds like Microsoft's method of XML processing, in DotNet platform.The DotNet platform has a class known as XmlTextReader which provides a stream API which also is based on 'pull' model.The usual SAX method is known as 'Push' model.The 'pull' model is said to be more efficient in some cases.(Interested readers can refer to page 307-322 of a very valuable book..

'ASP.Net..Tips,Tutorials and Code' by a team of authors led by Scott Mitchell(Techmedia).)

 

 

b)The Java-XML- Digital Signature package in the WSDP provides  a standard way for Java developers to access digital signature services. To quote: ***Using the XML Digital Signature APIs found in the WSDP, developers can sign and validate digital content and represent the signatures in an XML format. The signatures provide a standard way to verify that content originated from a known source and was not altered during transmission***.

 

c) Coming now to JAXB,in the words of Sun Documentation,

 

***The Java Architecture for XML Binding (JAXB) project  provides a standard API for automating the mapping between XML documents and Java objects. Using JAXB, a developer can compile a schema into Java classes that provide support for marshaling, unmarshaling, accessing, updating, and validating. The main goal of JAXB is to relieve the developer of these tasks so that they can be more productive and be exposed to fewer XML-oriented issues. JAXB 1.0.4 provides support for a subset of XML Schema and experimental support for RelaxNG. RelaxNG is a simplified XML schema system sponsored by the Oasis group. JAXB is currently integrated with JAX-RPC for easily transporting objects across the wire.***.

 

   There is common agreement in Industry that XML-Schema  is better than DTD.

In a DTD, element content is mostly limited to strings whereas an XML-Schema can set the data type of elements to very specific types such as integers and date. However, with thousands  of DTD based XML documents , being in use today, it is vital that compatibility is maintained. Tools are said  to be available for automating the conversion of DTD into an equivalent Schema.

( readers can see p114 of XML-Unleashed by

Michael Morrison..Techmedia, for details).

 

   If to create a valid XML document, we begin by creating a DTD.(Document-type-Definition),such DTD creation  is more difficult than creating a well-formed XML document, straight away! If the beginner can first create an XML document and from that generate a DTD automatically, it will be easier job.AlphaWorks of IBM created a Java library, DDbE(Data Descriptors by Example),to make it easier for beginners to create the DTD. The above library fulfils that role.For working properly, DDbE requires XML4j  parser from IBM. ( see p.636 of the above book).Student readers can check up the current status of such automated tools. Though unconventional, this approach, is easier and saves a lot of labour. We get a readymade framework which can then be suitably modified. The recommended method in JAXB is not to begin with DTD but to use an

XML-Schema.

--------------------------------------------

   Let us now try to get familiar with the technical terms in JAXB environment.

 

   We begin from an XML-Schema , first. An XML schema uses XML syntax to describe the relationships among elements, attributes and entities in an XML document. The purpose of an XML schema is to define a class of XML documents that must adhere to a particular set of structural rules and data constraints. 

 

There is a  command  in JAXB/bin known as xjc .(Actually, it is a batch file which uses jaxb binding compiler.). We can invoke this batch file from the command line (after setting the required path & classpath, to be defined soon).The command is like :

 >xjc    books.xsd , where books.xsd is the XML-Schema file being used.The command has a few optional arguments, to specify the name of target directory, package name etc. Sometimes, we may prefer to use an existing DTD as reference and in such cases, we can give -dtd  as option and then specify the DTD file).

 

 When we run this command,it generates a number of Java source files in layered packages.There is a default binding rule and it is generally sufficient. In case, we need more fine-tuned behaviour, we can supply such a binding schema also as an argument.

 

    These source files are then compiled.

Using these classes, we can convert an XML document which is based on the specified schema into corresponding java objects in a tree, different from the usual DOM tree and more efficient. This process of converting an XML document into Java objects is called Unmarshalling.

 

In the context of JAXB, a Java application is a client application that uses the JAXB binding framework to unmarshal XML data, validate and modify Java content objects, and marshal Java content back to XML data.

---

To paraphrase from Sun's Documentation,

***   

The general steps in the JAXB data binding process are:

1.  Generate classes. An XML schema is used as input to the JAXB binding compiler to generate JAXB classes based on that schema.

2.  Compile classes. All of the generated classes, source files, and application code must be compiled.

3.  Unmarshal. XML documents written according to the constraints in the source schema are unmarshalled by the JAXB binding framework.

4.  Generate content tree. The unmarshalling process generates a content tree of data objects instantiated from the generated JAXB classes; this content tree represents the structure and content of the source XML documents.

5.  Validate (optional). The unmarshalling process optionally involves validation of the source XML documents before generating the content tree.

6.  Process  the content. The client application can modify the XML data represented by the Java content tree by means of interfaces generated by the binding compiler.

7.  Marshal. The processed content tree is marshalled out to one or more XML output documents. The content may be validated before marshalling.

------------------------------------------------------------

The following code-snippet  illustrates the process of unmarshalling.

( we are assuming an xml document named 'library'.)."<package-name>" refers to the package in which the auto-genrated class files due to xjc command are available.

 ------------------------------------------- 

JAXBContext        context =

JAXBContext.newInstance("<package-name>") ;

Unmarshaller         unmarshaller =

         context.createUnmarshaller() ;

Library           library =

    (Library)unmarshaller.unmarshal

  (new     FileInputStream("library.xml")) ;

-------------------------------------------------------

library.xml is an example XML document that conforms to the schema file from which the JAXB-generated Java classes and interfaces are created, and Library is the root object in the XML document. Hereafter, we can use java  idiom to manipulate the objects in the library.

-------------------------------------------

An application can directly create java objects by using the ObjectFactory created by the xjc process.First, we get an instance of ObjectFactory.This factory instance is then used to create a library object. 

We create objects in that library tree, set attributes for such objects& add the objects to the root.Finally, an instance of Marshaller class, is created and used to send the object to xml file.

---------------------------------------

ObjectFactory   factory=

              new ObjectFactory();

Library  library = factory.createLibrary();

Book    book1 = factory.createBook();

book1.setTitle("java today");

book1.setPrice("200Rs");

library.add(book1);

Marshaller   marshaller =   context.createMarshaller();

marshaller.marshal(library, new FileOutputStream("library.xml")) ;

============================================

   Thus, the process of converting a java-object tree to xml is known as Marshalling.

To, recapitulate,

Unmarshalling means creating a java object tree  for an XML document.

Marshalling means  converting a javaobject tree into equivalent XML.

==========================================

With these introductory ideas, we take up a simple example in the next part of this tutorial.

************************************************************

 

                      ( 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).

Run setcpath again.

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.

********************************************

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

{

    public static void main(String args[])

    {

    try

    {

    JAXBContext         jContext=

JAXBContext.newInstance("generated");

    System.out.println("context ok");

 

    Unmarshaller   unmarshaller =

                       jContext.createUnmarshaller() ;

    System.out.println("unmarshaller  ok");

 

    Library         lib = (Library)unmarshaller.unmarshal

                 (new   FileInputStream("library.xml")) ;

 

 System.out.println("library object ready");

 

   Fiction      fiction = lib.getFiction();

  System.out.println("fiction group is ready");

 

   List   list1 = fiction.getBook();

System.out.println("fiction-list is ready!");

    

      int  n = list1.size();

      System.out.println(""+n);

 

  ListIterator   k = list1.listIterator(0);

// be careful about the case! ListIterator

 

     while(k.hasNext())

         {

         Object  ob = k.next();

         Book   book1 = (Book)ob;

    System.out.println(book1.getContent());

         }  

    }

    catch(Exception e1)

    {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

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:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">

 <xsd:element name="catalog" type="catalogType"/>

 <xsd:complexType name="catalogType">

  <xsd:sequence>

   <xsd:element ref="journal"  minOccurs="0" maxOccurs="unbounded"/>

  </xsd:sequence>

  <xsd:attribute name="section" type="xsd:string"/>

  <xsd:attribute name="publisher" type="xsd:string"/>

 </xsd:complexType>

 <xsd:element name="journal" type="journalType"/>

 <xsd:complexType name="journalType">

  <xsd:sequence>

   <xsd:element ref="article"  minOccurs="0" maxOccurs="unbounded"/>

  </xsd:sequence>

 </xsd:complexType>

 <xsd:element name="article" type="articleType"/>

 <xsd:complexType name="articleType">

  <xsd:sequence>

   <xsd:element name="title" type="xsd:string"/>

   <xsd:element name="author" type="xsd:string"/>

  </xsd:sequence>

  <xsd:attribute name="level" type="xsd:string"/>

  <xsd:attribute name="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>edit lesson.java

import java.util.*;

import javax.xml.bind.*;

import java.io.*;

import generated.*;

class lesson

{    public static void main(String args[])

    {

    try

    {

    JAXBContext jContext=JAXBContext.newInstance("generated");

    System.out.println("context ok");

 ObjectFactory factory=new ObjectFactory();

 System.out.println("object factory ready");

Catalog  catalog=(Catalog)(factory.createCatalog());

      System.out.println("catalog  ready");

 catalog.setSection("Java Technology");

 catalog.setPublisher("IBM developerWorks");

 System.out.println

("catalog attributes  set ");   

    Journal journal=(Journal)(factory.createJournal());

    java.util.List journalList=catalog.getJournal();

    journalList.add(journal);

    Article article=(Article)(factory.createArticle());

    article.setLevel("Intermediate");

    article.setDate("January-2004");

    article.setTitle("Service Oriented Architecture Frameworks");

    article.setAuthor("Naveen Balani");

    java.util.List  articleList=journal.getArticle();

     articleList.add(article);

        System.out.println("tree ready");

  Marshaller marshaller=jContext.createMarshaller();

      System.out.println("marshaller  ready");

marshaller.setProperty( Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE );

marshaller.marshal(catalog, new FileOutputStream("catalog.xml"));

 

    System.out.println("java tree converted into xml & filed");

 

 

    }

    catch(Exception e1)

    {System.out.println(""+e1);    }

    }

}

============================================

   We can now compile lesson.java

   >javac lesson.java

   If we execute we get the following messages in the console.

<console message>  

context ok

marshaller ok

object factory ready

catalog  ready

 catalog attributes set

ok

java tree converted into xml & filed

=======================================

We can now verify by editing the catalog.xml file.( g:\jaxbdem\catalog.xml)

We find it as shown below.

=====================================

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>

<catalog publisher="IBM developerWorks" section="Java Technology">

    <journal>

        <article date="January-2004" level="Intermediate">

            <title>Service Oriented Architecture Frameworks</title>

            <author>Naveen Balani</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.

                         HOME PAGE

 

 

 

 

  

 

 

 

         

 

 

  

 

 

 

 

 

 

 



 

   

1

1 1