Monday, November 15, 2010

JAXB an overview

JAXB provides a fast and convenient way to bind between XML schemas and Java classes
JAXB provides two main features: the ability to marshal Java objects into XML
the ability to unmarshal XML back into Java objects
Project site: https://jaxb.dev.java.net/

Let us start by defining a simple example. Assume we want to create a simple application that is able to convert a java object into an XML representation.

First of all let me show a simple example of xml code with its related xsd file.
We want to create a schema that represent an xml format like this one:


<entity_list>
  <entity type="university" id="1294681486">
    <name>University of Trento</name>
    <address>Via Sommarive 14, Trento</address>
  </entity>
</entity_list>



Which correspond to the following XML schema


<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <xsd:element name="entity_list" type="entityListType" />
   <xsd:complexType name="entityListType">
   <xsd:sequence>
    <xsd:element ref="entity" minOccurs="0"maxOccurs="unbounded"/>
  </xsd:sequence>
  </xsd:complexType>


  <xsd:element name="entity" type="entityType" />
  <xsd:complexType name="entityType">
  <xsd:sequence>
  <xsd:element name="name" type="xsd:string" />
  <xsd:element name="address" type="xsd:string" />
  </xsd:sequence>
<xsd:attribute name="id" type="xsd:integer" use="required"/>
<xsd:attribute name="type" type="xsd:string" use="required"/>
  </xsd:complexType>
</xsd:schema>


In order to convert this object into a java representation, let us define such object (in this case let us define an entityType and entityListType). Note that this operation can be done directly by our environment (Eclipse or NetBeans as you want) or by command line using the command:
>~$ xjc *.xsd
(Libraries at https://jaxb.dev.java.net/)

Once done this, we simply have to create the methods for marshalling and unmarshalling. An example of such a code is shown here.


public class JAXBConvesion {
private static JAXBConvesion jconv;
Marshaller marshaller;
Unmarshaller unMarshaller;
transfer.xml.ObjectFactory factory;
SchemaFactory schemaFactory;
WriteXml writer;

           /**
        * Initialize objects that we are going to use. note that "transfer.xml" in the JAXBContext is the   
        * package in which we have our EntityType and EntityListType java objects.
        * This is a singleton class, we did this only for concurrency 
        **/
private JAXBConvesion() {
   try {
     JAXBContext jaxbContext = JAXBContext.newInstance("transfer.xml");
             marshaller = jaxbContext.createMarshaller();
     marshaller.setProperty("jaxb.formatted.output", new Boolean(true));
     factory = new transfer.xml.ObjectFactory();

     unMarshaller = jaxbContext.createUnmarshaller();
     schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
CustomValidationEventHandler validationEventHandler = new CustomValidationEventHandler();
            unMarshaller.setEventHandler(validationEventHandler);
    writer = WriteXml.getInstance();
} catch (Exception e) {
e.printStackTrace();
}

}
        /**
        * This method convert the java object into XML format representation
        * Constant.entityXml represent the path to the xml file that contains the xml.
        **/
public void marshal(Object res) {
try {
String result = null;
StringWriter sw = new StringWriter();
marshaller.marshal(res, sw);
result = sw.getBuffer().toString();
writer.writeXml(result, Constant.entityXml);
} catch (Exception e) {
e.printStackTrace();
System.exit(0);
}
}
        /**
        * This method convert the XML into java object representation
        * entity.xsd is the xml schema  for the entity 
        **/
public EntityListType unmarshalEntityListType() {

try {
Schema schema = schemaFactory.newSchema(new File("entity.xsd"));
unMarshaller.setSchema(schema);

JAXBElement<EntityListType> listElement =(JAXBElement<EntityListType>)unMarshaller.unmarshal(new File(Constant.entityXml));
EntityListType list = listElement.getValue();

return list;
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
} catch (JAXBException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}



public boolean handleEvent(ValidationEvent event) {
if (event.getSeverity() == ValidationEvent.WARNING) {
return true;
}
if ((event.getSeverity() == ValidationEvent.ERROR)
|| (event.getSeverity() == ValidationEvent.FATAL_ERROR)) {

System.out.println("Validation Error:" + event.getMessage());

ValidationEventLocator locator = event.getLocator();
System.out.println("at line number:" + locator.getLineNumber());
System.out.println("Unmarshalling Terminated");
return false;
}
return true;
}


public static JAXBConvesion getInstance() {
if (jconv == null) {
jconv = new JAXBConvesion();
}
return jconv;
}

No comments:

Post a Comment