Archive

Archive for the ‘JAXB’ Category

JAXB Sample application

December 21, 2010 Leave a comment

Java Architecture for XML Binding (JAXB) allows java developer to map java classes to XML representations and XML to java classes.

JAXB provides two main features:
Marshalling -> Java objects to XML
Unmarshalling -> XML to Java objects.

Library used
JAXB RI Utility.

1.Create XML schema

First step of the process is to create the XML Schema to structure the XML document.

<?xml version="1.0" encoding="UTF-8"?>
<schema xmlns="http://www.w3.org/2001/XMLSchema" 
        targetNamespace="http://www.example.org/Customer"
	    xmlns:tns="http://www.example.org/Customer" 
	    elementFormDefault="qualified">
 	<element name="Customer" type="tns:Customer"/>
 	<complexType name="Customer">
	    <sequence>
	    	<element name="name" minOccurs="1">
	    		<simpleType>
	    			<restriction base="string">
	    			    <maxLength value="15"/>
	    			</restriction>
	    		</simpleType>
	    	</element>
	    	<element name="address">
	    	    <simpleType>
	    	        <restriction base="string">
	    	        	<maxLength value="50"/>
	    	        </restriction>
	    	    </simpleType>
	    	</element>
	    	<element name="city">
	    		<simpleType>
	    			<restriction base="string">
	    				<maxLength value="10"/>
	    			</restriction>
	    		</simpleType>
	    	</element>
	    	<element name="phone" minOccurs="1">
	    		<simpleType>
	    			<restriction base="string">
	    				<length value="10"/>
	    			</restriction>
	    		</simpleType>
	    	</element>
	    </sequence>
	</complexType>
</schema>

2. Create XML document
Create a XML document which is satisfying the rules defined in XML Schema.

<?xml version="1.0" encoding="UTF-8"?>
<Customer xmlns="http://www.example.org/Customer" 
			  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
			  xsi:schemaLocation="http://www.example.org/Customer Customer.xsd">
  <name>My name</name>
  <address>Tokiyo</address>
  <city>France</city>
  <phone>1111111111</phone>
</Customer>

3. Generate java objects equaivalent to XSD:
Generate java classes equivalent to XSL Schema using xjc.bat in JAXB-RI library.

Snapshot of creating java classes using jaxb-ri library.

4. Write Java class to bind XML to java objects ( Unmarshalling ):
Using JAXB API’s write a java class to unmarshall xml string into equivalent java objects. From the java objects the content in the xml file can be retrieved .

package com.room.jaxb.demo.test;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.transform.stream.StreamSource;

import com.room.jaxb.demo.Customer;

public class JAXBHandler {

	public static Object parse(String xml,String path){
		System.out.println("---- starts parsing -----"+xml);
		JAXBContext jaxbContext=null;
		Unmarshaller unMarshaller=null;
		Object out=null;
		try {
			jaxbContext=JAXBContext.newInstance(path);
			unMarshaller=jaxbContext.createUnmarshaller();
			out=unMarshaller.unmarshal(new StreamSource(new StringReader(xml)));
			System.out.println("----- Response :"+out);
		} catch (JAXBException e) {
			e.printStackTrace();
		}
		return out;
	}

	public static void main(String[] args) {
	   try {
		File file =new File("D:/SOASpace/JAXBDemo/src/com/room/jaxb/demo/Customer.xml");
		FileInputStream fis=null;
		DataInputStream dis=null;
		String path="com.room.jaxb.demo";
		   if(!file.exists() || file.length() < 0 ){
			   System.out.println("---- There is no file exists -----");
		   }else{
			   fis=new FileInputStream(file);
			   dis=new DataInputStream(fis);
			   BufferedReader br=new BufferedReader(new InputStreamReader(dis));
			   String strLine;
			   StringBuffer buffer=new StringBuffer();
			   while((strLine=br.readLine())!=null){
				  buffer.append(strLine);
			   }
			  JAXBElement  jaxbElement=(JAXBElement)parse(buffer.toString(), path);
			  Customer cust=jaxbElement.getValue();
			  System.out.println("-- Name --:"+cust.getName());
			  System.out.println("-- Address ---:"+cust.getAddress());
			  System.out.println("-- City ---:"+cust.getCity());
			  System.out.println("--- Phone ---:"+cust.getPhone());
		   }
		dis.close();
	} catch (FileNotFoundException e) {
		e.printStackTrace();
	} catch (IOException e) {
		e.printStackTrace();
	}
	}
}

5. Validating the input against XML Schema while UnMarshalling

public static Object parse(String xml,String path){
System.out.println(&quot;---- starts parsing -----&quot;+xml);
JAXBContext jaxbContext=null;
Unmarshaller unMarshaller=null;
Object out=null;
try {
jaxbContext=JAXBContext.newInstance(path);
unMarshaller=jaxbContext.createUnmarshaller();
//validating the input xml equivalent to XSD
SchemaFactory schemaFactory=SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema=schemaFactory.newSchema(new File(&quot;D:/SOASpace/JAXBDemo/src/com/room/jaxb/demo/Customer.xsd&quot;));
unMarshaller.setSchema(schema);
unMarshaller.setEventHandler(
new ValidationEventHandler() {
public boolean handleEvent(ValidationEvent ve) {
boolean flag=true;
if(ve.getSeverity()!=ValidationEvent.WARNING){
ValidationEventLocator vel=ve.getLocator();
System.out.println(&quot;Line:Col[&quot; + vel.getLineNumber() +
&quot;:&quot; + vel.getColumnNumber() +
&quot;]:&quot; + ve.getMessage());
flag=false;
}
return flag;
}
});
out=unMarshaller.unmarshal(new StreamSource(new StringReader(xml)));
System.out.println(&quot;----- Response :&quot;+out);
} catch (JAXBException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
}
return out;
}

 

In schema , if the maxLength of the name element exceeds 15 character the above code will raise exception. we can wrap this exception as our custom exception and can be display a valid understandable message to the client.

Advertisements
Categories: JAXB