Monday, October 4, 2010

DataTypeConverter usage in JAXB

JAXB : DataTypeConverter

Accessing the actual value as-it-is using JAVA API will be pain in some cases. For instance, list of values get stored in attribute with comma separation. Now, these value has to be retrieved as List object rather String object, then only it make sense and simple to use.

We are extending the sample written in JAXB Sample post to explain DataTypeConverter and XMLAdapter.

fruits.xsd

<?xml version="1.0" encoding="utf-8"?>
<schema targetNamespace="http://mycompany.org/jaxbsample"
 xmlns="http://www.w3.org/2001/XMLSchema" xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified"
 xmlns:jaxb="http://java.sun.com/xml/ns/jaxb" jaxb:version="2.1">
 <annotation>
  <appinfo>
   <jaxb:schemaBindings>
    <jaxb:package name="jaxbexample.model" />
   </jaxb:schemaBindings>
  </appinfo>
 </annotation>


 <element name="Fruits">
  <complexType>
   <sequence>
    <element name="Fruit" maxOccurs="unbounded">
     <complexType>
      <attribute name="name" type="string" />
      <attribute name="qty" type="int" />
      <attribute name="listValue" type="string">
       <annotation>
        <appinfo>
         <jaxb:property>
          <jaxb:baseType>
           <jaxb:javaType
            name="Object"
            parseMethod="jaxbexample.DataTypeConverter.parseStringToList"
            printMethod="jaxbexample.DataTypeConverter.printListToString" />
          </jaxb:baseType>
         </jaxb:property>
        </appinfo>
       </annotation>
      </attribute>
     </complexType>
    </element>
   </sequence>
  </complexType>
 </element> 
</schema>

jaxbexample.DataTypeConverter is a JAVA file and it has two methods parseStringToList, printListToString. In the time of generating JAXB beans, Adapter1.java is get created in jaxbexamples.model package.

DataTypeConverter.java

package jaxbexample;

import java.util.ArrayList;
import java.util.List;

public class DataTypeConverter {

 /** This method called in the time of unmarshalling
  * XML to Java
  * @param value
  * @return
  */
 public static List<String> parseStringToList(String value) {
  
  List<String> list = new ArrayList<String>();
  if (null == value || "".equals(value))
   return list;

  
  String[] strs = value.split(",");
  for (String str : strs) {
   list.add(str);
  }

  return list;
 }

 /** This method called in the time of marshalling
  * Java to XML
  * @param val
  * @return
  */
 public static String printListToString(List<String> val) {

  if (null == val)
   return null;

  StringBuilder sb = new StringBuilder();
  for (String str : val) {
   if (sb.length() > 0)
    sb.append(",");
   sb.append(str);
  }

  return sb.toString();
 }
}

JAXBAdapterSample.java

package jaxbexample;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

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

import jaxbexample.model.Fruits;
import jaxbexample.model.Fruits.Fruit;

public class JAXBAdapterSample {

 public static void main(String[] args) throws Exception {

  String filename = "./jaxbexample/fruits.xml";
  InputStream is = new FileInputStream(filename);

  Fruits fruits = (Fruits) unmarshallObject(is);

  for (Fruit fruit : fruits.getFruit()) {
   System.out.println("Name : " + fruit.getName() + " Qty:"
     + fruit.getQty());

   fruit.setQty(fruit.getQty() + 1);
   int i = 1;
   for (String possiblefruit : (List<String>) fruit.getListValue()) {
    System.out.println(i++ + ". " + possiblefruit);
   }
  }
 }

 public static Object unmarshallObject(InputStream is) throws Exception {
  String packageName = "jaxbexample.model";
  JAXBContext context = JAXBContext.newInstance(packageName);
  Unmarshaller unmarshaller = context.createUnmarshaller();
  Object jaxbObject = unmarshaller.unmarshal(is);
  return jaxbObject;

 }

 public static void marshallObject(Object o, String filename)
   throws Exception {
  String packageName = "jaxbexample.model";
  File f = new File(filename);

  JAXBContext context = JAXBContext.newInstance(packageName);
  Marshaller marshaller = context.createMarshaller();
  marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
  marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");

  OutputStream fos = new FileOutputStream(f);
  marshaller.marshal(o, fos);

  try {
   fos.close();
  } finally {
   // do nothing
  }
 }

}

output

Name : Apple Qty:10
1. Apple
2. Orange
3. Banana
Name : Orange Qty:5
1. Apple
2. Orange
3. Banana
Name : Banana Qty:20
1. Apple
2. Orange
3. Banana

Recent Posts

Unix Commands | List all My Posts

Texts

This blog intended to share the knowledge and contribute to JAVA Community such a way that by providing samples and pointing right documents/webpages. We try to give our knowledege level best and no guarantee can be claimed on truth. Copyright and Terms of Policy refer blogspot.com