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

10 comments:

Hüsnü78 said...

Samsun
Nevşehir
Van
Bartın
Edirne
4L4

Per2i said...

Yalova
Hatay
Muş
Bursa
Mersin
AJ82Q

Alihan said...

İstanbul Lojistik
Zonguldak Lojistik
Konya Lojistik
Ağrı Lojistik
Ordu Lojistik
OUR

49C54Jesse138DE said...

F6469
Siirt Lojistik
Bolu Şehir İçi Nakliyat
Çerkezköy Çekici
Bybit Güvenilir mi
Kırşehir Lojistik
Tunceli Evden Eve Nakliyat
Muş Şehir İçi Nakliyat
Eskişehir Parça Eşya Taşıma
Karaman Lojistik

AA513Gordon48125 said...

29E6B
Tekirdağ Parça Eşya Taşıma
Urfa Parça Eşya Taşıma
Sivas Şehirler Arası Nakliyat
Ünye Koltuk Kaplama
Edirne Şehir İçi Nakliyat
Şırnak Şehirler Arası Nakliyat
Yalova Şehirler Arası Nakliyat
Mardin Evden Eve Nakliyat
Ardahan Şehir İçi Nakliyat

8BF5FAllison4EA02 said...

500A3
binance indirim kodu %20

8A3E4PhilipEB73E said...

034F2
Karabük Canlı Sohbet Ücretsiz
rastgele sohbet uygulaması
kars bedava görüntülü sohbet sitesi
canli sohbet chat
çankırı ucretsiz sohbet
düzce görüntülü sohbet kızlarla
Antalya Canlı Sohbet
Edirne En İyi Görüntülü Sohbet Uygulamaları
burdur mobil sohbet bedava

Anonymous said...

تنظيف مجالس G0dR83VICv

Anonymous said...

D4AA7A452B
fake takipçi

Anonymous said...

049151A365
kayıt ol coin kazan
telegram coin botları güvenilir mi
coin kazan
coin kazandıran oyunlar
telegram coin kasma nedir

Post a Comment

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