skip to main | skip to sidebar

Java Programs and Examples with Output

Pages

▼
 
  • RSS
  • Twitter
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  


}

Labels: XML Parsing

Leave a Reply

Newer Post Older Post
Subscribe to: Post Comments ( Atom )
  • Popular
  • Recent
  • Archives
Powered by Blogger.
 
 
 
© 2011 Java Programs and Examples with Output | Designs by Web2feel & Fab Themes

Bloggerized by DheTemplate.com - Main Blogger