package ibase.webitm.ejb.adm;


import java.rmi.RemoteException;
import java.util.*;
import java.text.*;
import java.sql.*;

import org.w3c.dom.*;
import javax.xml.parsers.*;
import javax.ejb.*;
import ibase.webitm.utility.*;
import ibase.system.config.*;
import ibase.webitm.ejb.*;

import ibase.webitm.utility.GenericUtility;

import ibase.system.config.*;
import java.text.SimpleDateFormat;
import javax.naming.InitialContext;	


import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
/*Created by Chetna on [25/08/2014] For Shift Rotate Change [Start]
 * */

@javax.ejb.Stateless

public class ShiftChangePrc  extends ProcessEJB implements ShiftChangePrcLocal ,ShiftChangePrcRemote 
{
	
	GenericUtility genericUtility = GenericUtility.getInstance();

	public String getData(String xmlString, String xmlString2, String windowName, String xtraParams) throws RemoteException,ITMException
	{  

		String rtrStr = ""; 
		String loginSite = ""; 
		Document headerDom = null;
		Document detailDom = null;
		System.out.println("ShiftChangePrc getData(xmlString,xmlString2,windowName,xtraParams CALLED..."+ xmlString);
		try
		{
			loginSite = genericUtility.getValueFromXTRA_PARAMS(xtraParams, "loginSiteCode");
			System.out.println("loginsitecode.....="+loginSite);
			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 :ShiftChangePrc :getData(String xmlString, String xmlString2, String windowName, String xtraParams):" + e.getMessage() + ":");
			rtrStr = genericUtility.createErrorString(e);
			throw new ITMException(e);
		}
		return rtrStr; 
	}
		
		
	public String getData(Document headerDom, Document detailDom, String windowName, String xtraParams) throws RemoteException,ITMException
	{
		System.out.println("ShiftChangePrc getData(headerDom,detailDom,windowName,xtraParams CALLED..."+ windowName);
		
		String errCode = "";
		String errString = "";
		String siteCode= "" ;
		String sql= "" ;
		String resultString = "";
		String userId ="";
		Connection conn = null;
		ResultSet rs = null;
		ResultSet rs1 = null;
		PreparedStatement pstmt = null;

		StringBuffer retTabSepStrBuff = new StringBuffer("<?xml version=\"1.0\"?>\r\n<DocumentRoot>\r\n<description>Datawindow Root</description>\r\n<group0>\r\n<description>Group0 description</description>\r\n<Header0>\r\n<description>Header0 members</description>\r\n");
			
		boolean bappend = false ;	
		String frstrDate="";
		String tostrDate="";
		String reasCode="";
		String empCode="";
		Date fromDate= null;
		Date toDate= null;

		java.sql.Timestamp jSqlFromDate = null;
		java.sql.Timestamp jSqlToDate = null;

		try
		{
			AppConnectParm appConnect = new AppConnectParm();
			InitialContext ctx = new InitialContext(appConnect.getProperty()) ;
			ITMDBAccessLocal itmDBAccessEJB = (ITMDBAccessLocal)ctx.lookup("ibase/ITMDBAccessEJB/local");		
			
			SimpleDateFormat simpleDateFormat = new SimpleDateFormat(genericUtility.getApplDateFormat());

			ConnDriver connDriver = new ConnDriver();
			conn = connDriver.getConnectDB("DriverITM");			
			siteCode =  checkNull(genericUtility.getColumnValue("site_code",headerDom));
			empCode=    checkNull(genericUtility.getColumnValue("emp_code",headerDom,"1"));
			frstrDate=  checkNull( genericUtility.getColumnValue("from_dt",headerDom,"1"));
			tostrDate=  checkNull( genericUtility.getColumnValue("to_dt",headerDom,"1"));
			System.out.println("Emp CODE "+ empCode+"From Daet "+ frstrDate+"To Date "+ tostrDate);	

			
			jSqlFromDate = java.sql.Timestamp.valueOf(genericUtility.getValidDateTimeString(frstrDate,genericUtility.getApplDateFormat(),genericUtility.getDBDateFormat()));

			jSqlToDate = java.sql.Timestamp.valueOf(genericUtility.getValidDateTimeString(tostrDate,genericUtility.getApplDateFormat(),genericUtility.getDBDateFormat()));

			                                         
			sql =" SELECT WORK_SHIFT.EMP_CODE , "
			  +" WORK_SHIFT.SHIFT ,"
			  +" WORKSHFT.DESCR ,"
			  +" WORK_SHIFT.FROM_DT ,"
			  +" WORK_SHIFT.TO_DT ,"
			  +" EMPLOYEE.EMP_FNAME ,"
			  +" EMPLOYEE.EMP_LNAME ,"
			  +" EMPLOYEE.DEPT_CODE ,"
			  +" EMPLOYEE.EMP_SITE ,"
			  +" WORK_SHIFT.CHG_DATE ,"
			  +" WORK_SHIFT.CHG_USER ,"
			  +" WORK_SHIFT.CHG_TERM ,"
			  +" WORK_SHIFT.REAL_SHIFT ,"
			  +" WORK_SHIFT.PATTERN_CODE  "   
			  +" FROM EMPLOYEE ,"
			  +" WORK_SHIFT ,"
			  +" WORKSHFT  " 
			  +" WHERE  WORK_SHIFT.EMP_CODE = EMPLOYEE.EMP_CODE  AND " 
			  +" WORK_SHIFT.SHIFT = WORKSHFT.SHIFT  "
			  +" AND  WORK_SHIFT.EMP_CODE = ?  " 
			  +" AND  WORK_SHIFT.FROM_DT = ? " 
			  +" AND  WORK_SHIFT.TO_DT = ? " 
			  +" ORDER BY EMPLOYEE.EMP_CODE ASC, "
			  +" WORK_SHIFT.FROM_DT ASC ,"
			  +" WORK_SHIFT.TO_DT   ASC    "; 

			pstmt = conn.prepareStatement(sql);
			System.out.println("After prepareStatement ..." + sql);
			pstmt.setString(1,empCode);
			pstmt.setTimestamp(2,jSqlFromDate);	
			pstmt.setTimestamp(3,jSqlToDate);			

			rs = pstmt.executeQuery();	
			int cnt = 0;
			int i = 0;
			if(rs.next())
			{
								
				frstrDate =  genericUtility.getValidDateString(rs.getString("FROM_DT"), genericUtility.getDBDateFormat(), genericUtility.getApplDateFormat());
				tostrDate   = genericUtility.getValidDateString(rs.getString("TO_DT"), genericUtility.getDBDateFormat(), genericUtility.getApplDateFormat());
						          
				fromDate = simpleDateFormat.parse(frstrDate);
				toDate =   simpleDateFormat.parse(tostrDate);

				//while(fromDate.before(toDate))
				while(fromDate.compareTo(toDate) <= 0)
				{
					retTabSepStrBuff.append("<Detail2 domID='"+i+"' >\r\n");
					retTabSepStrBuff.append("<attribute updateFlag='N' selected='N' />\r\n");
					retTabSepStrBuff.append("<emp_code><![CDATA[").append((rs.getString("EMP_CODE") == null ) ? " ":rs.getString("EMP_CODE")).append("]]></emp_code>\r\n");
					retTabSepStrBuff.append("<shift><![CDATA[").append(rs.getString("SHIFT")==null ? "	":rs.getString("SHIFT")).append("]]></shift>\r\n");
					retTabSepStrBuff.append("<workshft_descr visible='1' protect='1'><![CDATA[").append((rs.getString("DESCR") == null ) ? " ":rs.getString("DESCR")).append("]]></workshft_descr>\r\n");


					retTabSepStrBuff.append("<from_dt><![CDATA[").append((fromDate == null ) ? " ":simpleDateFormat.format(fromDate)).append("]]></from_dt>\r\n");
					retTabSepStrBuff.append("<to_dt><![CDATA[").append((fromDate == null ) ? " ":simpleDateFormat.format(fromDate)).append("]]></to_dt>\r\n");

					retTabSepStrBuff.append("<emp_fname><![CDATA[").append((rs.getString("EMP_FNAME") == null ) ? " ":rs.getString("EMP_FNAME")).append("]]></emp_fname>\r\n");
					retTabSepStrBuff.append("<emp_lname><![CDATA[").append((rs.getString("EMP_LNAME") == null ) ? " ":rs.getString("EMP_LNAME")).append("]]></emp_lname>\r\n");
					retTabSepStrBuff.append("<dept_code><![CDATA[").append((rs.getString("DEPT_CODE") == null ) ? " ":rs.getString("DEPT_CODE")).append("]]></dept_code>\r\n");
					retTabSepStrBuff.append("<emp_site><![CDATA[").append((rs.getString("EMP_SITE") == null ) ? " ":rs.getString("EMP_SITE")).append("]]></emp_site>\r\n");
					retTabSepStrBuff.append("<chg_date><![CDATA[").append((rs.getString("CHG_DATE") == null ) ? " ":genericUtility.getValidDateString(rs.getString("CHG_DATE"),genericUtility.getDBDateFormat(), genericUtility.getApplDateFormat())).append("]]></chg_date>\r\n");
					retTabSepStrBuff.append("<chg_user><![CDATA[").append((rs.getString("CHG_USER") == null ) ? " ":rs.getString("CHG_USER")).append("]]></chg_user>\r\n");
					retTabSepStrBuff.append("<chg_term><![CDATA[").append((rs.getString("CHG_TERM") == null ) ? " ":rs.getString("CHG_TERM")).append("]]></chg_term>\r\n");
					retTabSepStrBuff.append("<real_shift><![CDATA[").append((rs.getString("REAL_SHIFT") == null ) ? " ":rs.getString("REAL_SHIFT")).append("]]></real_shift>\r\n");
					retTabSepStrBuff.append("<pattern_code><![CDATA[").append((rs.getString("PATTERN_CODE") == null ) ? " ":rs.getString("PATTERN_CODE")).append("]]></pattern_code>\r\n");


					retTabSepStrBuff.append("</Detail2>\r\n");   
					
					i++;
					fromDate = addDays(fromDate, 1);
					// increment the day by 1 							
				}
					
				retTabSepStrBuff.append("</Header0>\r\n");
				retTabSepStrBuff.append("</group0>\r\n");	
				retTabSepStrBuff.append("</DocumentRoot>\r\n");
				resultString = retTabSepStrBuff.toString();
				System.out.println("ResultString....." + resultString);
			}
	  		else
			{
				// HERE WHEN WE DOES resultString = "", THEN IT RETURN BLANK TO GET DATA METHOD WHEN WE ARE PUTTIING WRONG TRAN ID THEN IT WILL REFRESS ALL DISPLATY BROW WINDOW INPLACE OF RETURN ERROR MESSAGE. 
				resultString = "";
				System.out.println("Result String when tran id is wrong --->>>>>>" +resultString);
			}
				
			closePstmtRset(pstmt , rs);
			
				
		}
		catch (SQLException e)
		{
			System.out.println("SQLException :ShiftChangePrc :getData(Document headerDom, Document detailDom, String windowName, String xtraParams):" + e.getMessage() + ":");
			throw new ITMException(e);
		}
		catch (Exception e)
		{
			System.out.println("Exception :ShiftChangePrc :getData(Document headerDom, Document detailDom, String windowName, String xtraParams):" + e.getMessage() + ":");
			throw new ITMException(e);
		}
		finally
		{
				
			try
			{
				retTabSepStrBuff = null;
				if(pstmt != null)
				{
					pstmt.close();
					pstmt=null;
				}
				
				if(rs != null)
				{					
					rs.close();
					rs = null;
				
				}
				if(conn != null)
				{					
					conn.close();
					conn = null;
					System.out.println("come in finally");
				}
			}
			catch(Exception e)
			{
				errString = genericUtility.createErrorString(e);
				e.printStackTrace();
				throw new ITMException(e);
			}
		}	
		System.out.println("----Come here 2");
		return resultString;	
	}
		public String process(String xmlString, String xmlString2, String windowName, String xtraParams) throws RemoteException,ITMException
		{
			System.out.println("xtraParams:::------->>>>>>>>>>>>>>"+ xtraParams ); 
			System.out.println("xmlString:::------->>>>>>>>>>>>>>"+ xmlString );
			System.out.println("xmlString2:::------->>>>>>>>>>>>>>"+ xmlString2 );
			System.out.println("windowName:::------->>>>>>>>>>>>>>"+ windowName );
			String retStr = "";
			Document detailDom = null;
			Document headerDom = null;
			
			GenericUtility genericUtility = GenericUtility.getInstance();
			try
			{	
				if(xmlString != null && xmlString.trim().length()!=0)
				{
					headerDom = genericUtility.parseString(xmlString); 
					System.out.println("headerDom" + headerDom);
				}
				if(xmlString2 != null && xmlString2.trim().length()!=0)
				{
					detailDom = genericUtility.parseString(xmlString2); 
					System.out.println("detailDom" + detailDom);
				}
										
			    retStr = process(headerDom, detailDom, windowName, xtraParams);
			    
			}
			catch (Exception e)
			{
				System.out.println("Exception :ShiftChangePrc :process(String xmlString, String xmlString2, String windowName, String xtraParams):" + e.getMessage() + ":");
				e.printStackTrace();
				retStr = genericUtility.createErrorString(e);
				throw new ITMException(e);
			}
			return retStr;		
		}
		public String process(Document headerDom, Document detailDom, String windowName, String xtraParams) throws RemoteException,ITMException
		{
			System.out.println("ShiftChangePrc process(Document,Document,windowName,xtraParams CALLED..."+  windowName);
			System.out.println("header Dom------------------->"+headerDom);
			System.out.println("detailDom------------------->"+detailDom);
			
			String childNodeName = "";
			String siteCode = "";	
			String empCode = "";
			String shift = "";
			String workshftDescr = null;
			String empFname = null;
			String empLname= null;
			String deptCode =null;
			String empSite= null;
			String chgDate=null;
			String chgTerm= null;
			String chgUser = "";
			String realShift= null;
			String patternCode=null;
			String errString=null;
			String userId="";
			String fromDate = "";
			String toDate = "";
			Date tDate = null ;
			Date fDate = null;
			String retString = "VPSUCC1";
		
			String prevSiteCode ="";
			String prevTodate ="";
			String PrevFromdate = "";
			int counter = 0;
			   
			Connection conn = null;
			ResultSet rs = null;
			PreparedStatement pstmt = null;
			String isql = "";
			
			int updCnt = 0;
			int parentNodeListLength = 0;
			int childNodeListLength = 0;
			NodeList parentList = null;
			NodeList childNodeList = null;
			Node parentNode = null;
			Node childNode = null;
		
			ArrayList <String> shiftArr = null;
			ArrayList <String> frmDateArr = null;
			ArrayList <String> toDateArr = null;
			ArrayList <String> shiftValues = null;
			HashMap<Integer, ArrayList<String>> insertMap = new HashMap<Integer, ArrayList<String>>() ;
		
			PreparedStatement existCheckPstmt = null;
			PreparedStatement existUpdatePstmt = null;
			PreparedStatement insertPstmt = null;
			ResultSet existCheckRs = null;
			java.sql.Timestamp jSqlFromDate = null;
			java.sql.Timestamp jSqlToDate = null;
			Date utilFromDate = null;
			Date utilToDate = null;


				try
				{
					AppConnectParm appConnect = new AppConnectParm();
					InitialContext ctx = new InitialContext(appConnect.getProperty());
					ITMDBAccessLocal itmDBAccessEJB = (ITMDBAccessLocal)ctx.lookup("ibase/ITMDBAccessEJB/local");			
					System.out.println(" I N S I D E C A S E  ");
					SimpleDateFormat simpleDateFormat = new SimpleDateFormat(genericUtility.getApplDateFormat());
					
				    userId  = checkNull(genericUtility.getValueFromXTRA_PARAMS(xtraParams, "loginCode"));
					chgTerm = genericUtility.getValueFromXTRA_PARAMS(xtraParams,"chgTerm");

					String empCodeDom  =  checkNull(genericUtility.getColumnValue("emp_code",headerDom));
					String fromDateDom =  checkNull(genericUtility.getColumnValue("from_dt",headerDom));
					String toDateDom   =  checkNull( genericUtility.getColumnValue("to_dt",headerDom));
					
					System.out.println("Emp Code PK"+empCodeDom+"From date PK"+fromDateDom+"To Date PK"+toDateDom);
					
					
					if(detailDom == null ||  genericUtility.getColumnValue("emp_code",headerDom) ==null ||  genericUtility.getColumnValue("from_dt",headerDom) ==null||  genericUtility.getColumnValue("to_dt",headerDom) ==null)
					{
		                errString = itmDBAccessEJB.getErrorString("emp_code","VTTRANID03",userId);
						return errString;
					}

					utilFromDate = simpleDateFormat.parse(fromDateDom);
					utilToDate =   simpleDateFormat.parse(toDateDom);

					//while(fromDate.before(toDate))
					int noOfDaysBetweenDates = 0;
					while(utilFromDate.compareTo(utilToDate) <= 0)
					{
						noOfDaysBetweenDates++;
						utilFromDate = addDays(utilFromDate, 1);
					}

				 	ConnDriver connDriver = new ConnDriver();
					conn = connDriver.getConnectDB("DriverITM");
					conn.setAutoCommit(false);

					String existCheckSql = "SELECT COUNT(1) FROM WORK_SHIFT WHERE EMP_CODE = ? AND FROM_DT = ?";
 					existCheckPstmt = conn.prepareStatement(existCheckSql);
					
					String existUpdateSql = "UPDATE WORK_SHIFT SET SHIFT = ? , TO_DT = ? WHERE EMP_CODE = ? AND FROM_DT = ?";
 					existUpdatePstmt = conn.prepareStatement(existUpdateSql);

					String insertSql = "INSERT INTO WORK_SHIFT (EMP_CODE , SHIFT , FROM_DT, TO_DT , CHG_DATE , CHG_USER , CHG_TERM , REAL_SHIFT , PATTERN_CODE) VALUES (? , ? , ? , ? , fn_sysdate() , ? , ? , ? , ?)";
 					insertPstmt = conn.prepareStatement(insertSql);

					parentList = detailDom.getElementsByTagName("Detail2");
				    parentNodeListLength = parentList.getLength();
					System.out.println(" ShiftChange parentList.getLength() ["+parentList.getLength()+"]");
					String frDate = "";
					String shiftFromDate = "";
					String shiftToDate = "";
					String previousShift = "";
					System.out.println("parentNodeListLength ["+parentNodeListLength+"] noOfDaysBetweenDates ["+noOfDaysBetweenDates+" ]");

					if (parentNodeListLength == 0)
					{
						errString = itmDBAccessEJB.getErrorString("shift","VPSHFTCH08",userId);
						return errString;
					}
					else if (parentNodeListLength != noOfDaysBetweenDates)
					{
						errString = itmDBAccessEJB.getErrorString("shift","VPSHFTCH09",userId);
						return errString;
					}
					for (int prntCtr = 0; prntCtr < parentNodeListLength; prntCtr++ )
					{	
						parentNode = parentList.item(prntCtr);
						childNodeList = parentNode.getChildNodes();
						System.out.println(" ShiftChange childList.getLength() ["+childNodeList.getLength()+"]");		
						for (int ctr = 0; ctr < childNodeList.getLength(); ctr++)
						{
							
						
							childNode = childNodeList.item(ctr);
							childNodeName = checkNull(childNode.getNodeName());
							
							if(childNode.getNodeType() != Node.ELEMENT_NODE)
							{
								continue;
							}
							else if (childNode.getFirstChild() == null)
							{
								continue;
							}
							
							System.out.println("childNode"+childNode+"Name = "+childNodeName+"Chid value ="+checkNull(childNode.getFirstChild().getNodeValue()));

							if(childNodeName.equalsIgnoreCase("shift"))
							{
								shift = checkNull(childNode.getFirstChild().getNodeValue());
								//shiftArr.add(checkNull(childNode.getFirstChild().getNodeValue().trim()));
							}
							else if(childNodeName.equalsIgnoreCase("from_dt"))
							{
								frDate = checkNull(childNode.getFirstChild().getNodeValue());
								//frmDateArr.add(checkNull(childNode.getFirstChild().getNodeValue().trim()));
							}
							else if(childNodeName.equalsIgnoreCase("real_shift"))
							{
								realShift = checkNull(childNode.getFirstChild().getNodeValue() );
							}
							else if(childNodeName.equalsIgnoreCase("pattern_code"))
							{
								patternCode = checkNull(childNode.getFirstChild().getNodeValue() );
							}
							else
							{
								continue;
							}
						
						} //fOR childNodeList
						if(shift == null || shift.trim().length() == 0)
						{
							errString = itmDBAccessEJB.getErrorString("shift","VPSHFTCH06",userId);
							break;
						}
						else
						{
							boolean flag = isRecordExist(conn," WORKSHFT "," WHERE SHIFT ='"+shift+"' AND DAY_NO = 1");

							if(flag == false)
							{
								errString = itmDBAccessEJB.getErrorString("shift","VPSHFTCH07",userId);
								break;
							}
						}

						shift = shift.trim();
						if (previousShift == null || previousShift.trim().length() == 0)
						{
							previousShift = shift.trim();
							shiftFromDate = frDate;
							shiftToDate = frDate;
						}
						else
						{
							if (previousShift.equals(shift))
							{
								shiftToDate = frDate;
							}
							else
							{
								jSqlFromDate = java.sql.Timestamp.valueOf(genericUtility.getValidDateTimeString(shiftFromDate,genericUtility.getApplDateFormat(),genericUtility.getDBDateFormat()));

								jSqlToDate = java.sql.Timestamp.valueOf(genericUtility.getValidDateTimeString(shiftToDate,genericUtility.getApplDateFormat(),genericUtility.getDBDateFormat()));

								existCheckPstmt.setString(1 , empCodeDom);
								existCheckPstmt.setTimestamp(2,jSqlFromDate);	
								existCheckRs = existCheckPstmt.executeQuery();
								int existCnt = 0;
								if (existCheckRs.next())
								{
									existCnt = existCheckRs.getInt(1);
								}
								existCheckRs.close();
								existCheckRs = null;
								existCheckPstmt.clearParameters();
								if (existCnt > 0)
								{
									existUpdatePstmt.setString(1 , previousShift);
									existUpdatePstmt.setTimestamp(2,jSqlToDate);
									existUpdatePstmt.setString(3 , empCodeDom);
									existUpdatePstmt.setTimestamp(4,jSqlFromDate);
									existCnt = existUpdatePstmt.executeUpdate();
									existUpdatePstmt.clearParameters();
								}
								else
								{
									insertPstmt.setString(1 , empCodeDom);
									insertPstmt.setString(2 , previousShift);
									insertPstmt.setTimestamp(3 , jSqlFromDate);
									insertPstmt.setTimestamp(4 , jSqlToDate);
									insertPstmt.setString(5 , userId);
									insertPstmt.setString(6 , chgTerm);
									insertPstmt.setString(7 , realShift);
									insertPstmt.setString(8 , patternCode);
									existCnt = insertPstmt.executeUpdate();
									insertPstmt.clearParameters();
								}
								previousShift = shift.trim();
								shiftFromDate = frDate;
								shiftToDate = frDate;
							}

						}
					}

					if (errString != null && errString.trim().length() > 0)
					{
						conn.rollback();
					}
					else
					{
					
						jSqlFromDate = java.sql.Timestamp.valueOf(genericUtility.getValidDateTimeString(shiftFromDate,genericUtility.getApplDateFormat(),genericUtility.getDBDateFormat()));

						jSqlToDate = java.sql.Timestamp.valueOf(genericUtility.getValidDateTimeString(shiftToDate,genericUtility.getApplDateFormat(),genericUtility.getDBDateFormat()));

						existCheckPstmt.setString(1 , empCodeDom);
						existCheckPstmt.setTimestamp(2,jSqlFromDate);	
						existCheckRs = existCheckPstmt.executeQuery();
						int existCnt = 0;
						if (existCheckRs.next())
						{
							existCnt = existCheckRs.getInt(1);
						}
						existCheckRs.close();
						existCheckRs = null;
						existCheckPstmt.clearParameters();
						if (existCnt > 0)
						{
							existUpdatePstmt.setString(1 , previousShift);
							existUpdatePstmt.setTimestamp(2,jSqlToDate);
							existUpdatePstmt.setString(3 , empCodeDom);
							existUpdatePstmt.setTimestamp(4,jSqlFromDate);
							existCnt = existUpdatePstmt.executeUpdate();
							existUpdatePstmt.clearParameters();
						}
						else
						{
							insertPstmt.setString(1 , empCodeDom);
							insertPstmt.setString(2 , previousShift);
							insertPstmt.setTimestamp(3 , jSqlFromDate);
							insertPstmt.setTimestamp(4 , jSqlToDate);
							insertPstmt.setString(5 , userId);
							insertPstmt.setString(6 , chgTerm);
							insertPstmt.setString(7 , realShift);
							insertPstmt.setString(8 , patternCode);
							existCnt = insertPstmt.executeUpdate();
							insertPstmt.clearParameters();
						}
						if (existCheckRs != null)
						{
							existCheckRs.close();
							existCheckRs = null;
						}
						if (existCheckPstmt != null)
						{
							existCheckPstmt.close();
							existCheckPstmt = null;
						}
						if (existUpdatePstmt != null)
						{
							existUpdatePstmt.close();
							existUpdatePstmt = null;
						}
						if (insertPstmt != null)
						{
							insertPstmt.close();
							insertPstmt = null;
						}
						conn.commit();
						errString = itmDBAccessEJB.getErrorString("shift","VPSUCC1",userId);
					}
				}
			    
				catch (Exception e)
				{
					try
					{
						conn.rollback();
						System.out.println("Exception " + e.getMessage());
						e.printStackTrace();
						throw new ITMException(e);
					}
					catch (Exception e1) 
					{
						e1.printStackTrace();
						throw new ITMException(e1);
					}
				} finally {
					try {
						
							if (rs != null)
							{
								rs.close();
								rs = null;
							}
							if (pstmt != null) 
							{
								pstmt.close();
								pstmt = null;
							}
							if (existCheckRs != null)
							{
								existCheckRs.close();
								existCheckRs = null;
							}
							if (existCheckPstmt != null)
							{
								existCheckPstmt.close();
								existCheckPstmt = null;
							}
							if (existUpdatePstmt != null)
							{
								existUpdatePstmt.close();
								existUpdatePstmt = null;
							}
							if (insertPstmt != null)
							{
								insertPstmt.close();
								insertPstmt = null;
							}
							if (conn != null)
							{
								conn.close();
								conn = null;
							}

					} 
					catch (Exception e)
					{
						e.printStackTrace();
						throw new ITMException(e);
					}
				}
				System.out.println(" retString..  [" + errString + "] ");
				return errString;	

			
		}
		 /**
	     * add days to date in java
	     * @param date
	     * @param days
	     * @return
	     */
	    public static Date addDays(Date date, int days) {
			System.out.println("ShiftChangePrc addDays(date,days ) Called date ="+date +"day = "+days);
	        GregorianCalendar cal = new GregorianCalendar();
	        cal.setTime(date);
	        cal.add(Calendar.DATE, days);
	          
	    	System.out.println("ShiftChangePrc addDays(date,days ) return date = "+cal.getTime());

	        return cal.getTime();
	    }
	     
	    /**
	     * subtract days to date in java
	     * @param date
	     * @param days
	     * @return
	     */
	    public static Date subtractDays(Date date, int days) 
	    {
	    	System.out.println("ShiftChangePrc subtractDays(date,days ) Called date ="+date +"day = "+days);
	        GregorianCalendar cal = new GregorianCalendar();
	        cal.setTime(date);
	        cal.add(Calendar.DATE, -days);
	        
	    	System.out.println("ShiftChangePrc subtractDays(date,days ) return date = "+cal.getTime());
	        return cal.getTime();
	    }
	 
		private String checkNull(String input)
		{
			if (input == null) {
				input = "";
			} else {
				input = input.trim();
			}
			return input;
		}
		private void closePstmtRset(PreparedStatement pstmt, ResultSet rset )throws Exception
		{
			System.out.println("Closing PreparedStatement and result.........");
			try 
			{
				if (rset != null)
				{
					rset.close();
					rset = null;
				}
				if (pstmt != null)
				{
					pstmt.close();
					pstmt = null;
				}
			
			}
			catch (Exception exp) 
			{
				exp.printStackTrace();
				throw new Exception(exp);
			}
		}

		private boolean isRecordExist(Connection conn , String tableName, String condition)
		{
		
			PreparedStatement pstmt = null ; 
			ResultSet rs = null;
			String sql="";
			boolean isExist=false;
			int recCount=0;
			
			
			try
			{	
				
				sql = " SELECT  COUNT(*)  FROM  "+tableName +"  "+condition;
				pstmt =  conn.prepareStatement(sql);
				rs = pstmt.executeQuery();
				if(rs.next())
				{
					recCount=rs.getInt(1);
				
				}
				if(recCount>0)
				{
					isExist=true;
					
				}
				else
				{
					isExist=false;
				
				}
				if(rs != null)
				{
					rs.close();
					rs = null;
				}
				if(pstmt != null)
				{
					pstmt.close();
					pstmt = null;
				}
				
			}
			catch(Exception ex)
			{
				ex.printStackTrace();
			}		
			finally
			{
				try
				{
					if(rs != null)
					{
						rs.close();
						rs = null;
					}
					if(pstmt != null)
					{
						pstmt.close();
						pstmt = null;
					}
				}
				catch(Exception e)
				{
					e.printStackTrace();
				}
			}		
			
			System.out.print("---------Final--isExist-------"+isExist);
			return isExist;
		}

}
/*Created by Chetna on [25/08/2014] For Shift Rotate Change [END]
 * */