package ibase.webitm.ejb.fin;
import ibase.webitm.utility.*;
import ibase.utility.CommonConstants;
import ibase.webitm.ejb.*;
import ibase.system.config.*;
import java.rmi.RemoteException;
import java.text.*;
import java.util.*;
import java.util.Date;
import java.sql.*;

import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.apache.axis.encoding.XMLType;
import javax.ejb.Stateless;
import javax.naming.InitialContext;
import javax.xml.rpc.ParameterMode;
import org.w3c.dom.*;

import javax.swing.text.DefaultEditorKit.CutAction;
import javax.xml.parsers.*;

import javax.ejb.*;

import javax.naming.InitialContext;
import java.io.*;

import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.Transformer;
import ibase.webitm.ejb.fin.InsuranceUpdate;
import javax.ejb.Stateless; 
@Stateless

public class ReceivablesTransPrc extends ProcessEJB implements ReceivablesTransPrcLocal,ReceivablesTransPrcRemote //SessionBean
{
	private static final String reasCode = null;
	Connection conn = null;
	String errorString = null;
	GenericUtility genericUtility = GenericUtility.getInstance();
	ITMDBAccessEJB itmDBAccessEJB = new ITMDBAccessEJB();
	
	java.sql.Date currDate = null;
	String currAppdate= "";

	/*public void ejbCreate() throws RemoteException, CreateException 
	{
		System.out.println("Create Method Called....");
	}
	public void ejbRemove()
	{
	}
	public void ejbActivate() 
	{
	}
	public void ejbPassivate() 
	{
	}*/
	

	
	//java.sql.Date today = null;
	
	File filePtr = null;

	static
	{
		File mkd = new File("../log");
		if(!mkd.exists())
		{
			mkd.mkdirs();
			System.out.println("Directory Built................ "+mkd);
		}

	}
	
	public String process() throws RemoteException,ITMException
	{
		return "";
	}

	@Override
	public String getData(String xmlString, String xmlString2, String windowName, String xtraParams) throws RemoteException,ITMException
	{
	
		
		String rtrStr = "";
		Document headerDom = null;
		Document detailDom = null;	
	/*	try
		{
			
		}
		catch(Exception e)
		{
			e.printStackTrace(); 
			throw new ITMException(e);
		}*/

		try
		{
			
			currDate = new java.sql.Date(System.currentTimeMillis()) ;
			currAppdate = new SimpleDateFormat(genericUtility.getApplDateFormat()).format(currDate);
			currAppdate = currAppdate.replace("/", "-");		
			filePtr = new File("../log/Receivables_Trans"+currAppdate+".log");
			System.out.print("filePtr@@@@@@@@@@@@@@"+filePtr);
					
			/*
			currDate = new java.sql.Date(System.currentTimeMillis()) ;
			currAppdate = new SimpleDateFormat("dd-MM-yy").format(currDate);
			filePtr = new File("../log/Receivables_Trans"+currAppdate+".log");*/

			if(xmlString != null && xmlString.trim().length()!=0)
			{
				System.out.println("XML String :"+xmlString);
				headerDom = genericUtility.parseString(xmlString); 				
			}
			if(xmlString2 != null && xmlString2.trim().length()!=0)
			{
				System.out.println("XML String :"+xmlString2);
				detailDom = genericUtility.parseString(xmlString2); 				
			}
			rtrStr = getData(headerDom, detailDom, windowName, xtraParams);
		}
		catch (Exception e)
		{

			System.out.println("Exception :ReceivablesTransPrcEJB :getData(String xmlString, String xmlString2, String windowName, String xtraParams):" + e.getMessage() + ":");
			rtrStr = e.getMessage();
			throw new ITMException(e);

		}
		return rtrStr; 
	}//END OF GETDATA(1)

	public String blanknull(String s)
	{
		if( s==null )
			return " ";
		else
			return s;
	}


	@Override
	public String getData(Document headerDom, Document detailDom, String windowName,
			String xtraParams) throws RemoteException,ITMException
			{
		//writeLog(filePtr,"G E T D A T A  I N  P R O C E S S ",false);
		String errCode = "";
		String errString = "";
		String getDataSql= "" ;
		SimpleDateFormat  simpleDateFormat=null;
		String resultString = "";
		ResultSet rs1 = null,rs=null;
		PreparedStatement pstmt = null;
		StringBuffer retTabSepStrBuff = new StringBuffer();
		int cnt=0,count=0,i=2;
		String sql="",tranId="",tranType="", siteCode="", custCodeFrom="", custCodeTo="",reasCode="", processDate="";
		java.sql.Timestamp tranDateFrom = null;
		java.sql.Timestamp                tranDateTo = null;
		String dateFrom="",dateTo="";
		String tranDateFrom1 = "", tranDateTo1="";

		ConnDriver connDriver = new ConnDriver();
		Connection conn= null;
		try
		{
			if(conn==null)
			{
				conn = connDriver.getConnectDB("DriverITM");
				conn.setAutoCommit(false);        
			}
			
			DatabaseMetaData dbmd = conn.getMetaData();
			//writeLog(filePtr,"DriverName["+dbmd.getDriverName() + "]",true);
		//	writeLog(filePtr,"DriverURI["+dbmd.getURL()  + "]",true);
			//writeLog(filePtr,"DriverUSER["+dbmd.getUserName() + "]",true);
			//writeLog(filePtr,"ApplDateFormat["+genericUtility.getApplDateFormat() + "]",true);
			//writeLog(filePtr,"DBDateFormat["+genericUtility.getDBDateFormat() + "]",true);

			System.out.println("DriverName["+dbmd.getDriverName() + "]");
			System.out.println("DriverURI["+dbmd.getURL()  + "]");
			System.out.println("DriverUSER["+dbmd.getUserName() +"]");

			//simpleDateFormat = new SimpleDateFormat("dd/MM/yy");

			System.out.println("ReceivablesTransPrc : getData() Method Called");

			tranDateFrom1 = genericUtility.getColumnValue( "tran_date_from", headerDom );
			tranDateTo1 = genericUtility.getColumnValue( "tran_date_to", headerDom );

			if ( tranDateFrom1 == null  )
			{
				System.out.println("tran Date From is Null...");
				errString = itmDBAccessEJB.getErrorString("","VMTRDTFRNU","","",conn);
				return errString;
			}

			if ( tranDateTo1 == null  )
			{
				System.out.println("tran Date To is Null...");
				errString = itmDBAccessEJB.getErrorString("","VMTRDTTONU","","",conn);
				return errString;
			}


			dateFrom=genericUtility.getColumnValue("tran_date_from", headerDom );
			dateFrom=genericUtility.getValidDateString(dateFrom, genericUtility.getApplDateFormat(), genericUtility.getDBDateFormat());
			tranDateFrom=java.sql.Timestamp.valueOf(dateFrom + " 00:00:00");
			dateTo=genericUtility.getColumnValue("tran_date_to", headerDom );
			dateTo=genericUtility.getValidDateString(dateTo, genericUtility.getApplDateFormat(), genericUtility.getDBDateFormat());
			tranDateTo=java.sql.Timestamp.valueOf(dateTo + " 00:00:00");

			System.out.println("tranDateTo="+tranDateTo);

			tranType = genericUtility.getColumnValue("tran_type",headerDom);
			siteCode = genericUtility.getColumnValue("site_code",headerDom);
			custCodeFrom = genericUtility.getColumnValue("cust_code_from",headerDom);
			custCodeTo = genericUtility.getColumnValue("cust_code_to",headerDom);
			reasCode = genericUtility.getColumnValue("reas_code",headerDom);
			processDate = genericUtility.getColumnValue("process_date",headerDom);

			/*writeLog(filePtr,"tranDateFrom:::"+tranDateFrom,true);
			writeLog(filePtr,"tranDateTo:::"+tranDateTo,true);
			writeLog(filePtr,"tranType:::"+tranType,true);
			writeLog(filePtr,"siteCode:::"+siteCode,true);
			writeLog(filePtr,"custCodeFrom:::"+custCodeFrom,true);
			writeLog(filePtr,"custCodeTo:::"+custCodeTo,true);
			writeLog(filePtr,"reasCode:::"+reasCode,true);
			writeLog(filePtr,"processDate:::"+processDate,true);*/
			
			
			System.out.println("tranDateFrom=>"+tranDateFrom);
			System.out.println("tranDateTo=>"+tranDateTo);
			System.out.println("tranType =>"+tranType);
			System.out.println("siteCode =>"+siteCode);
			System.out.println("custCodeFrom=>"+custCodeFrom);
			System.out.println("custCodeTo=>"+custCodeTo);
			System.out.println("reasCode =>"+reasCode);
			System.out.println("processDate =>"+processDate);

			if ( tranDateFrom == null  )
			{
				//writeLog(filePtr,"tran Date From is Null:::"+tranDateFrom,true);
				System.out.println("tran Date From is Null...");
				errString = itmDBAccessEJB.getErrorString("","VMTRDTFRNU","","",conn);
				return errString;
			}

			if ( tranDateTo == null  )
			{
				//writeLog(filePtr,"tran Date To is Null:::"+tranDateTo,true);
				System.out.println("tran Date To is Null...");
				errString = itmDBAccessEJB.getErrorString("","VMTRDTTONU","","",conn);
				return errString;
			}
			else
			{
				if( tranDateFrom != null && tranDateTo != null)
				{
					if( tranDateTo.before(tranDateFrom))
					{
						errString = itmDBAccessEJB.getErrorString("","VMTRDTINV","","",conn);
						return errString;
					}
				}
			}

			if ( tranType == null || tranType.trim().length() == 0 )
			{
			//	writeLog(filePtr,"tran Type is Null...:::"+tranType,true);
				System.out.println("tran Type is Null...");
				errString = itmDBAccessEJB.getErrorString("","VMTRTYPENU","","",conn);
				return errString;
			}

			if ( siteCode == null || siteCode.trim().length() == 0 )
			{
				//writeLog(filePtr,"site Code is Null.....:::"+siteCode,true);
				System.out.println("site Code From is Null...");
				errString = itmDBAccessEJB.getErrorString("","VMSTCODENU","","",conn);
				return errString;
			}
			else
			{

				sql=  " select count(1) from site where site_code = ?  ";
				pstmt = conn.prepareStatement(sql);
				pstmt.setString(1,siteCode);
				rs = pstmt.executeQuery();
				if (rs.next())
				{
					cnt = rs.getInt(1);
				}
				pstmt.close();
				pstmt = null;
				rs.close();
				rs = null;

				if(cnt == 0 )
				{
					//writeLog(filePtr,"siteCode not founds in siteMaster:::",true);
					System.out.println("Invalid Site Code From ...");
					errString = itmDBAccessEJB.getErrorString("","VMSITECOIN","","",conn);
					return errString;
				}


			}

			System.out.println("cust_code__from is :::"+custCodeFrom);
			System.out.println("cust_code__to is :::"+custCodeTo);
			
			//writeLog(filePtr,"cust_code__from:::"+custCodeFrom,true);
			//writeLog(filePtr,"cust_code__to:::"+custCodeTo,true);
			
			if ( custCodeFrom == null || custCodeFrom.trim().length() == 0 )
			{
				System.out.println("cust Code From is Null...");
				errString = itmDBAccessEJB.getErrorString("","VMCUCOFRNU","","",conn);
				return errString;
			}
			else
			{
				sql=  " select count(1)from customer where cust_code = ?  ";
				pstmt = conn.prepareStatement(sql);
				pstmt.setString(1,custCodeFrom);
				rs = pstmt.executeQuery();
				if (rs.next())
				{
					cnt = rs.getInt(1);
				}
				pstmt.close();
				pstmt = null;
				rs.close();
				rs = null;

				if(cnt == 0 )
				{
					//writeLog(filePtr,"Invalid cust Code From ...:::",true);
					System.out.println("Invalid cust Code From ...");
					errString = itmDBAccessEJB.getErrorString("","VMCUCOFRIN","","",conn);
					return errString;
				}
			}

			if ( custCodeTo == null || custCodeTo.trim().length() == 0 )
			{
				//writeLog(filePtr,"cust Code To is Null....:::",true);
				System.out.println("cust Code To is Null...");
				errString = itmDBAccessEJB.getErrorString("","VMCUCOTONU","","",conn);
				return errString;
			}
			else
			{
				sql=  " select count(*)from customer where cust_code = ?  ";
				pstmt = conn.prepareStatement(sql);
				pstmt.setString(1,custCodeTo);
				rs = pstmt.executeQuery();
				if (rs.next())
				{
					cnt = rs.getInt(1);
				}

				if(cnt == 0 )
				{
					//writeLog(filePtr,"Invalid cust Code To ...:::",true);
					System.out.println("Invalid cust Code To ...");
					errString = itmDBAccessEJB.getErrorString("","VMCUCOTOIN","","",conn);
					return errString;
				}
				pstmt.close();
				pstmt = null;
				rs.close();
				rs = null;
			}


			if ( reasCode == null || reasCode.trim().length() == 0 )
			{
				//writeLog(filePtr,"reas Code is Null...:::",true);
				System.out.println("reas Code is Null...");
				errString = itmDBAccessEJB.getErrorString("","VMREASCONU","","",conn);
				return errString;
			}
			else
			{

				sql = "  select count(1) from gencodes where fld_value = ?  and fld_name='REAS_CODE' ";         
				pstmt = conn.prepareStatement(sql);
				pstmt.setString(1,reasCode);
				rs = pstmt.executeQuery();
				if ( rs.next() )
				{
					cnt =  rs.getInt(1);
				}
				pstmt.close();
				pstmt = null;
				rs.close();
				rs = null;

				if( cnt == 0)
				{
					//writeLog(filePtr,"reas Code is not vaild...:::",true);
					errString = itmDBAccessEJB.getErrorString("","VMREACOINV","","",conn);
					return errString;
				}
			}

			getDataSql=  " select tran_id,tran_ser,tran_date,cust_code,ref_date,curr_code,exch_rate,site_code," +
					"fin_entity,tot_amt,adj_amt,status,stat_date,reas_code,bank_code,cust_ref_no,cust_ref_date,ref_no,due_date from  receivables " +
					" where ( tran_date >= ? and tran_date <= ? )  and site_code = ?  " +
					" and   ( cust_code >= ? and cust_code <= ? ) and ( tot_amt <> adj_amt ) ";
			//writeLog(filePtr,"GetData 1st Sql :::."+ sql,true);
		
			System.out.println("Sql Fired :::::"+getDataSql);                                        
			pstmt = conn.prepareStatement(getDataSql);
			pstmt.setTimestamp(1,tranDateFrom);
			pstmt.setTimestamp(2,tranDateTo);
			pstmt.setString(3,siteCode);
			pstmt.setString(4,custCodeFrom);
			pstmt.setString(5,custCodeTo);
			//writeLog(filePtr,"getDataSql :::."+ getDataSql,true);
			System.out.println("QUERY IS IN PROCESS..........");
			rs1 = pstmt.executeQuery();
			System.out.println("QUERY  PROCESS FINISED.......");
			while(rs1.next()) 
			{
				//tran_id
				retTabSepStrBuff.append((rs1.getString(1)==null?"":rs1.getString(1))).append("\t");
				//tran_ser
				retTabSepStrBuff.append((rs1.getString(2)==null?"":rs1.getString(2))).append("\t");
				//tran_date
				if(rs1.getTimestamp(3)!=null)
				{
					retTabSepStrBuff.append(this.genericUtility.getValidDateString(rs1.getTimestamp(3).toString(),this.genericUtility.getDBDateFormat(),this.genericUtility.getApplDateFormat())).append("\t");
				}
				else
				{
					retTabSepStrBuff.append(" ").append("\t");
				}
				//tran_type
				retTabSepStrBuff.append(tranType ==null?" ":tranType).append("\t");
				//cust_code
				retTabSepStrBuff.append((rs1.getString(4)==null?"":rs1.getString(4))).append("\t");
				//ref_date
				if(rs1.getTimestamp(5)!=null)
				{
					retTabSepStrBuff.append(this.genericUtility.getValidDateString(rs1.getTimestamp(5).toString(),this.genericUtility.getDBDateFormat(),this.genericUtility.getApplDateFormat())).append("\t");
				}
				else
				{
					retTabSepStrBuff.append(" ").append("\t");
				}
				//curr_code
				retTabSepStrBuff.append((rs1.getString(6)==null?"":rs1.getString(6))).append("\t");
				//exch_rate
				retTabSepStrBuff.append((rs1.getString(7)==null?"":rs1.getDouble(7))).append("\t");
				//site_code
				retTabSepStrBuff.append((rs1.getString(8)==null?"":rs1.getString(8))).append("\t");
				//fin_entity
				retTabSepStrBuff.append((rs1.getString(9)==null?"":rs1.getString(9))).append("\t");
				//tot_amt
				retTabSepStrBuff.append(String.valueOf(rs1.getDouble(10))).append("\t");
				//adj_amt
				retTabSepStrBuff.append(String.valueOf(rs1.getDouble(11))).append("\t");
				//status
				retTabSepStrBuff.append((rs1.getString(12)==null?"":rs1.getString(12))).append("\t");
				//stat_date
				if(rs1.getTimestamp(13)!=null)
				{
					retTabSepStrBuff.append(this.genericUtility.getValidDateString(rs1.getTimestamp(13).toString(),this.genericUtility.getDBDateFormat(),this.genericUtility.getApplDateFormat())).append("\t");
				}
				else
				{
					retTabSepStrBuff.append(" ").append("\t");
				}
				//reas_code
				retTabSepStrBuff.append(reasCode).append("\t");
				//bank_code
				retTabSepStrBuff.append((rs1.getString(15)==null?"":rs1.getString(15))).append("\t");

				//cust_ref_no,
				retTabSepStrBuff.append((rs1.getString(16)==null?"":rs1.getString(16))).append("\t");
				//cust_ref_date
				if(rs1.getTimestamp(17)!=null)
				{
					retTabSepStrBuff.append(this.genericUtility.getValidDateString(rs1.getTimestamp(17).toString(),this.genericUtility.getDBDateFormat(),this.genericUtility.getApplDateFormat())).append("\t");
				}
				else
				{
					retTabSepStrBuff.append(" ").append("\t");
				}
				//ref_no,
				retTabSepStrBuff.append((rs1.getString(18)==null?"":rs1.getString(18))).append("\t");
				//due_date
				if(rs1.getTimestamp(19)!=null)
				{
					retTabSepStrBuff.append(this.genericUtility.getValidDateString(rs1.getTimestamp(19).toString(),this.genericUtility.getDBDateFormat(),this.genericUtility.getApplDateFormat())).append("\t");
				}
				else
				{
					retTabSepStrBuff.append(processDate).append("\t");
				}

				retTabSepStrBuff.append("\n");                                
				count++;
				
				
				
	/*			writeLog(filePtr," tran_id :::."+rs1.getString(1),true);
				writeLog(filePtr," tran_ser :::."+rs1.getString(2),true);
				writeLog(filePtr," tot_amt :::."+rs1.getDouble(10),true);
				writeLog(filePtr," curr_code :::."+rs1.getString(6),true);
				writeLog(filePtr," cust_ref_no :::."+rs1.getString(16),true);
				writeLog(filePtr," ref_no :::."+rs1.getString(18),true);
				writeLog(filePtr," adj_amt :::."+rs1.getDouble(11),true);
				writeLog(filePtr," BANK_CODE :::."+rs1.getString(15),true);*/
				System.out.println("#####Counter:["+count+"]");
				
				
				
			}//END WHILE
			rs1.close();
			pstmt.close();
			rs1=null;
			pstmt=null;
			if (count == 0 )
			{
				errString = itmDBAccessEJB.getErrorString("","VTNOREC1","","",conn);
			}

			else
			{
				System.out.println("Sql:::::is Null ::::::::::::::");
				errString = itmDBAccessEJB.getErrorString("","VTNOREC1","","",conn);
			}

			System.out.println("retTabSepStrBuff:::["+retTabSepStrBuff.toString()+"]");



		}        //end of try        
		catch (SQLException e)
		{ 
			e.printStackTrace();
			System.out.println("SQLException :ReceivablesTransPrcEJB :getData(Document headerDom, Document detailDom, String windowName, String xtraParams):" +e.getMessage() + ":");
			throw new ITMException(e);
		}
		catch (Exception e)
		{
			e.printStackTrace();
			System.out.println("Exception :ReceivablesTransPrcEJB :getData(Document  headerDom, Document detailDom, String windowName, String xtraParams):" +e.getMessage() + ":");
			throw new ITMException(e);
		}
		finally
		{                
			try
			{                
				conn.close();
				conn = null;
			}
			catch(Exception e)
			{
				errString = e.getMessage();
				e.printStackTrace();
				throw new ITMException(e);
			}
		}                
		if (getDataSql.trim().length()>0 && count > 0)
		{
			return retTabSepStrBuff.toString();        
		}
		else 
		{
			errString = itmDBAccessEJB.getErrorString("","VTNOREC1","","",conn);
			return errString;
		}
			}


	public String process(String xmlString, String xmlString2, String windowName, String xtraParams)
			throws RemoteException,ITMException
			{
		Document detailDom = null;
		Document headerDom = null;
		GenericUtility genericUtility = GenericUtility.getInstance();
		String retStr = "";
		try
		
		
		{	
			
	/*		writeLog(filePtr," IN P R O C E S S  :::.",true);
		//	writeLog(filePtr,"Generating  Receipt............... ",true);
			writeLog(filePtr,"xmlString :::."+xmlString,true);
			writeLog(filePtr,"xmlString :::."+xmlString2,true);
			writeLog(filePtr,"windowName :::."+windowName,true);
			writeLog(filePtr,"xtraParams :::."+xtraParams,true);
			*/
			
			
			System.out.println("xmlString[process]::::::::::;;;"+xmlString);
			System.out.println("xmlString2[process]::::::::::;;;"+xmlString2);
			System.out.println("windowName[process]::::::::::;;;"+windowName);
			System.out.println("xtraParams[process]:::::::::;;;"+xtraParams);
		}
		catch(Exception e)
		{
			System.out.println(e.getMessage());
			e.printStackTrace();
		}
		try
		{	
			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 :InvInsurancePrcEJB :process(String xmlString, String xmlString2, String windowName, String xtraParams):" + e.getMessage() + ":");
			e.printStackTrace();
			retStr = e.getMessage();
		}
		return retStr;
			}//END OF PROCESS (1)

	public String process(Document headerDom, Document detailDom, String windowName, String xtraParams) throws RemoteException,ITMException
	{		
		
		//writeLog(filePtr," IN P R O C E S S  :::.",true);
		String retStr = "";
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String sql = "" ,sql1 = "",errString = "";
		String retString = "" ,errCode = "",tranId="";
		String loginSiteCode="",empCode="",chgUser="",chgTerm="",loginCode="";
		String custCodeFr = "",custCodeTo = "",refNo = "";
		String childNodeName = null;

		int count =0,cnt =0;
		int parentNodeListLength = 0;
		int childNodeListLength = 0;
		String currCode="";
		String siteCode = "";
		String tranType  = "";
		String tranSer = "";
		String custRefNo = "";
		String finEntity ="";
		String returnString = "";
		String reasCode = "";
		String refDate = null;
		String custRefDate =null;
		String procesDate =null;
		String dueDate =null;
		String remarks = "";
		double exchRate=0,netAmt=0;
		double totAmt = 0,adjAmt = 0,diff= 0; 
		SimpleDateFormat  simpleDateFormat=null,sdf = null;;
		ArrayList tranIdArray = null;
		HashMap insUpdHMap = null;
		HashMap crMap = new HashMap();
		HashMap drMap = new HashMap();
		HashMap retMap = null;
		HashMap confMap = new HashMap();
		ConnDriver connDriver = new ConnDriver();
		NodeList parentNodeList = null;
		NodeList childNodeList = null;
		Node parentNode = null;
		Node childNode = null;
		try
		{
			simpleDateFormat = new SimpleDateFormat(genericUtility.getDBDateFormat());
			sdf = new SimpleDateFormat(genericUtility.getApplDateFormat());
			//simpleDateFormat = new SimpleDateFormat("dd/MM/yy");
			//	tranDate= simpleDateFormat.parse(simpleDateFormat.format(new Date()));
			//writeLog(filePtr,"xtraParams :::."+xtraParams,true);
			System.out.println("xtraParams :::::::::::::::::::::::::::::::::: "+xtraParams);

			loginSiteCode = genericUtility.getValueFromXTRA_PARAMS(xtraParams,"loginSiteCode");
			empCode = genericUtility.getValueFromXTRA_PARAMS(xtraParams,"loginEmpCode");
			chgUser = genericUtility.getValueFromXTRA_PARAMS(xtraParams,"userId");
			chgTerm = genericUtility.getValueFromXTRA_PARAMS(xtraParams,"termId");
			loginCode = genericUtility.getValueFromXTRA_PARAMS(xtraParams,"loginCode");

			
			/*
			writeLog(filePtr,"empCode :::."+empCode,true);
			writeLog(filePtr,"Login Site Code :::."+loginSiteCode,true);
			writeLog(filePtr,"userId :::."+chgUser,true);
			writeLog(filePtr,"termId :::."+chgTerm,true);*/
			
			System.out.println("empCode..............."+empCode);
			System.out.println("Login Site Code............."+loginSiteCode);
			System.out.println("userId............."+chgUser);
			System.out.println("termId............."+chgTerm);
			conn = connDriver.getConnectDB("DriverITM");
			conn.setAutoCommit(false);
			connDriver = null;

			custCodeFr  = genericUtility.getColumnValue( "cust_code_from", headerDom );
			System.out.println("cust_code_fr="+custCodeFr);
			//writeLog(filePtr,"custCodeFr :::."+custCodeFr,true);

			custCodeTo  = genericUtility.getColumnValue( "cust_code_to", headerDom );
			System.out.println("cust_code_to="+custCodeTo);
			//writeLog(filePtr,"custCodeTo :::."+custCodeTo,true);

			procesDate = genericUtility.getColumnValue("process_date", headerDom );
			System.out.println("process_date="+procesDate);
			//writeLog(filePtr,"procesDate :::."+procesDate,true);

			reasCode  = genericUtility.getColumnValue( "reas_code", headerDom );
			System.out.println("reas_code="+reasCode);
			//writeLog(filePtr,"reasCode :::."+reasCode,true);

			crMap.put("cust_code_fr", custCodeFr);
			crMap.put("cust_code_to", custCodeTo);
			crMap.put("process_date", procesDate);
			crMap.put("reas_code", reasCode);

			parentNodeList = detailDom.getElementsByTagName("Detail2");
			parentNodeListLength = parentNodeList.getLength();			
			for(int ctr = 0; ctr < parentNodeListLength ; ctr++ )
			{
				System.out.println("TEST LENGTH="+parentNodeListLength);
				//writeLog(filePtr,"reasCode :::."+reasCode,true);
				parentNode = parentNodeList.item(ctr);


				dueDate = genericUtility.getColumnValueFromNode("due_date",detailDom.getElementsByTagName("Detail2").item(ctr));
				//writeLog(filePtr,"dueDate :::::  "+dueDate,true);
				
				refDate = genericUtility.getColumnValueFromNode("ref_date",detailDom.getElementsByTagName("Detail2").item(ctr));
				custRefDate = genericUtility.getColumnValueFromNode("cust_ref_date",detailDom.getElementsByTagName("Detail2").item(ctr));
				//writeLog(filePtr,"refDate :::."+refDate,true);

				refNo = genericUtility.getColumnValueFromNode("ref_no",detailDom.getElementsByTagName("Detail2").item(ctr))==null?"":genericUtility.getColumnValueFromNode("ref_no",detailDom.getElementsByTagName("Detail2").item(ctr));
				System.out.println("refNo="+refNo);
				//writeLog(filePtr,"refNo :::."+refNo,true);

				totAmt = Double.parseDouble(genericUtility.getColumnValueFromNode("tot_amt",detailDom.getElementsByTagName("Detail2").item(ctr))==null?"0":genericUtility.getColumnValueFromNode("tot_amt",detailDom.getElementsByTagName("Detail2").item(ctr)));
				System.out.println("total amt="+totAmt);
				//writeLog(filePtr,"totAmt :::."+totAmt,true);

				//totAmt = Double.parseDouble(genericUtility.getColumnValue( "tot_amt",detailDom.getElementsByTagName("Detail2").item(ctr))==null?"0":genericUtility.getColumnValue( "tot_amt",detailDom ).trim());
				

				adjAmt = Double.parseDouble(genericUtility.getColumnValueFromNode("adj_amt",detailDom.getElementsByTagName("Detail2").item(ctr))==null?"0":genericUtility.getColumnValueFromNode("adj_amt",detailDom.getElementsByTagName("Detail2").item(ctr)));
				//writeLog(filePtr,"adjAmt :::."+adjAmt,true);
				
				//adjAmt = Double.parseDouble(genericUtility.getColumnValue( "adj_amt", detailDom )==null?"0":genericUtility.getColumnValue( "adj_amt", detailDom ).trim());
				System.out.println("adj amt="+adjAmt);

				siteCode = genericUtility.getColumnValueFromNode("site_code",detailDom.getElementsByTagName("Detail2").item(ctr))==null?"":genericUtility.getColumnValueFromNode("site_code",detailDom.getElementsByTagName("Detail2").item(ctr));
				//writeLog(filePtr,"siteCode :::. "+siteCode,true);
				//siteCode = genericUtility.getColumnValue( "site_code", detailDom )==null?"":genericUtility.getColumnValue( "site_code",detailDom ).trim();
				System.out.println("siteCode="+siteCode);

				currCode = genericUtility.getColumnValueFromNode("curr_code",detailDom.getElementsByTagName("Detail2").item(ctr))==null?"":genericUtility.getColumnValueFromNode("curr_code",detailDom.getElementsByTagName("Detail2").item(ctr));
				//currCode = genericUtility.getColumnValue( "curr_code", detailDom )==null?"":genericUtility.getColumnValue( "curr_code", detailDom ).trim();
				System.out.println("currCode="+currCode);
				//writeLog(filePtr,"currCode :::."+currCode,true);

				tranType = genericUtility.getColumnValueFromNode("tran_type",detailDom.getElementsByTagName("Detail2").item(ctr))==null?"":genericUtility.getColumnValueFromNode("tran_type",detailDom.getElementsByTagName("Detail2").item(ctr));
				//tranType = genericUtility.getColumnValue( "tran_type", detailDom )==null?"":genericUtility.getColumnValue( "tran_type",detailDom ).trim();
				System.out.println("tran_type="+tranType);
				//writeLog(filePtr,"tranType :::."+tranType,true);

				tranSer = genericUtility.getColumnValueFromNode("tran_ser",detailDom.getElementsByTagName("Detail2").item(ctr))==null?"":genericUtility.getColumnValueFromNode("tran_ser",detailDom.getElementsByTagName("Detail2").item(ctr));
				//tranSer = genericUtility.getColumnValue( "tran_ser", detailDom )==null?"":genericUtility.getColumnValue( "tran_ser", detailDom ).trim();
				System.out.println("tran_ser="+tranSer);
				//writeLog(filePtr,"tranSer :::."+tranSer,true);

				exchRate = Double.parseDouble(genericUtility.getColumnValueFromNode("exch_rate",detailDom.getElementsByTagName("Detail2").item(ctr))==null?"":genericUtility.getColumnValueFromNode("exch_rate",detailDom.getElementsByTagName("Detail2").item(ctr)));
				//exchRate = Double.parseDouble(genericUtility.getColumnValue( "exch_rate", detailDom )==null?"0":genericUtility.getColumnValue( "exch_rate", detailDom ).trim());
				System.out.println("exch_rate="+exchRate);
				//writeLog(filePtr,"exchRate :::. "+exchRate,true);

				/*	if(genericUtility.getColumnValueFromNode("ref_date",detailDom.getElementsByTagName("Detail2").item(ctr))!= null)
				{

					refDate = simpleDateFormat.parse(genericUtility.getColumnValueFromNode("ref_date",detailDom.getElementsByTagName("Detail2").item(ctr)));

				}

				if(genericUtility.getColumnValueFromNode("cust_ref_date",detailDom.getElementsByTagName("Detail2").item(ctr))!= null)
				{

					custRefDate = simpleDateFormat.parse(genericUtility.getColumnValueFromNode("cust_ref_date",detailDom.getElementsByTagName("Detail2").item(ctr)));

				}*/

				custRefNo = genericUtility.getColumnValueFromNode("cust_ref_no",detailDom.getElementsByTagName("Detail2").item(ctr))==null?"":genericUtility.getColumnValueFromNode("cust_ref_no",detailDom.getElementsByTagName("Detail2").item(ctr));
				//writeLog(filePtr,"custRefNo :::."+custRefNo,true);
				
				finEntity = genericUtility.getColumnValueFromNode("fin_entity",detailDom.getElementsByTagName("Detail2").item(ctr))==null?"":genericUtility.getColumnValueFromNode("fin_entity",detailDom.getElementsByTagName("Detail2").item(ctr));
				//writeLog(filePtr,"finEntity :::."+finEntity,true);
				//custRefDate = simpleDateFormat.parse(Double.parseDouble(genericUtility.getColumnValueFromNode("exch_rate",detailDom.getElementsByTagName("Detail2").item(ctr))==null?"":genericUtility.getColumnValueFromNode("exch_rate",detailDom.getElementsByTagName("Detail2").item(ctr)));
				/*

				if(genericUtility.getColumnValue( "ref_date", detailDom )!= null)
				{
				refDate = simpleDateFormat.parse(genericUtility.getColumnValue( "ref_date", detailDom ));
				System.out.println("ref_date="+refDate);
				}

				if(genericUtility.getColumnValue( "cust_ref_date", detailDom )!= null)
				{
				custRefDate = simpleDateFormat.parse(genericUtility.getColumnValue( "cust_ref_date", detailDom ));
				System.out.println("cust_ref_date="+custRefDate);
				}

				custRefNo = genericUtility.getColumnValue( "cust_ref_no", detailDom )==null?"":genericUtility.getColumnValue( "cust_ref_no", detailDom ).trim();
				System.out.println("cust_ref_no="+custRefNo);

				finEntity = genericUtility.getColumnValue( "fin_entity", detailDom )==null?"":genericUtility.getColumnValue( "fin_entity", detailDom ).trim();
				System.out.println("fin_entity="+finEntity);
				 */





				diff = totAmt - adjAmt;
				//writeLog(filePtr,"diff :::."+diff,true);
				
				
				crMap.put("due_date", dueDate);
				crMap.put("ref_no", refNo);
				crMap.put("curr_code", currCode);
				crMap.put("tran_type", tranType);
				crMap.put("tran_ser", tranSer);
				crMap.put("diff", diff);
				crMap.put("exch_rate", exchRate);
				crMap.put("ref_date", refDate);
				crMap.put("cust_ref_date", custRefDate);
				crMap.put("cust_ref_no", custRefNo);
				crMap.put("fin_entity", finEntity);
				crMap.put("site_code", siteCode);





				tranIdArray = new ArrayList();
				retMap = new HashMap();
				
				if(diff > 0)
				{
					System.out.println("called CREDIT note for customer form ....");		
					crMap.put("cust_code_fr", custCodeFr);
					crMap.put("cust_code_to", custCodeTo);

					remarks= "Ref No "+refNo+" Dtd. "+refDate+" Transfer To "+ custCodeTo;
					
					writeLog(filePtr,"Ref No "+refNo+" Ref. Date "+refDate+" Transfer To Customer "+ custCodeTo,true);
					//writeLog(filePtr,""+remarks,true);
					writeLog(filePtr,""+"Credit Amt :"+Math.abs(diff),true);
					
					crMap.put("drcr_flag", "C");
					crMap.put("tran_ser", "MDRCRC");
					crMap.put("sundry_type", "C");
					crMap.put("remarks", remarks);

					retMap = drcrNote(crMap, xtraParams, conn);
					
					if(retMap.containsKey("TRAN_ID"))
					{

						tranId = (String)retMap.get("TRAN_ID");
						writeLog(filePtr,""+"Credit Note Generated :"+tranId,true);
						tranIdArray.add(tranId);						
						System.out.println("TRAN ID GENRATE FOR custCodeFr CREDIT  "+tranId);
					}
					else if(retMap.containsKey("ERR_STRING"))
					{
						System.out.println(" ERROR IN custCodeFr CREDIT");
						errString = itmDBAccessEJB.getErrorString("","VTPROUNSU2","","",conn);
						return errString;
					}

					
					System.out.println("called DEBIT note for customer To ....");
					//writeLog(filePtr,"called DEBIT note for customer To ....",true);
					
					crMap.put("cust_code_fr", custCodeTo);
					crMap.put("cust_code_to", custCodeFr);

					crMap.put("drcr_flag", "D");
					crMap.put("tran_ser", "MDRCRD");
					crMap.put("sundry_type", "C");

					remarks= "Ref No "+refNo+" Dtd  "+refDate+" Transfer from "+ custCodeFr;
					crMap.put("remarks", remarks);
					
					writeLog(filePtr,"Ref No "+refNo+" Ref. Date "+refDate+" Transfer From Customer "+ custCodeFr,true);
					//writeLog(filePtr,""+remarks,true);
					writeLog(filePtr,""+"Debit Amt :"+Math.abs(diff),true);

					retMap = drcrNote(crMap, xtraParams, conn);
					if(retMap.containsKey("TRAN_ID"))
					{
						tranId = (String)retMap.get("TRAN_ID");
						writeLog(filePtr,""+"Debit Note Generated :"+tranId,true);
						tranIdArray.add(tranId);
						System.out.println("TRAN ID GENRATE FOR custCodeTo DEBIT  "+tranId);
					}
					else if(retMap.containsKey("ERR_STRING"))
					{
						System.out.println(" ERROR IN custCodeTo DEBIT ");
						errString = itmDBAccessEJB.getErrorString("","VTPROUNSU2","","",conn);
						return errString;
					}
					confMap.put(refNo, tranIdArray);
				}
				else
				{
					System.out.println("called dr note....");
					//writeLog(filePtr,"called CREDIT note for customer To ....",true);
					
					crMap.put("cust_code_fr", custCodeTo);
					crMap.put("cust_code_to", custCodeFr);
					crMap.put("drcr_flag", "C");
					crMap.put("tran_ser", "MDRCRC");
					crMap.put("sundry_type", "C");
					crMap.put("diff", Math.abs(diff));
					remarks= "Ref No "+refNo+" Dtd  "+refDate+" Transfer from "+ custCodeFr;

					crMap.put("remarks", remarks);
					
					writeLog(filePtr,"Ref No "+refNo+" Ref. Date "+refDate+" Transfer From Customer "+ custCodeFr,true);
					//writeLog(filePtr,""+remarks,true);
					writeLog(filePtr,""+"Credit Amt :"+Math.abs(diff),true);

					retMap = drcrNote(crMap, xtraParams, conn);
					if(retMap.containsKey("TRAN_ID"))
					{
						tranId = (String)retMap.get("TRAN_ID");
						writeLog(filePtr,""+"Credit Note Generated :"+tranId,true);
						tranIdArray.add(tranId);
						System.out.println("TRAN ID GENRATE FOR custCodeTo CREDIT  "+tranId);
					}
					else if(retMap.containsKey("ERR_STRING"))
					{
						System.out.println("ERROR IN  custCodeTo CREDIT  "+tranId);
						errString = itmDBAccessEJB.getErrorString("","VTPROUNSU2","","",conn);
						return errString;
					}

					
					//writeLog(filePtr,"called DEBIT note for customer From ....",true);
					
					crMap.put("cust_code_fr", custCodeFr);
					crMap.put("cust_code_to", custCodeTo);
					crMap.put("drcr_flag", "D");
					crMap.put("tran_ser", "MDRCRD");
					crMap.put("sundry_type", "C");
					crMap.put("diff", Math.abs(diff));
					remarks= "Ref No "+refNo+" Dtd  "+refDate+" Transfer To "+ custCodeTo;
					crMap.put("remarks", remarks);
					
					writeLog(filePtr,"Ref No "+refNo+" Ref. Date "+refDate+" Transfer To Customer "+ custCodeTo,true);
					//writeLog(filePtr,""+remarks,true);
					writeLog(filePtr,""+"Debit Amt :"+Math.abs(diff),true);
					

					retMap = drcrNote(crMap, xtraParams, conn);
					if(retMap.containsKey("TRAN_ID"))
					{
						tranId = (String)retMap.get("TRAN_ID");
						writeLog(filePtr,""+"Debit Note Generated :"+tranId,true);
						tranIdArray.add(tranId);
						System.out.println(" TRAN ID GENRATE FOR custCodeFr DEBIT ");
					}
					else if(retMap.containsKey("ERR_STRING"))
					{
						System.out.println(" ERROR IN custCodeFr DEBIT ");
						errString = itmDBAccessEJB.getErrorString("","VTPROUNSU2","","",conn);
						return errString;

					}
					confMap.put(refNo, tranIdArray);
				}
			}
			//for conf
			System.out.println("confMap------------------->"+confMap);
			
			//writeLog(filePtr," Calling confirm ...... "+confMap,true);
			
				Set tranSet =confMap.keySet();
				Iterator itr=tranSet.iterator();
				System.out.println("tranSet.size()--"+tranSet.size());
             
				while(itr.hasNext())
				{
					tranIdArray = (ArrayList)confMap.get((String) itr.next());
					System.out.println("Printing Key--"+tranIdArray);
					
					
					
					
					tranId = (String)tranIdArray.get(0);
					System.out.println("Printing Key 0--"+tranId);
					//writeLog(filePtr,"ref no  CREDIT note , tran id is ::: "+tranId,true);
					
					errString=confirmReceipt("misc_drcr_rcp_cr",tranId,xtraParams,conn);
					if(!(errString.indexOf("VTSUCC1") > -1)&&((errString.indexOf("VTMCONF20")< 1)))// replacing this VTSUCC1 to VTMCONF20
					{
						//writeLog(filePtr,"Confirm Unsucesses full rollbacking ",true);
						System.out.println("@@@@@@@@@@@@@Confirm Unsucesses full rollbacking");
						conn.rollback();
						return errString;
					}
					else{
						//writeLog(filePtr,"Confirm CR sucesses full ",true);
						writeLog(filePtr,"Credit Note is "+tranId+" Confirm sucessesfully",true);
						
						System.out.println("@@@@@@@@@@@@@Confirm CR sucesses full ");
						//conn.rollback();
						errString = "";
					}
					System.out.println("Confirming receipt here for credit "+errString);
					tranId = (String)tranIdArray.get(1);
					System.out.println("Printing Key-- 1"+tranId);
					//writeLog(filePtr,"call confirm to DEBIT note , tran id is ::: "+tranId,true);
					
					errString=confirmReceipt("misc_drcr_rcp_dr",tranId,xtraParams,conn);
					System.out.println("Confirming receipt here for debit "+errString);
					if(!(errString.indexOf("VTSUCC1") > -1)&&((errString.indexOf("VTMCONF20")< 1)))// replacing this VTSUCC1 to VTMCONF20
					{
						//writeLog(filePtr,"Confirm Unsucesses full rollbacking ",true);
						System.out.println("@@@@@@@@@@@@@Confirm Unsucesses full rollbacking");
						conn.rollback();
						return errString;
					}
					else{
						writeLog(filePtr,"Debit Note is "+tranId+" Confirm sucessesfully",true);
						//writeLog(filePtr,"Confirm sucesses full ",true);
						System.out.println("@@@@@@@@@@@@@Confirm sucesses full ");
						//conn.rollback();
						errString = "";
					}
				}
		

		}
		catch(Exception e)
		{
			writeLog(filePtr,"Problem in Process "+sql,true);
			System.out.println("Exception in InvInsurancePrcEJB..."+e.getMessage());
			e.printStackTrace();
			errString = e.getMessage();

		}
		finally
		{
			try
			{		
				if(errString.trim().length() > 0)
				{
					//writeLog(filePtr,"Problem in Process   "+sql,true);
					conn.rollback();
					System.out.println(" Rollback connection.............");
					errString = itmDBAccessEJB.getErrorString("","VTPROUNSU2","");
				}
				else
				{
					writeLog(filePtr," Process complete sucessesfully   "+sql,true);
					conn.commit();
					writeLog(filePtr,"-------------------------------------------"+sql,true);
					System.out.println("commiting connection.............");
					errString = itmDBAccessEJB.getErrorString("","VTCONF","");
				}
				if (pstmt != null)
				{
					pstmt.close();
				}
				if(conn != null)
				{
					conn.close();
					conn = null;
				}	
			}
			catch(Exception e)
			{
				//writeLog(filePtr,"Problem in Process "+sql,true);
				System.out.println("Error In closing connection::==> "+e);
				e.printStackTrace();
			}
		}
		System.out.println("returning from  InvInsurancePrcEJB   "+errString);
		return (errString);


	}

	HashMap drcrNote(HashMap map,String xtraParams ,Connection conn) throws ITMException
	{
		
		
	//	//writeLog(filePtr,"calling DR CR  :::.",true);
		////writeLog(filePtr,"Generating  Receipt............... ",true);
		//writeLog(filePtr,"xtraParams :::."+xtraParams,true);
		////writeLog(filePtr,"xmlString :::."+xmlString2,true);
		
		
		
		String errString = "",currCode = "",sql = "",drcrFlag = "",tranSer = "" ,remarks = "";
		String tranType = "",siteCode = "",tranId = "",finEntity = "",custCodeFr = "", custCodeTo = "" ;
		String generatedTranId = "",sundryCode = "",acctCodeAr = "",cctrCodeAr = "",cctrCodeD = "";
		String userId = "",chgTerm = "",stdExrt = "",procesDate ="",custRefNo = "",acctCodeD = "",reasCode = "",refNo = "";
		double exchRate = 0 , diff = 0; 
		int val = 0;
		HashMap retmap = new HashMap();


		java.util.Date tempDate = null;
		//java.sql.Date today = null;
		String custRefDate = "",refDate = "" , dueDate ="";
		Timestamp dueDate1 =null;
		//Date procesDate = null;
		PreparedStatement pstmt = null;
		ResultSet rs= null;
		GenericUtility genericUtility = null;
		FinCommon finCommon = new FinCommon();
		SimpleDateFormat  simpleDateFormat=null;
		String objName="";
		try 
		{
			//writeLog(filePtr," debitNote called........... ",true);
			
			System.out.println("debitNote called........... ");
			ITMDBAccessEJB itmDBAccess = new ITMDBAccessEJB();
			genericUtility = GenericUtility.getInstance();
			userId = genericUtility.getValueFromXTRA_PARAMS(xtraParams,"loginCode");
			chgTerm = genericUtility.getValueFromXTRA_PARAMS( xtraParams, "chgTerm" );
			
			System.out.println("map = "+map);
			if(map == null)
			{
				errString = itmDBAccess.getErrorString("","VTIMP","","",conn);
				retmap.put("ERR_STRING", errString);
				return retmap;
			}
			dueDate = (String)map.get("due_date");
			refNo = (String)map.get("ref_no");
			finEntity = (String)map.get("fin_entity");
			siteCode = (String)map.get("site_code");
			custCodeFr = (String)map.get("cust_code_fr");
			custCodeTo = (String)map.get("cust_code_to");
			diff = (Double)map.get("diff");
			exchRate = (Double)map.get("exch_rate");
			currCode = (String)map.get("curr_code");
			tranType = (String)map.get("tran_type");
			procesDate = (String)map.get("process_date");
			refDate = (String)map.get("ref_date");
			custRefNo = (String)map.get("cust_ref_no");
			custRefDate = (String)map.get("cust_ref_date");
			drcrFlag = (String)map.get("drcr_flag");
			tranSer = (String)map.get("tran_ser");
			reasCode = (String)map.get("reas_code");
			remarks = (String)map.get("remarks");

			//writeLog(filePtr,"dueDate :::: "+dueDate,true);
			//writeLog(filePtr,"refNo :::: "+refNo,true);
			//writeLog(filePtr,"finEntity :::: "+finEntity,true);
			//writeLog(filePtr,"custCodeFr ::::  "+custCodeFr,true);
			//writeLog(filePtr,"siteCode ::::"+custCodeTo,true);
			//writeLog(filePtr,"diff :::: "+diff,true);
			//writeLog(filePtr,"currCode :::: "+currCode,true);
			//writeLog(filePtr,"tranType ::::  "+tranType,true);
			//writeLog(filePtr,"custRefNo :::: "+custRefNo,true);
			//writeLog(filePtr,"tranSer ::::  "+tranSer,true);
			//writeLog(filePtr,"remarks ::::  "+remarks,true);
			

			/*simpleDateFormat = new SimpleDateFormat(genericUtility.getDBDateFormat());

			tempDate= simpleDateFormat.parse(procesDate);

			Timestamp procesDate1 = Timestamp.valueOf(simpleDateFormat.format(tempDate).toString() + " 00:00:00.0");

			tempDate= simpleDateFormat.parse(custRefDate);
			Timestamp custRefDate1 = Timestamp.valueOf(simpleDateFormat.format(tempDate).toString() + " 00:00:00.0");

			tempDate= simpleDateFormat.parse(dueDate);
			Timestamp dueDate1 = Timestamp.valueOf(simpleDateFormat.format(tempDate).toString() + " 00:00:00.0");

			tempDate= simpleDateFormat.parse(refDate);
			Timestamp refDate1 = Timestamp.valueOf(simpleDateFormat.format(tempDate).toString() + " 00:00:00.0");
			 */


			procesDate=genericUtility.getValidDateString(procesDate, genericUtility.getApplDateFormat(), genericUtility.getDBDateFormat());
			Timestamp procesDate1=java.sql.Timestamp.valueOf(procesDate + " 00:00:00");

			//custRefDate=genericUtility.getValidDateString(custRefDate, genericUtility.getApplDateFormat(), genericUtility.getDBDateFormat());
			//Timestamp custRefDate1=java.sql.Timestamp.valueOf(custRefDate + " 00:00:00");

			refDate=genericUtility.getValidDateString(refDate, genericUtility.getApplDateFormat(), genericUtility.getDBDateFormat());
			Timestamp refDate1=java.sql.Timestamp.valueOf(refDate + " 00:00:00");
           
			if(dueDate == null)
            {
            	procesDate=genericUtility.getValidDateString(procesDate, genericUtility.getApplDateFormat(), genericUtility.getDBDateFormat());
            	 dueDate1=java.sql.Timestamp.valueOf(procesDate + " 00:00:00");
            }
            else
            {
			dueDate=genericUtility.getValidDateString(dueDate, genericUtility.getApplDateFormat(), genericUtility.getDBDateFormat());
			 dueDate1=java.sql.Timestamp.valueOf(refDate + " 00:00:00");
            }



			sql = "select acct_code__ar,cctr_code__ar from customer where cust_code = ? ";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, custCodeFr);
			rs = pstmt.executeQuery();
			if( rs.next())
			{
				acctCodeAr = rs.getString("acct_code__ar")==null?"":rs.getString("acct_code__ar");
				cctrCodeAr = rs.getString("cctr_code__ar")==null?"":rs.getString("cctr_code__ar");
			}
			rs.close();
			rs = null;
			pstmt.close();
			pstmt = null;
			//writeLog(filePtr,"sql  ------> "+sql,true);

			if(tranSer.equalsIgnoreCase("MDRCRC"))
			{
				objName="misc_drcr_rcp_cr";
			}
			else
			{
				objName="misc_drcr_rcp_dr";
			}
			
			//writeLog(filePtr,"calling  generatedTranId ",true);
			generatedTranId=getTranId(siteCode,tranType,xtraParams,conn,objName); 
			//writeLog(filePtr,"generatedTranId "+generatedTranId,true);
			//String sqlDeb = "insert into MISC_DRCR_RCP (TRAN_ID,TRAN_SER,TRAN_DATE,EFF_DATE,FIN_ENTITY,SITE_CODE,SUNDRY_TYPE,SUNDRY_CODE,ACCT_CODE,CCTR_CODE,AMOUNT,CURR_CODE,EXCH_RATE,DRCR_FLAG,CONFIRMED,CHG_USER,CHG_DATE,CHG_TERM,REF_NO__CR ,REMARKS ) values (?,'MDRCRD',?,?,?,?,'C',?,?,?,?,?,?,'D','N',?,?,?,?,?)";
			String sqlDeb = "insert into MISC_DRCR_RCP (TRAN_ID,TRAN_SER,TRAN_DATE,EFF_DATE,DUE_DATE,FIN_ENTITY,SITE_CODE,SUNDRY_TYPE,SUNDRY_CODE,ACCT_CODE,CCTR_CODE,AMOUNT,CURR_CODE,EXCH_RATE,DRCR_FLAG,CONFIRMED,CHG_USER,CHG_DATE,CHG_TERM,REF_NO__CR ,REMARKS,CUST_REF_NO,CUST_REF_DATE,CUST_REF_AMT,AMOUNT__BC,TRAN_TYPE,RND_OFF ,RND_TO) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
			pstmt = conn.prepareStatement(sqlDeb);
			pstmt.setString(1,generatedTranId);
			pstmt.setString(2,tranSer);
			pstmt.setTimestamp(3,procesDate1);
			pstmt.setTimestamp(4,procesDate1);
			pstmt.setTimestamp(5,dueDate1);
			pstmt.setString(6,finEntity);//
			pstmt.setString(7,siteCode);
			pstmt.setString(8,"C");
			pstmt.setString(9,custCodeFr);
			pstmt.setString(10,acctCodeAr);
			pstmt.setString(11,cctrCodeAr);
			pstmt.setDouble(12,diff);
			pstmt.setString(13,currCode);
			pstmt.setDouble(14,exchRate);
			pstmt.setString(15,drcrFlag);//
			pstmt.setString(16,"N");
			pstmt.setString(17,userId);
			pstmt.setTimestamp(18,new java.sql.Timestamp(System.currentTimeMillis()));//isue
			pstmt.setString(19,chgTerm);
			pstmt.setString(20,null);
			pstmt.setString(21,remarks);
			pstmt.setString(22,refNo);
			pstmt.setTimestamp(23,refDate1);
			pstmt.setDouble(24,diff);
			pstmt.setDouble(25,diff*exchRate);
			pstmt.setString(26,tranType);
			pstmt.setString(27,"N");
			pstmt.setDouble(28,0);
			//writeLog(filePtr," insert sql for MISC_DRCR_RCP ------> "+sqlDeb,true);
			val = pstmt.executeUpdate();
			if(val > 0)
			{
				
				
				//writeLog(filePtr,remarks,true);
				//writeLog(filePtr,"Tran Id is "+generatedTranId,true);
				
				
				
				/*			conn.commit() ;
			pstmt.close();
			pstmt = null;*/

				sql = "select udf_str1,udf_str2  from gencodes where fld_name='REAS_CODE'  and mod_name='W_RECEIVABLE_TRN' and fld_value= ?  ";
				pstmt = conn.prepareStatement(sql);
				pstmt.setString(1, reasCode);
				rs = pstmt.executeQuery();
				if( rs.next())
				{
					acctCodeD = rs.getString("udf_str1")==null?"":rs.getString("udf_str1");
					cctrCodeD = rs.getString("udf_str2")==null?"":rs.getString("udf_str2");
				}
				//writeLog(filePtr,"sql  ------> "+sql,true);
				
				rs.close();
				rs = null;
				pstmt.close();
				pstmt = null;

				val =0;
				System.out.println("insertion  done into the misc_drcr_rcp");
				String sqlDeb5="Insert into misc_drcr_rdet(TRAN_ID ,LINE_NO,REAS_CODE,ACCT_CODE,CCTR_CODE,NET_AMT,AMOUNT  )values (?,?,?,?,?,?,?)";
				pstmt = conn.prepareStatement(sqlDeb5);
				pstmt.setString(1,generatedTranId);
				pstmt.setInt(2,1);
				pstmt.setString(3,reasCode);
				pstmt.setString(4,acctCodeD);
				pstmt.setString(5,cctrCodeD);
				pstmt.setDouble(6,diff);
				pstmt.setDouble(7,diff);
				val= pstmt.executeUpdate();
				//writeLog(filePtr,"  insert det sql for misc_drcr_rdet  ------> "+sqlDeb5,true);
				
				if(val > 0)
				{
					retmap.put("TRAN_ID", generatedTranId);
					System.out.println("insert sucessfully ="+generatedTranId);
				}
				else
				{
					System.out.println("errorrrr="+generatedTranId);
					errString = "VTPROUNSU2";
					retmap.put("ERR_STRING", errString);
					//return retmap;
				}
				conn.commit();
			}


		}
		catch (SQLException e) 
		{
			writeLog(filePtr,"Problem to generate CREDIT/DEBIT  ",true);
			try {
				conn.rollback();
			} catch (SQLException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			System.out.println("Exception :debitNote :debitNote :SQLException :==>\n"+e.getMessage());
			e.printStackTrace();
			throw new ITMException(e);
		}catch (Exception e) 
		{
			writeLog(filePtr,"Problem to generate CREDIT/DEBIT  ",true);
			try {
				conn.rollback();
			} catch (SQLException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			System.out.println("Exception :debitNote :debitNote :Exception :==>\n"+e.getMessage());
			e.printStackTrace();
			throw new ITMException(e);
		}
		return  retmap;
	}//debitNote end
	public String getTranId(String siteCode ,String tranType ,String xtraParams,Connection conn,String objname)throws ITMException//
	{

		String tranIdRecp=null;
		String objname1="w_"+objname;
		System.out.println("current site Code --"+siteCode);
		Date CurrDate = null;
		SimpleDateFormat  simpleDateFormat=null;
		//Timestamp timestampcurrDate=null;
		try{
			
			
			//writeLog(filePtr,"getTranId function calling........ ",true);


			simpleDateFormat = new SimpleDateFormat(genericUtility.getApplDateFormat());
			//CurrDate= simpleDateFormat.parse(simpleDateFormat.format(new Date()));
			//timestampcurrDate = Timestamp.valueOf(simpleDateFormat.format(CurrDate).toString() + " 00:00:00.0");

			StringBuffer xmlBuff = new StringBuffer();
			String xmlString = null;
			xmlBuff.append("<?xml version='1.0' encoding='UTF-8'?>\n");//encoding= 'ISO-8859-1' instead UTF-8 added by kiran G on Jan 17 15.00pm
			xmlBuff.append("<DocumentRoot>");
			xmlBuff.append("<description>").append("Datawindow Root").append("</description>");
			xmlBuff.append("<group0>");
			xmlBuff.append("<description>").append("Group0 description").append("</description>");
			xmlBuff.append("<Header0>");
			xmlBuff.append("<objName><![CDATA[").append("objname").append("]]></objName>");
			xmlBuff.append("<pageContext><![CDATA[").append("1").append("]]></pageContext>");
			xmlBuff.append("<objContext><![CDATA[").append("1").append("]]></objContext>");
			xmlBuff.append("<editFlag><![CDATA[").append("A").append("]]></editFlag>");
			xmlBuff.append("<focusedColumn><![CDATA[").append("").append("]]></focusedColumn>");
			xmlBuff.append("<action><![CDATA[").append("SAVE").append("]]></action>");
			xmlBuff.append("<elementName><![CDATA[").append("").append("]]></elementName>");
			xmlBuff.append("<keyValue><![CDATA[").append("1").append("]]></keyValue>");
			xmlBuff.append("<taxKeyValue><![CDATA[").append("	").append("]]></taxKeyValue>");
			xmlBuff.append("<saveLevel><![CDATA[").append("1").append("]]></saveLevel>");
			xmlBuff.append("<forcedSave><![CDATA[").append(true).append("]]></forcedSave>");
			xmlBuff.append("<taxInFocus><![CDATA[").append(false).append("]]></taxInFocus>");
			xmlBuff.append("<description>").append("Header0 members").append("</description>");
			xmlBuff.append("<Detail1 objContext =\"1\"").append(" objName=\"objname\" domID=\"1\" dbID=\"\">");
			xmlBuff.append("<attribute selected=\"N\" updateFlag=\"A\" status=\"N\" pkNames=\"\"/>");
			xmlBuff.append("<tran_id/>");
			xmlBuff.append("<item_ser><![CDATA[").append(" ").append("]]></item_ser>");
			xmlBuff.append("<tran_date><![CDATA[").append(simpleDateFormat.format(new java.util.Date())).append("]]></tran_date>");
			xmlBuff.append("<site_code><![CDATA[").append(siteCode).append("]]></site_code>");
			xmlBuff.append("<tran_type><![CDATA[").append(tranType).append("]]></tran_type>");
			if("misc_drcr_rcp_dr".equalsIgnoreCase(objname))
			{
				xmlBuff.append("<drcr_flag><![CDATA[").append("D").append("]]></drcr_flag>");

			}else
			{
				xmlBuff.append("<drcr_flag><![CDATA[").append("C").append("]]></drcr_flag>");

			}
			xmlBuff.append("</Detail1>");
			xmlBuff.append("</Header0>");
			xmlBuff.append("</group0>");
			xmlBuff.append("</DocumentRoot>");
			//End of Genrating xml for tran_id
			xmlString = xmlBuff.toString();
			System.out.println("xmlstring ==="+xmlString);
			
			tranIdRecp = getUniqueKey(xmlString, xtraParams, objname1, conn);
			System.out.println("I am calling the getUniqueKey.. "+tranIdRecp);
			//writeLog(filePtr,"calling the getUniqueKey........ "+tranIdRecp,true);

		}catch (Exception e) {
			try {
				conn.rollback();
			} catch (SQLException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new ITMException(e);
		} 

		//writeLog(filePtr,"return for getTranId........ "+tranIdRecp,true);
		return tranIdRecp;

	}//end of getTranId

	public String getUniqueKey(String xmlValues,String xtraParams ,String tranWindow,Connection conn)throws ITMException
	{

		System.out.println(" i am  in the getUniqueKey.. ");
		//writeLog(filePtr," IN getUniqueKey........ ",true);
		
		String uniqueKey = null;
		String sql = "";
		java.sql.ResultSet rs = null;
		java.sql.PreparedStatement pstmt = null;
		String keyString = ""; 
		String keyColumn = "";
		String refSeries = "";
		String userId = "";
		GenericUtility genericUtility = GenericUtility.getInstance();
		try
		{
			userId = genericUtility.getValueFromXTRA_PARAMS(xtraParams,"loginEmpCode");

			sql = "select key_string, tran_id_col, ref_ser from transetup where tran_window = ?";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1,tranWindow);
			rs = pstmt.executeQuery();

			if(rs.next())
			{
				keyString = rs.getString("key_String"); 
				keyColumn = rs.getString("tran_id_col");
				refSeries = rs.getString("ref_ser");
			}
			rs.close();
			rs = null;
			pstmt.close();
			pstmt = null;

			try{	
				TransIDGenerator tg = new TransIDGenerator(xmlValues,userId, CommonConstants.DB_NAME);
				uniqueKey = tg.generateTranSeqID(refSeries, keyColumn, keyString, conn);
				System.out.println("uniquekey---"+uniqueKey);
			}catch (ITMException ie)
			{
				conn.rollback();
				ie.printStackTrace(); 	
				throw new ITMException(ie);

			}
			catch(Exception e)
			{
				conn.rollback();
				e.printStackTrace();
				System.out.println("Exception :In CRemittanceConf: getUniqueKey :above---"+e);
				throw new ITMException(e);
			}
			return uniqueKey;
		}
		catch(Exception e)
		{
			try {
				conn.rollback();
			} catch (SQLException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			System.out.println("Exception :In CRemittanceConf: getUniqueKey :==>\n" + e.getMessage());
			e.printStackTrace();
			uniqueKey = null;
			throw new ITMException(e);
		}


	}//end of getUniqueKey


	public String confirmReceipt(String businessObj, String tranIdFr,String xtraParams,Connection conn) throws Exception, ITMException
	{
		String methodName = "";
		String compName = "";
		String retString = "";
		String serviceCode = "";
		String serviceURI = "";
		String actionURI = "";
		String sql = "";
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		System.out.println("confirmReceipt(String businessObj, String tranIdFr,String xtraParams, String forcedFlag, Connection conn) called >>><!@#>");
		System.out.println("Transaction Id for Confirmation--"+tranIdFr);
		System.out.println("businessObj--"+businessObj);
		try
		{
			methodName = "gbf_post";
			actionURI = "http://NvoServiceurl.org/" + methodName;

			sql = "SELECT SERVICE_CODE,COMP_NAME FROM SYSTEM_EVENTS WHERE OBJ_NAME = ? AND EVENT_CODE = 'pre_confirm' ";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1,businessObj);
			rs = pstmt.executeQuery();
			if ( rs.next() )
			{
				serviceCode = rs.getString("SERVICE_CODE");
				compName = rs.getString("COMP_NAME");
			}
			System.out.println("serviceCode = "+serviceCode+" compName "+compName);
			sql = "SELECT SERVICE_URI FROM SYSTEM_EVENT_SERVICES WHERE SERVICE_CODE = ? ";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1,serviceCode);
			rs = pstmt.executeQuery();
			if ( rs.next() )
			{
				serviceURI = rs.getString("SERVICE_URI");
			}
			System.out.println("serviceURI = "+serviceURI+" compName = "+compName);
			Service service = new Service();
			Call call = (Call)service.createCall();
			call.setTargetEndpointAddress(new java.net.URL(serviceURI));
			call.setOperationName( new javax.xml.namespace.QName("http://NvoServiceurl.org", methodName ) );
			call.setUseSOAPAction(true);
			call.setSOAPActionURI(actionURI);
			Object[] aobj = new Object[4];

			call.addParameter( new javax.xml.namespace.QName("http://NvoServiceurl.org", "component_name"), XMLType.XSD_STRING, ParameterMode.IN);
			call.addParameter( new javax.xml.namespace.QName("http://NvoServiceurl.org", "tran_id"), XMLType.XSD_STRING, ParameterMode.IN);
			call.addParameter( new javax.xml.namespace.QName("http://NvoServiceurl.org", "xtra_params"), XMLType.XSD_STRING, ParameterMode.IN);
			call.addParameter( new javax.xml.namespace.QName("http://NvoServiceurl.org", "forced_flag"), XMLType.XSD_STRING, ParameterMode.IN);

			aobj[0] = new String(compName);
			aobj[1] = new String(tranIdFr);
			aobj[2] = new String(xtraParams);
			System.out.println("@@@@@@@@@@loginEmpCode:" +genericUtility.getValueFromXTRA_PARAMS(xtraParams,"loginEmpCode")+":");
			call.setReturnType(XMLType.XSD_STRING);
			retString = (String)call.invoke(aobj);
			System.out.println("Confirm Complete @@@@@@@@@@@Return string from NVO is:==>["+retString+"]");

		}
		catch (Exception e) {
			conn.rollback();
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new ITMException(e);
		} 
		finally
		{
			try
			{
				if (pstmt != null)
				{
					pstmt.close();
					pstmt = null;
				}
				if (rs != null)
				{
					rs.close();
					rs = null;
				}    

			}
			catch (Exception e)					
			{
				conn.rollback();
				e.printStackTrace();
				e.getMessage();
				throw new ITMException(e);
			}
		}
		return retString;
	}//end of confirmReceipt
	private 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();}
	}

}