
/*
    Window Name : W_file_to_batch_load
*/
package ibase.webitm.ejb.sys; 

import ibase.webitm.ejb.dis.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;
import java.io.*;
import java.rmi.RemoteException;
import java.util.*;
import java.util.Date;
import java.text.SimpleDateFormat; 
import java.sql.*;
import org.w3c.dom.*;
import javax.xml.parsers.*;
import javax.ejb.*;
import javax.naming.InitialContext;
import ibase.webitm.utility.ITMException;
import ibase.webitm.ejb.*;
import ibase.webitm.utility.GenericUtility;
import ibase.webitm.utility.TransIDGenerator;
import ibase.utility.CommonConstants;
import ibase.ejb.*;
import ibase.system.config.*;
import java.util.*;
import java.lang.*; 
import javax.ejb.Stateless; // added for ejb3

@Stateless // added for ejb3

public class MasterApply  implements  MasterApplyLocal , MasterApplyRemote // SessionBean
{

	Connection conn = null;
	ITMDBAccessEJB itmDBAccessEJB = null;
	CommonConstants commonConstants;
	SessionContext cSessionContext;
	GenericUtility genericUtility = GenericUtility.getInstance();
	String userId = "";
	String logInSite = "";
	int tran_sl = 0;
	String win_name= "";
	String batch_id = "";
	public void ejbCreate() throws RemoteException, CreateException
	{
		try
		{
			itmDBAccessEJB = new ITMDBAccessEJB();
			ConnDriver conndriver = new ConnDriver();
 			conn = conndriver.getConnectDB("DriverITM");
 			commonConstants  = new CommonConstants();
			System.out.println("MasterApplyEJB ejbCreate called.........");
		}
		catch (Exception e)
		{
			System.out.println("Exception :CreateBatchPrcEJB :ejbCreate :==>"+e);
			throw new CreateException();
		}
	}
	/*public void ejbRemove()
	{
	}
	public void ejbActivate() 
	{
	}
	public void ejbPassivate() 
	{
	}
	public void setSessionContext(SessionContext mSessionContext) 
	{
		this.cSessionContext = mSessionContext;
	}*/
	
	
//CREATING XMLSTRING BY TAKING DATA AND FIELD NAME FROM BATCHLOADET AND INSERTING IN TO CHARGEBACK
public void  applyMasterTable(String batchid,String xtraParam)
{
	String winName = "";
	StringBuffer logBuff =new StringBuffer();
	System.out.println("Enter In to Dom Creation and master apply in  Corresponding Master...."); 
	System.out.println("Transation for Batch id::::::"+batchid); 
	ResultSet rs = null;
	ResultSet rs1 = null;
	ResultSet dateRs = null;
	PreparedStatement pstmt = null;
	PreparedStatement pstmt1 = null; 
	PreparedStatement psUpdateBl = null;
	PreparedStatement datepstmt = null;
	StringBuffer xmlBuff = null;
	String sql = "";
	String sql1 = "";
	String BachId = "";
	String fldData = "";
	String fldName = "";
	String xmlStrPass = "";
	int objSsl = 0;
	int totObjSl = 0;
	int tranSl = 1;
	int fldNo = 0;
	Document dom = null;
	Connection conect = null;
	int maxTranSl =0;
	String	update = "";
	String xmlStr = "";
	String tableName = "";
	String dateStr = "";
	String tableNameDet1 = " ";
	String tableNameDet2 = " ";
	String tableNameDet3 = " ";
	String collectWin = "";
	ArrayList headerDateFilelds = new ArrayList();
	ArrayList detati1DateFilelds = new ArrayList();
	ArrayList detati2DateFilelds = new ArrayList();
	ArrayList detati3DateFilelds = new ArrayList();
	ArrayList collectFldList = new ArrayList();
	String collectField = "";
	ArrayList pointerList  = null;
	try
	{
		ConnDriver conndriver = new ConnDriver();
   		conect = conndriver.getConnectDB("DriverITM");
     	
	}
	catch(Exception g){}
	java.io.File objFile = new java.io.File (CommonConstants.JBOSSHOME+File.separator+"LOG");
	java.io.File objFile1 = new java.io.File (CommonConstants.JBOSSHOME+File.separator+"XMLCB");
	if(!(objFile.exists()))
	{
		objFile.mkdir();
	}
	
	if(!(objFile1.exists()))
	{
		objFile1.mkdir();
		
	}
	//COLLECTING WINDOW NAME FROM BATCHID AND BATCHLOAD
	try
	{
		collectWin = "SELECT WIN_NAME FROM BATCHLOAD WHERE BATCH_ID=? AND  TRAN_SL = (SELECT MIN(TRAN_SL) FROM BATCHLOAD WHERE BATCH_ID = ?)";
		System.out.println(collectWin);
		pstmt = conn.prepareStatement(collectWin);
		pstmt.setString(1,batchid.trim());
		pstmt.setString(2,batchid.trim());
		rs = pstmt.executeQuery();
		if(rs.next())
		{
			winName = rs.getString(1);
			System.out.println("win_name"+win_name);
		}
		rs.close();
		
	}
	catch(SQLException sexwin) 
	{
		System.out.println("SQLException :[MasterApplyEJB(1)][Excuting Query Failed1]" +collectWin+sexwin.getMessage());
	}
	catch(Exception exwin)
	{
		System.out.println("Exception1(MasterApplyEJB(1)) ::"+collectWin+exwin.getMessage());
		exwin.printStackTrace();
	}
	System.out.println("win_name:::::::::::"+winName);
	System.out.println("BatchId:::::::::::"+batchid);
		
	try
	{
		 collectField = "SELECT A.obj_sl__source,A.FLD_NAME__DEST,A.comp_name ,A.method_name  FROM EDI_CONTROL_DET A, EDI_CONTROL B WHERE A.WIN_NAME = B.WIN_NAME 	AND A.LINE_NO = B.LINE_NO "
		 +"AND B.WIN_NAME = ?	AND B.EDI_MEDIUM = 2 and A.FLD_NO__SOURCE <>0 and comp_name is not  null and  method_name is  not  null ORDER BY A.OBJ_SL__SOURCE,A.FLD_NO__DEST ";
		pstmt = conect.prepareStatement(collectField);
		pstmt.setString(1,winName.trim()); 
		rs = pstmt.executeQuery();
		while(rs.next())
		{
			int  form = 0;
			CbBean collectFiels = new CbBean();
			form = rs.getInt(1);
			form++;
		
			collectFiels.setFormNo(new Integer(form).toString());
			collectFiels.setFldName(rs.getString(2));
			collectFiels.setCompName(rs.getString(3));
			collectFiels.setMethName(rs.getString(4));
			collectFldList.add(collectFiels);
			
		}
		pstmt.close();
	}
	catch(SQLException extc111)
	{
		System.out.println("SQLException :[CreateBatchEJB(TableCreation)][Excuting Query Failed1]" + collectField + extc111.getMessage());
	}
	catch(Exception extc111)
	{
		System.out.println("Exception1(TableCreation) ::"+collectField +extc111.getMessage());
		extc111.printStackTrace();
	}

	//COLLECTIING  TABLE NAME FROM A GIVEN WINDOW
	try
	{
		dateStr = "SELECT TABLE_NAME ,TABLE_NAME_DET1 , TABLE_NAME_DET2 ,TABLE_NAME_DET3 FROM  TRANSETUP  WHERE TRAN_WINDOW = ?";
		datepstmt = conect.prepareStatement(dateStr);
		datepstmt.setString(1,winName.trim()); 
		dateRs = datepstmt.executeQuery();
		if(dateRs.next())
		{
			tableName = dateRs.getString(1);
			tableNameDet1 = dateRs.getString(2);
			tableNameDet2 = dateRs.getString(3);
			tableNameDet3 = dateRs.getString(4);
		}
		datepstmt.close();
	}
	catch(SQLException extc)
	{
				System.out.println("SQLException :[MasterApplyEJB(2)][Excuting Query Failed1]" + dateStr + extc.getMessage());
	}
	catch(Exception extc)
	{
		System.out.println("Exception1(MasterApplyEJB(2)) ::"+dateStr +extc.getMessage());
		extc.printStackTrace();
	}
	System.out.println("HeaderTable Name::::"+tableName);
	System.out.println("Detail Table1:1:::::"+tableNameDet1);
	System.out.println("Detail Table1:2:::::"+tableNameDet2);
	System.out.println("Detail Table1:3::::::"+tableNameDet3);
	//COLLECTING THE DATE FIELD LIST FROM HEADER
	if(tableName != null)
	{
		try
		{
			dateStr = "SELECT * from "+tableName.trim();
			datepstmt = conn.prepareStatement(dateStr);
			dateRs = datepstmt.executeQuery();
			ResultSetMetaData rsmd = dateRs.getMetaData();
	   	 	int numberOfColumns = rsmd.getColumnCount();
	    	for(int colCount =1;colCount<=numberOfColumns;colCount++)
	    	{
	    	
	    		if((rsmd.getColumnType(colCount) == java.sql.Types.DATE )|| (rsmd.getColumnType(colCount)==java.sql.Types.TIMESTAMP))//HARD CODE FOR DATE 91
	     		{
	     			System.out.println("Date field collect...");
					String dateFlds = rsmd.getColumnName(colCount);
					headerDateFilelds.add(dateFlds);
				}
			}
			datepstmt.close();
			
			System.out.println("total date fld in ="+headerDateFilelds);
			
			
		}
	 	catch(SQLException extc1)
		{
			System.out.println("SQLException :[MasterApplyEJB(3)][Excuting Query Failed1]" +dateStr+extc1.getMessage());
		}
		catch(Exception extc1)
		{
			System.out.println("Exception1(MasterApplyEJB(3)) ::"+dateStr+extc1.getMessage());
			extc1.printStackTrace();
		}
	}
	//COLLECTING THE DATE FIELD LIST FROM (DETAIL-1)
	if(tableNameDet1 != null)
	{
	
		try
		{
			dateStr = "SELECT * from "+tableNameDet1.trim();
			datepstmt = conn.prepareStatement(dateStr);
			dateRs = datepstmt.executeQuery();
			ResultSetMetaData rsmd = dateRs.getMetaData();
	   	 	int numberOfColumns = rsmd.getColumnCount();
	    	for(int colCount =1;colCount<=numberOfColumns;colCount++)
	    	{
	    		
	    		if((rsmd.getColumnType(colCount) == java.sql.Types.DATE) || (rsmd.getColumnType(colCount)==java.sql.Types.TIMESTAMP))//HARD CODE FOR DATE 91
	     		{
                     System.out.println("Date field colect...");
					String dateFlds = rsmd.getColumnName(colCount);
					detati1DateFilelds.add(dateFlds);
				}
			}
			datepstmt.close();
			
			System.out.println("Total Date fld in ="+detati1DateFilelds);
			
			
		}
	 	catch(SQLException extc1)
		{
			System.out.println("SQLException :[MasterApplyEJB(4)][Excuting Query Failed1]" +dateStr+extc1.getMessage());
		}
		catch(Exception extc1)
		{
			System.out.println("Exception1(MasterApplyEJB(4)) ::"+dateStr+extc1.getMessage());
			extc1.printStackTrace();
		}
	}
	//COLLECTING THE DATE FIELD LIST FROM (DETAIL-2)
	if(tableNameDet2 != null)
	{
	
		try
		{
			dateStr = "SELECT * from "+tableNameDet1.trim();
			datepstmt = conn.prepareStatement(dateStr);
			dateRs = datepstmt.executeQuery();
			ResultSetMetaData rsmd = dateRs.getMetaData();
	   	 	int numberOfColumns = rsmd.getColumnCount();
	    	for(int colCount =1;colCount<=numberOfColumns;colCount++)
	    	{
	    		
	    		if((rsmd.getColumnType(colCount) == java.sql.Types.DATE )||(rsmd.getColumnType(colCount)== java.sql.Types.TIMESTAMP))//HARD CODE FOR DATE 91
	     		{
	     			System.out.println("Date field collect...");
					String dateFlds = rsmd.getColumnName(colCount);
					detati2DateFilelds.add(dateFlds);
				}
			}
			datepstmt.close();
			
			System.out.println("total date fld in ="+detati2DateFilelds);
			
			
		}
	 	catch(SQLException extc1)
		{
			System.out.println("SQLException :[CreateBatchEJB(MasterApplyEJB(5))][Excuting Query Failed1]" +dateStr+extc1.getMessage());
		}
		catch(Exception extc1)
		{
			System.out.println("Exception1(MasterApplyEJB(5)) ::"+dateStr+extc1.getMessage());
			extc1.printStackTrace();
		}
	}
	//COLLECTING THE DATE FIELD LIST FROM (DETAIL-3)
	if(tableNameDet3 != null)
	{
		try
		{
			dateStr = "SELECT * from "+tableNameDet1.trim();
			datepstmt = conn.prepareStatement(dateStr);
			dateRs = datepstmt.executeQuery();
			ResultSetMetaData rsmd = dateRs.getMetaData();
	   	 	int numberOfColumns = rsmd.getColumnCount();
	    	for(int colCount =1;colCount<=numberOfColumns;colCount++)
	    	{
	    		
	    		if((rsmd.getColumnType(colCount) == java.sql.Types.DATE )|| (rsmd.getColumnType(colCount)==java.sql.Types.TIMESTAMP))//HARD CODE FOR DATE 91
	     		{
	     			System.out.println("Date field collect...");
					String dateFlds = rsmd.getColumnName(colCount);
					detati3DateFilelds.add(dateFlds);
				}
			}
			datepstmt.close();
			
			System.out.println("total date fld in ="+detati3DateFilelds);
		}
	 	catch(SQLException extc1)
		{
			System.out.println("SQLException :[MasterApplyEJB(6)][Excuting Query Failed1]" +dateStr+extc1.getMessage());
		}
		catch(Exception extc1)
		{
			System.out.println("Exception1(MasterApplyEJB(6)) ::"+dateStr+extc1.getMessage());
			extc1.printStackTrace();
		}
	}
	//GET MAX OBJSL (OBJSL=0 HEADER  OTHERWISE DTL )FOR A WINDOW
	sql="SELECT MAX(EDI_CONTROL_DET.OBJ_SL__SOURCE) + 1 FROM EDI_CONTROL_DET,EDI_CONTROL "
		+" WHERE ( EDI_CONTROL_DET.WIN_NAME = ? ) AND "
		+"( EDI_CONTROL.WIN_NAME = EDI_CONTROL_DET.WIN_NAME ) AND "
		+"( EDI_CONTROL.LINE_NO = EDI_CONTROL_DET.LINE_NO ) AND "
		+"( EDI_CONTROL.EDI_MEDIUM = 2 )";
		try
		{
			pstmt = conect.prepareStatement(sql);
			pstmt.setString(1,winName.trim()); 
			rs = pstmt.executeQuery(); 
			if(rs.next())
			{
				totObjSl = rs.getInt(1);	
			}
			rs.close();
			pstmt.close();
		}
		catch(SQLException se)
		{
			System.out.println("SQLException :[MasterApplyEJB(7)][Excuting Query Failed1]" + sql + se.getMessage());
		}
		catch(Exception ex)
		{
			System.out.println("Exception1 ::(MasterApplyEJB(7))"+sql +ex.getMessage());
			ex.printStackTrace();
		}
		System.out.println("MAX OF DATAWINDOW (totObjSl):"+totObjSl);
		sql = "";
		
		//GETTING MAX HEADER FOR A PARTICULAR WINDOW
		String sqlmax="SELECT MAX(TRAN_SL) FROM BATCHLOAD WHERE WIN_NAME= ? AND BATCH_ID= ? ";
		try
		{
			pstmt = conect.prepareStatement(sqlmax);
			pstmt.setString(1,winName.trim()); 
			pstmt.setString(2,batchid.trim());
			rs = pstmt.executeQuery(); 
			if(rs.next())
			{
				maxTranSl = rs.getInt(1);
			}
			rs.close();
			pstmt.close();
		}
		catch(SQLException se33)
		{
			
			System.out.println("SQLException :[MasterApplyEJB(8)][Excuting Query Failed1]" + sql + se33.getMessage());
		}
		catch(Exception ex33)
		{
		
			System.out.println("Exception1 (MasterApplyEJB(8))::"+sql +ex33.getMessage()); 
			ex33.printStackTrace();
		}
		System.out.println("MAX OF HEADER (maxTranSl):"+maxTranSl);
		tran_sl = maxTranSl;
		logBuff.append(	"<?xml version='1.0' encoding='UTF-8'?>\n").append("<Root>\n");
		logBuff.append("<Header>");
		logBuff.append("<win_name>").append(winName).append("</win_name>");
		logBuff.append("<batch_id>").append(batchid).append("</batch_id>");
		
		for(int transl = 1 ; transl<=maxTranSl;transl++)//maxTranSl
		{			String TranID = "";
			int totalDetRec = 0;
			String errMsg= "";
			String loadStatus = "";
			String tranTag = "<TranSl  domID=\""+transl+"\" >"; 
			logBuff.append(tranTag);
			 xmlBuff =new StringBuffer();
			System.out.println("total no of objsl="+totObjSl);
			xmlBuff.append(	"<?xml version='1.0' encoding='UTF-8'?>\n").append("<Root>\n");
			xmlBuff.append("<DocumentRoot>");
			xmlBuff.append("<description>").append("Datawindow Root").append("</description>");
			xmlBuff.append("<group0>");
			xmlBuff.append("<description>").append("Group0 description").append("</description>");
			xmlBuff.append("<Header0>");
			xmlBuff.append("<objName><![CDATA[").append("charge_back").append("]]></objName>");
			xmlBuff.append("<pageContext><![CDATA[").append("1").append("]]></pageContext>");
			xmlBuff.append("<objContext><![CDATA[").append("1").append("]]></objContext>");
			xmlBuff.append("<editFlag><![CDATA[").append("A").append("]]></editFlag>");
			xmlBuff.append("<focusedColumn><![CDATA[").append("").append("]]></focusedColumn>");
			xmlBuff.append("<action><![CDATA[").append("SAVE").append("]]></action>");
			xmlBuff.append("<elementName><![CDATA[").append("").append("]]></elementName>");
			xmlBuff.append("<keyValue><![CDATA[").append("1").append("]]></keyValue>");
			xmlBuff.append("<taxKeyValue><![CDATA[").append("").append("]]></taxKeyValue>");
			xmlBuff.append("<saveLevel><![CDATA[").append("1").append("]]></saveLevel>");
			xmlBuff.append("<forcedSave><![CDATA[").append(true).append("]]></forcedSave>");
			xmlBuff.append("<taxInFocus><![CDATA[").append(false).append("]]></taxInFocus>");
			xmlBuff.append("<description>").append("Header0 members").append("</description>");
			objSsl = 0;
		//GET MAX OBJ_SSL FOR A HEADER(THAT HOW MANY DETAIL RECORD FOR A PARTICULAR HEADER RECORD)		
		sql = "SELECT MAX(BATCHLOADDET.OBJ_SSL) FROM BATCHLOADDET,BATCHLOAD WHERE BATCHLOAD.BATCH_ID=BATCHLOADDET.BATCH_ID AND BATCHLOAD.TRAN_SL=BATCHLOADDET.TRAN_SL AND BATCHLOAD.WIN_NAME=? "
		+ " AND BATCHLOAD.TRAN_SL=?   AND BATCHLOAD.BATCH_ID= ?";
		try
		{
			pstmt = conect.prepareStatement(sql);
			pstmt.setString(1,winName.trim()); 
			pstmt.setInt(2,tranSl); 
			pstmt.setString(3,batchid.trim()); 
			rs = pstmt.executeQuery(); 
			if(rs.next())
			{
				objSsl = rs.getInt(1);	
			}
			System.out.println("TOTAL DETAIL OF HEADER =("+transl+")IS("+objSsl+")");
			rs.close();
			pstmt.close();
		}
		catch(SQLException se11)
		{
			try{conect.rollback();}catch(Exception see){}
			System.out.println("SQLException :[MasterApplyEJB(9)][Excuting Query Failed1]" + sql + se11.getMessage());
		}
		catch(Exception ex11)
		{
			try{conect.rollback();}catch(Exception exe){}
			System.out.println("Exception1 (MasterApplyEJB(9))::"+sql +ex11.getMessage());
			ex11.printStackTrace();
		}
		//LOOP FOR NO OF TOTAL DATAWINDOW(HEADER + DETAIL)
		for(int ctr = 0 ; ctr<totObjSl;ctr++)
		{
			int temp = ctr+1; 
			//CONDITION FOR HEADER OBJSL=0
			if(temp == 1)
			{
				System.out.println("HEADER OF TRANSL :"+transl);
				String tag = "<Detail1 dbID=\"\" domID=\""+transl+"\" objName=\"charge_back\" objContext=\"1\" >"; 
				
				xmlBuff.append(tag);
				String tag1 = "<attribute pkNames=\"\" status=\"N\" updateFlag=\"A\" selected=\"N\" />";
				xmlBuff.append(tag1);
				xmlBuff.append("<tran_id/>");
				try 
				{		
					//GETTING FIELD VALUE FOR ALL THE FIELD FOR A PARTICULAR TRANSL ,OBJSSL(1,0.1.2...MAX)
					sql = "SELECT BATCHLOAD.BATCH_ID,BATCHLOADDET.FLD_NO,BATCHLOADDET.FLD_DATA  FROM BATCHLOAD,BATCHLOADDET"
						+" WHERE BATCHLOAD.BATCH_ID=BATCHLOADDET.BATCH_ID  AND BATCHLOAD.TRAN_SL=BATCHLOADDET.TRAN_SL AND BATCHLOAD.WIN_NAME = ? "
						+ "AND BATCHLOADDET.OBJ_SL= ? AND BATCHLOAD.TRAN_SL=?   and BATCHLOAD.BATCH_ID= ? ";
						pstmt = conect.prepareStatement(sql);
						pstmt.setString(1,winName);
						pstmt.setInt(2,ctr);
						pstmt.setInt(3,transl); 
						pstmt.setString(4,batchid.trim()); 						
						rs = pstmt.executeQuery();
						while(rs.next())
						{ 
							BachId = rs.getString(1);
							fldNo = rs.getInt(2);
							fldData = rs.getString(3);
				
							try
							{ 
								//GETTING THE FILED NAME FOR A PARTICULAR FILED
								sql1 = "SELECT FLD_NAME__DEST  FROM EDI_CONTROL_DET A, EDI_CONTROL B WHERE A.WIN_NAME = B.WIN_NAME 	AND A.LINE_NO = B.LINE_NO"
									+" AND B.WIN_NAME = ?	AND A.OBJ_SL__SOURCE =? "
									+" AND B.EDI_MEDIUM = 2 and A.FLD_NO__SOURCE <>0 and A.FLD_NO__SOURCE = ? ORDER BY A.OBJ_SL__SOURCE,A.FLD_NO__DEST ";
									pstmt1 = conect.prepareStatement(sql1);
									pstmt1.setString(1,winName);
									pstmt1.setInt(2,ctr);
									pstmt1.setInt(3,fldNo);
									rs1 = pstmt1.executeQuery();
									if(rs1.next())
									{
										fldName = rs1.getString(1);	
									}
                                                                        
									fldName = fldName.toLowerCase();
										//IF FILED IS DATE THEN CONVERT IN TO APPDATE FORMAT
										for(int dateFldCount = 0;dateFldCount<headerDateFilelds.size();dateFldCount++)
										{
												String dateFld = (String)headerDateFilelds.get(dateFldCount);
												if(fldName.trim().equalsIgnoreCase(dateFld.trim()))  
												{
														System.out.println("find........");
														Object date = null;
														System.out.println("Field data="+fldData);
														System.out.println("Db date format="+fldData);
														SimpleDateFormat sdf = new SimpleDateFormat(genericUtility.getDBDateFormat());
														date = sdf.parse(fldData);
														SimpleDateFormat sdf1 = new SimpleDateFormat(genericUtility.getApplDateFormat());
														fldData=sdf1.format(date).toString();
														System.out.println("application date format="+fldData);
													
				
													}
													
										}
								     	
									xmlBuff.append("<").append(fldName).append(">").append("<![CDATA[").append(fldData.trim()).append("]]>").append("<").append("/").append(fldName).append(">");
									rs1.close();
									pstmt1.close(); 
									
							}
							catch(SQLException se3)
							{
								System.out.println("SQLException :[MasterApplyEJB(10)][Excuting Query Failed2]" + sql1 + se3.getMessage());
							}
							catch(Exception ex3)
							{
								System.out.println("Exception2(MasterApplyEJB(10)) ::"+sql1+ex3.getMessage());
								ex3.printStackTrace();
							}
						}
						String end = "</Detail1>";
						xmlBuff.append(end); 
						rs.close();
						pstmt.close();
				}    
				catch(SQLException se1) 
				{
					System.out.println("SQLException :[MasterApplyEJB(11)][Excuting Query Failed3]" + sql + se1.getMessage());
				}
				catch(Exception ex1)
				{
					System.out.println("Exception3 (MasterApplyEJB(11))::"+sql +ex1.getMessage());
					ex1.printStackTrace();
				}
			}
			else
			{
				//FOR DETAIL LOOP FOR NO OF RECORD IN DETAIL
				for(int j=1;j<=objSsl;j++) //objSsl
				{
					pointerList = new ArrayList();
					if(j==1)
					{
						pointerList = detati1DateFilelds;
					}
					if(j==2)
					{
						pointerList = detati2DateFilelds;
					}
					if(j==3)
					{
						pointerList = detati3DateFilelds;
					}
					
					System.out.println("detail(" +j+")of" +"HEADER :"+transl);
					String tag = "<Detail"+temp;
					tag = tag +" dbID=\"\" domID=\""+j+"\" objName=\"charge_back\"  objContext=\"2\""+">";
					xmlBuff.append(tag);
					xmlBuff.append("<attribute  pkNames=\"tran_id:line_no:\" status=\"N\" updateFlag=\"A\" selected=\"N\"/>");
					xmlBuff.append("<tran_id><![CDATA[").append("").append("]]></tran_id>");
					xmlBuff.append("<line_no><![CDATA[").append(j).append("]]></line_no>");
					
					try
					{	//GETTING FIELD VALUE FOR ALL THE FIELD FOR A PARTICULAR TRANSL 
						sql = "SELECT BATCHLOAD.BATCH_ID,BATCHLOADDET.FLD_NO,BATCHLOADDET.FLD_DATA  FROM BATCHLOAD,BATCHLOADDET"
							+" WHERE BATCHLOAD.BATCH_ID=BATCHLOADDET.BATCH_ID  AND BATCHLOAD.TRAN_SL=BATCHLOADDET.TRAN_SL AND BATCHLOAD.WIN_NAME = ? "
							+ "AND BATCHLOADDET.OBJ_SL= ? AND BATCHLOAD.TRAN_SL=? and BATCHLOADDET.OBJ_SSL=? AND BATCHLOAD.BATCH_ID= ?  ";
							pstmt = conect.prepareStatement(sql);
							pstmt.setString(1,winName);
							pstmt.setInt(2,ctr);
							pstmt.setInt(3,transl); 
							pstmt.setInt(4,j);
							pstmt.setString(5,batchid.trim());
						
							rs = pstmt.executeQuery();
							while(rs.next())
							{ 
								BachId = rs.getString(1);
								fldNo = rs.getInt(2);
								fldData = rs.getString(3);
					
								try
								{ 
									sql1 = "SELECT FLD_NAME__DEST  FROM EDI_CONTROL_DET A, EDI_CONTROL B WHERE A.WIN_NAME = B.WIN_NAME 	AND A.LINE_NO = B.LINE_NO"
										+" AND B.WIN_NAME = ?	AND A.OBJ_SL__SOURCE =? "
										+" AND B.EDI_MEDIUM = 2 and A.FLD_NO__SOURCE <>0 and A.FLD_NO__SOURCE = ? ORDER BY A.OBJ_SL__SOURCE,A.FLD_NO__DEST ";
										pstmt1 = conect.prepareStatement(sql1);
										pstmt1.setString(1,winName);
										pstmt1.setInt(2,ctr);
										pstmt1.setInt(3,fldNo);
										rs1 = pstmt1.executeQuery();
								
										if(rs1.next())
										{
											fldName = rs1.getString(1);	
										}
										fldName = fldName.toLowerCase();
										//IF FILED IS DATE THEN CONVERT IN TO APPDATE FORMAT
										for(int dateFldCount = 0;dateFldCount<pointerList.size();dateFldCount++)
										{
												String dateFld = (String)pointerList.get(dateFldCount);
												if(fldName.trim().equalsIgnoreCase(dateFld.trim()))  
												{
														System.out.println("find........");
														Object date = null;
														System.out.println("Field data="+fldData);
														System.out.println("Db date format="+fldData);
														SimpleDateFormat sdf = new SimpleDateFormat(genericUtility.getDBDateFormat());
														date = sdf.parse(fldData);
														SimpleDateFormat sdf1 = new SimpleDateFormat(genericUtility.getApplDateFormat());
														fldData=sdf1.format(date).toString();
														System.out.println("application date format="+fldData);
													
				
													}
													
										}
										xmlBuff.append("<").append(fldName).append(">").append("<![CDATA[").append(fldData.trim()).append("]]>").append("<").append("/").append(fldName).append(">");
										pstmt1.close();
								}
								catch(SQLException se3)
								{
									System.out.println("SQLException :[MasterApplyEJB(12)][Excuting Query Failed2]" + sql1 + se3.getMessage());
								}
								catch(Exception ex3)
								{
									System.out.println("Exception2(MasterApplyEJB(12)) ::"+sql1+ex3.getMessage());
									ex3.printStackTrace();
								}
							}
							String end = "</Detail"+temp+">";
							xmlBuff.append(end);
							rs.close();
							pstmt.close();
					}    
					catch(SQLException se1)
					{
						System.out.println("SQLException :[MasterApplyEJB(13)][Excuting Query Failed3]" + sql + se1.getMessage());
					}
					catch(Exception ex1)
					{
						System.out.println("Exception3 (MasterApplyEJB(13))::"+sql +ex1.getMessage());
						ex1.printStackTrace();
					}
				}
			
			}		
				
		}//end of for
			xmlBuff.append("</Header0>");
			xmlBuff.append("</group0>");
			xmlBuff.append("</DocumentRoot>");
			xmlBuff.append("</Root>\r\n");
			try 
			{
					//System.out.println("Before modifying:::::::::::::"+xmlBuff.toString());
					 xmlStrPass = xmlBuff.toString();
					 System.out.println("passing xmlString is::::::::"+xmlStrPass);
					System.out.println("Size:::"+collectFldList.size());
					

						for(int count = 0;count<collectFldList.size();count++)
						{ 
							System.out.println("call the ejb "+ count +"times");
							
							CbBean collectFiels = (CbBean)collectFldList.get(count);
							//	String methodStr = "replaceVal";
							//String classStr = "ibase.webitm.ejb.dis.ChargeBackEJB";
							System.out.println("[component:"+collectFiels.getCompName().trim()+"]");
							System.out.println("[Field:"+collectFiels.getFldName().trim()+"]");
							System.out.println("[Method:"+collectFiels.getMethName().trim()+"]");
							System.out.println("[Form:"+collectFiels.getFormNo().trim()+"]");
							Class cobj = Class.forName(	collectFiels.getCompName().trim()); 
							Class stringClass= Class.forName("java.lang.String");
							Class[] paramSpec = new Class[4];
							paramSpec[0] = stringClass;
							paramSpec[1] = stringClass; 
							paramSpec[2] = stringClass;
							paramSpec[3] = stringClass;
							String params[] = new String[4];
							params[0] = xmlStrPass;
							params[1] = collectFiels.getFldName().trim();;
							params[2] = collectFiels.getFormNo().trim();
							params[3] = xtraParam;
							
							java.lang.reflect.Method metObj = cobj.getMethod(collectFiels.getMethName().trim(),paramSpec);
							metObj.setAccessible(true);
							xmlStr = (String)metObj.invoke(cobj.newInstance(), params);	
							xmlStrPass = xmlStr; 
							
						}
					
				
					System.out.println("xmlStr::::::::::::::::::"+xmlStrPass);
					FileOutputStream	fos1 = new FileOutputStream(CommonConstants.JBOSSHOME + File.separator +"XMLCB"+File.separator+"CB"+transl+batchid+".xml");
					byte convertStringToByte1[] = xmlStrPass.getBytes();
					fos1.write(convertStringToByte1);
					fos1.close();
			} 
			catch(Exception e) 
			{ 
				System.out.println("Exception : [MasterApplyEJB(14)][getErrorString] \n:==>"+e.getMessage());
				e.printStackTrace();
			}
		//	System.out.println("Before Update:::::::"+xmlBuff);
			String errMessage = null;
			try
			{
				
				String errStr = saveData(xmlStrPass);
				System.out.println("After update:::::::"+errStr);
				DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
				DocumentBuilder db = dbf.newDocumentBuilder(); 
				OutputStreamWriter errorWriter = new OutputStreamWriter(System.err, "UTF-8");//writes the thing with the specific format hardcoded
				ByteArrayInputStream baos = new ByteArrayInputStream(errStr.getBytes()); 
				dom = db.parse(baos);
				Node  parentNode = dom.getElementsByTagName("Error").item(0);
				if(parentNode != null)
				{
					NodeList childNodeList = parentNode.getChildNodes();
					int	childNodeListLength = childNodeList.getLength();
			
					for (int childRow = 0; childRow < childNodeListLength; childRow++)
					{
				
						Node childNode = childNodeList.item(childRow);
						String childNodeName = childNode.getNodeName();
				
						if (childNodeName.equals("message"))
						{
							 errMessage = (childNode.getFirstChild().getNodeValue()).trim();
							System.out.println("Message::::: "+ errMessage);	
						}
					}
					System.out.println("message::::::::::"+ errMessage);			
				}
			}
			catch(Exception g)
			{
				System.out.println(g.getMessage());
			}
			if(errMessage != null)
			{
					update = "";
				loadStatus = "N";
				errMsg = errMessage;
				//<Root><Detail>Success</Detail><TranID>0000001405</TranID></Root>
				try
				{ 
					update = "UPDATE  BATCHLOAD SET  ERROR_MSG  = ? WHERE BATCH_ID =? AND TRAN_SL= ? ";		
					psUpdateBl = conect.prepareStatement(update);
					psUpdateBl.setString(1,errMessage);
					psUpdateBl.setString(2,batchid.trim());				
					psUpdateBl.setInt(3,transl);
					psUpdateBl.executeUpdate();
					psUpdateBl.close();
				}
				catch(SQLException seUpdate)
				{
					System.out.println("SQLException(Update Batchload) :[domCreation][Excuting Query Failed ]" + update + seUpdate.getMessage());
				}
				catch(Exception exUpdate)
				{
					System.out.println("Exception3(Update Batchload) ::"+update +exUpdate.getMessage());
					exUpdate.printStackTrace();
				}
	
			}
			else
			{
				loadStatus = "Y";
				try
				{
					 TranID = "";
					//String xmlStr="<Root><Detail>Success</Detail><TranID>0000001405</TranID></Root>";
					NodeList parentNodeList = dom.getElementsByTagName("Root");
					Node parentNode = parentNodeList.item(0);
					NodeList childNodeList = parentNode.getChildNodes();
					int ctr = 0;
					int childNodeListLength = childNodeList.getLength();
					for (int childRow = 0; childRow < childNodeListLength; childRow++)
					{
						Node childNode = childNodeList.item(childRow);
						String childNodeName = childNode.getNodeName();
						if (childNodeName.equals("TranID"))
						{
							TranID = (childNode.getFirstChild().getNodeValue()).trim();
							
						}
					}
				System.out.println("tran_id="+TranID);
				
			}
			catch(Exception e){System.out.println(e.getMessage());}
			
			try
			{ 
				update = "";
				update = "UPDATE  BATCHLOAD SET  LOAD_STAT = 'Y' , LOAD_DATE = ?  WHERE BATCH_ID =? AND TRAN_SL=? ";	
				java.sql.Timestamp ts=new java.sql.Timestamp(System.currentTimeMillis());
			 	SimpleDateFormat sdt=new SimpleDateFormat(genericUtility.getDBDateFormat());
				psUpdateBl = conect.prepareStatement(update);
				psUpdateBl.clearParameters();
				psUpdateBl.setDate(1,java.sql.Date.valueOf(sdt.format(ts)));
				psUpdateBl.setString(2,batchid.trim());
				psUpdateBl.setInt(3,transl);
				int rec = psUpdateBl.executeUpdate();
				psUpdateBl.close();
				System.out.println("No of record Update = "+rec);
			}
			catch(SQLException seUpdate)
			{
				System.out.println("SQLException(Update Batchload) :[domCreation][Excuting Query Failed ]" + update + seUpdate.getMessage());
			}
			catch(Exception exUpdate)
			{
				System.out.println("Exception3(Update Batchload) ::"+update +exUpdate.getMessage());
				exUpdate.printStackTrace();
			}
		}
		logBuff.append("<tran_id>").append(TranID).append("</tran_id>");
		logBuff.append("<total_det>").append(totalDetRec).append("</total_det>");
		logBuff.append("<load_status>").append(loadStatus).append("</load_status>");
		logBuff.append("<err_msg>").append(errMsg).append("</err_msg>");
		logBuff.append("</TranSl>");
	
	}//end of transl
	logBuff.append("</Header>"); 
	logBuff.append("</Root>"); 
	try 
	{ 
		//WRITING IN THE XMLSTRING(LOG) IN A FILE
		FileOutputStream	fos11 = new FileOutputStream(CommonConstants.JBOSSHOME + File.separator +"LOG"+File.separator+ "LOG"+batchid+".xml");
		byte convertStringToByte11[] = logBuff.toString().getBytes();
		fos11.write(convertStringToByte11);
		fos11.close();
	} 
	catch(Exception e)
	{ 
		System.out.println("Exception : [CreateEJB][getErrorString] \n:==>"+e.getMessage());
		e.printStackTrace();
	}

	System.out.println("END OF MASTER APPLY......");
}//end of dom creation
	private String saveData(String xmlString)throws ITMException
	{
		  System.out.println("saving data...........");
		  InitialContext ctx = null;
		  String retString = null;
		  MasterStatefulLocal masterStateful =null;
		  try
		  {
			   AppConnectParm appConnect = new AppConnectParm();
			   ctx = new InitialContext(appConnect.getProperty());
			    masterStateful = (MasterStatefulLocal)ctx.lookup("ibase/MasterStatefulEJB/local");
			   //MasterStateful masterStateful = masterStatefulHome.create();
			   String [] authencate = new String[2];
			   authencate[0] = userId;
			   authencate[1] = userId;
			   retString = masterStateful.processRequest(authencate, logInSite, true, xmlString);
		 }
		 catch(ITMException itme)
		 {
		   System.out.println("ITMException :FeedBackServlet :saveData :==>");
			throw itme;
		 }
		 catch(Exception e)
		 {
		  	System.out.println("Exception :FeedBackServlet :saveData :==>");
			throw new ITMException(e);
		 }
	  	 return retString;
	}
	
}//END OF EJB

	