JAXB & XML Utils




  • Convert XML2Java Using JAXB and XML2Java
  • Find the word count in one paragraph
  • Masking XML data with desired text




  • Convert XML2Java Using JAXB
This utility talks about how to convert XML  to Java objects using JAXB with the help of predefined and well executed jar files

JAXB
------
 JAXB stands for Java Architecture for XML Binding (JAXB)


















Test XML
---------
For sample application let's take the XML which has Music directors name,date of birth and recent movie. By using JAXB we will be able to generate List of Music Director Objects.



<?xml version="1.0" encoding="UTF-8"?>
<Music>
<MusicDirector>
<Name>Ilayaraja</Name>
<DOB>3-June-1943</DOB>
<RecentMovie>Sriramarajyam</RecentMovie>
<MovieLanguage>Telugu</MovieLanguage>
</MusicDirector>
<MusicDirector>
<Name>A.R.Rahman</Name>
<DOB>06-Jan-1966</DOB>
<RecentMovie>Robo</RecentMovie>
<MovieLanguage>Tamil</MovieLanguage>
</MusicDirector>
<MusicDirector>
<Name>YuvanSakarRaja</Name>
<DOB>31-August-1979</DOB>
<RecentMovie>Mangatha</RecentMovie>
<MovieLanguage>Tamil</MovieLanguage>
</MusicDirector>
</Music>

To generate Java objects from the XML we need to define data types first , which object has to convert in which data type that one we should define. for that we need to create one XSD (XML Schema Definition).


Here is the simple steps to create xsd by pumping XML and by using trang.jar file


1) Generate XSD using trang.jar file by giving XML as input

















      


-I means Input as XML  Music.xml
-O mean output as XSD  Music.xsd

Once xsd got generated we need to generate Java Objects by using xjc command




















So, finally JAXB will generate the Java Objects like Music.java, Music Director.java and ObjectFactory.java files

Now we need to write client program using main method then start using the generated Java Objects.

Steps to create java objects from xml

Create JAXBContext object from the new instance XML root element   like this 

        JAXBContext context = JAXBContext.newInstance(new Class[] {Music.class} );
Create Unmarshall Object for accessing the xml elements
         Unmarshaller unMarshaller = context.createUnmarshaller();
         Music music = (Music)unMarshaller.unmarshal(new File("D:/Music/Music.xml"));

Prepare list of Music Objects and access the data from the XML

       musicList = music.getMusicDirector();
System.out.println("----List of Music Directors in xml :"+musicList.size()+" members");
for(MusicDirector musicDirector : musicList){
System.out.println("Name Of Music Director :"+musicDirector.getName());
System.out.println("Music Direcotr DOB :"+musicDirector.getDOB());
System.out.println("Music Director Language:"+musicDirector.getMovieLanguage());
System.out.println("Director recent Movie "+musicDirector.getRecentMovie());
System.out.println("---------------------------------------");
}
     
Complete Program


package com.music;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

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

public class MusicClientClass {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
try{
List<MusicDirector> musicList = new ArrayList();
JAXBContext context = JAXBContext.newInstance(new Class[] {Music.class} );
Unmarshaller unMarshaller = context.createUnmarshaller();
Music music = (Music)unMarshaller.unmarshal(new File("D:/Music/Music.xml"));
musicList = music.getMusicDirector();
System.out.println("----List of Music Directors in xml :"+musicList.size()+" members");
for(MusicDirector musicDirector : musicList){
System.out.println("Name Of Music Director :"+musicDirector.getName());
System.out.println("Music Direcotr DOB :"+musicDirector.getDOB());
System.out.println("Music Director Language:"+musicDirector.getMovieLanguage());
System.out.println("Director recent Movie "+musicDirector.getRecentMovie());
System.out.println("---------------------------------------");
}


}catch(JAXBException jaxEx){
jaxEx.printStackTrace();
}

}

}



OutPut from the Music.xml
-------------------------------------


----List of Music Directors in xml :3 members
Name Of Music Director :Ilayaraja
Music Direcotr DOB :3-June-1943
Music Director Language:Telugu
Director recent Movie Sriramarajyam
---------------------------------------
Name Of Music Director :A.R.Rahman
Music Direcotr DOB :06-Jan-1966
Music Director Language:Tamil
Director recent Movie Robo
---------------------------------------
Name Of Music Director :YuvanSakarRaja
Music Direcotr DOB :31-August-1979
Music Director Language:Tamil
Director recent Movie Mangatha
---------------------------------------

Java2XML


I am done with how to convert xml2java and now let me convert java object to XML file. Thing is need to do revers for the above one . Creation of JAXBContext is same as above except creating Marshaling object instead UN marshaling.

Create MusicDirector Object and add the object to the root.


MusicDirector newMusicDir = new MusicDirector();

newMusicDir.setName("Devi Sri Prasad");
newMusicDir.setDOB("02-August-1979");
newMusicDir.setMovieLanguage("Telugu");
newMusicDir.setRecentMovie("Oosaravelli");

Music newMusic = new Music();
newMusic.getMusicDirector().add(newMusicDir);

So, now one MusicDirector segment will be added to the root tag Music


Here is the complete program

package com.music;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

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

public class MusicClientClass {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
try{
List<MusicDirector> musicList = new ArrayList();
JAXBContext context = JAXBContext.newInstance(new Class[] {Music.class} );
Marshaller marshaller = context.createMarshaller();
                        marshaller.marshal(newMusic, new File("D:/Music/Music.xml"));


                        Music newMusic = new Music();
MusicDirector newMusicDir = new MusicDirector();
newMusicDir.setName("Devi Sri Prasad");
newMusicDir.setDOB("02-August-1979");
newMusicDir.setMovieLanguage("Telugu");
newMusicDir.setRecentMovie("Oosaravelli");
newMusic.getMusicDirector().add(newMusicDir);


Music music = (Music)unMarshaller.unmarshal(new File("D:/Music/Music.xml"));
musicList = music.getMusicDirector();
System.out.println("----List of Music Directors in xml :"+musicList.size()+" members");
for(MusicDirector musicDirector : musicList){
System.out.println("Name Of Music Director :"+musicDirector.getName());
System.out.println("Music Direcotr DOB :"+musicDirector.getDOB());
System.out.println("Music Director Language:"+musicDirector.getMovieLanguage());
System.out.println("Director recent Movie "+musicDirector.getRecentMovie());
System.out.println("---------------------------------------");
}
}catch(JAXBException jaxEx){
jaxEx.printStackTrace();
}

}

}


output
---------
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Music>
<MusicDirector>
<Name>Devi Sri Prasad</Name>
<DOB>02-August-1979</DOB>
<RecentMovie>Oosaravelli</RecentMovie>
<MovieLanguage>Telugu</MovieLanguage>
</MusicDirector>
</Music>


It all completed how to convert XML2Java and Java2XML.

Click here to download the trang.jar file



XML Masking Utility
---------------------------

1 )   Masking XML data with desired text


This String Util is all about .. if we have one XML as a String and if you want to mask any text .. By using code snippet we can able to do



input XML

---------

<rooot>

    <parent>

         <child>

                   <Password>123abcd*</Password>

         </child>

    </parent>

</root>



Java code to mask XML

-------------------------
public class XMLStringMask {
     public static void main(String args[]){
           String genString="";
               String actualString="";
               String str = "<root><parent><child><Password>123abcd*</Password></child></parent></root>";
               String temp1 = str;
                          if(str!=null && str.contains("<Password>")){
                                      str =str.substring(str.indexOf("<Password>"),str.indexOf("</Password>"))+"</Password>";
                                      str = str.substring(0,str.indexOf("</Password>"));
                                      String split[] = str.split("<Password>");
                                      for(int i=0;i<split.length;i++){
                                                  System.out.println(split[i]);
                                                  actualString=split[i];
                                                  //System.out.println(actualString);
                                                  for(j=0;j<split[i].length();j++){
                                                              genString = genString+"*";
                                                  }
                                      }
                          }
                          str = temp1.replace(actualString, genString);
                          System.out.println(str);
     }
}

OutPut
-------
<root><parent><child><Password>********</Password></child></parent></root>








2) Find the word count in one paragraph

This piece of code will find out the word from a paragraph with the number of occurs.
Input Paragraph

                                 "Peter Piper picked a peck of pickled peppers." +
   "A peck of pickled peppers Peter Piper picked." +
   "If Peter Piper picked a peck of pickled peppers," +
   "Where's the peck of pickled peppers Peter Piper picked?"
desired text          : Peter

Java code 



public class StringOccurs {

/**
 * @param args
 */
public static void main(String args[]){
  String searchFor = "Peter";
  String base = "Peter Piper picked a peck of pickled peppers." +
   "A peck of pickled peppers Peter Piper picked." +
   "If Peter Piper picked a peck of pickled peppers," +
   "Where's the peck of pickled peppers Peter Piper picked?";
  int len = searchFor.length();
  int result = 0;
  if (len > 0) {
  int start = base.indexOf(searchFor);
  //System.out.println(start);
  while (start != -1) {
  result++;
  //System.out.println(start+len);
  start = base.indexOf(searchFor, start+len);
  //System.out.println(start);
  }
  }
  System.out.println("occrences:"+result);
          }
}

output
occurs:4