Wednesday, December 21, 2011

Composite Pattern - Java Example

Composite can be used when clients should ignore the difference between compositions of objects and individual objects. If programmers find that they are using multiple objects in the same way, and often have nearly identical code to handle each of them, then composite is a good choice; it is less complex in this situation to treat primitives and composites as homogeneous.

Structure

Composite pattern in UML.
Component
  • is the abstraction for all components, including composite ones
  • declares the interface for objects in the composition
  • (optional) defines an interface for accessing a component's parent in the recursive structure, and implements it if that's appropriate
Leaf
  • represents leaf objects in the composition .
  • implements all Component methods
Composite
  • represents a composite Component (component having children)
  • implements methods to manipulate children
  • implements all Component methods, generally by delegating them to its children

Composite pattern in LePUS3.

Variation

As it is described in Design Patterns, the pattern also involves including the child-manipulation methods in the main Component interface, not just the Composite subclass. More recent descriptions sometimes omit these methods.

Example

The following example, written in Java, implements a graphic class, which can be either an ellipse or a composition of several graphics. Every graphic can be printed. In algebraic form,
Graphic = ellipse | GraphicList
       GraphicList = empty | Graphic GraphicList
It could be extended to implement several other shapes (rectangle, etc.) and methods (translate, etc.).
import java.util.List;
import java.util.ArrayList;
 
/** "Component" */
interface Graphic {
 
    //Prints the graphic.
    public void print();
}
 
/** "Composite" */
class CompositeGraphic implements Graphic {
 
    //Collection of child graphics.
    private List<Graphic> mChildGraphics = new ArrayList<Graphic>();
 
    //Prints the graphic.
    public void print() {
        for (Graphic graphic : mChildGraphics) {
            graphic.print();
        }
    }
 
    //Adds the graphic to the composition.
    public void add(Graphic graphic) {
        mChildGraphics.add(graphic);
    }
 
    //Removes the graphic from the composition.
    public void remove(Graphic graphic) {
        mChildGraphics.remove(graphic);
    }
}
 
/** "Leaf" */
class Ellipse implements Graphic {
 
    //Prints the graphic.
    public void print() {
        System.out.println("Ellipse");
    }
}
 
/** Client */
public class Program {
 
    public static void main(String[] args) {
        //Initialize four ellipses
        Ellipse ellipse1 = new Ellipse();
        Ellipse ellipse2 = new Ellipse();
        Ellipse ellipse3 = new Ellipse();
        Ellipse ellipse4 = new Ellipse();
 
        //Initialize three composite graphics
        CompositeGraphic graphic = new CompositeGraphic();
        CompositeGraphic graphic1 = new CompositeGraphic();
        CompositeGraphic graphic2 = new CompositeGraphic();
 
        //Composes the graphics
        graphic1.add(ellipse1);
        graphic1.add(ellipse2);
        graphic1.add(ellipse3);
 
        graphic2.add(ellipse4);
 
        graphic.add(graphic1);
        graphic.add(graphic2);
 
        //Prints the complete graphic (four times the string "Ellipse").
        graphic.print();
    }
}

Tuesday, December 20, 2011

Composite Pattern

Motivation

There are times when a program needs to manipulate a tree data structure and it is necessary to treat both Branches as well as Leaf Nodes uniformly. Consider for example a program that manipulates a file system. A file system is a tree structure that contains Branches which are Folders as well as Leaf nodes which are Files. Note that a folder object usually contains one or more file or folder objects and thus is a complex object where a file is a simple object. Note also that since files and folders have many operations and attributes in common, such as moving and copying a file or a folder, listing file or folder attributes such as file name and size, it would be easier and more convenient to treat both file and folder objects uniformly by defining a File System Resource Interface.

Intent

  • The intent of this pattern is to compose objects into tree structures to represent part-whole hierarchies.
  • Composite lets clients treat individual objects and compositions of objects uniformly.

Implementation

The figure below shows a UML class diagram for the Composite Pattern:
Composite Pattern Implementation - UML Class Diagram

  • Component - Component is the abstraction for leafs and composites. It defines the interface that must be implemented by the objects in the composition. For example a file system resource defines move, copy, rename, and getSize methods for files and folders.
  • Leaf - Leafs are objects that have no children. They implement services described by the Component interface. For example a file object implements move, copy, rename, as well as getSize methods which are related to the Component interface.
  • Composite - A Composite stores child components in addition to implementing methods defined by the component interface. Composites implement methods defined in the Component interface by delegating to child components. In addition composites provide additional methods for adding, removing, as well as getting components.
  • Client - The client manipulates objects in the hierarchy using the component interface.
A client has a reference to a tree data structure and needs to perform operations on all nodes independent of the fact that a node might be a branch or a leaf. The client simply obtains reference to the required node using the component interface, and deals with the node using this interface; it doesn�t matter if the node is a composite or a leaf.

Applicability & Examples

The composite pattern applies when there is a part-whole hierarchy of objects and a client needs to deal with objects uniformly regardless of the fact that an object might be a leaf or a branch.

Example - Graphics Drawing Editor.

In graphics editors a shape can be basic or complex. An example of a simple shape is a line, where a complex shape is a rectangle which is made of four line objects. Since shapes have many operations in common such as rendering the shape to screen, and since shapes follow a part-whole hierarchy, composite pattern can be used to enable the program to deal with all shapes uniformly.
In the example we can see the following actors:
  • Shape (Component) - Shape is the abstraction for Lines, Rectangles (leafs) and and ComplexShapes (composites).
  • Line, Rectangle (Leafs) - objects that have no children. They implement services described by the Shape interface.
  • ComplexShape (Composite) - A Composite stores child Shapes in addition to implementing methods defined by the Shape interface.
  • GraphicsEditor (Client) - The GraphicsEditor manipulates Shapes in the hierarchy.
Alternative Implementation: Note that in the previous example there were times when we have avoided dealing with composite objects through the Shape interface and we have specifically dealt with them as composites (when using the method addToShape()). To avoid such situations and to further increase uniformity one can add methods to add, remove, as well as get child components to the Shape interface. The UML diagram below shows it:
Composite Pattern Alternative Implementation - UML Class Diagram


Specific problems and implementation

Graphics Editors use composite pattern to implement complex and simple graphics as previously explained.
File System implementations use the composite design pattern as described previously.

Consequences

  • The composite pattern defines class hierarchies consisting of primitive objects and composite objects. Primitive objects can be composed into more complex objects, which in turn can be composed.
  • Clients treat primitive and composite objects uniformly through a component interface which makes client code simple.
  • Adding new components can be easy and client code does not need to be changed since client deals with the new components through the component interface.

Related Patterns

Decorator Pattern - Decorator is often used with Composite. When decorators and composites are used together, they will usually have a common parent class. So decorators will have to support the Component interface with operations like Add, Remove, and GetChild.

Known Uses

File System Implementation as discussed previously.

Composite Design Pattern

Add caption

Ignoring Inheritance with @XmlTransient

In previous articles I have covered how to map inheritance relationships in JAXB and EclipseLink MOXy.  In this example I will describe how to remove an inheritance relationship in JAXB by leveraging @XmlTransient at the type level.


Java Model

Base

In this example we want all of our domain objects to have an id property.  We will accomplish this by having all of our domain objects extend the same base class (Base). Since this base class is not relevant to the domain model we will tell JAXB to ignore it by marking it @XmlTransient.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package blog.inheritance.xmltransient;
 
import javax.xml.bind.annotation.XmlTransient;
 
@XmlTransient
public abstract class Base {
 
    private int id;
 
    public int getId() {
        return id;
    }
 
    public void setId(int id) {
        this.id = id;
    }
 
}

Customer

Since the parent class has been marked @XmlTransient the id property will be treated as part of the child classes.  In the Customer class we will demonstrate this by including the id property in the propOrder specified on @XmlType.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package blog.inheritance.xmltransient;
 
import java.util.List;
 
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
 
@XmlRootElement
@XmlType(propOrder={"id", "name", "address", "phoneNumbers"})
public class Customer extends Base {
 
    private String name;
    private Address address;
    private List<PhoneNumber> phoneNumbers;
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public Address getAddress() {
        return address;
    }
 
    public void setAddress(Address address) {
        this.address = address;
    }
 
    @XmlElement(name="phone-number")
    public List<PhoneNumber> getPhoneNumbers() {
        return phoneNumbers;
    }
 
    public void setPhoneNumbers(List<PhoneNumber> phoneNumbers) {
        this.phoneNumbers = phoneNumbers;
    }
 
}

Address

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package blog.inheritance.xmltransient;
 
public class Address extends Base {
 
    private String street;
 
    public String getStreet() {
        return street;
    }
 
    public void setStreet(String street) {
        this.street = street;
    }
 
}

PhoneNumber

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package blog.inheritance.xmltransient;
 
public class PhoneNumber extends Base {
 
    private String number;
 
    public String getNumber() {
        return number;
    }
 
    public void setNumber(String number) {
        this.number = number;
    }
 
}


Demo Code

Below is the demo code that can be used to run this example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package blog.inheritance.xmltransient;
 
import java.io.File;
 
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
 
public class Demo {
 
    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(Customer.class);
 
        Unmarshaller unmarshaller = jc.createUnmarshaller();
        Customer customer = (Customer) unmarshaller.unmarshal(new File("input.xml"));
 
        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(customer, System.out);
    }
 
}

XML (input.xml)

In the XML you will notice that there are no inheritance indicators present.  The properties of the base class are simply treated as properties of the respective subclasses:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<?xml version="1.0" encoding="UTF-8"?>
<customer>
   <id>12</id>
   <name>Jane Doe</name>
   <address>
      <id>34</id>
      <street>1 A Street</street>
   </address>
   <phone-number>
      <id>45</id>
      <number>555-1111</number>
   </phone-number>
   <phone-number>
      <id>67</id>
      <number>555-2222</number>
   </phone-number>
</customer>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

JAXB - self-referential-objects-and-downcasting

You can solve the issue by marking the IdentifiableObject class with @XmlTransient: Nodes
package forum8257098;

import java.util.List;

import javax.xml.bind.annotation.*;

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Nodes {

    @XmlElement(name="node")
    private List<Node> nodes;

}
Node
package forum8257098;

import javax.xml.bind.annotation.*;

@XmlRootElement
public class Node extends IdentifiableObject {

    @XmlElement
    private Node parent;

    @XmlElement
    private String aField;

}
IdentifiableObject
package forum8257098;

import javax.xml.bind.annotation.*;

@XmlTransient
public class IdentifiableObject {

    @XmlID
    @XmlAttribute
    private String id;

    @XmlAttribute
    private String name;

}
Demo
package forum8257098;

import java.io.File;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

public class Demo {

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(Nodes.class);

        Unmarshaller unmarshaller = jc.createUnmarshaller();
        File xml = new File("src/forum8257098/input.xml");
        Nodes nodes = (Nodes) unmarshaller.unmarshal(xml);

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(nodes, System.out);
    }

}
Input/Output
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<nodes>
    <node name="Node 1" id="49ad1cb6-f6fe-47f9-a544-4a1c6337c4a5">
        <aField>This is Node 1</aField>
    </node>
    <node name="Node 2" id="0a1d1895-49e1-4079-abc1-749c304cc5a2">
        <parent name="Node 1" id="49ad1cb6-f6fe-47f9-a544-4a1c6337c4a5"/>
        <aField>This is Node 2</aField>
    </node>
</nodes>
For More Information

Sunday, December 18, 2011

JAXB & Collection Properties

In this post will examine the different options JAXB offers for representing collections in XML.  We will look at the following annotations:
  • @XmlElement
  • @XmlElementWrapper
  • @XmlList
  • @XmlList and @XmlAttribute
  • @XmlList and @XmlValue


Java Model

For this example we will use the following model.   We will apply different JAXB annotations to observe the effect it has on the XML representation.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import java.util.*;
import javax.xml.bind.annotation.*;
 
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Customer {
 
    private List<String> emailAddresses;
     
    public Customer() {
        emailAddresses = new ArrayList<String>();
    }
 
    public List<String> getEmailAddresses() {
        return emailAddresses;
    }
 
    public void setEmailAddresses(List<String> emailAddresses) {
        this.emailAddresses = emailAddresses;
    }
 
}

Demo Code

The following code will be used to convert the Customer object to XML.  We will examine the impact of changing the metadata on the XML representation.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
 
public class Demo {
 
    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(Customer.class);
 
        Customer customer = new Customer();
        customer.getEmailAddresses().add("janed@example.com");
        customer.getEmailAddresses().add("jdoe@example.org");
 
        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(customer, System.out);
    }
}

Default

By default each item in the collection will be marshalled to an XML element.

1
2
3
4
<customer>
    <emailAddresses>janed@example.com</emailAddresses>
    <emailAddresses>jdoe@example.org</emailAddresses>
</customer>

@XmlElement

We can control the name of the XML element a collection item is marshalled to by using the @XmlElement annotation.

1
2
3
4
5
6
7
8
9
10
11
import java.util.*;
import javax.xml.bind.annotation.*;
 
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Customer {
 
    @XmlElement(name="email-address")
    private List<String> emailAddresses;
 
}

The following is the corresponding XML output:

1
2
3
4
<customer>
    <email-address>janed@example.com</email-address>
    <email-address>jdoe@example.org</email-address>
</customer>

@XmlElementWrapper

Sometimes we want to add a grouping element to organize our collection data.  This is done using the @XmlElementWrapper annotation.

1
2
3
4
5
6
7
8
9
10
11
12
import java.util.*;
import javax.xml.bind.annotation.*;
 
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Customer {
 
    @XmlElementWrapper(name="email-addresses")
    @XmlElement(name="email-address")
    private List<String> emailAddresses;
 
}

The following is the corresponding XML output:

1
2
3
4
5
6
<customer>
    <email-addresses>
        <email-address>janed@example.com</email-address>
        <email-address>jdoe@example.org</email-address>
    </email-addresses>
</customer>

@XmlList

We can also represent our collection data as space seperated text.  This is done using the @XmlList annotation.

1
2
3
4
5
6
7
8
9
10
11
import java.util.*;
import javax.xml.bind.annotation.*;
 
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Customer {
 
    @XmlList
    private List<String> emailAddresses;
 
}

The following is the corresponding XML output:

1
2
3
4
<customer>
    <emailAddresses>janed@example.com jdoe@example.org</emailAddresses>
</customer>
  

@XmlList and @XmlAttribute

Since @XmlList allows us to represent a collection in a single piece of text it is also compatible with an XML attribute.

1
2
3
4
5
6
7
8
9
10
11
12
import java.util.*;
import javax.xml.bind.annotation.*;
 
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Customer {
 
    @XmlList
    @XmlAttribute
    private List<String> emailAddresses;
 
}

The following is the corresponding XML output:

1
2
<customer
    emailAddresses="janed@example.com jdoe@example.org"/>

@XmlList and @XmlValue

Since @XmlList allows us to represent a collection in a single piece of text it is also compatible with a single text node.

1
2
3
4
5
6
7
8
9
10
11
12
import java.util.*;
import javax.xml.bind.annotation.*;
 
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Customer {
 
    @XmlList
    @XmlValue
    private List<String> emailAddresses;
 
}

The following is the corresponding XML output:

1
<customer>janed@example.com jdoe@example.org</customer>

Thursday, December 15, 2011

JAXB - Code Sample

JAXB uses annotations to indicate the central elements.

Table 1.
Annotation Description
@XmlRootElement(namespace = "namespace") Define the root element for a XML tree
@XmlType(propOrder = { "field2", "field1",.. }) Allows to define the order in which the fields are written in the XML file
@XmlElement(name = "neuName") Define the XML element which will be used. Only need to be used if the neuNeu is different then the JavaBeans Name

2.2. Usage

Create a new Java project called "de.vogella.xml.jaxb".
Create the following domain model with the JAXB annotations.
package de.vogella.xml.jaxb.model;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

@XmlRootElement(name = "book")
// If you want you can define the order in which the fields are written
// Optional
@XmlType(propOrder = { "author", "name", "publisher", "isbn" })
public class Book {

 private String name;
 private String author;
 private String publisher;
 private String isbn;

 // If you like the variable name, e.g. "name", you can easily change this
 // name for your XML-Output:
 @XmlElement(name = "bookName")
 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 public String getAuthor() {
  return author;
 }

 public void setAuthor(String author) {
  this.author = author;
 }

 public String getPublisher() {
  return publisher;
 }

 public void setPublisher(String publisher) {
  this.publisher = publisher;
 }

 public String getIsbn() {
  return isbn;
 }

 public void setIsbn(String isbn) {
  this.isbn = isbn;
 }

}

   
package de.vogella.xml.jaxb.model;

import java.util.ArrayList;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;

//This statement means that class "Bookstore.java" is the root-element of our example
@XmlRootElement(namespace = "de.vogella.xml.jaxb.model")
public class Bookstore {

 // XmLElementWrapper generates a wrapper element around XML representation
 @XmlElementWrapper(name = "bookList")
 // XmlElement sets the name of the entities
 @XmlElement(name = "book")
 private ArrayList<Book> bookList;
 private String name;
 private String location;

 public void setBookList(ArrayList<Book> bookList) {
  this.bookList = bookList;
 }

 public ArrayList<Book> getBooksList() {
  return bookList;
 }

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 public String getLocation() {
  return location;
 }

 public void setLocation(String location) {
  this.location = location;
 }
}

   
Create the following test program for writing and reading the XML file.
package test;

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

import de.vogella.xml.jaxb.model.Book;
import de.vogella.xml.jaxb.model.Bookstore;

public class BookMain {

 private static final String BOOKSTORE_XML = "./bookstore-jaxb.xml";

 public static void main(String[] args) throws JAXBException, IOException {

  ArrayList<Book> bookList = new ArrayList<Book>();

  // create books
  Book book1 = new Book();
  book1.setIsbn("978-0060554736");
  book1.setName("The Game");
  book1.setAuthor("Neil Strauss");
  book1.setPublisher("Harpercollins");
  bookList.add(book1);

  Book book2 = new Book();
  book2.setIsbn("978-3832180577");
  book2.setName("Feuchtgebiete");
  book2.setAuthor("Charlotte Roche");
  book2.setPublisher("Dumont Buchverlag");
  bookList.add(book2);

  // create bookstore, assigning book
  Bookstore bookstore = new Bookstore();
  bookstore.setName("Fraport Bookstore");
  bookstore.setLocation("Frankfurt Airport");
  bookstore.setBookList(bookList);

  // create JAXB context and instantiate marshaller
  JAXBContext context = JAXBContext.newInstance(Bookstore.class);
  Marshaller m = context.createMarshaller();
  m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
  m.marshal(bookstore, System.out);

  Writer w = null;
  try {
   w = new FileWriter(BOOKSTORE_XML);
   m.marshal(bookstore, w);
  } finally {
   try {
    w.close();
   } catch (Exception e) {
   }
  }

  // get variables from our xml file, created before
  System.out.println();
  System.out.println("Output from our XML File: ");
  Unmarshaller um = context.createUnmarshaller();
  Bookstore bookstore2 = (Bookstore) um.unmarshal(new FileReader(
    BOOKSTORE_XML));

  for (int i = 0; i < bookstore2.getBooksList().toArray().length; i++) {
   System.out.println("Book " + (i + 1) + ": "
     + bookstore2.getBooksList().get(i).getName() + " from "
     + bookstore2.getBooksList().get(i).getAuthor());
  }

 }
}

   
If you run the BookMain a XML file will be created from the object. Afterwards the file is read again and the object are created again.

Wednesday, December 14, 2011

The Beginners Guide to JAXB

  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.
*******************************************