/*
Created on Nov 29, 2006
Modification :
1-If only 50% is defined in Employee Master , then System should not allow to make a voucher & should give error. When try to enter manually then also the error
Code added On [23052007] 
2-[09062007] Enter sitecode eand employee bank site should same
*/
package ibase.webitm.ejb.fin;

import java.rmi.RemoteException;
import java.sql.*;
import java.text.*;
import java.io.ByteArrayOutputStream;
import org.w3c.dom.*;


import javax.ejb.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.Transformer;
import javax.naming.InitialContext;

import ibase.utility.CommonConstants;
import ibase.system.config.*;
import ibase.webitm.ejb.ProcessEJB;
import ibase.webitm.utility.ITMException;
import ibase.webitm.utility.GenericUtility;
import ibase.webitm.utility.TransIDGenerator;
import ibase.webitm.ejb.*;
import ibase.webitm.utility.TaxCalculation;
import java.util.Vector;
import java.io.*;
import ibase.webitm.ejb.MasterStatefulLocal;//added for ejb3
import ibase.webitm.ejb.MasterStatefulEJB;//addes for ejb3
import javax.ejb.Stateless; // added for ejb3
@Stateless // added for ejb3

public class MiscPayAutoPrc extends ProcessEJB implements MiscPayAutoPrcLocal,MiscPayAutoPrcRemote //SessionBean
{
	
	File mkd = new File("C:\\pb10\\log");
	File filePtr = new File("c:\\pb10\\log\\MiscPayAutoPrc.log");
	String taxAmt = "0.0";
	String blankTaxString = null;
	StringBuffer processLogBuffer = null;
	StringBuffer buffer = null;
	StringBuffer tranIdRetBuff= null;
	
   /* public void create()throws RemoteException,CreateException{}
    public void remove()throws RemoteException{}
    public void ejbActivate(){}
    public void ejbPassivate(){}*/
	public void setSessionContext(SessionContext mSessionContext){}
	public String getData(String xmlString, String xmlString2, String windowName, String xtraParams) throws RemoteException,ITMException
	{
	    String resultString = "";
	    Document dom = null, dom2 = null;
	    try{
	        System.out.println("xmlString :"+xmlString+"\nxmlString2 :"+xmlString2);
		    if(xmlString != null){
		        dom = GenericUtility.getInstance().parseString(xmlString);
		    }
		    if(xmlString2 != null){
		        dom2 = GenericUtility.getInstance().parseString(xmlString2);
		    }
		    resultString = getData(dom,dom2,windowName,xtraParams);
	    }catch(ITMException e){
	        System.out.println("ITMException : "+e);
	        e.printStackTrace();
	        throw e;
	    }catch(Exception e){
	        System.out.println("Exception : "+e);
	        e.printStackTrace();
	        throw new ITMException(e);
	    }
	    return resultString; 
	}

	public String getData(Document dom, Document dom2, String windowNamem, String xtraParams) throws RemoteException,ITMException
	{
		if(!mkd.exists())
		{
			mkd.mkdirs(); 
			writeLog(filePtr,"Directory Built ["+mkd+"]...",false);
			
		}
		else
		{
				writeLog(filePtr,"Directory Exist ...",false);
		}
		writeLog(filePtr,"Process Data Start Time["+new java.sql.Timestamp(System.currentTimeMillis()).toString()+"]",false);
	
	    Connection conn = null;
	    PreparedStatement pstmt = null;
	    ResultSet rs = null;
	    String sql = "";
	    StringBuffer tabSeparatedData = new StringBuffer();
	    String frDate = "",toDate = "",frVoucher = "", toVoucher = "", siteCode = "",bankCode = "";
	    String sundryType = "",sundryCode = "",payMode = "",batchNo = "",chequeSplit = "",bankCodeAdd = "";
	    ConnDriver connDriver = new ConnDriver();
	    try{
	        conn = connDriver.getConnectDB();
	        frDate = GenericUtility.getInstance().getColumnValue("date__fr",dom);
	        toDate = GenericUtility.getInstance().getColumnValue("date__to",dom);
	        frVoucher = GenericUtility.getInstance().getColumnValue("vouch_no__fr",dom);
	        toVoucher = GenericUtility.getInstance().getColumnValue("vouch_no__to",dom);
	        siteCode = GenericUtility.getInstance().getColumnValue("site_code__fr",dom);
	        bankCode = GenericUtility.getInstance().getColumnValue("bank_code",dom);
	        sundryType = GenericUtility.getInstance().getColumnValue("sundry_type",dom);
	        sundryCode = GenericUtility.getInstance().getColumnValue("sundry_code",dom);
	        payMode = GenericUtility.getInstance().getColumnValue("pay_mode",dom);
	        batchNo = GenericUtility.getInstance().getColumnValue("entry_batch_no",dom);
	        chequeSplit = GenericUtility.getInstance().getColumnValue("chq_split",dom);
	        bankCodeAdd = GenericUtility.getInstance().getColumnValue("bank_code__add",dom);
	        if(frVoucher == null || frVoucher.trim().length() == 0){
	            frVoucher = "0";
	        }
	        if(toVoucher == null || toVoucher.trim().length() == 0){
	            toVoucher = "Z";
	        }
	        if(sundryType == null){
	            sundryType = "%";
	        }
	        else{
	            sundryType = sundryType + "%";
	        }
	        if(sundryCode == null){
	            sundryCode = "%";
	        }
	        else{
	            sundryCode = sundryCode + "%";
	        }
	        if(batchNo == null){
	            batchNo = "%";
	        }
	        else{
	            batchNo = batchNo + "%";
	        }
	        if(frDate!= null && frDate.indexOf("-") != -1){
	            frDate = frDate.replace('-','/');
	        }
	        if(toDate!= null && toDate.indexOf("-") != -1){
	            toDate = toDate.replace('-','/');
	        }
	       /* Timestamp frDateTimestamp = Timestamp.valueOf(GenericUtility.getInstance().getValidDateString(frDate.substring(0,8),GenericUtility.getInstance().getApplDateFormat(),GenericUtility.getInstance().getDBDateFormat()));
	        Timestamp toDateTimestamp = Timestamp.valueOf(GenericUtility.getInstance().getValidDateString(toDate.substring(0,8),GenericUtility.getInstance().getApplDateFormat(),GenericUtility.getInstance().getDBDateFormat()));
	        System.out.println("frDate.substring(0,8)::::"+frDate.substring(0,8));
	        System.out.println("toDate.substring(0,8)::::"+toDate.substring(0,8));*/
	        
	        String frDate1  = GenericUtility.getInstance().getValidDateString(frDate.substring(0,8),GenericUtility.getInstance().getApplDateFormat(),GenericUtility.getInstance().getDBDateFormat());
	        String toDate1 = GenericUtility.getInstance().getValidDateString(toDate.substring(0,8),GenericUtility.getInstance().getApplDateFormat(),GenericUtility.getInstance().getDBDateFormat());
	        System.out.println("FromDate :["+frDate1+"]");
	        System.out.println("ToDate :["+toDate1+"]");
	        Timestamp frDateTimestamp = Timestamp.valueOf(frDate1+" 00:00:00");
	        Timestamp toDateTimestamp = Timestamp.valueOf(toDate1+" 00:00:00");
	        
	        sql = "SELECT MISC_PAYABLES.REF_NO,MISC_PAYABLES.TRAN_DATE,MISC_PAYABLES.REF_DATE,MISC_PAYABLES.BILL_NO,"
	            +"MISC_PAYABLES.BILL_DATE,MISC_PAYABLES.CURR_CODE,MISC_PAYABLES.EXCH_RATE,MISC_PAYABLES.SUNDRY_CODE,"   
	            +"MISC_PAYABLES.ACCT_CODE,MISC_PAYABLES.CCTR_CODE,MISC_PAYABLES.DUE_DATE,MISC_PAYABLES.SITE_CODE,"
	            +"MISC_PAYABLES.FIN_ENTITY,MISC_PAYABLES.TOT_AMT,MISC_PAYABLES.SUNDRY_TYPE,MISC_PAYABLES.BANK_CODE,"
	            +"CASE WHEN MISC_PAYABLES.PAY_MODE IS NULL THEN '' ELSE MISC_PAYABLES.PAY_MODE END,MISC_PAYABLES.ADV_AMT,MISC_PAYABLES.TRAN_ID,MISC_PAYABLES.TRAN_SER,MISC_PAYABLES.ADJ_AMT,"
	            +"MISC_PAYABLES.HOLD_AMT, fn_confirmed_by(misc_payables.tran_ser, misc_payables.ref_no) as username,"
	            +"misc_payables.tot_amt - (case when misc_payables.adj_amt is null then 0 else misc_payables.adj_amt end) - (case when misc_payables.hold_amt is null then 0 else misc_payables.hold_amt end) as net_payable "  
	            +"FROM MISC_PAYABLES  WHERE ( misc_payables.site_code  = '"+siteCode+"' ) AND " 
	            +" ( misc_payables.sundry_type like '"+sundryType+"' ) AND  "
	            +" ( misc_payables.sundry_code like '"+sundryCode+"' ) AND  "
	            +" ( misc_payables.due_date >= ? ) AND "
	            +" ( misc_payables.due_date <= ? ) AND "
	            +" ( misc_payables.ref_no >= '"+frVoucher+"' ) AND "
	            +" ( misc_payables.ref_no <= '"+toVoucher+"' ) AND "
	            +" ( misc_payables.auto_pay = 'Y' ) AND "
	            +" (misc_payables.tot_amt - misc_payables.adj_amt <>  0 ) AND "
	            +" (misc_payables.hold_amt is null or misc_payables.tot_amt - misc_payables.adj_amt - misc_payables.hold_amt <>  0 ) AND "
	            +"  (misc_payables.pay_mode like '"+payMode+"' or misc_payables.pay_mode is null) AND "
	            +"  misc_payables.entry_batch_no like '"+batchNo+"' "
	            +" ORDER BY MISC_PAYABLES.SUNDRY_TYPE ASC,"
	            +" MISC_PAYABLES.SUNDRY_CODE ASC," 
	            +" MISC_PAYABLES.REF_NO ASC   ";
			System.out.println("Executing SQL :: "+sql);
			writeLog(filePtr,"Executing SQL (GET DATA):: "+sql,true);
			pstmt = conn.prepareStatement(sql);
			pstmt.setTimestamp(1,frDateTimestamp);
			System.out.println("Setting From Date:::["+frDateTimestamp+"]");
			writeLog(filePtr,"Setting From Date:::["+frDateTimestamp+"]",true);
			pstmt.setTimestamp(2,toDateTimestamp);
			System.out.println("Setting To Date:::["+toDateTimestamp+"]");
			writeLog(filePtr,"Setting To Date:::["+toDateTimestamp+"]",true);
			
			rs = pstmt.executeQuery();
	        while(rs.next()){
	            tabSeparatedData.append(rs.getString(1)).append("\t");
	            tabSeparatedData.append(rs.getString(2)).append("\t");
	            tabSeparatedData.append(rs.getString(3)).append("\t");
	            tabSeparatedData.append(rs.getString(4)).append("\t");
	            tabSeparatedData.append(rs.getString(5)).append("\t");
	            tabSeparatedData.append(rs.getString(6)).append("\t");
	            tabSeparatedData.append(rs.getString(7)).append("\t");
	            tabSeparatedData.append(rs.getString(8)).append("\t");
	            tabSeparatedData.append(rs.getString(9)).append("\t");
	            tabSeparatedData.append(rs.getString(10)).append("\t");
	            tabSeparatedData.append(rs.getString(11)).append("\t");
	            tabSeparatedData.append(rs.getString(12)).append("\t");
	            tabSeparatedData.append(rs.getString(13)).append("\t");
	            tabSeparatedData.append(rs.getString(14)).append("\t");
	            tabSeparatedData.append(rs.getString(15)).append("\t");
	            tabSeparatedData.append(rs.getString(16)).append("\t");
	            tabSeparatedData.append((rs.getString(17) == null) ? "":rs.getString(17)).append("\t");
	            tabSeparatedData.append(rs.getString(18)).append("\t");
	            tabSeparatedData.append(rs.getString(19)).append("\t");
	            tabSeparatedData.append(rs.getString(20)).append("\t");
	            tabSeparatedData.append(rs.getString(21)).append("\t");
	            tabSeparatedData.append(rs.getString(22)).append("\t");
	            tabSeparatedData.append(rs.getString(23)).append("\t");
	            tabSeparatedData.append(rs.getString(24)).append("\n");
	        }
	        
	        System.out.println("processLogBuffer=["+processLogBuffer);
	        writeLog(filePtr,"tabSeparatedData :: "+tabSeparatedData.toString(),true);
	        wirteLog(processLogBuffer,"BankPaymenViewTrace.txt","logfile_path",false);
			processLogBuffer.delete(0,processLogBuffer.toString().length());
			processLogBuffer = null;
	    }
	    catch(Exception e)
	    {
	    	//writeTrace(processLogBuffer,e);
	        throw new ITMException(e);
	    }
	    finally
	    {
	        try
	        {
	            if(rs != null)
	            {
	                rs.close();
	                rs = null;
	            }
	            if(pstmt != null)
	            {
	                pstmt.close();
	                pstmt = null;
	            }
	            if(conn != null)
	            {
	                conn.close();
	                conn = null;
	            }
	        }
	        catch(Exception e){}
	    }	    
	    System.out.println("tabSeparatedData :: "+tabSeparatedData.toString());
	    
	    return tabSeparatedData.toString();
	}
	
	public String process(String xmlString, String xmlString2, String windowName, String xtraParams) throws RemoteException,ITMException
	{
	    String returnString = "";
	    Document dom = null,dom2 = null;
	    try
	    {
	        System.out.println("Process :: \n xmlString : "+xmlString+"\n xmlString2 :"+xmlString2);
	        if(xmlString != null)
	        {
	            dom = GenericUtility.getInstance().parseString(xmlString);
	        }
	        if(xmlString2 != null)
	        {
	            dom2 = GenericUtility.getInstance().parseString(xmlString2);
	        }
	        returnString = process(dom,dom2,windowName,xtraParams);
	    }
	    catch(ITMException e)
	    {
	        System.out.println("ITMException :"+e);
	        e.printStackTrace();
	        throw e;
	    }
	    catch(Exception e)
	    {
	        System.out.println("Exception :"+e);
	        e.printStackTrace();
	        throw new ITMException(e);
	    }
	    return returnString;
	}
	
	public String process(Document headerDom, Document detailDom, String windowName, String xtraParams) throws RemoteException,ITMException
	{	
		if(!mkd.exists())
		{
			mkd.mkdirs(); 
			writeLog(filePtr,"Directory Built ["+mkd+"]...",false);
			
		}
		else
		{
				writeLog(filePtr,"Directory Exist ...",false);
		}
		writeLog(filePtr,"Process Data Start Time["+new java.sql.Timestamp(System.currentTimeMillis()).toString()+"]",true);
		tranIdRetBuff = new StringBuffer();
		buffer = new StringBuffer();
	    String resultString = null;

	    String chequeSplit= "";
	    try
	    {
			writeLog(filePtr,"Header Dom::::["+ GenericUtility.getInstance().serializeDom(headerDom)+"]",true);
			writeLog(filePtr,"Detail Dom::::["+ GenericUtility.getInstance().serializeDom(detailDom)+"]",true);
			writeLog(filePtr,"windowName::::["+ windowName+"]",true);
			writeLog(filePtr,"xtraParams::::["+ xtraParams+"]",true);
			
	        resultString = miscAutoPay(headerDom,detailDom,windowName,xtraParams);
	        writeLog(filePtr,"Result String => "+resultString,true);
	        System.out.println("Result String => "+resultString);
	        if(resultString == null)
	        {
		        if(tranIdRetBuff.length()>0)
				{
					//tranIdRetBuff.deleteCharAt((tranIdRetBuff.length() - 1));
					resultString = tranIdRetBuff.toString();
				}
			}
			if(buffer.toString().length()>0)
			{
				wirteLog(buffer,"BankPayment.txt","logfile_path",false);
			
			}
	    }
	    
	    catch(Exception e)
	    {
	    	writeLog(filePtr,e,true);
	        System.out.println("ITMException : "+e);
	       
	    }
	     System.out.println("Result String => "+resultString);
	    
	  	writeLog(filePtr,"String return From My Component ["+resultString+"]",true);
	  	System.out.println("String return From My Component ["+resultString+"]");
	  	
	    return resultString;
	}
	
	private String miscAutoPay(Document headerDom, Document detailDom, String windowName, String xtraParams)throws ITMException
	{
	    Connection conn = null;
	    Statement stmt = null;
	    PreparedStatement pstmt = null;
	    ResultSet rs = null;
	    String filtRefNo = "",filtRefNoUpto = "", filtBankCode = "",filtTranDate = "";
	    String filtPost = "",filtExchRate = "",filtChequeSplit = "",filtTaxEnv = "";
	    String filtSundryType = "",filtSundryCode = "",filtPayMode = "";
	    String detPayModePrev = "",detPayModeCurr = "",detSundryTypePrev = "",detSundryTypeCurr = "";
	    String detSundryCodePrev = "",detSundryCodeCurr = "",detCurrCode = "",detExchRate = "";
	    String detVaouchNo = "",detVouchDate = "",detTranSer = "",detFinent = "",detSitecode = "";
	    String detAcctcodeAP = "",detCctrCodeAP = "",detPayAmt = "",detAdjAmt = "",detHoldAmt = "";
	    String detDueDate = "";
	    String tranType = "",loginUser = "",sql = "",tranID = "",insertSql = "",remarks = "";
	    String termID = "",currCodeBc = "",exchRateBc = "",filtBankCodeAdd = "",filtBankCodeAddName = "";
	    String acctCodeBal = "",cctrCodeBal = "",acctCodeBc = "",cctrCodeBc = "",acctCodeCf = "";
	    String acctCodeCfAp = "",cctrCodeCfAp = "",cctrCodeCf = "",updateSql = "",exchRateHdr = "";
	    String empBank[][] = null;
	    SimpleDateFormat sdf = null;
	    ConnDriver connDriver = new ConnDriver();
	    FinCommon finCommon = new FinCommon();
	    
	    double totAmt = 0,adjAmt = 0,holdAmt = 0,payAmt = 0,diffAmt = 0,totalDiffAmt = 0,totAmtBc = 0;
	    double sundryAmt = 0;
	    double taxAmount = 0,totalTax = 0;
	    int lineNo = 0;
	    boolean paymentFlag = true;
	    NodeList detailNodeList = null;
	    Node detailNode = null;
	    int nodeListLength = 0;
	    Vector sunCodeVec = new Vector();
	    
	    String errCode = null;
	    String errString = null;
	   
	    
	    try{
	        conn = connDriver.getConnectDB("DriverITM");
	        //conn.setAutoCommit(false);
	        System.out.println("xtraParams : "+xtraParams);
	        writeLog(filePtr,"xtraParams : "+xtraParams,true);
	        loginUser = GenericUtility.getInstance().getValueFromXTRA_PARAMS(xtraParams,"loginCode");
	        termID = GenericUtility.getInstance().getValueFromXTRA_PARAMS(xtraParams,"termId");
	        tranType = finCommon.getFinparams("999999","TRAN_TYPE_AUTO_PAY",conn);
	        sdf = new SimpleDateFormat(GenericUtility.getInstance().getApplDateFormat());
	        if(tranType.equalsIgnoreCase("NULLFOUND"))  
	        tranType = "O";
	        filtRefNo = GenericUtility.getInstance().getColumnValue("ref_no",headerDom); //last cheque no
	        filtRefNoUpto = GenericUtility.getInstance().getColumnValue("ref_no__upto",headerDom);
	        filtBankCode = GenericUtility.getInstance().getColumnValue("bank_code",headerDom); // Filter Bank Code
	        filtTranDate = GenericUtility.getInstance().getColumnValue("date__pay",headerDom);
	        filtPost = GenericUtility.getInstance().getColumnValue("post",headerDom);
	        filtExchRate = GenericUtility.getInstance().getColumnValue("exch_rate",headerDom);
	        filtChequeSplit = GenericUtility.getInstance().getColumnValue("chq_split",headerDom);
	        filtPayMode = GenericUtility.getInstance().getColumnValue("pay_mode",headerDom);
	        filtSundryType = GenericUtility.getInstance().getColumnValue("sundry_type",headerDom);
	        filtSundryCode = GenericUtility.getInstance().getColumnValue("sundry_code",headerDom);
	        filtBankCodeAdd = GenericUtility.getInstance().getColumnValue("bank_code__add",headerDom);
	        filtBankCodeAddName = GenericUtility.getInstance().getColumnValue("bank_name__add",headerDom);
	        filtTaxEnv = GenericUtility.getInstance().getColumnValue("tax_env",headerDom);
	        String  siteCode = GenericUtility.getInstance().getColumnValue("site_code__fr",headerDom);
	        
	        if(filtTranDate.indexOf("-") != -1)
	        {
	            filtTranDate = filtTranDate.replace('-','/');
	        }
	        filtTranDate = filtTranDate.substring(0,8);
	        detailNodeList = detailDom.getElementsByTagName("Detail2");
		    nodeListLength = detailNodeList.getLength();
		    for(int n = 0;n < nodeListLength;n++)
		    {
		        detailNode = detailNodeList.item(n);
		        detPayModePrev = GenericUtility.getInstance().getColumnValueFromNode("pay_mode",detailNode);
		        detSundryTypePrev = GenericUtility.getInstance().getColumnValueFromNode("sundry_type",detailNode);
		        detSundryCodePrev = GenericUtility.getInstance().getColumnValueFromNode("sundry_code",detailNode);
		        if(!sunCodeVec.contains(detSundryCodePrev))
		        {
		        	errCode = null;
		        	sunCodeVec.add(detSundryCodePrev);
		            
			        detPayModeCurr = detPayModePrev;
			        detSundryTypeCurr = detSundryTypePrev;
			        detSundryCodeCurr = detSundryCodePrev;
			        remarks = "Automatic Payment ";
			        int  k = 0, r = 0;
			        if(filtSundryType.equalsIgnoreCase("E"))
			        {
			            sql = "select count(*) from employee_bank where emp_code = '"+detSundryCodePrev+"'";
			            writeLog(filePtr,"sql :::["+sql+"]",true);
				        stmt = conn.createStatement();
				        rs = stmt.executeQuery(sql);
				        
				        if(rs.next())
				        {
				            r = rs.getInt(1);
				        }
				        empBank = new String[r][3];
				        rs.close();
				        stmt.close();
				        //23052007
				        double totPerc = 0;
				        String percStr = null;
				        //added on 09062007
				        String siteCodeFrBnk = null;  
				       	sql = "SELECT BANK.SITE_CODE FROM EMPLOYEE_BANK,BANK WHERE EMPLOYEE_BANK.BANK_CODE = BANK.BANK_CODE AND EMP_CODE = '"+detSundryCodePrev+"'";
				       	System.out.println("sql :::["+sql+"]");
				       	writeLog(filePtr,"sql :::["+sql+"]",true);
				        stmt = conn.createStatement();
				        rs = stmt.executeQuery(sql);
				        while(rs.next())
				        {
				        	siteCodeFrBnk = null;
				        	siteCodeFrBnk = (rs.getString(1)==null?" ":rs.getString(1));
				        	if(!siteCodeFrBnk.equalsIgnoreCase(siteCode))
				        	{
				        		errCode = "SITEMISMAT";
				       	 		buffer.append("SITEMISMAT=").append("The Site code of employee ["+siteCodeFrBnk+"] and enter sitecode["+siteCode+"] (bank and entry)"+detSundryCodePrev+" does not match").append("\n");
				        	}
				        }
				        rs.close();
				        stmt.close();
			            
			            sql = "select bank_code,amt_type,amount from employee_bank where emp_code = '"+detSundryCodePrev+"'";
			            writeLog(filePtr,"sql :::["+sql+"]",true);
				        stmt = conn.createStatement();
				        rs = stmt.executeQuery(sql);
				        
				        while(rs.next())
				        {
				        	
				            empBank[k][0] = rs.getString(1);
				            empBank[k][1] = rs.getString(2);
				            empBank[k][2] = rs.getString(3);
				            
				            //23052007
				            if("P".equalsIgnoreCase(rs.getString(2)))
				            {
				            	percStr = 	((rs.getString(3)==null)?"0":rs.getString(3)); 
				            	System.out.println("Perc Str ["+percStr+"]");
				            	//writeTrace(processLogBuffer,"Perc Str ["+percStr+"]");
				            	writeLog(filePtr,"Perc Str ["+percStr+"]",true);
				            	totPerc = totPerc + Double.parseDouble(percStr);          
				        	}
				        	//end
				            k++; 
				        }
				        rs.close();
				        stmt.close();
				        percStr = null;
				        //23052007
				        System.out.println("Total Percentage ::::["+totPerc+"]");
				        writeLog(filePtr,"Total Percentage ::::["+totPerc+"]",true);
				        if(totPerc!=100 && totPerc!=0)
				        {
							buffer.append("PERCMISMAT=").append("The total percentage ["+totPerc+"]of the different bank of customer "+detSundryCodePrev+" not 100%").append("\n");
							errCode = "PERCMISMAT";
						 }
			        }
			        totAmt = 0;
			        lineNo = 0;
			        taxAmount = 0;
			        totalTax = 0;
			        if(errCode==null)
			        {
				        if(filtSundryType != null && filtSundryType.equalsIgnoreCase("E") && k > 0)
				        {
				            for(int j = n;j <= nodeListLength && detSundryCodeCurr.equalsIgnoreCase(detSundryCodePrev) && detPayModePrev.equalsIgnoreCase(detPayModeCurr); j++)
				            {
				                detPayModeCurr = GenericUtility.getInstance().getColumnValueFromNode("pay_mode",detailNode);
				                detSundryTypeCurr = GenericUtility.getInstance().getColumnValueFromNode("sundry_type",detailNode);
				                detSundryCodeCurr = GenericUtility.getInstance().getColumnValueFromNode("sundry_code",detailNode);
					                
				                detCurrCode = GenericUtility.getInstance().getColumnValueFromNode("curr_code",detailNode);
				                detVaouchNo = GenericUtility.getInstance().getColumnValueFromNode("ref_no",detailNode);
				                detVouchDate = GenericUtility.getInstance().getColumnValueFromNode("ref_date",detailNode);
				                detTranSer = GenericUtility.getInstance().getColumnValueFromNode("tran_ser",detailNode);
				                detFinent = GenericUtility.getInstance().getColumnValueFromNode("fin_entity",detailNode);
				                detSitecode = GenericUtility.getInstance().getColumnValueFromNode("site_code",detailNode);
				                detExchRate = GenericUtility.getInstance().getColumnValueFromNode("exch_rate",detailNode);
				                detAcctcodeAP = GenericUtility.getInstance().getColumnValueFromNode("acct_code",detailNode);
				                detCctrCodeAP = GenericUtility.getInstance().getColumnValueFromNode("cctr_code",detailNode);
					                
				                detPayAmt = GenericUtility.getInstance().getColumnValueFromNode("tot_amt",detailNode);
				                detAdjAmt = GenericUtility.getInstance().getColumnValueFromNode("adj_amt",detailNode);
				                detHoldAmt = GenericUtility.getInstance().getColumnValueFromNode("hold_amt",detailNode);
				                detDueDate  = GenericUtility.getInstance().getColumnValueFromNode("due_date",detailNode);
				                
								int count =0;
								sql = "select count(*)  from misc_payment where ref_no = '"+detVaouchNo+"'";
								System.out.println("sql  ["+sql+"]");
								 writeLog(filePtr,"sql  ["+sql+"]",true);
								stmt = conn.createStatement();
								rs = stmt.executeQuery(sql);
								if(rs.next())
								{
									count = rs.getInt(1);
								}
								rs.close();
								stmt.close();
								System.out.println("Count   ["+count+"]");
								  writeLog(filePtr,"Count   ["+count+"]",true);
								if(count >0)
								{
									ITMDBAccessEJB itmDBAccessEJB = new ITMDBAccessEJB();
									return(itmDBAccessEJB.getErrorString("","VOUCHEXIT",""));
								}
				                if(detDueDate != null && detDueDate.indexOf("-") != -1)
				                {
				                    detDueDate = detDueDate.replace('-','/');
				                    detDueDate = detDueDate.substring(0,8);
				                }
				                if(detVouchDate != null && detVouchDate.indexOf("-") != -1)
				                {
				                    detVouchDate = detVouchDate.replace('-','/');
				                    detVouchDate = detVouchDate.substring(0,8);
				                }
				                
				                if( sdf.parse(filtTranDate ).after(sdf.parse(detDueDate)) )
				                {
				                    detDueDate = filtTranDate;
				                }
				                if(filtBankCode == null)
				                {
				                    filtBankCode = "";
				                }
				                if(filtExchRate == null)
				                {
				                    filtExchRate = "1.0"; 
				                }
				                if(detAdjAmt != null){
				                    adjAmt = Double.parseDouble(detAdjAmt);		                
				                }
				                if(detHoldAmt != null){
				                    holdAmt = Double.parseDouble(detHoldAmt);
				                }
				                if(detPayAmt != null){
				                    payAmt = Double.parseDouble(detPayAmt);		                
				                }	
				                payAmt = payAmt - adjAmt - holdAmt;
				                if (payAmt < 0 ) payAmt = 0;
				               
				                totAmt = totAmt + payAmt;
				                System.out.println(" Value n is "+n+" Pay Amt : "+payAmt + "Total Amt : "+totAmt);
				                  writeLog(filePtr," Value n is "+n+" Pay Amt : "+payAmt + "Total Amt : "+totAmt,true);
				                n++;
						        j = n;    
						        if(n < nodeListLength)
						        {
						            detailNode = detailNodeList.item(n);
					                detPayModeCurr = GenericUtility.getInstance().getColumnValueFromNode("pay_mode",detailNode);
					                detSundryTypeCurr = GenericUtility.getInstance().getColumnValueFromNode("sundry_type",detailNode);
					                detSundryCodeCurr = GenericUtility.getInstance().getColumnValueFromNode("sundry_code",detailNode);
						        }   
				                if(!detSundryCodeCurr.equalsIgnoreCase(detSundryCodePrev) || !detPayModeCurr.equalsIgnoreCase(detPayModePrev) || n >= nodeListLength){
				                    n--;
				                    break;
				                }
				                if(detPayModeCurr == null)
				                {
				                    detPayModeCurr = "";
				                }			           
				            }
				            //
				            if(filtPayMode == null)
				            {
				                filtRefNo = "";
				            }		            
				            k = 0;
				            int row = 0;
				            int len = empBank.length;
				            double hdrAmount = 0,restAmount = totAmt;
				            
				            //added letter
				            
						/*	double amt = 0;
							while(row < len)
							{
								String amtType = empBank[row][1];
								if(amtType != null && amtType.equalsIgnoreCase("F"))
								{
							 		amt =  amt +Double.parseDouble(empBank[row][2]);
								}
								row++;
							}
							totAmt = totAmt - amt;
							System.out.println("Total amount ["+totAmt+"]");
							System.out.println("Fixed amount ["+amt+"]");
			                 
			                 
			                
				             row = 0;
				            len = empBank.length;*/
				            writeLog(filePtr,"Total no of Bank of Employee ["+detSundryCodePrev+"] :["+len+"]",true);
				                         
				            while(row < len)
				            {
				                String bankName = empBank[row][0];
			                    String amtType = empBank[row][1];
			                    String amount = empBank[row][2];
			                    
				                
								System.out.println("row :"+row+" len :"+len);
								writeLog(filePtr,"row :"+row+" len :"+len,true);
								System.out.println("bankName :"+bankName);
								System.out.println("amtType :"+amtType);
								 writeLog(filePtr,"amtType :"+amtType,true);
								System.out.println("Rest Amount :"+restAmount);
								writeLog(filePtr,"Rest Amount :"+restAmount,true);
								System.out.println("amount :"+amount);
								writeLog(filePtr,"amount :"+amount,true);
			                    
			                    if(filtRefNoUpto == null || filtRefNoUpto.trim().length() == 0)
			                    {
			                        filtRefNoUpto = "0";
			                    }
			                    if(filtPayMode.substring(0,1).equalsIgnoreCase("Q") || filtPayMode.substring(0,1).equalsIgnoreCase("D") || filtPayMode.substring(0,1).equalsIgnoreCase("T"))
			                    {
					                if(filtRefNo.trim().length() > 0)
					                {
					                    filtRefNo = Long.toString(Long.parseLong(filtRefNo) + 1);
					                }
					                if(Long.parseLong(filtRefNoUpto) > 0 && Long.parseLong(filtRefNo) > Long.parseLong(filtRefNoUpto))
					                {
					                    break;
					                }
					            }
			                    if(restAmount > 0)
			                    {
			                        if(amtType != null && amtType.equalsIgnoreCase("P"))
			                        {
				                        hdrAmount = totAmt * Double.parseDouble(amount)/100;
				                    }
				                    else if(amtType != null && amtType.equalsIgnoreCase("F"))
				                    {
				                        hdrAmount = Double.parseDouble(amount);
				                    }
				                    if(restAmount < hdrAmount || (row == len -1 && restAmount > hdrAmount))
				                    {
				                        hdrAmount = restAmount;
				                    }
				                    
				                    restAmount = restAmount  - hdrAmount;
				                    sql = "select acct_code__bal, cctr_code__bal, acct_code__bc, cctr_code__bc,acct_code__cf, "+
				    	        	"acct_code__cf_ap, cctr_code__cf, cctr_code__cf_ap from bank where bank_code = '"+bankName+"'";
				    		        System.out.println("SQL : "+sql);
				    		        writeLog(filePtr,"SQL : "+sql,true);
				    		        stmt = conn.createStatement();
				    		        rs = stmt.executeQuery(sql);
				    		        if(rs.next())
				    		        {
				    		            acctCodeBal = rs.getString("acct_code__bal");
				    		            cctrCodeBal = rs.getString("cctr_code__bal");
				    		            acctCodeBc = rs.getString("acct_code__bc");
				    		            cctrCodeBc = rs.getString("cctr_code__bc");
				    		            acctCodeCf = rs.getString("acct_code__cf");
				    		            acctCodeCfAp = rs.getString("acct_code__cf_ap");
				    		            cctrCodeCf = rs.getString("cctr_code__cf");
				    		            cctrCodeCfAp = rs.getString("cctr_code__cf_ap");
				    		        }
				    		        if(acctCodeCfAp == null || acctCodeCfAp.length() == 0)
				    		        {
				    		            acctCodeCfAp = acctCodeCf;
				    		        }
				    		        if(cctrCodeCfAp == null || cctrCodeCfAp.length() == 0)
				    		        {
				    		            cctrCodeCfAp = cctrCodeCf;
				    		        }
				    		        stmt.close();
				    		        rs.close();
					    		        
				                    String refSer = "",keyString = "",tranIdCol = "";
					                sql = "select key_string,ref_ser,tran_id_col from transetup where tran_window = 'w_misc_pay'";
					                System.out.println("SQL :: "+sql);
					                  writeLog(filePtr,"SQL : "+sql,true);
					                stmt = conn.createStatement();
					                rs = stmt.executeQuery(sql);
					                
					                if(rs.next())
					                {
					                    keyString = rs.getString("key_string");
					                    refSer = rs.getString("ref_ser");
					                    tranIdCol = rs.getString("tran_id_col");
					                }
						            
					                stmt.close();
				    		        rs.close();
				    		        //09062007 (set currCode bc with Curr Code
				    		        currCodeBc = detCurrCode;
				    		        
					                String xmlString = "<Detail1><tran_id></tran_id><site_code>"+detSitecode+"</site_code>"+
					                	"<tran_type>"+tranType+"</tran_type><tran_date>"+filtTranDate+"</tran_date>"+
					                	"<pay_mode>"+detPayModeCurr+"</pay_mode><bank_code>"+filtBankCode+"</bank_code></Detail1>";
					                TransIDGenerator tranIDgen = new TransIDGenerator(xmlString,loginUser,CommonConstants.DB_NAME);
					                
					                tranID = tranIDgen.generateTranSeqID(refSer,tranIdCol,keyString,conn);
					                
				                    insertSql = "insert into misc_payment (tran_id, tran_date,  tran_type, sundry_type, "+
					                	"sundry_code,pay_mode, bank_code, ref_no, ref_date, remarks, net_amt,curr_code,  "+
					                	"exch_rate, net_amt__bc, site_code, fin_entity, acct_code__bal, cctr_code__bal, "+
					                	"auto_paid, confirmed, chg_date,chg_user, chg_term, bank_charges, acct_code__bc, "+
					                	"cctr_code__bc,curr_code__bc, exch_rate__bc , chq_name, acct_code__cf, cctr_code__cf,tax_amt )"+
					                	"values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
				                    
					                System.out.println("insertSql : "+insertSql);
					                 writeLog(filePtr,"SQL : "+insertSql,true);
					                  writeLog(filePtr,"tranID : "+tranID,true);
					                pstmt = conn.prepareStatement(insertSql);
					                pstmt.setString(1,tranID);
					                pstmt.setTimestamp(2,Timestamp.valueOf(GenericUtility.getInstance().getValidDateTimeString(filtTranDate,GenericUtility.getInstance().getApplDateFormat(),GenericUtility.getInstance().getDBDateFormat())));
					                pstmt.setString(3,tranType);
					                pstmt.setString(4,detSundryTypePrev);//sundry Type
					                pstmt.setString(5,detSundryCodePrev);//sundry code
					                pstmt.setString(6,detPayModePrev);//pay mode
					                pstmt.setString(7,bankName);//bank code
					                pstmt.setString(8,filtRefNo);//ref_no
					                if(filtChequeSplit.equalsIgnoreCase("Y"))
					                {
					                    pstmt.setTimestamp(9,Timestamp.valueOf(GenericUtility.getInstance().getValidDateTimeString(filtTranDate,GenericUtility.getInstance().getApplDateFormat(),GenericUtility.getInstance().getDBDateFormat())));
					                }
					                else
					                {
					                    pstmt.setTimestamp(9,Timestamp.valueOf(GenericUtility.getInstance().getValidDateTimeString(detDueDate,GenericUtility.getInstance().getApplDateFormat(),GenericUtility.getInstance().getDBDateFormat())));
					                }
					                pstmt.setString(10,remarks);
					                pstmt.setDouble(11,hdrAmount);//net amt
					                pstmt.setString(12,detCurrCode);
					                pstmt.setDouble(13,Double.parseDouble(filtExchRate));
					                pstmt.setDouble(14,hdrAmount);
					                pstmt.setString(15,detSitecode);
					                pstmt.setString(16,detFinent);
					                pstmt.setString(17,acctCodeBal);
					                pstmt.setString(18,cctrCodeBal);
					                pstmt.setString(19,"Y");
					                pstmt.setString(20,"N"); 
					                pstmt.setTimestamp(21,new Timestamp(System.currentTimeMillis()));
					                pstmt.setString(22,loginUser);
					                pstmt.setString(23,termID);
					                pstmt.setDouble(24,0);
					                pstmt.setString(25,acctCodeBc);
					                pstmt.setString(26,cctrCodeBc);
					                pstmt.setString(27,currCodeBc);
					                pstmt.setDouble(28,Double.parseDouble(detExchRate));
					                pstmt.setString(29,filtBankCodeAddName);
					                pstmt.setString(30,acctCodeCfAp);
					                pstmt.setString(31,cctrCodeCfAp);
					                pstmt.setInt(32,0);
					                int upd = 0;
					                upd = pstmt.executeUpdate();
					                if(upd > 0)
						            {
						            	tranIdRetBuff.append(tranID).append(",");
						            	writeLog(filePtr,"Adding Tranid ["+tranID+"]",true);
						            }
					                System.out.println("Record Inserted in Misc Payment : "+upd);
					                writeLog(filePtr,"Record Inserted in Misc Payment : "+upd,true);
					                pstmt.close();
						            pstmt = null;
						            
						            lineNo++;
						            if(filtChequeSplit.equalsIgnoreCase("Y"))
						            {
						                insertSql = "insert into  misc_paydet ( tran_id,  tran_ser, vouch_no, vouch_date, net_amt, " +
					            		"pay_amt,curr_code, exch_rate__vouch, diff_amt__exch, acct_code__ap,cctr_code__ap, " +
					            		"sundry_type,sundry_code, bank_charges,drawn_at,stan_code) " +
					            		"values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
						            }
						            else
						            {
						                insertSql = "insert into  misc_paydet ( tran_id,  tran_ser, vouch_no, vouch_date, net_amt, " +
					            		"pay_amt,curr_code, exch_rate__vouch, diff_amt__exch, acct_code__ap,cctr_code__ap, " +
					            		"sundry_type,sundry_code, bank_charges,drawn_at,stan_code,tax_env,line_no, tax_amt, net_pay_amt) " +
					            		"values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
						            }
					                Timestamp detDate = Timestamp.valueOf(GenericUtility.getInstance().getValidDateTimeString(detVouchDate,GenericUtility.getInstance().getApplDateFormat(),GenericUtility.getInstance().getDBDateFormat()));
						            System.out.println("SQL : "+insertSql);
						            writeLog(filePtr,"insertSql : "+insertSql,true);
					                pstmt = conn.prepareStatement(insertSql);
						            pstmt.setString(1,tranID);
						            pstmt.setString(2,detTranSer);
						            pstmt.setString(3,detVaouchNo);
						            pstmt.setTimestamp(4,detDate);
						            pstmt.setDouble(5,hdrAmount);
						            pstmt.setDouble(6,hdrAmount);
						            pstmt.setString(7,detCurrCode);
						            pstmt.setDouble(8,Double.parseDouble(detExchRate));
						            pstmt.setDouble(9,diffAmt);
						            pstmt.setString(10,detAcctcodeAP);
						            pstmt.setString(11,detCctrCodeAP);
						            pstmt.setString(12,detSundryTypeCurr);
						            pstmt.setString(13,detSundryCodeCurr);
						            pstmt.setDouble(14,0);
						            pstmt.setString(15,"");//drawn at
						            pstmt.setString(16,"");//stan code
						            if(!filtChequeSplit.equalsIgnoreCase("Y")){
						                pstmt.setString(17,filtTaxEnv);
						                pstmt.setInt(18,lineNo);
						                pstmt.setInt(19,0);
						                pstmt.setDouble(20,hdrAmount);
						            }    
						            upd = pstmt.executeUpdate();
						            System.out.println("Record Inserted in Misc Payment Detail : "+upd);
						             writeLog(filePtr,"Record Inserted in Misc Payment Detail : "+upd,true);
						             //writeTrace(processLogBuffer,"Record Inserted in Misc Payment Detail : "+upd);	
						            pstmt.close();
						            pstmt = null;
						            if(filtChequeSplit.equalsIgnoreCase("Y") && filtTaxEnv != null && filtTaxEnv.trim().length() > 0)
						            {
						                //calculate tax & update misc pay detail
						                taxAmt = "0";
						                //handleTax(tranID,row,detVouchDate,Double.parseDouble(ls_Quantity.get(j).toString()),Double.parseDouble(ls_rate.get(j).toString()),"INR",ls_siteCode,row,taxClass,taxChap,taxEnv,ls_clgRate.get(j).toString(),ls_discount.get(j).toString());
						            }
			                    }
			                    row++;
			                } 
			            }
			            else
			            {
			            	  writeLog(filePtr,"filtSundryType != null && filtSundryType.equalsIgnoreCase(E) && k > 0..........",true);
			            	
			                if(filtBankCode == null)
			                {
			                	//Temporarily taken
			                    filtBankCode = "HDFC      ";
			                }
				            sql = "select acct_code__bal, cctr_code__bal, acct_code__bc, cctr_code__bc,acct_code__cf, "+
				        	"acct_code__cf_ap, cctr_code__cf, cctr_code__cf_ap from bank where bank_code = '"+filtBankCode+"'";
					        System.out.println("SQL : "+sql);
					        stmt = conn.createStatement();
					        rs = stmt.executeQuery(sql);
					        if(rs.next()){
					            acctCodeBal = rs.getString("acct_code__bal");
					            cctrCodeBal = rs.getString("cctr_code__bal");
					            acctCodeBc = rs.getString("acct_code__bc");
					            cctrCodeBc = rs.getString("cctr_code__bc");
					            acctCodeCf = rs.getString("acct_code__cf");
					            acctCodeCfAp = rs.getString("acct_code__cf_ap");
					            cctrCodeCf = rs.getString("cctr_code__cf");
					            cctrCodeCfAp = rs.getString("cctr_code__cf_ap");
					        }
					        if(acctCodeCfAp == null || acctCodeCfAp.length() == 0)
					        {
					            acctCodeCfAp = acctCodeCf;
					        }
					        if(cctrCodeCfAp == null || cctrCodeCfAp.length() == 0)
					        {
					            cctrCodeCfAp = cctrCodeCf;
					        }
					        stmt.close();
					        rs.close();
					        //detailNodeList = detailDom.getElementsByTagName("Detail2");
					        //nodeListLength = detailNodeList.getLength();
					        
				            paymentFlag = true;
				            totAmt = 0;
				            totalDiffAmt = 0;
				            sundryAmt = 0;
				            
				            for(int j=n;j < nodeListLength && detSundryCodeCurr.equalsIgnoreCase(detSundryCodePrev) &&  detPayModePrev.equalsIgnoreCase(detPayModeCurr);j++)
				            {
				                
				                detPayModeCurr = GenericUtility.getInstance().getColumnValueFromNode("pay_mode",detailNode);
				                detSundryTypeCurr = GenericUtility.getInstance().getColumnValueFromNode("sundry_type",detailNode);
				                detSundryCodeCurr = GenericUtility.getInstance().getColumnValueFromNode("sundry_code",detailNode);
					            
				                detCurrCode = GenericUtility.getInstance().getColumnValueFromNode("curr_code",detailNode);
					            detVaouchNo = GenericUtility.getInstance().getColumnValueFromNode("ref_no",detailNode);
					            detVouchDate = GenericUtility.getInstance().getColumnValueFromNode("ref_date",detailNode);
					            detTranSer = GenericUtility.getInstance().getColumnValueFromNode("tran_ser",detailNode);
					            detFinent = GenericUtility.getInstance().getColumnValueFromNode("fin_entity",detailNode);
					            detSitecode = GenericUtility.getInstance().getColumnValueFromNode("site_code",detailNode);
					            detExchRate = GenericUtility.getInstance().getColumnValueFromNode("exch_rate",detailNode);
					            detAcctcodeAP = GenericUtility.getInstance().getColumnValueFromNode("acct_code",detailNode);
					            detCctrCodeAP = GenericUtility.getInstance().getColumnValueFromNode("cctr_code",detailNode);
					            detPayAmt = GenericUtility.getInstance().getColumnValueFromNode("tot_amt",detailNode);
					            detAdjAmt = GenericUtility.getInstance().getColumnValueFromNode("adj_amt",detailNode);
					            detHoldAmt = GenericUtility.getInstance().getColumnValueFromNode("hold_amt",detailNode);
					            detDueDate  = GenericUtility.getInstance().getColumnValueFromNode("due_date",detailNode);
				                
				                if(detDueDate != null && detDueDate.indexOf("-") != -1)
				                {
				                    detDueDate = detDueDate.replace('-','/');
				                    detDueDate = detDueDate.substring(0,8);
				                }    
					            
					            if(detVouchDate != null && detVouchDate.indexOf("-") != -1)
					            {
					                detVouchDate = detVouchDate.replace('-','/');
					                detVouchDate = detVouchDate.substring(0,8);
					            }
					            if(detAdjAmt != null)
					            {
					                adjAmt = Double.parseDouble(detAdjAmt);		                
					            }
					            if(detHoldAmt != null)
					            {
					                holdAmt = Double.parseDouble(detHoldAmt);
					            }
					            if(detPayAmt != null)
					            {
					                payAmt = Double.parseDouble(detPayAmt);		                
					            }	
					            payAmt = payAmt - adjAmt - holdAmt;
					            totAmt = totAmt + payAmt;
						            
					            if(paymentFlag)
					            {
					                String refSer = "",keyString = "",tranIdCol = "";
					                sql = "select key_string,ref_ser,tran_id_col from transetup where tran_window = 'w_misc_pay'";
					                System.out.println("SQL :: "+sql);
					                
					                stmt = conn.createStatement();
					                rs = stmt.executeQuery(sql);
					                
					                if(rs.next())
					                {
					                    keyString = rs.getString("key_string");
					                    refSer = rs.getString("ref_ser");
					                    tranIdCol = rs.getString("tran_id_col");
					                }
						                
					                String xmlString = "<Detail1><tran_id></tran_id><site_code>"+detSitecode+"</site_code>"+
					                	"<tran_type>"+tranType+"</tran_type><tran_date>"+filtTranDate+"</tran_date>"+
					                	"<pay_mode>"+detPayModeCurr+"</pay_mode><bank_code>"+filtBankCode+"</bank_code></Detail1>";
					                TransIDGenerator tranIDgen = new TransIDGenerator(xmlString,loginUser,CommonConstants.DB_NAME);
					                
					                tranID = tranIDgen.generateTranSeqID(refSer,tranIdCol,keyString,conn);
					                
					                sql = "select curr_code from site, finent where site.fin_entity = finent.fin_entity "+
					                	"and site_code = '"+detSitecode+"'";
					                System.out.println("SQL : "+sql);
					               
					                 writeLog(filePtr,"SQL :: "+sql,true);
					                stmt = conn.createStatement();
					                rs = stmt.executeQuery(sql);
					                if(rs.next())
					                {
					                    currCodeBc = rs.getString(1);
					                }
					                stmt.close();
					                rs.close();
						                
					                exchRateHdr = detExchRate;
					                if(filtExchRate == null || Double.parseDouble(filtExchRate) == 0)
					                {
					                    filtExchRate = detExchRate;
					                }
					                sql = "select std_exrt from currency where curr_code = '"+currCodeBc+"'";
					                System.out.println("SQL : "+sql);
					                //writeTrace(processLogBuffer,"SQL :: "+sql);
					                 writeLog(filePtr,"SQL :: "+sql,true);
					                stmt = conn.createStatement();
					                rs = stmt.executeQuery(sql);
					                if(rs.next())
					                {
					                    exchRateBc = rs.getString(1); 
					                }
						                
					                insertSql = "insert into misc_payment (tran_id, tran_date,  tran_type, sundry_type, "+
					                	"sundry_code,pay_mode, bank_code, ref_no, ref_date, remarks, net_amt,curr_code,  "+
					                	"exch_rate, net_amt__bc, site_code, fin_entity, acct_code__bal, cctr_code__bal, "+
					                	"auto_paid, confirmed, chg_date,chg_user, chg_term, bank_charges, acct_code__bc, "+
					                	"cctr_code__bc,curr_code__bc, exch_rate__bc , chq_name, acct_code__cf, cctr_code__cf,tax_amt )"+
					                	"values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
					                System.out.println("insertSql : "+insertSql);
					                //writeTrace(processLogBuffer,"insertSql : "+insertSql);
					                 writeLog(filePtr,"insertSql : "+insertSql,true);
					                pstmt = conn.prepareStatement(insertSql);
					                pstmt.setString(1,tranID);
					                pstmt.setTimestamp(2,Timestamp.valueOf(GenericUtility.getInstance().getValidDateTimeString(filtTranDate,GenericUtility.getInstance().getApplDateFormat(),GenericUtility.getInstance().getDBDateFormat())));
					                pstmt.setString(3,tranType);
					                pstmt.setString(4," ");//sundry Type
					                pstmt.setString(5," ");//sundry code
					                pstmt.setString(6," ");//pay mode
					                pstmt.setString(7,filtBankCode);//bank code
					                pstmt.setString(8,filtRefNo);//ref_no
					                if(filtChequeSplit.equalsIgnoreCase("Y"))
					                {
					                    pstmt.setTimestamp(9,Timestamp.valueOf(GenericUtility.getInstance().getValidDateTimeString(filtTranDate,GenericUtility.getInstance().getApplDateFormat(),GenericUtility.getInstance().getDBDateFormat())));
					                }
					                else
					                {
					                    pstmt.setTimestamp(9,Timestamp.valueOf(GenericUtility.getInstance().getValidDateTimeString(detDueDate,GenericUtility.getInstance().getApplDateFormat(),GenericUtility.getInstance().getDBDateFormat())));
					                }
					                
					                pstmt.setTimestamp(9,Timestamp.valueOf(GenericUtility.getInstance().getValidDateTimeString(filtTranDate,GenericUtility.getInstance().getApplDateFormat(),GenericUtility.getInstance().getDBDateFormat())));
					                pstmt.setString(10,remarks);
					                pstmt.setDouble(11,0);//net amt
					                pstmt.setString(12,detCurrCode);
					                pstmt.setDouble(13,Double.parseDouble(filtExchRate));
					                pstmt.setDouble(14,0);
					                pstmt.setString(15,detSitecode);
					                pstmt.setString(16,detFinent);
					                pstmt.setString(17,acctCodeBal);
					                pstmt.setString(18,cctrCodeBal);
					                pstmt.setString(19,"Y");
					                pstmt.setString(20,"N");
					                pstmt.setTimestamp(21,new Timestamp(System.currentTimeMillis()));
					                pstmt.setString(22,loginUser);
					                pstmt.setString(23,termID);
					                pstmt.setDouble(24,0);
					                pstmt.setString(25,acctCodeBc);
					                pstmt.setString(26,cctrCodeBc);
					                pstmt.setString(27,currCodeBc);
					                pstmt.setDouble(28,Double.parseDouble(exchRateBc));
					                pstmt.setString(29,filtBankCodeAddName);
					                pstmt.setString(30,acctCodeCfAp);
					                pstmt.setString(31,cctrCodeCfAp);
					                pstmt.setInt(32,0);
					                int upd = pstmt.executeUpdate();
					                paymentFlag = false;
					                if(upd > 0)
						            {
						            	tranIdRetBuff.append(tranID).append(",");
						            	writeLog(filePtr,"Adding Tranid ["+tranID+"]",true);
						            }
					            }
					            /*To be put later
					             lc_chg = 0
					             ls_drawn_at = ''
								if mpaymode = 'D' or mpaymode = 'P' or mpaymode = 'T' then
										// if dd/pay order/transfer then get bank charges
		
								lc_chg = gf_bankcharges_calc( mbankcode, mpaymode, mtrandate, mpayamt )
								//			lc_tot = lc_tot + lc_chg
						
								if mpaymode = 'D' or mpaymode = 'P' then 
								ls_drawn_at = nvo_miscpay.gbf_payable_at(msundrytype,msundrycode, mbankcode) 	
								end if	
								ls_stancode = nvo_miscpay.gbf_stan_drawn(msundrytype, msundrycode) 
					             */
					            diffAmt = (payAmt * Double.parseDouble(detExchRate)) - (payAmt * Double.parseDouble(filtExchRate));
					            totalDiffAmt = totalDiffAmt + diffAmt;
					            lineNo++;
					            if(filtChequeSplit.equalsIgnoreCase("Y"))
					            {
					                insertSql = "insert into  misc_paydet ( tran_id,  tran_ser, vouch_no, vouch_date, net_amt, " +
				            		"pay_amt,curr_code, exch_rate__vouch, diff_amt__exch, acct_code__ap,cctr_code__ap, " +
				            		"sundry_type,sundry_code, bank_charges,drawn_at,stan_code) " +
				            		"values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
					            }
					            else
					            {
					                insertSql = "insert into  misc_paydet ( tran_id,  tran_ser, vouch_no, vouch_date, net_amt, " +
				            		"pay_amt,curr_code, exch_rate__vouch, diff_amt__exch, acct_code__ap,cctr_code__ap, " +
				            		"sundry_type,sundry_code, bank_charges,drawn_at,stan_code,tax_env,line_no, tax_amt, net_pay_amt) " +
				            		"values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
					            }
					            
					            pstmt = conn.prepareStatement(insertSql);
					            pstmt.setString(1,tranID);
					            pstmt.setString(2,detTranSer);
					            pstmt.setString(3,detVaouchNo);
					            pstmt.setTimestamp(4,Timestamp.valueOf(GenericUtility.getInstance().getValidDateTimeString(detVouchDate,GenericUtility.getInstance().getApplDateFormat(),GenericUtility.getInstance().getDBDateFormat())));
					            pstmt.setDouble(5,payAmt);
					            pstmt.setDouble(6,payAmt);
					            pstmt.setString(7,detCurrCode);
					            pstmt.setDouble(8,Double.parseDouble(detExchRate));
					            pstmt.setDouble(9,diffAmt);
					            pstmt.setString(10,detAcctcodeAP);
					            pstmt.setString(11,detCctrCodeAP);
					            pstmt.setString(12,detSundryTypeCurr);
					            pstmt.setString(13,detSundryCodeCurr);
					            pstmt.setDouble(14,0);
					            pstmt.setString(15,"");//drawn at
					            pstmt.setString(16,"");//stan code
					            if(!filtChequeSplit.equalsIgnoreCase("Y"))
					            {
					                pstmt.setString(17,filtTaxEnv);//stan code
					                pstmt.setInt(18,lineNo);//stan code
					                pstmt.setInt(19,0);//stan code
					                pstmt.setDouble(20,payAmt);//stan code
					            }
					            pstmt.executeUpdate();
					            
					            if(filtTaxEnv != null && filtTaxEnv.trim().length() > 0)
					            {
					                //calculate tax & update tax in detail
					            }
					            sundryAmt = sundryAmt + payAmt;
					            
					            detPayModePrev = detPayModeCurr;
					            detSundryTypePrev = detSundryTypeCurr;
					            detSundryCodePrev = detSundryCodeCurr;
					            
					            n++;
						        j = n;
						        
					            if(n < nodeListLength){
					                detailNode = detailNodeList.item(n);
						            detPayModeCurr = GenericUtility.getInstance().getColumnValueFromNode("pay_mode",detailNode);
						            detSundryTypeCurr = GenericUtility.getInstance().getColumnValueFromNode("sundry_type",detailNode);
						            detSundryCodeCurr = GenericUtility.getInstance().getColumnValueFromNode("sundry_code",detailNode);				            
					            }
						        
					            if(detPayModeCurr == null){
					                detPayModeCurr = "";
					            }
					            if((!detPayModeCurr.equalsIgnoreCase("D") && !detPayModeCurr.equalsIgnoreCase("T") && !detPayModeCurr.equalsIgnoreCase("P") && !detSundryCodePrev.equalsIgnoreCase(detSundryCodeCurr)) || (detPayModeCurr.equalsIgnoreCase("Q") && filtChequeSplit.equalsIgnoreCase("Y"))){
					                break;
					            }
					            /*To be put later
					             lc_chg = 0
								if msundrycode <> osundrycode then 
									lb_sundry = false
									// amit - 25-06-01 - paymode changed to opaymode
									lc_chg = gf_bankcharges_calc( mbankcode, opaymode, mtrandate, lc_sundryamt )
									//// end.
									lc_tot = lc_tot + lc_chg
									lc_sundryamt = 0
							
									update misc_paydet set bank_charges = :lc_chg
										where tran_id = :mpayno and tran_ser = :mtranser and vouch_no = :mvouchno;
									if get_sqlcode() <> 0 then
										i++
							  	 		populateerror(9999,'populateerror')
										errcode = 'DS000' + string(sqlca.sqldbcode)+' ~t'+sqlca.sqlerrtext
										errcode = gf_error_location(errcode)
										exit 
									end if      
								end if	
					            */
				            }
				            totAmtBc = totAmt * Double.parseDouble(exchRateHdr);
				            updateSql = "update misc_payment set sundry_type = ?, sundry_code = ?, " +
				            		"pay_mode = ?, ref_no = ?, remarks = ?, net_amt = ?, " +
				            		"curr_code = ?,net_amt__bc = ?, bank_charges = ?, " +
				            		"diff_amt__exch = ? , chq_name = ?	where tran_id = ?";
				            pstmt = conn.prepareStatement(updateSql);
				            pstmt.setString(1,detSundryTypePrev);
				            pstmt.setString(2,detSundryCodePrev);
				            pstmt.setString(3,detPayModePrev);
				            pstmt.setString(4,filtRefNo);
				            pstmt.setString(5,remarks);
				            pstmt.setDouble(6,totAmt);
				            pstmt.setString(7,detCurrCode);
				            pstmt.setDouble(8,totAmtBc);
				            pstmt.setDouble(9,0);
				            pstmt.setDouble(10,totalDiffAmt);
				            pstmt.setString(11,filtBankCodeAddName);
				            pstmt.setString(12,(tranID+"          ").substring(0,10));
				            pstmt.executeUpdate();
				            
				            /*if ls_autopost = 'Y' then
							// call confirmation routine for misc payment
							lds_hdr.reset()
							lds_det.reset()
					
							lds_hdr.retrieve(mpayno)
							lds_det.retrieve(mpayno)
							errcode = nvo_miscpay.gbf_post_misc_payhdr(lds_hdr.describe("datawindow.data"))
							if len(trim(errcode)) > 0 then
								exit
							end if
						
							errcode = nvo_miscpay.gbf_post_misc_paydet(lds_hdr.describe("datawindow.data"), lds_det.describe("datawindow.data"))
							if len(trim(errcode)) > 0 then
								exit
							end if
							end if*/
				        }//else end	   
			        }//end of errcode   
			               
		        }//endVectorlist
		      }
		      
			
			
	    }
	    catch(SQLException sqle)
	    {
	    	try
	    	{
				ITMDBAccessEJB itmDBAccessEJB = new ITMDBAccessEJB();
				errString = itmDBAccessEJB.getErrorString("", "ERROR,EXCE" , "", "", conn);
				itmDBAccessEJB = null;
				System.out.println("errString: "+errString);
				writeLog(filePtr,sqle,true);
			//	errString = "Exception";
				sqle.printStackTrace();
				//return errString; 
			
			}
			catch(Exception s)
			{
				writeLog(filePtr,s,true);
				s.printStackTrace();
			}
	    }
	    catch(Exception e)
	    {
	    
	   	 	writeLog(filePtr,e,true);
	    	//writeTrace(processLogBuffer,e);
	    	try
	    	{
				ITMDBAccessEJB itmDBAccessEJB = new ITMDBAccessEJB();
				errString = itmDBAccessEJB.getErrorString("", "ERROR,EXCE" , "", "", conn);
				itmDBAccessEJB = null;
				System.out.println("errString: "+errString);
			//	errString = "Exception";
				e.printStackTrace();
			//	return errString; 
			
			}
			catch(Exception e1)
			{
				e1.printStackTrace();
			}
	    }
	    finally
	    {
		    sunCodeVec.clear();
		}
	    return errString;   
	} 
	
	private String calcBankChrgs() throws ITMException
	{
	    return "";
	}
	private  void wirteLog(StringBuffer buffer,String fileName,String pathVar,boolean append)
	{
		System.out.println("fileName ["+fileName+"]");
		System.out.println("Buffer ["+buffer+"]");
		try
		{
			BufferedReader in   = new BufferedReader(new FileReader("C:\\WINNT\\itm2.ini"));
			String fileStr = null;
			String logPath = null;
			while((fileStr =in.readLine())!=null)
			{
				//System.out.println("fileStr["+fileStr+"]");
				if(fileStr.toUpperCase().indexOf(pathVar.toUpperCase())!=-1 )
				{
					logPath=fileStr;
					break;
				}
			}
			fileStr=null;
			System.out.println("logPath From ini ["+logPath+"]");
			//writeTrace(processLogBuffer,"logPath From ini ["+logPath+"]");
			if(logPath!= null)
			{
				if(logPath.indexOf("//")!=-1)
				{
					logPath = null;
					System.out.println("Setting null To LogPath ");
					//writeTrace(processLogBuffer,"Setting null To LogPath ");
				}
			}
			System.out.println("logPath="+logPath);
			//writeTrace(processLogBuffer,"logPath=["+logPath+"]");
			if(logPath !=null && logPath.trim().length()!=0)
			{
				String path = null;
				path = logPath.substring(logPath.indexOf("=")+1);
				System.out.println("Path :- ["+path+"]");
				////writeTrace(processLogBuffer,"Path :- ["+path+"]");
				File fileFolder = new File(path);
				if(!fileFolder.exists())
				{
					fileFolder.mkdirs(); 
					System.out.println("Directory Built................ ["+fileFolder+"]");
					//writeTrace(processLogBuffer,"Directory Built................ ["+fileFolder+"]");
				}
				fileFolder = null;
			 	File fObj = new File(path.trim()+"//"+fileName);
				PrintWriter pw = new PrintWriter((new FileOutputStream(fObj,append)),true);
				//System.out.println("Writting Buffer -------------- ["+buffer+"]");
				pw.println("Time ::::::::::::::-["+new java.sql.Timestamp(System.currentTimeMillis())+"]");
				pw.println(buffer.toString());
				fObj=null; 
				pw = null;
			}
		} 
		catch(Exception e)
		{
			e.printStackTrace();
		}
			
	}
	
	private void handleTax(String tranId,int lineNo,String tranDate,double quantity,double rate, String currCode,String siteCode,int ctr,String taxClass,String taxChap,String taxEnv,String rateClg,String discount)throws Exception
	{
		StringBuffer valueXmlString =null;
		try
		{
			//xml String in the foll. format
			valueXmlString = new StringBuffer("<?xml version=\"1.0\"?>");
			valueXmlString.append("<Root>");
			valueXmlString.append("<Detail3 dbID='' domID='"+ctr+"' objName='sorder' objContext='3'>");
			valueXmlString.append("<attribute pkNames='' status='N' updateFlag='A' selected='N' />");
			valueXmlString.append("<tran_id>").append(tranId).append("</tran_id>");
			valueXmlString.append("<line_no>").append(lineNo).append("</line_no>");
			valueXmlString.append("<tax_date>").append(tranDate).append("</tax_date>");
			valueXmlString.append("<rate>").append(rate).append("</rate>");
			valueXmlString.append("<rate__clg>").append(rateClg).append("</rate__clg>");
			valueXmlString.append("<tax_class>").append(taxClass).append("</tax_class>");
			valueXmlString.append("<tax_chap>").append(taxChap).append("</tax_chap>");
			valueXmlString.append("<tax_env>").append(taxEnv).append("</tax_env>");
			valueXmlString.append("<tax_amt>").append("0").append("</tax_amt>");
			valueXmlString.append("<discount>").append(discount).append("</discount>");
			valueXmlString.append("<quantity>").append(quantity).append("</quantity>");	
			valueXmlString.append("<Taxes/>");
			valueXmlString.append("</Detail3>");
			valueXmlString.append("</Root>");
			
			Document itemDoc = GenericUtility.getInstance().parseString(valueXmlString.toString());
			Node currRecordNode = itemDoc.getElementsByTagName("Detail3").item(0);
			TaxCalculation taxCal = new TaxCalculation();
			appendOrReplaceTaxesNode(currRecordNode);
			NodeList currRecordChildList = currRecordNode.getChildNodes();
			int childListLength = currRecordChildList.getLength();
			Node currTaxNode = null;
			for (int i = 0; i < childListLength; i++)
			{
				if (currRecordChildList.item(i).getNodeName().equalsIgnoreCase("Taxes"))
				{
					currTaxNode = currRecordChildList.item(i);
				}
			}
			//taxCal.setUpdatedTaxDom(currRecordNode);
			taxCal.setUpdatedTaxDom(currTaxNode);
			taxCal.setTaxDom(currTaxNode);
			taxCal.setDataNode(currRecordNode);
			//taxCal.taxCalc("S-ORD", (tranId+":"+lineNo),tranDate,"rate__stduom", "quantity__stduom", currCode,siteCode);
			taxCal.taxCalc("S-ORD", tranId,tranDate,"rate__stduom", "quantity__stduom", currCode,siteCode,"2");//chandu changed on dated 28-Nov-2014
			System.out.println("CurrentTaxNode ::"+serializeDom(currTaxNode));
			System.out.println("CurrentRecordNode ::"+serializeDom(currRecordNode));
			//To get the calculated tax - Jiten 21/02/06
			taxAmt = GenericUtility.getInstance().getColumnValueFromNode("tax_amt",currRecordNode);
			currRecordChildList = currRecordNode.getChildNodes();
			for (int i = 0; i < childListLength; i++)
			{
				if (currRecordChildList.item(i).getNodeName().equalsIgnoreCase("Taxes"))
				{
					currTaxNode = currRecordChildList.item(i);					
					saveData(currTaxNode);
				}
			}
		}
		catch(Exception e)
		{
			writeLog(filePtr,e,true);
			throw new ITMException(e);
		}
	}
	private void appendOrReplaceTaxesNode(Node currRecordNode)throws ITMException 
	{
		boolean found = false;
		MasterDataStatefulLocal masterDataStateful = null;
		try
		{

			if(	this.blankTaxString == null)
			{
				AppConnectParm appConnect = new AppConnectParm();
				InitialContext initialContext = new InitialContext(appConnect.getProperty());
				masterDataStateful = (MasterDataStatefulLocal)initialContext.lookup("ibase/MasterStatefulEJB/local");
				//MasterDataStateful masterDataStateful = masterDataStatefulHome.create();
				this.blankTaxString = masterDataStateful.getBlankTaxDomForAdd("2");//chandu changed on dated 28-Nov-14
			}
			NodeList dataNodeChildList = currRecordNode.getChildNodes();
			int dataNodeChildListLen = dataNodeChildList.getLength();
			for (int i=0; i < dataNodeChildListLen; i++)
			{
				if (dataNodeChildList.item(i) != null)
				{
					if (dataNodeChildList.item(i).getNodeName().equalsIgnoreCase("Taxes") )
					{
						currRecordNode.replaceChild(currRecordNode.getOwnerDocument().importNode(GenericUtility.getInstance().parseString(blankTaxString).getFirstChild(), true),dataNodeChildList.item(i));
						found = true;
						break;
					}
				}
			}
			if (!found)
			{
				currRecordNode.appendChild(currRecordNode.getOwnerDocument().importNode(GenericUtility.getInstance().parseString(blankTaxString).getFirstChild(), true));
			}
		}
		catch(Exception e)
		{
			writeLog(filePtr,e,true);
			System.out.println("Exception :: removeTaxNodeInDetail :==>\n"+e);
			throw new ITMException(e);
		}
	}

	private String serializeDom(Node dom)throws ITMException
	{
		String retString = null;
		try
		{
			ByteArrayOutputStream out = new ByteArrayOutputStream();
			Transformer serializer = TransformerFactory.newInstance().newTransformer();
			serializer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
			serializer.transform(new DOMSource(dom), new javax.xml.transform.stream.StreamResult(out));
			retString = out.toString();
			out.flush();
			out.close();
			out = null;	
		}
		catch (Exception e)
		{
			writeLog(filePtr,e,true);
			System.out.println("Exception : MasterStatefulEJB : serializeDom :"+e);
			throw new ITMException(e);
		}
		return retString;
	}
	//*********************
	private void saveData (Node currNode) throws Exception
	{
		Connection conn = null;
		ConnDriver connDriver = new ConnDriver();
		try
		{
			conn = connDriver.getConnectDB("DriverITM");
			StringBuffer fieldNameBuff = new StringBuffer();
			StringBuffer fieldValueBuff = new StringBuffer();
			StringBuffer insertQueryBuff = new StringBuffer();
			Statement stmt =null;
			String insertSql =null;
			int q =0,noOfField = 0,nodeLength = 0;
			stmt = conn.createStatement();
			Node currChildNode = null;
			NodeList currNodeList = currNode.getChildNodes();
			nodeLength = currNodeList.getLength();
			for (int i = 0;i < nodeLength ; i++ )
			{
				Node taxNode = currNodeList.item(i);
				NodeList taxfield = taxNode.getChildNodes();
				noOfField = taxfield.getLength();
				for (int j = 0;j < noOfField ; j++ )
				{																							 
					String fieldName = 	taxfield.item(j).getNodeName();
					if (!fieldName.equalsIgnoreCase("attribute") && !fieldName.equalsIgnoreCase("tax_descr") && !fieldName.equalsIgnoreCase("cc_editopt"))
					{
						if (taxfield.item(j).getFirstChild() != null && taxfield.item(j).getFirstChild().getNodeValue() != null && taxfield.item(j).getFirstChild().getNodeValue().trim().length() > 0)
						{
							fieldNameBuff.append(fieldName).append(",");
							if (fieldName.equalsIgnoreCase("TAX_AMT__TCURR") || fieldName.equalsIgnoreCase("EXCH_RATE") || fieldName.equalsIgnoreCase("EXCH_RATE_TRAN") || fieldName.equalsIgnoreCase("ROUND_TO") || fieldName.equalsIgnoreCase("RECO_PERC") || fieldName.equalsIgnoreCase("RECO_AMOUNT") || fieldName.equalsIgnoreCase("TAXABLE_AMT") || fieldName.equalsIgnoreCase("TAX_PERC") || fieldName.equalsIgnoreCase("TAX_AMT"))
							{
								fieldValueBuff.append(taxfield.item(j).getFirstChild().getNodeValue().trim()).append(",");
							}
							else
							{
								fieldValueBuff.append("'").append(taxfield.item(j).getFirstChild().getNodeValue().trim()).append("'").append(",");
							}
						}																		
					}
				}
				fieldNameBuff.deleteCharAt((fieldNameBuff.length() - 1));
				fieldValueBuff.deleteCharAt((fieldValueBuff.length() - 1));
				String tempString = "INSERT INTO TAXTRAN (" +fieldNameBuff+") VALUES ("+fieldValueBuff+")";
				//insertQueryBuff.append("INSERT INTO TAXTRAN (").append(fieldNameBuff).append(") VALUES (").append(fieldValueBuff).append(")");
				insertQueryBuff.append(tempString);
				fieldNameBuff.delete(0,fieldNameBuff.length());
				fieldValueBuff.delete(0,fieldValueBuff.length());
				System.out.println("insertQueryBuff ::"+insertQueryBuff.toString());
				stmt.addBatch(insertQueryBuff.toString());				
				insertQueryBuff.delete(0,insertQueryBuff.length());
			}
			stmt.executeBatch();			
		}
		catch(Exception e)
		{
			writeLog(filePtr,e,true);
			throw e;
		}
		finally
		{
			System.out.println("Closing Connection.....");
			conn.close();
			conn = null;
		}
	}
	
	
	/*public  void  writeTrace(StringBuffer sb,String msg)
	{
		if(sb!=null)
		{
			sb.append(msg).append("\n");
		}
	}*/
/*	public  void  writeTrace(StringBuffer sb,Exception e)
	{
			java.io.ByteArrayOutputStream byteBuff = new java.io.ByteArrayOutputStream();
			java.io.PrintStream printBuff= new PrintStream(byteBuff);
			e.printStackTrace(printBuff);
			printBuff=null;
			if(sb!=null)
			{
				sb.append(byteBuff.toString());
			}
			
			byteBuff =null;
	}*/
	static void writeLog(File f,String ex,boolean flag)
	{
		try
		{
			PrintWriter pw = new PrintWriter((new FileOutputStream(f,flag)),flag);
			pw.println(ex);
			pw.close();
		}
		catch(Exception exWm){exWm.printStackTrace();}
	}
	 static void writeLog(File f,Exception ex,boolean flag)
	{
		try
		{
			PrintWriter pw = new PrintWriter((new FileOutputStream(f,flag)),flag);
			ex.printStackTrace(pw);
			pw.close();
		}
		catch(Exception exWe){exWe.printStackTrace();}
	}
}//end of ejbs
