.:: CODE SNIPPET ::.

"Your time is limited, so don't waste it living someone else's life"

JAXB overview and practice


Overview

Brief understanding about JAXB
JAXB (Java Architecture for XML Binding) is one of Java SE APIs. It provides basically a fast and convenient way to bind Java objects with the structural document, in particular XML document. That means you can load an XML document content and create a Java object tree (unmarshalling). Otherwise, you can also simply persist any Java object into a XML document (marshalling).
What does it help us?
All we need to define is a schema contains: definition of Java classes, elements, attributes and constraints between the elements. JAXB takes care of all the rest jobs. We can use JAXB in any certain case such as loading the configuration files, saving processing context,…

How does it work?
JAXB architecture
JAXB Architecture

* Schema compiler: Binds a source schema to a set of schema-derived program elements. The binding is described by an XML-based binding language.
* Schema generator: Maps a set of existing program elements to a derived schema. The mapping is described by program annotations.
* Binding runtime framework: Provides unmarshalling (reading) and marshalling (writing) operations for accessing, manipulating, and validating XML content using either schema-derived or existing program elements.
Processing summary
Processing

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.
1. Compile classes: All of the generated classes, source files, and application code must be compiled.
1. Unmarshal: XML documents written according to the constraints in the source schema are unmarshalled by the JAXB binding framework. Note that JAXB also supports unmarshalling XML data from sources other than files and documents, such as DOM nodes, string buffers, SAX sources, and so forth.
1. 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.
1. Validate (optional): The unmarshalling process involves validation of the source XML documents before generating the content tree. Note that if you modify the content tree in Step 6, you can also use the JAXB Validate operation to validate the changes before marshalling the content back to an XML document.
1. Process content: The client application can modify the XML data represented by the Java content tree by using interfaces generated by the binding compiler.
1. Marshal: The processed content tree is marshalled out to one or more XML output documents. The content may be validated before marshalling.

Using JAXB

* Generate the java class from the predefined schema.
We just use the compiler ‘xjc’ included in the Java SE package. We can easily check it out via terminal command:

xjc -version

Usage of this compiler tool with the schema named ‘po.xsd’ as below, assume that we place the xsd file at location ‘/home/user/work/schema’. In any terminal we execute the commands:

cd /home/user/work/schema
xjc -p company.vn.study.po po.xsd

We will then generate the java files in package company.com.po
Item.java
ObjectFactory.java
PurchaseOrderType.java
USAddress.java.

* Create a test program with generated classes to test marshalling and unmarshalling
Create a new java project with package company.vn.study.po, and import the generated file in step 1 in that package.
Create a new test class with java main function, and do some stuff to marshal and unmarshal.

private static final String DIR_SCHEMA = "/home/user/working/doc/study/java/jee/jaxb/schema-sample";
public static void main(String[] args)
    {
        JAXBContext context = null;
        Unmarshaller unmarshaller = null;
        Marshaller marshaller = null;
        InputStream is = null;
        OutputStream out = null;
        ObjectFactory factory = null;
        try
        {
            factory = new ObjectFactory();
            context = JAXBContext.newInstance("company.vn.study.po");
            unmarshaller = context.createUnmarshaller();
            marshaller = context.createMarshaller();
            is = new FileInputStream(DIR_SCHEMA + "/order.xml");
            out = new FileOutputStream(DIR_SCHEMA + "/order1.xml");

            Source source = new StreamSource(is);
            JAXBElement root = unmarshaller.unmarshal(source, PurchaseOrderType.class);
            PurchaseOrderType po = root.getValue();
            // ---------

            root = factory.createPurchaseOrder(po);
            marshaller.marshal(root, out);
        }
        catch (UnmarshalException e)
        {
            System.out.println("Unmarshal exception catch");
        }
        catch (JAXBException e)
        {
            e.printStackTrace();
        }
        catch (FileNotFoundException e)
        {
            e.printStackTrace();
        }

    }
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: