package ibase.webitm.ejb;

import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.StringReader;
import java.io.StringWriter;
import java.rmi.RemoteException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.Vector;

import javax.annotation.PostConstruct;
import javax.ejb.SessionContext;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.ChannelSftp.LsEntry;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.bson.types.ObjectId;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

//import ibase.dirPath;
import ibase.scheduler.ejb.BaseRegisteredEJB;
import ibase.scheduler.utility.interfaces.Schedule;
import ibase.system.config.ConnDriver;
import ibase.system.config.nosql.NoSQLConnDriver;
import ibase.system.config.resource.NoSQLConnection;
import ibase.utility.BaseLogger;
import ibase.utility.CommonConstants;
import ibase.utility.E12GenericUtility;
import ibase.utility.EMail;
import ibase.utility.JSONtoXMLConverter;
import ibase.utility.MongoDBHandler;
import ibase.utility.UserInfoBean;
import ibase.webitm.utility.ITMException;
import ibase.webitm.utility.UploadTemplateMapping;
import ibase.webitm.utility.ValidateXMLInput;
import ibase.webitm.utility.VisionEDIUtility;
import ibase.webitm.utility.X12toXmlGenerator;
import ibase.webitm.utility.XLS2XMLGenerator;

@javax.ejb.Stateless 
public class ITMUploadFileEJB extends BaseRegisteredEJB implements ITMUploadFileRemote,ITMUploadFileLocal, Schedule //implements SessionBean 
{
	public String globalTranID = ""; //Added by Gagan B. on 17th-FEB-23 to share tranId with setDataAndConfirm API.
	private E12GenericUtility genericUtility = new E12GenericUtility();
	private DBAccessEJB dbAccess = null;
	private File DUMP_DIR = null;
	protected ibase.utility.UserInfoBean userInfo = null;

	//added by vishal on 14.5.17 for enterprise implementation in for file upload ejb. Start.
	private boolean IS_FTP_PATH = false;
	private String FILE_UPLOAD_SRC_PATH = "";
	private String FILE_UPLOAD_REJ_PATH = "";
	private String FILE_UPLOAD_SUCC_PATH = "";
	private String FILE_UPLOAD_LOG_PATH = "";
	private String FTP_HOST_URL = "";
	private String ftpUserName = "";
	private String ftpPassword = "";
	private FTPClient ftpClient = null ;
	//added by vishal on 14.5.17 for enterprise implementation in for file upload ejb. End.
	//added by Amey W on 8.10.18 for SFTP connection for file transfer. START.
	private boolean IS_SFTP_PATH = false;
	private String fileUploadPort = "";
	private ChannelSftp sftpChannel = null ;
	private Session session = null;
	//added by Amey W on 8.10.18 for SFTP connection for file transfer. End.
	private String mailAddr = "";
	//Added by Ravindra C on 19/02/2021 [to set common upload success and failed path]
	private String commonUploadFailedFilePath = "";
	private String commonUploadSuccessFilePath = "";

	public void setSessionContext(SessionContext sessionContext) {}

	public ITMUploadFileEJB() 
	{
		try
		{
			setDefaultParms();
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
	}
	
	@PostConstruct
	public void ejbCreate()
	{
		try
		{
			setDefaultParms();
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}			
	}

	public void ejbActivate() {}
	public void ejbPassivate() {}
	public void ejbRemove() {}
	
	private void setDefaultParms()
	{
		//added by vishal on 14.5.17 for enterprise implementation in for file upload ejb.Start
		IS_FTP_PATH = false;
		FILE_UPLOAD_SRC_PATH = "";
		FILE_UPLOAD_REJ_PATH = "";
		FILE_UPLOAD_SUCC_PATH = "";
		FILE_UPLOAD_LOG_PATH = "";
		FTP_HOST_URL = "";
		ftpUserName = "";
		ftpPassword = "";
		ftpClient = null;
		userInfo = null;
		mailAddr = "";
		
		fileUploadPort = "";
		IS_SFTP_PATH = false;

		if( FILE_UPLOAD_SRC_PATH.length() > 0 )
		{
			DUMP_DIR = new File( ( new File( FILE_UPLOAD_SRC_PATH ) ) + "" ); 
		}//added by vishal on 14.5.17 for enterprise implementation in for file upload ejb.End
		else
		{
			DUMP_DIR = new File( ( new File( CommonConstants.UPLOAD_LOC ) ) + File.separator + "dump" ); //$NON-NLS-1$
		}
		BaseLogger.log("3", userInfo,null, "DUMP_DIR : ["+ DUMP_DIR +"]" );
		if( ! DUMP_DIR.exists() )
		{
			DUMP_DIR.mkdirs();
		}
		//Added by Ravindra C on 19/02/2021 [to set common upload success and failed path]
		commonUploadFailedFilePath = ( new File( CommonConstants.UPLOAD_LOC ) ) + File.separator + "upload_failed";
		commonUploadSuccessFilePath = ( new File( CommonConstants.UPLOAD_LOC ) ) + File.separator + "upload_success";
	}

	public String schedule( HashMap map )throws RemoteException, ITMException
	{
		return ""; //$NON-NLS-1$
	}

	public String schedulePriority( String wrkflwPriority )throws RemoteException, ITMException
	{
		return schedule(""); //$NON-NLS-1$
	}

	public String schedule( String scheduleParamXML )throws RemoteException, ITMException
	{
		try
		{
			BaseLogger.log( "3", userInfo, null, "scheduleParamXML ["+ scheduleParamXML +"]" ); //$NON-NLS-1$ //$NON-NLS-2$
			Document paramDom = genericUtility.parseString( scheduleParamXML );			
			String userInfoList = genericUtility.serializeDom(paramDom.getElementsByTagName("USERINFOXML").item(0).getChildNodes().item(0)); //$NON-NLS-1$
			UserInfoBean userInfo = new ibase.utility.UserInfoBean( userInfoList );
			this.userInfo = userInfo;

			//added by vishal on 14.5.17 for [enterprise implementation in for file upload ejb]Start.
			setEnterpriseWiseUploadPath( userInfo );
			if( FILE_UPLOAD_SRC_PATH.length() > 0 )
			{
				//Changed by Amey on 29/10/18 [SFTP implementation related changes]
				if( IS_FTP_PATH || IS_SFTP_PATH )
				{
					DUMP_DIR = new File( ( new File( CommonConstants.UPLOAD_LOC ) ) + File.separator + "dump" );//$NON-NLS-1$
				}
				else
				{
					DUMP_DIR = new File( ( new File( FILE_UPLOAD_SRC_PATH ) ) + "" );
				}
				if ( ! DUMP_DIR.exists() )
				{
					DUMP_DIR.mkdirs();
				}
			}
			//added by vishal on 14.5.17 for [enterprise implementation in for file upload ejb]End.

			NodeList paramList = paramDom.getElementsByTagName( "ACTUALPARAMETER" ); //$NON-NLS-1$

			String userInfoStr = ""; //$NON-NLS-1$
			String newFileName = ""; //$NON-NLS-1$
			String isIntractive = ""; //$NON-NLS-1$
			String objName = ""; //$NON-NLS-1$
			String oriFileName = ""; //$NON-NLS-1$
			//Added by Ravindra C on 27/02/2021 [add app_id to identify the source]
			String appId = "";
			boolean isExcelDriver = false;
			//Added by Prasad on 13/12/2020 [set dynamic value to isRetainPkValue]
			boolean isRetainPkValue = false;
			//Added by Ravindra C on 13/12/2020 [apply template while uploading data through scheduler]
			String templateName = "";

			int noOfParam = paramList.getLength();
			for( int paramCnt = 0; paramCnt < noOfParam; paramCnt++ )
			{
				String value = ( String )( paramList.item( paramCnt ).getFirstChild().getNodeValue() );
				value = ( value == null || value.length() == 0  || value.equalsIgnoreCase( "null" ) ) ? "" : value; //$NON-NLS-1$ //$NON-NLS-2$

				if( paramCnt == 0 )
				{
					userInfoStr = value;
				}
				else if( paramCnt == 1 )
				{
					newFileName = value;
				}
				else if( paramCnt == 2 )
				{
					isIntractive = value;
				}
				else if( paramCnt == 3 )
				{
					objName = value;
				}
				else if( paramCnt == 4 )
				{
					oriFileName = value;
				}
				else if( paramCnt == 6 )
				{
					if( value.length() == 0 )
					{
						value = "false"; //$NON-NLS-1$
					}
					isExcelDriver = Boolean.valueOf( value );
				}
				//Added by Ravindra C on 13/01/2021 [apply template while uploading data through scheduler]
				else if( paramCnt == 7 )
				{
					templateName = value;
				}
				//Added by Ravindra C on 27/02/2021 [add app_id to identify the source] START
				else if( paramCnt == 8 )
				{
					appId = value;
				}
				//Added by Ravindra C on 27/02/2021 [add app_id to identify the source] END
				//Added by Prasad on 13/01/2021 [set dynamic value to isRetainPkValue] START
				else if( paramCnt == 9 )
				{
					if( value.length() == 0 )
					{
						value = "false"; //$NON-NLS-1$
					}
					isRetainPkValue = Boolean.valueOf( value );
				}
				//Added by Prasad on 13/01/2021 [set dynamic value to isRetainPkValue] END
			}
			BaseLogger.log( "3", userInfo, null, "userInfoStr ["+ userInfoStr +"]" );
			BaseLogger.log( "3", userInfo, null, "newFileName ["+ newFileName +"]" );
			BaseLogger.log( "3", userInfo, null, "isIntractive ["+ isIntractive +"]" );
			BaseLogger.log( "3", userInfo, null, "objName ["+ objName +"]" );
			BaseLogger.log( "3", userInfo, null, "oriFileName ["+ oriFileName +"]" );
			BaseLogger.log( "3", userInfo, null, "isExcelDriver ["+ isExcelDriver +"]" );
			BaseLogger.log( "3", userInfo, null, "templateName ["+ templateName +"]" );
			BaseLogger.log( "3", userInfo, null, "appId ["+ appId +"]" );
			BaseLogger.log( "3", userInfo, null, "isRetainPkValue ["+ isRetainPkValue +"]" );
			
			//Added by Prasad on 08/01/2021 [file write related implementation for success factor] START
			if ( "EDI_BATCHLOAD".equalsIgnoreCase( newFileName ) )
			{
				//Changed by Ravindra C on 27/02/2021 [add app_id to identify the source] START
				String[] fileInfoArr = new String[7];
				fileInfoArr[0] = isIntractive;
				fileInfoArr[1] = newFileName;
				fileInfoArr[2] = objName;
				fileInfoArr[3] = oriFileName;
				fileInfoArr[4] = templateName;
				fileInfoArr[5] = appId;
				fileInfoArr[6] = ""+ isRetainPkValue;
				
				processEDIBatchload( fileInfoArr );
				//Changed by Ravindra C on 27/02/2021 [add app_id to identify the source] END
			}
			//Added by Prasad on 08/01/2021 [file write related implementation for success factor] END
			else
			{
				if ( newFileName != null && newFileName.trim().length() > 0 )
				{
					if ( ( new File( newFileName ) ).isAbsolute() )
					{
						DUMP_DIR = new File( newFileName );
					}
					else
					{
						if ( newFileName.indexOf( "." ) == 0 ) //$NON-NLS-1$
						{
							if( FILE_UPLOAD_SRC_PATH.length() > 0 && ! IS_FTP_PATH && ! IS_SFTP_PATH )
							{
								DUMP_DIR = new File( new File( FILE_UPLOAD_SRC_PATH ) + File.separator + new File( newFileName ) ); //$NON-NLS-1$
							}
							else
							{
								DUMP_DIR = new File( new File( CommonConstants.DUMP_DIR ) + File.separator + new File( newFileName ) ); //$NON-NLS-1$
							}
						}
					}
				}
				//changed by vishal on 14.5.17 for [enterprise implementation in for file upload ejb]Start.
				if( IS_FTP_PATH )
				{
					//Changed by Prasad on 13/01/2021 [set dynamic value to isRetainPkValue]
					readFilesByFTP( DUMP_DIR, userInfo, isIntractive, objName, oriFileName, isExcelDriver, isRetainPkValue );
				}
				//changed by vishal on 14.5.17 for [enterprise implementation in for file upload ejb]End.
				//Changed by Amey on 29/10/18 [SFTP implementation related changes] START
				else if ( IS_SFTP_PATH )
				{
					//Changed by Prasad on 13/01/2021 [set dynamic value to isRetainPkValue]
					readFilesBySFTP( DUMP_DIR, userInfo, isIntractive, objName, oriFileName, isExcelDriver, isRetainPkValue );
				}
				//Changed by Amey on 29/10/18 [SFTP implementation related changes] END
				else
				{
					if ( newFileName != null && newFileName.indexOf( "." ) > 0 ) //$NON-NLS-1$
					{
						String[] fileInfoArr = new String[5];
						fileInfoArr[0] = isIntractive;
						fileInfoArr[1] = newFileName;
						fileInfoArr[2] = objName;
						fileInfoArr[3] = oriFileName;
						//Added by Ravindra C on 13/12/2020 [apply template while uploading data through scheduler]
						fileInfoArr[4] = templateName;
						
						//Changed by Prasad on 13/01/2021 [set dynamic value to isRetainPkValue]
						insertFileData( fileInfoArr, userInfo, DUMP_DIR, CommonConstants.APPLICATION_CONTEXT, "", isExcelDriver, isRetainPkValue ); //$NON-NLS-1$
					}
					else
					{
						String[] fileList = DUMP_DIR.list();
						for ( int fileCtr = 0; fileCtr < fileList.length; fileCtr++ )
						{
							String directoryFileName = fileList[fileCtr];
							BaseLogger.log( "3", userInfo, null, "directoryFileName ["+ directoryFileName +"]" ); //$NON-NLS-1$ //$NON-NLS-2$
							if ( ( new File( DUMP_DIR + File.separator + new File(directoryFileName) ) ).isDirectory() )
							{
								BaseLogger.log( "3", userInfo, null, "The UploadedFile ["+ directoryFileName +"] is Directory" ); //$NON-NLS-1$ //$NON-NLS-2$
							}
							else
							{
								String [] fileInfoArr = new String[5];
								fileInfoArr[0] = isIntractive;
								fileInfoArr[1] = directoryFileName;
								fileInfoArr[2] = objName;
								fileInfoArr[3] = oriFileName;
								//Added by Ravindra C on 13/12/2020 [apply template while uploading data through scheduler]
								fileInfoArr[4] = templateName;
								
								//Changed by Prasad on 13/01/2021 [set dynamic value to isRetainPkValue]
								insertFileData( fileInfoArr, userInfo, DUMP_DIR, CommonConstants.APPLICATION_CONTEXT, "", isExcelDriver, isRetainPkValue ); //$NON-NLS-1$
							}
						}
					}
				}
			}
		}
		catch(Exception e)
		{
			//
			
			//
			BaseLogger.log("0", userInfo,null,"UploadFileEJB :==>Schedule"); //$NON-NLS-1$
			e.printStackTrace();
		}
		finally
		{
			try 
			{
				if( ftpClient != null)
				{
					ftpClient.logout();
					ftpClient.disconnect();
				}
				if ( sftpChannel != null )
				{
					sftpChannel.exit();
					session.disconnect();
				}
			}
			catch (IOException e1) 
			{
				e1.printStackTrace();
			}
		}
		return ""; //$NON-NLS-1$
	}

	public String insertFileData( String[] fileInfoArr, UserInfoBean userInfo, File DUMP_DIR, String applicationContext, String menuObjName, boolean isExcelDriver )throws RemoteException, ITMException
	{
		return insertFileData( fileInfoArr, userInfo, DUMP_DIR, applicationContext, menuObjName, isExcelDriver, true );
	}
	
	public String insertFileData( String[] fileInfoArr, UserInfoBean userInfo, File DUMP_DIR, String applicationContext, String menuObjName, boolean isExcelDriver, boolean isRetainPkValue )throws RemoteException, ITMException
	{
		//Changed by Prasad on 13/01/2021 [set dynamic value to isRetainPkValue]
		return insertFileData( fileInfoArr, userInfo, DUMP_DIR, applicationContext, menuObjName, isExcelDriver, isRetainPkValue, null, 1 );
	}
	
	//Added By Pankaj t on 16-06-17 [F16KSUN001][to set retainPkValue flag true for primary key value is set from uploaded xml when key flag "A"]
	public String insertFileData( String[] fileInfoArr, UserInfoBean userInfo, File DUMP_DIR, String applicationContext, String menuObjName, boolean isExcelDriver, boolean isRetainPkValue, String batchID, int tranSl )throws RemoteException, ITMException
	{
		StringBuffer responseHTMLBuff = null;
		StringBuffer xmlStringBuff = null;

		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		boolean isError = false;

		String retString = "";
		String fileName = "";
		String tempFileName = null;
		//Changed by Prasad on 30/01/18 [Calling masterStateful component to processRequest]
		//ITMTransactionCoreModel itmTransCoreMdl = null;
		try
		{
			//E12GenericUtility genericUtility = new E12GenericUtility();
			BaseLogger.log( "3", userInfo, null, "userInfo : ["+ userInfo +"]" );
			setUserInfoBean(userInfo);
			String loginCode = userInfo.getLoginCode();
			String entityCode = userInfo.getEntityCode();
			String entityType = userInfo.getUserType();
			
			String xmlStringArr[] = null;
			boolean isRetXML = false;//Added by Santosh on 15-02-2018
			String templateName = "";

			BaseLogger.log( "3", userInfo, null, "fileInfoArr["+ Arrays.toString(fileInfoArr) +"]" );
			boolean isModeInteractive = ( fileInfoArr[0] == null ) ? false :( ( Boolean.valueOf( fileInfoArr[0] )).booleanValue() );

			fileName = fileInfoArr[1];
			BaseLogger.log( "3", userInfo, null, "fileName : ["+ fileName +"]" );
			
			String fileType = fileName.substring( fileName.indexOf( "." ) ); //$NON-NLS-1$
			BaseLogger.log( "3", userInfo, null, "Uploading File of Type ["+ fileType +"]" ); //$NON-NLS-1$ //$NON-NLS-2$

			String objName = fileInfoArr[2];
			BaseLogger.log( "3", userInfo, null, "objName : ["+ objName +"]" );
			
			String oriFileName = fileInfoArr[3];
			BaseLogger.log( "3", userInfo, null, "oriFileName : ["+ oriFileName +"]" );
			
			//Added by Santosh on 15-02-2018 to return xml if fileInfoArr[7] = true [Start]
			if( fileInfoArr.length >= 8 )
			{
				isRetXML = ( fileInfoArr[7] != null && "true".equalsIgnoreCase(fileInfoArr[7].trim()) ) ? true : false;
			}
			BaseLogger.log( "3", userInfo, null, "isRetXML ["+ isRetXML +"]" );
			//Added by Santosh on 15-02-2018 to return xml if fileInfoArr[7] = true [End]
			
			if( fileInfoArr.length >= 5 )
			{
				templateName = checkNull( fileInfoArr[4] );
			}
			BaseLogger.log( "3", userInfo, null, "templateName : ["+ templateName +"]" );
			
			ConnDriver connDriver = new ConnDriver();
			String transDB = userInfo.getTransDB();
			//commented and added By Sneha on 17-1-14 to Pass transDB to support MultiDB connection : START
			BaseLogger.log( "3", userInfo, null, "insertFileData.. transDB...["+ transDB +"]" );
			//if(transDB != null && !"null".equalsIgnoreCase(transDB.trim()) && transDB.trim().length() > 0)
			//{
			conn = connDriver.getConnectDB(transDB);
			//}
			//commented and added By Sneha on 17-1-14 to Pass transDB to support MultiDB connection : END
			
			// Changes by Gagan B. on 15-NOV-23 moved the file checking code in try/catch block. [START]
			File loadedFileObj = null;
			
			try {
				loadedFileObj = new File( DUMP_DIR + File.separator + fileName );
				BaseLogger.log( "3", userInfo, null, "loadedFileObj ["+ loadedFileObj +"], DUMP_DIR["+ DUMP_DIR +"]" );
				BaseLogger.log( "3", userInfo, null, "loadedFileObj path :["+ loadedFileObj.getAbsolutePath() +"], exists :["+ loadedFileObj.exists() +"]" );
				
				// Changes by Gagan B. on 04-DEC-23 [use getAbsolutePath() and then .exists() method] - START
				BaseLogger.log( "3", userInfo, null, "loadedFileObj.getAbsolutePath() path :["+ loadedFileObj.getAbsolutePath() +"], exists :["+ loadedFileObj.exists() +"]" );
				
				String loadedFileObjFilePath =  loadedFileObj.getAbsolutePath();
				loadedFileObj = new File (loadedFileObjFilePath);
				
				BaseLogger.log( "3", userInfo, null, "loadedFileObj absoule Path gsb["+ loadedFileObjFilePath +"]");
				BaseLogger.log( "3", userInfo, null, "loadedFileObj path :["+ loadedFileObj +"], exists :["+ loadedFileObj.exists() +"]" );
				// Changes by Gagan B. on 04-DEC-23 [use getAbsolutePath() and then .exists() method] - END
				
				if( ! loadedFileObj.exists() )
				{
					// Changes by Gagan B. on 15-NOV-23 to move server.log file to upload_failed folder in case of load file not exist error. [START]
					String fromPath = CommonConstants.JBOSSHOME + File.separator + "server" +  File.separator + "default" + File.separator 
							+ "log" + File.separator + "server.log"; 
					String toPath = CommonConstants.JBOSSHOME + File.separator+ "upload_failed";
					String movedFileName = batchID + "_server.log";
					BaseLogger.log("3", null, null, "Inside processEDIBatchload gsb fromPath [" + fromPath + "]");
					BaseLogger.log("3", null, null, "Inside processEDIBatchload gsb toPath [" + toPath + "]");
					BaseLogger.log("3", null, null, "Inside processEDIBatchload gsb movedFileName [" + movedFileName + "]");
					genericUtility.copyFileWithNewName(fromPath, toPath, movedFileName);
					// Changes by Gagan B. on 15-NOV-23 to move server.log file to upload_failed folder in case of load file not exist error. [END]
					
					//Added by Ravindra on 11/05/2021 [to save error message in batchload] START
					retString = genericUtility.getErrorString( "", "Load file not exist", "File not found", "" );
					String xmlString = "<Root><header><objName><![CDATA["+ objName +"]]></objName></header></Root>";
					generateUploadResponse(objName, retString, fileName, batchID, tranSl, ""+ tranSl, xmlString, conn, getMasterApplyEJB(objName, userInfo) );
					//Added by Ravindra on 11/05/2021 [to save error message in batchload] END
					return "<HTML><BODY>Load file not exist</BODY></HTML>";
				}
			} catch (Exception e) {
//				//Added by Amol s on 23-oct --strt
				MasterApplyEJB masterApplyEJB = new MasterApplyEJB();
				masterApplyEJB.updateBatchLoad( batchID, tranSl, "E", "", null, getUserInfoBean() );
				BaseLogger.log("3", null, null,
	            "Exception2 in processEDIBatchload [" + E12GenericUtility.getStackTrace(e) + "]");
				throw new ITMException( e );
				//Added by Amol s -end

			}
			// Changes by Gagan B. on 15-NOV-23 moved the file checking code in try/catch block. [END]
			
			
			//Added by Ravindra C on 13/12/2020 [apply template while uploading data through scheduler] START
			UploadTemplateMapping templateMapping = null;
			//Added By Ravindra C on 22-01-2021 [for auto confirm transaction from upload]
			boolean isDataUploadAutoConfirm = false;
			if ( templateName.length() > 0 )
			{
				templateMapping = new UploadTemplateMapping( userInfo );
				retString = templateMapping.setTemplateDetails( objName, templateName, userInfo );
				//Added by Ravindra on 11/05/2021 [to save error message in batchload] START
				if ( retString.indexOf( "<Errors>" ) != -1 )
				{
					String xmlString = "<Root><header><objName><![CDATA["+ objName +"]]></objName></header></Root>";
					generateUploadResponse(objName, retString, fileName, batchID, tranSl, ""+ tranSl, xmlString, conn, getMasterApplyEJB(objName, userInfo) );
					return retString;
				}
				//Added by Ravindra on 11/05/2021 [to save error message in batchload] END
				//Added By Ravindra C on 22-01-2021 [for auto confirm transaction from upload]
				isDataUploadAutoConfirm = templateMapping.isAutoConfirm();
			}
			//Added by Ravindra C on 13/12/2020 [apply template while uploading data through scheduler] END

			boolean isTemplateExist = false;
			String templUpld = null;
			String sql = " select OBJ_NAME, TEMPL_UPLD, TEMPL_TYPE_UPLD, TEMPL_DNLD, TEMPL_TYPE_DNLD" //$NON-NLS-1$
					+" from OBJECT_EXIM_FMT " //$NON-NLS-1$
					+" where OBJ_NAME  = '" + objName + "'" //$NON-NLS-1$ //$NON-NLS-2$
					+" and OBJ_CONTEXT = '" + (checkNull(entityType)).trim() + "-" + (checkNull(entityCode)).trim() + "'"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$

			//$NON-NLS-1$
			pstmt = conn.prepareStatement( sql );
			rs = pstmt.executeQuery();
			if( rs.next() )
			{
				objName = rs.getString( "OBJ_NAME" ); //$NON-NLS-1$
				templUpld = rs.getString( "TEMPL_UPLD" ); //$NON-NLS-1$
				isTemplateExist = true;
			}
			rs.close();
			rs = null;
			pstmt.close();
			pstmt = null;
			//Gulzar on 29/05/15
			//conn.close();
			//conn = null;

			if( isTemplateExist )
			{
				String xlsFileName = fileName;
				BaseLogger.log( "3", userInfo, null, "xlsFileName :: ["+ xlsFileName +"]" ); //$NON-NLS-1$
				File UPLOAD_DIR = new File( CommonConstants.JBOSSHOME );
				if ( ! UPLOAD_DIR.exists() )
				{
					UPLOAD_DIR.mkdir();
				}
				fileName = CommonConstants.JBOSSHOME + File.separator + "UPLOAD" + File.separator + entityType + (checkNull(entityCode)).trim() + "-" + objName + ".xml"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
				ibase.webitm.utility.XLS2XMLCustomXfm xmlConverter = new ibase.webitm.utility.XLS2XMLCustomXfm();
				xmlConverter.convert( DUMP_DIR + File.separator + xlsFileName, 
						CommonConstants.JBOSSHOME + File.separator + "UPLOAD" + File.separator + "template" + File.separator + templUpld + ".xml", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
						fileName );

				loadedFileObj = new File( fileName );
			}
			else if( fileType.equalsIgnoreCase( ".xls" ) ) //$NON-NLS-1$
			{
				BaseLogger.log( "3", userInfo, null, "checkbox : isExcelDriver ["+isExcelDriver+"]" ); //$NON-NLS-1$ //$NON-NLS-2$
				if( isExcelDriver )
				{  		   
					XLS2XMLGenerator xmlGenerator = new XLS2XMLGenerator( loginCode, fileName, null );
					xmlStringArr = xmlGenerator.generateXML();
					objName = xmlGenerator.getObjName();
				}
				else
				{					 				     
					XLS2XMLGenerator xmlGenerator = new XLS2XMLGenerator();
					xmlStringArr = xmlGenerator.generateXML( fileName );
					objName = xmlGenerator.getJxlObjName();	
					BaseLogger.log( "3", userInfo, null, "ITMUploadFileEJB:xmlStringArr ["+ xmlStringArr[0] +"]" ); //$NON-NLS-1$ //$NON-NLS-2$
				}
				//Commented and changed by Gulzar on 22/05/14 to check if menuObjName ="" is passed
				//if(menuObjName != null) 
				if( menuObjName != null && menuObjName.trim().length() > 0 && !"null".equalsIgnoreCase(menuObjName) )//Gulzar on 22/05/14
				{
					if( ! menuObjName.equalsIgnoreCase(objName) )
					{
						BaseLogger.log( "3", userInfo, null, "menuObjName.length() ["+ menuObjName.length() +"]" ); //$NON-NLS-1$ //$NON-NLS-2$
						//Added by Ravindra on 11/05/2021 [to save error message in batchload] START
						retString = genericUtility.getErrorString( "", (Messages.getString("ITMUploadFileEJB_allowedOnlyToUpload")+menuObjName), "Invalid Object", "" );
						String xmlString = "<Root><header><objName><![CDATA["+ objName +"]]></objName></header></Root>";
						generateUploadResponse(objName, retString, fileName, batchID, tranSl, ""+ tranSl, xmlString, conn, getMasterApplyEJB(objName, userInfo) );
						//Added by Ravindra on 11/05/2021 [to save error message in batchload] END
						return "<HTML><BODY>"+Messages.getString("ITMUploadFileEJB_allowedOnlyToUpload")+menuObjName+"</BODY></HTML>"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
					}
				}
				if ( oriFileName != null && oriFileName.length() > 0 )
				{
					BaseLogger.log( "3", userInfo, null, "Converting to xml from Array" ); //$NON-NLS-1$
					StringBuffer tempXmlBuff = new StringBuffer();
					for ( int i = 0; i < xmlStringArr.length; i++ )
					{
						tempXmlBuff.append( xmlStringArr[ i ] );
					}
					String tempXmlFileName = System.currentTimeMillis() + "_" + loginCode + "_temp.xml"; //$NON-NLS-1$ //$NON-NLS-2$
					BaseLogger.log( "3", userInfo, null, "tempXmlFileName ["+ tempXmlFileName +"]" ); //$NON-NLS-1$ //$NON-NLS-2$
					FileWriter fos = new FileWriter( DUMP_DIR + File.separator + tempXmlFileName );
					fos.write( tempXmlBuff.toString() );
					fos.flush();
					fos.close();

					loadedFileObj = new File( tempXmlFileName );
					BaseLogger.log("3", userInfo,null,"New xml file created ["+tempXmlFileName+"]");	 //$NON-NLS-1$ //$NON-NLS-2$
					xmlStringArr = null;
				}
			}
			else if( fileType.equalsIgnoreCase( ".x12" ) ) //$NON-NLS-1$
			{
				BaseLogger.log( "3", userInfo, null, "Loading .x12 file......" ); //$NON-NLS-1$
				//Added by yogesh on 24-sep-11 [DI1BSUN011| RnD to convert edi-->xml] start
				//X12toXmlGenerator x12toXMl = new X12toXmlGenerator();
				//x12toXMl.convertToXml( loadedFileObj.getAbsolutePath() );
				tempFileName = fileName + ".xml"; //$NON-NLS-1$
				if( fileName != null && fileName.indexOf(".") != -1 )
				{
					tempFileName = fileName.substring( 0, fileName.lastIndexOf(".") ) + ".xml";
				}
				File x12ToXMlFile = new File( DUMP_DIR + File.separator + tempFileName );
				BaseLogger.log( "3", userInfo, null, "Converting .x12 to .xml" ); //$NON-NLS-1$
				new X12toXmlGenerator( loadedFileObj.getAbsolutePath(), x12ToXMlFile.getAbsolutePath() );
				//x12ToXmlfileName = fileName+".xml";
				//Added by yogesh on 24-sep-11 [DI1BSUN011| RnD to convert edi-->xml] end
				BaseLogger.log( "3", userInfo, null, "Converted xml fileName ["+ x12ToXMlFile.getAbsolutePath() +"]" );						 //$NON-NLS-1$ //$NON-NLS-2$
				loadedFileObj = new File( DUMP_DIR + File.separator + tempFileName );
				if ( oriFileName == null )
				{
					ValidateXMLInput vxi = new ValidateXMLInput();							
					String outputFileName = vxi.validate( CommonConstants.UPLOAD_LOC + File.separator + "setting" + File.separator + "x12.xslt", loadedFileObj.getAbsolutePath(), "Output", ".xml", applicationContext );							 //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
					loadedFileObj = new File( outputFileName );							
				}
			}
			//Added by yogesh on 03-sep-11 [ DI1BSUN011|upload xml to batchload] start
			//Added by Ravindra C on 27/12/2020 [to support json data upload] START
			else if( fileType.equalsIgnoreCase( ".json" ) )
			{
				String jsonString = genericUtility.readFile( loadedFileObj.getAbsolutePath() );
				BaseLogger.log( "3", userInfo, null, "jsonString json file data= ["+jsonString +"]" );
				// Added by Gagan B. to check whether the json string is valid or not and if not, then convert the  XML to JSON [START]
				if (!genericUtility.isJSONValid(jsonString)) {
					jsonString = genericUtility.xmlToJSONString(jsonString);
				}
				BaseLogger.log( "3", userInfo, null, "jsonString json file data gsb= ["+jsonString +"]" );
				// Added by Gagan B. to check whether the json string is valid or not and if not, then convert the  XML to JSON [END]
				String xmlString = "";
				HashMap<String, String> keyDetailMap = null;
				if( templateMapping != null )
				{
					keyDetailMap = templateMapping.getMappingSheetDetailMap();
					BaseLogger.log( "3", userInfo, null, "keyDetailMap map for json=["+ keyDetailMap +"]" );
					xmlString = (new JSONtoXMLConverter()).jsonToXMLString( jsonString, keyDetailMap );
					BaseLogger.log( "3", userInfo, null, "if templateMapping not null xmlString--["+ xmlString +"]" );
				} 
				// Changes by Gagan B. as per Danish Sir's suggestion for handling condition when templateMapping is null on 08-FEB-23. [START] 
				else 
				{
					xmlString = (new JSONtoXMLConverter()).jsonToXMLString( jsonString, keyDetailMap );
					BaseLogger.log( "3", userInfo, null, "else xmlString--["+ xmlString +"]" );
				}
				// Added by Gagan B. on 8th July for adding isDataUpload="true" in xml for mimicing upload utility [START]
	            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
	            DocumentBuilder builder = factory.newDocumentBuilder();
	            InputSource inputSource = new InputSource(new StringReader(xmlString));
	            Document document = builder.parse(inputSource);

	            E12GenericUtility.addisDataUploadAttribute(document);
	            xmlString = E12GenericUtility.documentToString(document);
	            BaseLogger.log( "3", userInfo, null, "added isDataUpload attribute xmlString----["+ xmlString +"]" );
	            // Added by Gagan B. on 8th July for adding isDataUpload="true" in xml for mimicing upload utility [END]
				
				if( fileName != null && fileName.indexOf(".") != -1 )
				{
					tempFileName = fileName.substring( 0, fileName.lastIndexOf(".") ) + ".xml";
					genericUtility.writeFile( DUMP_DIR.getAbsolutePath(), tempFileName, xmlString );
					loadedFileObj = new File( DUMP_DIR.getAbsolutePath() + File.separator + tempFileName );
				}
				// Changes by Gagan B. as per Danish Sir's suggestion for handling condition when templateMapping is null on 08-FEB-23. [END]
			}else if( fileType.equalsIgnoreCase( ".xml" ) ) {
				
				String xmlString="";
				HashMap<String, String> keyDetailMap = null;
				BaseLogger.log( "3", userInfo, null, "templateMapping map for xml=["+ (templateMapping!=null) +"]" );
				if(templateMapping!=null) {
					keyDetailMap = templateMapping.getMappingSheetDetailMap();
					BaseLogger.log( "3", userInfo, null, "keyDetailMap map for xml=["+ keyDetailMap +"]" );
					xmlString = getDetailXmlString( loadedFileObj.getAbsolutePath(),keyDetailMap);
				}
				// Changes by Gagan B. as per Danish Sir's suggestion for handling condition when templateMapping is null on 08-FEB-23. [START] 
				else
				{
					// Changes by Gagan B. for reading file content and storing in XML String in case of keyDetailMap is null.
					xmlString = E12GenericUtility.readFileContents(loadedFileObj.getAbsolutePath());
					BaseLogger.log( "3", userInfo, null, "xmlString in case of keyDetailMap null:: ["+ xmlString +"]" );
				}
				if( fileName != null && fileName.indexOf(".") != -1 )
				{
					tempFileName = fileName.substring( 0, fileName.lastIndexOf(".") ) + ".xml";
					System.out.println("tempFile name for xml=["+tempFileName);
					genericUtility.writeFile( DUMP_DIR.getAbsolutePath(), tempFileName, xmlString );
					loadedFileObj = new File( DUMP_DIR.getAbsolutePath() + File.separator + tempFileName );
				}
				// Changes by Gagan B. as per Danish Sir's suggestion for handling condition when templateMapping is null on 08-FEB-23. [END]
				
				//String jsonString = genericUtility.readFile( loadedFileObj.getAbsolutePath() );
				//System.out.println("jsonString for xml===>"+jsonString);
				/*BaseLogger.log( "3", userInfo, null, "jsonString json file data= ["+jsonString +"]" );
				String xmlString = "";
				HashMap<String, String> keyDetailMap = null;
				if( templateMapping != null )
				{
					keyDetailMap = templateMapping.getMappingSheetDetailMap();
					xmlString = (new JSONtoXMLConverter()).jsonToXMLString( jsonString, keyDetailMap );
					BaseLogger.log( "3", userInfo, null, "xmlString : ["+ xmlString +"]" );
					if( fileName != null && fileName.indexOf(".") != -1 )
					{
						tempFileName = fileName.substring( 0, fileName.lastIndexOf(".") ) + ".xml";
						genericUtility.writeFile( DUMP_DIR.getAbsolutePath(), tempFileName, xmlString );
						
						loadedFileObj = new File( DUMP_DIR.getAbsolutePath() + File.separator + tempFileName );
					}
				}
				else
				{
					retString = "Template not found!";
					return retString;
				}*/
			}
			//Added by Ravindra C on 27/12/2020 [to support json data upload] END
			if ( xmlStringArr == null )
			{
				BaseLogger.log( "3", userInfo, null, "Loading file......" ); //$NON-NLS-1$
				if ( oriFileName != null && oriFileName.length() > 0 )
				{
					ValidateXMLInput vxi = new ValidateXMLInput();
					BaseLogger.log( "3", userInfo, null, "oriFileName - ["+ oriFileName +"]" );
					String outputFileName = vxi.validate( oriFileName, loadedFileObj.getAbsolutePath(), "Output", ".xml", applicationContext); //$NON-NLS-1$ //$NON-NLS-2$
					BaseLogger.log( "3", userInfo, null, "outputFileName ["+ outputFileName +"]" ); //$NON-NLS-1$ //$NON-NLS-2$
					loadedFileObj = new File( outputFileName );
				}
				BaseLogger.log( "3", userInfo, null, "xml file loadedFileObj ["+ loadedFileObj +"]" ); //$NON-NLS-1$ //$NON-NLS-2$
				
				Document dataDom = genericUtility.parseFile( loadedFileObj );
				Node objNameNode = dataDom.getElementsByTagName( "objName" ).item( 0 ); //$NON-NLS-1$
				if ( objNameNode != null && objNameNode.getFirstChild() != null )
				{
					objName = objNameNode.getFirstChild().getNodeValue();
				}

				Node detailNode = dataDom.getElementsByTagName( "Detail1" ).item( 0 ); //$NON-NLS-1$
				BaseLogger.log( "3", userInfo, null, "detailNode ITMUploadFileEJB:" + detailNode ); //$NON-NLS-1$ //$NON-NLS-2$
				StringBuffer eachTransBuffer = null;
				ArrayList<String> xmlStringArrList = new ArrayList<String>();
				do
				{
					if( detailNode.getNodeType() == Node.ELEMENT_NODE && detailNode.getNodeName().startsWith( "Detail" ) ) //$NON-NLS-1$
					{
						if( detailNode.getNodeName().equals( "Detail1" ) ) //$NON-NLS-1$
						{
							if( eachTransBuffer != null )
							{
								xmlStringArrList.add( eachTransBuffer.toString() );
							}
							eachTransBuffer = new StringBuffer();
						}
						eachTransBuffer.append( genericUtility.serializeDom( detailNode ) );
					}
				}
				while ( ( detailNode = detailNode.getNextSibling() ) != null );
				xmlStringArrList.add( eachTransBuffer.toString() );

				xmlStringArr = new String[ xmlStringArrList.size() ];
				xmlStringArr = ( String[] )xmlStringArrList.toArray( xmlStringArr );
			}
			BaseLogger.log( "9", userInfo, null, "xmlStringArr : ["+ xmlStringArr.length +"]" ); //$NON-NLS-1$ //$NON-NLS-2$
			if( objName == null )
			{
				objName = fileInfoArr[2];
			}
			BaseLogger.log( "3", userInfo, null, "objName : ["+ objName +"]" ); //$NON-NLS-1$ //$NON-NLS-2$
			if ( xmlStringArr.length > 0 )
			{
				isModeInteractive = false;
			}
			tempFileName = E12GenericUtility.checkNull( tempFileName );
			String uploadFileName = tempFileName.length() > 0 ? tempFileName : fileName;
			BaseLogger.log( "3", userInfo, null, "uploadFileName : ["+ uploadFileName +"]" );
			
			//MasterApplyEJB masterApply = new MasterApplyEJB();
			//masterApply.setObjFormDetail( objName, userInfo );
			
			HashMap<String, String> detailDataMap = new LinkedHashMap<String, String>();
			//StringBuffer responseHTMLBuffLog =  new StringBuffer();
			for( int index = 0; index < xmlStringArr.length; index++ )
			{
				//Changed by Gulzar/Rakesh on 10/11/12 to check whether the xmlStringArr contains blank rows - START
				String uploadData = xmlStringArr[index];
				if( uploadData == null || uploadData.trim().length() == 0 )
				{
					continue;
				}
				//Changed by Gulzar/Rakesh on 10/11/12 - END
				
				//Added by Ravindra C on 13/12/2020 [apply template while uploading data through scheduler] START
				if ( fileType.equalsIgnoreCase( ".json" ) && templateMapping != null )
				{
					StringBuffer strBuff = new StringBuffer();
					System.out.println("before applying template for json=["+uploadData);
					strBuff.append( "<Root>" ).append( uploadData ).append( "</Root>" );
					uploadData = templateMapping.applyTemplate( strBuff.toString() );
					if ( uploadData.indexOf( "<Errors>" ) != -1 )
					{
						retString = uploadData;
						break;
					}
				}
				if ( fileType.equalsIgnoreCase( ".xml" ) && templateMapping != null )
				{
					System.out.println("Applying template for xml file");
					StringBuffer strBuff = new StringBuffer();
					strBuff.append( "<Root>" ).append( uploadData ).append( "</Root>" );
					uploadData = templateMapping.applyTemplate( strBuff.toString() );
					if ( uploadData.indexOf( "<Errors>" ) != -1 )
					{
						retString = uploadData;
						break;
					}
				}
				BaseLogger.log( "3", userInfo, null, "uploadData : ["+ uploadData +"]" );
				//Added by Ravindra C on 13/12/2020 [apply template while uploading data through scheduler] END
				
				xmlStringBuff = new StringBuffer( "<Root>" );
				xmlStringBuff.append( "<header>" ); //$NON-NLS-1$
				xmlStringBuff.append( "<objName><![CDATA[" ).append( objName ).append( "]]></objName>" ); //$NON-NLS-1$ //$NON-NLS-2$
				xmlStringBuff.append( "<pageContext><![CDATA[2]]></pageContext>" ); //$NON-NLS-1$
				xmlStringBuff.append( "<objContext><![CDATA[1]]></objContext>" ); //$NON-NLS-1$
				xmlStringBuff.append( "<editFlag><![CDATA[A]]></editFlag>" ); //$NON-NLS-1$
				xmlStringBuff.append( "<focusedColumn><![CDATA[]]></focusedColumn>" ); //$NON-NLS-1$
				xmlStringBuff.append( "<keyValue><![CDATA[1]]></keyValue>" ); //$NON-NLS-1$
				xmlStringBuff.append( "<saveLevel><![CDATA[1]]></saveLevel>" ); //$NON-NLS-1$
				xmlStringBuff.append( "<forcedSave><![CDATA[false]]></forcedSave>" ); //$NON-NLS-1$
				xmlStringBuff.append( "<isModeInteractive><![CDATA[" ).append( isModeInteractive ).append( "]]></isModeInteractive>" ); //$NON-NLS-1$ //$NON-NLS-2$
				xmlStringBuff.append( "<action><![CDATA[SAVE]]></action>" ); //$NON-NLS-1$
				xmlStringBuff.append( "</header>" ); //$NON-NLS-1$
				xmlStringBuff.append( uploadData );
				xmlStringBuff.append( "</Root>" ); //$NON-NLS-1$

				//Added by Prasad on 30/01/18 [Calling masterStateful component to processRequest] START
				String xmlString = xmlStringBuff.toString();

				String uploadDataDBId = getUploadDataDBId( xmlString );
				BaseLogger.log( "3", userInfo, null, "uploadDataDBId : ["+ uploadDataDBId +"]" );
				
				detailDataMap.put( uploadDataDBId, xmlString );
				//Added by Prasad on 19/10/18 [inserting record into batchload] START
			}
			//Added by Prasad on 19/10/18 [inserting record into batchload] START
			if ( ( retString.indexOf( "<Errors>" ) == -1 ) && ( batchID == null || batchID.trim().length() == 0 ) )
			{
				batchID = getDBAccess().generateTranId( "I-BL", userInfo.getSiteCode(), userInfo.getLoginCode(), conn );

				E12CreateBatchLoadEjb batchLoadEjb = new E12CreateBatchLoadEjb();
				String xtraParams = getXtraParams( userInfo );
				//tempFileName = E12GenericUtility.checkNull( tempFileName );
				//String batchFileName = tempFileName.length() > 0 ? tempFileName : fileName;
				retString = batchLoadEjb.insertBatchData( detailDataMap, "A", batchID, objName, uploadFileName, xtraParams, userInfo );
				BaseLogger.log( "3", userInfo, null, "retString : ["+ retString +"]" );
				batchLoadEjb = null;
				if ( ! "SUCCESS".equalsIgnoreCase( retString ) )
				{
					//Added by Ravindra on 11/05/2021 [to save error message in batchload] START
					String xmlString = "<Root><header><objName><![CDATA["+ objName +"]]></objName></header></Root>";
					generateUploadResponse(objName, retString, tempFileName, batchID, tranSl, ""+ tranSl, xmlString, conn, getMasterApplyEJB(objName, userInfo) );
					//Added by Ravindra on 11/05/2021 [to save error message in batchload] END
					return retString;
				}
			}
			
			responseHTMLBuff = new StringBuffer( "<COL WIDTH=350><COL WIDTH=350>"
					+ "<TR>"
					+ "<TH WIDTH=4%>Sr no</TH>"
					+ "<TH WIDTH=48%><P>Generated Trans. id</P></TH>"
					+ "<TH WIDTH=48%><P>Status</P></TH>"
					+ "</TR>" ); //$NON-NLS-1$
			//Changed by Pooja S on 12-JAN-2021 [Batchload interface to store keyFieldValue for the transaction]
			int rowNo = tranSl;
			if ( retString.indexOf( "<Errors>" ) == -1 )
			{
				for ( Map.Entry<String, String> entry : detailDataMap.entrySet() )
				{
					String dBId = entry.getKey();
					String xmlString = entry.getValue();
					BaseLogger.log( "3", userInfo, null, "dBId : ["+ dBId +"], xmlString : ["+ xmlString +"]" );
					//Added By Ravindra C on 22-01-2021 [for auto confirm transaction from upload]
					//Added by Pankaj P on 25/05/2021 [set batchid details to masterStateful related changes]
					MasterApplyEJB masterApplyEJB = getMasterApplyEJB(objName, userInfo); // Change by Gagan 22-FEB-23
					BaseLogger.log( "3", null, null, "serviceConfigGlobal from ITMUploadFileEJB: [" + VisionEDIUtility.serviceConfigGlobal +"]" );
					if(VisionEDIUtility.serviceConfigGlobal.equalsIgnoreCase("setDataAndConfirm")) {
						masterApplyEJB.setRunMode("B"); // Added by Gagan 22-FEB-23
					}
					retString = masterApplyEJB.saveData( xmlString, userInfo, isRetainPkValue, isDataUploadAutoConfirm, (batchID+":"+rowNo), conn );
					if ( retString.indexOf( "<Errors>" ) != -1 )
					{
						isError = true;
					}
					//Changed by Ravindra C on 19/01/2021 [to send notification in case of error in uploading] START
					//Changed by Ravindra on 12/03/2021 [Pass transaction xml to mail component]
					String response = generateUploadResponse( objName, retString, uploadFileName, batchID, rowNo, dBId, xmlString, conn, getMasterApplyEJB( objName, userInfo ) );
					rowNo++;
					responseHTMLBuff.append( response ); //$NON-NLS-1$
				}
			}
			else
			{
				if ( batchID != null && batchID.trim().length() > 0 )
				{
					//Changed by Ravindra on 12/03/2021 [Pass transaction xml to mail component]
					String xmlString = "<Root><header><objName><![CDATA["+ objName +"]]></objName></header></Root>";
					String response = generateUploadResponse( objName, retString, uploadFileName, batchID, rowNo, "", xmlString, conn, getMasterApplyEJB( objName, userInfo ) );
					responseHTMLBuff.append( response );
				}
			}
			//masterApply = null;
			//Added by Santosh on 15-02-2018 to return xml if fileInfoArr[7] = true [Start]
			if( isRetXML )
			{
				return retString;
			}
			//Added by Santosh on 15-02-2018 to return xml if fileInfoArr[7] = true [End]
		}
		catch(ITMException itme)
		{
		//Added by Amol s on 23-oct --strt
			MasterApplyEJB masterApplyEJB = new MasterApplyEJB();
			masterApplyEJB.updateBatchLoad( batchID, tranSl, "E", "", null, getUserInfoBean() );
		//Added by Amol s on 23-oct --end

			try
			{
				BaseLogger.log("0", userInfo,null,"Rollback the Changes when exception......");
				conn.rollback();
			}
			catch(Exception ee)
			{
			//Added by Amol s on 23-oct --strt
				//MasterApplyEJB masterApplyEJB = new MasterApplyEJB();
				masterApplyEJB.updateBatchLoad( batchID, tranSl, "E", "", null, getUserInfoBean() );
				BaseLogger.log("3", null, null,
	            "Exception2 in processEDIBatchload [" + E12GenericUtility.getStackTrace(ee) + "]");
				throw new ITMException( ee );
				//Added by Amol s -end

			}
			isError = true;
			BaseLogger.log("0", userInfo,null,"ITMException :UploadFileEJB :==>ITMException"+ itme.getMessage()); //$NON-NLS-1$
			throw itme;
		}
		catch(Exception e)
		{
			MasterApplyEJB masterApplyEJB = new MasterApplyEJB();
			masterApplyEJB.updateBatchLoad( batchID, tranSl, "E", "", null, getUserInfoBean() );
			try
			{
				BaseLogger.log("0", userInfo,null,"Rollback the Changes when exception@@......");
				conn.rollback();
			}
			catch(Exception ee)
			{
				//Added by Amol s on 23-oct --strt
				//MasterApplyEJB masterApplyEJB = new MasterApplyEJB();
				masterApplyEJB.updateBatchLoad( batchID, tranSl, "E", "", null, getUserInfoBean() );
				BaseLogger.log("3", null, null,
	            "Exception2 in processEDIBatchload [" + E12GenericUtility.getStackTrace(ee) + "]");
				throw new ITMException( ee );
				//Added by Amol s -end

			}
			isError = true;
			BaseLogger.log("0", userInfo,null,"ITMException :UploadFileEJB :==>Exception"+ e.getMessage()); //$NON-NLS-1$
			throw new ITMException(e);
		}
		finally
		{
			try
			{
				//Added by Ravindra C on 13/12/2020 [apply template while uploading data through scheduler] START
				if ( retString.indexOf( "<Errors>" ) != -1 )
				{
					isError = true;
					createUploadLog( retString, fileName );
					// Changes by Gagan B. to copy log file to upload_failed folder in case of error on 23-OCT-23 [START]
					moveLogFile(batchID);
					// Changes by Gagan B. to copy log file to upload_failed folder in case of error on 23-OCT-23 [END]
				}
				//Added by Ravindra C on 13/12/2020 [apply template while uploading data through scheduler] END
				tempFileName = E12GenericUtility.checkNull( tempFileName );
				if( isError )
				{
					if ( tempFileName.length() > 0 )
					{
						moveErrorFile( tempFileName, DUMP_DIR );
					}
					moveErrorFile( fileName, DUMP_DIR );
				}
				else
				{
					if ( tempFileName.length() > 0 )
					{						
						moveUploadFile( tempFileName, DUMP_DIR );
					}
					moveUploadFile( fileName, DUMP_DIR );
				}
				if ( conn != null )
				{
					/*if( ! isError )
					{
						BaseLogger.log("3", userInfo,null,"Commiting the Changes in finally......");
						conn.commit();
					}*/
					conn.close();
					conn = null;
				}
				//Changed by Prasad on 30/01/18 [Calling masterStateful component to processRequest] START
				/*if ( itmTransCoreMdl != null )
				{
					itmTransCoreMdl.remove();
					itmTransCoreMdl = null;
				}*/
				//Changed by Prasad on 30/01/18 [Calling masterStateful component to processRequest] END
			}
			catch ( Exception e)
			{
				//Added by Amol s on 23-oct --strt
				MasterApplyEJB masterApplyEJB = new MasterApplyEJB();
				masterApplyEJB.updateBatchLoad( batchID, tranSl, "E", "", null, getUserInfoBean() );
				BaseLogger.log("3", null, null,
	            "Exception2 in processEDIBatchload [" + E12GenericUtility.getStackTrace(e) + "]");
				throw new ITMException( e );
				//Added by Amol s -end

			}
		}
		return responseHTMLBuff.toString();
	}
	//Added by Ankush S. on 07-Nov-2022[create detail xml string from xmlFile data]START
	private String getDetailXmlString(String filePath,HashMap<String, String> keyDetailMap) {
		String xmlString="<Root>";
		try {
			StringBuilder strBuilder = new StringBuilder("<Root>");
			System.out.println("file path="+filePath);
			DocumentBuilder documentBuilder;
			documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
			Document document = documentBuilder.parse(filePath);
			NodeList rootNodeList = document.getChildNodes();
			Node rootNode = rootNodeList.item(0);
			NodeList rootChildList = rootNode.getChildNodes();
			BaseLogger.log("0", userInfo,null,"Root Node List Length==>"+rootChildList.getLength());
			Map<String,List<Node>>nodeMap = new HashMap<String, List<Node>>();
			for(int i=0;i<rootChildList.getLength();i++) {
				Node rootChild  = rootChildList.item(i);
			
				if(!rootChild.getNodeName().contains("#")) {
					if(nodeMap.containsKey(rootChild.getNodeName())) {//check key is present or not
						nodeMap.get(rootChild.getNodeName()).add(rootChild);
					}
					else {//if key is not present add new 
						nodeMap.put(rootChild.getNodeName(),new ArrayList<Node>());
						nodeMap.get(rootChild.getNodeName()).add(rootChild);
					}
				}
			}
			BaseLogger.log("0", userInfo,null,"Key Details Map="+keyDetailMap);
			BaseLogger.log("0", userInfo,null,"Node Map="+nodeMap);
			for(Map.Entry<String,String>entry:keyDetailMap.entrySet()) {
				BaseLogger.log("0", userInfo,null,"Key found in Map="+entry.getKey());
				BaseLogger.log("0", userInfo,null,"value found in Map="+entry.getValue());
				Node childNode =null;
				if(!entry.getKey().equals("")||entry.getKey()!=null ||!entry.getKey().equals(null)) {
					
					if(nodeMap.containsKey(entry.getKey())) {
						
						List<Node> childNodeList   = nodeMap.get(entry.getKey());
						
						for(int i=0;i<childNodeList.size();i++) {
							Node rowNode = childNodeList.get(i);
							BaseLogger.log("0", userInfo,null,"Row  Node Name="+rowNode.getNodeName());
							if(!rowNode.getNodeName().contains("#")) 
							{
								
								NodeList dataNodes = rowNode.getChildNodes();
								
								for(int k=0;k<dataNodes.getLength();k++) {
									Node data = dataNodes.item(k);
									if(!data.getNodeName().contains("#")) {
							
										strBuilder.append("<"+data.getNodeName()+"><![CDATA["+
										data.getTextContent()+"]]>"+
										"</"+data.getNodeName()+">");
								
									}
								}
								strBuilder.append("</"+entry.getValue()+">");
							}
						}					
					}
					
				}
				
			}
			strBuilder.append("</Root>");
			System.out.println("String to return=with cdata["+strBuilder.toString());
			BaseLogger.log("0", userInfo,null,"xmlString=["+xmlString+"]");
			xmlString = strBuilder.toString();
		} catch (Exception e) {
			BaseLogger.log("0", userInfo,null,"Exception in Reading xml file"+e.getMessage());
		}
		
		return xmlString;
	}
	//Added by Ankush S. on 07-Nov-2022[create detail xml string from xmlFile data]END
	
	//Added by Prasad on 29/10/18 [creating a common method from schedular and manually] START
	private String getUploadDataDBId( String uploadData )
	{
		String dbId = "";
		try 
		{
			Document uploadDataDom = genericUtility.parseString( uploadData );
			Node parentNode = uploadDataDom.getElementsByTagName( "Detail1" ).item( 0 );
			if ( parentNode != null && parentNode.getAttributes().getNamedItem( "dbID" ) != null )
			{
				dbId = parentNode.getAttributes().getNamedItem( "dbID" ).getNodeValue();
			}
		}
		catch (ITMException e) 
		{
			//e.printStackTrace();
			//Added by amol s on 23-Oct -24 --strt
			BaseLogger.log("3", null, null,
                    "Exception in getUploadDataDBId [" + E12GenericUtility.getStackTrace(e) + "]");
			//throw new ITMException(e); show error

			//Added by amol s on 23-Oct -24  --end

		}
		catch (DOMException e) 
		{
			//Added by amol s on 23-Oct -24 --strt
			BaseLogger.log("3", null, null,
                    "Exception in getUploadDataDBId [" + E12GenericUtility.getStackTrace(e) + "]");
			//Added by amol s on 23-Oct -24  --end

		}
		BaseLogger.log( "2", userInfo, null, "dbId : ["+ dbId +"]" );
		return dbId;
	}
	
	//Added by Ravindra on 11/05/2021 [to save error message in batchload] START
	private HashMap<String, MasterApplyEJB> objWiseMasterApplyMap = new HashMap<String, MasterApplyEJB>();
	private MasterApplyEJB getMasterApplyEJB( String objName, UserInfoBean userInfo )
	{
		MasterApplyEJB masterApply = null;
		if ( objWiseMasterApplyMap.containsKey( objName ) )
		{
			masterApply = objWiseMasterApplyMap.get( objName );
		}
		if ( masterApply == null )
		{
			masterApply = new MasterApplyEJB();
			masterApply.setObjFormDetail( objName, userInfo );
			objWiseMasterApplyMap.put( objName, masterApply );
		}
		return masterApply;
	}
	//Added by Ravindra on 11/05/2021 [to save error message in batchload] END

	//Changed by Ravindra C on 19/01/2021 [to send notification in case of error in uploading]
	private String generateUploadResponse( String objName, String responseStr, String tempFileName, String batchId, int rowNo, String excelDataDBId, String xmlStr, Connection conn, MasterApplyEJB masterApplyEJB ) throws ITMException
	{
		StringBuffer responseHTMLBuff = new StringBuffer();

		try 
		{
			if ( masterApplyEJB == null )
			{
				masterApplyEJB = new MasterApplyEJB();
			}
			
			String dataDumpFolderName = "XLS_UPLOAD";
			if( tempFileName.endsWith( ".json" ) )
			{
				dataDumpFolderName = "JSON_UPLOAD";
			}
			String uploadedFilePath = CommonConstants.JBOSSHOME + File.separator + dataDumpFolderName + File.separator + getUserInfoBean().getLoginCode() + File.separator + batchId;
			String uploadFileName = (batchId + "_" + rowNo + ".xml");
			
			responseHTMLBuff.append( "<TR>" );
			Document responseDom = genericUtility.parseString( responseStr );
			Node errorsNode = null;
			if ( responseDom != null && responseDom.getElementsByTagName( "Errors" ) != null )
			{
				errorsNode = responseDom.getElementsByTagName( "Errors" ).item( 0 );
			}
			BaseLogger.log( "3", userInfo, null, "errorsNode ["+ errorsNode +"]" );
			if( errorsNode != null )
			{
				//Changed by Pankaj T on 31-07-2018 [For upload utility if error occurs then rollBack the transaction]-Start
				if( conn != null )
				{
					BaseLogger.log("3",userInfo,null, "Rollback the Changes when error found......");
					conn.rollback();
				}
				//Changed by Pankaj T on 31-07-2018 [For upload utility if error occurs then rollBack the transaction]-End
				String errorMessage = "";
				String msg = "", descr = "", trace = "", redirect = ""; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
				NodeList errorChildNodeList = errorsNode.getChildNodes();
				for(int appCnt = 0; appCnt < errorChildNodeList.getLength(); appCnt++)
				{
					String errCode = "";
					String errorType = "";
					String columnName = "";
					Node currChild = errorChildNodeList.item(appCnt);

					if (currChild.getNodeName().equalsIgnoreCase("error")) //$NON-NLS-1$
					{
						errorType = currChild.getAttributes().getNamedItem( "type" ).getNodeValue(); //$NON-NLS-1$

						if (currChild.getAttributes().getNamedItem("column_name") != null) //$NON-NLS-1$
						{
							columnName = currChild.getAttributes().getNamedItem("column_name").getNodeValue();
						}
						errCode = currChild.getAttributes().getNamedItem("id") == null ? "" : currChild.getAttributes().getNamedItem("id").getNodeValue();

						StringBuffer responseHTML = new StringBuffer();
						NodeList currChildList = currChild.getChildNodes();
						for (int ctr = 0; ctr < currChildList.getLength(); ctr++)
						{
							Node currNode = currChildList.item(ctr);
							if (currNode.getNodeName().equalsIgnoreCase("message") && currNode.getFirstChild() != null) //$NON-NLS-1$
							{
								msg = currNode.getFirstChild().getNodeValue();									
							}
							else if (currNode.getNodeName().equalsIgnoreCase("description") && currNode.getFirstChild() != null) //$NON-NLS-1$
							{
								String descrAppendStr = "";
								descr = currNode.getFirstChild().getNodeValue().trim();
								if( descr.endsWith("]") ) //$NON-NLS-1$
								{
									descr = descr.replaceAll(descr.substring(descr.lastIndexOf("]")-1),new Integer(rowNo).toString()+"]");										 //$NON-NLS-1$ //$NON-NLS-2$
								}
								else
								{
									//descr = descr +" Error occurred on insertion of record no. :["+(rowNo)+"]"; //$NON-NLS-1$ //$NON-NLS-2$
									descrAppendStr = " Error occurred on insertion of record no. :["+(rowNo)+"]";
								}									
								responseHTML.append( "<b>"+Messages.getString("ITMUploadFileEJB_description")+"</b>"+descr + descrAppendStr ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
							}
							else if (currNode.getNodeName().equalsIgnoreCase("trace") && currNode.getFirstChild() != null) //$NON-NLS-1$
							{
								trace = currNode.getFirstChild().getNodeValue();	
								responseHTML.append( "</br><b>"+Messages.getString("ITMUploadFileEJB_trace")+"</b>"+trace );
							}
							else if (currNode.getNodeName().equalsIgnoreCase("redirect") && currNode.getFirstChild() != null) //$NON-NLS-1$
							{
								redirect = currNode.getFirstChild().getNodeValue();
							}
						}
						if ( errCode != null && errCode.length() > 0 )
						{
//							errorMessage += errorType + ":" + errCode + ":" + descr + "\n";
							// Changes by Gagan B. on 15-DEC-23 to add trace in BATCHLOAD.ERROR_MSG
							errorMessage += errorType + ":" + errCode + ":" + descr + ": trace: "+ trace + "\n";
							if(errorMessage.length() > 2000) {
								errorMessage = errorMessage.substring(0, 2000);
							}
							
						}
						else
						{
							errorMessage += errorType + ":" + descr + "\n";
						}

						responseHTMLBuff.append( "<TD WIDTH=4%>"+(rowNo)+"</TD>" );
						if ( "P".equalsIgnoreCase(errorType) )
						{
							responseHTMLBuff.append( "<TD WIDTH=48%>"+Messages.getString("ITMUploadFileEJB_recordNo")+(rowNo)+Messages.getString("ITMUploadFileEJB_successUploaded")+"</TD>" );
							responseHTMLBuff.append( "<TD WIDTH=48% VALIGN=TOP><P><FONT SIZE=1 STYLE='font-size: 10pt'>" );
							responseHTMLBuff.append( "</FONT></P>" );
							responseHTMLBuff.append( "</TD>" );
						}
						else
						{
							responseHTMLBuff.append( "<TD WIDTH=48%>"+Messages.getString("ITMUploadFileEJB_recoreNotUploaded")+"</TD>" );
							responseHTMLBuff.append( "<TD WIDTH=48% VALIGN=TOP><P><FONT SIZE=1 STYLE='font-size: 10pt'>" );
							responseHTMLBuff.append( Messages.getString("ITMUploadFileEJB_errorForColumnName")+ columnName +"</br>");
							responseHTMLBuff.append( responseHTML );
							responseHTMLBuff.append( "</FONT></P>" );
							responseHTMLBuff.append( "</TD>" );
						}
					}
				}
				if ( errorMessage != null && errorMessage.endsWith( "\n" ) )
				{
					errorMessage = errorMessage.substring( 0, errorMessage.length() - 1 );
				}
				
				String uploadLogFileName = (batchId + "_" + rowNo + ".log");
				String logFilePath = uploadedFilePath + File.separator + "log";
				writeLog( uploadLogFileName, logFilePath, null, responseStr );
				
				String errorFilePath = uploadedFilePath + File.separator + "failed";
				moveFile( uploadFileName, uploadedFilePath, errorFilePath, null );
				
				masterApplyEJB.updateBatchLoad( batchId, rowNo, errorMessage, "E", excelDataDBId, conn, userInfo );
				
				//Added by Ravindra C on 19/01/2021 [to send notification in case of error in uploading] 
				//Changed by Ravindra on 12/03/2021 [Pass transaction xml to mail component]
				sendNotification( "E", objName, batchId, ""+ rowNo, excelDataDBId, xmlStr, errorMessage, conn );
			}
			else
			{
				String tranId = genericUtility.getColumnValue( "TranID", responseDom );
				globalTranID = tranId; //Added by Gagan B. on 17th-FEB-23 to share tranId with setDataAndConfirm API.
				BaseLogger.log( "3", userInfo, null, "tranId.......[" + tranId + "]" );

				responseHTMLBuff.append( "<TD WIDTH=4%>"+(rowNo)+"</TD>" );
				responseHTMLBuff.append( "<TD WIDTH=48%>"+tranId+"</TD>" );
				responseHTMLBuff.append( "<TD WIDTH=48%>" );
				responseHTMLBuff.append( "<P>"+Messages.getString("ITMUploadFileEJB_recordNo")+(rowNo)+Messages.getString("ITMUploadFileEJB_successfullyUploaded")+"</P>" );
				responseHTMLBuff.append( "</TD>" );

				String successFilePath = uploadedFilePath + File.separator + "success";
				moveFile( uploadFileName, uploadedFilePath, successFilePath, null );
				
				masterApplyEJB.updateBatchLoad( batchId, rowNo, "Uploaded successfully", "Y", tranId, conn, userInfo );
			}
			//masterApplyEJB.sendWebSocketNotification( batchId, conn, getUserInfoBean() );
			responseHTMLBuff.append( "</TR>" );
		}
		catch (ITMException e) 
		{
			//Added by Amol s on 23-oct --strt
			//MasterApplyEJB masterApplyEJB = new MasterApplyEJB();
			masterApplyEJB.updateBatchLoad( batchId, rowNo, "E", "", null, getUserInfoBean() );
			BaseLogger.log("3", null, null,
            "Exception2 in processEDIBatchload [" + E12GenericUtility.getStackTrace(e) + "]");
			throw new ITMException( e );
			//Added by Amol s -end
		}
		catch (DOMException e) 
		{
			//MasterApplyEJB masterApplyEJB = new MasterApplyEJB();
			masterApplyEJB.updateBatchLoad( batchId, rowNo, "E", "", null, getUserInfoBean() );
			BaseLogger.log("3", null, null,
            "Exception2 in processEDIBatchload [" + E12GenericUtility.getStackTrace(e) + "]");
			throw new ITMException( e );
			//Added by Amol s -end
		}
		catch (SQLException e) 
		{
			//MasterApplyEJB masterApplyEJB = new MasterApplyEJB();
			masterApplyEJB.updateBatchLoad( batchId, rowNo, "E", "", null, getUserInfoBean() );
			BaseLogger.log("3", null, null,
            "Exception2 in processEDIBatchload [" + E12GenericUtility.getStackTrace(e) + "]");
			throw new ITMException( e );
			//Added by Amol s -end
		}
		return responseHTMLBuff.toString();
	}
	//Added by Prasad on 29/10/18 [creating a common method from schedular and manually] END

	private String checkNull( String input )
	{
		if( input == null )
		{
			input = ""; //$NON-NLS-1$
		}
		return input;
	}

	private void createUploadLog( String errStr, String fileName )throws RemoteException, ITMException
	{
		try
		{
			//added by vishal Pathare
			BaseLogger.log( "3", userInfo, null, "fileName ["+ fileName +"]" );
			String logFileName = fileName.substring( 0, fileName.indexOf( "." ) ); //$NON-NLS-1$
			//String logFile = logFileName+".log";
			String logFile = System.currentTimeMillis() + "_" + userInfo.getLoginCode() + "_" + logFileName +".log";
			String commonDestinationFilePath = ( new File( CommonConstants.UPLOAD_LOC ) ) + File.separator + "upload_log";
			String destinationFilePath = "";
			//changed by vishal on 14.5.17 for [enterprise implementation in for file upload ejb]Start.
			if( FILE_UPLOAD_LOG_PATH.length() > 0 )
			{
				//Changed by Amey on 29/10/18 [SFTP implementation related changes]
				if( IS_FTP_PATH || IS_SFTP_PATH )
				{
					moveLogFileOnRemote( FILE_UPLOAD_LOG_PATH, logFile, errStr );
					return;
				}
				else
				{
					destinationFilePath = ( new File( FILE_UPLOAD_LOG_PATH) ) + "";
				}
			}
			else 
			{
				destinationFilePath = commonDestinationFilePath; //$NON-NLS-1$
			}
			//added by vishal on 14.5.17 for [enterprise implementation in for file upload ejb]End.
			//$NON-NLS-1$
			writeLog( logFile, destinationFilePath, commonDestinationFilePath, errStr );
		}
		catch(Exception e)
		{
			BaseLogger.log("0", userInfo,null,"ITMException :UploadFileEJB :==>createUploadLog["+e.getMessage()); //$NON-NLS-1$
			e.printStackTrace();
			throw new ITMException(e);
		}
	}
	
	private void writeLog( String logFile, String destinationFilePath, String commonDestinationFilePath, String logData ) throws ITMException
	{
		try
		{
			BaseLogger.log( "3", userInfo, null, "logFile ["+ logFile +"]" );
			BaseLogger.log( "3", userInfo, null, "destinationFilePath ["+ destinationFilePath +"]" );
			BaseLogger.log( "3", userInfo, null, "commonDestinationFilePath ["+ commonDestinationFilePath +"]" );
			
			File dir = new File(destinationFilePath);
			if ( ! dir.exists() )
			{
				dir.mkdirs();
			}
			BaseLogger.log( "3", userInfo, null, "dir["+ dir +"]" ); //$NON-NLS-1$ //$NON-NLS-2$
			dir = new File( destinationFilePath );
			if ( ! dir.exists() )
			{
				BaseLogger.log( "3", userInfo, null, "Destination File Path not exist........" );
				if ( commonDestinationFilePath != null )
				{
					dir = new File( commonDestinationFilePath );
					if ( ! dir.exists() )
					{
						dir.mkdirs();
					}
					BaseLogger.log( "3", userInfo, null, "set to common log dir["+ dir +"]" ); //$NON-NLS-1$ //$NON-NLS-2$
				}
			}

			FileWriter fstream = new FileWriter( dir + File.separator + logFile ); //$NON-NLS-1$
			BufferedWriter out = new BufferedWriter(fstream);
			out.write( logData );	
			out.flush();
			out.close();
		}
		catch(Exception e)
		{
			BaseLogger.log("0", userInfo,null,"ITMException :UploadFileEJB :==>createUploadLog["+e.getMessage()); //$NON-NLS-1$
			e.printStackTrace();
			throw new ITMException(e);
		}
	}
	
	public void moveUploadFile( String newFileName , File DUMP_DIR ) throws RemoteException, ITMException
	{
		BaseLogger.log("2", userInfo,null,"Enter in moveUploadFile function .........[" + newFileName + "]"); //$NON-NLS-1$ //$NON-NLS-2$
		try
		{
			//String sourceFilePath =  DUMP_DIR + File.separator + newFileName;
			//String destinationFilePath = ( new File( CommonConstants.UPLOAD_LOC ) ) + File.separator + "dump_upd"; //$NON-NLS-1$
			//String destinationFilePath = ( new File( CommonConstants.UPLOAD_LOC ) ) + File.separator + "upload_success"; //$NON-NLS-1$
			//added by vishal Pathare
			String destinationFilePath = "";
			if( FILE_UPLOAD_SUCC_PATH.length() > 0 )
			{
				if( IS_FTP_PATH )
				{
					moveFileOnRemote( DUMP_DIR, FILE_UPLOAD_SUCC_PATH, newFileName );
					return;
				}
				//Changed by Amey on 29/10/18 [SFTP implementation related changes] START
				else if( IS_SFTP_PATH )
				{
					uploadFileSFTP( DUMP_DIR, FILE_UPLOAD_SUCC_PATH, newFileName );
					return;
				}
				//Changed by Amey on 29/10/18 [SFTP implementation related changes] E
				else
				{
					destinationFilePath = ( new File( FILE_UPLOAD_SUCC_PATH) ) + "";
				}
			}
			else 
			{
				destinationFilePath = commonUploadSuccessFilePath;
			}
			moveFile( newFileName, DUMP_DIR.getAbsolutePath(), destinationFilePath, commonUploadSuccessFilePath );
		}
		catch (Exception e)
		{
			BaseLogger.log("0", userInfo,null,"Exception :UploadFileEJB : deleteUploadFile :==>\n"+e.getMessage()); //$NON-NLS-1$
			e.printStackTrace();
		}
	}

	private void moveErrorFile( String newFileName, File DUMP_DIR ) throws RemoteException, ITMException
	{
		BaseLogger.log("2", userInfo,null,"Eneter in moveUploadFile function .........[" + newFileName + "]"); //$NON-NLS-1$ //$NON-NLS-2$
		try
		{
			///Chnaged by vishal on 14.5.17 for [enterprise implementation in for file upload ejb]Start.
			//String sourceFilePath = DUMP_DIR + File.separator + newFileName;
			//String destinationFilePath = ( new File( CommonConstants.UPLOAD_LOC ) ) + File.separator + "upload_log"; //$NON-NLS-1$
			//String destinationFilePath = ( new File( CommonConstants.UPLOAD_LOC ) ) + File.separator + "upload_failed"; //$NON-NLS-1$
			String destinationFilePath = "";
			if( FILE_UPLOAD_REJ_PATH.length() > 0 )
			{
				if( IS_FTP_PATH )
				{
					moveFileOnRemote( DUMP_DIR, FILE_UPLOAD_REJ_PATH, newFileName );
					return;
				}
				//Changed by Amey on 29/10/18 [SFTP implementation related changes] START
				else if( IS_SFTP_PATH )
				{
					uploadFileSFTP( DUMP_DIR, FILE_UPLOAD_REJ_PATH, newFileName );
					return;
				}
				//Changed by Amey on 29/10/18 [SFTP implementation related changes] END
				else
				{
					destinationFilePath = ( new File( FILE_UPLOAD_REJ_PATH) ) + "";
				}
			}
			else
			{
				destinationFilePath = commonUploadFailedFilePath;
			}
			//added by vishal on 14.5.17 for [enterprise implementation in for file upload ejb]End.
			moveFile( newFileName, DUMP_DIR.getAbsolutePath(), destinationFilePath, commonUploadFailedFilePath );
		}
		catch (Exception e)
		{
			BaseLogger.log("0", userInfo,null,"Exception : ITMUploadFileEJB : moveErrorFile :==>\n"+e.getMessage()); //$NON-NLS-1$
			e.printStackTrace();
		}
	}
	
	private void moveFile( String newFileName, String sourceFilePathDir, String destinationFilePath, String commonDestinationFilePath ) throws ITMException
	{
		String sourceFilePath = sourceFilePathDir + File.separator + newFileName;
		BaseLogger.log( "3", userInfo, null, "sourceFilePath ["+ sourceFilePath +"]" );
		BaseLogger.log( "3", userInfo, null, "destinationFilePath ["+ destinationFilePath +"]" );
		BaseLogger.log( "3", userInfo, null, "commonDestinationFilePath ["+ commonDestinationFilePath +"]" );
		
		File file = new File( sourceFilePath );
		if ( file.exists() )
		{
			BaseLogger.log( "3", userInfo, null, "File Exist........" ); //$NON-NLS-1$
			File dir = new File(destinationFilePath);
			if ( ! dir.exists() )
			{
				dir.mkdirs();
			}
			BaseLogger.log( "3", userInfo, null, "dir["+ dir +"]" ); //$NON-NLS-1$ //$NON-NLS-2$
			dir = new File( destinationFilePath );
			if ( ! dir.exists() )
			{
				BaseLogger.log( "3", userInfo, null, "Destination File Path not exist........" );
				if ( commonDestinationFilePath != null )
				{
					dir = new File( commonDestinationFilePath );
					if ( ! dir.exists() )
					{
						dir.mkdirs();
					}
					BaseLogger.log( "3", userInfo, null, "moved to common failed dir["+ dir +"]" ); //$NON-NLS-1$ //$NON-NLS-2$
				}
			}
			boolean success = file.renameTo( new File( dir, file.getName() ) );
			if ( ! success )
			{
				BaseLogger.log( "3", userInfo, null, "File was not moved" ); //$NON-NLS-1$
			}
		}
		else
		{
			BaseLogger.log( "3", userInfo, null, "File not exist to move" );
		}
	}
	
	//Changed by yogesh on 04-oct-11 [DI1BSUN011 | upload xml data in to batchload] start
	private String getXtraParams(ibase.utility.UserInfoBean userInfo)throws Exception
	{
		final String XTRA_PARAMS_SEPARATOR = "~~"; //$NON-NLS-1$
		StringBuffer xtraParamsBuff = new StringBuffer();

		xtraParamsBuff.append("loginCode=" + userInfo.getLoginCode()); //$NON-NLS-1$
		xtraParamsBuff.append(XTRA_PARAMS_SEPARATOR).append("loginEmpCode=" + userInfo.getEmpCode()); //$NON-NLS-1$
		xtraParamsBuff.append(XTRA_PARAMS_SEPARATOR).append("loginSiteCode=" + userInfo.getSiteCode()); //$NON-NLS-1$
		xtraParamsBuff.append(XTRA_PARAMS_SEPARATOR).append("entityCode=" + userInfo.getEntityCode()); //$NON-NLS-1$
		xtraParamsBuff.append(XTRA_PARAMS_SEPARATOR).append("profileId=" + userInfo.getProfileId()); //$NON-NLS-1$
		xtraParamsBuff.append(XTRA_PARAMS_SEPARATOR).append("userType=" + userInfo.getUserType()); //$NON-NLS-1$
		xtraParamsBuff.append(XTRA_PARAMS_SEPARATOR).append("runMode=I"); //$NON-NLS-1$
		xtraParamsBuff.append(XTRA_PARAMS_SEPARATOR).append("termId="+userInfo.getRemoteHost()); //$NON-NLS-1$
		String chgTerm = userInfo.getRemoteHostName();

		if( chgTerm != null && chgTerm.length() > 15 )
		{
			chgTerm = chgTerm.substring(0, 15);
		}
		else if( chgTerm == null || chgTerm.length() == 0 )
		{
			chgTerm = userInfo.getRemoteHost();
		}

		xtraParamsBuff.append(XTRA_PARAMS_SEPARATOR).append("chgTerm=" + chgTerm ); //$NON-NLS-1$
		return xtraParamsBuff.toString();
	}
	//Changed by yogesh on 04-oct-11 [DI1BSUN011 | upload xml data in to batchload] end

	/**
	 * @return the userInfoBean
	 */
	public UserInfoBean getUserInfoBean() 
	{
		return userInfo;
	}
	
	/**
	 * @param userInfoBean the userInfoBean to set
	 */
	public void setUserInfoBean(UserInfoBean userInfoBean) 
	{
		this.userInfo = userInfoBean;
	}

	private DBAccessEJB getDBAccess()
	{
		try 
		{
			if ( dbAccess == null )
			{
				//AppConnectParm appConnect = new AppConnectParm();
				//InitialContext initialContext = new InitialContext(appConnect.getProperty());

				//dbAccess = (DBAccessLocal) initialContext.lookup("ibase/DBAccessEJB/local");
				dbAccess = new DBAccessEJB();
			}
		}
		/*catch (NamingException e) 
		{
			e.printStackTrace();
		}*/
		catch (Exception e) 
		{
			e.printStackTrace();
		}

		return dbAccess;
	}

	//added by vishal on 14.5.17 for [enterprise implementation in for file upload ejb]Start.
	private void setEnterpriseWiseUploadPath(UserInfoBean userInfo) throws Exception 
	{
		String enterpriseValue = E12GenericUtility.checkNull( userInfo.getEnterprise() );
		BaseLogger.log("2", userInfo,null, "enterpriseValue ; ["+enterpriseValue+"]" );

		if( enterpriseValue.length() > 0 )
		{
			Connection conn = null;
			PreparedStatement pstmt = null;
			ResultSet rs = null;

			try 
			{
				ConnDriver connDriver = new ConnDriver();
				String transDB = userInfo.getTransDB();
				conn = connDriver.getConnectDB( transDB );

				connDriver = null;

				String sql = "SELECT FILE_UPLOAD_SRC,FILE_UPLOAD_REJ,FILE_UPLOAD_SUC, FILE_UPLOAD_LOG,FILE_UPLOAD_USER,FILE_UPLOAD_PASS,FILE_UPLOAD_HOST,FILE_UPLOAD_PORT "
						+ " FROM ENTERPRISE "
						+ " WHERE TRIM( ENTERPRISE ) = ?";

				pstmt = conn.prepareStatement( sql );
				pstmt.setString(1, enterpriseValue);
				rs = pstmt.executeQuery();
				if( rs.next() )
				{
					FTP_HOST_URL = E12GenericUtility.checkNull( rs.getString( "FILE_UPLOAD_HOST" ));
					ftpUserName = E12GenericUtility.checkNull( rs.getString( "FILE_UPLOAD_USER" ));
					ftpPassword = E12GenericUtility.checkNull( rs.getString( "FILE_UPLOAD_PASS" ));
					//Added by Amey on 29/10/18 [file upload port column added in enterprise]
					fileUploadPort = E12GenericUtility.checkNull( rs.getString( "FILE_UPLOAD_PORT" ));
					String fileUploadSrcPath = E12GenericUtility.checkNull( rs.getString( "FILE_UPLOAD_SRC" )); 
					String fileUploadRejectPath = E12GenericUtility.checkNull( rs.getString( "FILE_UPLOAD_REJ" )); 
					String fileUploadSuccessPath = E12GenericUtility.checkNull( rs.getString( "FILE_UPLOAD_SUC" ));
					String fileUploadLogPath1 = E12GenericUtility.checkNull( rs.getString( "FILE_UPLOAD_LOG" ));

					BaseLogger.log("3", userInfo,null, "fileUploadSrcPath : ["+ FILE_UPLOAD_SRC_PATH +"]" +
							"\n fileUploadRejectPath : ["+ FILE_UPLOAD_REJ_PATH +"]" +
							"\n fileUploadSuccessPath : ["+ FILE_UPLOAD_SUCC_PATH +"]" +
							"\n fileUploadLogPath : ["+ FILE_UPLOAD_LOG_PATH +"]" +
							"\n ftpUserName : ["+ ftpUserName +"]" +
							"\n ftpPassword : ["+ ftpPassword +"]" +
							"\n FTP_HOST_URL : ["+ FTP_HOST_URL +"]"+
							"\n FILE_UPLOAD_PORT : ["+ fileUploadPort +"]"+
							"\n fileUploadSrcPath : ["+ fileUploadSrcPath +"]"+
							"\n fileUploadRejectPath : ["+ fileUploadRejectPath +"]"+
							"\n fileUploadLogPath1 : ["+ fileUploadSuccessPath +"]");

					//Changed by Amey W on 19.10.18 for [For SFTP Connection] START.
					/*if( FTP_HOST_URL.length() > 0 )
					{
						IS_FTP_PATH = true;
					}
					else
					{
						IS_FTP_PATH = false;
					}*/
					if( FTP_HOST_URL.length() > 0 )
					{
						if(FTP_HOST_URL.toLowerCase().startsWith("ftp"))
						{
							IS_FTP_PATH = true;
						}
						else if(FTP_HOST_URL.toLowerCase().startsWith("sftp"))
						{
							IS_SFTP_PATH = true;
						}
					}
					else
					{
						IS_FTP_PATH = false;
						IS_SFTP_PATH = false;
					}
					//added by Amey W on 19.10.18 for [For SFTP Connection] END.

					FILE_UPLOAD_SRC_PATH = updatePath( fileUploadSrcPath );
					FILE_UPLOAD_REJ_PATH = updatePath( fileUploadRejectPath );
					FILE_UPLOAD_SUCC_PATH = updatePath( fileUploadSuccessPath );
					FILE_UPLOAD_LOG_PATH = updatePath( fileUploadLogPath1 );
				}
				if( rs!=null)
				{
					rs.close();
					rs = null;
				}
				if( pstmt!=null )
				{
					pstmt.close();
					pstmt = null;
				}
				if( conn!=null)
				{
					conn.close();
				}
			}
			catch ( SQLException e ) 
			{
				e.printStackTrace();
				throw new ITMException(e);
			}
			catch ( Exception e ) 
			{
				e.printStackTrace();
			}
			finally
			{
				if( rs!=null)
				{
					rs.close();
					rs = null;
				}
				if( pstmt!=null )
				{
					pstmt.close();
					pstmt = null;
				}
				if( conn!=null)
				{
					conn.close();
				}
			}
		}
		else
		{
			FILE_UPLOAD_SRC_PATH="";
			FILE_UPLOAD_REJ_PATH="";
			FILE_UPLOAD_SUCC_PATH="";
			FILE_UPLOAD_LOG_PATH="";
		}
	}

	private String updatePath(String fileUploadSrcPath) 
	{
		Date currentDate= new Date(System.currentTimeMillis());
		if( fileUploadSrcPath.contains("YYYY") )
		{
			SimpleDateFormat sd = new SimpleDateFormat("YYYY");
			String strDate=sd.format(currentDate);
			fileUploadSrcPath = fileUploadSrcPath.replace("YYYY", strDate);
		}
		if( fileUploadSrcPath.contains("MMM") )
		{
			SimpleDateFormat sd = new SimpleDateFormat("MMM");
			String strDate=sd.format(currentDate);
			fileUploadSrcPath = fileUploadSrcPath.replace("MMM", strDate.toUpperCase());
		}
		if( fileUploadSrcPath.contains("MM") )
		{
			SimpleDateFormat sd = new SimpleDateFormat("MM");
			String strDate=sd.format(currentDate);
			fileUploadSrcPath = fileUploadSrcPath.replace("MM", strDate);
		}
		BaseLogger.log("2", userInfo,null,"fileUploadSrcPath["+fileUploadSrcPath+"]");
		return fileUploadSrcPath;
	}

	private boolean createFTPConnection() throws Exception
	{
		boolean ftpConn = false;
		try
		{
			BaseLogger.log("3", userInfo,null,"createFTPConnection ftpClient["+ftpClient+"]");
			ftpClient = null;
			//added by Amey W on 19.10.18 for [For SFTP Connection] START.
			String ftpHostUrl = "";
			if ( FTP_HOST_URL.startsWith("ftp://") )
			{
				ftpHostUrl = FTP_HOST_URL.replace("ftp://", "");
				BaseLogger.log("0", userInfo,null,ftpHostUrl+" ftp ="+ftpHostUrl.length());
			}	
			String server = ftpHostUrl;
			int port = 21;
			if ( fileUploadPort != null )
			{
				port = Integer.valueOf(fileUploadPort);
			}
			//added by Amey W on 19.10.18 for [For SFTP Connection] END.
			String user = ftpUserName;
			String pass = ftpPassword;
			BaseLogger.log("3", userInfo,null,"ftpClient["+ftpClient+"]");

			ftpClient = new FTPClient();
			BaseLogger.log("3", userInfo,null,"ftpClient1["+ftpClient+"]");
			ftpClient.connect( server, port );
			ftpClient.login( user, pass );
			ftpClient.enterLocalPassiveMode();
			ftpClient.setFileType( FTP.BINARY_FILE_TYPE );

			BaseLogger.log("3", userInfo,null,"ftpClient["+ftpClient+"]");
			BaseLogger.log("3", userInfo,null,"ftp client connected on Dir["+ ftpClient.printWorkingDirectory() +"]");
			int replyCode = ftpClient.getReplyCode();
			if( ftpClient.getReplyCode() == 530 )
			{
				createLogAndSendMail( replyCode, getServerReplyString());
				ftpConn = false; 
			}
			else
			{
				ftpConn = true; 
			}
			return ftpConn;
		}
		catch (Exception e)
		{
			BaseLogger.log("0", userInfo,null,"Exception in createFTPConnection()["+e.getMessage()+"]");
			setFTPExceptionLog( ftpClient.getReplyCode(), getServerReplyString(), e.getMessage());
			return false;
		}
	}

	//Changed by Prasad on 13/01/2021 [set dynamic value to isRetainPkValue]
	private void readFilesByFTP( File dUMP_DIR, UserInfoBean userInfo, String isIntractive, String objName, String oriFileName, boolean isExcelDriver, boolean isRetainPkValue ) throws IOException  
	{
		BaseLogger.log("2", userInfo,null,"readFilesByFTP called");
		try 
		{
			boolean ftpConn = createFTPConnection();
			if( ! ftpConn )
			{
				return;
			}
			BaseLogger.log("3", userInfo,null, "FILE_UPLOAD_SRC_PATH : ["+ FILE_UPLOAD_SRC_PATH +"]" );

			FTPFile[] files = ftpClient.listFiles( FILE_UPLOAD_SRC_PATH );
			for ( FTPFile file : files )
			{
				String fileName = file.getName();
				if( ! file.isDirectory() )
				{
					BaseLogger.log("3", userInfo,null,"fileName1["+fileName+"]");
					//download remote file
					boolean isDownload = downloadRemoteFile( ftpClient, fileName, dUMP_DIR );

					if ( isDownload )
					{
						try
						{
							BaseLogger.log("3", userInfo,null,"file download ");
							String [] fileInfoArr = new String[4];
							fileInfoArr[0] = isIntractive;
							fileInfoArr[1] = fileName;
							fileInfoArr[2] = objName;
							fileInfoArr[3] = oriFileName;

							//Changed by Prasad on 13/01/2021 [set dynamic value to isRetainPkValue]
							insertFileData( fileInfoArr, userInfo, dUMP_DIR, CommonConstants.APPLICATION_CONTEXT, "", isExcelDriver, isRetainPkValue );
						}
						catch(Exception e )
						{
							BaseLogger.log("3", userInfo,null,"Error in insertFileData By FTP: " + e.getMessage());
							e.printStackTrace();
							setFTPExceptionLog( ftpClient.getReplyCode(), getServerReplyString(), e.getMessage());
						}
					}
					else
					{
						createLogAndSendMail( ftpClient.getReplyCode(), getServerReplyString() );
					}
				}
				else
				{
					BaseLogger.log("3", userInfo,null, "isDirectory : ["+ fileName +"]" );
				}
			}
			boolean completed = false;
			try 
			{
				completed = ftpClient.completePendingCommand();
			} 
			catch (Exception e)
			{
				if( ftpClient!=null )
				{
					ftpClient.logout();
					ftpClient.disconnect();
				}
				BaseLogger.log("0", userInfo,null,"Exception in completePendingCommand");
			}
			if( completed )
			{
				disconnectFTP();
				BaseLogger.log("3", userInfo,null,"file Moving completed");
			}
		} 
		catch (Exception ex) 
		{
			BaseLogger.log("0", userInfo,null,"Error in read Files By FTP: " + ex.getMessage());
			ex.printStackTrace();
			setFTPExceptionLog( ftpClient.getReplyCode(), getServerReplyString(), ex.getMessage());
			ftpClient.logout();
			ftpClient.disconnect();
		} 
		finally
		{
			try 
			{
				if (ftpClient.isConnected())
				{
					ftpClient.logout();
					ftpClient.disconnect();
				}
			} 
			catch (IOException ex) 
			{
				ex.printStackTrace();
			}
		}
	}

	private void disconnectFTP() throws IOException 
	{
		boolean completed;
		try 
		{
			completed = ftpClient.completePendingCommand();

			if (completed)
			{
				ftpClient.logout();
				ftpClient.disconnect();
			}
		}
		catch (IOException e)
		{
			ftpClient.logout();
			ftpClient.disconnect();
		}
	}

	private boolean downloadRemoteFile( FTPClient ftpClient, String fileName, File dUMP_DIR ) throws IOException 
	{
		boolean isDownload = false;
		try 
		{
			File downloadFile = new File( dUMP_DIR + "" );
			if( ! downloadFile.exists() )
			{
				downloadFile.mkdirs();
				BaseLogger.log("3", userInfo,null, "Download file path created" );
			}

			downloadFile = new File( ( new File( downloadFile+"" ) ) + File.separator + fileName ); 
			BaseLogger.log("3", userInfo,null, "downloadFile path: ["+ downloadFile +"]" );
			OutputStream outputStream = new BufferedOutputStream( new FileOutputStream( downloadFile ) );
			isDownload = ftpClient.retrieveFile( FILE_UPLOAD_SRC_PATH + File.separator + fileName, outputStream );
			outputStream.close();
			if( isDownload ) 
			{
				BaseLogger.log("3", userInfo,null,"File name:"+fileName+"has been downloaded successfully");
			}
			else
			{
				BaseLogger.log("3", userInfo,null,"File could not download");
			}
		} 
		catch (Exception e) 
		{
			BaseLogger.log("0", userInfo,null,"Exception in downloadRemoteFile["+e.getMessage()+"]");
		}
		return isDownload;
	}

	private void moveFileOnRemote( File dUMP_DIR, String remotePath, String newFileName ) 
	{
		try 
		{
			if( ftpClient != null )
			{
				BaseLogger.log("3", userInfo,null,"Start uploading downloaded file");
				BaseLogger.log("3", userInfo,null,"remoteFilePath["+ remotePath +"]");

				InputStream inputStream = new FileInputStream( dUMP_DIR + File.separator + newFileName );
				BaseLogger.log("3", userInfo,null,"dUMP_DIR["+dUMP_DIR+"]");

				String currentFtpDir = ftpClient.printWorkingDirectory();
				BaseLogger.log("3", userInfo,null,"currentFtpDir["+currentFtpDir+"]");

				boolean exist = ftpClient.changeWorkingDirectory( remotePath );
				if( !exist )
				{
					boolean created = makeFTPDirectories( remotePath  );
					BaseLogger.log("3", userInfo,null,"success["+created+"]");
					if( !created )
					{
						createLogAndSendMail( ftpClient.getReplyCode(), getServerReplyString() );
						inputStream.close();
						return;
					}
					ftpClient.changeWorkingDirectory( currentFtpDir );
				}
				else
				{
					ftpClient.changeWorkingDirectory( currentFtpDir );
				}
				BaseLogger.log("3", userInfo,null,"currentFtpDir1["+currentFtpDir+"]");

				String fileMovePath = remotePath+File.separator+newFileName;
				BaseLogger.log("3", userInfo,null,"inputStream["+inputStream+"]");
				boolean done = ftpClient.storeFile( fileMovePath, inputStream );
				inputStream.close();
				if( done )
				{
					BaseLogger.log("3", userInfo,null,"File move successfully on Remote");
					deleteRemoteFile( newFileName, dUMP_DIR );
				}
				else
				{
					BaseLogger.log("3", userInfo,null,"File could not Move");
					createLogAndSendMail(ftpClient.getReplyCode(), getServerReplyString());
					//createUploadLog( "["+ newFileName +"] : file could not move", newFileName );
				}
			}
			else
			{
				BaseLogger.log("3", userInfo,null,"ftp connection closed");
				createLogAndSendMail( -1, "FTP connection closed");
			}
		} 
		catch (Exception e) 
		{
			BaseLogger.log("0", userInfo,null,"Exception in moveFileOnRemote["+e.getMessage()+"]");
			e.printStackTrace();
			setFTPExceptionLog( ftpClient.getReplyCode(), getServerReplyString(), e.getMessage());
		}
	}

	private void deleteRemoteFile( String newFileName, File dumpDir ) throws IOException
	{
		boolean deleted = false;
		if ( IS_FTP_PATH && ftpClient != null )
		{
			deleted = ftpClient.deleteFile( FILE_UPLOAD_SRC_PATH + File.separator + newFileName );
		}
		else if ( IS_SFTP_PATH && sftpChannel != null )
		{
			try 
			{
				sftpChannel.rm( FILE_UPLOAD_SRC_PATH + File.separator + newFileName );
				deleted = true;
			}
			catch (SftpException e) 
			{
				deleted = false;
			}
		}
		if( deleted ) 
		{
			BaseLogger.log("3", userInfo,null,"Remote file "+ newFileName+" deleted successfully");
			deleteLocalFile( dumpDir, newFileName );
		}
		else
		{
			BaseLogger.log("3", userInfo,null,"Remote file"+newFileName+" could not delete");
			if ( IS_FTP_PATH && ftpClient != null )
			{
				createLogAndSendMail( ftpClient.getReplyCode(), getServerReplyString());
			}
		}
	}

	private void deleteLocalFile(File dUMP_DIR2, String newFileName)
	{
		File localDownloadedFile = new File(dUMP_DIR2+File.separator+newFileName);
		boolean deleted = localDownloadedFile.delete();
		if( deleted )
		{
			BaseLogger.log("3", userInfo,null,"localDownloadedFile "+newFileName+"deletetd successfully");
		}
		else
		{
			BaseLogger.log("3", userInfo,null,"localDownloadedFile "+newFileName+"could not delete");
			createLogAndSendMail( -1, "localDownloadedFile "+newFileName+"could not delete");
		}
	}

	private void moveLogFileOnRemote( String fileUploadLogPath, String logFileName, String errStr ) throws Exception 
	{
		try 
		{
			if( ftpClient != null )
			{
				BaseLogger.log("3", userInfo,null,"Start uploading log file");
				String currentFtpDir = ftpClient.printWorkingDirectory();
				BaseLogger.log("3", userInfo,null,"currentFtpDir["+currentFtpDir+"]");

				boolean exist = ftpClient.changeWorkingDirectory( fileUploadLogPath );
				BaseLogger.log("3", userInfo,null,"ftp client["+ftpClient.getReplyCode()+"]");
				if( !exist)
				{
					boolean created = makeFTPDirectories( fileUploadLogPath  );
					BaseLogger.log("3", userInfo,null,"success["+created+"]");
					if( !created )
					{
						createLogAndSendMail( ftpClient.getReplyCode(), getServerReplyString() );
						return;
					}
					ftpClient.changeWorkingDirectory( currentFtpDir );
				}
				else
				{
					ftpClient.changeWorkingDirectory( currentFtpDir );
				}
				BaseLogger.log("3", userInfo,null,"ftpClient.workin["+ftpClient.printWorkingDirectory());
				String fileMovePath = fileUploadLogPath + File.separator + logFileName;

				OutputStream outputStream = ftpClient.storeFileStream( fileMovePath );
				OutputStream buffer = new BufferedOutputStream( outputStream );
				ObjectOutput output = new ObjectOutputStream( buffer );
				output.writeObject( errStr );
				output.close();
				buffer.close();
				outputStream.close();

				BaseLogger.log("3", userInfo,null,"log file created successfully");
				ftpClient.changeWorkingDirectory( currentFtpDir );
				BaseLogger.log("3", userInfo,null,"ftpClient["+ ftpClient +"]");
				BaseLogger.log("3", userInfo,null,"ftpClient.working Directory["+ftpClient.printWorkingDirectory());

				createFTPConnection();
			}
			//added by Amey W on 19.10.18 for [For SFTP Connection] START.
			else if( sftpChannel != null )
			{
				try
				{
					createSFTPConnection();
					boolean exist = changeWorkingDirectory( sftpChannel, fileUploadLogPath );
					if( ! exist )
					{
						exist = makeSFTPDirectories( fileUploadLogPath );
						if( ! exist )
						{
							BaseLogger.log( "3", userInfo, null, "Directory not created" );
						}
					}
					if( exist )
					{
						InputStream stream = new ByteArrayInputStream( errStr.getBytes ());
						sftpChannel.put( stream, logFileName );
						stream.close();
						BaseLogger.log( "3", userInfo, null, "Log file moved");
						//createSFTPConnection();
					}
				}
				catch (SftpException s) 
				{
					BaseLogger.log("0", userInfo,null,"[Sftp Exceptiojn = "+s+"]" );
					createLogAndSendMailSFTP(s.id,s.getMessage());
				}
			}//added by Amey W on 19.10.18 for [For SFTP Connection] END.
			else
			{
				BaseLogger.log("3", userInfo,null,"FTP connection closed");
				createLogAndSendMail( -1, "FTP connection closed");
			}
		} 
		catch (Exception e) 
		{
			BaseLogger.log("0", userInfo,null,"Exception in uploadFileOnRemote["+e.getMessage()+"]");
			setFTPExceptionLog( ftpClient.getReplyCode(), getServerReplyString(), e.getMessage());
		}
	}

	private boolean makeFTPDirectories( String dirPath ) throws IOException
	{
		try
		{
			BaseLogger.log("3", userInfo,null,"dirPath["+dirPath+"]");
			String[] pathElements = dirPath.split( "/" );
			if ( pathElements != null && pathElements.length > 0 ) 
			{
				for ( String singleDir : pathElements )
				{
					BaseLogger.log("3", userInfo,null,"singleDir["+singleDir+"]");
					if( singleDir.trim().length() == 0 )
					{
						continue;
					}
					boolean dirExisted = ftpClient.changeWorkingDirectory( singleDir );
					if ( ! dirExisted ) 
					{
						boolean dirCreated = ftpClient.makeDirectory( singleDir );
						if ( dirCreated ) 
						{
							BaseLogger.log("3", userInfo,null, "CREATED directory: ["+ singleDir +"]" );
							ftpClient.changeWorkingDirectory( singleDir );
						}
						else
						{
							BaseLogger.log("3", userInfo,null,"COULD NOT create directory: " + singleDir);
							return false;
						}
					}
				}
			}
			return true;
		}
		catch (Exception e)
		{
			BaseLogger.log("0", userInfo,null,"Exception in makeDirectories["+e.getMessage()+"]");
			e.printStackTrace();
			return false;
		}
	}

	private String getServerReplyString()
	{
		String[] replies = ftpClient.getReplyStrings();
		if (replies != null && replies.length > 0) 
		{
			for (String aReply : replies) 
			{
				return aReply;
			}
		}
		return "server:"+ftpClient.getReplyCode();
	}

	private void createLogAndSendMail(int replyCode, String serverReply)
	{
		try
		{
			String errLogString = ""; 
			boolean mailFlag = true;
			boolean fileLogFlag = true;
			//connection
			if( replyCode == 0 )
			{
				errLogString = "Error code "+ serverReply +"\n";
				errLogString+= "Messgae: Please check server credentials or contact administrator";
			}//login Incorrect
			else if( replyCode == 530 )
			{
				errLogString = "Error code "+ serverReply +"\n";
				errLogString+= "Messgae: Please check server credentials or contact administrator";
			}//delete operation failed/can't make directory/failed to open file
			else if( replyCode == 550 )
			{
				errLogString = "Error code "+ serverReply +"\n";
				errLogString += "Messgae: Requested action not taken. File unavailable (for example, file not found, or no access).";
			}//could not create file
			else if( replyCode == 553 )
			{
				errLogString = "Error code "+ serverReply +"\n";
				errLogString += "Messgae: Requested action not taken. File name not allowed. (for example, file not found, or no access).";
			}//pipe broken
			else if( replyCode == 421 )
			{
				errLogString = "Error code "+ serverReply +"\n";
				errLogString += "Service not available, closing control connection. This may be a reply to any command if the service knows it must shut down.";
				mailFlag = false;
				fileLogFlag = false;
			}//parse
			else if( replyCode == 226 )
			{
				errLogString = "Error code "+ serverReply +"\n";
				fileLogFlag = false;
				mailFlag = false;
			}//custom
			else if( replyCode == -1 )
			{
				errLogString = "Error code "+ serverReply +"\n";
			}
			else
			{
				errLogString = "Error code "+ serverReply +"\n";
				mailFlag = false;
				fileLogFlag = false;
			}

			if( mailFlag ) 
			{
				sendLogViaMail( errLogString, "FTP log: XML file upload" );
			}
			if( fileLogFlag ) 
			{
				writeLogInFile( errLogString, "FTP_log" );
			}
			BaseLogger.log("3", userInfo,null, "Log String[" +errLogString +"]" );
		} 
		catch ( Exception e)
		{
			BaseLogger.log("0", userInfo,null,"Exception in createLogAndSendMail["+e.getMessage()+"]");
		}
	}

	private void setFTPExceptionLog(int replyCode, String serverReplyString, String message) 
	{
		createLogAndSendMail( ftpClient.getReplyCode(), getServerReplyString()+"\nException: "+message+"");
	}

	private String getRoleCodeEmailAddr()
	{
		String usrType = userInfo.getUserType();
		BaseLogger.log("2", userInfo,null,"[ITMUploadFileEJB] argType getRoleCodeEmailAddr 1:"+usrType+":");
		String retEmailAddr = "";
		try
		{
			String masterTable = null;
			String whereFieldName = null;
			String selFieldName = null;

			if (usrType.equalsIgnoreCase("C"))
			{
				masterTable = "CUSTOMER";
				whereFieldName = "CUST_CODE";
				selFieldName = "EMAIL_ADDR";
			}
			else if (usrType.equalsIgnoreCase("S"))
			{
				masterTable = "SUPPLIER";
				whereFieldName = "SUPP_CODE";
				selFieldName = "EMAIL_ADDR";
			}
			else if (usrType.equalsIgnoreCase("E"))
			{
				masterTable = "EMPLOYEE";
				whereFieldName = "EMP_CODE";
				selFieldName = "EMAIL_ID_OFF";
			}
			else if (usrType.equalsIgnoreCase("P"))
			{
				masterTable = "SALES_PERS";
				whereFieldName = "SALES_PERS";
				selFieldName = "EMAIL_ADDR";
			}

			//AppConnectParm appConnect = new AppConnectParm();
			//InitialContext ctx = new InitialContext(appConnect.getProperty());
			//DBAccessRemote dbAccess =(DBAccessRemote)ctx.lookup("ibase/DBAccessEJB/remote");
			//DBAccessEJB dbAccess = new DBAccessEJB();
			//retEmailAddr = dbAccess.getEmailAddr(selFieldName, masterTable, whereFieldName, userInfo.getLoginCode());
			BaseLogger.log("3",userInfo,null, "userInfo.getEntityCode["+userInfo.getEntityCode()+"]");
			retEmailAddr = getDBAccess().getEmailAddr(selFieldName, masterTable, whereFieldName, userInfo.getEntityCode(), userInfo);
			dbAccess = null;
		}
		catch (Exception e)
		{
			BaseLogger.log("0", userInfo,null,"Exception :ITMUploadFileEJB :getEmailAddr :==>\n"+e.getMessage());
		}
		return retEmailAddr;
	}
	//added by vishal on 14.5.17 for [enterprise implementation in for file upload ejb]End.
	
	//added by Amey W on 19.10.18 for [For SFTP Connection] START.
	private boolean createSFTPConnection() 
	{
		boolean sftpConn = false;
		String sftpHostUrl = "";

		if ( FTP_HOST_URL.startsWith("sftp://") )
		{
			sftpHostUrl = FTP_HOST_URL.replace("sftp://", "");
			BaseLogger.log("0", userInfo, null, "sftpHostUrl : ["+ sftpHostUrl +"]" );
		}

		String server = sftpHostUrl;
		int port = 22;
		if ( fileUploadPort != null )
		{
			port = Integer.valueOf( fileUploadPort );
		}
		String user = ftpUserName;
		String pass = ftpPassword;

		try 
		{
			JSch jsch = new JSch();
			session = jsch.getSession( user, server, port );
			session.setPassword( pass );

			//Yes for secure connection
			java.util.Properties config = new java.util.Properties(); 
			config.put( "StrictHostKeyChecking", "no" );
			session.setConfig(config);

			session.connect();
			BaseLogger.log( "3", userInfo,null,"connection established! session created as : ["+ config +"]" );

			Channel channel = session.openChannel("sftp");
			channel.connect();
			BaseLogger.log("3", userInfo,null,"channel connected as = "+channel);

			sftpChannel = (ChannelSftp) channel;
			if( sftpChannel != null )
			{
				sftpConn = true;
				BaseLogger.log("3", userInfo,null,"sftpChannel connection established as ["+ sftpChannel +"]");
			}
			else
			{
				sftpConn = false;
			}
			return sftpConn;
		} 
		catch ( JSchException s ) 
		{
			BaseLogger.log( "0", userInfo, null, "SftpException in createSFTPConnection : ["+ s +"]" );
			createLogAndSendMailSFTP( 10, s.getMessage() ) ;
			return false;
		}
		catch ( Exception e ) 
		{
			e.printStackTrace();
			return false;
		}
	}

	//Changed by Prasad on 13/01/2021 [set dynamic value to isRetainPkValue]
	private void readFilesBySFTP( File dUMP_DIR, UserInfoBean userInfo, String isIntractive, String objName, String oriFileName, boolean isExcelDriver, boolean isRetainPkValue ) throws Exception
	{
		BaseLogger.log( "0", userInfo, null, "In readFilesBySFTP method" );
		
		boolean sftpConn = false;
		boolean isDownload = false;

		sftpConn = createSFTPConnection();
		if( ! sftpConn )
		{
			return;
		}
		boolean isDirExist = changeWorkingDirectory( sftpChannel, FILE_UPLOAD_SRC_PATH, true );
		if ( ! isDirExist )
		{
			return;
		}
		String fileName = "";
		try 
		{
			Vector<ChannelSftp.LsEntry> list = sftpChannel.ls( FILE_UPLOAD_SRC_PATH );
			for( ChannelSftp.LsEntry entry : list ) 
			{
				isDownload = false;
				fileName = entry.getFilename();
				BaseLogger.log( "0", userInfo, null, "SFTP file : ["+ entry.getFilename() +"]" );
				if( ! ( ".".equals( fileName ) || "..".equals( fileName ) ) )
				{
					fileName = entry.getFilename();
					isDownload = downloadFileSFTP( fileName, dUMP_DIR );
				}
				if( isDownload )
				{
					try
					{
						BaseLogger.log( "3", userInfo, null, "SFTP file download" );
						String [] fileInfoArr = new String[4];
						fileInfoArr[0] = isIntractive;
						fileInfoArr[1] = fileName;
						fileInfoArr[2] = objName;
						fileInfoArr[3] = oriFileName;

						//Changed by Prasad on 13/01/2021 [set dynamic value to isRetainPkValue]
						insertFileData( fileInfoArr, userInfo, dUMP_DIR, CommonConstants.APPLICATION_CONTEXT, "", isExcelDriver, isRetainPkValue );
					}
					catch(Exception e )
					{
						BaseLogger.log( "3", userInfo, null, "Error readFilesBySFTP By FTP : ["+ e.getMessage() +"]" );
						e.printStackTrace();
						setFTPExceptionLog( ftpClient.getReplyCode(), getServerReplyString(), e.getMessage());
						disconnectSFTP();
					}
				}
				else
				{
					BaseLogger.log( "0", userInfo, null, "Sftp files not downloaded" );
					//createLogAndSendMail( ftpClient.getReplyCode(), getServerReplyString() );
				}
			}
		}
		catch ( SftpException s ) 
		{
			BaseLogger.log( "0", userInfo, null, "SftpException in readFilesBySFTP : ["+ s +"]" );
			createLogAndSendMailSFTP( s.id, s.getMessage() );
			disconnectSFTP();
		}
		catch( Exception e )
		{
			BaseLogger.log( "0", userInfo, null, "Exception in readFilesBySFTP : ["+ e.getMessage()+"]" );
			disconnectSFTP();
		}
	}
	
	private boolean changeWorkingDirectory( ChannelSftp channelSftp, String path, boolean isSendMail ) throws IOException 
	{
		try
		{
			channelSftp.cd( path );
			BaseLogger.log( "0", userInfo, null,"ChangeWorkingDirectory to: "+path);
			return true;
		}
		catch ( SftpException s ) 
		{
			BaseLogger.log( "0", userInfo, null, "SftpException in changeWorkingDirectory : ["+ s +"]"+"- Cannot change directory because mat be specified path was wrong or directoty does'nt exist!" );
			if ( isSendMail )
			{
				createLogAndSendMailSFTP( s.id, s.getMessage() );
			}
			return false;
		}
		catch( Exception e )
		{
			BaseLogger.log( "0", userInfo, null, "Exception in changeWorkingDirectory : ["+ e.getMessage()+"]" );
			return false;
		}
	}
	
	private boolean changeWorkingDirectory( ChannelSftp channelSftp, String path ) throws IOException 
	{
		return changeWorkingDirectory( channelSftp, path, false );
	}
	
	private boolean downloadFileSFTP( String readFileName, File dUMP_DIR ) throws Exception
	{
		BaseLogger.log( "2", userInfo, null, "downloadFileSFTP : ["+ readFileName +"], dUMP_DIR : ["+ dUMP_DIR +"]" );
		boolean isDownload = false;
		String downloadFileName = readFileName;

		changeWorkingDirectory( sftpChannel, FILE_UPLOAD_SRC_PATH );
		try
		{
			sftpChannel.get( FILE_UPLOAD_SRC_PATH + File.separator + downloadFileName, dUMP_DIR + File.separator + downloadFileName ); 
			BaseLogger.log( "0", userInfo, null, "Downloaded fileName ["+ downloadFileName +"]" );

			File file = new File( dUMP_DIR + File.separator + downloadFileName );
			if( file.exists() )
			{
				isDownload =  true;
			}
		}
		catch ( SftpException s ) 
		{
			BaseLogger.log( "0", userInfo, null, "SftpException in downloadFileSFTP : ["+ s +"]" );
			createLogAndSendMailSFTP( s.id, s.getMessage() );
		}
		catch( Exception e )
		{
			BaseLogger.log( "0", userInfo, null, "Exception in downloadFileSFTP : ["+ e.getMessage()+"]" );
		}
		return isDownload;
	}

	private void uploadFileSFTP( File dUMP_DIR, String SFTP_REM_WORK_Dir, String uploadFileName ) throws Exception
	{
		BaseLogger.log("2",userInfo,null, "In uploadFileSFTP : dUMP_DIR : ["+ dUMP_DIR +"], SFTP_REM_WORK_Dir : ["+ SFTP_REM_WORK_Dir +"], uploadFileName : ["+ uploadFileName +"]" );
		boolean sftpConn = createSFTPConnection();
		if( sftpConn )
		{
			boolean exist = changeWorkingDirectory( sftpChannel, SFTP_REM_WORK_Dir );
			if( ! exist )
			{
				boolean created = makeSFTPDirectories( SFTP_REM_WORK_Dir );
				if( ! created )
				{
					BaseLogger.log( "3", userInfo, null, "SFTP Directory not created" );
				}
			}

			try
			{
				boolean dirChange = changeWorkingDirectory( sftpChannel, SFTP_REM_WORK_Dir );
				if( dirChange )
				{
					sftpChannel.put( dUMP_DIR + File.separator + uploadFileName, SFTP_REM_WORK_Dir + File.separator + uploadFileName ); 
				}
				deleteRemoteFile( uploadFileName, dUMP_DIR );
			}
			catch (SftpException s) 
			{
				BaseLogger.log( "0", userInfo, null, "SftpException in uploadFileSFTP : ["+ s +"]" );
				createLogAndSendMailSFTP( s.id, s.getMessage() );
			}
			catch(Exception e)
			{
				BaseLogger.log( "0", userInfo, null, "Exception in uploadFileSFTP : ["+ e.getMessage()+"]" );
			}
		}
	}

	private boolean makeSFTPDirectories( String dirPath ) throws IOException
	{
		BaseLogger.log( "2", userInfo, null, "In makeSFTPDirectories : ["+ dirPath +"]" );
		boolean exist = false;
		try 
		{
			String[] folders = dirPath.split("/");
			if (folders[0].isEmpty())
			{
				folders[0] = "/";
			}
			String fullPath = folders[0];
			for (int i = 1; i < folders.length; i++) 
			{
				Vector ls = sftpChannel.ls(fullPath);
				boolean isExist = false;
				for (Object o : ls) 
				{
					if (o instanceof LsEntry) 
					{
						LsEntry e = (LsEntry) o;
						if (e.getAttrs().isDir() && e.getFilename().equals(folders[i])) 
						{
							isExist = true;
							exist = false;
						}
					}
				}
				if ( ! isExist && ! folders[i].isEmpty() ) 
				{
					sftpChannel.mkdir( fullPath + folders[i] ); 
					BaseLogger.log( "3", userInfo , null, "Directory created" );
					exist = true;
				}
				fullPath = fullPath + folders[i] + "/";
			}
			return exist; 
		} 
		catch ( SftpException s ) 
		{
			BaseLogger.log( "0", userInfo, null, "SftpException in makeSFTPDirectories : ["+ s +"]" );
			createLogAndSendMailSFTP( s.id, s.getMessage() );
			return false;
		}
		catch ( Exception e ) 
		{
			BaseLogger.log( "0", userInfo, null, "Exception in makeSFTPDirectories : ["+ e.getMessage()+"]" );
			e.printStackTrace();
			return false;
		}
	}

	private void createLogAndSendMailSFTP( int replyCode, String serverReply)
	{
		BaseLogger.log( "2", userInfo, null, "In createLogAndSendMailSFTP : replyCode ["+ replyCode +"], serverReply : ["+ serverReply +"]" );
		try
		{
			String errLogString = ""; 
			boolean mailFlag = true;
			boolean fileLogFlag = true;

			if( replyCode == 2 )
			{
				errLogString = "Error code "+ serverReply +"\n";
				errLogString+= "Messgae: No Such File on Remote server or invalid remote directory path";
			}//invalid remote path/directory
			else if( replyCode == 4 )
			{
				errLogString = "Error code "+ serverReply +"\n";
				errLogString+= "Messgae: No such File on local machine or invalid local directory path";
			}//invalid local path/directory
			else if( replyCode == 10 )
			{
				errLogString = "Error code "+ serverReply +"\n";
				errLogString += "Messgae: Connection to SFTP server failed [causes: invalid inputs(username/password) / server credentials or contact administrator ]";
			}//Jsch Exception If Connection to SFTP server failed.
			else
			{
				errLogString = "Error code "+ serverReply +"\n";
				mailFlag = false;
				fileLogFlag = false;
			}

			if( mailFlag ) 
			{
				sendLogViaMail( errLogString, "SFTP log: XML file upload" );
			}
			if( fileLogFlag ) 
			{
				writeLogInFile( errLogString, "SFTP_log" );
			}
			BaseLogger.log( "3", userInfo, null, "Log String[" +errLogString +"]" );
		} 
		catch ( Exception e)
		{
			BaseLogger.log( "0", userInfo, null, "Exception in createLogAndSendMailSFTP : ["+ e.getMessage()+"]" );
		}
	}

	private void sendLogViaMail( String errorLog, String subject )
	{
		BaseLogger.log( "2", userInfo, null, "In sendSFTPLogViaMail" );
		if( E12GenericUtility.checkNull( mailAddr ).length() == 0 )
		{
			mailAddr = getRoleCodeEmailAddr();
		}
		BaseLogger.log( "3", userInfo, null, "mailAddr["+ mailAddr +"]" );
		if( mailAddr.length() > 0 )
		{
			EMail mail = new EMail();
			try 
			{
				String mailInfoStr ="<Root><TO_ADD>"+ mailAddr +"</TO_ADD> "
						+ "<SUBJECT>"+ subject +"</SUBJECT>"
						+ "<MESSAGE>"+ errorLog +"</MESSAGE>"
						+ "</Root>";
				//Changed by Pankaj T. on 10-04-2020 for Configure SMTP mail server against ENTERPRISE
				mail.sendMail( mailInfoStr, "", this.userInfo );
			} 
			catch (Exception e)
			{
				BaseLogger.log( "0", userInfo, null, "Exception in sendSFTPLogViaMail["+ e.getMessage() +"]" );
			}
		}
	}

	private void writeLogInFile( String errorLog, String folderName )
	{
		BaseLogger.log( "2", userInfo, null, "In writeSFTPLogInFile : errorLog ["+ errorLog +"]" );
		try
		{
			String destinationFilePath = ( new File( CommonConstants.UPLOAD_LOC ) ) + File.separator + "upload_log" + File.separator + folderName;
			String userId = "";
			if ( userInfo != null )
			{
				userId = userInfo.getLoginCode();
			}
			String logFileName = "SFTP_log_"+ userId + "_" + System.currentTimeMillis() + ".log";

			if ( ! ( new File ( destinationFilePath ) ).exists()  ) 
			{
				( new File( destinationFilePath ) ).mkdir(); 
			}				
			if(!( new File ( destinationFilePath + File.separator + logFileName ) ).exists() ) 
			{
				( new File( destinationFilePath + File.separator + logFileName ) ).createNewFile(); 
			}

			boolean exist = changeWorkingDirectory( sftpChannel, FILE_UPLOAD_LOG_PATH );
			if( ! exist )
			{
				exist = makeSFTPDirectories( FILE_UPLOAD_LOG_PATH );
				if( ! exist )
				{
					BaseLogger.log( "3", userInfo, null, "Directory not created" );
				}
			}
			if( exist )
			{
				InputStream stream = new ByteArrayInputStream( errorLog.getBytes() );
				sftpChannel.put( stream, logFileName );
				stream.close();
				BaseLogger.log( "3", userInfo, null, "Error Log file write" );
				//createSFTPConnection();
			}
		}
		catch ( SftpException s ) 
		{
			BaseLogger.log( "0", userInfo, null, "SftpException in writeLogInFile : ["+ s +"]" );
			createLogAndSendMailSFTP(s.id,s.getMessage());
		}
		catch(Exception e)
		{
			BaseLogger.log( "0", userInfo, null, "Exception in writeLogInFile : ["+ e.getMessage()+"]" );
		}
	}
	
	private void disconnectSFTP()
	{
		BaseLogger.log( "2", userInfo, null, "In disconnectSFTP" );
		try 
		{
			sftpChannel.quit();
			sftpChannel.exit();
			session.disconnect();
		}
		catch (Exception e) 
		{
			e.printStackTrace();
		}
	}
	//added by Amey W on 19.10.18 for [For SFTP Connection] END.
	
	//Added by Prasad on 08/01/2021 [file write related implementation for success factor] START
	private void processEDIBatchload( String[] scheduleInfoArr ) throws ITMException
	{
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		//Added globally to as per suggestion of gagan B , to avoid the scope issue --strt
		String batchID = "";
		int tranSl = 0;
		String dependency = ""; 
		String loadStat = "";
		//Added globally to as per suggestion of gagan B , to avoid the scope issue --end

		
		MasterApplyEJB masterApplyEJB = new MasterApplyEJB();
		HashMap<Integer, HashMap<String, String>> dataMap = null;
		
		//boolean isError = false;
		try 
		{
			ConnDriver connDriver = new ConnDriver();
			conn = connDriver.getConnectDB( userInfo.getTransDB() );
			connDriver = null;
			
			//Added by Ravindra C on 27/02/2021 [add app_id to identify the source] START
			String appId = checkNull( scheduleInfoArr[5] );
			BaseLogger.log( "3", userInfo, null, "appId : ["+ appId +"]" );
			String appIdAddr = "";
			if ( appId.length() > 0 )
			{
				appIdAddr = (appId + "_");
			}
			//Added by Ravindra C on 27/02/2021 [add app_id to identify the source] END
			
			//Changed by Pooja S on 12-JAN-2021 [Batchload interface to store keyFieldValue for the transaction]
			String sql = "SELECT BATCH.BATCH_ID, BATCH.WIN_NAME, BATCH.DATA_FILE_NAME, BATCH.SUBJECT, BATCH.XFRM_TEMPLATE, TEMPL.TEMPLATE_NAME, BATCH.TRAN_SL, BATCH.EDI_ADDR, BATCH.THREAD_KEY, BATCH.ADD_USER, BATCH.LOAD_STAT, TRAN.LOAD_ORDER, BATCH.LOAD_ORDER " + 
					" FROM TRANSETUP TRAN, BATCHLOAD BATCH LEFT OUTER JOIN OBJ_FILE_TEMPLATE TEMPL ON BATCH.XFRM_TEMPLATE = TEMPL.TEMPLATE_ID " + 
					" WHERE ( BATCH.LOAD_STAT IN ( 'N', 'R' )  OR ERROR_MSG Like '%Load file not exist%')" +
					" AND TRAN.TRAN_WINDOW = BATCH.WIN_NAME " + 
					" AND BATCH.EDI_ADDR IS NOT NULL AND BATCH.EDI_ADDR IN ( '"+ appIdAddr +"fileSystem', '"+ ( appIdAddr + CommonConstants.API_FILE_DESTINATION ) +"' ) " + 
					" ORDER BY TRAN.LOAD_ORDER, BATCH.LOAD_ORDER, BATCH.ADD_DATE, BATCH.BATCH_ID, BATCH.TRAN_SL ";
			
			pstmt = conn.prepareStatement( sql );
			rs = pstmt.executeQuery();
			
			dataMap = new LinkedHashMap<Integer, HashMap<String,String>>();
			
			ResultSetMetaData rsmd = rs.getMetaData();
			int noOfColumns = rsmd.getColumnCount();
			int index = 0;
			while( rs.next() )
			{
				HashMap<String, String> tempMap = new HashMap<String, String>();
				for(int ctr = 1; ctr <= noOfColumns; ctr++)
				{
					if( "mysql".equalsIgnoreCase( CommonConstants.DB_NAME ) )
					{
						tempMap.put( rsmd.getColumnName(ctr).toUpperCase(), rs.getString(ctr) );
					}
					else
					{
						tempMap.put( rsmd.getColumnName(ctr), rs.getString(ctr) );
					}
				}
				dataMap.put( ++index, tempMap );
			}
			rs.close();
			rs = null;
			pstmt.close();
			pstmt = null;
			
			//Added By Ravindra C on 17-07-21 to update the load_stat As a I.
			masterApplyEJB.updateBatchLoad( dataMap, "I", conn, getUserInfoBean() );
			
			if ( conn != null )
			{
				conn.close();
				conn = null;
			}
			BaseLogger.log( "3", userInfo, null, "index : ["+ index +"], dataMap : ["+ dataMap +"]" );
			
			//String batchID = "";
			String fileName = "";
			String objName = "";
			String subject = "";
			String templateId = "";
			String templateName = "";
			String ediAddr = "";
			String threadKey = "";
			//String dependency = "";
			String addUser = "";
			//check with gagan  Amol S
			//String loadStat = "";
			String tranSlStr = "0";
//			int tranSl = 0;
			for( Map.Entry<Integer, HashMap<String, String>> dataEntry : dataMap.entrySet() )
			{
				HashMap<String, String> tempDataMap = dataEntry.getValue();
				
				objName = checkNull( tempDataMap.get( "WIN_NAME" ) );
				objName = objName.substring( objName.indexOf("_") + 1 );
				batchID = checkNull( tempDataMap.get( "BATCH_ID" ) );
				fileName = checkNull( tempDataMap.get( "DATA_FILE_NAME" ) ); 
				subject = checkNull( tempDataMap.get( "SUBJECT" ) );
				templateId = checkNull( tempDataMap.get( "XFRM_TEMPLATE" ) );
				templateName = checkNull( tempDataMap.get( "TEMPLATE_NAME" ) );
				//Added by Pooja S on 12-JAN-2021 [Batchload interface to store keyFieldValue for the transaction]
				tranSlStr = checkNull( tempDataMap.get( "TRAN_SL" ) );
				if ( tranSlStr.length() > 0 )
				{
					tranSl = Integer.parseInt( tranSlStr );
				}
				ediAddr = checkNull( tempDataMap.get( "EDI_ADDR" ) );
				threadKey = checkNull( tempDataMap.get( "THREAD_KEY" ) );
				addUser = checkNull( tempDataMap.get( "ADD_USER" ) ).trim();
				loadStat = checkNull( tempDataMap.get( "LOAD_STAT" ) );
				
				BaseLogger.log( "3", userInfo, null, "objName : ["+ objName +"]" );
				BaseLogger.log( "3", userInfo, null, "batchID : ["+ batchID +"]" );
				BaseLogger.log( "3", userInfo, null, "fileName : ["+ fileName +"]" );
				BaseLogger.log( "3", userInfo, null, "subject : ["+ subject +"]" );
				BaseLogger.log( "3", userInfo, null, "templateId : ["+ templateId +"]" );
				BaseLogger.log( "3", userInfo, null, "templateName : ["+ templateName +"]" );
				BaseLogger.log( "3", userInfo, null, "ediAddr : ["+ ediAddr +"]" );
				BaseLogger.log( "3", userInfo, null, "threadKey : ["+ threadKey +"]" );
				BaseLogger.log( "3", userInfo, null, "addUser : ["+ addUser +"]" );
				BaseLogger.log( "3", userInfo, null, "loadStat : ["+ loadStat +"]" );
				
				if ( fileName.length() == 0 || fileName.indexOf( "." ) == -1 )
				{
					continue;
				}
				dependency = "";
				threadKey = checkNull( threadKey );
				if ( threadKey.length() > 0 )
				{
					dependency = getDBAccess().getDBColumnValue( "BATCHLOAD", "(BATCH_ID || ':' || TRAN_SL)~AS~DEPENDENCY", (" THREAD_KEY = '"+ threadKey +"' AND LOAD_STAT = 'E' "), userInfo.getTransDB() );
				}
				dependency = checkNull( dependency );
				if ( dependency.length() > 0 )
				{
					//Changed by Ravindra C on 17-07-21 to update the load_stat As a N. - Start
					//getDBAccess().updateTableColumnValue( "BATCHLOAD", "DEPENDENCY", dependency, (" BATCH_ID = '" + batchID + "' AND TRAN_SL = '"+ tranSl +"' "), userInfo.getTransDB() );
					
					// Changes by Gagan B. to copy log file in case of load stat E on 09-OCT-23 [START]
					if (loadStat.equalsIgnoreCase("E")) {
						String fromPath = CommonConstants.JBOSSHOME + File.separator + "server" +  File.separator + "default" + File.separator 
								+ "log" + File.separator + "server.log"; 
						String toPath = CommonConstants.JBOSSHOME + File.separator+ "upload_failed";
						String movedFileName = batchID + "_server.log";
						BaseLogger.log("3", null, null, "Inside processEDIBatchload gsb fromPath [" + fromPath + "]");
						BaseLogger.log("3", null, null, "Inside processEDIBatchload gsb toPath [" + toPath + "]");
						BaseLogger.log("3", null, null, "Inside processEDIBatchload gsb movedFileName [" + movedFileName + "]");
						genericUtility.copyFileWithNewName(fromPath, toPath, movedFileName);
					}
					// Changes by Gagan B. to copy log file in case of load stat E on 09-OCT-23 [END]
					
					masterApplyEJB.updateBatchLoad( batchID, tranSl, loadStat, dependency, null, getUserInfoBean() );
					//Changed by Ravindra C on 17-07-21 to update the load_stat As a I. - End
					continue;
				}
				else
				{
					String[] fileInfoArr = new String[6];
					fileInfoArr[0] = "false";
					fileInfoArr[1] = fileName;
					fileInfoArr[2] = objName;
					fileInfoArr[3] = "";
					fileInfoArr[4] = templateName;
					fileInfoArr[5] = subject;
					//fileInfoArr[7] = "true"; //isRetXML
					
					String fileType = fileName.substring( fileName.lastIndexOf(".") + 1 );
					BaseLogger.log( "3", userInfo, null, "fileType : ["+ fileType +"]" );
					String uploadFilePath = "";
					String dataDumpFolderName = "";
					if( "json".equalsIgnoreCase( fileType ) )
					{
						dataDumpFolderName = "JSON_UPLOAD";
					}
					else
					{
						dataDumpFolderName = "XLS_UPLOAD";
						fileType = "xml";
					}
					//Changed by Ravindra C on 19/02/2021 [set added user in path]
					//uploadFilePath = CommonConstants.JBOSSHOME + File.separator + dataDumpFolderName + File.separator + userInfo.getLoginCode() + File.separator + batchID;
					uploadFilePath = CommonConstants.JBOSSHOME + File.separator + dataDumpFolderName + File.separator + addUser + File.separator + batchID;
					DUMP_DIR = new File( uploadFilePath );
					if ( ! DUMP_DIR.exists() )
					{
						DUMP_DIR.mkdirs();
					}
					//Added by Ravindra C on 19/02/2021 [move failed file to load folder in case of reload] START
					if( "R".equalsIgnoreCase( loadStat ) )
					{
						moveFailedFileToUpload( uploadFilePath, fileName );
					}
					//Added by Ravindra C on 19/02/2021 [move failed file to load folder in case of reload] END
					if ( ediAddr.equalsIgnoreCase( (appIdAddr + CommonConstants.API_FILE_DESTINATION) ) && subject.length() > 0 )
					{
						String inputData = getProcessData( "EDI_DATA", subject );
						inputData = checkNull( inputData );
						if ( inputData.length() > 0 )
						{
							new E12GenericUtility().writeFile( uploadFilePath, fileName, inputData );
						}
					}
					//Changed by Prasad on 13/01/2021 [set dynamic value to isRetainPkValue]
					//Added by Pooja S on 12-JAN-2021 [Batchload interface to store keyFieldValue for the transaction] start
					insertFileData( fileInfoArr, userInfo, DUMP_DIR, CommonConstants.APPLICATION_CONTEXT, "", false, false, batchID, tranSl );
				}
			}
		}
		catch (SQLException e) 
		{
			//Added by Amol s --strt
			masterApplyEJB.updateBatchLoad( batchID, tranSl, "E", dependency, null, getUserInfoBean() );
			BaseLogger.log("3", null, null,
            "Exception2 in processEDIBatchload [" + E12GenericUtility.getStackTrace(e) + "]");
			throw new ITMException( e );
			//Added by Amol s -end
			
			
			/*
			// Added by Gagan B. on 16-FEB-24 to update update batchload table in case of exception to avoid the stucking at LOAD_STAT at I. [START]
			for( Map.Entry<Integer, HashMap<String, String>> dataEntry : dataMap.entrySet() ) {
				HashMap<String, String> tempDataMap = dataEntry.getValue();
				String errorMsg = getErrorString(e);
				String batchId = checkNull( tempDataMap.get( "BATCH_ID" ) );
				String tranSlStr = checkNull( tempDataMap.get( "TRAN_SL" ) );
				int tranSl = Integer.parseInt(tranSlStr);
				masterApplyEJB.updateBatchLoad( batchId, tranSl, errorMsg, "E", "", conn, userInfo );
			}
			// Added by Gagan B. on 16-FEB-24 to update update batchload table in case of exception to avoid the stucking at LOAD_STAT at I. [END]
			 */
		}
		catch (Exception e) 
		{
			//Added by Amol s --strt
			masterApplyEJB.updateBatchLoad( batchID, tranSl, "E", dependency, null, getUserInfoBean() );
			BaseLogger.log("3", null, null,
            "Exception2 in processEDIBatchload [" + E12GenericUtility.getStackTrace(e) + "]");
			throw new ITMException( e );
			//Added by Amol s -end
			/*
			// Added by Gagan B. on 16-FEB-24 to update update batchload table in case of exception to avoid the stucking at LOAD_STAT at I. [START]
			for (Map.Entry<Integer, HashMap<String, String>> dataEntry : dataMap.entrySet()) {
				HashMap<String, String> tempDataMap = dataEntry.getValue();
				String errorMsg = getErrorString(e);
				String batchId = checkNull(tempDataMap.get("BATCH_ID"));
				String tranSlStr = checkNull(tempDataMap.get("TRAN_SL"));
				int tranSl = Integer.parseInt(tranSlStr);
				masterApplyEJB.updateBatchLoad(batchId, tranSl, errorMsg, "E", "", conn, userInfo);
			}
			// Added by Gagan B. on 16-FEB-24 to update update batchload table in case of exception to avoid the stucking at LOAD_STAT at I. [END]
			*/
			//throw new ITMException( e );
		}
		finally
		{
			try 
			{
				// Added by Amol S. on 25-Oct-24 to update  batchload table in case of exception to avoid the stucking at LOAD_STAT at I. [strt]
				if (loadStat.equalsIgnoreCase("I"))
				{
				BaseLogger.log("3", null, null,  " Error Occured, Load stat is stuck at I for batchId : " + batchID +"");
				//masterApplyEJB.updateBatchLoad( batchID, tranSl, "E", dependency, null, getUserInfoBean() );
				masterApplyEJB.updateBatchLoad(batchID, tranSl, "Error Occured, Load stat is stuck at I", "E", "", conn, userInfo);
				}
				// Added by Amol S. on 25-Oct-24 to update  batchload table in case of exception to avoid the stucking at LOAD_STAT at I. [end]

				if ( rs != null )
				{
					rs.close();
					rs = null;
				}
				if ( pstmt != null )
				{
					pstmt.close();
					pstmt = null;
				}
				if ( conn != null )
				{
					conn.close();
					conn = null;
				}
			}
			catch (SQLException e) 
			{
				//Added by Amol S on 25-Oct- 24 in case load stat is stuck at I --Start
				masterApplyEJB.updateBatchLoad( batchID, tranSl, "E", dependency, null, getUserInfoBean() );
				BaseLogger.log("3", null, null,
	            "Exception3 in processEDIBatchload [" + E12GenericUtility.getStackTrace(e) + "]");
				throw new ITMException( e );
				
				//Added by Amol S on 25-Oct- 24 in case load stat is stuck at I --End
				/*
				 * 
				 * 
				// Added by Gagan B. on 16-FEB-24 to update update batchload table in case of exception to avoid the stucking at LOAD_STAT at I. [START]
				for (Map.Entry<Integer, HashMap<String, String>> dataEntry : dataMap.entrySet()) {
					HashMap<String, String> tempDataMap = dataEntry.getValue();
					String errorMsg = getErrorString(e);
					String batchId = checkNull(tempDataMap.get("BATCH_ID"));
					String tranSlStr = checkNull(tempDataMap.get("TRAN_SL"));
					int tranSl = Integer.parseInt(tranSlStr);
					masterApplyEJB.updateBatchLoad(batchId, tranSl, errorMsg, "E", "", conn, userInfo);
				}
				// Added by Gagan B. on 16-FEB-24 to update update batchload table in case of exception to avoid the stucking at LOAD_STAT at I. [END]
			*/
			}
			
		}
	}
	//Added by Prasad on 08/01/2021 [file write related implementation for success factor] END
	
	//Added by Ravindra C on 19/01/2021 [to send notification in case of error in uploading] START
	private void sendNotification( String notificationType, String objName, String batchId, String rowNo, String tranId, String xmlStr, String errorDescription, Connection conn )
	{
		try 
		{
			String formatCode = getDBAccess().getDBColumnValue( "SYSPARM", "VAR_VALUE", " VAR_NAME = '"+ objName.toUpperCase() +"' AND VAR_TYPE = '"+ notificationType +"' ", conn );
			BaseLogger.log( "3", userInfo, null, "formatCode : ["+ formatCode +"], errorDescription ["+ errorDescription +"]" );
			
			if( checkNull( formatCode ).length() > 0 && "E".equalsIgnoreCase( notificationType ) )
			{
				//Added By Ravindra C on 27-04-21 to add some tag in the mail info XML 
				String winName = "w_"+objName;

				String objDescr = getDBAccess().getDBColumnValue( "ITM2MENU", "DESCR", " WIN_NAME = '"+ winName +"'", conn );
				BaseLogger.log( "3", userInfo, null, "objDescr : ["+ objDescr +"]");

				UploadFileEJB uploadFile = new UploadFileEJB();
				TreeMap batchloadDetails = uploadFile.getSortedErrorData( batchId, null, rowNo, userInfo, conn );
				uploadFile = null;
				
				HashMap batchloadDetailMap = (HashMap) batchloadDetails.get( Integer.parseInt( rowNo ) );
				BaseLogger.log( "3", userInfo, null, "batchloadDetailMap : ["+ batchloadDetailMap +"]" );
				//Added By Ravindra C on 27-04-21 to add some tag in the mail info XML - End
				
				EMail emailObj = new EMail();
			
				StringBuffer xmlDataBuff = new StringBuffer();
				xmlDataBuff.append("<Detail1>");
				xmlDataBuff.append("<user_code><![CDATA[").append( userInfo.getLoginCode() ).append("]]></user_code>");
				xmlDataBuff.append("<user_name><![CDATA[").append( userInfo.getUserName() ).append("]]></user_name>");
				xmlDataBuff.append("<emp_code><![CDATA[").append( userInfo.getEmpCode() ).append("]]></emp_code>");
				
				xmlDataBuff.append("<batch_id><![CDATA[").append( batchId ).append("]]></batch_id>");
				xmlDataBuff.append("<row_no><![CDATA[").append( rowNo ).append("]]></row_no>");
				
				//Added By Ravindra C on 27-04-21 to add some tag in the mail info XML - Start
				xmlDataBuff.append("<obj_name><![CDATA[").append( objName ).append("]]></obj_name>");
				xmlDataBuff.append("<obj_descr><![CDATA[").append( objDescr ).append("]]></obj_descr>");
				xmlDataBuff.append("<load_date><![CDATA[").append( batchloadDetailMap.get( "loadDate" ) ).append("]]></load_date>");
				xmlDataBuff.append("<load_status><![CDATA[").append( batchloadDetailMap.get( "loadStat" ) ).append("]]></load_status>");
				xmlDataBuff.append("<load_order><![CDATA[").append( batchloadDetailMap.get( "loadOrder" ) ).append("]]></load_order>");
				xmlDataBuff.append("<thread_key><![CDATA[").append( batchloadDetailMap.get( "threadKey" ) ).append("]]></thread_key>");
				xmlDataBuff.append("<dependency><![CDATA[").append( batchloadDetailMap.get( "dependency" ) ).append("]]></dependency>");
				xmlDataBuff.append("<tran_id__ref><![CDATA[").append( batchloadDetailMap.get( "tranIdRef" ) ).append("]]></tran_id__ref>");
				xmlDataBuff.append("<error_descr><![CDATA[").append( batchloadDetailMap.get( "errorMessage" ) ).append("]]></error_descr>");
				xmlDataBuff.append("<edi_addr><![CDATA[").append( batchloadDetailMap.get( "ediAddr" ) ).append("]]></edi_addr>");
				xmlDataBuff.append("<template_id><![CDATA[").append( batchloadDetailMap.get( "xfrmTemplate" ) ).append("]]></template_id>");
				xmlDataBuff.append("<add_date><![CDATA[").append( batchloadDetailMap.get( "addDate" ) ).append("]]></add_date>");
				xmlDataBuff.append("<add_user><![CDATA[").append( batchloadDetailMap.get( "addUser" ) ).append("]]></add_user>");
				xmlDataBuff.append("<chg_date><![CDATA[").append( batchloadDetailMap.get( "chgDate" ) ).append("]]></chg_date>");
				xmlDataBuff.append("<chg_user><![CDATA[").append( batchloadDetailMap.get( "chgUser" ) ).append("]]></chg_user>");
				//Added By Ravindra C on 27-04-21 to add some tag in the mail info XML - End
				
				xmlDataBuff.append("</Detail1>");

				StringBuffer mailInfoXml = new StringBuffer();
				mailInfoXml.append("<?xml version=\"1.0\" ?>");
				mailInfoXml.append("<Root>");
				mailInfoXml.append("<Header></Header>");
				mailInfoXml.append("<Errors></Errors>");
				mailInfoXml.append("<ENTITY_CODE><![CDATA["+ userInfo.getLoginCode() +"]]></ENTITY_CODE>");
				mailInfoXml.append("<FORMAT_CODE><![CDATA["+ formatCode +"]]></FORMAT_CODE>"); 
				mailInfoXml.append("<XML_DATA>"+ xmlDataBuff.toString() +"</XML_DATA>");
				//Added by Ravindra on 12/03/2021 [Pass transaction xml to mail component]
				mailInfoXml.append("<TRANSACTION_XML>"+ xmlStr +"</TRANSACTION_XML>");
				mailInfoXml.append("<MESSAGE_TYPE><![CDATA[text/html]]></MESSAGE_TYPE>");
				mailInfoXml.append("</Root>");

				BaseLogger.log( "3", userInfo, null, "mailInfoXml : ["+ mailInfoXml +"]" );
				emailObj.sendMail( mailInfoXml.toString(), "ITM", userInfo );
				emailObj = null;
			}
		}
		catch (Exception e) 
		{
			e.printStackTrace();
			BaseLogger.log( "0", userInfo, null, "Exception :: sendNotification : ["+ e.getMessage() +"]" );
		}
	}
	//Added by Ravindra C on 19/01/2021 [to send notification in case of error in uploading] END
	
	private String getProcessData( String collection, String refId )
	{
		NoSQLConnection connection = null;
		String inputData = null;
		try 
		{
			if ( CommonConstants.API_FILE_DESTINATION != null && CommonConstants.API_FILE_DESTINATION.length() > 0 )
			{
				NoSQLConnDriver connDriver = new NoSQLConnDriver();
				connection = connDriver.getConnectNoSQLDB( (userInfo.getEnterprise() + "_NOSQL"), CommonConstants.API_FILE_DESTINATION );
				connDriver = null;
				
				MongoDBHandler dbHandler = new MongoDBHandler( connection, collection );
				ObjectId mongoDBRefId = new ObjectId( refId );
				BaseLogger.log( "3", userInfo, null, "mongoDBRefId : ["+ mongoDBRefId +"]" );
				
				JSONObject mongoDBDataJson = dbHandler.retrieve( mongoDBRefId );
				BaseLogger.log( "3", userInfo, null, "mongoDBDataJson : ["+ mongoDBDataJson +"]" );
				if ( mongoDBDataJson != null )
				{
					inputData = E12GenericUtility.getJSONValue( mongoDBDataJson, "INPUT_DATA" );
				}
			}
		}
		catch (SQLException e) 
		{
			BaseLogger.log( "0", userInfo, null, "SQLException :: getProcessData : ["+ e.getMessage() +"]" );
			e.printStackTrace();
		}
		catch (JSONException e) 
		{
			BaseLogger.log( "0", userInfo, null, "JSONException :: getProcessData : ["+ e.getMessage() +"]" );
			e.printStackTrace();
		}
		catch (Exception e) 
		{
			BaseLogger.log( "0", userInfo, null, "Exception :: getProcessData : ["+ e.getMessage() +"]" );
			e.printStackTrace();
		}
		finally
		{
			try 
			{
				if( connection != null )
				{
					connection.close();
					connection = null;
				}
			}
			catch (Exception e) 
			{
				e.printStackTrace();
			}
		}
		BaseLogger.log( "3", userInfo, null, "inputData : ["+ inputData +"]" );
		return inputData;
	}
	
	//Added by Ravindra C on 19/02/2021 [move failed file to load folder in case of reload] START
	private void moveFailedFileToUpload( String uploadFilePath, String fileName )
	{
		File file = new File( commonUploadFailedFilePath + File.separator + fileName );
		if ( file.exists() )
		{
			File dir = new File( uploadFilePath );
			if ( ! dir.exists() )
			{
				dir.mkdirs();
			}
			BaseLogger.log( "3", userInfo, null, "dir --> ["+ dir +"]" );
			boolean success = file.renameTo( new File( dir, file.getName() ) );
			if ( ! success )
			{
				BaseLogger.log( "3", userInfo, null, "File was not moved" );
			}
		}
		else
		{
			BaseLogger.log( "3", userInfo, null, "File not exist In the failed path" );
			file = new File( commonUploadSuccessFilePath + File.separator + fileName );
			if ( file.exists() )
			{
				File dir = new File( uploadFilePath );
				if ( ! dir.exists() )
				{
					dir.mkdirs();
				}
				BaseLogger.log( "3", userInfo, null, "dir --> ["+ dir +"]" );
				boolean success = file.renameTo( new File( dir, file.getName() ) );
				if ( ! success )
				{
					BaseLogger.log( "3", userInfo, null, "File was not moved" );
				}
			}
		}
	}
	//Added by Ravindra C on 19/02/2021 [move failed file to load folder in case of reload] END
	
	// Added by Gagan B. to copy log file to upload_failed folder
	public void moveLogFile(String batchID) {
		try {
			String fromPath = CommonConstants.JBOSSHOME + File.separator + "server" +  File.separator + "default" + File.separator 
					+ "log" + File.separator + "server.log"; 
			String toPath = CommonConstants.JBOSSHOME + File.separator+ "upload_failed";
			String movedFileName = batchID + "_server.log";
			BaseLogger.log("3", null, null, "Inside processEDIBatchload gsb fromPath [" + fromPath + "]");
			BaseLogger.log("3", null, null, "Inside processEDIBatchload gsb toPath [" + toPath + "]");
			BaseLogger.log("3", null, null, "Inside processEDIBatchload gsb movedFileName [" + movedFileName + "]");
			genericUtility.copyFileWithNewName(fromPath, toPath, movedFileName);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	 public static String getErrorString(Exception e) {
	        StringBuilder sb = new StringBuilder();

	        // Append error message
	        String errorMessage = e.getMessage();
	        if (errorMessage != null) {
	            sb.append("Error Message: ").append(errorMessage).append("\n");
	        }

	        // Append error type
	        String errorType = e.getClass().getSimpleName();
	        if (errorType != null) {
	            sb.append("Error Type: ").append(errorType).append("\n");
	        }

	        // Append stack trace
	        StringWriter sw = new StringWriter();
	        e.printStackTrace(new PrintWriter(sw));
	        String stackTrace = sw.toString();
	        if (stackTrace != null) {
	            sb.append("Stack Trace: ").append(stackTrace).append("\n");
	        }

	        // Append timestamp
	        sb.append("Timestamp: ").append(System.currentTimeMillis()).append("\n");

	        // Ensure the string length does not exceed 2000 characters
	        if (sb.length() > 2000) {
	            return sb.substring(0, 1997) + "..."; 
	        }

	        return sb.toString();
	    }
}