analytics

Sunday, July 8, 2012

JAXB


JAXB stands for Java Architecture for XML Binding

 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. 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-Data binding.

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.

Using JAXB annotation we do convert Java object to / from XML file. Converting a Java object into a XML file is called Marshalling and converting XML content into a java object is called Un-marshalling.

·         Marshalling – Convert a Java object into a XML file.
·         Un-marshalling – Convert XML content into a Java Object

Technologies used in this article
1.      JDK 1.6
2.      JAXB 2.0

Working with JAXB is easy, just annotate object with JAXB annotation, later use jaxbMarshaller.marshal() or jaxbMarshaller.unmarshal() to do the object / XML conversion.
 JAXB Dependency
No extra JAXB libraries are required if you are using JDK1.6 or above, because JAXB is bundled in JDK 1.6. For JDK < 1.6 we need to put “jaxb-api.jar” and “jaxb-impl.jar” on our project classpath.
JAXB Annotation
For object that needs to convert to / from XML file, it have to annotate with JAXB annotation. The annotation are pretty self-explanatory, you can refer to this JAXB guide for detail explanation.
package com.myproj.core;

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

@XmlRootElement
public class Customer {

         String name;
         int age;
         int id;

         public String getName() {
                 return name;
         }

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

         public int getAge() {
                 return age;
         }

         @XmlElement
         public void setAge(int age) {
                 this.age = age;
         }

         public int getId() {
                 return id;
         }

         @XmlAttribute
         public void setId(int id) {
                 this.id = id;
         }

}


Convert Object to XML

JAXB marshalling example, convert customer object into a XML file. The jaxbMarshaller.marshal() contains a lot of overloaded methods, find one that suit your output.
package com.myproj.core;
 
import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
 
public class JAXBExample {
         public static void main(String[] args) {
 
           Customer customer = new Customer();
           customer.setId(100);
           customer.setName("Kamesh");
           customer.setAge(29);
 
           try {
 
                 File file = new File("C:\\file.xml");
                 JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
                 Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
 
                 // output pretty printed
                 jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
 
                 jaxbMarshaller.marshal(customer, file);
                 jaxbMarshaller.marshal(customer, System.out);
 
               } catch (JAXBException e) {
                 e.printStackTrace();
               }
 
         }
}

Output

Convert XML to java Object

JAXB un-marshalling example, convert a XML file content into a customer object. The jaxbMarshaller.unmarshal()contains a lot of overloaded methods, find one that suit yours.
package com.myproj.core;
 
import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
 
public class JAXBExample {
         public static void main(String[] args) {
 
          try {
 
                 File file = new File("C:\\file.xml");
                 JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
 
                 Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
                 Customer customer = (Customer) jaxbUnmarshaller.unmarshal(file);
                 System.out.println(customer);
 
           } catch (JAXBException e) {
                 e.printStackTrace();
           }
 
         }
}

Output
Customer [name=Kamesh, age=29, id=100]

JAXB Architecture




A JAXB implementation consists of the following architectural components:
·         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.

The JAXB Binding Process

 

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. Note that JAXB also supports unmarshalling XML data from sources other than files/documents, such as DOM nodes, string buffers, SAX Sources, and so forth.
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. Note that if you modify the content tree in Step 6, below, you can also use the JAXB Validate operation to validate the changes before marshalling the content back to an XML document.
6.     Process 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.

More about Unmarshalling
Unmarshalling provides a client application the ability to convert XML data into JAXB-derived Java objects.
More about Marshalling
Marshalling provides a client application the ability to convert a JAXB-derived Java object tree back into XML data. By default, the Marshaller uses UTF-8 encoding when generating XML data.
Client applications are not required to validate the Java content tree before marshalling. There is also no requirement that the Java content tree be valid with respect to its original schema to marshal it back into XML data.

 

More about Validation
Validation is the process of verifying that an XML document meets all the constraints expressed in the schema. JAXB 1.0 provided validation at unmarshal time and also enabled on-demand validation on a JAXB content tree. JAXB 2.0 only allows validation at unmarshal and marshal time. A web service processing model is to be lax in reading in data and strict on writing it out. To meet that model, validation was added to marshal time so one could confirm that they did not invalidate the XML document when modifying the document in JAXB form.

No comments:

Post a Comment