package ibase.webitm.ejb.sys;

import java.util.*;
import java.text.SimpleDateFormat;
import java.sql.*;
import java.io.*;
import org.w3c.dom.*;

import javax.xml.parsers.*;
import ibase.webitm.ejb.*;
import ibase.webitm.utility.GenericUtility;
import ibase.utility.CommonConstants;
import ibase.system.config.*;
public class GenVal
{
	
	GenericUtility genericUtility = GenericUtility.getInstance();
	ITMDBAccessEJB itmDBAccessEJB = new ITMDBAccessEJB();

	CommonConstants commonConstants = new CommonConstants();
	boolean flag =false;
	boolean xFlag = true;
	boolean isFromButton=false;
	//changed by msalam on 26/09/07 start
	//field added to store focused Row of the form
	int formCtxFocusedRow = 0;
	//changed by msalam on 26/09/07 end

	//added by msalam on 22/11/07 for appending log in jboss log
	File filePtr ;
	File logDir ;
	String logDirName = "";
	HashMap<String, String> errorMap=new HashMap<String, String>(); 
	String formNo="";
	int Ctr=0;
	//end added by msalam on 22/11/07 for appending log in jboss log

	//public String genVal(String modName ,String objContext,Document data ) //comment added by sagar on 24/12/14 
		public HashMap genVal(String modName ,String objContext,Document data ) 
	{
		System.out.println("Generalized Validation Is In Process.************************************.......");
		Statement stmt = null;
		ResultSet rs = null;
		Connection conn = null;
		String fldName ="",valType = "",fldMin = "",sqlInput = "",fldMax = "",errCD = "",blankOpt = "",fldData ="",fldType="";
		String errCode ="";
		String sql = "	SELECT FLD_NAME,VAL_TYPE,FLD_MIN,SQL_INPUT,FLD_MAX,ERROR_CD,BLANK_OPT ,FLD_TYPE FROM GENMST WHERE MOD_NAME= '"+modName.toUpperCase()+"'";
		//System.out.println("SQL :: "+sql);
		System.out.println(">>>>>>>>sql in genVal:"+sql);
		String errMsg =" ";
		NodeList dataList=null;
		StringTokenizer st = null;
		String colValue="";
		String colName1="";
		java.util.Vector sqlInputVec = new java.util.Vector();
		//added by priyanka on 31/12/14
		if( this.isFromButton)
		{
			sql = "	SELECT FLD_NAME,VAL_TYPE,FLD_MIN,SQL_INPUT,FLD_MAX,ERROR_CD,BLANK_OPT ,FLD_TYPE,FORM_NO  FROM GENMST WHERE MOD_NAME= '"+modName.toUpperCase()+"' and trim(FORM_NO) is not null ";
		}
		else		
		{
			sql = "	SELECT FLD_NAME,VAL_TYPE,FLD_MIN,SQL_INPUT,FLD_MAX,ERROR_CD,BLANK_OPT ,FLD_TYPE,FORM_NO  FROM GENMST WHERE MOD_NAME= '"+modName.toUpperCase()+"' and trim(FORM_NO) is null ";
		}
		System.out.println("SQL :: "+sql);
		//ended by added by priyanka
		try
		{
			ConnDriver connDriver = new ConnDriver();
			conn = connDriver.getConnectDB("DriverITM");
			connDriver = null;

			stmt = conn.createStatement();
			rs = stmt.executeQuery(sql);
			while (rs.next())
			{
				flag =false;
				fldName = rs.getString(1).trim();
				valType = rs.getString(2);
				fldMin = rs.getString(3);
				sqlInput = rs.getString(4);
				fldMax = rs.getString(5);
				errCD = rs.getString(6);
				blankOpt = rs.getString(7);
				fldType = rs.getString(8);
				formNo=rs.getString(9);//added by priyanka
			//	added by priyanka on 31/12/14
				if(isFromButton)
				{
					if(formNo!=null && formNo.trim().length()>0)
					{
						objContext=formNo;	
					}
				}
				System.out.println("Getting objcontext ==form_no>>>>>"+objContext);
				
				
				System.out.println("Getting sqlInput====="+sqlInput);
				if( sqlInput != null )
				{
					System.out.println("SQL Input==not null");
					st = new StringTokenizer( sqlInput, ":" );
					sqlInputVec.clear();
					
					while ( st.hasMoreTokens() )
					{
						sqlInputVec.add( st.nextToken() );
					}
					System.out.println("sqlInputVec============="+sqlInputVec);
								
				}	
				
				if(isFromButton)
				{
					
					if( sqlInputVec.size() != 0 )
					{
						System.out.println("SQL Input=!=0========"+sqlInputVec.size());
						
						for(int ctr=0; ctr < sqlInputVec.size(); ctr++)
						{								
							System.out.println("For===========");
							String colName = (String)sqlInputVec.get( ctr );
							System.out.println("colName======"+colName);
							//added on 310107
							int objContextInt = Integer.parseInt( colName.substring( 0, colName.indexOf( "." ) ) );
							objContextInt++;
							String objContext1 = new Integer( objContextInt ).toString();
							System.out.println("objContext1======"+objContext1);
							 colName1  = colName.substring( colName.indexOf( "." ) + 1 );
							// 21-09-2007 manoharan
							colName1 = colName1.replaceAll( ",", " " );
							colName1 = colName1.trim();
							System.out.println("get colName1======"+colName1);
																					
						}
										
					}
					
					dataList = data.getElementsByTagName("Detail"+formNo );
					System.out.println("Getting  dataList lenght===="+dataList.getLength());
					//System.out.println("len===["+dataList.getLength()+"]=-=============fldName["+fldName+"]");
					
					
					for (Ctr = 0; Ctr < dataList.getLength(); Ctr++)
					{
						
						System.out.println("*************1st for");
						Node detailListNode = dataList.item(Ctr);
						NodeList valueList= detailListNode.getChildNodes(); 
						
						System.out.println("valueList.getLength()============="+valueList.getLength());
						
							for (int cntr = 0; cntr < valueList.getLength(); cntr++) 
							{
								System.out.println("Particular line==========="+Ctr);
								Node	valueNode = valueList.item(cntr); 		
							  
								System.out.println("colName1=check==========="+colName1);
								System.out.println("valueNode.getNodeName()=check==========="+valueNode.getNodeName());
								if(colName1.equalsIgnoreCase(valueNode.getNodeName()))
								{	
									System.out.println("colName1.equalsIgnoreCase(fldName");
									//fldData=genericUtility.getColumnValue("remarks", data);
								     fldData = getValueFromDom1(data,fldName,objContext,Ctr);
									System.out.println("FLD-DATA Is ================"+fldData);
									//flag=true;
								}
								
							}				   
					
							/*if(errMsg!=null && errMsg.trim().length()>0)
							{
								System.out.println("Error Message*********");
								break;
							}*/
			
							if(errMsg!=null && errMsg.trim().length()>0 && flag==true) //condition added by sagar on 25/12/14
							{
								System.out.println(">>>>>>>>>>>Error Caught");
								System.out.println(">>>>>>>>Before Adding to errorMap >fldName:"+fldName);
								System.out.println(">>>>>>>>Before Adding to errorMap >errMsg:"+errMsg);
								//errorMap.put(fldName.trim(), errMsg.trim());
								errorMap.put(errMsg.trim(), fldName.trim());
								errMsg="";
							}
							//ended by priyanka
					if(	flag == true )				
					{
					if ( checkBlank( fldName, fldData, blankOpt) && valType.trim().equalsIgnoreCase( "M" ) )
					{
							errMsg = errCD;//user enter blank but blank option is Y
					}
					else
					{
						//next 2 line commented by msalam on 22/11/07 as validation is required on fldData blank also
						// 06/10/08 manoharan uncommented and added condition that valtype "M"
						//System.out.println("fldData********************["+fldData+"]");
						if ( (  fldData != null && fldData.trim().length() > 0 && "M".equalsIgnoreCase(valType.trim())) || !"M".equalsIgnoreCase(valType.trim()) )
						{
						//end commented by msalam on 22/11/07 as validation is required on fldData blank also

							if( valType == null ) valType= " ";
							//cross query validation
							if (valType.equalsIgnoreCase("Q"))
							{
								//***errMsg = genVal( fldName, modName, data, objContext, fldMin, sqlInput, fldMax, errCD, conn );
								errMsg = genVal( fldName, modName, data, objContext, fldMin, sqlInput, fldMax, errCD );
						        System.out.println("Return error mesg if Found======="+errMsg);
							}
							//slab validation
							else if( valType.equalsIgnoreCase( "S" ) )
							{
								//if field type is N
								try
								{
									double fldValue = 0,fldMinValue = 0,fldMaxValue = 0;
									fldValue = Double.parseDouble(fldData);
									fldMinValue =  Double.parseDouble(fldMin);
									fldMaxValue =  Double.parseDouble(fldMax);
									if (fldValue < fldMinValue || fldValue > fldMaxValue)
									{
										errMsg = errCD;
									}
								}
								catch(NumberFormatException noFormat)
								{
									errMsg = errCD;
								}

							}
							//cruss slab validation
							else if(valType.equalsIgnoreCase("X"))
							{
								double fldValue = 0,fldMinValue = 0,fldMaxValue = 0;
								try
								{
									fldMinValue = Double.parseDouble(fldMin);
								}
								catch(NumberFormatException noFormat)
								{
									String fldMinValueStr= getValueFromDom(data,fldMin,objContext);
									if(fldMinValueStr!=null || fldMinValueStr.trim().length()!=0)
										fldMinValue = Double.parseDouble(fldMinValueStr);
								}
								try
								{
									fldMaxValue = Double.parseDouble(fldMax);
								}
								catch(NumberFormatException noFormat)
								{
									String fldMaxValueStr = getValueFromDom(data,fldMax,objContext);
									if(fldMaxValueStr!=null || fldMaxValueStr.trim().length()!=0)
										fldMaxValue = Double.parseDouble(fldMaxValueStr);
								}
								double dfldData = 0;
								if(fldData!=null | fldData.trim().length()!=0)
								{
									 dfldData = Double.parseDouble(fldData);
								}

								if (dfldData < fldMinValue || dfldData > fldMaxValue)
								{
									errMsg = errCD;
								}
							}
							//master Validation
							else if( valType.trim().equalsIgnoreCase("M") )
							{
								//System.out.println("Calling masterVal for module * * * * * [" + modName.trim() + "]");
								//***errMsg = masterVal( fldName, modName, fldData, errCD, conn );
								System.out.println(">>>>>>>If valType M:"+valType);
								errMsg = masterVal( fldName, modName, fldData, errCD );
							}
						//next line commented by msalam on 22/11/07 as validation is required on fldData blank also
						}//end of blank opt N
						//end commented by msalam on 22/11/07 as validation is required on fldData blank also
					}
				  }
			   }
					
		    }
			else
			{
				System.out.println("Not from Button");
			fldData = getValueFromDom(data,fldName,objContext);
			System.out.println("objContext********************["+objContext+"]");
			//if(	flag == true )
				System.out.println("Fld Name :["+fldName+"] Value : "+fldData+"] Present["+flag+"]");
			//System.out.println("validation Type********************["+valType+"]");
			if(	flag == true )
			{
				if ( checkBlank( fldName, fldData, blankOpt) && valType.trim().equalsIgnoreCase( "M" ) )
				{
					errMsg = errCD;//user enter blank but blank option is Y
				}
				else
				{
					System.out.println("NOt from button");
					//next 2 line commented by msalam on 22/11/07 as validation is required on fldData blank also
					// 06/10/08 manoharan uncommented and added condition that valtype "M"
					//System.out.println("fldData********************["+fldData+"]");
					if ( (  fldData != null && fldData.trim().length() > 0 && "M".equalsIgnoreCase(valType.trim())) || !"M".equalsIgnoreCase(valType.trim()) )
					{
						//end commented by msalam on 22/11/07 as validation is required on fldData blank also

						if( valType == null ) valType= " ";
						//cross query validation
						if (valType.equalsIgnoreCase("Q"))
						{						
								System.out.println("Not from isFromButton====================");
								errMsg = genVal( fldName, modName, data, objContext, fldMin, sqlInput, fldMax, errCD );
							
						}
						//slab validation
						else if( valType.equalsIgnoreCase( "S" ) )
						{
							//if field type is N
							try
							{
								double fldValue = 0,fldMinValue = 0,fldMaxValue = 0;
								fldValue = Double.parseDouble(fldData);
								fldMinValue =  Double.parseDouble(fldMin);
								fldMaxValue =  Double.parseDouble(fldMax);
								if (fldValue < fldMinValue || fldValue > fldMaxValue)
								{
									errMsg = errCD;
								}
							}
							catch(NumberFormatException noFormat)
							{
								errMsg = errCD;
							}

						}
						//cruss slab validation
						else if(valType.equalsIgnoreCase("X"))
						{
							double fldValue = 0,fldMinValue = 0,fldMaxValue = 0;
							try
							{
								fldMinValue = Double.parseDouble(fldMin);
							}
							catch(NumberFormatException noFormat)
							{
								String fldMinValueStr= getValueFromDom(data,fldMin,objContext);
								if(fldMinValueStr!=null || fldMinValueStr.trim().length()!=0)
									fldMinValue = Double.parseDouble(fldMinValueStr);
							}
							try
							{
								fldMaxValue = Double.parseDouble(fldMax);
							}
							catch(NumberFormatException noFormat)
							{
								String fldMaxValueStr = getValueFromDom(data,fldMax,objContext);
								if(fldMaxValueStr!=null || fldMaxValueStr.trim().length()!=0)
									fldMaxValue = Double.parseDouble(fldMaxValueStr);
							}
							double dfldData = 0;
							if(fldData!=null | fldData.trim().length()!=0)
							{
								dfldData = Double.parseDouble(fldData);
							}

							if (dfldData < fldMinValue || dfldData > fldMaxValue)
							{
								errMsg = errCD;
							}
						}
						//master Validation
						else if( valType.trim().equalsIgnoreCase("M") )
						{
							//System.out.println("Calling masterVal for module * * * * * [" + modName.trim() + "]");
							//***errMsg = masterVal( fldName, modName, fldData, errCD, conn );
							errMsg = masterVal( fldName, modName, fldData, errCD );
						}
						//next line commented by msalam on 22/11/07 as validation is required on fldData blank also
					}//end of blank opt N
					//end commented by msalam on 22/11/07 as validation is required on fldData blank also
				}			
			}
			}
						
				System.out.println(">>>>>>>>>Get fldName:"+fldName);
				System.out.println(">>>>>>>>>Get errMsg:"+errMsg);
				if(errMsg!=null && errMsg.trim().length()>0 && flag==true) //condition added by sagar on 25/12/14
				{
					System.out.println(">>>>>>>>Before Adding to errorMap >fldName:"+fldName);
					System.out.println(">>>>>>>>Before Adding to errorMap >errMsg:"+errMsg);
					//errorMap.put(fldName.trim(), errMsg.trim());
					errorMap.put(errMsg.trim(), fldName.trim());
					errMsg="";
				}
			}
			rs.close();
			rs = null;
			stmt.close();
			stmt = null;
			if (conn != null)
			{
				conn.close(); 
				conn = null; 
			}
			
			if(errMsg.trim().length()==0 && xFlag == true) 
			{
				System.out.println(">>>>>>>>>>>>>Check for ModeName:X");
				xFlag = false;
				//System.out.println("Calling genVal for module * * * * * [X]");
				//***errMsg = genVal("X",objContext,data ,conn);
				errorMap = genVal("X",objContext,data );//code added by sagar on 25/12/14
				System.out.println(">>>>>>>>>>>>>errorMap from Mod Name=X :"+errorMap);
				xFlag = true;
			}
			System.out.println(">>>>>>>>Final Return errorMap:"+errorMap);
		} // end of try
		catch (SQLException sx)
		{
			//System.out.println("SQLException ()::" +sql+ sx.getMessage() + ":");
			sx.printStackTrace();

		}
		catch (Exception e)
		{
			//System.out.println("Exception () ::" + e.getMessage());
			e.printStackTrace();

		}		
		
		finally
		{
			try
			{
				if(rs !=null)
				{
					rs.close();
					rs=null;
				}
				if(stmt!=null)
				{
					stmt.close();
					stmt=null;
				}
				if (conn != null)
				{
					conn.close(); 
					conn = null; 
				}
			}
			catch(Exception ex)
			{
				ex.printStackTrace();
			}
			
			//return stkOpt;
		 }
		//return errMsg;
		return errorMap;//return type changed by sagar on 25/12/14

	}
	//changed by msalam on 26/09/07 start
	//to overload the function
	//public String genVal(String modName ,String objContext,Document data ,Connection conn)
	//public String genVal(String modName ,String objContext,Document data, String focusedRow, Connection conn)
	
		//added by priyanka 4
	public HashMap genVal(String modName ,String objContext,Document data, String focusedRow,boolean isFromButton)
	{
		System.out.println("focusedRow==========="+focusedRow);
		this.isFromButton=isFromButton;
		return genVal(modName,objContext,data,focusedRow); 
		
	}

	
	//public String genVal(String modName ,String objContext,Document data, String focusedRow)//comment added by sagar on 25/12/14
		public HashMap genVal(String modName ,String objContext,Document data, String focusedRow)
		{
		String errMsg =" ";
		HashMap<String, String> errorMsgMap= new HashMap<String, String>(); 
		//changed by msalam on 26/09/07 start
		if( focusedRow != null )
		{
			this.formCtxFocusedRow = Integer.parseInt( focusedRow );
		}
		//changed by msalam on 26/09/07 end
		//changed by msalam on 22/11/07 for appending log
		if(CommonConstants.J2EE_VERSION.equals("1"))
		{
			logDirName =  CommonConstants.JBOSSHOME  + File.separator + "log" ;
		}
		else if(CommonConstants.J2EE_VERSION.equals("2"))
		{
			logDirName =  CommonConstants.JBOSSHOME   + File.separator + "server"+ File.separator +"default"+ File.separator +"log" ;
		}
		logDir = new File(logDirName);
		filePtr = new File(logDirName+ File.separator + "genval.log");

		//System.out.println("--------------------------------------->GenVal called");
		writeLog( filePtr, "GenVal called", true );
		//end changed by msalam on 22/11/07 for appending log
		//***errMsg = genVal( modName, objContext, data, conn);
		//errMsg = genVal( modName, objContext, data);//comment added by sagar on 25/12/14
		errorMsgMap = genVal( modName, objContext, data);//code added by sagar on 25/12/14
		System.out.println(">>>>>>>>>>>Return errorMsgMap in GenVal:"+errorMsgMap.toString());
		//return errMsg;//comment added by sagar on 25/12/14
		return errorMsgMap;
	}

	//changed by msalam on 26/09/07 end
	/* The method is to check wheather the blank validation is check or not.
   	If blank opt is Y and user left field blank it return true*/
	private boolean checkBlank(String colName, String colValue, String blankOpt)
	{
		boolean result = false;
		try
		{
			writeLog( filePtr, "Blank Option " + blankOpt, true );
			//System.out.println("Blank Option "+blankOpt);
			// 08-10-2007 manoharan default value assigned for blankopt also
			// blankopt is N and empty data then indicate error
			if (blankOpt == null)
			{
				blankOpt = "N";
			}

			//if (blankOpt != null && blankOpt.equalsIgnoreCase("Y"))
			if (blankOpt != null && blankOpt.equalsIgnoreCase("N"))
			// end 08-10-2007 manoharan
			{
				if (colValue == null || colValue.trim().length() == 0)
				{
					result = true;
				}
			}
		}catch(Exception e)
		{
			//System.out.println("Exception "+e);
			e.printStackTrace();
		}
		return result;
	}
	//master validation
	//private String masterVal( String fldName, String  modName, String fldData, String errCD, Connection conn )
	private String masterVal( String fldName, String  modName, String fldData, String errCD )
	{

		String err = " ";
		Statement mst = null;
		ResultSet mrs = null;
		Connection conn = null;
		int count=0;
		String sql ="";
		writeLog( filePtr, "fldData:::::::::"+fldData, true );
		try
		{

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

		//System.out.println("fldData:::::::::"+fldData);
		//next 2 lines commented by msalam on 23/11/07 as validation is required on fldData blank also
		//if( fldData != null && fldData.trim().length()!=0 )
		//{
		//end commented by msalam on 23/11/07 as validation is required on fldData blank also
			if(modName.equalsIgnoreCase("X"))
			{
				sql="SELECT COUNT(*)  FROM GENCODES WHERE FLD_NAME = '"+fldName+"'AND MOD_NAME = 'X' AND RTRIM(FLD_VALUE) = RTRIM('"+fldData+"') AND ACTIVE = 'Y'";
			}
			else
			{
				sql ="SELECT COUNT(*)  FROM GENCODES WHERE FLD_NAME = '"+fldName+"' AND MOD_NAME = '"+modName.toUpperCase()+"' AND RTRIM(FLD_VALUE) = RTRIM('"+fldData+"') AND ACTIVE = 'Y'";
			}
			writeLog( filePtr, "Excecuting Query(valtype=M);:::::::::::::::"+sql, true );
			//System.out.println("Excecuting Query(valtype=M);:::::::::::::::"+sql);
			//try
			//{
			 System.out.println(">>>>>>>>>>>>>in masterVal sql:"+sql);
				mst=conn.createStatement();
				mrs = mst.executeQuery( sql );
				if(mrs.next())
				{
					count = mrs.getInt(1);
				}
				mrs.close();
				mrs = null;
				mst.close();
				mst = null;
				System.out.println(">>>>>>>>>>>>>in masterVal count:"+count);
				if(count==0)
				{
					err = errCD;
					writeLog( filePtr, "Master validation record Not Found", true );
				}
				conn.close();
				conn = null;
			}
			catch(Exception e){e.printStackTrace();}
		//next line commented by msalam on 22/11/07 as validation is required on fldData blank also
		//}//end of blank opt N
		//end commented by msalam on 22/11/07 as validation is required on fldData blank also


		return err;
	}

	//private String genVal( String fldName, String modName, Document dom, String objContext, String queryFrDB, String sqlInput, String resultStr, String errcd, Connection conn )
	private String genVal( String fldName, String modName, Document dom, String objContext, String queryFrDB, String sqlInput, String resultStr, String errcd )
	{
		//System.out.println( "Result Should come as " + resultStr );
		writeLog( filePtr, "Result Should come as " + resultStr, true );
		//System.out.println("Incomming dom:::" + GenericUtility getInstance().serializeDom(dom));
		PreparedStatement pstmt1= null;
		ResultSet rs1  = null;
		java.util.Vector resultStrVec = new java.util.Vector();
		java.util.Vector sqlInputVec = new java.util.Vector();
		java.util.Vector dataVec = new java.util.Vector();
		StringTokenizer st = null;
		String data="";
		String errCode =" ";
		Connection conn = null;
		String colType ="";
		String colValue="";
		try
		{
			writeLog( filePtr, "Mod Name :::" + modName, true );
			writeLog( filePtr, "Field Name :::" + fldName, true );
			writeLog( filePtr, "Database queries :::" + queryFrDB, true );
			writeLog( filePtr, "Input to query :::" + sqlInput, true );
			writeLog( filePtr, "Value after execute :::" + resultStr, true );
			System.out.println(">>>>>>>>>>>>>>>In genVal Start>>>>>>>>>>>>>>>>>>>>");
            System.out.println(">>>>>>>>queryFrDB:"+queryFrDB);
            System.out.println(">>>>>>>>sqlInput:"+sqlInput);
            System.out.println(">>>>>>>>resultStr:"+resultStr);
            System.out.println(">>>>>>>>fldName:"+fldName);
			//***enumerate the sqlinput and store individual parameter in an vector(check for null)
			if( sqlInput != null )
			{
				st = new StringTokenizer( sqlInput, ":" );
				while ( st.hasMoreTokens() )
				{
					sqlInputVec.add( st.nextToken() );
				}
			}
			System.out.println(">>>>>>>>>>>>sqlInputVec:"+sqlInputVec.toString());
			//***Enumerate the resultStr and store individual parameter in an vector
			st = new StringTokenizer( resultStr, "," );
			while ( st.hasMoreTokens() )
			{
				resultStrVec.add( st.nextToken() );
			}
			System.out.println(">>>>>>>>>>>>resultStrVec:"+resultStrVec.toString());
		}
		catch ( Exception e )
		{
			writeLog( filePtr, "Excetion in seperating sql input ::", true );
			
			e.printStackTrace();

		}
	    try
		{
			//**********Executing The Query
			StringBuffer QueryBuf= new StringBuffer( queryFrDB );
		    if( sqlInputVec.size() != 0 )
		    {
				for(int ctr=0; ctr < sqlInputVec.size(); ctr++)
				{
					String colName = (String)sqlInputVec.get( ctr );
					//added on 310107
					int objContextInt = Integer.parseInt( colName.substring( 0, colName.indexOf( "." ) ) );
					objContextInt++;
					String objContext1 = new Integer( objContextInt ).toString();

					String colName1  = colName.substring( colName.indexOf( "." ) + 1 );
					// 21-09-2007 manoharan
					colName1 = colName1.replaceAll( ",", " " );
					colName1 = colName1.trim();
					// end 21-09-2007
					colType = getType(modName, objContext1, colName1);
					//*****find the value of given field

					//changed by msalam on 24/09/07
					//for getting value of last row
					System.out.println("Ctr==========="+Ctr);
					//added by priyanka
					if(isFromButton)
					{
					     colValue = getValueFromDom1( dom, colName1, objContext1,Ctr);
					}
					else
					{
						 colValue = getValueFromDom( dom, colName1, objContext1);
					}

					writeLog( filePtr, "colValue form dom===[" + colValue + "]" + " Col Type [" + colType + "]", true );

					//changed by msalam on 24/09/07 end
					//changed by msalam on 03/10/07 for colType = "DATETIME"

					if( colType.toUpperCase().indexOf( "DATETIME") != -1 )
					{
						String dataBase = null;
						dataBase = 	CommonConstants.DB_NAME;
						String replaceDateColValue = null;
						String dateColValue = null;
						dateColValue = colValue;
						if( dateColValue == null )
						{
							dateColValue = "";
						}
						if( dataBase.equalsIgnoreCase( "ORACLE") )
						{
							replaceDateColValue = "TO_DATE( '" + getDateInAppFormat( dateColValue.trim(), "yyyy-mm-dd" ) + "', 'yyyy/MM/dd' )";
						}
						else if( dataBase.equalsIgnoreCase( "DB2") )
						{
							if( dateColValue == null || dateColValue.trim().length() == 0 )
							{
								replaceDateColValue = "cast(null as timestamp)";
							}
							else
							{
								replaceDateColValue = "timestamp( '" + getDateInAppFormat( dateColValue.trim() ) + "' )";
							}
						}
						else if( dataBase.equalsIgnoreCase( "MSSQL") )
						{
							if( dateColValue == null || dateColValue.trim().length() == 0 )
							{
								replaceDateColValue = "cast(null as datetime)";
							}
							else
							{
								replaceDateColValue = "convert( '" + getDateInAppFormat( dateColValue.trim() ) + "'as DATETIME )";
							}
						}
						int index = QueryBuf.toString().indexOf( '?' );
						QueryBuf.replace( index, index + 1, replaceDateColValue );
					}

					//changed by msalam on 03/10/07 for colType = "DATETIME" end

					//Changed by msalam on 22/10/07 for colType = "DATETIME" start
					//if( ( colType.toUpperCase().indexOf( "STRING" ) != -1 ) || ( colType.toUpperCase().indexOf( "CHAR" ) != -1) || ( colType.toUpperCase().indexOf( "VARCHAR" ) != -1 ) )
					//changed line below
					else if( ( colType.toUpperCase().indexOf( "STRING" ) != -1 ) ||
						( colType.toUpperCase().indexOf( "CHAR" ) != -1) ||
						( colType.toUpperCase().indexOf( "VARCHAR" ) != -1 )  )
					{
						int index = QueryBuf.toString().indexOf( '?' );
						//next line changed and modified line added by msalam to replace null by blank on 23/11/07
						//QueryBuf.replace( index, index + 1, "'" + colValue.trim() + "'" );
						if( colValue != null )
						{
							QueryBuf.replace( index, index + 1, "'" + colValue.trim() + "'" );
						}
						else
						{
							QueryBuf.replace( index, index + 1, "''" );
						}
						//end changed by msalam on 23/11/07
					}
					else if((colType.toUpperCase().indexOf("DECIMAL") != -1) || (colType.toUpperCase().indexOf("DOUBLE") != -1) || (colType.toUpperCase().indexOf("NUMBER") != -1) || (colType.toUpperCase().indexOf("LONG") != -1))
					{
						int index = QueryBuf.toString().indexOf( '?' );
						//next line changed and modified line added by msalam to replace null by blank on 23/11/07
						//QueryBuf.replace( index, index + 1, colValue);
						if( colValue != null )
						{
							QueryBuf.replace( index, index + 1, colValue);
						}
						else
						{
							QueryBuf.replace( index, index + 1, "0.0" );
						}
						//end changed by msalam on 23/11/07
					}
					//Changed by msalam on 22/10/07 for colType = "DATETIME" end
				}
			}
			ConnDriver connDriver = new ConnDriver();
			conn = connDriver.getConnectDB("DriverITM");
			connDriver = null;
			writeLog( filePtr, "After replace parameter Final 	Query[*********]:::" + QueryBuf.toString(), true );
			pstmt1= conn.prepareStatement( QueryBuf.toString() );
			rs1 = pstmt1.executeQuery();
			ResultSetMetaData rsmd = rs1.getMetaData();
			int numberOfColumns = rsmd.getColumnCount();
			System.out.println(">>>>>>>>>>>numberOfColumns:"+numberOfColumns);
			if( numberOfColumns != resultStrVec.size() )
			{
				errCode = "CONFIGERR";
			}
			else
			{
				while (rs1.next())
				{
					for(int ctr = 1; ctr <= numberOfColumns; ctr++)
					{
						int metaType = rsmd.getColumnType(ctr);
						writeLog( filePtr, "metaType----------------------------------"+metaType, true );
						if (metaType == Types.VARCHAR)
						{
							data = rs1.getString(ctr);
						}
						else if (metaType == Types.CHAR)
						{
							data = rs1.getString(ctr);
						}
						else if(metaType == Types.NUMERIC)
						{
							data = new Integer(rs1.getInt(ctr)).toString();
						}
						else if(metaType == Types.DECIMAL)
						{
							data = new Double(rs1.getDouble(ctr)).toString();
						}
						else if( metaType == Types.TIMESTAMP )
						{
							data =rs1.getTimestamp( ctr ).toString();
						}
						else if(metaType == 4)
						{
								data = new Integer( rs1.getInt( ctr ) ).toString();
						}
						System.out.println(">>>>>>>>>>>in for numberOfColumns data:"+data);
					}
					writeLog( filePtr, "Query RESULT ====>>>" + data, true );
					dataVec.add( data );
				}
			}
			rs1.close();
			rs1 = null;
			pstmt1.close();
			pstmt1 = null;
			conn.close();
			conn = null;
			System.out.println(">>>>>>>resultStrVec:"+resultStrVec.toString());
			for( int counter = 0; counter < resultStrVec.size(); counter++ )
			{
				System.out.println(">>>>>>>In for resultStrVec:");
				String result = (String)resultStrVec.get( counter );
				String valueFrDatabase = (String)dataVec.get( counter );
				System.out.println(">>>>>>>>>>result:"+result);
				System.out.println(">>>>>>>>>>valueFrDatabase:"+valueFrDatabase);
				writeLog( filePtr, "valueFrDatabase=" + valueFrDatabase, true );
				writeLog( filePtr, "QRY Result" + result, true );
				if( !result.trim().equalsIgnoreCase( valueFrDatabase.trim() ) )
				{
					System.out.println(">>>>>>>>>>>Assign errcd to errCode:"+errcd);
					errCode = errcd ;
					break;
				}
			}

		}
		catch (SQLException sx)
		{
			writeLog( filePtr, "Exception in executing ", true );
			sx.printStackTrace();
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	    System.out.println(">>>>>>>>>>>errCode from genVal:"+errCode);
	    System.out.println(">>>>>>>>>>>>>>>In genVal End>>>>>>>>>>>>>>>>>>>>");
		return errCode;
	}
	//******** Get the type of the field
	private String getType(String winName,String objContext,String fldName)
	{
		Document dom = null;
		NodeList parentNodeList = null;
		NodeList childNodeList = null;
		Node parentNode = null;
		Node childNode = null;
		int parentNodeListLength = 0;
		int childNodeListLength = 0;
		String tagName = null;
		String tagValue = null;
		String colName = "";
		String colType = "";
		String childNodeName = "";
		String fldType="";
		try
		{
				String ObjName =winName.substring(2,winName.length())+"2"+objContext;
				// 01/10/08 manoharan not working in linux
				//String filename = CommonConstants.JBOSSHOME + File.separator + "bin\\metadata\\"+ ObjName.trim() + ".xml";
				String filename = CommonConstants.JBOSSHOME + File.separator + "bin" + File.separator + "metadata" + File.separator + ObjName.trim() + ".xml";
				// end 01/10/08 manoharan not working in linux
				File file = new File(filename);
				DocumentBuilder parser1 = DocumentBuilderFactory.newInstance().newDocumentBuilder();
				dom = parser1.parse(file);
				NodeList columnsNodeList = dom.getElementsByTagName("table_column");
				int tableColLength = columnsNodeList.getLength();
				for(int i= 0  ;i < tableColLength;i++ )
				{
					NodeList columnNodeList  =  columnsNodeList.item(i).getChildNodes();
					int tableColChildLength = columnNodeList.getLength();
					for(int j= 0 ;j <  tableColChildLength;j++)
					{
						Node colNode = columnNodeList.item(j) ;
						tagName = colNode.getNodeName() ;
						if (tagName.equals("type") )
						{
							colType = colNode.getFirstChild().getNodeValue();
						}
						if (tagName.equals("name"))
						{
							colName = colNode.getFirstChild().getNodeValue();
						}
					}
					if(fldName.equalsIgnoreCase(colName))
					{
						fldType = colType;
						break;
					}
				}
		}
		catch(FileNotFoundException fileNotFound)
		{
			fileNotFound.printStackTrace();
		}
		catch(Exception e )
		{
			e.printStackTrace();

		}
		return	fldType;
	}
	//*****Get the parameter field value
	//function changed by msalam on 26/09/07
	//for getting value of last row in place of first row only
	private String getValueFromDom(Document dom, String fldName, String objContext)
	{
		String value = "";
		int currentFormNo= 0;
		NodeList parentNodeList = null;
		Node parentNode = null;
		NodeList childNodeList = null;
		int  childNodeListLength = 0;
		Node childNode = null;
		String childNodeName ="";
		try
		{
			System.out.println("Enter in getValueFromDom>>>>>>>>>>>>");
			if(objContext != null && objContext.trim().length()>0)
			{
				currentFormNo = Integer.parseInt(objContext);
			}
			String tag = "Detail"+currentFormNo;
			System.out.println("tag==========="+tag);
			parentNodeList = dom.getElementsByTagName(tag);
			System.out.println("parentNodeList==========="+parentNodeList);
			//Changed By Pragyan 14-JUL-14 To support genvalidation for both MOBILEE12 and RCP.start
			//changed by msalam on 26/09/07 start
			//for getting value of focused Row rather than first row only
			//commented next line and added lines
			//parentNode = parentNodeList.item(0);
			//added lines in place of previous line
			//parentNode = parentNodeList.item( currentFormNo == 1 ? 0 : (this.formCtxFocusedRow - 1) );
			if(parentNodeList != null && parentNodeList.getLength() < this.formCtxFocusedRow )
			{
			
				parentNode = parentNodeList.item( currentFormNo == 1 ? 0 : (parentNodeList.getLength() - 1) );
				
			}
			else
			{
				parentNode = parentNodeList.item( currentFormNo == 1 ? 0 : (this.formCtxFocusedRow - 1) );
			}
			//Changed By Pragyan 14-JUL-14  support genvalidation for both MOBILEE12 and RCP.end
			
			//changed by msalam on 26/09/07 end
			System.out.println("parentNode========="+parentNode);
			childNodeList = parentNode.getChildNodes();
			System.out.println("childNodeList========="+childNodeList);
			childNodeListLength = childNodeList.getLength();
			System.out.println("childNodeListLength========="+childNodeListLength);

			// 21-09-2007 manoharan
			fldName = fldName.replaceAll(","," ");
			fldName = fldName.trim();
			System.out.println("fldName========="+fldName);
			// end 21-09-2007 manoharan
			for(int ctr = 1; ctr < childNodeListLength; ctr++)
			{
				childNode = childNodeList.item(ctr);
				childNodeName = childNode.getNodeName();
				if (childNodeName.equalsIgnoreCase(fldName))
				{
					flag = true;
					if (childNode.getFirstChild() != null)
					{
						value = childNode.getFirstChild().getNodeValue();
						break;
					}
				}
			}

		}//end try
		catch(Exception e)
		{
			e.printStackTrace();
		}
		return value;
	}
	
	//added by priyanka
	
	private String getValueFromDom1(Document dom, String fldName, String objContext,int cnt)
	{
		String value = "";
		int currentFormNo= 0;
		NodeList parentNodeList = null;
		Node parentNode = null;
		NodeList childNodeList = null;
		int  childNodeListLength = 0;
		Node childNode = null;
		String childNodeName ="";
		try
		{
			System.out.println("Enter in getValueFromDom>>>>>>>>>>>>");
			if(objContext != null && objContext.trim().length()>0)
			{
				currentFormNo = Integer.parseInt(objContext);
			}
			String tag = "Detail"+currentFormNo;
			System.out.println("tag==========="+tag);
			parentNodeList = dom.getElementsByTagName(tag);
			System.out.println("parentNodeList==========="+parentNodeList);
			//Changed By Pragyan 14-JUL-14 To support genvalidation for both MOBILEE12 and RCP.start
			//changed by msalam on 26/09/07 start
			//for getting value of focused Row rather than first row only
			//commented next line and added lines
			//parentNode = parentNodeList.item(0);
			//added lines in place of previous line
			//parentNode = parentNodeList.item( currentFormNo == 1 ? 0 : (this.formCtxFocusedRow - 1) );
			/*if(parentNodeList != null && parentNodeList.getLength() < this.formCtxFocusedRow )
			{
			
				parentNode = parentNodeList.item( currentFormNo == 1 ? 0 : (parentNodeList.getLength() - 1) );
				
			}
			else
			{
				parentNode = parentNodeList.item( currentFormNo == 1 ? 0 : (this.formCtxFocusedRow - 1) );
			}*/
			//Changed By Pragyan 14-JUL-14  support genvalidation for both MOBILEE12 and RCP.end
			
			//changed by msalam on 26/09/07 end
		//	System.out.println("parentNode========="+parentNode);
			//childNodeList = parentNode.getChildNodes();
			//System.out.println("childNodeList========="+childNodeList);
			//childNodeListLength = childNodeList.getLength();
			//System.out.println("childNodeListLength========="+childNodeListLength);

			// 21-09-2007 manoharan
			fldName = fldName.replaceAll(","," ");
			fldName = fldName.trim();
			System.out.println("fldName========="+fldName);
			System.out.println("Count====="+cnt);
			parentNode = parentNodeList.item(cnt);
			childNodeList = parentNode.getChildNodes();
			childNodeListLength = childNodeList.getLength();
			// end 21-09-2007 manoharan
			for(int ctr = 0; ctr < childNodeListLength; ctr++)
			{
				childNode = childNodeList.item(ctr);
				childNodeName = childNode.getNodeName();
				if (childNodeName.equalsIgnoreCase(fldName))
				{
					flag = true;
					if (childNode.getFirstChild() != null)
					{
						value = childNode.getFirstChild().getNodeValue();
						break;
					}
				}
			}

		}//end try
		catch(Exception e)
		{
			e.printStackTrace();
		}
		System.out.println("Printing Dom======="+dom.toString());
		return value;
		
	}
	
	
	private String getFormValue(Document dom, String fldName, String objContext,String formNo)
	{
		String value = "";
		int currentFormNo= 0;
		NodeList parentNodeList = null;
		Node parentNode = null;
		NodeList childNodeList = null;
		int  childNodeListLength = 0;
		Node childNode = null;
		String childNodeName ="";
		try
		{
			if(objContext != null && objContext.trim().length()>0)
			{
				currentFormNo = Integer.parseInt(objContext);
			}
			String tag = "Detail"+currentFormNo;
			parentNodeList = dom.getElementsByTagName(tag);
			System.out.println("parentNodeList============="+parentNodeList);
	
			

		}//end try
		catch(Exception e)
		{
			e.printStackTrace();
		}
		return value;
		
		

		
	}
	//added by msalam on 22-10-2007 to get date in application format
	private String getDateInAppFormat( String dateColValue )
	{
		String appDate = null;
		Object date = null;
		SimpleDateFormat DBDate=null;
		try
		{
			DBDate= new SimpleDateFormat( genericUtility.getApplDateFormat() ); //"yyyy-mm-dd");
			date = DBDate.parse( java.sql.Timestamp.valueOf( genericUtility.getValidDateTimeString( dateColValue, genericUtility.getApplDateFormat(), genericUtility.getDBDateFormat() ) ).toString() );
			appDate = DBDate.format( date ).toString() + " 00:00:00" ;
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		return ( appDate );
	}
	//
	//FUNCTION ADDED BY MSALAM ON 22/11/07 TO GET DATE IN GIVEN FORMAT
	private String getDateInAppFormat( String dateColValue, String dateFormat )
	{
		String appDate = null;
		Object date = null;
		SimpleDateFormat DBDate=null;
		if ( dateColValue == null || dateColValue.trim().length() == 0 )
		{
			return "";
		}
		try
		{
			DBDate= new SimpleDateFormat( dateFormat );
			date = DBDate.parse( java.sql.Timestamp.valueOf( genericUtility.getValidDateTimeString( dateColValue, genericUtility.getApplDateFormat(), genericUtility.getDBDateFormat() ) ).toString() );
			appDate = DBDate.format( date ).toString() ;
			writeLog( filePtr, appDate, true );

		}
		catch(Exception e)
		{
			writeLog( filePtr, "Exception in getDateInFormat", true );
		}
		return ( appDate );
	}

	//END FUNCTION ADDED BY MSALAM ON 22/11/07 TO GET DATE IN GIVEN FORMAT
	//functions added by msalam on 22/11/07 for appending log in jboss logg

	static void writeLog(File f,String Msg,boolean flag)
	{
		try{
			if(! CommonConstants.DEBUG_LEVEL.equals("0")) // added by kunal on 17/07/13 ,for remove Out Of Memory Error
			{
			PrintWriter pw = new PrintWriter((new FileOutputStream(f,flag)),flag);
			pw.println("PosSave ::"+Msg);
			pw.close();
			}
		}
		catch(Exception exWm){exWm.printStackTrace();}
	}
	//end functions added by msalam on 22/11/07 for appending log in jboss logg
}//END OF EJB


