package ibase.webitm.bean.adm;

import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

import javax.naming.InitialContext;

import ibase.scheduler.utility.interfaces.Schedule;
import ibase.system.config.AppConnectParm;
import ibase.system.config.ConnDriver;
import ibase.utility.CommonConstants;
import ibase.utility.E12GenericUtility;
import ibase.utility.EMail;
import ibase.utility.UserInfoBean;
import ibase.webitm.ejb.MasterStatefulLocal;
import ibase.webitm.utility.ITMException;

/**
 * @author Ahmed Mohammed Ali
 * 
 * @since 20/Jan/2017 
 */

public class EmpSecuritiesScheduler implements Schedule
{	
	@SuppressWarnings("rawtypes")
	@Override
	public String schedule(HashMap arg0) throws Exception 
	{
		return null;
	}

	@Override
	public String schedule(String arg0) throws Exception 
	{
		return this.performOp(arg0);
	}

	@Override
	public String schedulePriority(String arg0) throws Exception 
	{
		return this.performOp(arg0);
	}
	
	/**
	 * To generate transaction and send mail to designated person at start of financial year
	 * 
	 * @return null
	 * @throws ITMException
	 */
	public String performOp(String scheduleParamXML) throws ITMException
	{
		Connection conn = null;
		boolean isError = false;
		String retString = "";
		try
		{
			printLog("STDOUT","EmpSecuritiesScheduler : performOp => Scheduler Started");
			printLog("STDOUT","EmpSecuritiesScheduler : performOp : =>" + scheduleParamXML);
			ConnDriver connDriver = new ConnDriver();
			conn = connDriver.getConnectDB();
			retString = performOp(scheduleParamXML, conn);
		}
		catch(Exception e)
		{
			isError = true;
			e.printStackTrace();
			throw new ITMException(e);
		}
		finally
		{
			try
			{
				if(conn != null)
				{
					if(isError)
					{
						conn.rollback();
					}
					else
					{
						conn.commit();
					}
					conn.close();
					conn = null;
				}
			}
			catch(Exception e)
			{
				e.printStackTrace();
				throw new ITMException(e);
			}
		}
		return retString;
	}
	
	@SuppressWarnings("deprecation")
	private String performOp(String scheduleParamXML, Connection conn) throws ITMException
	{
		String retString = "";
		try
		{
			printLog("STDOUT","EmpSecuritiesScheduler : performOp => Connection Established");
			Date currentDate = new Date();
			printLog("STDOUT","EmpSecuritiesScheduler : performOp : currentDate =>" + currentDate);
			Timestamp currTimestamp = new Timestamp(currentDate.getTime());
			printLog("STDOUT","EmpSecuritiesScheduler : performOp : currTimestamp =>" + currTimestamp);
			currTimestamp.setHours(00);
			currTimestamp.setMinutes(00);
			currTimestamp.setSeconds(00);
			currTimestamp.setNanos(000);
			printLog("STDOUT","EmpSecuritiesScheduler : performOp : currTimestamp1 =>" + currTimestamp);
			HashMap<String, Object> acctPrdMap = null;
			acctPrdMap = getAcctPrdMap(conn);
			printLog("STDOUT","EmpSecuritiesScheduler : performOp : acctPrdMap =>" + acctPrdMap.toString());
			if(acctPrdMap != null)
			{
				int diffDays = compare((Timestamp)acctPrdMap.get("fr_date"), currTimestamp);
				printLog("STDOUT","EmpSecuritiesScheduler : performOp : diffFirstDay =>" + diffDays);
				
				if(diffDays == 0)
				{
					retString = generateTranSendMail(acctPrdMap, scheduleParamXML, "N", "Y", "ANN_DISC_INT_MAIL", 
							currentDate, true, "ANN_DISC_MAIL_FREQ", conn);
				}
				else if(diffDays >= 0)
				{
					retString = generateTranSendMail(acctPrdMap, scheduleParamXML, "Y", "Y", "INIT_DISC_INT_MAIL", 
							currentDate, true, "INIT_DISC_MAIL_FREQ", conn);
				}
				generateTranSendMail(acctPrdMap, scheduleParamXML, "N", "N", "ANN_DISC_REM_MAIL", 
						currentDate, false, "ANN_DISC_MAIL_FREQ", conn);
				generateTranSendMail(acctPrdMap, scheduleParamXML, "Y", "N", "INIT_DISC_REM_MAIL", 
						currentDate, false, "INIT_DISC_MAIL_FREQ", conn);
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
			printLog("STDERR",e);
			throw new ITMException(e);
		}
		return retString;
	}
	
	@SuppressWarnings("deprecation")
	private String generateTranSendMail(HashMap<String, Object> acctPrdMap, String scheduleParamXML, 
			String isEmployeeNew, String toGenerateTran, String formatCode, Date currentDate, boolean toSendMail,
			String varName, Connection conn) throws ITMException
	{
		String retString = "";
		try
		{
			printLog("STDOUT","EmpSecuritiesScheduler : generateTranAndSendMail : acctPrdMap =>" + acctPrdMap.toString());
			printLog("STDOUT","EmpSecuritiesScheduler : generateTranAndSendMail : scheduleParamXML =>" + scheduleParamXML);
			printLog("STDOUT","EmpSecuritiesScheduler : generateTranAndSendMail : isEmployeeNew =>" + isEmployeeNew);
			printLog("STDOUT","EmpSecuritiesScheduler : generateTranAndSendMail : formatCode =>" + formatCode);
			boolean isErrorFound = false;
			ArrayList<String> employeeList = null;
			employeeList = getEmployeeList((String)acctPrdMap.get("code"), isEmployeeNew, toGenerateTran, 
					(Timestamp)acctPrdMap.get("fr_date"), conn);
			printLog("STDOUT","EmpSecuritiesScheduler : generateTranSendMail : employeeList =>" + employeeList.toString());
			String xmlString = "";
			String errString = "";
			AppConnectParm appConnect = new AppConnectParm();
			InitialContext ctx = new InitialContext(appConnect.getProperty());
			MasterStatefulLocal masterStateful = null;
			UserInfoBean userInfo = new UserInfoBean(scheduleParamXML);
			String transInfo = "";
			boolean isMailSent = false;
			String objName = "emp_securities";
			String refSer = "";
			String adminEmpCode1 = "";
			String adminEmpCode2 = "";
			String adminEmpMailId = "";
			int emailIdCount = 0;
			StringBuffer mailIdBuff = null;
			HashMap<String, Object> tranInfoMap = null;
			String intervalOldEmp = "";
			String intervalDays[] = null;
			Timestamp currTimestamp = new Timestamp(currentDate.getTime());
			currTimestamp.setHours(00);
			currTimestamp.setMinutes(00);
			currTimestamp.setSeconds(00);
			currTimestamp.setNanos(000);
			String refID = "";
			int difference = 0;
			int updateCount = 0;
			String reportTo = "";
			String reportToMailID = "";
			String reportToAdminMailID = "";
			String reportToAdmin = "";
			boolean toIncludeReportTo = false;
			boolean toIncludeReportToAdmin = false;
			int number = 0;
			
			if(employeeList != null)
			{
				refSer = getRefSerForObject(objName, conn);
				printLog("STDOUT","EmpSecuritiesScheduler : generateTranSendMail : refSer =>" + refSer);
				for(String empCode : employeeList)
				{
					if("Y".equalsIgnoreCase(toGenerateTran))
					{
						xmlString = generateTranData(empCode, (String)acctPrdMap.get("code"), currentDate, conn);
						printLog("STDOUT","EmpSecuritiesScheduler : generateTranSendMail : xmlString =>" + xmlString);
						masterStateful = (MasterStatefulLocal) ctx.lookup("ibase/MasterStatefulEJB/local");
						errString = masterStateful.processRequest(userInfo, xmlString, true, conn);
						masterStateful = null;
						printLog("STDOUT","EmpSecuritiesScheduler : generateTranSendMail : errString =>" + errString);
						tranInfoMap = getTranInfoMap(empCode, (String)acctPrdMap.get("code"), conn);
						printLog("STDOUT","EmpSecuritiesScheduler : generateTranSendMail : tranInfoMap =>" 
						+ tranInfoMap.toString());
						toSendMail = true;//Modified by Ahmed on 01/FEB/2017[Request ID: A16HSUN008][START]
					}
					else
					{
						intervalOldEmp = getValueFromPayrParm(empCode, varName, conn);
						printLog("STDOUT","EmpSecuritiesScheduler : generateTranSendMail : intervalOldEmp =>" 
								+ intervalOldEmp);
						intervalDays = intervalOldEmp.split(",");
						printLog("STDOUT","EmpSecuritiesScheduler : generateTranSendMail : intervalDays =>" 
								+ intervalDays.toString());
						tranInfoMap = getTranInfoMap(empCode, (String)acctPrdMap.get("code"), conn);
						printLog("STDOUT","EmpSecuritiesScheduler : generateTranSendMail : tranInfoMap =>" 
								+ tranInfoMap.toString());
						if(tranInfoMap != null)
						{
							for(int i = 0; i <= intervalDays.length; i++)
							{
								if(i == ((Integer)tranInfoMap.get("remind_count") + 1) || i == intervalDays.length)
								{
									//Modified by Ahmed on 31/Jan/2017[Req ID: A16HSUN008][START]
									number = i-1;
									break;
									//Modified by Ahmed on 31/Jan/2017[Req ID: A16HSUN008][END]
								}
							}
							difference = daysBetween((Timestamp)tranInfoMap.get("last_remind_date"), currTimestamp);
							printLog("STDOUT","EmpSecuritiesScheduler : generateTranSendMail : difference =>" 
									+ difference);
							printLog("STDOUT","EmpSecuritiesScheduler : generateTranSendMail : intervalDays[i-1] =>" 
									+ intervalDays[number]);
							if(difference >= Integer.parseInt(intervalDays[number]))
							{
								toSendMail = true;
								if((Integer)tranInfoMap.get("remind_count") + 1 == 1)
								{
									toIncludeReportTo = false;
									toIncludeReportToAdmin = false;
								}
								else if((Integer)tranInfoMap.get("remind_count") + 1 == 2)
								{
									toIncludeReportTo = true;
									toIncludeReportToAdmin = false;
								}
								else if((Integer)tranInfoMap.get("remind_count") + 1 >= 3)
								{
									toIncludeReportTo = true;
									toIncludeReportToAdmin = true;
								}
								updateCount = updateRemindDateAndCounter((String)tranInfoMap.get("tran_id"), empCode, 
										(String)acctPrdMap.get("code"), (Integer)tranInfoMap.get("remind_count"), conn);
								printLog("STDOUT","EmpSecuritiesScheduler : generateTranSendMail : updateCount =>" 
										+ updateCount);
								if(updateCount == 0 )
								{
									isErrorFound = true;
								}
								updateCount = 0;
							}
							difference = 0;
							number = 0;
								//}
							//}
						}
					}
					if(toSendMail)
					{
						transInfo = getDomString(empCode, (String)acctPrdMap.get("code"), conn);
						printLog("STDOUT","EmpSecuritiesScheduler : generateTranSendMail : transInfo =>" + transInfo);
						if(tranInfoMap != null)
						{
							refID = (String)tranInfoMap.get("tran_id");
						}
						printLog("STDOUT","EmpSecuritiesScheduler : generateTranSendMail : refId =>" + refID);
						mailIdBuff = new StringBuffer();
						emailIdCount = 0;
						adminEmpMailId = "";
						adminEmpCode1 = getHREmpCode(empCode, "1", conn);
						printLog("STDOUT","EmpSecuritiesScheduler : generateTranSendMail : adminEmpCode1 =>" 
								+ adminEmpCode1);
						if(adminEmpCode1 != null && adminEmpCode1.trim().length() > 0)
						{
							adminEmpMailId = getEmployeeEmailId(adminEmpCode1, conn);
							printLog("STDOUT","EmpSecuritiesScheduler : generateTranSendMail : adminEmpMailId =>" 
									+ adminEmpMailId);
							emailIdCount++;
							mailIdBuff.append(emailIdCount > 1?"," + adminEmpMailId.trim():adminEmpMailId.trim());
						}
						adminEmpMailId = "";
						adminEmpCode2 = getHREmpCode(empCode, "2", conn);
						printLog("STDOUT","EmpSecuritiesScheduler : generateTranSendMail : adminEmpCode2 =>" 
								+ adminEmpCode2);
						if(adminEmpCode2 != null && adminEmpCode2.trim().length() > 0)
						{
							adminEmpMailId = getEmployeeEmailId(adminEmpCode2, conn);
							printLog("STDOUT","EmpSecuritiesScheduler : generateTranSendMail : adminEmpMailId =>" 
									+ adminEmpMailId);
							emailIdCount++;
							mailIdBuff.append(emailIdCount > 1?"," + adminEmpMailId.trim():adminEmpMailId.trim());
						}
						
						if(toIncludeReportTo && !toIncludeReportToAdmin)
						{
							reportTo = getReportToEmpCode(empCode, conn);
							printLog("STDOUT","EmpSecuritiesScheduler : generateTranSendMail : reportTo =>" 
									+ reportTo);
							if(reportTo != null && reportTo.trim().length() > 0)
							{
								reportToMailID = getEmployeeEmailId(reportTo, conn);
								printLog("STDOUT","EmpSecuritiesScheduler : generateTranSendMail : reportToMailID =>" 
										+ reportToMailID);
								emailIdCount++;
								mailIdBuff.append(emailIdCount > 1?"," + reportToMailID.trim():reportToMailID.trim());
							}
						}
						else if(toIncludeReportTo && toIncludeReportToAdmin)
						{
							reportTo = getReportToEmpCode(empCode, conn);
							printLog("STDOUT","EmpSecuritiesScheduler : generateTranSendMail : reportTo =>" 
									+ reportTo);
							if(reportTo != null && reportTo.trim().length() > 0)
							{
								reportToMailID = getEmployeeEmailId(reportTo, conn);
								printLog("STDOUT","EmpSecuritiesScheduler : generateTranSendMail : reportToMailID =>" 
										+ reportToMailID);
								emailIdCount++;
								mailIdBuff.append(emailIdCount > 1?"," + reportToMailID.trim():reportToMailID.trim());
							}
							
							reportToAdmin = getReportToAdminEmpCode(empCode, conn);
							printLog("STDOUT","EmpSecuritiesScheduler : generateTranSendMail : reportToAdmin =>" 
									+ reportToAdmin);
							if(reportToAdmin != null && reportToAdmin.trim().length() > 0)
							{
								reportToAdminMailID = getEmployeeEmailId(reportToAdmin, conn);
								printLog("STDOUT","EmpSecuritiesScheduler : generateTranSendMail : reportToAdminMailID =>" 
										+ reportToAdminMailID);
								emailIdCount++;
								mailIdBuff.append(emailIdCount > 1?"," + reportToAdminMailID.trim():reportToAdminMailID.trim());
							}
						}
						emailIdCount = 0;
						printLog("STDOUT","EmpSecuritiesScheduler : generateTranSendMail : mailIdBuff =>" 
								+ mailIdBuff.toString());
						try
						{
							isMailSent = sendMail(transInfo, refSer, refID, formatCode, empCode, "", "", mailIdBuff.toString());
						}
						catch(Exception e)
						{
							e.printStackTrace();
						}
						printLog("STDOUT","EmpSecuritiesScheduler : generateTranSendMail : isMailSent =>" + isMailSent);
						mailIdBuff = null;
						if(!isMailSent)
						{
							isErrorFound = true;
							printLog("STDOUT","EmpSecuritiesScheduler : generateTranSendMail : isErrorFound =>" + isErrorFound);
						}
						isMailSent = false;
						isErrorFound = false;
						toSendMail = false;
						refID = "";
						transInfo = "";
						reportTo = "";
						reportToMailID = "";
						reportToAdminMailID = "";
						reportToAdmin = "";
					}
					tranInfoMap = null;
					toIncludeReportTo = false;
					toIncludeReportToAdmin = false;
				}
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
			printLog("STDERR",e);
			throw new ITMException(e);
		}
		return retString;
	}

	private HashMap<String, Object> getAcctPrdMap(Connection conn) throws ITMException 
	{
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		HashMap<String, Object> acctPrdMap = null;
		try
		{
			Timestamp fromDate = null;
			String acctPrd = "";
			acctPrdMap = new HashMap<String, Object>();
			String sql = "SELECT CODE, FR_DATE FROM ACCTPRD WHERE ? BETWEEN FR_DATE AND TO_DATE";
			pstmt = conn.prepareStatement(sql);
			pstmt.setTimestamp(1, new Timestamp(System.currentTimeMillis()));
			printLog("STDOUT","PreparedStatement =>" + generateActualSql(sql, new Timestamp(System.currentTimeMillis())));
			rs = pstmt.executeQuery();
			if(rs.next())
			{
				acctPrd = rs.getString("CODE");
				fromDate = rs.getTimestamp("FR_DATE");
			}
			if(rs != null)
			{
				rs.close();
				rs = null;
			}
			if(pstmt != null)
			{
				pstmt.close(); 
				pstmt =null;
			}
			printLog("STDOUT","EmpSecuritiesScheduler : getAcctPrdMap : acctPrd =>" + acctPrd);
			printLog("STDOUT","EmpSecuritiesScheduler : getAcctPrdMap : fromDate =>" + fromDate);
			acctPrdMap.put("code", acctPrd);
			acctPrdMap.put("fr_date", fromDate);
			printLog("STDOUT","EmpSecuritiesScheduler : getAcctPrdMap : acctPrdMap =>" + acctPrdMap.toString());
		}
		catch(Exception e)
		{
			e.printStackTrace();
			printLog("STDERR",e);
			throw new ITMException(e);
		}
		finally
		{
			try
			{
				if(rs != null)
				{
					rs.close();
					rs = null;
				}
				if(pstmt != null)
				{
					pstmt.close(); 
					pstmt =null;
				}
			}
			catch(SQLException sqle)
			{
				printLog("STDERR",sqle);
				sqle.printStackTrace();
			}
		}
		return acctPrdMap;
	}
	
	private int compare(Timestamp t1, Timestamp t2) throws ITMException 
	{
		int retCount = 0;
		try
		{			
		    long l1 = t1.getTime();
		    long l2 = t2.getTime();
		    printLog("STDOUT","EmpSecuritiesScheduler : compare : l1 =>" + l1);
		    printLog("STDOUT","EmpSecuritiesScheduler : compare : l2 =>" + l2);
		    if (l2 > l1)
		    {
		    	retCount = 1;
		    }
		    else if (l1 > l2)
		    {
		    	retCount = -1;
		    }
		    else
		    {
		    	retCount = 0;
		    }
		    printLog("STDOUT","EmpSecuritiesScheduler : compare : retCount =>" + retCount);
		}
		catch(Exception e)
		{
			e.printStackTrace();
			printLog("STDERR",e);
			throw new ITMException(e);
		}
		return retCount;
	}
	
	 public int daysBetween(Timestamp t1, Timestamp t2) throws ITMException
	 {
		 int retCount = 0;
			try
			{			
			    long l1 = t1.getTime();
			    long l2 = t2.getTime();
			    printLog("STDOUT","EmpSecuritiesScheduler : compare : l1 =>" + l1);
			    printLog("STDOUT","EmpSecuritiesScheduler : compare : l2 =>" + l2);
			    long difference = (l2 - l1) / (1000 * 60 * 60 * 24);
			    
			    retCount = (int) difference;
			    printLog("STDOUT","EmpSecuritiesScheduler : compare : retCount =>" + retCount);
			}
			catch(Exception e)
			{
				e.printStackTrace();
				printLog("STDERR",e);
				throw new ITMException(e);
			}
			return retCount;
	 }
	
	private ArrayList<String> getEmployeeList(String acctPrd, String isEmployeeNew, String toGenerateTran, 
			Timestamp frDate, Connection conn) throws ITMException
	{
		ArrayList<String> employeeList = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		PreparedStatement pstmt1 = null;
		ResultSet rs1 = null;
		try
		{
			printLog("STDOUT","EmpSecuritiesScheduler : getEmployeeList : acctPrd =>" + acctPrd);
			printLog("STDOUT","EmpSecuritiesScheduler : getEmployeeList : isEmployeeNew =>" + isEmployeeNew);
			employeeList = new ArrayList<String>();
			int rowCount = 0;
			String sql = "";
			if("Y".equalsIgnoreCase(isEmployeeNew))
			{
				sql = "SELECT EMP_CODE FROM EMPLOYEE WHERE INSIDER_TRADING_OPT = 'Y' AND RELIEVE_DATE IS NULL AND DATE_JOIN >= ?";
			}
			else
			{
				sql = "SELECT EMP_CODE FROM EMPLOYEE WHERE INSIDER_TRADING_OPT = 'Y' AND RELIEVE_DATE IS NULL AND DATE_JOIN < ?";
			}
			pstmt = conn.prepareStatement(sql);
			pstmt.setTimestamp(1, frDate);
			printLog("STDOUT","PreparedStatement =>" + generateActualSql(sql, frDate));
			rs = pstmt.executeQuery();
			while(rs.next())
			{
				printLog("STDOUT","EmpSecuritiesScheduler : getEmployeeList : EMP_CODE =>" + checkNull(rs.getString("EMP_CODE")));
				rowCount = 0;
				sql = "";
				sql = "SELECT COUNT(1) AS ROW_COUNT FROM EMP_SECURITIES_HDR WHERE EMP_CODE = ? AND ACCT_PRD = ? AND STATUS = 'O'";
				pstmt1 = conn.prepareStatement(sql);
				pstmt1.setString(1, checkNull(rs.getString("EMP_CODE")));
				pstmt1.setString(2, acctPrd);
				printLog("STDOUT","PreparedStatement =>" + generateActualSql(sql, checkNull(rs.getString("EMP_CODE")), acctPrd));
				rs1 = pstmt1.executeQuery();
				if(rs1.next())
				{
					rowCount = rs1.getInt("ROW_COUNT");
				}
				if(rs1 != null)
				{
					rs1.close();
					rs1 = null;
				}
				if(pstmt1 != null)
				{
					pstmt1.close(); 
					pstmt1 =null;
				}
				printLog("STDOUT","EmpSecuritiesScheduler : getEmployeeList : rowCount =>" + rowCount);
				if(rowCount > 0 && "N".equalsIgnoreCase(toGenerateTran) 
						&& ("Y".equalsIgnoreCase(isEmployeeNew) || "N".equalsIgnoreCase(isEmployeeNew)))
				{
					employeeList.add(checkNull(rs.getString("EMP_CODE")));
					//continue;
				}
				else if(rowCount == 0 && "Y".equalsIgnoreCase(toGenerateTran))
				{
					employeeList.add(checkNull(rs.getString("EMP_CODE")));
				}
			}
			if(rs != null)
			{
				rs.close();
				rs = null;
			}
			if(pstmt != null)
			{
				pstmt.close(); 
				pstmt =null;
			}
			printLog("STDOUT","EmpSecuritiesScheduler : getEmployeeList : employeeList =>" + employeeList.toString());
		}
		catch(Exception e)
		{
			e.printStackTrace();
			printLog("STDERR",e);
			throw new ITMException(e);
		}
		finally
		{
			try
			{
				if(rs1 != null)
				{
					rs1.close();
					rs1 = null;
				}
				if(pstmt1 != null)
				{
					pstmt1.close(); 
					pstmt1 =null;
				}
				if(rs != null)
				{
					rs.close();
					rs = null;
				}
				if(pstmt != null)
				{
					pstmt.close(); 
					pstmt =null;
				}
			}
			catch(SQLException sqle)
			{
				sqle.printStackTrace();
				printLog("STDERR",sqle);
				throw new ITMException(sqle);
			}
		}
		return employeeList;
	}
	
	private String generateTranData(String empCode, String acctPrd, Date currentDate, Connection conn) throws ITMException
	{
		String xmlString = "";
		try
		{
			printLog("STDOUT","EmpSecuritiesScheduler : getTranData : empCode =>" + empCode);
			printLog("STDOUT","EmpSecuritiesScheduler : getTranData : acctPrd =>" + acctPrd);
			E12GenericUtility genericUtility = new E12GenericUtility();
			
			SimpleDateFormat sdf = new SimpleDateFormat(genericUtility.getApplDateFormat());
			
			String tranDate = sdf.format(currentDate);
			String lastRemindDate = sdf.format(currentDate);
			String statusDate = sdf.format(currentDate);
			String status = "O";
			
			int remindCount = 0;
			
			printLog("STDOUT","EmpSecuritiesScheduler : getTranData : tranDate =>" + tranDate);
			printLog("STDOUT","EmpSecuritiesScheduler : getTranData : lastRemindDate =>" + lastRemindDate);
			printLog("STDOUT","EmpSecuritiesScheduler : getTranData : statusDate =>" + statusDate);
			printLog("STDOUT","EmpSecuritiesScheduler : getTranData : status =>" + status);
			printLog("STDOUT","EmpSecuritiesScheduler : getTranData : remindCount =>" + remindCount);
			
			StringBuffer valueXmlString = new StringBuffer();
			valueXmlString.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
			valueXmlString.append("<DocumentRoot>");
			valueXmlString.append("<description>").append("Datawindow Root").append("</description>");
			valueXmlString.append("<group0>");
			valueXmlString.append("<description>").append("Group0description").append("</description>");
			valueXmlString.append("<Header0>");
			valueXmlString.append("<objName><![CDATA[").append("emp_securities").append("]]></objName>");
			valueXmlString.append("<pageContext><![CDATA[").append("1").append("]]></pageContext>");
			valueXmlString.append("<objContext><![CDATA[").append("1").append("]]></objContext>");
			valueXmlString.append("<editFlag><![CDATA[").append("A").append("]]></editFlag>");
			valueXmlString.append("<focusedColumn><![CDATA[").append("").append("]]></focusedColumn>");
			valueXmlString.append("<action><![CDATA[").append("SAVE").append("]]></action>");
			valueXmlString.append("<elementName><![CDATA[").append("").append("]]></elementName>");
			valueXmlString.append("<keyValue><![CDATA[").append("1").append("]]></keyValue>");
			valueXmlString.append("<taxKeyValue><![CDATA[").append("").append("]]></taxKeyValue>");
			valueXmlString.append("<saveLevel><![CDATA[").append("1").append("]]></saveLevel>");
			valueXmlString.append("<forcedSave><![CDATA[").append("true").append("]]></forcedSave>");
			valueXmlString.append("<taxInFocus><![CDATA[").append("false").append("]]></taxInFocus>");
			valueXmlString.append("<description>").append("Header0 members").append("</description>");
			valueXmlString.append("<Detail1 objContext =\"1\"").append(" objName=\"emp_securities\" domID=\"1\"	dbID=\"\">");
			valueXmlString.append("<attribute selected=\"N\" updateFlag=\"A\" status=\"N\" pkNames=\"\"/>");
			valueXmlString.append("<emp_code>").append("<![CDATA[" + empCode + "]]>").append("</emp_code>");
			valueXmlString.append("<acct_prd>").append("<![CDATA[" + acctPrd + "]]>").append("</acct_prd>");
			valueXmlString.append("<tran_date>").append("<![CDATA[" + tranDate + "]]>").append("</tran_date>");
			valueXmlString.append("<last_remind_date>").append("<![CDATA[" + lastRemindDate + "]]>").append("</last_remind_date>");
			valueXmlString.append("<remind_count>").append("<![CDATA[" + remindCount + "]]>").append("</remind_count>");
			valueXmlString.append("<status>").append("<![CDATA[" + status + "]]>").append("</status>");
			valueXmlString.append("<status_date>").append("<![CDATA[" + statusDate + "]]>").append("</status_date>");
			valueXmlString.append("</Detail1>");
			valueXmlString.append("</Header0>");
			valueXmlString.append("</group0>");
			valueXmlString.append("</DocumentRoot>");
			
			xmlString = valueXmlString.toString();
			printLog("STDOUT","EmpSecuritiesScheduler : getTranData : xmlString =>" + xmlString);
		}
		catch(Exception e)
		{
			e.printStackTrace();
			printLog("STDERR",e);
			throw new ITMException(e);
		}
		return xmlString;
	}
	
	private String getDomString(String empCode, String acctPrd, Connection conn) throws ITMException
	{
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String domString = "";
		try
		{
			String tranID = "", status = "", addUser = "", chgUser = "", addTerm = "", chgTerm = "", empName = "";
			int remindCount = 0;
			Timestamp tranDate = null;
			Timestamp lastRemindDate = null;
			Timestamp statusDate = null;
			Timestamp addDate = null;
			Timestamp chgDate = null;
			
			
			String sql = "SELECT TRAN_ID, EMP_CODE, ACCT_PRD, TRAN_DATE, LAST_REMIND_DATE, REMIND_COUNT, " +
					"STATUS, STATUS_DATE, ADD_DATE, ADD_USER, ADD_TERM, CHG_USER, CHG_DATE, CHG_TERM, " +
					"DDF_GET_MASTERS_NAME('EMPLOYEE', EMP_CODE, 'FML') AS EMP_NAME " +
					"FROM EMP_SECURITIES_HDR WHERE EMP_CODE = ? AND ACCT_PRD = ? ";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, empCode);
			pstmt.setString(2, acctPrd);
			printLog("STDOUT","PreparedStatement =>" + generateActualSql(sql, empCode, acctPrd));
			rs = pstmt.executeQuery();
			if(rs.next())
			{
				tranID = checkNull(rs.getString("TRAN_ID"));
				tranDate = rs.getTimestamp("TRAN_DATE");
				lastRemindDate = rs.getTimestamp("LAST_REMIND_DATE");
				remindCount = rs.getInt("REMIND_COUNT");
				statusDate = rs.getTimestamp("STATUS_DATE");
				status = checkNull(rs.getString("STATUS"));
				addDate = rs.getTimestamp("ADD_DATE");
				addUser = checkNull(rs.getString("ADD_USER"));
				addTerm = checkNull(rs.getString("ADD_TERM"));
				chgDate = rs.getTimestamp("CHG_DATE");
				chgUser = checkNull(rs.getString("CHG_USER"));
				chgTerm = checkNull(rs.getString("CHG_TERM"));
				empName = checkNull(rs.getString("EMP_NAME"));
			}
			if(rs != null)
			{
				rs.close();
				rs = null;
			}
			if(pstmt != null)
			{
				pstmt.close(); 
				pstmt =null;
			}
			
			E12GenericUtility genericUtility = new E12GenericUtility();
			SimpleDateFormat sdf = new SimpleDateFormat(genericUtility.getApplDateFormat());
			String tranDateStr = "";
			if(tranDate != null)
			{
				try
				{
					tranDateStr = sdf.format(tranDate);
				}
				catch(Exception e)
				{
					tranDateStr = "";
				}
			}
			
			String lastRemindDateStr = "";
			if(lastRemindDate != null)
			{
				try
				{
					lastRemindDateStr = sdf.format(lastRemindDate);
				}
				catch(Exception e)
				{
					lastRemindDateStr = "";
				}
			}
			
			String statusDateStr = "";
			if(statusDate != null)
			{
				try
				{
					statusDateStr = sdf.format(statusDate);
				}
				catch(Exception e)
				{
					statusDateStr = "";
				}
			}
			
			String chgDateStr = "";
			if(chgDate != null)
			{
				try
				{
					chgDateStr = sdf.format(chgDate);
				}
				catch(Exception e)
				{
					chgDateStr = "";
				}
			}
			
			String addDateStr = "";
			if(addDate != null)
			{
				try
				{
					addDateStr = sdf.format(addDate);
				}
				catch(Exception e)
				{
					addDateStr = "";
				}
			}
			
			StringBuffer xmlBuffer = new StringBuffer();
			xmlBuffer.append("<ROOT>");
			xmlBuffer.append("<Detail1>");
			xmlBuffer.append("<tran_id>").append("<![CDATA[" + tranID + "]]>").append("</tran_id>");
			xmlBuffer.append("<tran_date>").append("<![CDATA[" + tranDateStr + "]]>").append("</tran_date>");
			xmlBuffer.append("<emp_code>").append("<![CDATA[" + empCode + "]]>").append("</emp_code>");
			xmlBuffer.append("<acct_prd>").append("<![CDATA[" + acctPrd + "]]>").append("</acct_prd>");
			xmlBuffer.append("<last_remind_date>").append("<![CDATA[" + lastRemindDateStr + "]]>").append("</last_remind_date>");
			xmlBuffer.append("<remind_count>").append("<![CDATA[" + remindCount + "]]>").append("</remind_count>");
			xmlBuffer.append("<status>").append("<![CDATA[" + status + "]]>").append("</status>");
			xmlBuffer.append("<status_date>").append("<![CDATA[" + statusDateStr + "]]>").append("</status_date>");
			xmlBuffer.append("<emp_name>").append("<![CDATA[" + empName + "]]>").append("</emp_name>");
			xmlBuffer.append("<add_date>").append("<![CDATA[" + addDateStr + "]]>").append("</add_date>");
			xmlBuffer.append("<add_term>").append("<![CDATA[" + addTerm + "]]>").append("</add_term>");
			xmlBuffer.append("<add_user>").append("<![CDATA[" + addUser + "]]>").append("</add_user>");
			xmlBuffer.append("<chg_date>").append("<![CDATA[" + chgDateStr + "]]>").append("</chg_date>");
			xmlBuffer.append("<chg_user>").append("<![CDATA[" + chgUser + "]]>").append("</chg_user>");
			xmlBuffer.append("<chg_term>").append("<![CDATA[" + chgTerm + "]]>").append("</chg_term>");
			xmlBuffer.append("</Detail1>");
			xmlBuffer.append("</ROOT>");
			domString = xmlBuffer.toString();
			printLog("STDOUT","EmpSecuritiesScheduler : getDomString : domString =>" + domString);
		}
		catch(Exception e)
		{
			e.printStackTrace();
			printLog("STDERR",e);
			throw new ITMException(e);
		}
		finally
		{
			try
			{
				if(rs != null)
				{
					rs.close();
					rs = null;
				}
				if(pstmt != null)
				{
					pstmt.close(); 
					pstmt =null;
				}
			}
			catch(SQLException sqle)
			{
				sqle.printStackTrace();
				printLog("STDERR",sqle);
				throw new ITMException(sqle);
			}
		}
		return domString;
	}
	
	private boolean sendMail(String transInfo, String refSer, String refId, String formatCode, 
			String entityCode, String linkAddr, String empCodeMailId, String mailIdCcAdd ) throws ITMException
	{
		boolean isMailSent = false;
	    try
	    {
	    	String retValue = "";
	    	printLog("STDOUT","EmpSecuritiesScheduler : sendMail : transInfo =>" + transInfo);
			printLog("STDOUT","EmpSecuritiesScheduler : sendMail : refSer =>" + refSer);
			printLog("STDOUT","EmpSecuritiesScheduler : sendMail : refId =>" + refId);
			printLog("STDOUT","EmpSecuritiesScheduler : sendMail : formatCode =>" + formatCode);
			printLog("STDOUT","EmpSecuritiesScheduler : sendMail : entityCode =>" + entityCode);
			printLog("STDOUT","EmpSecuritiesScheduler : sendMail : linkAddr =>" + linkAddr);
			printLog("STDOUT","EmpSecuritiesScheduler : sendMail : empCodeMailId =>" + empCodeMailId);
			printLog("STDOUT","EmpSecuritiesScheduler : sendMail : mailIdCcAdd =>" + mailIdCcAdd);
	    	if (formatCode != null)
	    	{
	    		String lineNo = "";
				//String emailType = "link";
	    		String emailType = "";
				linkAddr = linkAddr.trim();
				if(linkAddr.trim().length() > 0)
				{
					emailType = "link";
				}
				else
				{
					emailType = "";
				}
				
				StringBuffer valueXmlString = null;
				valueXmlString = new StringBuffer("<?xml version='1.0' encoding='UTF-8'?><ROOT><TRANS_INFO>");
			    valueXmlString.append("<OBJ_NAME>").append("<![CDATA[emp_securities]]>").append("</OBJ_NAME>");
				valueXmlString.append("<REF_SER>").append("<![CDATA[" + refSer + "]]>").append("</REF_SER>");
				valueXmlString.append("<REF_ID>").append("<![CDATA[" + refId + "]]>").append("</REF_ID>");
				valueXmlString.append("<LINE_NO>").append("<![CDATA[" + lineNo + "]]>").append("</LINE_NO>");
				valueXmlString.append("</TRANS_INFO>");
				
				valueXmlString.append("<MAIL>");
				valueXmlString.append("<EMAIL_TYPE>").append("<![CDATA[" + emailType + "]]>").append("</EMAIL_TYPE>");
				valueXmlString.append("<ENTITY_CODE>").append("<![CDATA[" + entityCode + "]]>").append("</ENTITY_CODE>");
				valueXmlString.append("<ENTITY_TYPE>").append("<![CDATA[E]]>").append("</ENTITY_TYPE>");
				valueXmlString.append("<FORMAT_CODE>").append("<![CDATA[" + formatCode +"]]>").append("</FORMAT_CODE>");
				valueXmlString.append("<TO_ADD>").append("<![CDATA[" + empCodeMailId +"]]>").append("</TO_ADD>");
				valueXmlString.append("<CC_ADD>").append("<![CDATA[" + mailIdCcAdd +"]]>").append("</CC_ADD>");
				if(linkAddr.trim().length() > 0)
				{
					valueXmlString.append("<LINK_ADDR>").append("<![CDATA[" + linkAddr + "]]>").append("</LINK_ADDR>");
				}
				valueXmlString.append("<ATTACHMENT><BODY></BODY><LOCATION></LOCATION></ATTACHMENT>");
				valueXmlString.append("</MAIL>");
				valueXmlString.append("<XML_DATA>").append(transInfo).append("</XML_DATA>");
				valueXmlString.append("</ROOT>");
				String mailDomStr = valueXmlString.toString();
				printLog("STDOUT","EmpSecuritiesScheduler : sendMail : mailDomStr =>" + mailDomStr);
				EMail email = new EMail();
				retValue = email.sendMail(mailDomStr, "ITM");
				if("S".equalsIgnoreCase(retValue))
				{
					printLog("STDOUT","EmpSecuritiesScheduler : sendMail => Mail sent successfully" );
					isMailSent = true;
				}
			}
	    }
	    catch (ITMException itme)
	    {
	    	printLog("STDERR","EmpSecuritiesScheduler : sendMail : ITMException =>" + itme.getMessage());
	    	itme.printStackTrace();
	    	printLog("STDERR",itme);
	    	throw itme;
	    }
	    catch (Exception e)
	    {
	    	printLog("STDOUT","EmpSecuritiesScheduler : sendMail : Exception =>" + e.getMessage());
	    	e.printStackTrace();
	    	printLog("STDERR",e);
	    	throw new ITMException(e);
	    }
		return isMailSent;
	}
	
	private String getRefSerForObject(String objName, Connection conn) throws ITMException 
	{
		String refSer = "";
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		try
		{
			String tranWindow = "w_"+objName;
			String sql = "SELECT REF_SER FROM TRANSETUP WHERE TRAN_WINDOW = ?";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, tranWindow);
			printLog("STDOUT","PreparedStatement =>" + generateActualSql(sql, tranWindow));
			rs = pstmt.executeQuery();
			if(rs.next())
			{
				refSer = checkNull(rs.getString("REF_SER"));
			}
			if(rs != null)
			{
				rs.close();
				rs = null;
			}
			if(pstmt != null)
			{
				pstmt.close(); 
				pstmt =null;
			}
			printLog("STDOUT","EmpSecuritiesScheduler : getRefSerForObject : refSer =>" + refSer);
		}
		catch(Exception e)
		{
			e.printStackTrace();
			printLog("STDERR",e);
	    	throw new ITMException(e);
		}
		finally
		{
			try
			{
				if(rs != null)
				{
					rs.close();
					rs = null;
				}
				if(pstmt != null)
				{
					pstmt.close(); 
					pstmt =null;
				}
			}
			catch(SQLException sqle)
			{
				sqle.printStackTrace();
				printLog("STDERR",sqle);
				throw new ITMException(sqle);
			}
		}
		return refSer;
	}
	
	private HashMap<String, Object> getTranInfoMap(String empCode, String acctPrd, Connection conn) 
			throws ITMException 
	{
		HashMap<String, Object> tranInfoMap = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		try
		{
			tranInfoMap = new HashMap<String, Object>();
			String sql = "SELECT * FROM EMP_SECURITIES_HDR WHERE EMP_CODE = ? AND ACCT_PRD = ?";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, empCode);
			pstmt.setString(2, acctPrd);
			printLog("STDOUT","PreparedStatement =>" + generateActualSql(sql, empCode, acctPrd));
			rs = pstmt.executeQuery();
			if(rs.next())
			{
				tranInfoMap.put("tran_id", checkNull(rs.getString("TRAN_ID")));
				tranInfoMap.put("last_remind_date", rs.getTimestamp("LAST_REMIND_DATE"));
				tranInfoMap.put("remind_count", rs.getInt("REMIND_COUNT"));
			}
			if(rs != null)
			{
				rs.close();
				rs = null;
			}
			if(pstmt != null)
			{
				pstmt.close(); 
				pstmt = null;
			}
			printLog("STDOUT","EmpSecuritiesScheduler : getTranInfoMap : tranInfoMap =>" 
					+ tranInfoMap.toString());
		}
		catch(Exception e)
		{
			e.printStackTrace();
			printLog("STDERR",e);
	    	throw new ITMException(e);
		}
		finally
		{
			try
			{
				if(rs != null)
				{
					rs.close();
					rs = null;
				}
				if(pstmt != null)
				{
					pstmt.close(); 
					pstmt =null;
				}
			}
			catch(SQLException sqle)
			{
				sqle.printStackTrace();
				printLog("STDERR",sqle);
				throw new ITMException(sqle);
			}
		}
		return tranInfoMap;
	}
	
	private String getHREmpCode(String empCode, String adminNo, Connection conn) throws ITMException 
	{
		String adminEmpCode = "";
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		try
		{
			String sql = "SELECT FN_GET_HR_EMP_CODE( ?, 'EMSEC', ?) AS ADMIN_CODE FROM DUAL";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, empCode);
			pstmt.setString(2, adminNo);
			printLog("STDOUT","PreparedStatement =>" + generateActualSql(sql, empCode, adminNo));
			rs = pstmt.executeQuery();
			if(rs.next())
			{
				adminEmpCode = checkNull(rs.getString("ADMIN_CODE"));
			}
			if(rs != null)
			{
				rs.close();
				rs = null;
			}
			if(pstmt != null)
			{
				pstmt.close(); 
				pstmt = null;
			}
			printLog("STDOUT","EmpSecuritiesScheduler : getHREmpCode : adminEmpCode =>" + adminEmpCode);
		}
		catch(Exception e)
		{
			e.printStackTrace();
			printLog("STDERR",e);
	    	throw new ITMException(e);
		}
		finally
		{
			try
			{
				if(rs != null)
				{
					rs.close();
					rs = null;
				}
				if(pstmt != null)
				{
					pstmt.close(); 
					pstmt =null;
				}
			}
			catch(SQLException sqle)
			{
				sqle.printStackTrace();
				printLog("STDERR",sqle);
				throw new ITMException(sqle);
			}
		}
		return adminEmpCode;
	}
	
	private String getEmployeeEmailId(String empCode, Connection conn) throws ITMException 
	{
		String emailIdOff = "";
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		try
		{
			String sql = "SELECT EMAIL_ID_OFF FROM EMPLOYEE WHERE EMP_CODE = ?";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, empCode);
			printLog("STDOUT","PreparedStatement =>" + generateActualSql(sql, empCode));
			rs = pstmt.executeQuery();
			if(rs.next())
			{
				emailIdOff = checkNull(rs.getString("EMAIL_ID_OFF"));
			}
			if(rs != null)
			{
				rs.close();
				rs = null;
			}
			if(pstmt != null)
			{
				pstmt.close(); 
				pstmt = null;
			}
			printLog("STDOUT","EmpSecuritiesScheduler : getEmployeeEmailId : emailIdOff =>" + emailIdOff);
		}
		catch(Exception e)
		{
			e.printStackTrace();
			printLog("STDERR",e);
	    	throw new ITMException(e);
		}
		finally
		{
			try
			{
				if(rs != null)
				{
					rs.close();
					rs = null;
				}
				if(pstmt != null)
				{
					pstmt.close(); 
					pstmt =null;
				}
			}
			catch(SQLException sqle)
			{
				sqle.printStackTrace();
				printLog("STDERR",sqle);
				throw new ITMException(sqle);
			}
		}
		return emailIdOff;
	}
	
	private String getReportToEmpCode(String empCode, Connection conn) throws ITMException 
	{
		String empCodeReportTo = "";
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		try
		{
			String sql = "SELECT REPORT_TO FROM EMPLOYEE WHERE EMP_CODE = ?";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, empCode);
			printLog("STDOUT","PreparedStatement =>" + generateActualSql(sql, empCode));
			rs = pstmt.executeQuery();
			if(rs.next())
			{
				empCodeReportTo = checkNull(rs.getString("REPORT_TO"));
			}
			if(rs != null)
			{
				rs.close();
				rs = null;
			}
			if(pstmt != null)
			{
				pstmt.close(); 
				pstmt = null;
			}
			printLog("STDOUT","EmpSecuritiesScheduler : getReportToEmpCode : empCodeReportTo =>" + empCodeReportTo);
		}
		catch(Exception e)
		{
			e.printStackTrace();
			printLog("STDERR",e);
	    	throw new ITMException(e);
		}
		finally
		{
			try
			{
				if(rs != null)
				{
					rs.close();
					rs = null;
				}
				if(pstmt != null)
				{
					pstmt.close(); 
					pstmt =null;
				}
			}
			catch(SQLException sqle)
			{
				sqle.printStackTrace();
				printLog("STDERR",sqle);
				throw new ITMException(sqle);
			}
		}
		return empCodeReportTo;
	}
	
	private String getReportToAdminEmpCode(String empCode, Connection conn) throws ITMException 
	{
		String empCodeReportToAdmin = "";
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		try
		{
			String sql = "SELECT REPORT_TO__ADMIN FROM EMPLOYEE WHERE EMP_CODE = ?";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, empCode);
			printLog("STDOUT","PreparedStatement =>" + generateActualSql(sql, empCode));
			rs = pstmt.executeQuery();
			if(rs.next())
			{
				empCodeReportToAdmin = checkNull(rs.getString("REPORT_TO__ADMIN"));
			}
			if(rs != null)
			{
				rs.close();
				rs = null;
			}
			if(pstmt != null)
			{
				pstmt.close(); 
				pstmt = null;
			}
			printLog("STDOUT","EmpSecuritiesScheduler : getReportToEmpCode : getReportToAdminEmpCode =>"
			+ empCodeReportToAdmin);
		}
		catch(Exception e)
		{
			e.printStackTrace();
			printLog("STDERR",e);
	    	throw new ITMException(e);
		}
		finally
		{
			try
			{
				if(rs != null)
				{
					rs.close();
					rs = null;
				}
				if(pstmt != null)
				{
					pstmt.close(); 
					pstmt =null;
				}
			}
			catch(SQLException sqle)
			{
				sqle.printStackTrace();
				printLog("STDERR",sqle);
				throw new ITMException(sqle);
			}
		}
		return empCodeReportToAdmin;
	}
	
	private String getValueFromPayrParm(String empCode, String varName, Connection conn) throws ITMException
	{
		String varValue = "";
		String sql = "";
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		try
		{
			printLog("STDOUT","EmpSecuritiesScheduler : getValueFromPayrParm : empCode =>" + empCode);
			printLog("STDOUT","EmpSecuritiesScheduler : getValueFromPayrParm : varName =>" + varName);
			
			sql = "SELECT DDF_HR_SITE_ENV_VALUE(?, ?, ?) AS VAR_VALUE FROM DUAL";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, empCode);
			pstmt.setTimestamp(2, new Timestamp(System.currentTimeMillis()));
			pstmt.setString(3, varName);
			printLog("STDOUT","PreparedStatement =>" + generateActualSql(sql, empCode, 
					new Timestamp(System.currentTimeMillis()), varName));
			rs = pstmt.executeQuery();
			if(rs.next())
			{
				varValue = checkNull(rs.getString("VAR_VALUE"));
			}
			if(rs != null) 
			{
				rs.close();
				rs = null;
			}
			if(pstmt != null) 
			{
				pstmt.close();
				pstmt = null;
			}
			printLog("STDOUT","EmpSecuritiesScheduler : getValueFromPayrParm : varValue =>" + varValue);
		}
		catch (Exception e)
		{
			 e.printStackTrace();
			 printLog("STDERR",e);
			 throw new ITMException(e);
		}
		finally
		{
			try
			{
				if(rs != null) 
				{
					rs.close();
					rs = null;
				}
				if(pstmt != null) 
				{
					pstmt.close();
					pstmt = null;
				}
			}
			catch(Exception d)
			{
				d.printStackTrace();
				printLog("STDERR",d);
				throw new ITMException(d);
			}		
		}
		return varValue;
	}
	
	@SuppressWarnings("deprecation")
	private int updateRemindDateAndCounter(String tranID, String empCode, String acctPrd, int remindCount, 
			Connection conn) throws ITMException
	{
		int updateCount = 0;
		PreparedStatement pstmt = null;
		try
		{
			printLog("STDOUT","EmpSecuritiesScheduler : updateRemindDateAndCounter : tranID =>" 
					+ tranID);
			printLog("STDOUT","EmpSecuritiesScheduler : updateRemindDateAndCounter : empCode =>" 
					+ empCode);
			printLog("STDOUT","EmpSecuritiesScheduler : updateRemindDateAndCounter : acctPrd =>" 
					+ acctPrd);
			printLog("STDOUT","EmpSecuritiesScheduler : updateRemindDateAndCounter : remindCount =>" 
					+ remindCount);
			remindCount = remindCount + 1;
			printLog("STDOUT","EmpSecuritiesScheduler : updateRemindDateAndCounter : remindCount+1 =>" 
					+ remindCount);
			//Modified by Ahmed on 31/Jan/2017[Req ID: A16HSUN008][START]
			Timestamp lastRemindDate = new Timestamp(System.currentTimeMillis());
			lastRemindDate.setHours(00);
			lastRemindDate.setMinutes(00);
			lastRemindDate.setSeconds(00);
			lastRemindDate.setNanos(000);
			printLog("STDOUT","EmpSecuritiesScheduler : updateRemindDateAndCounter : lastRemindDate =>" 
					+ lastRemindDate);
			//Modified by Ahmed on 31/Jan/2017[Req ID: A16HSUN008][END]
			
			String sql = "UPDATE EMP_SECURITIES_HDR SET LAST_REMIND_DATE = ?, REMIND_COUNT = ?" +
					" WHERE TRAN_ID = ? AND EMP_CODE = ? AND ACCT_PRD = ?";
			pstmt = conn.prepareStatement(sql);
			//Modified by Ahmed on 31/Jan/2017[Req ID: A16HSUN008][START]
			//pstmt.setTimestamp(1, new Timestamp(System.currentTimeMillis()));
			pstmt.setTimestamp(1, lastRemindDate);
			//Modified by Ahmed on 31/Jan/2017[Req ID: A16HSUN008][END]
			pstmt.setInt(2, remindCount);
			pstmt.setString(3, tranID);
			pstmt.setString(4, empCode);
			pstmt.setString(5, acctPrd);
			printLog("STDOUT","PreparedStatement =>" + generateActualSql(sql, new Timestamp(System.currentTimeMillis()), 
					remindCount, tranID, empCode, acctPrd));
			updateCount = pstmt.executeUpdate();
			if(pstmt != null)
			{
				pstmt.close(); 
				pstmt = null;
			}
			printLog("STDOUT","EmpSecuritiesScheduler : updateRemindDateAndCounter : updateCount =>" 
					+ updateCount);
		}
		catch(Exception e)
		{
			e.printStackTrace();
			printLog("STDERR",e);
	    	throw new ITMException(e);
		}
		finally
		{
			try
			{
				if(pstmt != null)
				{
					pstmt.close(); 
					pstmt =null;
				}
			}
			catch(SQLException sqle)
			{
				sqle.printStackTrace();
				printLog("STDERR",sqle);
				throw new ITMException(sqle);
			}
		}
		return updateCount;
	}
	
	private String checkNull(String input) 
	{
		if(input == null || "null".equalsIgnoreCase(input))
		{
			input = "";
		}
		else
		{
			input = input.trim();
		}
		return input;
	}
	
	private void printLog(String title, String msg) 
	{
		String logFile = "";
		String logDir = "";
		File logFileDir = null;
		FileWriter fileWriter = null;
		
		try
		{
			String logFileName = "";
			SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
			logFileName = "EmpSecurities_"+sdf.format(new Date());
			
			logDir = CommonConstants.JBOSSHOME + File.separator + "applnlog" + File.separator + "EmpSecurities-To-Track-Exceptions";
			
			logFileDir = new File(logDir);

			if (!logFileDir.exists()) 
			{
				logFileDir.mkdirs();
			}

			logFile = logDir + File.separator + logFileName + ".log";
			
			SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
		    java.util.Date now = new java.util.Date();
		    String strDate = sdfDate.format(now);
			
			fileWriter = new FileWriter(logFile, true);
			
			fileWriter.write("\r\n");
			fileWriter.write(strDate + " " + "INFO" + " " + "["+ title +"] : " + msg);
		} 
		catch (Exception ex) 
		{
			ex.printStackTrace();
			printLog("STDERR", ex);
			printLog("STDOUT","Inside Exception [getLog]>>" + ex.toString());
		} 
		finally 
		{
			try 
			{
				if (fileWriter != null) 
				{
					fileWriter.flush();
					fileWriter.close();
				}
			} 
			catch (Exception e) 
			{
				e.printStackTrace();
				printLog("STDERR", e);
			}
		}
	}
	
	private void printLog(String title, Exception e) 
	{	
		try
		{
			StringWriter strError = new StringWriter();
			e.printStackTrace(new PrintWriter(strError));
			String err = strError.toString();	
			printLog(title, err);
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
			printLog("STDERR","Inside Exception [getLog]>>" + ex.toString());
		}
	}

	/*private void printLog(String title, PreparedStatement pstmt)
	{
		String result = "";
		ResultSet rs = null;
		
		try
		{
			rs = pstmt.executeQuery();
			
			ResultSetMetaData rsmd = rs.getMetaData();
			int numberOfColumns = rsmd.getColumnCount();
			
		    while (rs.next()) 
		    {
		       for (int i = 1; i <= numberOfColumns; i++)
		       {
		    	   result+="<"+rsmd.getColumnName(i)+">";
	               result+=rs.getString(i);
	               result+="</"+rsmd.getColumnName(i)+">\n";				  
		       }
		    }
		    printLog(title, result);
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
			printLog("STDERR", ex);
			printLog("STDERR","Inside Exception [getLog]>>" + ex.toString());
		}
	}*/
	
	private String generateActualSql(String sqlQuery, Object... parameters) 
	{
	    String[] parts = sqlQuery.split("\\?");
	    StringBuilder sb = new StringBuilder();

	    for (int i = 0; i < parts.length; i++) 
	    {
	        String part = parts[i];
	        sb.append(part);
	        if (i < parameters.length) 
	        {
	            sb.append(formatParameter(parameters[i]));
	        }
	    }
	    return sb.toString();
	}

	private String formatParameter(Object parameter) 
	{
	    if (parameter == null) 
	    {
	        return "NULL";
	    } 
	    else 
	    {
	        if (parameter instanceof String) 
	        {
	            return "'" + ((String) parameter).replace("'", "''") + "'";
	        } 
	        else if (parameter instanceof Timestamp) 
	        {
	            return "to_timestamp('" + new SimpleDateFormat("MM/dd/yyyy HH:mm:ss.SSS").
	                    format(parameter) + "', 'mm/dd/yyyy hh24:mi:ss.ff3')";
	        } 
	        else if (parameter instanceof Date) 
	        {
	            return "to_date('" + new SimpleDateFormat("MM/dd/yyyy HH:mm:ss").
	                    format(parameter) + "', 'mm/dd/yyyy hh24:mi:ss')";
	        } 
	        else if (parameter instanceof Boolean) 
	        {
	            return ((Boolean) parameter).booleanValue() ? "1" : "0";
	        } 
	        else 
	        {
	            return parameter.toString();
	        }
	    }
	}
}
