skip to main | skip to sidebar

Java Programs and Examples with Output

Pages

  • Home
 
  • RSS
  • Twitter
Showing posts with label XML Parsing. Show all posts
Showing posts with label XML Parsing. Show all posts
Friday, October 19, 2012

Java Program to Split XML to 10 contracts in each

Posted by Raju Gupta at 6:00 AM – 0 comments
 

Given an XML with many contracts, this program will split 10 contracts in each xml in the output.

Here, I have placed a contract in between <Contract> and </Contract> tags. If you have different tags, replace it with the Contract tag.

Example: if your input xml has 104 contracts, the output will be 11 xmls, 10 xmls having 10 contracts each and 11th xml has 4 contracts.  

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;

public class SplitXML {
 public static void main(String [] args) throws Exception {
  double startTime=System.currentTimeMillis();
  int count=0;
  int i=1;
  StringBuffer sb=new StringBuffer();
  StringBuffer str=new StringBuffer();
  
  //Writer output=null;
  String newline = System.getProperty("line.separator"); 
//System.out.println("args[0]========"+args[0]);
//System.out.println("args[1]========"+args[1]);
  FileInputStream fi=new FileInputStream(args[0]);
  BufferedReader br=new BufferedReader(new InputStreamReader(fi));
  String temp,strLine;
  List<String> list=new ArrayList<String>();
  while((temp=br.readLine())!=null)
  {
   if(temp.equals("<CONTRACT>")||temp.equals("<contract>"))
    temp="<Contract>";
   if(temp.equals("</CONTRACT>")||temp.equals("</contract>"))
    temp="</Contract>";
   if(temp.equalsIgnoreCase("<ROOT>")||temp.equalsIgnoreCase("</ROOT>"))
    temp=" ";
  strLine=temp+"n";
  /*if(strLine.equals("<root>"))
   strLine=strLine.replace("<root>", " ");
  if(strLine.equals("</root>"))
   strLine=strLine.replace("</root>", " ");
  if(strLine.equals("</ROOT>"))
   strLine=strLine.replace("</ROOT>", " ");*/
  sb.append(strLine);
  //System.out.println(strLine);
  // if(strLine.equals("contStrTag"))
  // count++;
  if(strLine.contains("</Contract>"))
  {
  // System.out.println("first loop");
  //String data=sb.toString();
  sb.delete(0, sb.length());
  //System.out.println(data);
  //System.out.println("inside iffffffff");
  count++;
  list.add(strLine);
  // sb.delete(0, sb.length());
  }
  }
  // System.out.println("no of contracts=="+count);
  //String temp[] = sb.toString().split("#");
  /* for (int j = 0; j < temp.length; j++)
  {
  System.out.println("second loop");
  System.out.println(temp[j]);
  }*/
  System.out.println("count===="+count);
  int extra=count%10;
  //int tot=count/10;
  //for(String str:list){
  int item=0;
  //String str="";
  
  int tem=0;
  if(list.isEmpty()==false){
  for(i=0;i<list.size();i++)
  { 
    tem++;
  //for(int j=1;j<=10;j++){
  //System.out.println("for each");
  //str=str+list.get(i);
   str.append(list.get(i));
   
  if((i+1) % 10 == 0){
   Writer output = null;
   item++;
   output=new BufferedWriter(new FileWriter(args[1]+"/Life2012_"+item+".xml"));
   System.out.println("file created!!!!");
   output.write("<root>");
   // System.out.println("after root");
   //System.out.println("after root");
   output.write(newline);
   output.write(str.toString());
   //System.out.println(str);
   output.write("</root>");
   output.close();
   str.delete(0, str.length());
  }
  }
  }
  System.out.println("tem value===="+tem);
  if(extra>0){
   /*for(int j=tem;j<list.size();j++){
    str=str+list.get(j);
   }*/
   Writer output = null;
   item++;
   output=new BufferedWriter(new FileWriter(args[1]+"/Life2012_"+item+".xml"));
   System.out.println("file created!!!!");
   output.write("<root>");
   // System.out.println("after root");
   //System.out.println("after root");
   output.write(newline);
   output.write(str.toString());
   output.write("</root>");
   output.close();
   str=null;
  }
  //}
  // }
//System.out.println("args[0]========"+args[0]);
//System.out.println("args[1]========"+args[1]);
System.out.println("total files created=="+item);
  System.out.println("done");
  System.out.println("Total Time Taken:"+(System.currentTimeMillis()-startTime)/1000+" Seconds");
 }
}

[ Read More ]
Read more...

Parsing an xml using SAX Parser

Posted by Raju Gupta at 2:00 AM – 0 comments
 

Here, this program parses an xml using SAX Parser. All the data of the xml including tags are stored in an stringbuffer in xml format.

Also, this program checks wheather the input xml is well formed or not. If it is not well formed, it will throw an exception.

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

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.SAXNotRecognizedException;
import org.xml.sax.SAXNotSupportedException;
import org.xml.sax.helpers.DefaultHandler;
 
public class ValidateXML extends DefaultHandler  {

 /**
  * @param args
  */
 
 static List<String> emps=new ArrayList<String>();
public static StringBuffer buffer=new StringBuffer();


 public static void main(String[] args) 
 {
  
  
  try {
   SAXParserFactory factory=SAXParserFactory.newInstance();
   
   SAXParser parser=factory.newSAXParser();
    File file=new File("C:/Users/Raj/Java Program/Parsers/DOM/employees.xml");

   
     parser.parse(file, new ValidateXML());
    
     
     //System.out.println(buffer);
    /* System.out.println("the no. of emps are :::: "+emps.size());
   for(int i=0;i<emps.size();i++)
    System.out.println("EMP"+i+"n"+emps.get(i));*/
  }
   catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  
  catch (ParserConfigurationException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (SAXException e) {
   System.out.println("XML is not well formed");
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  
  
  
  
 }

  public void startElement(String uri, String localName, String qName,
   Attributes attributes) throws SAXException 
   {
  
  //System.out.println("name start tag has to be displayed");
  buffer.append("<"); 
   System.out.println("Start element qname ==== "+qName);
   //System.out.println("uri===="+uri);
   //System.out.println("local name===="+localName);
  buffer.append(qName);
   buffer.append(">"); 
   //System.out.println("Inside start Element::::"+qName);
  
   
   
   }
 
  
   public void endElement(String uri, String localName, String qName)
    throws SAXException 
    {
 
 buffer.append("</"); 
   System.out.println("end element name == "+qName);
 buffer.append(qName);
   buffer.append(">"); 
   
   /*if(buffer.toString().contains("<Personnel>"))
    buffer.toString().replace("<Personnel>", " ");
   if(buffer.toString().contains("</Personnel>"))
    buffer.toString().replace("</Personnel>", " ");*/
   /*if(qName.equalsIgnoreCase("employee")){
   emps.add(buffer);
   buffer.delete(0, buffer.length());
   }*/
   //
   //System.out.println(buffer);
 
    }
  
   
   @Override
   public void characters(char[] ch, int start, int length)
     throws SAXException 
     {
    //System.out.println("The string is ::::"+new String(ch,start,length));
    
   buffer.append(new String(ch,start,length).replaceAll("&", "&amp;").trim());  
 
   
   
     }
   
}

[ Read More ]
Read more...
Sunday, October 14, 2012

Merge xml fragment from another xml

Posted by Raju Gupta at 6:00 PM – 0 comments
 

This helps in merging xml fragment from one xml to another, below the tag specified.

Problem this asset addresses
1. copy xml fragment from one xml to another
2. place the copied fragment below the tag mentioned
3. read xml document which was stored in a string   

Sample code used below is to merge 2 document as follows,

doc   



    
 NEW 
    

    
 ............ 0 
    



doc1


    
NEW
    

    
 ................. 1 
    



    
NEW
    

    
 .................2 
    



    
NEW
    

    
 .................3 
    



import java.io.File;
import java.io.StringWriter;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;


public class XmlParse {
public static void main(String[] args) {
 try {
  DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); 
  domFactory.setIgnoringComments(true);
  DocumentBuilder builder = domFactory.newDocumentBuilder(); 
  Document doc = builder.parse(new File("D:\Test\src\test.xml")); 
  Document doc1 = builder.parse(new File("D:\Test\src\test1.xml")); 

  /***** Read xml document which is stored in a string *******/

  /*String inputxml ="<?xml version="1.0" encoding="UTF-8" standalone="no"?><Customer><names><firstName>fName</firstName><lastName>lName</lastName><middleName>nName</middleName></Customer>";
  InputStream is = new ReaderInputStream(new StringReader(inputxml));
  Document doc = builder.parse(is);*/
  
  NodeList nodes = doc.getElementsByTagName("facility");
  
  NodeList nodes1 = doc1.getElementsByTagName("facility");
  for(int i=2;i<nodes1.getLength();i=i+2){
   
   Node n=doc.importNode(nodes1.item(i), true);
   nodes.item(0).getParentNode().appendChild(n);
  
  }
  
  Transformer transformer = TransformerFactory.newInstance().newTransformer();
  transformer.setOutputProperty(OutputKeys.INDENT, "yes");

  StreamResult result = new StreamResult(new StringWriter());
  DOMSource source = new DOMSource(doc);
  transformer.transform(source, result);

  String xmlOutput = result.getWriter().toString();
  System.out.println(xmlOutput);

 } catch (Exception e) {
  System.out.println(e);
 }
 
}


}


Output format:



    
NEW
    

    
 ................. 0 
    



    
NEW
    

    
 .................2 
    



    
NEW
    

    
 .................3 
    




Needed Jar :
commons-io-1.4.jar

[ Read More ]
Read more...
Wednesday, September 19, 2012

DOM Parser for an XML request from PDF and Doc

Posted by Admin at 12:40 AM – 0 comments
 
A DOM parser which parses an XML and will retrieve all tags and tag values and stores them in table.

Limitations
parses upto 4 levels of XML structure. Can extend any number of levels using similar loops.
import java.io.File;

import java.sql.Date;
import java.text.SimpleDateFormat;
import java.text.DateFormat;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.xml.sax.InputSource;
import com.cna.rating.service.communications.RatingOtoXManager;
import com.inet.utility.DataStore;
import org.apache.log4j.Logger;
import com.inet.utility.SystemStartupProperties;


import java.util.Vector;
import java.util.ArrayList;
import com.inet.core.PageProcess;
import com.inet.print.Ifileextend;
import com.inet.print.PrintException;
import com.inet.print.PrintJob;
import com.inet.utility.DataStore;
import com.inet.utility.ExceptionError;
import com.inet.utility.InetFormat;
import com.inet.utility.InetParm;
//import com.inet.utility.SystemStartupProperties;
import com.inet.utility.ValidateInputException;
import com.inet.pageobjects.smtpMail;

import java.io.StringReader;
import java.io.Reader;
import java.io.IOException;
import java.io.PrintWriter;

/* to import the JAXP APIs */

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.FactoryConfigurationError;
import javax.xml.parsers.ParserConfigurationException;

/* for the exceptions */
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;

/* import the W3C definition for a DOM and DOM exceptions*/
import org.w3c.dom.Text;
import org.w3c.dom.Document;
import org.w3c.dom.DOMException;
import org.w3c.dom.Element;

import java.net.UnknownHostException;

public class StoreAppData implements Runnable{
 private static Logger logger = Logger.getRootLogger(); 
 
 static boolean process;
 DataStore pendingAppStore=null;
 Thread t =null;

 public void ProcessPendingApp(){
  t =new Thread(this);
  t.start();
     }

 public void run(){
    try{
    if(pendingAppStore == null){
     pendingAppStore = new DataStore("rating");
    }
        while(true)
        {
    int appCount=0;
    ArrayList appRequestList = checkPendingApplications();
    appCount = appRequestList.size();
    if (appCount>0)
    {
    for (int i=0; i<appCount; i++){
     String pending_app_id = appRequestList.get(i).toString();
     saveProcessXMLFieldData(pending_app_id);
    }//End For loop
    }
     logger.debug(" going to Sleeeeeeeeeeeeeep");
     Thread.sleep(50000);
        } //End While
  }catch(Exception e){
     logger.debug("Error Message is "+e.getMessage());
    }//End Catch
    finally {
      if (pendingAppStore != null){
        pendingAppStore.closeConnection();
     }
    }

 } // End of run() method


 public ArrayList checkPendingApplications() throws Exception{

  ArrayList pending_Req_ids = new ArrayList();

  boolean resultPresent=true;

  try {
    if (pendingAppStore == null){
     pendingAppStore = new DataStore("rating");
    }

   //Get all the pending app_req_id from pending_appQueue table
   String appIdQuery = "select * from pending_appQueue";
   pendingAppStore.execute_stmt(appIdQuery.toString(), 0, 0);
   int app_id_count = pendingAppStore.getRecordCount();

   if (app_id_count>0)
   {
      resultPresent = false;
   }
   int i=0;
   while ((!resultPresent) && (i<app_id_count))
   {
    resultPresent=pendingAppStore.next();
    pending_Req_ids.add(pendingAppStore.getString("app_req_id"));
    logger.debug("Value Arraylist is  "+pending_Req_ids.get(i).toString());
    i++;
   }
   pendingAppStore.close_resultset();
  }
     catch (IOException ioe) {
        // I/O error
        ioe.printStackTrace();
     }
  catch(Exception E)
  {
    logger.debug("Error Message is "+E.getMessage());
  }
  return pending_Req_ids;

 }

//  Function for storing Field data and workqueue starts
   public void saveProcessXMLFieldData(String appRequest) throws Exception,SAXException,
         ParserConfigurationException {

     // Parsing the xml file starts
            String xmldata="";
         String custr_nbr = "99999";
         String custr_rolodex_key = "99999";
         java.util.Date app_rcvd_dt= new java.util.Date();
         SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yy");
         String s = formatter.format(app_rcvd_dt);

       //Parsing the XML using DOM object model
       try {

        Document doc;
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();

        if (pendingAppStore == null){
        pendingAppStore = new DataStore("rating");
       }

       String appXMLData ="select app_xml from application_stage where app_req_id ="+appRequest;
       pendingAppStore.execute_stmt(appXMLData.toString(), 0, 0);
       xmldata = pendingAppStore.getString(0);
       pendingAppStore.close_resultset();


        Reader reader = new StringReader(xmldata);
        InputSource inputSource = new InputSource(reader);
        doc = builder.parse(inputSource);

        String proState =((doc.getElementsByTagName("ProState")).item(0)).getFirstChild().getNodeValue();
        String producerEmail =((doc.getElementsByTagName("ProContEmail")).item(0)).getFirstChild().getNodeValue();
        String producerName =((doc.getElementsByTagName("ProName")).item(0)).getFirstChild().getNodeValue();
        String customerName =((doc.getElementsByTagName("CusName")).item(0)).getFirstChild().getNodeValue();
        String app_id =((doc.getElementsByTagName("AppID")).item(0)).getFirstChild().getNodeValue();
        String app_ver =((doc.getElementsByTagName("AppVersion")).item(0)).getFirstChild().getNodeValue();
       String effDate =((doc.getElementsByTagName("EffectiveDate")).item(0)).getFirstChild().getNodeValue();

          SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy");
       java.util.Date effectiveDt = new Date(sdf.parse(effDate).getTime());
       String effectiveDate = formatter.format(effectiveDt);

        int nodeCount = doc.getDocumentElement().getChildNodes().getLength();
        Element eachChildNode;
        String childNodeName = "";
        String childNodeValue = "";


        String appIdQuery ="select app_id from application_stage where app_req_id ="+appRequest;
       pendingAppStore.execute_stmt(appIdQuery.toString(), 0, 0);
        String app_id_value = pendingAppStore.getString(0);
       pendingAppStore.close_resultset();

        String prdctgnrlcd_Query ="select prdct_gnrl_cd from prdct_application where app_id ='"+app_id_value+"'";
       pendingAppStore.execute_stmt(prdctgnrlcd_Query.toString(), 0, 0);
        String prdct_gnrl_cd = pendingAppStore.getString(0);
       pendingAppStore.close_resultset();
       System.out.println("Insertion into app_details_stage table starts");
        logger.debug("Insertion into app_details_stage table starts");

          for (int i=0; i<nodeCount; i++)
          {

           eachChildNode=(Element) doc.getDocumentElement().getChildNodes().item(i);
           int childlength = doc.getDocumentElement().getChildNodes().item(i).getChildNodes().getLength();
           boolean childPresent = eachChildNode.hasChildNodes();
          if (childlength>1)
          {
          for (int j=0; j<childlength; j++)
           {
            if (doc.getDocumentElement().getChildNodes().item(i).getChildNodes().item(j).hasChildNodes())
            {
             int innerChildLength =doc.getDocumentElement().getChildNodes().item(i).getChildNodes().item(j).getChildNodes().getLength();

             if (innerChildLength>1)
             {
             for (int k=0; k<innerChildLength;k++)
             {
              childNodeName = doc.getDocumentElement().getChildNodes().item(i).getChildNodes().item(j).getChildNodes().item(k).getNodeName();

              if (doc.getDocumentElement().getChildNodes().item(i).getChildNodes().item(j).getChildNodes().item(k).hasChildNodes())
              {

              childNodeValue = doc.getDocumentElement().getChildNodes().item(i).getChildNodes().item(j).getChildNodes().item(k).getFirstChild().getNodeValue();
              String insertApplicationDetailQuery = "insert into app_details_stage (app_req_id,app_field_name,app_field_value,prdct_gnrl_cd,app_id,app_ver)"+
                         "values("+appRequest+",'"+childNodeName+"','"+childNodeValue+"',"+prdct_gnrl_cd+",'"+app_id+"','"+app_ver+"')";
              pendingAppStore.execute_stmt(insertApplicationDetailQuery.toString(), 0, 0);
              pendingAppStore.close_resultset();
              }
              else{
               childNodeValue="";
               String insertApplicationDetailQuery = "insert into app_details_stage (app_req_id,app_field_name,app_field_value,prdct_gnrl_cd,app_id,app_ver)"+
                         "values("+appRequest+",'"+childNodeName+"','"+childNodeValue+"',"+prdct_gnrl_cd+",'"+app_id+"','"+app_ver+"')";
              pendingAppStore.execute_stmt(insertApplicationDetailQuery.toString(), 0, 0);
              pendingAppStore.close_resultset();
              }
             }
             }
             else
             {
              childNodeName = doc.getDocumentElement().getChildNodes().item(i).getChildNodes().item(j).getNodeName();
              childNodeValue = doc.getDocumentElement().getChildNodes().item(i).getChildNodes().item(j).getFirstChild().getNodeValue();
              String insertApplicationDetailQuery = "insert into app_details_stage (app_req_id,app_field_name,app_field_value,prdct_gnrl_cd,app_id,app_ver)"+
                       "values("+appRequest+",'"+childNodeName+"','"+childNodeValue+"',"+prdct_gnrl_cd+",'"+app_id+"','"+app_ver+"')";
             pendingAppStore.execute_stmt(insertApplicationDetailQuery.toString(), 0, 0);
             pendingAppStore.close_resultset();
             }

             }
             else
             {

              childNodeName = doc.getDocumentElement().getChildNodes().item(i).getChildNodes().item(j).getNodeName();
              childNodeValue = "";
              String insertApplicationDetailQuery = "insert into app_details_stage (app_req_id,app_field_name,app_field_value,prdct_gnrl_cd,app_id,app_ver)"+
                        "values("+appRequest+",'"+childNodeName+"','"+childNodeValue+"',"+prdct_gnrl_cd+",'"+app_id+"','"+app_ver+"')";
             pendingAppStore.execute_stmt(insertApplicationDetailQuery.toString(), 0, 0);
             pendingAppStore.close_resultset();
             }
           } //End j loop
          } //End if child length
          else
          {
          if (doc.getDocumentElement().getChildNodes().item(i).hasChildNodes())
          {
           childNodeName = doc.getDocumentElement().getChildNodes().item(i).getNodeName();
           childNodeValue = doc.getDocumentElement().getChildNodes().item(i).getFirstChild().getNodeValue();
           String insertApplicationDetailQuery = "insert into app_details_stage (app_req_id,app_field_name,app_field_value,prdct_gnrl_cd,app_id,app_ver)"+
                     "values("+appRequest+",'"+childNodeName+"','"+childNodeValue+"',"+prdct_gnrl_cd+",'"+app_id+"','"+app_ver+"')";
          pendingAppStore.execute_stmt(insertApplicationDetailQuery.toString(), 0, 0);
          pendingAppStore.close_resultset();
          }
          else{
           childNodeName = doc.getDocumentElement().getChildNodes().item(i).getNodeName();
            childNodeValue="";
           String insertApplicationDetailQuery = "insert into app_details_stage (app_req_id,app_field_name,app_field_value,prdct_gnrl_cd,app_id,app_ver)"+
                      "values("+appRequest+",'"+childNodeName+"','"+childNodeValue+"',"+prdct_gnrl_cd+",'"+app_id+"','"+app_ver+"')";
           pendingAppStore.execute_stmt(insertApplicationDetailQuery.toString(), 0, 0);
           pendingAppStore.close_resultset();
           }
           } //End else child length
           } //End i loop
         logger.debug("Insertion into app_details_stage table ends");
       System.out.println("Insertion into app_details_stage table Ends");

     //parsing the xml file ends

     // inserting data into work_queue table starts
     pendingAppStore.init_parm();
     pendingAppStore.create_parameter("@product_gnrl_cd","Code_Large","I",prdct_gnrl_cd);
     pendingAppStore.create_parameter("@proState","char","I",proState);
     pendingAppStore.execute_sproc("getAdmittedStatus_SSP", 0);
     String wqueue_status = pendingAppStore.getString(0);
     pendingAppStore.close_resultset();
     logger.debug("The Admitted Status is "+wqueue_status);


     // Getting underwriter team from stored procedure get_undwr_team_SSP starts
     pendingAppStore.init_parm();
     pendingAppStore.create_parameter("@product_gnrl_cd","Code_Large","I",prdct_gnrl_cd);
     pendingAppStore.create_parameter("@proState","char","I",proState);
     pendingAppStore.execute_sproc("get_undwr_team_SSP", 0);
     String undwr_team = pendingAppStore.getString(0);
     pendingAppStore.close_resultset();
     logger.debug("The Underwriter team is  "+undwr_team);


     // Getting underwriter team from stored procedure get_undwr_team_SSP ends
     String workDescQuery = "select work_desc_cd from work_desc where work_desc='"+wqueue_status+"'";
     pendingAppStore.execute_stmt(workDescQuery, 0, 0);
     String work_desc_cd = pendingAppStore.getString(0);
     pendingAppStore.close_resultset();
     logger.debug("The work_desc_cd of Admitted Status is  "+work_desc_cd);

     String inet_ind = "I";
     pendingAppStore.init_parm(); //resetting the parameters
     //Passing input parameters to the stored procedure to insert record into work_queue
     pendingAppStore.create_parameter("@appRequest","Quote","I",appRequest);
     pendingAppStore.create_parameter("@wqStatus","char","I",wqueue_status);
     pendingAppStore.create_parameter("@wqueue_rcvd_dt","DATE","I",s);
     pendingAppStore.create_parameter("@wqueue_crtd_dt","DATE","I",s);
     pendingAppStore.create_parameter("@lst_chng_dt","DATE","I",s);
     pendingAppStore.create_parameter("@inet_ind","char","I",inet_ind);
     pendingAppStore.create_parameter("@product_gnrl_cd","Code_Large","I",prdct_gnrl_cd);
     pendingAppStore.create_parameter("@work_desc_cd","Code_Small","I",work_desc_cd);
     pendingAppStore.create_parameter("@undwr_team","char","I",undwr_team);
     pendingAppStore.create_parameter("@custr_nbr","Code_Large","I",custr_nbr);
     pendingAppStore.create_parameter("@custr_rolodex_key","Code_Large","I",custr_rolodex_key);
     pendingAppStore.create_parameter("@wqueue_pol_effv_dt","DATE","I",effectiveDate);
     pendingAppStore.execute_sproc("WorkQueueItemEpack_EZ_ISP", 0);
     pendingAppStore.close_resultset();
     // inserting in work_queue table ends

     //Sending Email to Producer Email id
     sendEmail(producerName,producerEmail);
     logger.debug("Entry made in work_queue table and mail sent to producer saying Thanks for submission  ");

     //Delete the processed app_req_id from pending_appQueue
     String delProcessedAppId ="delete from pending_appQueue where app_req_id ="+appRequest;
     pendingAppStore.execute_stmt(delProcessedAppId.toString(), 0, 0);

    }
    //  Handling the Parser exceptions starts
    catch (SAXException sxe) {
     // Error generated during parsing
     Exception  x = sxe;
     if (sxe.getException() != null)
      x = sxe.getException();
     x.printStackTrace();

     } catch (ParserConfigurationException pce) {
      // Parser with specified options can't be built
      pce.printStackTrace();

     } catch (IOException ioe) {
     // I/O error
     ioe.printStackTrace();
     }
     catch (Exception e) {
        logger.debug("Excetption is " + e);
       }
    //  Handling the Parser exceptions ends
    }
   // Function for storing Field data and workqueue ends
   
  
 /**
 * This method is sendEmail
 * @input param  : producerName,producerEmail,applicationExpired
 * @return param : None
 * @exception : Exception
 */  
 public void sendEmail(String producerName,String producerEmail) throws Exception {
   try {

    String ls_email_id = producerEmail;
    String ls_message ="";    
    ls_message = "
 Thank you for forwarding your submission."+
          "
 A regional underwriter will contact you shortly."+
          "
 Please do not respond to this Email.";    

    String ls_smtphost =
     new String(
      SystemStartupProperties.getSystemProperties(
       "smtp.host"));
    String ls_from =
     new String(
      SystemStartupProperties.getSystemProperties(
       "smtp.from"));
    String ls_subject = "CNA Epack EZ Application for "+producerName;

    smtpMail mail = new smtpMail(ls_smtphost);

    if (mail == null){
     throw new ExceptionError("0C001225SY Mail server unavailable");
    }

    mail.compose(ls_from);
    mail.setSubject(ls_subject);
    mail.setTo(ls_email_id);
    mail.setMessage(ls_message);       
    mail.send();
   }
    catch (Exception lo_Exception) {
    logger.debug(lo_Exception.getMessage());
   }

 }
 //Method sending Email - Ends here  


}

[ Read More ]
Read more...
Saturday, September 15, 2012

Generic XML builder for ematrix

Posted by Admin at 1:59 AM – 0 comments
 

Builds XML using recursive methods for list having map,table or list data


import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;



public class XMLBuilder {

 
 /**
     * Public Method to return the response in requested format
     * @param context
     * @param paramList
     * @param sFormatType
     * @return
     * @throws Exception
     */
    public Object getFormattedResponse(HashMap paramMap) throws Exception {
     if(paramMap != null) {
        String sFormat = (String) paramMap.get("format");
        System.out.println("getFormattedResponse:: Format from Request::"+sFormat);
        if(sFormat!= null && sFormat.equalsIgnoreCase("XML")) {
         Object retObject = paramMap.get("returnObject");
         return getXMLResponse(retObject);
        }
     } else {
      System.out.println("getFormattedResponse:: Returning NULL as ParamMap is empty");
     }
     return null;
    }

    /**
     * Method to return XML format
     * @param context
     * @param paramList
     * @return XML String
     */
 private Object getXMLResponse( Object paramObj) {
  if (paramObj != null && paramObj.getClass().equals(ArrayList.class)) {
   ArrayList paramList = (ArrayList) paramObj;
   StringBuffer sb = new StringBuffer();
   sb.append("<mwsList type="TopList">");
   for (Object object : paramList) {
    if(object == null) {
     System.out.println("Object is null ..");
    }else if (object.getClass().equals(HashMap.class)) {
     sb.append(getMapdata(object));
    } else if (object.getClass().equals(Hashtable.class)) {
     sb.append(getTabledata(object));
    }else if (object.getClass().equals(ArrayList.class)) {
     sb.append(getArrayListdata(object));
    } else if(object.getClass().equals(String.class)) {
     sb.append("<mwsItem><mwsField><mwsKey></mwsKey><mwsVal>");
     sb.append(object);
     sb.append("</mwsVal></mwsField></mwsItem>");
    } else {
     System.out.println("getXMLResponse:: Data Structure Class Not Handled -- "+object.getClass().getName());
    }
    
   }
   sb.append("</mwsList>");
   System.out.println("getXMLResponse :: Returning String = "+sb.toString());
   return sb.toString();
  } else {
   System.out.println("getXMLResponse :: Returning Object = "+paramObj);
   return paramObj;
  }

 }

 /**
 * Method to get data from List 
 */
 private Object getArrayListdata(Object object) {
  List lst = (List) object;
  
  Iterator it = lst.iterator();
  StringBuffer sb = new StringBuffer();
  int index =0;
  sb.append("<mwsList>");
  while(it.hasNext()) {
   sb.append("<mwsItem>");
   System.out.println("getArrayListdata:: Processing - "+it.next());
   Object val =  lst.get(index);
   sb.append("<mwsField>");
   sb.append("<mwsKey>");
   sb.append("");
   sb.append("</mwsKey>");
   sb.append("<mwsVal>");
   if(val != null && val.getClass().equals(String.class)) {
    sb.append(val);
   } else if(val != null && val.getClass().equals(HashMap.class)) {
    sb.append(getMapdata(val));
   } else if(val != null && val.getClass().equals(ArrayList.class)) {
    sb.append(getArrayListdata(val));
   }else if(val != null && val.getClass().equals(Hashtable.class)) {
    sb.append(getTabledata(val));
   }
   sb.append("</mwsVal>");
   sb.append("</mwsField>");
   index++;
   sb.append("</mwsItem>");
  }
  sb.append("</mwsList>");
  return sb.toString();
 }

 /**
 * Method to check for Map class and get the data from it
 */
 private String getMapdata(Object object) {
  Map map = (Map) object;
  Set set = map.keySet();
  Iterator it = set.iterator();
  StringBuffer sb = new StringBuffer();
  String sKey = "";
  String sVal = "";
  sb.append("<mwsItem>");
  while(it.hasNext()) {
   sKey = (String) it.next();
   Object val =  map.get(sKey);
   sb.append("<mwsField>");
   sb.append("<mwsKey>");
   sb.append(sKey);
   sb.append("</mwsKey>");
   sb.append("<mwsVal>");
   if(val != null && val.getClass().equals(String.class)) {
    sb.append(val);
   } else if(val != null && val.getClass().equals(HashMap.class)) {
    sb.append(getMapdata(val));
   } else if(val != null && val.getClass().equals(ArrayList.class)) {
    sb.append(getArrayListdata(val));
   }else if(val != null && val.getClass().equals(Hashtable.class)) {
    sb.append(getTabledata(val));
   }
   sb.append("</mwsVal>");
   sb.append("</mwsField>");
   
  }
  sb.append("</mwsItem>");
  return sb.toString();
 }
 /**
 * Method to get the data from HashTable
 */
 private String getTabledata(Object object) {
  Hashtable map = (Hashtable) object;
  Set set = map.keySet();
  Iterator it = set.iterator();
  StringBuffer sb = new StringBuffer();
  String sKey = "";
  String sVal = "";
  sb.append("<mwsItem>");
  while(it.hasNext()) {
   sKey = (String) it.next();
   Object val =  map.get(sKey);
   sb.append("<mwsField>");
   sb.append("<mwsKey>");
   sb.append(sKey);
   sb.append("</mwsKey>");
   sb.append("<mwsVal>");
   if(val != null && val.getClass().equals(String.class)) {
    sb.append(val);
   } else if(val != null && val.getClass().equals(HashMap.class)) {
    sb.append(getMapdata(val));
   } else if(val != null && val.getClass().equals(ArrayList.class)) {
    sb.append(getArrayListdata(val));
   }else if(val != null && val.getClass().equals(Hashtable.class)) {
    sb.append(getTabledata(val));
   }
   sb.append("</mwsVal>");
   sb.append("</mwsField>");
   
  }
  sb.append("</mwsItem>");
  return sb.toString();
 }
}

[ Read More ]
Read more...
Friday, September 14, 2012

Generic Parsing of XML in JAVA

Posted by Admin at 2:05 PM – 0 comments
 

import java.io.*;
import java.net.*;
import org.w3c.dom.*;
import org.w3c.dom.Node.*;

import oracle.xml.parser.v2.*;


public class XMLParsingUsingDOM {

 static public void main(String[] argv) {
  try {

   if (argv.length != 1) {
    // must pass in the name of the XML file
    System.err.println("Usage: java DOMExample filename");
    System.exit(1);
   }

   // Get an instance of the parser
   DOMParser parser = new DOMParser();

   // Generate a URL from the filename
   URL url = createURL(argv[0]);

   // Set various parser options; validation on,
   // warnings shown, error stream set to stderr.
   parser.setErrorStream(System.err);
   parser.setValidationMode(true);
   parser.showWarnings(true);
   // parse the do*****ent
   parser.parse(url);

   // Obtain the do*****ent
   Document doc = parser.getDocument();

   // print do*****ent elements
   System.out.print("The elements are: ");
   printElements(doc);

   // print do*****ent elements attributes
   System.out.println("The attributes of each element are: ");
   printElementAttributes(doc);

  } catch (Exception e) {
   System.out.println(e.toString());
  }
 }


 static void printElements(Document doc) {

  NodeList nodelist = doc.getElementsByTagName("*");
  Node     node;

  for (int i=0; i<nodelist.getLength(); i++) {
   node = nodelist.item(i);
   System.out.print(node.getNodeName() + " ");
  }

  System.out.println();

 }
 static void printElementAttributes(Document doc) {

  NodeList      nodelist = doc.getElementsByTagName("*");
  Node          node;
  Element       element;
  NamedNodeMap  nnm = null;

  String attrname;
  String attrval;
  int    i, len;

  len = nodelist.getLength();

  for (int j=0; j < len; j++) {
   element = (Element)nodelist.item(j);
   System.out.println(element.getTagName() + ":");
   nnm = element.getAttributes();
  }

  if (nnm != null) {
   for (i=0; i<nnm.getLength(); i++) {
    node = nnm.item(i);
    attrname = node.getNodeName();
    attrval  = node.getNodeValue();
    System.out.println(" " + attrname + " = " + attrval);
   }
  }

  System.out.println();

 }


 static URL createURL(String filename) {

  URL url = null;

  try {
   url = new URL(filename);
  } catch (MalformedURLException ex) {
   try {
    File f = new File(filename);
    url = f.toURL();
   } catch (MalformedURLException e) {
    System.out.println("Cannot create URL for: " + filename);
    System.exit(0);
   }
  }

  return url;

 }

}

XML Document

     

John
B
12


Mary
A
11


Simon
A
18

 
[ Read More ]
Read more...
Sunday, September 9, 2012

XML Parsing with JAVA with Example

Posted by Admin at 1:46 AM – 0 comments
 
Writing XML documents is very straightforward, but reading them is not nearly as
simple. Fortunately, we can use an XML parser to read the document for us. The
XML parser exposes the contents of an XML document through an API. A client
application reads an XML document through this API. As well as reading the
document and providing the contents to the client application, the parser also checks
the document for well-formedness and (optionally) validity. If it finds an error, it
informs the client application.
XML parser is a software module to read documents and a means to provide access to
their content. XML parser generates a structured tree to return the results to the
browser. An XML parser is similar to a processor that determines the structure and
properties of the data. An XML parser can read a XML document to create an output
to generate a display form. Now, XML parser for Java runs on any platform where
there is Java virtual machine. It is sometimes called XML4J. It has an interface which
allows you to take a string of XML formatted text, pick the XML tags and use them to
extract the tagged information.
Among the various XML parsers, the two mostly used ones are SAX parser & DOM
parser. Here is a brief description of these two different parsers.

SAX
SAX, the Simple API for XML, is the gold standard of XML APIs. It is the most
complete and correct by far. Given a fully validating parser that supports all its
optional features, there is very little you can’t do with it. It has one or two holes, but
they're really off in the weeds of the XML specifications, and you have to look pretty
hard to find them. SAX is an event driven API. The SAX classes and interfaces model
the parser, the stream from which the document is read, and the client application
receiving data from the parser. However, no class models the XML document itself.
Instead the parser feeds content to the client application through a callback interface,
much like the ones used in Swing and the AWT. This makes SAX very fast and very
memory efficient (since it doesn’t have to store the entire document in memory).
However, SAX programs can be harder to design and code because you normally
need to develop your own data structures to hold the content from the document.
SAX works best when your processing is fairly local; that is, when all the information
you need to use is close together in the document. For example, you might process
one element at a time. Applications that require access to the entire document at once
in order to take useful action would be better served by one of the tree-based APIs
like DOM or JDOM. Finally, because SAX is so efficient, it’s the only real choice for
truly huge XML documents. Of course, “truly huge” has to be defined relative to
available memory. However, if the documents you're processing are in the gigabyte
range, you really have no choice but to use SAX.
DOM
DOM, the Document Object Model, is a fairly complex API that models an XML
document as a tree. Unlike SAX, DOM is a read-write API. It can both parse existing
XML documents and create new ones. Each XML document is represented as
Document object. Documents are searched, queried, and updated by invoking methods
on this Document object and the objects it contains. This makes DOM much more
convenient when random access to widely separated parts of the original document is
required. However, it is quite memory intensive compared to SAX, and not nearly as
well suited to streaming applications.
Ahead in the document I have included example of XML parsing with Java using both
of these parsers.
XML Parsing with JAVA
I would like to start with an example of how to parse a XML file create Java Objects
and manipulate them.
The idea here is to parse the employees.xml file with content as below
<?xml version="1.0" encoding="UTF-8"?>
<Office>
<Employee type="permanent">
<Name>Debamalya</Name>
<Id>235960</Id>
<Age>25</Age>
</Employee>
<Employee type="contract">
<Name>Rishin</Name>
<Id>3675</Id>
<Age>24</Age>
</Employee>
<Employee type="permanent">
<Name>Debalina</Name>
<Id>3676</Id>
<Age>28</Age>
</Employee>
</Office>
From the parsed content create a list of Employee objects and print it to the console.
The output would be something like
Employee Details - Name:Debamalya, Type:permanent, Id:235960, Age:25.
Employee Details - Name:Rishin, Type:contract, Id:3675, Age:24.
Employee Details - Name:Debalina, Type:permanent, Id:3676, Age:28.
I will start with a DOM parser to parse the xml file, create Employee value objects
and add them to a list. To ensure we parsed the file correctly let's iterate through the
list and print the employees data to the console. Later we will see how to implement
the same using SAX parser.
In a real world situation you might get an xml file from a third party vendor which
you need to parse and update your database.
Using DOM Parser:
This program DomParserExample.java uses DOM API.
The steps are
• Get a document builder using document builder factory and parse the xml file
to create a DOM object.
• Get a list of employee elements from the DOM.
• For each employee element get the id, name, age and type. Create an
employee value object and add it to the list.
• At the end iterate through the list and print the employees to verify we parsed
it right.

a) Getting a document builder
private void parseXmlFile(){ 
 DocumentBuilderFactory dbf = 
   DocumentBuilderFactory.newInstance(); 

 try { 
  //Using factory get an instance of document builder 
  DocumentBuilder db = dbf.newDocumentBuilder(); 
  //parse using builder to get DOM representation of the XML 
  file 
  dom = db.parse("employees.xml"); 

 }catch(ParserConfigurationException pce) { 
  pce.printStackTrace(); 
 }catch(SAXException se) { 
  se.printStackTrace(); 
 }catch(IOException ioe) { 
  ioe.printStackTrace(); 
 } 
}

b) Get a list of employee elements
Get the rootElement from the DOM object. From the root element get all employee
elements. Iterate through each employee element to load the data.
private void parseDocument(){ 
 //get the root element 
 Element docEle = dom.getDocumentElement(); 

 //get a nodelist of elements 
 NodeList nl = 
   docEle.getElementsByTagName("Employee"); 
 if(nl != null && nl.getLength() > 0) { 
  for(int i = 0 ; i < nl.getLength();i++) { 

   //get the employee element 
   Element el = (Element)nl.item(i); 

   //get the Employee object 
   Employee e = getEmployee(el); 

   //add it to list 
   myEmpls.add(e); 
  } 
 } 
}
c) Reading in data from each employee.
/** 
 * I take an employee element and read the values in, create 
 * an Employee object and return it 
 */ 
private Employee getEmployee(Element empEl) { 

 //for each  element get text or int values of //name ,id, age and name 
 String name = getTextValue(empEl,"Name"); 
 int id = getIntValue(empEl,"Id"); 
 int age = getIntValue(empEl,"Age"); 

 String type = empEl.getAttribute("type"); 

 //Create a new Employee with the value read from the xml nodes 
 Employee e = new Employee(name,id,age,type); 

 return e; 
} 

/** 
 * I take a xml element and the tag name, look for the tag 
and  
 * get the text content 
 * i.e for Deb xml snippet 
if 
 * the Element points to employee node and tagName is  
 *'name' I will return Deb 
 */ 
private String getTextValue(Element ele, String tagName) { 
 String textVal = null; 
 NodeList nl = ele.getElementsByTagName(tagName); 
 if(nl != null && nl.getLength() > 0) { 
  Element el = (Element)nl.item(0); 
  textVal = el.getFirstChild().getNodeValue(); 
 } 

 return textVal; 
} 

/** 
 * Calls getTextValue and returns a int value 
 */ 
private int getIntValue(Element ele, String tagName) { 
 //in production application you would catch the exception 
 return Integer.parseInt(getTextValue(ele,tagName)); 
} 

d) Iterating and printing.
private void printData(){ 
 System.out.println("No of Employees '" + myEmpls.size() + 
   "'."); 
 Iterator it = myEmpls.iterator(); 
 while(it.hasNext()) { 
  System.out.println(it.next().toString()); 
 } 
}

Using SAX Parser:
This program SAXParserExample.java parses a XML document and prints it on the
console.
Sax parsing is event based modeling. When a Sax parser parses a XML document and
every time it encounters a tag it calls the corresponding tag handler methods.
When it encounters a Start Tag it calls this method
public void startElement(String uri,..
When it encounters a End Tag it calls this method
public void endElement(String uri,...
Like the DOM example this program also parses the xml file, creates a list of
employees and prints it to the console. The steps involved are
• Create a Sax parser and parse the xml
• In the event handler create the employee object
• Print out the data
Basically the class extends DefaultHandler to listen for call back events. And we
register this handler with the Sax parser to notify us of call back events. We are only
interested in start event, end event and character event.
In start event if the element is employee we create a new instant of employee object
and if the element is Name/Id/Age we initialize the character buffer to get the text
value.
In end event if the node is employee then we know we are at the end of the employee
node and we add the Employee object to the list. If it is any other node like
Name/Id/Age we call the corresponding methods like setName/SetId/setAge on the
Employee object. Java Bean classes can be used for this. In character event we store
the data in a temp string variable.

a) Create a Sax Parser and parse the xml
private void parseDocument() { 

 //get a factory 
 SAXParserFactory spf = 
   SAXParserFactory.newInstance(); 
 try { 

  //get a new instance of parser 
  SAXParser sp = spf.newSAXParser(); 

  //parse the file and also register this class for call backs 
  sp.parse("employees.xml", this); 

 }catch(SAXException se) { 
  se.printStackTrace(); 
 }catch(ParserConfigurationException pce) { 
  pce.printStackTrace(); 
 }catch (IOException ie) { 
  ie.printStackTrace(); 
 } 
} 

b) In the event handlers create the Employee object and call the corresponding setter
methods.
public void startElement(String uri, String localName, String 
  qName, Attributes attributes) throws SAXException { 
 //reset 
 tempVal = ""; 
 if(qName.equalsIgnoreCase("Employee")) { 
  //create a new instance of employee 
  tempEmp = new Employee(); 
  tempEmp.setType(attributes.getValue("type")); 
 } 
} 

public void characters(char[] ch, int start, int length) 
  throws SAXException { 
 tempVal = new String(ch,start,length); 
} 

public void endElement(String uri, String localName, 
  String qName) throws SAXException { 

 if(qName.equalsIgnoreCase("Employee")) { 
  //add it to the list 
  myEmpls.add(tempEmp); 

 }else if (qName.equalsIgnoreCase("Name")) { 
  tempEmp.setName(tempVal); 
 }else if (qName.equalsIgnoreCase("Id")) { 
  tempEmp.setId(Integer.parseInt(tempVal)); 
 }else if (qName.equalsIgnoreCase("Age")) { 
  tempEmp.setAge(Integer.parseInt(tempVal)); 
 } 

}

c) Iterating and printing.
private void printData(){ 
 
 System.out.println("No of Employees '" + myEmpls.size() + 
"'."); 
 
  Iterator it = myEmpls.iterator(); 
  while(it.hasNext()) { 
   System.out.println(it.next().toString()); 
  } 
 }

Writing XML with Java
The previous programs illustrated how to parse an existing XML file using both SAX
and DOM Parsers. But generating a XML file from scratch is a different story, for
instance you might like to generate an xml file for the data extracted from a database.
To keep the example simple this program XMLCreatorExample.java generates XML
from a list preloaded with hard coded data. The output will be book.xml file with the
following content.
<?xml version="1.0" encoding="UTF-8"?>
<Books>
<Book Subject="Java 1.5">
<Author>Kathy Sierra .. etc</Author>
<Title>Head First Java</Title>
</Book>
<Book Subject="Java Architect">
<Author>Kathy Sierra .. etc</Author>
<Title>Head First Design Patterns</Title>
</Book>
</Books>
The steps involved are
• Load Data
• Get an instance of Document object using document builder factory
• Create the root element Books
• For each item in the list create a Book element and attach it to Books element
• Serialize DOM to FileOutputStream to generate the xml file "book.xml".

a) Load Data.
/** 
 * Add a list of books to the list 
 * In a production system you might populate the list from a db
 */ 
private void loadData(){ 
 myData.add(new Book("Head First Java", 
   "Kathy Sierra .. etc","Java 1.5")); 
 myData.add(new Book("Head First Design Patterns", 
   "Kathy Sierra .. etc","Java Architect")); 
} 
b) Getting an instance of DOM.
/** 
 * Using JAXP in implementation independent manner create a 
document object 
 * using which we create a xml tree in memory 
 */ 
private void createDocument() { 

 //get an instance of factory 
 DocumentBuilderFactory dbf = 
   DocumentBuilderFactory.newInstance(); 
 try { 
  //get an instance of builder 
  DocumentBuilder db = dbf.newDocumentBuilder(); 

  //create an instance of DOM 
  dom = db.newDocument(); 

 }catch(ParserConfigurationException pce) { 
  //dump it 
  System.out.println("Error while trying to 
    instantiate DocumentBuilder " + pce); 
    System.exit(1); 
 } 

} 
}
c) Create the root element Books.
/** 
 * The real workhorse which creates the XML structure 
 */ 
private void createDOMTree(){ 

 //create the root element  

 Element rootEle = dom.createElement("Books"); 
 dom.appendChild(rootEle); 

 //No enhanced for 
 Iterator it  = myData.iterator(); 
 while(it.hasNext()) { 
  Book b = (Book)it.next(); 
  //For each Book object  create element and attach it to root 
  Element bookEle = createBookElement(b); 
  rootEle.appendChild(bookEle); 
 } 

}
d) Creating a book element.
/** 
 * Helper method which creates a XML element 
 * @param b The book for which we need to create an xml 
representation 
 * @return XML element snippet representing a book 
 */ 
private Element createBookElement(Book b){ 
 Element bookEle = dom.createElement("Book"); 
 bookEle.setAttribute("Subject", b.getSubject()); 
 //create author element and author text node and attach it to bookElement 
 Element authEle = dom.createElement("Author"); 
 Text authText = dom.createTextNode(b.getAuthor()); 
 authEle.appendChild(authText); 
 bookEle.appendChild(authEle); 
 //create title element and title text node and attach it to bookElement 
 Element titleEle = dom.createElement("Title"); 
    Text titleText = dom.createTextNode(b.getTitle()); 
 titleEle.appendChild(titleText); 
 bookEle.appendChild(titleEle); 
 return bookEle; 
}
e) Serialize DOM to FileOutputStream to generate the xml file "book.xml".
/** 
 * This method uses Xerces specific classes 
 * prints the XML document to file. 
 */ 
private void printToFile(){ 
 try 
 { 
  //print 
  OutputFormat format = new OutputFormat(dom); 
  format.setIndenting(true); 
  //to generate output to console use this serializer 
  //XMLSerializer serializer = new 
  XMLSerializer(System.out, format); 

  //to generate a file output use fileoutputstream instead of 
  system.out 
  XMLSerializer serializer = new XMLSerializer( 
    new FileOutputStream(new File("book.xml")), 
    format); 
  serializer.serialize(dom); 
 } catch(IOException ie) { 
  ie.printStackTrace(); 
 } 
}
Note:
The Xerces internal classes OutputFormat and XMLSerializer are in different
packages.
In JDK 1.5 with built in Xerces parser they are under
com.sun.org.apache.xml.internal.serialize.OutputFormat
com.sun.org.apache.xml.internal.serialize.XMLSerializer
In Xerces 2.7.1 which we are using to run these examples they are under
org.apache.xml.serialize.XMLSerializer
org.apache.xml.serialize.OutputFormat
We are using Xerces 2.7.1 with JDK 1.4 and JDK 1.3 as the default parser with JDK
1.4 is Crimson and there is no built in parser with JDK 1.3.
Also please remember it is not advisable to use parser implementation specific classes
like OutputFormat and XMLSerializer as they are only available in Xerces and if
you switch to another parser in the future you may have to rewrite.
Another example, of writing a XML containing the first 10 Fibonacci numbers is as
follows.
<?xml version="1.0"?>
<Fibonacci_Numbers>
<fibonacci>1</fibonacci>
<fibonacci>1</fibonacci>
<fibonacci>2</fibonacci>
<fibonacci>3</fibonacci>
<fibonacci>5</fibonacci>
<fibonacci>8</fibonacci>
<fibonacci>13</fibonacci>
<fibonacci>21</fibonacci>
<fibonacci>34</fibonacci>
<fibonacci>55</fibonacci>
</Fibonacci_Numbers>
To produce this, just add string literals for the <fibonacci> and </fibonacci> tags
inside the print statements, as well as a few extra print statements to produce the XML
declaration and the root element start- and end-tags. XML documents are just text,
and you can output them any way you’d output any other text document. The
FibonacciXML.java is created for this.

import java.math.BigInteger;

public class FibonacciXML {
 public static void main(String[] args) {
  BigInteger low = BigInteger.ONE;
  BigInteger high = BigInteger.ONE;
  System.out.println("");
  System.out.println("");
  for (int i = 0; i < 10; i++) {
   System.out.print(" ");
   System.out.print(low);
   System.out.println("");
   BigInteger temp = high;
   high = high.add(low);
   low = temp;
  }
  System.out.println("");
 }
}
   
Running Programs in JAVA
The instructions to compile and run these programs vary, based on the JDK that you
are using. This is due to the way the XML parser is bundled with various Java
distributions. These instructions are for Windows OS. For Unix or Linux OS you just
need to change the folder paths accordingly. Xerces parser is bundled with the JDK
1.5 distribution. So you need not download the parser separately.

Running DOMParserExample
1. Place DomParserExample.java, Employee.java, employees.xml to
c:\xercesTest
2. Go to command prompt and type
cd c:\xercesTest
3. To compile, type
javac -classpath . DomParserExample.java
4. To run, type
java -classpath . DomParserExample

Running SAXParserExample
1. Place SAXParserExample.java, Employee.java, employees.xml to
c:\xercesTest
2. Go to command prompt and type
cd c:\xercesTest
3. To compile, type
javac -classpath . SAXParserExample.java
4. To run,type
java -classpath . SAXParserExample

Running XMLCreatorExample
1. Place XMLCreatorExample.java, Book.java to c:\xercesTest
2. Go to command prompt and type
cd c:\xercesTest
3. To compile, type
javac -classpath . XMLCreatorExample.java
4. To run, type
java -classpath . XMLCreatorExample


Running FibonacciXML
1. Place FibonacciXML.java to c:\xercesTest
2. Go to command prompt and type
cd c:\xercesTest
Internal Use 15
XML Parsing with JAVA
3. To compile, type
javac -classpath . FibonacciXML.java
4. To run, type
java -classpath .


Comparison
Both SAX & DOM have there advantages & disadvantages but need to be used
according to the requirement.
SAX:
  1.  Parses node by node
  2.  Doesn’t store the XML in memory
  3.  We can’t insert or delete a node
  4.  Top to bottom traversing
DOM
  1. Stores the entire XML document into memory before processing.
  2. Occupies more memory
  3. We can insert or delete nodes
  4. Traverse in any direction.
If we need to find a node and doesn’t need to insert or delete we can go with SAX
itself otherwise we can use DOM parser, provided we have enough memory in place.
  
Conclusion
I hope this document will be useable to enlighten a beginner to be able to successfully
code for extracting data from an xml. XMLs are one of the most widely used
structures for storing data, and Java provides the most commonly used parsers. In real
life situations, we receive XMLs from a third party source which are needed to be
parsed & data need to be stored in databases. These motives can be easily met using
DOM or SAX XML parsers in Java.
We can have a JMS configured system where XMLs are received in a
automated way(these can be done using MDB), the same XMLs can be parsed using
Java parsers. The parser code can be scheduled to run automatically using a .ksh
script. The parsed value can be easily stored in oracle databases using simple JDBC
codes. In most of the IT projects XML sizes are usually huge & those are complex. In
such cases it is not possible to use DOM parser, but SAX parser is used frequently.
Although DOM parsers are easier to be coded, SAX parsers are more rapidly used in
case of real-life systems. 
[ Read More ]
Read more...
Older Posts
Subscribe to: Posts ( Atom )

List of Java Programs

  • Java Program to check Greater between the Two Number
  • Java Program to find that given number is Palindrome or not
  • Java Program to Demonstrate the Use of Pre and Post Operator
  • Java Program to Reverse the Given Number
  • Java Program to Print Number in the Given Data Type
  • Program to Demonstrate Skipping using Continue
  • Program to find whether entered character is a vowel or Consonant
  • Java Program to Calculate the Sum of Digits of Given Number
  • How to swap two numbers using only two variables
  • Checking the Given Number is Armstrong or Not
  • Average an Array of Values
  • Display ASCII Code Instead of Character
  • Comparison of Two Variable using If
  • Printing Table In java using While Loop
  • Generate Random Number Using Math.Random Function
  • To Find roots of Quadratic Equation
  • Performing Arithmetic Opration on Two Variable
  • Concatenation of Two String in Java
  • Command Line Argument in JAVA
  • Java Hello World Program
  • Calculate Circle Perimeter | Java Program
  • Calculate the Area of Circle | Java Program
  • To Find Whether Given Year is a Leap Year or not
  • Popular
  • Recent
  • Archives

Total Pageviews

Sparkline

Followers

Popular Posts of This Week

  • Sort an Integer array with Bucket Sort
    Here is a java program to Sort an Integer array with Bucket Sort class BucketSort { public int[] bucketSort(int[] array) { /...
  • Interthread Communication java
    class Q { int n; boolean valueSet = false; synchronized int get() { if(!valueSet) try { wait(); } cat...
  • Create an Adjacency matrix Graph and perform Add and Remove operation
    import java.util.ArrayList; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Queue; import...
  • Image encoding and decoding
    import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io....
  • Stop Watch Program - To measure the amount of time to process each input
    public class Stopwatch { private final long start; public Stopwatch() { start = System.currentTimeMillis(); } ...
  • Java Program to Generate the Lottery Number between 1 to 49
     A lottery requires that you select six different numbers from the integers 1 to 49. Write a program to do this for you and generate five s...
  • To Sort an Interger Array using Shell Sort
    To Sort an Interger Array using Shell Sort class ShellSort { public static int[] shellSort(int[] array) { int N = array.length; ...
  • String Search through FTP files
    Searching for a string through number of files in an FTP folder manually is a cumbersome process especially when the number of files in the ...
  • Thread Manager
    ThreadManager is a generalized class to work with java threads of specified count in a controlled manner Features - Contains synchronized m...
  • Java - Excel Connectivity
    This contains the sample code for Java Excel Connectivity import java.sql.*; import java.io.*; import java.util.*; import java.text.*; /*...
Powered by Blogger.

Archives

  • ▼  2014 ( 4 )
    • ▼  August ( 4 )
      • Java program to create a Binary Heap and Perform v...
      • Create an Adjacency matrix Graph and perform Add a...
      • To Sort an Interger Array using Shell Sort
      • Sort an Integer array with Bucket Sort
  • ►  2013 ( 6 )
    • ►  August ( 1 )
    • ►  April ( 5 )
  • ►  2012 ( 673 )
    • ►  November ( 9 )
    • ►  October ( 223 )
    • ►  September ( 272 )
    • ►  August ( 2 )
    • ►  June ( 1 )
    • ►  February ( 67 )
    • ►  January ( 99 )
 

Our Blogs

  • Linux Tutorial
  • C Programming Tutorial

Labels

  • Agile Methodology ( 1 )
  • Algorithm ( 3 )
  • AntiSamy ( 1 )
  • Arithmetic Operation ( 1 )
  • Array Example ( 9 )
  • ArrayList Examples ( 11 )
  • Average an Array of Values ( 1 )
  • Barcode Example ( 1 )
  • Basic Java Programs ( 34 )
  • Bing API Example ( 2 )
  • BitSet Example ( 1 )
  • Boolean Example ( 1 )
  • Bouncy Castle API ( 1 )
  • Break Statement ( 2 )
  • BufferedReader Example ( 2 )
  • Calendar Example ( 1 )
  • Chart Generation Example ( 1 )
  • Command Line Argument ( 1 )
  • Comparator Example ( 1 )
  • Concatenation of String ( 1 )
  • Continue Statement ( 1 )
  • Control Structure ( 1 )
  • Copy File Example ( 1 )
  • CRC Example ( 1 )
  • CSV Example ( 6 )
  • Data Structure ( 5 )
  • Date Example ( 2 )
  • Directory Example ( 1 )
  • Do - While Loop Example ( 1 )
  • Domino Database ( 1 )
  • Email Example ( 8 )
  • Encryption Example ( 3 )
  • Excel Example ( 15 )
  • Factorial Example ( 1 )
  • File Upload Example ( 1 )
  • Find Roots of Quadratic Equation ( 1 )
  • FTP Example ( 2 )
  • Graph Examples ( 1 )
  • Greater between Two Numbers ( 1 )
  • GSON Library ( 1 )
  • HashMap Example ( 1 )
  • HashSet Example ( 1 )
  • Hello World Program ( 1 )
  • If Condition ( 2 )
  • Inner Class Example ( 1 )
  • iText Example ( 3 )
  • JAR File ( 1 )
  • JAVA Applet ( 1 )
  • Java Applications ( 1 )
  • Java AWT Example ( 9 )
  • Java Certification ( 1 )
  • Java Class Examples ( 15 )
  • Java Collection Example ( 1 )
  • Java Command Example ( 4 )
  • Java Constructor Examples ( 1 )
  • Java Currency Example ( 1 )
  • Java Database Example ( 3 )
  • Java Date and Time Example ( 3 )
  • Java DateFormat Example ( 3 )
  • Java Examples ( 2 )
  • Java Exception Example ( 5 )
  • Java File Example ( 22 )
  • Java GUI Example ( 1 )
  • Java Image Examle ( 3 )
  • Java Inheritance Example ( 3 )
  • Java Input Output Example ( 1 )
  • Java IO Example ( 3 )
  • Java Jar Example ( 1 )
  • Java JSON Example ( 3 )
  • Java Mail Examples ( 4 )
  • Java Map Example ( 5 )
  • Java MapReduce Example ( 2 )
  • Java MultiThreading Example ( 7 )
  • Java Network Example ( 9 )
  • Java Package ( 1 )
  • Java Programs ( 1 )
  • Java RMI ( 1 )
  • Java Robot Class Examples ( 2 )
  • Java Runtime Example ( 1 )
  • Java Swing Example ( 9 )
  • Java Util Example ( 1 )
  • Java Vector Example ( 4 )
  • Java Voice Example ( 1 )
  • Java Webservice Example ( 1 )
  • Java XML Example ( 3 )
  • Java Zip Class Examples ( 2 )
  • JDBC ( 9 )
  • JDK Version Comparison ( 1 )
  • JFrame Example ( 3 )
  • JOptionPane Dialog Example ( 1 )
  • JPanel Example ( 1 )
  • JSP Example ( 2 )
  • JSTL Example ( 1 )
  • jUnit Example ( 2 )
  • LinkedList Example ( 2 )
  • List Example ( 1 )
  • Long Variable ( 1 )
  • Lottery Nubmer ( 1 )
  • MD5 Hashing Example ( 3 )
  • Memory Management Example ( 1 )
  • Method Override ( 1 )
  • MIDI Sound ( 8 )
  • Module Operator Example ( 2 )
  • Multiplication Table ( 1 )
  • Observer Interface Example ( 1 )
  • Operator Example ( 5 )
  • Pagination ( 1 )
  • Palindrome Number ( 1 )
  • Pass By Reference Example ( 1 )
  • Pass By Value Example ( 1 )
  • PDF File Example ( 3 )
  • PDF Generation Example ( 4 )
  • Pre and Post Operator ( 2 )
  • Prime Number ( 3 )
  • Progress Bar Example ( 1 )
  • Property List Example ( 2 )
  • Random Function ( 7 )
  • Recursion Example ( 2 )
  • Regex Example ( 2 )
  • Remote Host Example ( 2 )
  • Robot Class ( 4 )
  • Searching Example ( 3 )
  • Slideshow ( 1 )
  • Sorting Example ( 7 )
  • SpringLayout Example ( 1 )
  • Stack Example ( 4 )
  • Static Variable ( 1 )
  • StreamTokenizer Example ( 2 )
  • String Example ( 19 )
  • Struts2 Example ( 1 )
  • Sum of Digits ( 1 )
  • Swap Two Numbers ( 1 )
  • Switch Case ( 3 )
  • Tapestry Components ( 1 )
  • Thumbnail Example ( 2 )
  • TimerTask Example ( 2 )
  • To Calculate Volume ( 1 )
  • To Check Armstrong Number ( 1 )
  • Tree Example ( 1 )
  • TreeMap Example ( 1 )
  • TreeSet Example ( 1 )
  • Two Dimensional Array Example ( 1 )
  • UUID ( 1 )
  • Validation Example ( 2 )
  • Variable Casting ( 1 )
  • While Loop ( 1 )
  • XML Parsing ( 7 )
  • XSS Attacks ( 1 )
  • Zip File ( 15 )

Popular Posts

  • Java program to create a Binary Heap and Perform various operation
    A binary heap (min-heap) is a complete binary tree with elements from a partially ordered set, such that the element at every node is less ...
  • To Sort an Interger Array using Shell Sort
    To Sort an Interger Array using Shell Sort class ShellSort { public static int[] shellSort(int[] array) { int N = array.length; ...
  • Java Class to Calculate the Volume of Box
    Here is a Java Class to Calculate the Volume of Box. class Box { double width; double height; double depth; // This is the con...
  • Implementation of a basic generic tree, with labels of type T - Data Structure
    // This implements a basic generic tree, with labels of type T, // pointer to the parent node, and a singly linked list of children nodes...
  • Printing Table In java using While Loop
    Here is a Java Program to Print the Table public class Table { public static void main(String[] args) { int no = Integer.p...
  • Create an Adjacency matrix Graph and perform Add and Remove operation
    import java.util.ArrayList; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Queue; import...
  • Sort an Integer array with Bucket Sort
    Here is a java program to Sort an Integer array with Bucket Sort class BucketSort { public int[] bucketSort(int[] array) { /...
  • Merge-Sort Algorithm implementation in JAVA
    Merge-Sort Function void MergeSort(int low, int high) // a[low : high] is a global array to be sorted. // Small(P) is true if there...
  • Stack implemented as array - Data Structure
    // Stack implemented as array public class ArrayStack<T> { private T[] stack; private int numElements = 0; // points to s...
  • Performing Arithmetic Opration on Two Variable in Java
    Here is a Program to Perform the Arithmetic Operation between two Variable public class IntOps { public static void main(String[] ar...
 
 
© 2011 Java Programs and Examples with Output | Designs by Web2feel & Fab Themes

Bloggerized by DheTemplate.com - Main Blogger