package ibase.webitm.ejb.fin;
import java.lang.String;
import java.rmi.RemoteException;
import java.text.SimpleDateFormat;
import ibase.utility.CommonConstants;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.Transformer;
import java.util.*;
import java.util.Date;
import java.sql.*;
import java.text.*;
import java.text.SimpleDateFormat;
import java.io.*;
import org.w3c.dom.*; 
import javax.xml.parsers.*;
import javax.ejb.*;
import ibase.webitm.ejb.*;
import ibase.webitm.utility.*;
import ibase.system.config.*;
import java.util.*;
import javax.naming.InitialContext;
//import ibase.webitm.ejb.MasterStateful;// comented for ejb3
//import ibase.webitm.ejb.MasterStatefulHome;// commented for ejb3
import ibase.webitm.ejb.MasterStatefulLocal;//added for ejb3
import ibase.webitm.ejb.MasterStatefulEJB;//addes for ejb3
import ibase.webitm.utility.ITMException;
import ibase.webitm.utility.GenericUtility;
import java.io.File;
import ibase.system.config.ConnDriver;
import javax.ejb.Stateless; // added for ejb3

@Stateless // added for ejb3

public class AutoPmtGenPrc extends ProcessEJB implements AutoPmtGenPrcLocal,AutoPmtGenPrcRemote //SessionBean
{
	File filePtr ;
	File logDir ;
	String logDirName = "";			
	static String logOnOffFlag = "";//For On-Off Log file.
	ValidatorEJB validatorEJB = new ValidatorEJB();// Added by Jaimin 16/08/2007
	String err = "";
	GenericUtility genericUtility = GenericUtility.getInstance();
	ITMDBAccessEJB itmDBAccessEJB = new ITMDBAccessEJB();		
//	Connection conn = null;
	ResultSet rs1 = null;
	PreparedStatement pstmt1 = null;
	String Sql1="";
	java.sql.Timestamp dateTo = null;
	java.sql.Timestamp dateFr = null;	
	
	/*static void writeLog(File f,String Msg,boolean flag)
	{
		try
		{  
			PrintWriter pw = new PrintWriter((new FileOutputStream(f,flag)),flag);				
			if(logOnOffFlag.trim().equals("Y"))
			{
				pw.println( Msg);		
			}
			pw.close();
		}
		catch(Exception exWm){exWm.printStackTrace();}		
	}
	static void writeLog(File f,Exception Msg,boolean flag)
	{
		try{
			PrintWriter pw = new PrintWriter((new FileOutputStream(f,flag)),flag);				
			pw.println(" "+Msg);		
			pw.close();		
		}
		catch(Exception exWm){exWm.printStackTrace();}
	}*/
	
	public String getData(String xmlString, String xmlString2, String windowName, String xtraParams) throws RemoteException,ITMException
	{
		if(CommonConstants.J2EE_VERSION.equals("1"))
		{
			logDirName =  CommonConstants.JBOSSHOME  + File.separator + "log" ;
		}
		else if(CommonConstants.J2EE_VERSION.equals("2"))
		{
			logDirName =  CommonConstants.JBOSSHOME   + File.separator + "server"+ File.separator +"default"+ File.separator +"log" ;
		}
		logDir = new File(logDirName);
		filePtr = new File(logDirName+ File.separator + "AutoPmtGenSave.log");

		String rtrStr = "";
		Document headerDom = null;
		Document detailDom = null;	
		try
		{
			if(xmlString != null && xmlString.trim().length()!=0)
			{
				headerDom = genericUtility.parseString(xmlString); 				
			}
			if(xmlString2 != null && xmlString2.trim().length()!=0)
			{
				detailDom = genericUtility.parseString(xmlString2); 				
			}
			rtrStr = getData(headerDom, detailDom, windowName, xtraParams);
		}
		catch (Exception e)
		{			
			//writeLog(filePtr,"Exception -->"+e,true);
			rtrStr = e.getMessage();
		}
		return rtrStr; 
	}

	public String getData(Document headerDom, Document detailDom, String windowName, String xtraParams) throws RemoteException,ITMException
	{
		StringBuffer retTabSepStrBuff = new StringBuffer();
		Connection conn = null;
		ConnDriver connDriver = new ConnDriver();
		String fromDate = null;
		String toDate = null;		
		String vouchNoFrom = null;
		String vouchNoTo = null;
		String siteCode = null;
		String bankCode = null;
		String sundryType = null;
		String sundryCode = null;
		String payMode = null;
		String entryBatchNo = null;
		String chqSplit = null;
		String bankAdd = null;
		String errCode = "";
		String resultString = "";
		String getSql= null ;
		String currCode = "";
		String sql= null ;
		ResultSet rs = null;
		ResultSet rs1 = null;
		PreparedStatement pstmt = null;
		//Statement st = null; // Remarked - Rej - Asnot used - 29/12/2007

		//Added by Raj (FI78DIS032)- 29/12/2007
		double unapprovedPayAmt = 0d , payAmt = 0d , netPayable = 0d;
		String tranSer = "";
		String refNo = "";
		String tempSql = "";
		Statement stmtTemp = null; 
		ResultSet rsTemp = null;
		// End addition  - Raj - (FI78DIS032)- 29/12/2007
		try
		{
			conn = connDriver.getConnectDB("DriverITM");
			conn.setAutoCommit(false);
			stmtTemp = conn.createStatement(); // Added - by Raj  - (FI78DIS032)- 29/12/2007
			DatabaseMetaData dbmd = conn.getMetaData();
			//For logonoff
			getSql = "select var_value from finparm where prd_code='999999' and var_name='AUTOPAYGEN_LOG_FLAG'";
			pstmt = conn.prepareStatement(getSql); 
			rs = pstmt.executeQuery();
			if (rs.next())
			{
				logOnOffFlag = rs.getString(1);
				System.out.println("------------------in rs--------");
			}		
			System.out.println("----------------logOnOff:"+logOnOffFlag);
			rs.close();
			//pstmt.close();
			//
			//writeLog(filePtr,"In log File",true);
			SimpleDateFormat simpleDateFormat = new SimpleDateFormat(genericUtility.getDBDateFormat());
			fromDate = genericUtility.getColumnValue("date__fr",headerDom);
			////writeLog(filePtr,"fromDate-->"+fromDate,true);
			currCode= genericUtility.getColumnValue("curr_code",headerDom);
			////writeLog(filePtr,"currCode-->"+currCode,true);
			toDate = genericUtility.getColumnValue("date__to",headerDom);
			//writeLog(filePtr,"toDate-->"+toDate,true);
			siteCode = genericUtility.getColumnValue("site_code__fr",headerDom);
			//writeLog(filePtr,"siteCode-->"+siteCode,true);
			if ( siteCode == null || siteCode.trim().length() == 0 )
			{
			  siteCode = "";					
			} 
			vouchNoFrom = genericUtility.getColumnValue("vouch_no__fr",headerDom);
			//writeLog(filePtr,"vouchNoFrom-->"+vouchNoFrom,true);
			if ( vouchNoFrom == null || vouchNoFrom.trim().length() == 0 )
			{
				 vouchNoFrom = "0";					
			} 
			vouchNoTo = genericUtility.getColumnValue("vouch_no__to",headerDom);
			//writeLog(filePtr,"vouchNoTo -->"+vouchNoTo ,true);
			if(vouchNoTo == null || vouchNoTo.trim().length() == 0)
			{
				vouchNoTo = "z";				
			}
			sundryType = genericUtility.getColumnValue("sundry_type",headerDom);
			//writeLog(filePtr,"sundryType -->"+sundryType ,true);
			if ( sundryType == null  )
			{
				sundryType = "%";
			}
			else
			{
				sundryType =sundryType.trim()+"%";				
			}		
			sundryCode = genericUtility.getColumnValue("sundry_code",headerDom);
			//writeLog(filePtr,"sundryCode -->"+sundryCode ,true);
			if ( sundryCode == null)
			{
				sundryCode = "%";
			}
			else
			{
				sundryCode = sundryCode.trim()+"%";
			}
			payMode = genericUtility.getColumnValue("pay_mode",headerDom);
			//writeLog(filePtr,"payMode -->"+payMode ,true);
			if ( payMode == null || payMode.trim().length() == 0 )
			{
				payMode = "%";
			}
			entryBatchNo = genericUtility.getColumnValue("entry_batch_no",headerDom);
			//writeLog(filePtr,"entryBatchNo -->"+entryBatchNo ,true);
			if(entryBatchNo == null)
			{
				entryBatchNo = "%";
			}
			else
			{
				entryBatchNo = entryBatchNo.trim()+"%";
			}			
			fromDate=genericUtility.getValidDateString(fromDate,genericUtility.getApplDateFormat(),genericUtility.getDBDateFormat());
			//writeLog(filePtr,"fromDate -->"+fromDate ,true);
			toDate=genericUtility.getValidDateString(toDate,genericUtility.getApplDateFormat(),genericUtility.getDBDateFormat());
			//writeLog(filePtr,"toDate -->"+toDate ,true);
			dateFr = java.sql.Timestamp.valueOf(fromDate + " 00:00:00 "); 
			//writeLog(filePtr,"dateFr -->"+dateFr ,true);
			dateTo = java.sql.Timestamp.valueOf(toDate + " 00:00:00 ");			
			//writeLog(filePtr,"dateTo -->"+dateTo ,true);
			getSql= "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,"   
				+"misc_payables.pay_mode,"   
				+"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 pay_amt,"   
				+"fn_sundry_name(misc_payables.sundry_type,misc_payables.sundry_code,'') as sundry_name,"   
				+" 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 >= '" + vouchNoFrom + "' ) AND "  
				+"( misc_payables.ref_no <= '" + vouchNoTo + "' ) 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 + "' AND "  
				+"case when misc_payables.entry_batch_no is null then ' ' else"    
				+" misc_payables.entry_batch_no end like '"+entryBatchNo+"' AND "
				+" curr_code ='"+ currCode + "'"
				+" ORDER BY misc_payables.sundry_type ASC,"   
				+"misc_payables.sundry_code ASC,"   
				+"misc_payables.ref_no ASC";   
			    System.out.println("SQL==>"+getSql);
				//writeLog(filePtr,"getSql -->"+getSql,true);
				pstmt = conn.prepareStatement(getSql);   
				pstmt.setTimestamp(1,dateFr);
				pstmt.setTimestamp(2,dateTo);
				rs = pstmt.executeQuery();
				while(rs.next())
				{
					//Added below by Raj (FI78DIS032)- 29/12/2007
					tranSer = rs.getString("tran_ser");
					refNo = rs.getString("ref_no");
					payAmt = rs.getDouble("pay_amt");
					netPayable = rs.getDouble("net_payable");
					tempSql= "SELECT sum(case when auto_pay_det.pay_amt is null then 0 else auto_pay_det.pay_amt end) as pay_amt "
						+"FROM auto_pay_hdr, auto_pay_det " 
						+"WHERE ( auto_pay_det.tran_ser = '" + tranSer + "') AND "  
						+"( auto_pay_det.ref_no = '" + refNo + "' ) AND " 
						+"( auto_pay_hdr.tran_id = auto_pay_det.tran_id ) AND "  
						+"case when auto_pay_det.tran_id__pay is null then ' ' else "    
						+" auto_pay_det.tran_id__pay end = ' ' ";
					System.out.println("SQL==>"+tempSql);
					rsTemp = stmtTemp.executeQuery(tempSql);
					if (rsTemp.next()) 
					{
						unapprovedPayAmt = rsTemp.getDouble("pay_amt");
					}
					else
					{
						unapprovedPayAmt = 0d;
					}
					rsTemp.close();

					if (netPayable < 0 && netPayable > unapprovedPayAmt)
					{
						unapprovedPayAmt = netPayable;
					}
					else
					{
						if (netPayable > 0 && unapprovedPayAmt > netPayable)
						{
							unapprovedPayAmt = netPayable;
						}
					}

					payAmt = netPayable - unapprovedPayAmt;

					//Add ended by Raj (FI78DIS032)- 29/12/2007
					
					//Refno					  
					retTabSepStrBuff.append((rs.getString(1)==null)?" " :rs.getString(1)).append("\t");					
					//tran_date
					retTabSepStrBuff.append(rs.getTimestamp(2)).append("\t");
					dateTo = rs.getTimestamp(2);
	     			 //ref_date
					retTabSepStrBuff.append(rs.getTimestamp(3)).append("\t");
					dateFr = rs.getTimestamp(3);
					//bill_no
					retTabSepStrBuff.append((rs.getString(4)==null)?" " :rs.getString(4)).append("\t");
					//bill_date
					if(rs.getTimestamp(5)==null)
						retTabSepStrBuff.append("").append("\t");
					else
						retTabSepStrBuff.append(rs.getTimestamp(5)).append("\t");
					//fromDate = rs.getTimestamp(5);
					//curr_code
					retTabSepStrBuff.append((rs.getString(6)==null)?" " :rs.getString(6)).append("\t");
					//exch_rate
					retTabSepStrBuff.append(rs.getDouble(7)).append("\t");
					//sundry_code
					retTabSepStrBuff.append((rs.getString(8)==null)?" " :rs.getString(8)).append("\t");
					//acct_code
					retTabSepStrBuff.append((rs.getString(9)==null)?" " :rs.getString(9)).append("\t");
					//cctr_code
					retTabSepStrBuff.append((rs.getString(10)==null)?" " :rs.getString(10)).append("\t");
					//due_date
					retTabSepStrBuff.append(rs.getTimestamp(11)).append("\t"); 
					//toDate = rs.getTimestamp(11);
					//site_code
					retTabSepStrBuff.append((rs.getString(12)==null)?" " :rs.getString(12)).append("\t");
					//fin_entity
					retTabSepStrBuff.append((rs.getString(13)==null)?" " :rs.getString(12)).append("\t");
					//tot_amt
					retTabSepStrBuff.append(rs.getDouble(14)).append("\t");
					//sundry_type
					retTabSepStrBuff.append((rs.getString(15)==null)?" " :rs.getString(15)).append("\t");
					//bank_code
					retTabSepStrBuff.append((rs.getString(16)==null)?" " :rs.getString(16)).append("\t");
					//pay_mode
					retTabSepStrBuff.append((rs.getString(17)==null)?" " :rs.getString(17)).append("\t");
					//adv_amt
					retTabSepStrBuff.append(rs.getDouble(18)).append("\t");
					//tran_id
					retTabSepStrBuff.append((rs.getString(19)==null)?" " :rs.getString(19)).append("\t");
					//tran_ser
					retTabSepStrBuff.append((rs.getString(20)==null)?" " :rs.getString(20)).append("\t");
					//adj_amt
					retTabSepStrBuff.append(rs.getDouble(21)).append("\t");
					//hold_amt
					retTabSepStrBuff.append(rs.getDouble(22)).append("\t");
					//username
					retTabSepStrBuff.append(rs.getString(23)).append("\t");
					//pay_amt
					//retTabSepStrBuff.append(rs.getDouble(24)).append("\t");//Remarked by Raj (FI78DIS032)- 29/12/2007
					retTabSepStrBuff.append(payAmt).append("\t");//Added by Raj (FI78DIS032)- 29/12/2007
					//sundry_name
					retTabSepStrBuff.append((rs.getString(25)==null)?" " :rs.getString(25)).append("\t");
					//net_payable					
					retTabSepStrBuff.append(rs.getDouble(26)).append("\t");
					//unapproved_amt					
					retTabSepStrBuff.append(unapprovedPayAmt).append("\r\n");//Added by Raj (FI78DIS032)- 29/12/2007
					//retTabSepStrBuff.append(rs.getDouble(26)).append("\n");
					////writeLog(filePtr,"Data Feched -->"+retTabSepStrBuff ,true);
					////writeLog(filePtr,"----------------------------------------------------------------" ,true);
				}
				rs.close();
				pstmt.close();	
				resultString = retTabSepStrBuff.toString();
			}	
			catch(Exception e)
			{
				//writeLog(filePtr,"Exception in getData-->"+e,true);
				 throw new ITMException(e);				
			}
			finally
			{
				try
				{
					conn.close();
					conn = null;
				}
				catch (Exception e)
				{
					//writeLog(filePtr,"In Fianally... Exception in getData-->"+e,true);
					System.out.println(e.getMessage());					
				}
			}
		return resultString;	
	} 

	public String process(String xmlString, String xmlString2, String windowName, String xtraParams) throws RemoteException,ITMException
	{
		
		Document detailDom = null;
		Document headerDom = null;
		String retStr = "";
		
		try
		{	
			//writeLog(filePtr,"xmlString-->"+xmlString,true);
			//writeLog(filePtr,"xmlString2-->"+xmlString2,true);
			//writeLog(filePtr,"windowName-->"+windowName,true);			

			if(xmlString != null && xmlString.trim().length()!=0)
			{
				headerDom = genericUtility.parseString(xmlString); 
				System.out.println("headerDom" + headerDom);
				//writeLog(filePtr,"headerDom-->"+headerDom,true);
			}
			if(xmlString2 != null && xmlString2.trim().length()!=0)
			{
				detailDom = genericUtility.parseString(xmlString2); 
				System.out.println("detailDom" + detailDom);
				//writeLog(filePtr,"detailDom-->"+detailDom,true);
			}
			retStr = process(headerDom, detailDom, windowName, xtraParams);
		}
		catch (Exception e)
		{			
			System.out.println("Exception :AutoPrmGen :process:" + e.getMessage() + ":");
			e.printStackTrace();
			//writeLog(filePtr,"Exception in process-->"+e.getMessage(),true);
			retStr = e.getMessage();
		}
		//writeLog(filePtr,"Return from process-->"+retStr,true);
		return retStr;
	}
	// END OF PROCESS ONE

	public String process(Document headerDom, Document detailDom, String windowName, String xtraParams) throws RemoteException,ITMException
	{
		//writeLog(filePtr,"In process.............",true);
		//writeLog(filePtr,"headerDom-->"+headerDom,true);
		//writeLog(filePtr,"detailDom-->"+detailDom,true);
		//writeLog(filePtr,"windowName-->"+windowName,true);
		//writeLog(filePtr,"xtraParams-->"+xtraParams,true);
		Connection conn = null;
		ConnDriver connDriver = new ConnDriver();
		ResultSet rs = null;
		PreparedStatement pstmt = null;
		String refNo = "";
		String miscPayablesTranDate = "";
		String chgDate = "";
		String sDate= "";
		String refDate = "";
		String fromDate = "";
		String billNo = "";
		String billDate = "";
		String currCode = "";
		String dueDate = "";
		String exchRate = "";
		String sundryCode = "";
		String acctCode = "";
		String cctrCode = "";
		String siteCode = "";
		String finEntity = "";
		String totAmt = "";
		String sundryType = "";
		String bankCode = "";
		String bankCodeAdd = "";
		String payMode = "";
		String advAmt = "";
		String tranId = "";
		String tranSer = "";
		String adjAmt = "";
		String holdAmt = "";
		String userName = "";
		String payAmt = "";
		String sundryName = "";
		String netPayable = "";
		String childNodeName = "";
		String errCode = "";
		String errFrSret ="";
		String tranType = "";
		String chgTerm = "";
		String chgUser = "";
		String xmlOutString = "";
		String payDate = "";
		String retString = "";
		String lastChq = ""; //Added by Jaimin 06/08/2007
		String uptoChq = "";//Added by Jaimin 06/08/2007
		String errString = "";
		StringBuffer retBuf;
		//StringBuffer refNoBuff = null, tranSerBuff = null, payAmtBuff = null, netPayableBuff = null;//Added by jaimin 17/08/02007
		StringBuffer errStringBuff = null;//Added by jaimin 17/08/02007
		boolean validEntry = true;
		StringBuffer xmlString = null;
		int curDate = 0;
		int	curMonth = 0;
		int	curYear = 0;
		int lineNo = 0;
		//Added by Jaimin 25/07/2007
		Connection connectionObject = null;
		Statement statement = null;
		ResultSet resultSet = null;	
		String sql = "";
		String siteDescr = "",finentDescr = "",bankName = "";
		//End Jaimin 25/07/2007
		NodeList parentNodeList = null;
		NodeList childNodeList = null;
		Node parentNode = null;
		Node childNode = null; 	
		int updCnt = 0;
		int parentNodeListLength = 0;
		int childNodeListLength = 0;	
		try
		{			
			retBuf = new StringBuffer();
			conn = connDriver.getConnectDB("DriverITM");
			conn.setAutoCommit(false);
			System.out.println("AutoPmtGenPrcEJB ejbCreate called.........");
			//writeLog(filePtr,"AutoPmtGenPrcEJB ejbCreate called.........",true);
			//For logonoff
			sql = "select var_value from finparm where prd_code='999999' and var_name='AUTOPAYGEN_LOG_FLAG'";
			//writeLog(filePtr,"sql-->"+sql,true);
			pstmt = conn.prepareStatement(sql); 
			resultSet = pstmt.executeQuery();
			if (resultSet.next())
			{
				logOnOffFlag = resultSet.getString(1);					
			}		
			//writeLog(filePtr,"logOnOffFlag-->"+logOnOffFlag,true);
			System.out.println("----------------logOnOff:"+logOnOffFlag);
			resultSet.close();
			//pstmt.close();
			//
			siteCode = genericUtility.getColumnValue("site_code__fr",headerDom);
			//writeLog(filePtr,"siteCode-->"+siteCode,true);
			bankCode = genericUtility.getColumnValue("bank_code",headerDom);
			//writeLog(filePtr,"bankCode-->"+bankCode,true);
			bankCodeAdd = genericUtility.getColumnValue("bank_code__add",headerDom);
			//writeLog(filePtr,"bankCodeAdd-->"+bankCodeAdd,true);
			tranType = genericUtility.getColumnValue("tran_type",headerDom);
			//writeLog(filePtr,"tranType-->"+tranType,true);
			payDate = genericUtility.getColumnValue("date__pay",headerDom);
			//writeLog(filePtr,"payDate-->"+payDate,true);
			chgUser = genericUtility.getValueFromXTRA_PARAMS(xtraParams, "loginCode");  
			//writeLog(filePtr,"chgUser-->"+chgUser,true);
			chgTerm = genericUtility.getValueFromXTRA_PARAMS(xtraParams, "termId");
			//writeLog(filePtr,"chgTerm-->"+chgTerm,true);
			Calendar calCurr = Calendar.getInstance();
			curDate = calCurr.get(calCurr.DATE);
			//writeLog(filePtr,"curDate-->"+curDate,true);
			curMonth = calCurr.get(calCurr.MONTH);
			//writeLog(filePtr,"curMonth-->"+curMonth,true);
			curYear = calCurr.get(calCurr.YEAR);
			//writeLog(filePtr,"curYear-->"+curYear,true);
			chgDate = new Integer(curYear).toString()+ "-"+new Integer(curMonth).toString()+"-"+new Integer(curDate).toString();
			//writeLog(filePtr,"chgDate-->"+chgDate,true);
			exchRate = genericUtility.getColumnValue("exch_rate",headerDom);
			//writeLog(filePtr,"currExchangeRate-->"+exchRate,true);
			currCode = genericUtility.getColumnValue("curr_code",headerDom);
			//writeLog(filePtr,"currCode-->"+currCode,true);
			lastChq = genericUtility.getColumnValue("ref_no",headerDom);
			//writeLog(filePtr,"lastChq-->"+lastChq,true);
			uptoChq = genericUtility.getColumnValue("ref_no__upto",headerDom);
			//writeLog(filePtr,"uptoChq-->"+uptoChq,true);
			//chgDate = java.sql.Timestamp.valueOf(sDate + " 00:00:00");
			//Added by Jaimin 25/07/2007
			if (siteCode != null)
			{
				sql = "SELECT FIN_ENTITY,DESCR FROM SITE WHERE SITE_CODE ='"+siteCode+"'";
				//writeLog(filePtr,"sql-->"+sql,true);
				pstmt = conn.prepareStatement(sql);
				rs = pstmt.executeQuery();
				if (rs.next())
				{
					finEntity = rs.getString(1);
					siteDescr = rs.getString(2);
				}
				//writeLog(filePtr,"finEntity-->"+finEntity,true);
				//writeLog(filePtr,"siteDescr-->"+siteDescr,true);
			}
			rs.close();
			pstmt.close();
			pstmt = null;
			if ( finEntity != null )
			{
				sql = "SELECT DESCR FROM FINENT WHERE FIN_ENTITY ='"+finEntity+"'";
				//writeLog(filePtr,"sql-->"+sql,true);
				pstmt = conn.prepareStatement(sql);
				rs = pstmt.executeQuery();
				if (rs.next())
				{
					finentDescr = rs.getString(1);					
				}		
				//writeLog(filePtr,"finentDescr-->"+finentDescr,true);
			}
			rs.close();
			pstmt.close();
			pstmt = null;
			if ( bankCode != null )
			{
				sql = "SELECT BANK_NAME FROM BANK WHERE BANK_CODE ='" + bankCode +"'";
				//writeLog(filePtr,"sql-->"+sql,true);
				pstmt = conn.prepareStatement(sql);
				rs = pstmt.executeQuery();
				if (rs.next())
				{
					bankName= rs.getString(1);					
				}	
				//writeLog(filePtr,"bankName-->"+bankName,true);
			}
			rs.close();	
			pstmt.close();
			pstmt = null;
			//End by Jaimin 25/07/2007
			xmlString = new StringBuffer("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
			xmlString.append("<DocumentRoot><description>Datawindow Root</description><group0><description>Group0 escription</description>");
			xmlString.append("<Header0>");
			xmlString.append("<description>Header0 members</description>");
			xmlString.append("<objName><![CDATA[").append("auto_pay").append("]]></objName>");//"auto_pay" Added by Jaimin 25/07/2007
			xmlString.append("<pageContext><![CDATA[").append("1").append("]]></pageContext>");
			xmlString.append("<objContext><![CDATA[").append("1").append("]]></objContext>");
			xmlString.append("<editFlag><![CDATA[").append("A").append("]]></editFlag>");
			xmlString.append("<focusedColumn><![CDATA[").append("").append("]]></focusedColumn>");
			xmlString.append("<action><![CDATA[").append("SAVE").append("]]></action>");
			xmlString.append("<elementName><![CDATA[").append("").append("]]></elementName>");
			xmlString.append("<keyValue><![CDATA[").append("1").append("]]></keyValue>");
			xmlString.append("<taxKeyValue><![CDATA[").append("").append("]]></taxKeyValue>");
			xmlString.append("<saveLevel><![CDATA[").append("1").append("]]></saveLevel>");
			xmlString.append("<forcedSave><![CDATA[").append(true).append("]]></forcedSave>");
			xmlString.append("<taxInFocus><![CDATA[").append(false).append("]]></taxInFocus>");
			xmlString.append("<Detail1 dbID='' domID=\"1\" objName=\"auto_pay\" objContext=\"1\">");//"auto_pay" Added by Jaimin 25/07/2007
			xmlString.append("<attribute pkNames=\"tran_id:\" status=\"N\" updateFlag=\"A\" selected=\"N\" />");
			xmlString.append("<tran_id><![CDATA[]]></tran_id>");			
			xmlString.append("<tran_date><![CDATA[" + payDate + "]]></tran_date>");			
			xmlString.append("<tran_type><![CDATA[" + tranType + "]]></tran_type>");
			xmlString.append("<site_code><![CDATA[" + siteCode + "]]></site_code>");
			xmlString.append("<site_descr><![CDATA[" + siteDescr + "]]></site_descr>");//Added by Jaimin 25/07/2007
			xmlString.append("<fin_entity><![CDATA[" + finEntity + "]]></fin_entity>");
			xmlString.append("<finent_descr><![CDATA[" + finentDescr + "]]></finent_descr>");//Added by Jaimin 25/07/2007
			xmlString.append("<bank_code><![CDATA[" + bankCode + "]]></bank_code>");
			xmlString.append("<bank_name><![CDATA[" + bankName + "]]></bank_name>");//Added by Jaimin 25/07/2007
			xmlString.append("<exch_rate><![CDATA[" + exchRate + "]]></exch_rate>");
			xmlString.append("<curr_code><![CDATA[" + currCode + "]]></curr_code>");
			if (bankCodeAdd==null)
			{bankCodeAdd = "";}
			xmlString.append("<bank_code__add><![CDATA[" + bankCodeAdd + "]]></bank_code__add>");
			xmlString.append("<confirmed><![CDATA[N]]></confirmed>");
			xmlString.append("<emp_code__conf><![CDATA[]]></emp_code__conf>");
			xmlString.append("<conf_date><![CDATA[]]></conf_date>");
			xmlString.append("<chg_user><![CDATA[" + chgUser + "]]></chg_user>");
			xmlString.append("<chg_term><![CDATA[" + chgTerm + "]]></chg_term>");
			xmlString.append("<chg_date><![CDATA[" + chgDate + "]]></chg_date>");
			xmlString.append("<chq_no__fr><![CDATA[" + lastChq + "]]></chq_no__fr>");
			xmlString.append("<chq_no__to><![CDATA[" + uptoChq + "]]></chq_no__to>");			
			xmlString.append("</Detail1>");	
			parentNodeList = detailDom.getElementsByTagName("Detail2");
			parentNodeListLength = parentNodeList.getLength(); 
			System.out.println("parentNodeListLength:::::::::"+parentNodeListLength);
			//writeLog(filePtr,"parentNodeListLength-->"+parentNodeListLength,true);
			for (int selectedRow = 0; selectedRow < parentNodeListLength; selectedRow++)
			{
			    parentNode = parentNodeList.item(selectedRow);
				childNodeList = parentNode.getChildNodes();
				childNodeListLength = childNodeList.getLength();
				System.out.println("childNodeListLength::: "+ childNodeListLength+"\n");
				//writeLog(filePtr,"childNodeListLength-->"+childNodeListLength,true);
				for (int childRow = 0; childRow < childNodeListLength; childRow++)
				{
					childNode = childNodeList.item(childRow);
					childNodeName = childNode.getNodeName();
					if (childNodeName.equals("ref_no"))
					{
						if(childNode.getFirstChild()!=null)
						{
							refNo = childNode.getFirstChild().getNodeValue();
						}
					}
					if (childNodeName.equals("ref_date"))
					{
						if(childNode.getFirstChild()!=null)
						{
							String tmpDate = childNode.getFirstChild().getNodeValue();
							if (tmpDate.length()>10)
							{
								tmpDate = tmpDate.substring(0,9);
							}
							//refDate = childNode.getFirstChild().getNodeValue();
							refDate = genericUtility.getValidDateString(tmpDate,genericUtility.getDBDateFormat(),genericUtility.getApplDateFormat());
						}
					}
					if (childNodeName.equals("bill_no"))
					{
						if(childNode.getFirstChild()!=null)
						{
							billNo = childNode.getFirstChild().getNodeValue();
						}
					}
					if (childNodeName.equals("bill_date"))
					{
						if(childNode.getFirstChild()!=null)
						{
							String tmpDate = childNode.getFirstChild().getNodeValue();
							if (tmpDate.length()>10)
							{
								tmpDate = tmpDate.substring(0,9);
							}
							billDate = genericUtility.getValidDateString(tmpDate,genericUtility.getDBDateFormat(),genericUtility.getApplDateFormat());
							
							//billDate = childNode.getFirstChild().getNodeValue();
						}
					}
					if (childNodeName.equals("curr_code"))
					{
						if(childNode.getFirstChild()!=null)
						{
							currCode = childNode.getFirstChild().getNodeValue();
						}
					}
					if (childNodeName.equals("exch_rate"))
					{
						if(childNode.getFirstChild()!=null)
						{
							exchRate = childNode.getFirstChild().getNodeValue();
						}
					}
					if (childNodeName.equals("sundry_code"))
					{
						if(childNode.getFirstChild()!=null)
						{
							sundryCode = childNode.getFirstChild().getNodeValue();
						}
					}
					if (childNodeName.equals("acct_code"))
					{
						if(childNode.getFirstChild()!=null)
						{
							acctCode = childNode.getFirstChild().getNodeValue();
						}
					}
					if (childNodeName.equals("cctr_code"))
					{
						if(childNode.getFirstChild()!=null)
						{
							cctrCode = childNode.getFirstChild().getNodeValue();
						}
					}
					if (childNodeName.equals("due_date"))
					{
						if(childNode.getFirstChild()!=null)
						{
							String tmpDate = childNode.getFirstChild().getNodeValue();
							if (tmpDate.length()>10)
							{
								tmpDate = tmpDate.substring(0,9);
							}
							//dueDate = childNode.getFirstChild().getNodeValue();
							dueDate = genericUtility.getValidDateString(tmpDate,genericUtility.getDBDateFormat(),genericUtility.getApplDateFormat());
						}
					}
					if (childNodeName.equals("tot_amt"))
					{
						if(childNode.getFirstChild()!=null)
						{
							totAmt = childNode.getFirstChild().getNodeValue();
						}
					}
					if (childNodeName.equals("sundry_type"))
					{
						if(childNode.getFirstChild()!=null)
						{
							sundryType = childNode.getFirstChild().getNodeValue();
						}
					}
					if (childNodeName.equals("pay_mode"))
					{
						if(childNode.getFirstChild()!=null)
						{
							payMode = childNode.getFirstChild().getNodeValue();
						}
					}
					if (childNodeName.equals("adv_amt"))
					{
						if(childNode.getFirstChild()!=null)
						{
							advAmt = childNode.getFirstChild().getNodeValue();
						}
					}
					if (childNodeName.equals("tran_id"))
					{
						if(childNode.getFirstChild()!=null)
						{
							tranId = childNode.getFirstChild().getNodeValue();
						}
					}
					if (childNodeName.equals("tran_ser"))
					{
						if(childNode.getFirstChild()!=null)
						{
							tranSer = childNode.getFirstChild().getNodeValue();
						}
					}
					if (childNodeName.equals("adj_amt"))
					{
						if(childNode.getFirstChild()!=null)
						{
							adjAmt = childNode.getFirstChild().getNodeValue();
						}
					}
					if (childNodeName.equals("hold_amt"))
					{
						if(childNode.getFirstChild()!=null)
						{
							holdAmt = childNode.getFirstChild().getNodeValue();
						}
					}
					if (childNodeName.equals("username"))
					{
						if(childNode.getFirstChild()!=null)
						{
							userName = childNode.getFirstChild().getNodeValue();
						}
					}
					if (childNodeName.equals("pay_amt"))
					{
						if(childNode.getFirstChild()!=null)
						{
							payAmt = childNode.getFirstChild().getNodeValue();
						}
					}
					if (childNodeName.equals("sundry_name"))
					{
						if(childNode.getFirstChild()!=null)
						{
							sundryName = childNode.getFirstChild().getNodeValue();
						}
					}
					if (childNodeName.equals("net_payable"))
					{
						if(childNode.getFirstChild()!=null)
						{
							netPayable = childNode.getFirstChild().getNodeValue();
						}
					}
				} // For inner loop
					//if (Double.parseDouble(netPayable) != 0 ) // Condition added by jaimin 16/08/2007 // Remarked by Raj - 29/12/2007
					if (Double.parseDouble(payAmt) != 0 ) // Condition added by jaimin 16/08/2007 // Changed by Raj - 29/12/2007
					{
						System.out.println("--------------> if payAmt>0 :: "+payAmt);
						System.out.println("--------------> if netPayable>0 :: "+netPayable);
						if ( (Double.parseDouble(netPayable) > 0 && Double.parseDouble(payAmt) <= Double.parseDouble(netPayable) && Double.parseDouble(payAmt) >=0) 
							|| (Double.parseDouble(netPayable) < 0 && Double.parseDouble(payAmt) <= 0 && Double.parseDouble(payAmt) >= Double.parseDouble(netPayable)) )
						{ // End by Jaimin 16/08/2007
							System.out.println("----------------In condition--------------");
						
							lineNo++;
							xmlString.append("<Detail2 dbID=':' domID='1' objName='auto_pay' objContext='2'>");
							xmlString.append("<attribute pkNames='tran_id:line_no:' status='N' updateFlag='A' selected='N' />");
							xmlString.append("<tran_id><![CDATA[]]></tran_id>");
							xmlString.append("<line_no><![CDATA["+lineNo+"]]></line_no>");
							xmlString.append("<tran_ser><![CDATA["+tranSer+"]]></tran_ser>");
							xmlString.append("<ref_no><![CDATA["+refNo+"]]></ref_no>");
							xmlString.append("<tran_date><![CDATA[" + payDate + "]]></tran_date>");//Added by Jaimin 25/07/2007
							xmlString.append("<ref_date><![CDATA["+refDate+"]]></ref_date>");
							xmlString.append("<bill_no><![CDATA["+billNo+"]]></bill_no>");
							xmlString.append("<bill_date><![CDATA["+billDate+"]]></bill_date>");
							xmlString.append("<curr_code><![CDATA["+currCode+"]]></curr_code>");
							xmlString.append("<exch_rate><![CDATA["+exchRate+"]]></exch_rate>");
							xmlString.append("<sundry_type><![CDATA["+sundryType+"]]></sundry_type>");
							xmlString.append("<sundry_code><![CDATA["+sundryCode+"]]></sundry_code>");
							xmlString.append("<acct_code><![CDATA["+acctCode+"]]></acct_code>");
							xmlString.append("<cctr_code><![CDATA["+cctrCode+"]]></cctr_code>");
							xmlString.append("<due_date><![CDATA["+dueDate+"]]></due_date>");
							xmlString.append("<tot_amt><![CDATA["+totAmt+"]]></tot_amt>");
							xmlString.append("<pay_mode><![CDATA["+payMode+"]]></pay_mode>");
							xmlString.append("<adv_amt><![CDATA["+advAmt+"]]></adv_amt>");
							xmlString.append("<adj_amt><![CDATA["+adjAmt+"]]></adj_amt>");
							xmlString.append("<hold_amt><![CDATA["+holdAmt+"]]></hold_amt>");
							xmlString.append("<net_payable><![CDATA["+netPayable+"]]></net_payable>");
							xmlString.append("<pay_amt><![CDATA["+payAmt+"]]></pay_amt>");
							xmlString.append("<tran_id__pay><![CDATA[]]></tran_id__pay>");
							xmlString.append("<tran_id__miscpay><![CDATA["+tranId+"]]></tran_id__miscpay>");
							xmlString.append("<sundry_name><![CDATA["+sundryName+"]]></sundry_name>");					
							xmlString.append("</Detail2>");			
						}
						else
						{//case added by Jaimin 17/08/2007
							System.out.println("--------------> Error<---------------------"+refNo);	
							
							errString= errString+	"\n"+ "[ref_no ::"+refNo+"]"
							+"\n"+ "[tran_ser ::"+tranSer+"]"
							+"\n"+ "[pay_mode ::"+payMode+"]" 
							+"\n"+"[net_payable ::"+netPayable+"]"
							+"\n"+"[pay_Amt ::"+payAmt+"]"+"\n";
							
						}
					}
				}  //FOR OUTER LOOP
			if (errString.trim().length()>0 )
			{				
				err = errMsg("","","",errString);
			}//End by Jaimin 17/08/2007
			else
			{
				xmlString.append("</Header0></group0></DocumentRoot>");			
				xmlOutString  = xmlString.toString();
				 //writeLog(filePtr,"xmlString-->\n"+xmlString,true);
				 String [] authencate = new String[2];
				 authencate[0] = "";
				 authencate[1] = "";
				 InitialContext ctx = null;
				 MasterStatefulLocal masterStateful = null;
				 AppConnectParm appConnect = new AppConnectParm();
				 ctx = new InitialContext(appConnect.getProperty());
				 masterStateful = (MasterStatefulLocal)ctx.lookup("ibase/MasterStatefulEJB/local");// added for ejb3
				 //MasterStateful masterStateful = masterStatefulHome.create(); //commented for ejb3
				 retString = masterStateful.processRequest(authencate, siteCode, true,xmlOutString);
				 //Added - Gulzar - 25/01/08
				 if ( retString.indexOf("Success") > 0 )
				 {
					 retString = itmDBAccessEJB.getErrorString("","VTCOMPL","userId");
				 }
				 //End Added - Gulzar - 25/01/08
			}
			System.out.println("retString:: "+ retString);
		}	
		catch(Exception e)
		{
			//writeLog(filePtr,"Exception in process-->"+e,true);
			System.out.println( e.getMessage());
		}  
		finally
		{
			try
			{
				conn.close();
				conn = null;
			}
			catch (Exception e)
			{
				//writeLog(filePtr,"Exception in process-->"+e,true);
				System.out.println(e.getMessage());
			}
		}
		if ( errString.trim().length() > 0 )
		{
			return err;
		}
		else
		{
			return retString;
		}
	}	
	//Function added by Jaimin 20/08/2007
	public String errMsg(String columnName,String msgNo,String userId,String errTrace)throws RemoteException,ITMException
	{
       Connection conn = null;
		ConnDriver connDriver = new ConnDriver();
		StringBuffer errStringXml;
		Statement stmt = null;
		ResultSet rs = null;
		ResultSet rs1 = null;
		ResultSet rs2 = null;
		String sqlQuery,sqlQuery1;
		String msgType = "";
		String msgString = "";
		String msgDescription = "";
		String lmsgString = "";
		String profileId = "";
		String errSource = "";
		String tempMsgType = "";
		String msgOption = "";		
		String msgTime = "";

		String redirerr = "" ;
		String soundPlay = "";
		FileOutputStream fos;
		try
		{
			conn = connDriver.getConnectDB("DriverITM");
			sqlQuery = "SELECT MSG_TYPE,MSG_STR,MSG_DESCR,MSG_OPT,MSG_TIME,ALARM,ERR_SOURCE FROM MESSAGES WHERE MSG_NO='" + msgNo + "'";
			stmt = conn.createStatement();
			rs = stmt.executeQuery(sqlQuery);
			if (rs.next())
			{
				msgType = rs.getString("MSG_TYPE");
				msgString = rs.getString("MSG_STR");
				msgDescription = rs.getString("MSG_DESCR");
				errSource = rs.getString("ERR_SOURCE");
				msgOption = rs.getString("MSG_OPT");				
				msgTime = rs.getString("MSG_TIME");
				soundPlay = rs.getString("ALARM");
			}
			else
			{
				lmsgString = "Message Not Defined >>" + msgNo;
				msgDescription = "Message Id not found.";
				msgType = "";
				msgString = "";
			}

			if (msgType.equals("E") || msgType.trim().length() == 0) 
			{
				sqlQuery1 = "SELECT PROFILE_ID FROM USERS WHERE CODE='" + userId + "'";
				rs1 = conn.createStatement().executeQuery(sqlQuery1);
				if (rs1.next())
				{
					profileId=rs1.getString("profile_id");
					if (profileId == null)
					{
						profileId= "";
					}
					sqlQuery1 = "SELECT MSG_TYPE FROM MESSAGES_LEVEL WHERE MSG_NO='" + msgNo.trim() + "' AND PROFILE_ID='" + profileId.trim() + "'";
					rs2 = conn.createStatement().executeQuery(sqlQuery1);
					if (rs2.next())
					{
						tempMsgType = rs2.getString("msg_type");
					}
				}
				if (tempMsgType!=null && tempMsgType.trim().length()>0)
				{
					msgType = tempMsgType;
				}
			}
			if (msgType.equals("W"))
			{
				msgString = "Warning : " + msgString;
			}
			else if (msgType.equals("P"))
			{
				msgString = "Prompt : " + msgString;
			}
			else
			{
				msgType = "E";
				msgString = "Error : " + msgString;
			}
			if (errSource!=null && errSource.trim().equals("D"))
			{
				msgDescription = msgDescription +  " * From Database ";
			}
			if (redirerr==null || redirerr.trim().length()==0)
			{
				redirerr = "1";
			}
			if (msgOption!=null && msgOption.trim().equals("M"))
			{
				if (redirerr.trim().equals("1"))
				{
					redirerr = "2";
				}
				else
				{
					redirerr = "1";
				}
			}
			if (rs != null)
			{
				rs.close();
			}
			if (rs1 != null)
			{
				rs1.close();			
			}
			conn.close();
		}
		catch(ITMException itme)
		{
			System.out.println("ITMException : [ValidatorEJB][getErrorString] :==>\n"+itme.getMessage());
			throw itme;
		}
		catch(SQLException se)
		{
			lmsgString = "Database Error >>" + se.getErrorCode(); //msgNo;
			msgDescription = se.getMessage();
			msgType = "";
			msgString = "";
			System.out.println("Exception : [ValidatorEJB][getErrorString] :==>\n"+se.getMessage());
			se.printStackTrace();
			throw new ITMException(se);
		}
		catch(Exception e)
		{
			System.out.println("Exception : [ValidatorEJB][getErrorString] :==>\n"+e.getMessage());
			e.printStackTrace();
			throw new ITMException(e);
		}
		errStringXml = new StringBuffer();
		errStringXml.append("<?xml version=\"1.0\"?>\r\n<Root><Errors>\r\n");
		errStringXml.append("<error id=\"");
		errStringXml.append(msgNo).append("\" type=\"").append(msgType).append("\" column_name=\"");
		errStringXml.append(columnName).append("\">\r\n").append("<message>").append(msgString);
		errStringXml.append("</message>\r\n<description>").append(msgDescription).append("</description>\r\n");
		errStringXml.append("<type>").append(msgType).append("</type>\r\n<option>").append(msgOption).append("</option>\r\n");		
		errStringXml.append("<time>").append(msgTime).append("</time>\r\n");

		errStringXml.append("<alarm>").append(soundPlay).append("</alarm>\r\n<source>");
		errStringXml.append(errSource).append("</source>\r\n<trace>").append(errTrace);
		errStringXml.append("</trace>\r\n<redirect>").append(redirerr).append("</redirect>\r\n</error>\r\n");
		errStringXml.append("</Errors></Root>\r\n");
/*		if (msgType.trim().equals("E"))
		{
			errStringXml = buildErrorString();
		}*/
		try 
		{
			fos = new FileOutputStream("C:" + File.separator + "ErrorXml.xml");
			byte convertStringToByte[] = errStringXml.toString().getBytes();
			fos.write(convertStringToByte);
			fos.close();
		}
		catch(Exception e)
		{ 
			System.out.println("Exception : [ValidatorEJB][getErrorString] \n:==>"+e.getMessage());
			e.printStackTrace();
			throw new ITMException(e);
		}
		return errStringXml.toString();

	}
 }