/*
 * TransactionEmailTempltEJB.java
 * Author - Samadhan Pawar
 * Date - 25/11/2016
 * Request Id: S16FKAT002 
 */
package ibase.webitm.ejb;

import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.TreeMap;

import javax.imageio.ImageIO;
import javax.naming.InitialContext;

import org.apache.commons.codec.binary.Base64;
import org.json.JSONObject;
import org.json.XML;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;

import ibase.system.config.AppConnectParm;
import ibase.system.config.ConnDriver;
import ibase.utility.BaseLogger;
import ibase.utility.CommonConstants;
import ibase.utility.E12GenericUtility;
import ibase.utility.EMail;
import ibase.utility.UserInfoBean;
import ibase.webitm.bean.I18NMetadataObject;
import ibase.webitm.reports.utility.JasperReportGenerator;
import ibase.webitm.reports.utility.ResourceConstants;
import ibase.webitm.reports.utility.XSDParser;
import ibase.webitm.utility.ITMException;
import ibase.webitm.utility.TransIDGenerator;

@javax.ejb.Stateless
public class TransactionEmailTempltEJB implements TransactionEmailTempltRemote,TransactionEmailTempltLocal //implements SessionBean  
{	
	E12GenericUtility genericUtility = new E12GenericUtility();
	int lastDyanInpCol = 1;
	int lastDyanSubInpCol = 1;
	@Override
	public String getAllTemplatesHTMLData(String objName, UserInfoBean userInfo) throws ITMException 
	{
		BaseLogger.log("2", userInfo,  null,"[TransactionEmailTempltEJB]Getting Email Templates ....."); //$NON-NLS-1$
		Connection connection = null;
		PreparedStatement stmt = null;
		ResultSet rs = null;
		String retHTMLData = "<TABLE id=\"templateTable\" class=\"templateClass\" cellspacing=\"0\" cellpadding=\"0\">"; 
		try
		{
			connection = getConnection(userInfo);
			String selectQuery = "SELECT MAIL_DESCR,FORMAT_CODE FROM MAIL_FORMAT WHERE TEMPLATE_PURPOSE = ? AND (STATUS IS NULL OR STATUS = ?) AND WIN_NAME = ?  ORDER BY FORMAT_CODE"; 
			stmt = connection.prepareStatement(selectQuery);
			stmt.setString(1, "M");
			stmt.setString(2, "Y");
			stmt.setString(3, "w_"+objName);
			rs = stmt.executeQuery();
			while(rs.next())
			{
				retHTMLData += 	"<TR class=\"templateOpenTr\" id=\""+rs.getString("FORMAT_CODE").trim()+"\" name=\""+rs.getString("FORMAT_CODE")+"\" onClick=\"openSelectedTemplate(this,'"+objName+"','"+rs.getString("FORMAT_CODE")+"');\"> " +
									"<TD class=\"TemplateTd\" > " +
										"<table class=\"templateDataClass\"> " +
											"<tr> <td><DIV CLASS=\"templateNameClass\">"+ rs.getString("FORMAT_CODE") +" </DIV></td></tr> " +
											"<tr> <td><DIV CLASS=\"templeteDescrClass\" id=\"temltDescrDiv"+rs.getString("FORMAT_CODE")+"\" >"+ rs.getString("MAIL_DESCR") +" </DIV></td></tr> " +
										"</table>" +
									"</TD>" +
								"</TR>"; 
			}
			if(rs != null)
			{
				rs.close();
				rs = null;
			}
			if(stmt != null)
			{
				stmt.close();
				stmt = null;
			}
			retHTMLData += "</TABLE>"; 
		}
		catch (ITMException itme)
		{
			BaseLogger.log("0", userInfo,  null,"Exception :TransactionEmailTempltEJB :getAllTemplatesHTMLData :==>");
			throw itme;
		}
		catch (Exception e)
		{
			BaseLogger.log("0", userInfo,  null,"Exception :TransactionEmailTempltEJB :getAllTemplatesHTMLData :==>"); 
			throw new ITMException(e);
		}
		finally
		{
			try
			{
				if(connection != null)
				{
					if(stmt != null)
					{
						stmt.close();
						stmt = null;
					}
					if(rs != null)
					{
						rs.close();
						rs = null;
					}
					connection.close();
					connection = null;
				}
			}
			catch(Exception e)
			{
				System.err.println("Exception :TransactionEmailTempltEJB :getAllTemplatesHTMLData :\n"+e.getMessage()); //$NON-NLS-1$
				throw new ITMException(e);
			}
		}
		
		return retHTMLData;
	}
	@Override
	public String getPopHelpData(String objName, UserInfoBean userInfo,String pContext,String oContext,String fieldName,String jsonTranData) throws ITMException 
	{
		String standardNameForXML = objName + pContext + oContext + ".xml";
		String defaultPathForMetadataXML = "";
		String targetFileName = "";
		String xmlString ="";
		Document metadataDoc = null;
		TreeMap< Integer, TreeMap<Integer, I18NMetadataObject> > yTextMap = null;
		HashMap<String,String> labelFormDataMap = new HashMap<String,String>();
		HashMap<String,String> inputFormDataMap = new HashMap<String,String>();
		String fieldText = "";
		String fieldLable = "";
		int cnter = 1;
		String popHelpData = "";
		try
		{
			//Samadhan
			BaseLogger.log("3", userInfo,  null,"jsonTranData:"+jsonTranData);
			if(jsonTranData == null || jsonTranData.equalsIgnoreCase("null") || jsonTranData.length() <= 0)
			{
				BaseLogger.log("3", userInfo,  null,"TransactionEmailTempltEJB::getPopHelpData::Creating pophelp xml from bin metadata:"+standardNameForXML);
				// Commented and Added by Pankaj R on 24-Nov-20 as suggested by Danish sir
				// defaultPathForMetadataXML = CommonConstants.JBOSSHOME + File.separator + "bin" + File.separator + "metadata" + File.separator;
				defaultPathForMetadataXML = CommonConstants.JBOSSHOME + File.separator + "server" + File.separator + "default" + File.separator + "deploy" + File.separator + "ibase.ear" + File.separator + "metadata" + File.separator;

				targetFileName = defaultPathForMetadataXML + standardNameForXML; 
				xmlString = readFile(targetFileName);
				metadataDoc = genericUtility.parseString(xmlString);
				yTextMap = parseMetadataObjects(metadataDoc);

				Iterator<Integer> yTextMapIt = yTextMap.keySet().iterator();
				while( yTextMapIt.hasNext() )
				{
					Integer yCord = yTextMapIt.next();
					TreeMap<Integer, I18NMetadataObject> xTextMap = yTextMap.get( yCord );
					if( xTextMap != null )
					{
						Iterator<Integer> xTextMapIt = xTextMap.keySet().iterator();
						while( xTextMapIt.hasNext() )
						{
							Integer xCord = xTextMapIt.next();
							I18NMetadataObject xMetadataObj = xTextMap.get(xCord);
							//BaseLogger.log("3", userInfo,  null,"xCord..." + xCord + "xMetadataObj[" + xMetadataObj + "]");
							if( "Text".equalsIgnoreCase( xMetadataObj.getMetaType() ) )
							{
								labelFormDataMap.put(xMetadataObj.getName(),xMetadataObj.getText() );
							}
							else
							{
								inputFormDataMap.put(xMetadataObj.getName(), xMetadataObj.getName());
							}
						}
					}
				}
			}
			else
			{
				JSONObject jsonObject = new JSONObject(jsonTranData);
				Iterator<?> keys = jsonObject.keys();
				while(keys.hasNext() ) 
				{
					String key = (String)keys.next();
					if ( jsonObject.get(key) instanceof JSONObject ) 
					{
						JSONObject childJson = new JSONObject(jsonObject.get(key).toString());
						BaseLogger.log("3", userInfo,  null,childJson);
						Iterator<?> childKeys = childJson.keys();
						while(childKeys.hasNext() ) 
						{
							String childKey = (String)childKeys.next();
							BaseLogger.log("3", userInfo,  null,childKey);
							if(childKey.endsWith("_t"))
							{
								labelFormDataMap.put(childKey, childJson.getString(childKey) );
							}
							else
							{
								inputFormDataMap.put(childKey, childKey);
							}
						}
					}
					break;
				}
			}
			popHelpData += "<DOCUMENTROOT><DESCRIPTION/><METADATA><DEFAULT_COL>1</DEFAULT_COL></METADATA><GROUP0><DESCRIPTION/><HEADER0>";
			for (String key : inputFormDataMap.keySet()) 
			{
				fieldText = "";
				fieldLable = "";
				if(labelFormDataMap.containsKey(key+"_t"))
				{
					fieldLable = labelFormDataMap.get(key+"_t");
					if((fieldLable.substring(fieldLable.length()-1)).equals(":"))
					{
						fieldLable = fieldLable.substring(0,fieldLable.length()-1);
					}
					fieldText = inputFormDataMap.get(key);
					popHelpData += "<DETAIL id=\""+cnter+"\"><"+fieldName+" dbType=\"VARCHAR2\"><![CDATA["+fieldLable+"]]></"+fieldName+">" +
								" <Descr dbType=\"VARCHAR2\"><![CDATA["+fieldText+"]]></Descr></DETAIL>";
				cnter++;
				}
			}
			popHelpData += "<DESCRIPTION/></HEADER0></GROUP0></DOCUMENTROOT>";
			
		}catch(Exception e)
		{
			throw new ITMException(e);
		}
		return popHelpData;
	}
	
	@Override
	public String saveNewEmailTemplate(String objName, UserInfoBean userInfo,String toAddr,String ccAddr,String bccAddr,String subject,String body,String templateName,String templateCode,String attachObjLinks) throws ITMException
	{
		String retString = saveNewEmailTemplate(objName, userInfo, toAddr, ccAddr, bccAddr, subject, body, templateName, templateCode, attachObjLinks, "");
		return retString;
	}

	
	@Override
	public String saveNewEmailTemplate(String objName, UserInfoBean userInfo,String toAddr,String ccAddr,String bccAddr,String subject,String body,String templateName,String templateCode,String attachObjLinks, String calledFrom) throws ITMException 
	{
		BaseLogger.log("2", userInfo,  null,"saveNewEmailTemplate in save" +calledFrom);

		String retString = "<root><tran_id>";
		BaseLogger.log("2", userInfo,  null,"[TransactionEmailTempltEJB][saveNewEmailTemplate]Saving new Email Templates ....."); //$NON-NLS-1$
		Connection connection = null;
		PreparedStatement stmt = null;
		ResultSet rs = null;
		String formatCode ="";
		String errString = "";
		BaseLogger.log("2", userInfo,  null,"attachObjLinks in save" +attachObjLinks);
		try
		{
			connection = getConnection(userInfo);
			errString = checkTemplateExists(templateCode,connection,userInfo);
			if(errString.length() > 0 || !errString.equalsIgnoreCase(""))
			{
				return errString;
			}
			
			/*
			Changes by Gagan B. on 01-OCT-24 to create a file at path wildlfy/MAIL_FORMAT/<FORMAT_CODE>.txt
			which will containing the mail body of the mail format saved from EmailTemplate.jsp -- START
			*/
			String fileName = templateCode.trim() + ".html";
			String filePath = CommonConstants.JBOSSHOME + File.separator + "MAIL_FORMAT";
			String documentId = "";
			if (E12GenericUtility.checkNull(calledFrom).equals("EMAIL_TEMPLATE")) {
				
				if ( body.length() > 0 )
				{
					body = "<html>" + body + "</html>";
					BaseLogger.log( "3", null, null, "BODY_TEXT " + "[" + body + "]" );
					new E12GenericUtility().writeFile( filePath, fileName , body );
				}
				
				/*
				 * Changes by Gagan B. on 08-OCT-24 to upload html file to alfresco server in MAIL_FORMAT object and 
				 * store the doc ID in MAIL_FORMAT.BODY_TEXT -- START
				 */
				String uploadDocumentURL = CommonConstants.TOMCAT_HOME + 
						"/ibase/rest/DocumentHandlerService/uploadDocument";
				
				String refSer = "M-FOR";
				String refID = fileName;
				
				String HTMLFilePath = filePath + File.separator + refID;
				
				Unirest.setTimeouts(0, 0);
				HttpResponse<String> response = Unirest.post(uploadDocumentURL).header("TOKEN_ID", userInfo.getTokenID())
				   .field("REF_SER", refSer)
				   .field("REF_ID", refID)
				   .field("OBJ_NAME", "mail_format")
				   .field("DOC_LINK_OPT", "")
				   .field("FILE_METADATA", "")
				   .field("DOC_META_DATA", "")
				   .field("REF_DESCR", "")
				   .field("EXP_DATE", "")
				   .field("CACHE_OPT", "0")
				   .field("file", new File(HTMLFilePath))
				   .asString();
				
				String statusText = response.getStatusText();
				int statusCode = response.getStatus();
				String responseString = response.getBody().toString();
				
				BaseLogger.log("3", null, null, "Inside saveNewEmailTemplate statusText [" + statusText + "]");
				BaseLogger.log("3", null, null, "Inside saveNewEmailTemplate statusCode [" + statusCode + "]");
				BaseLogger.log("3", null, null, "Inside saveNewEmailTemplate responseString [" + responseString + "]");
				
				JSONObject uploadDocumentResponse = new JSONObject(responseString);
		        
		        // Extract the Document_Id
		        documentId = uploadDocumentResponse.getJSONObject("ID").getString("Document_Id");
		        
				BaseLogger.log("3", null, null, "Inside saveNewEmailTemplate documentId [" + documentId + "]");
				/*
				 * Changes by Gagan B. on 08-OCT-24 to upload html file to alfresco server in MAIL_FORMAT object and 
				 * store the doc ID in MAIL_FORMAT.BODY_TEXT -- END
				 */
				
			}
			/*
			Changes by Gagan B. on 01-OCT-24 to create a file at path wildlfy/MAIL_FORMAT/<FORMAT_CODE>.txt
			which will containing the mail body of the mail format saved from EmailTemplate.jsp -- END
			*/
			
			
			
			String sqlQuery = "Insert into MAIL_FORMAT (FORMAT_CODE,FORMAT_TYPE,SEND_TO,COPY_TO,BLIND_COPY,SUBJECT,BODY_TEXT,BODY_COMP,PRIORITY,DELIVERY_REPORT,RETURN_RECEIPT," +
							"MAIL_APPLICATION,MAIL_SERVER,MAIL_BOX,MAIL_ID,ATTACH_TYPE,ATTACH_TEXT,WINNAME,WIN_NAME,MAIL_GENERATION,MAIL_DESCR,FN_NAME,COND_METHOD,EMAIL_EXPR,TEMPLATE_PURPOSE,STATUS,USER_ID__OWN) " +
							"VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) "; 
			stmt = connection.prepareStatement(sqlQuery);
			//formatCode = getTransID("w_mail_format",connection);
			formatCode = templateCode;
			stmt.setString(1, formatCode);//FORMAT_CODE      NOT NULL CHAR(30)       
			stmt.setString(2, "T");//FORMAT_TYPE      NOT NULL VARCHAR2(1)    
			stmt.setString(3, toAddr);//SEND_TO          NOT NULL VARCHAR2(500)  
			stmt.setString(4, ccAddr);//COPY_TO                   VARCHAR2(500)  
			stmt.setString(5, bccAddr);//BLIND_COPY                VARCHAR2(500)  
			stmt.setString(6, subject);//SUBJECT                   VARCHAR2(150)  

			/*
			Changes by Gagan B. on 01-OCT-24 to create a file at path wildlfy/MAIL_FORMAT/<FORMAT_CODE>.txt
			which will containing the mail body of the mail format saved from EmailTemplate.jsp
			*/
			if (E12GenericUtility.checkNull(calledFrom).equalsIgnoreCase("")) {
				body = removeInlineImages(body);	
			} else if (E12GenericUtility.checkNull(calledFrom).equals("EMAIL_TEMPLATE")) {
//				body = filePath + File.separator + fileName;
				// Changes by Gagan B. on 08-OCT-24 to upload HTML to alfresco server in MAIL_FORMAT object and store the doc ID in MAIL_FORMAT.BODY_TEXT
				body = documentId;
			}
			/*
			Changes by Gagan B. on 01-OCT-24 to create a file at path wildlfy/MAIL_FORMAT/<FORMAT_CODE>.txt
			which will containing the mail body of the mail format saved from EmailTemplate.jsp
			*/
			
			stmt.setString(7, body);//BODY_TEXT                 VARCHAR2(1500) 
			stmt.setInt(8, 0);//BODY_COMP                 NUMBER(1)      
			stmt.setInt(9, 0);//PRIORITY                  NUMBER(1)      
			stmt.setInt(10, 0);//DELIVERY_REPORT           NUMBER(1)      
			stmt.setInt(11, 0);//RETURN_RECEIPT            NUMBER(1)      
			stmt.setString(12,"");//MAIL_APPLICATION          VARCHAR2(1)    
			stmt.setString(13, CommonConstants.SMTPHOST);//MAIL_SERVER               VARCHAR2(60)   
			stmt.setString(14, null);//MAIL_BOX                  VARCHAR2(60)   
			stmt.setString(15, CommonConstants.MAILFROM);//MAIL_ID                   VARCHAR2(60)   
			stmt.setString(16, "D");//ATTACH_TYPE      VARCHAR2(1)   //Change By PriyankaC to send selected type of attachment in mail.  
			stmt.setString(17, attachObjLinks);//ATTACH_TEXT     VARCHAR2(4000) //Change By PriyankaC to send selected type of attachment in mail.
			stmt.setString(18, null);//WINNAME                   VARCHAR2(30)   
			stmt.setString(19, "w_"+objName);//WIN_NAME                  VARCHAR2(40)   
			stmt.setString(20, null);//MAIL_GENERATION           CHAR(1)        
			stmt.setString(21, templateName);//MAIL_DESCR                VARCHAR2(60)   
			stmt.setString(22, null);//FN_NAME                   VARCHAR2(50)   
			stmt.setString(23, null);//COND_METHOD               VARCHAR2(100)  
			stmt.setString(24, null);//EMAIL_EXPR                VARCHAR2(500)  
			stmt.setString(25, "M");//TEMPLATE_PURPOSE			CHAR(1) 
			stmt.setString(26, "Y");//STATUS			CHAR(1) 
			stmt.setString(27, userInfo.getLoginCode());//USER_ID__OWN			CHAR(10) 
					
			//stmt.executeQuery();
			//Added By Pankaj T. on 16-06-2021 changed executeQuery to executeUpdate for data manipulation error in mysql
			stmt.executeUpdate();
			
			if(stmt != null)
			{
				stmt.close();
				stmt = null;
			}
			retString = retString +formatCode+ "</tran_id></root>";
			connection.commit();
		}
		catch (ITMException itme)
		{
			BaseLogger.log("0", userInfo,  null,"Exception :TransactionEmailTempltEJB :saveNewEmailTemplate :==>"); 
			itme.printStackTrace();
			throw itme;
		}
		catch (Exception e)
		{
			BaseLogger.log("0", userInfo,  null,"Exception :TransactionEmailTempltEJB :saveNewEmailTemplate :==>"); 
			e.printStackTrace();
			throw new ITMException(e);
		}
		finally
		{
			try
			{
				if(connection != null)
				{
					if(stmt != null)
					{
						stmt.close();
						stmt = null;
					}
					if(rs != null)
					{
						rs.close();
						rs = null;
					}
					connection.close();
					connection = null;
				}
			}
			catch(Exception e)
			{
				System.err.println("Exception :TransactionEmailTempltEJB :saveNewEmailTemplate :\n"+e.getMessage()); 
				throw new ITMException(e);
			}
		}
		
		return retString;
	}
	
	private String removeInlineImages(String body) 
	{
		String findStr = "<img src=\"";
		String colFullName = "";
		int currentIndex = 0;
		int nextSearchIndex = 0;
		String currColVal = "";
		while(body.indexOf(findStr,nextSearchIndex) != -1)
		{
			currColVal = "";
			BaseLogger.log("3", null,  null,nextSearchIndex);
			currentIndex = body.indexOf(findStr,nextSearchIndex);
			String firstPart = body.substring(0,currentIndex);
			String lastPart = body.substring(currentIndex,body.length());
			colFullName = lastPart.substring(0,lastPart.indexOf(">")+1);
			BaseLogger.log("3", null,  null,"colFullName:"+colFullName);
			
			currColVal = "";
			body = firstPart + lastPart.replaceFirst(colFullName.replace("+", "\\+"), currColVal);
			nextSearchIndex = currentIndex+currColVal.length();
		}
		return body;
	}
	private String checkTemplateExists(String templateCode,Connection connection,UserInfoBean userInfo) throws ITMException 
	{
		String retString = "";
		try
		{
			PreparedStatement stmt = null;
			ResultSet rs = null;
			//String sqlQuery = "SELECT FORMAT_CODE,(SELECT DESCR FROM ITM2MENU WHERE WIN_NAME = MAIL_FORMAT.WIN_NAME) FROM MAIL_FORMAT WHERE FORMAT_CODE = ? ";
			String sqlQuery = "SELECT MF.FORMAT_CODE, IM.DESCR FROM MAIL_FORMAT MF LEFT OUTER JOIN ITM2MENU IM ON IM.WIN_NAME = MF.WIN_NAME WHERE FORMAT_CODE = ? ";  
			stmt = connection.prepareStatement(sqlQuery);
			stmt.setString(1, templateCode);//FORMAT_CODE      NOT NULL CHAR(30)    
			rs = stmt.executeQuery();
			if(rs.next())
			{
				retString = checkNull(rs.getString(2));
				StringBuffer retStrBuff = new StringBuffer("<?xml version='1.0' encoding='"+userInfo.getCharEnc()+"'?><Errors>"); 
				retStrBuff.append("<error id='' type='E' column_name='tempateHdrName'>"); 
				retStrBuff.append("<message><![CDATA[Template code already exists]]></message>");
				if(retString.equalsIgnoreCase(""))
				{
					retStrBuff.append("<description><![CDATA[ Template code already exists, Enter different template code ]]></description>");
				}
				else
				{
					retStrBuff.append("<description><![CDATA[ Template code already exists for "+retString+", Enter different template code ]]></description>");
				}
				retStrBuff.append("<trace><![CDATA[]]></trace>"); 
				retStrBuff.append("<redirect>1</redirect></error></Errors>"); 
			    retString = retStrBuff.toString();	
			}
			if(stmt != null)
			{
				stmt.close();
				stmt = null;
			}
			if(rs != null)
			{
				rs.close();
				rs = null;
			}
		}
		catch (Exception e)
		{
			BaseLogger.log("0", userInfo,  null,"Exception :TransactionEmailTempltEJB :checkTemplateExists :==>"); //$NON-NLS-1$
			throw new ITMException(e);
		}
		return retString;
	}
	public String updateEmailTemplate(String objName, UserInfoBean userInfo,String toAddr, String ccAddr, String bccAddr, String subject,String body, String templateCode,String templateName,String attachObjLinks) throws ITMException
	{
		String retString = "";
		BaseLogger.log("2", userInfo,  null,"[TransactionEmailTempltEJB][updateEmailTemplate]Updating Email Templates ....."); //$NON-NLS-1$
		BaseLogger.log("2", userInfo,  null,"attachObjLinks in update" +attachObjLinks);
		Connection connection = null;
		PreparedStatement stmt = null;
		ResultSet rs = null;
		try
		{
			connection = getConnection(userInfo); 
			String sqlQuery = "UPDATE MAIL_FORMAT SET SEND_TO = ?,COPY_TO = ?,BLIND_COPY = ?,SUBJECT = ?, BODY_TEXT = ?, MAIL_DESCR = ?,ATTACH_TEXT = ?,ATTACH_TYPE = ? WHERE FORMAT_CODE = ?";
			stmt = connection.prepareStatement(sqlQuery);
					     
			stmt.setString(1, toAddr);//SEND_TO          NOT NULL VARCHAR2(500)  
			stmt.setString(2, ccAddr);//COPY_TO                   VARCHAR2(500)  
			stmt.setString(3, bccAddr);//BLIND_COPY                VARCHAR2(500)  
			stmt.setString(4, subject);//SUBJECT                   VARCHAR2(150)  
			body = removeInlineImages(body);
			stmt.setString(5, body);//BODY_TEXT                 VARCHAR2(1500) 
			stmt.setString(6, templateName);//MAIL_DESCR                VARCHAR2(60)   
			stmt.setString(7, attachObjLinks);//ATTACH_TEXT        VARCHAR2(4000) //Change By PriyankaC to send selected type of attachment in mail. 
			stmt.setString(8,"D");//ATTACH_TYPE          VARCHAR2(1) //Change By PriyankaC to send selected type of attachment in mail.
			stmt.setString(9, templateCode);//FORMAT_CODE      NOT NULL CHAR(30)    
		
			//stmt.executeQuery();
			//Added By Pankaj T. on 16-06-2021 changed executeQuery to executeUpdate for data manipulation error in mysql
			stmt.executeUpdate();
			
			if(stmt != null)
			{
				stmt.close();
				stmt = null;
			}
			connection.commit();
			retString = "SUCCESS";
		}
		catch (ITMException itme)
		{
			BaseLogger.log("0", userInfo,  null,"Exception :TransactionEmailTempltEJB :updateEmailTemplate :==>"); //$NON-NLS-1$
			throw itme;
		}
		catch (Exception e)
		{
			BaseLogger.log("0", userInfo,  null,"Exception :TransactionEmailTempltEJB :updateEmailTemplate :==>"); //$NON-NLS-1$
			throw new ITMException(e);
		}
		finally
		{
			try
			{
				if(connection != null)
				{
					if(stmt != null)
					{
						stmt.close();
						stmt = null;
					}
					if(rs != null)
					{
						rs.close();
						rs = null;
					}
					connection.close();
					connection = null;
				}
			}
			catch(Exception e)
			{
				System.err.println("Exception :TransactionEmailTempltEJB :updateEmailTemplate :\n"+e.getMessage()); //$NON-NLS-1$
				throw new ITMException(e);
			}
		}

		return retString;
	}
	
	@Override
	public String deteteSelectedTemplate(String objName, UserInfoBean userInfo,String formatCode) throws ITMException 
	{
		String retstring = "";
		Connection connection = null;
		PreparedStatement stmt = null;
		ResultSet rs = null;
		try
		{
			connection = getConnection(userInfo); 
			//String sqlQuery = "DELETE FROM MAIL_FORMAT WHERE FORMAT_CODE = ?";
			String sqlQuery = "UPDATE MAIL_FORMAT SET STATUS = ? WHERE FORMAT_CODE = ?";
			stmt = connection.prepareStatement(sqlQuery);
			stmt.setString(1, "N");//STATUS      NOT NULL CHAR(1)    
			stmt.setString(2, formatCode);//FORMAT_CODE      NOT NULL CHAR(30)    
			//stmt.executeQuery();
			//Added By Pankaj T. on 16-06-2021 changed executeQuery to executeUpdate for data manipulation error in mysql
			stmt.executeUpdate();
			connection.commit();
		}
		catch (ITMException itme)
		{
			BaseLogger.log("0", userInfo,  null,"Exception :TransactionEmailTempltEJB :deteteSelectedTemplate :==>"); 
			itme.printStackTrace();
			throw itme;
		}
		catch (Exception e)
		{
			BaseLogger.log("0", userInfo,  null,"Exception :TransactionEmailTempltEJB :deteteSelectedTemplate :==>");
			e.printStackTrace();
			throw new ITMException(e);
		}
		finally
		{
			try
			{
				if(connection != null)
				{
					if(stmt != null)
					{
						stmt.close();
						stmt = null;
					}
					if(rs != null)
					{
						rs.close();
						rs = null;
					}
					connection.close();
					connection = null;
				}
			}
			catch(Exception e)
			{
				System.err.println("Exception :TransactionEmailTempltEJB :deteteSelectedTemplate :\n"+e.getMessage()); //$NON-NLS-1$
				throw new ITMException(e);
			}
		}	
		return retstring;
	}
	
	public String getEmailData(String objName, UserInfoBean userInfo,String toAddr, String ccAddr, String bccAddr, String subject,String body, String tranDataStr, String tranPKNames,String tranPKValues, String attachments) throws ITMException {
		return getEmailData(objName, userInfo, toAddr, ccAddr, bccAddr, subject, body, tranDataStr, tranPKNames, tranPKValues, attachments, "");
	}

	
	public String getEmailData(String objName, UserInfoBean userInfo,String toAddr, String ccAddr, String bccAddr, String subject,String body, String tranDataStr, String tranPKNames,String tranPKValues, String attachments, String calledFrom) throws ITMException
	{
		BaseLogger.log("3", userInfo,  null,"getEmailData calledFrom[" + calledFrom +"]");
		String retXmlData = "";
		try
		{	
			retXmlData += "<Document>"; 
			String pkValues[] = tranPKValues.split(",");
			String tranId = "";
			Document currentPkTranDom = null;
			
			if (E12GenericUtility.checkNull(calledFrom).equalsIgnoreCase("EMAIL_TEMPLATE")) {
				
				retXmlData += "<EMAILDATA>";
				
				retXmlData += "<TRAN_ID><![CDATA["+tranId+"]]></TRAN_ID>";
				retXmlData += "<SEND_TO><![CDATA["+toAddr+"]]></SEND_TO>";
				retXmlData += "<COPY_TO><![CDATA["+ccAddr+"]]></COPY_TO>";
				retXmlData += "<BLIND_COPY><![CDATA["+bccAddr+"]]></BLIND_COPY>";
				retXmlData += "<SUBJECT><![CDATA["+subject+"]]></SUBJECT>";
				retXmlData += "<BODY_TEXT><![CDATA["+body+"]]></BODY_TEXT>";
				retXmlData += "<ATTACHMENTS><![CDATA["+getAttachmentsHtml(attachments,objName,userInfo)+"]]></ATTACHMENTS>";
				retXmlData += "</EMAILDATA>";
				retXmlData += "</Document>"; 

			} else {
				for(int pkCount = 0; pkCount < pkValues.length;pkCount++ )
				{
					currentPkTranDom = getCurrentTranDom(pkValues[pkCount], userInfo, objName);
					retXmlData += "<EMAILDATA>";
					tranId = pkValues[pkCount];
					if((tranId.substring(tranId.length()-1)).equals(":"))
					{
						tranId = tranId.substring(0,tranId.length()-1);
					}
					retXmlData += "<TRAN_ID><![CDATA["+tranId+"]]></TRAN_ID>";

					retXmlData += "<SEND_TO><![CDATA["+getEmailAddress(toAddr, currentPkTranDom, userInfo)+"]]></SEND_TO>";

					retXmlData += "<COPY_TO><![CDATA["+getEmailAddress(ccAddr, currentPkTranDom, userInfo)+"]]></COPY_TO>";

					retXmlData += "<BLIND_COPY><![CDATA["+getEmailAddress(bccAddr, currentPkTranDom, userInfo)+"]]></BLIND_COPY>";

					retXmlData += "<SUBJECT><![CDATA["+getFormatedEmailSub(subject,currentPkTranDom)+"]]></SUBJECT>";

					retXmlData += "<BODY_TEXT><![CDATA["+getFormatedEmailBody(body,currentPkTranDom)+"]]></BODY_TEXT>";
					
					retXmlData += "<ATTACHMENTS><![CDATA["+getAttachmentsHtml(attachments,objName,userInfo)+"]]></ATTACHMENTS>";

					retXmlData += "</EMAILDATA>";
				}	
				retXmlData += "</Document>"; 
			}
			
			
		}
		catch (ITMException itme)
		{
			BaseLogger.log("0", userInfo,  null,"Exception :TransactionEmailTempltEJB :getEmailData :==>");
			throw itme;
		}
		catch (Exception e)
		{
			BaseLogger.log("0", userInfo,  null,"Exception :TransactionEmailTempltEJB :getEmailData :==>");
			throw new ITMException(e);
		}
		return retXmlData;
	}
	public String getEmailDataFromJsonData(String objName, UserInfoBean userInfo,String toAddr, String ccAddr, String bccAddr, String subject,String body, String tranDataStr, String tranPKNames,String tranPKValues, String attachments, String jsonTranData) throws ITMException
	{
		String retXmlData = "";
		try
		{	
			retXmlData += "<Document>"; 
			String tranId = "";
			Document currentPkTranDom = null;
			JSONObject jsonObject = new JSONObject(jsonTranData);
			Iterator<?> keys = jsonObject.keys();
			String jsonToXml = "";
			while(keys.hasNext() ) 
			{
				tranId = (String)keys.next();
				if ( jsonObject.get(tranId) instanceof JSONObject ) 
				{
					JSONObject childJson = new JSONObject(jsonObject.get(tranId).toString());
					BaseLogger.log("3", userInfo,  null,childJson);
					jsonToXml = XML.toString(childJson);
					BaseLogger.log("3", userInfo,  null,jsonToXml);
					currentPkTranDom = genericUtility.parseString("<Detail1>"+jsonToXml+"</Detail1>");
				}
				retXmlData += "<EMAILDATA>";
				
				if((tranId.substring(tranId.length()-1)).equals(":"))
				{
					tranId = tranId.substring(0,tranId.length()-1);
				}
				retXmlData += "<TRAN_ID><![CDATA["+tranId+"]]></TRAN_ID>";

				retXmlData += "<SEND_TO><![CDATA["+getEmailAddress(toAddr, currentPkTranDom, userInfo)+"]]></SEND_TO>";

				retXmlData += "<COPY_TO><![CDATA["+getEmailAddress(ccAddr, currentPkTranDom, userInfo)+"]]></COPY_TO>";

				retXmlData += "<BLIND_COPY><![CDATA["+getEmailAddress(bccAddr, currentPkTranDom, userInfo)+"]]></BLIND_COPY>";

				retXmlData += "<SUBJECT><![CDATA["+getFormatedEmailSub(subject,currentPkTranDom)+"]]></SUBJECT>";

				retXmlData += "<BODY_TEXT><![CDATA["+getFormatedEmailBody(body,currentPkTranDom)+"]]></BODY_TEXT>";
				
				retXmlData += "<ATTACHMENTS><![CDATA["+getAttachmentsHtml(attachments,objName,userInfo)+"]]></ATTACHMENTS>";

				retXmlData += "</EMAILDATA>";
			}	
			retXmlData += "</Document>"; 
		}
		catch (ITMException itme)
		{
			BaseLogger.log("0", userInfo,  null,"Exception :TransactionEmailTempltEJB :getEmailData :==>");
			throw itme;
		}
		catch (Exception e)
		{
			BaseLogger.log("0", userInfo,  null,"Exception :TransactionEmailTempltEJB :getEmailData :==>");
			throw new ITMException(e);
		}
		return retXmlData;
	}
	
	public String sendMail(String objName, UserInfoBean userInfo,String toAddr, String ccAddr, String bccAddr, String subject,String body, String tranDataStr, String tranPKNames,String tranPKValues, String attachments,String saveFlag,String templateName,String templateCode,String editFlag) throws ITMException
	{
		String retXmlData = "";
		String saveStatus = "";
		try
		{	
			if("true".equalsIgnoreCase(saveFlag))
			{
				if("A".equalsIgnoreCase(editFlag))
				{
					saveStatus = saveNewEmailTemplate(objName, userInfo, toAddr, ccAddr, bccAddr, subject, body, templateName, templateCode, attachments);
				}
				else
				{
					saveStatus = updateEmailTemplate(objName, userInfo, toAddr, ccAddr, bccAddr, subject, body, templateCode, templateName, attachments);
				}
				if(saveStatus != null && saveStatus.indexOf("<Errors>") != -1)
				{
					return saveStatus;
				}
			}
			String pkValues[] = tranPKValues.split(",");
			String tranId = "";
			Document currentPkTranDom = null;
			String mailData = "<root>";
			for(int pkCount = 0; pkCount < pkValues.length;pkCount++ )
			{
				//Added By Pankaj T. on 04-08-2021 if transaction data present then use at is else create - start
				try
				{
					E12GenericUtility e12GenericUtility = new E12GenericUtility();
					if( E12GenericUtility.checkNull(tranDataStr).length() > 0 )
					{
						currentPkTranDom = e12GenericUtility.parseString(tranDataStr);
					}
					else
					{
						currentPkTranDom = getCurrentTranDom(pkValues[pkCount], userInfo, objName);
					}
				}
				catch (Exception e)
				{
					System.out.println("TransactionEmailTempltEJB.sendMail() Exception tranDataStr : ["+tranDataStr+"]");
					currentPkTranDom = getCurrentTranDom(pkValues[pkCount], userInfo, objName);	
				}
				//Added By Pankaj T. on 04-08-2021 if transaction data present then use at is else create - end
				mailData += "<EMAILDATA>";
				tranId = pkValues[pkCount];
				if( ( ( tranId != null ) && ( tranId.length() > 0 ) && ( tranId.substring(tranId.length()-1)).equals(":") ) )
				{
					tranId = tranId.substring(0,tranId.length()-1);
				}
				mailData += "<TRAN_ID><![CDATA["+tranId+"]]></TRAN_ID>";

				mailData += "<TO><![CDATA["+getEmailAddress(toAddr, currentPkTranDom, userInfo)+"]]></TO>";

				mailData += "<CC><![CDATA["+getEmailAddress(ccAddr, currentPkTranDom, userInfo)+"]]></CC>";

				mailData += "<BCC><![CDATA["+getEmailAddress(bccAddr, currentPkTranDom, userInfo)+"]]></BCC>";

				mailData += "<SUB><![CDATA["+getFormatedEmailSub(subject,currentPkTranDom)+"]]></SUB>";

				mailData += "<BODY><![CDATA["+getFormatedEmailBody(body,currentPkTranDom)+"]]></BODY>";
				
				mailData += "<ATTACHMENTS><![CDATA["+attachments+"]]></ATTACHMENTS>";
				//Added by Amol S  on 15-May -25 to passs template code in xml --start
				mailData += "<TEMPLATE_CODE><![CDATA["+templateCode+"]]></TEMPLATE_CODE>";
				//Added by Amol S  on 15-May -25 to passs template code in xml --End

				mailData += "</EMAILDATA>";
			}	
			mailData += "</root>"; 
			BaseLogger.log("0", userInfo,  null,"MailData:::==>"+mailData); 
            //Comment out by Ajit to pass the transaction xml to sendMail method on 12-JAN-26
			//retXmlData = sendMail(objName, userInfo, mailData,"");
			retXmlData = sendMail(objName, userInfo, mailData,"",tranDataStr);
		}
		catch (ITMException itme)
		{
			BaseLogger.log("0", userInfo,  null,"Exception :TransactionEmailTempltEJB :sendMail :==>"); 
			throw itme;
		}
		catch (Exception e)
		{
			BaseLogger.log("0", userInfo,  null,"Exception :TransactionEmailTempltEJB :sendMail :==>"); 
			throw new ITMException(e);
		}
		return retXmlData;
	}
	
	public String sendMailFromJsonData(String objName, UserInfoBean userInfo,String toAddr, String ccAddr, String bccAddr, String subject,String body, String tranDataStr, String tranPKNames,String tranPKValues, String attachments,String saveFlag,String templateName,String templateCode,String editFlag, String jsonTranData) throws ITMException
	{
		String retXmlData = "";
		String saveStatus = "";
		try
		{	
			if("true".equalsIgnoreCase(saveFlag))
			{
				if("A".equalsIgnoreCase(editFlag))
				{
					saveStatus = saveNewEmailTemplate(objName, userInfo, toAddr, ccAddr, bccAddr, subject, body, templateName, templateCode, attachments);
				}
				else
				{
					saveStatus = updateEmailTemplate(objName, userInfo, toAddr, ccAddr, bccAddr, subject, body, templateCode, templateName, attachments);
				}
				if(saveStatus != null && saveStatus.indexOf("<Errors>") != -1)
				{
					return saveStatus;
				}
			}
			
			String tranId = "";
			Document currentPkTranDom = null;
			String mailData = "<root>";
			
			JSONObject jsonObject = new JSONObject(jsonTranData);
			Iterator<?> keys = jsonObject.keys();
			String jsonToXml = "";
			while(keys.hasNext() ) 
			{
				tranId = (String)keys.next();
				if ( jsonObject.get(tranId) instanceof JSONObject ) 
				{
					JSONObject childJson = new JSONObject(jsonObject.get(tranId).toString());
					BaseLogger.log("3", userInfo,  null,childJson);
					jsonToXml = XML.toString(childJson);
					BaseLogger.log("3", userInfo,  null,jsonToXml);
					currentPkTranDom = genericUtility.parseString("<Detail1>"+jsonToXml+"</Detail1>");
				}
			
				mailData += "<EMAILDATA>";
				
				if((tranId.substring(tranId.length()-1)).equals(":"))
				{
					tranId = tranId.substring(0,tranId.length()-1);
				}
				mailData += "<TRAN_ID><![CDATA["+tranId+"]]></TRAN_ID>";

				mailData += "<TO><![CDATA["+getEmailAddress(toAddr, currentPkTranDom, userInfo)+"]]></TO>";

				mailData += "<CC><![CDATA["+getEmailAddress(ccAddr, currentPkTranDom, userInfo)+"]]></CC>";

				mailData += "<BCC><![CDATA["+getEmailAddress(bccAddr, currentPkTranDom, userInfo)+"]]></BCC>";

				mailData += "<SUB><![CDATA["+getFormatedEmailSub(subject,currentPkTranDom)+"]]></SUB>";

				mailData += "<BODY><![CDATA["+getFormatedEmailBody(body,currentPkTranDom)+"]]></BODY>";
				
				mailData += "<ATTACHMENTS><![CDATA["+attachments+"]]></ATTACHMENTS>";

				mailData += "</EMAILDATA>";
			}	
			mailData += "</root>"; 
			retXmlData = sendMail(objName, userInfo, mailData, jsonTranData);
		}
		catch (ITMException itme)
		{
			BaseLogger.log("0", userInfo,  null,"Exception :TransactionEmailTempltEJB :sendMail :==>"); 
			throw itme;
		}
		catch (Exception e)
		{
			BaseLogger.log("0", userInfo,  null,"Exception :TransactionEmailTempltEJB :sendMail :==>"); 
			throw new ITMException(e);
		}
		return retXmlData;
	}
	
	
	public String sendMail(String objName, UserInfoBean userInfo,String mailData, String jsonTranData)throws ITMException
	{
		
		BaseLogger.log("3", userInfo,  null,"sendMail Method callled 16-May====@@");

		String retString = "<root>";
		String emailString = "";
		NodeList emailNodeList = null;
		//Added by amol s
		NodeList templateNodeList=null;
		Node emailNode = null;
		Document emailDom = null;
		Document currentPkTranDom = null;
		String to = "",cc = "",bcc = "",sub = "",body = "",mainBody="",tranId = "",attachObjLink = "",attachmentPath = "";
		String recipients="";
		String attachementArr[] = null;
		String jsonToXml = "",inlineImages = "";
		ArrayList<String> tempImageNames = null;
		FileInputStream fis = null;
		try
		{
			EMail email = new EMail();
			Document allMailDom = genericUtility.parseString(mailData);
			emailNodeList = allMailDom.getElementsByTagName("EMAILDATA");
			
			//Added by Amol S To get the value of template Code from NodeList  --start
			
			 templateNodeList = allMailDom.getElementsByTagName("TEMPLATE_CODE");
			 String templateCode = null;
			 if (templateNodeList != null && templateNodeList.getLength() > 0) {
			     Node templateNode = templateNodeList.item(0);
			     if (templateNode != null && templateNode.getFirstChild() != null) {
			         templateCode = templateNode.getFirstChild().getNodeValue().trim();
			     }
			 }
			 
				BaseLogger.log("3", userInfo,  null,"sendMail templateCode" +templateCode);

			//Added by Amol S To get the value of template Code  --End

			String imagePath = CommonConstants.APPLICATION_CONTEXT+File.separator+"temp"+File.separator;
			for(int emlCntr = 0; emlCntr < emailNodeList.getLength(); emlCntr++ )
			{
				recipients="";
				to = "";
				cc = "";
				bcc = "";
				sub = "";
				body = "";
				mainBody = ""; //Change By PriyankaC to send HTML body  in mail.
				tranId = "";
				attachObjLink =  "";
				attachmentPath = "";
				jsonToXml = "";
				inlineImages = "";
				tempImageNames = new ArrayList<String>();
				emailString = "<root>";
				emailNode = emailNodeList.item(emlCntr);
				emailDom = genericUtility.parseString(genericUtility.serializeDom(emailNode));
				if(emailDom.getElementsByTagName("TRAN_ID").item(0) != null)
				{
					if(emailDom.getElementsByTagName("TRAN_ID").item(0).getFirstChild() != null)
					{
						tranId = checkNull(emailDom.getElementsByTagName("TRAN_ID").item(0).getFirstChild().getNodeValue());
					}
				}
				if(emailDom.getElementsByTagName("TO").item(0) != null)
				{
					if(emailDom.getElementsByTagName("TO").item(0).getFirstChild() != null)
					{
						to = checkNull(emailDom.getElementsByTagName("TO").item(0).getFirstChild().getNodeValue());
					}
				}
				if(emailDom.getElementsByTagName("CC").item(0) != null)
				{
					if(emailDom.getElementsByTagName("CC").item(0).getFirstChild() != null)
					{
						cc = checkNull(emailDom.getElementsByTagName("CC").item(0).getFirstChild().getNodeValue());
					}
				}
				if(emailDom.getElementsByTagName("BCC").item(0) != null)
				{
					if(emailDom.getElementsByTagName("BCC").item(0).getFirstChild() != null)
					{
						bcc = checkNull(emailDom.getElementsByTagName("BCC").item(0).getFirstChild().getNodeValue());
					}
				}
				if(emailDom.getElementsByTagName("SUB").item(0) != null)
				{
					if(emailDom.getElementsByTagName("SUB").item(0).getFirstChild() != null)
					{
						sub = checkNull(emailDom.getElementsByTagName("SUB").item(0).getFirstChild().getNodeValue());
					}
				}
				if(emailDom.getElementsByTagName("BODY").item(0) != null)
				{
					if(emailDom.getElementsByTagName("BODY").item(0).getFirstChild() != null)
					{
						body = checkNull(emailDom.getElementsByTagName("BODY").item(0).getFirstChild().getNodeValue());
					}
				}
				if(emailDom.getElementsByTagName("ATTACHMENTS").item(0) != null)
				{
					if(emailDom.getElementsByTagName("ATTACHMENTS").item(0).getFirstChild() != null)
					{
						attachObjLink = checkNull(emailDom.getElementsByTagName("ATTACHMENTS").item(0).getFirstChild().getNodeValue());
					}
				}
				if( ( ( tranId != null ) && ( tranId.length() > 0 ) && ( tranId.substring(tranId.length()-1)).equals(":") ) )
				{
					tranId = tranId.substring(0,tranId.length()-1);
				}
				if(to.length() > 0)
				{
					emailString += "<TO_ADD><![CDATA["+to+"]]></TO_ADD>";
					recipients = recipients + " " +to;
				}
				if(cc.length() > 0)
				{
					emailString += "<CC_ADD><![CDATA["+cc+"]]></CC_ADD>";
					recipients = recipients + " " +cc;
				}
				if(bcc.length() > 0)
				{
					emailString += "<BCC_ADD><![CDATA["+bcc+"]]></BCC_ADD>";
					recipients = recipients + " " +bcc;
				}
				if(sub.length() > 0)
				{
					emailString += "<SUBJECT><![CDATA["+sub+"]]></SUBJECT>";
				}
				if(body.length() > 0)
				{
					//emailString += "<MESSAGE><![CDATA["+body+"]]></MESSAGE>";
					String findStr = "<img src=\"";
					String colFullName = "";
					boolean found = false;
					int currentIndex = 0;
					int nextSearchIndex = 0;
					String currColVal = "";
					int imageCntr = 0;
					
					while(body.indexOf(findStr,nextSearchIndex) != -1)
					{
						currColVal = "";
						imageCntr++;
						BaseLogger.log("3", userInfo,  null,nextSearchIndex);
						currentIndex = body.indexOf(findStr,nextSearchIndex);
						String firstPart = body.substring(0,currentIndex);
						String lastPart = body.substring(currentIndex,body.length());
						colFullName = lastPart.substring(0,lastPart.indexOf(">")+1);
						BaseLogger.log("3", userInfo,  null,"colFullName:"+colFullName);
						String sourceData = colFullName;
						String encodingPrefix = "base64,";
						int contentStartIndex = sourceData.indexOf(encodingPrefix) + encodingPrefix.length();
						byte[] imageData = Base64.decodeBase64(sourceData.substring(contentStartIndex));
						//CommonConstants.APPLICATION_CONTEXT + File.separator + "bin" + File.separator + "metadata" + File.separator;
						InputStream in = new ByteArrayInputStream(imageData);
						BufferedImage bImageFromConvert = ImageIO.read(in);
						BaseLogger.log("3", userInfo,  null,"inlineImagePath:"+imagePath);
						while(new File(imagePath+"image"+imageCntr+".png").exists())
						{
							imageCntr++;
						}
						tempImageNames.add("image"+imageCntr);
						ImageIO.write(bImageFromConvert, "png", new File(imagePath+"image"+imageCntr+".png"));	
						inlineImages = inlineImages + "<image"+imageCntr+"><![CDATA["+imagePath+"image"+imageCntr+".png"+"]]></image"+imageCntr+">";
						currColVal = "<img   src=\"cid:image"+imageCntr+"\">";
						body = firstPart + lastPart.replaceFirst(colFullName.replace("+", "\\+"), currColVal);
						nextSearchIndex = currentIndex+currColVal.length();
						in.close();
					}
					//emailString += "<INLINE_IMAGES>"+inlineImages+"</INLINE_IMAGES>";
					   mainBody =  body;
					   BaseLogger.log("3", userInfo,  null,"mainBody : " +mainBody);//Change By PriyankaC to send HTML body  in mail.
					//emailString += "<MESSAGE><![CDATA["+body+"]]></MESSAGE>";
				}
				if(attachObjLink.length() > 0)
				{
					if((attachObjLink.substring(attachObjLink.length()-1)).equals(","))
					{
						attachObjLink = attachObjLink.substring(0,attachObjLink.length()-1);
						if(jsonTranData == null || jsonTranData.equalsIgnoreCase("null") || jsonTranData.length() <= 0)
						{
							currentPkTranDom = getCurrentTranDom(tranId, userInfo, objName);
						}
						else
						{
							JSONObject jsonObject = new JSONObject(jsonTranData);
							JSONObject childJson = new JSONObject(jsonObject.get(tranId).toString());
							BaseLogger.log("3", userInfo,  null,childJson);
							jsonToXml = XML.toString(childJson);
							BaseLogger.log("3", userInfo,  null,jsonToXml);
							currentPkTranDom = genericUtility.parseString("<Detail1>"+jsonToXml+"</Detail1>");
						}
						attachementArr = attachObjLink.split(",");
						BaseLogger.log("3", userInfo,  null,"attachementArr.. " +attachementArr);
						for(int i = 0; i < attachementArr.length; i++)
						{
						   //Change By PriyankaC to send HTML body  in mail.[START]
							String[] linkParts = attachementArr[i].split("~");
						    String  attachLinks = linkParts[0]; 
							String attachType = linkParts[1];
							BaseLogger.log("3", userInfo,  null,"attachLinks.1 " +attachType +"attachLinks.2 "+attachLinks);
							if("B".equalsIgnoreCase(attachType))
							{
								String bodyAttchPath  = getAttachmentPath(objName,attachLinks,userInfo,currentPkTranDom,tranId,"html"); //Change By PriyankaC to send selected type of attachment  in mail.
								BaseLogger.log("3", userInfo,  null,"bodyAttchPath :"+bodyAttchPath);
								//reading file html from path
								String htmlContent = readFile(bodyAttchPath);
								mainBody = 	 mainBody + htmlContent;
								BaseLogger.log("3", userInfo,  null,"mainBody :"+mainBody);
							}
							else
							{
							attachmentPath = attachmentPath + getAttachmentPath(objName,attachLinks,userInfo,currentPkTranDom,tranId,"pdf")+";"; //Change By PriyankaC to send selected type of attachment  in mail.
							}
						}
						BaseLogger.log("3", userInfo,  null,"Attachment Path:"+attachmentPath);
						
						//Change By PriyankaC to send HTML body  in mail.[END]
					}
					emailString += "<EMAIL_TYPE><![CDATA[page]]></EMAIL_TYPE>";
					if(attachmentPath != null & attachmentPath.trim().length()>0)
					{
						emailString += "<XML_DATA_FILE><![CDATA["+attachmentPath+"]]></XML_DATA_FILE>";
					}
					
				}
				//Samadhan for inlineImages
				emailString += "<INLINE_IMAGES>"+inlineImages+"</INLINE_IMAGES>";
				
				emailString += "<MESSAGE><![CDATA["+mainBody+"]]></MESSAGE>"; //Change By PriyankaC to send HTML body  in mail.

				
				emailString += "<MESSAGE_TYPE><![CDATA[text/html]]></MESSAGE_TYPE>";
				emailString += "<OBJ_NAME><![CDATA[" + objName + "]]></OBJ_NAME>";
				emailString += "<REF_ID><![CDATA[" + tranId + "]]></REF_ID>";
				
				//added by amol s to append the value of template code to the emailstring -start
				emailString += "<TEMPLATE_CODE><![CDATA[" + templateCode + "]]></TEMPLATE_CODE>";
				//added by amol s to append the value of template code to the emailstring -End

				emailString += "</root>";
				BaseLogger.log("3", userInfo,  null,"emailString::@@"+emailString);
			    BaseLogger.log("3", null, null, "To:: " + to);
			    BaseLogger.log("3", null, null, "templateCode::==> " + cc);
			    BaseLogger.log("3", null, null, "BCC: " + bcc);
			    BaseLogger.log("3", null, null, "retString==>" + retString);
			    

				retString += "<MAIL><TRAN_ID>"+tranId+"</TRAN_ID>";
				if(to.length() > 0 || cc.length() > 0 || bcc.length() > 0)
				{
				    BaseLogger.log("3", null, null, "Inside the if block to test:::");

					String status = "";
					String failedReason = "";
					
					try
					{
					    BaseLogger.log("3", null, null, "Inside the TRY ==>");
						status = email.sendMail(emailString, null, userInfo);
					    BaseLogger.log("3", null, null, "Inside the METHOD CALLED ==>");

					}
					catch(Exception e)
					{
						e.printStackTrace();
						status = "N";
						failedReason = e.getMessage();
					}
					retString += "<STATUS>"+status+"</STATUS>";
					retString += "<FAILED_REASON>"+failedReason+"</FAILED_REASON>";
					if(recipients.substring(recipients.length()-1).equals(","))
					{
						recipients = recipients.substring(0, recipients.length()-1);
					}
					retString += "<RECIPIENTS>"+recipients+"</RECIPIENTS>";
				}
				else
				{
					retString += "<FAILED_REASON><![CDATA[NO_RECIPIENTS]]></FAILED_REASON>";
					retString += "<RECIPIENTS><![CDATA[NO_RECIPIENTS]]></RECIPIENTS>";
					retString += "<STATUS>N</STATUS>";
				}
				retString += "</MAIL>";
				for (String fileName : tempImageNames) 
				{
					if(new File(imagePath+fileName+".png").exists())
					{
						BaseLogger.log("3", userInfo,  null,"tempImagePathForDelete:"+imagePath);
						BaseLogger.log("3", userInfo,  null,"tempImageNameForDelete:"+fileName);
						new File(imagePath+fileName+".png").delete();
					}
				}
			}
			
		}catch(Exception e)
		{
			throw new ITMException(e);
		}
		
		finally
		{
			try {
				if (fis != null)
					fis.close();
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		retString += "</root>";
		return retString;
	}

	
	
	//Added overriden method including the transaction xml in the method paramter arguments by Ajit on 12-Jan-26 [Start]
	public String sendMail(String objName, UserInfoBean userInfo,String mailData, String jsonTranData, String tranXmlString)throws ITMException
	{
		
		BaseLogger.log("3", userInfo,  null,"sendMail Method callled 16-May====@@");
		BaseLogger.log("3", userInfo,  null,"tranXmlString:: "+tranXmlString );

		String retString = "<root>";
		String emailString = "";
		NodeList emailNodeList = null;
		//Added by amol s
		NodeList templateNodeList=null;
		Node emailNode = null;
		Document emailDom = null;
		Document currentPkTranDom = null;
		String to = "",cc = "",bcc = "",sub = "",body = "",mainBody="",tranId = "",attachObjLink = "",attachmentPath = "";
		String recipients="";
		String attachementArr[] = null;
		String jsonToXml = "",inlineImages = "";
		ArrayList<String> tempImageNames = null;
		FileInputStream fis = null;
		try
		{
			EMail email = new EMail();
			Document allMailDom = genericUtility.parseString(mailData);
			emailNodeList = allMailDom.getElementsByTagName("EMAILDATA");
			
			//Added by Amol S To get the value of template Code from NodeList  --start
			
			 templateNodeList = allMailDom.getElementsByTagName("TEMPLATE_CODE");
			 String templateCode = null;
			 if (templateNodeList != null && templateNodeList.getLength() > 0) {
			     Node templateNode = templateNodeList.item(0);
			     if (templateNode != null && templateNode.getFirstChild() != null) {
			         templateCode = templateNode.getFirstChild().getNodeValue().trim();
			     }
			 }
			 
				BaseLogger.log("3", userInfo,  null,"sendMail templateCode" +templateCode);

			//Added by Amol S To get the value of template Code  --End

			String imagePath = CommonConstants.APPLICATION_CONTEXT+File.separator+"temp"+File.separator;
			for(int emlCntr = 0; emlCntr < emailNodeList.getLength(); emlCntr++ )
			{
				recipients="";
				to = "";
				cc = "";
				bcc = "";
				sub = "";
				body = "";
				mainBody = ""; //Change By PriyankaC to send HTML body  in mail.
				tranId = "";
				attachObjLink =  "";
				attachmentPath = "";
				jsonToXml = "";
				inlineImages = "";
				tempImageNames = new ArrayList<String>();
				emailString = "<root>";
				emailNode = emailNodeList.item(emlCntr);
				emailDom = genericUtility.parseString(genericUtility.serializeDom(emailNode));
				if(emailDom.getElementsByTagName("TRAN_ID").item(0) != null)
				{
					if(emailDom.getElementsByTagName("TRAN_ID").item(0).getFirstChild() != null)
					{
						tranId = checkNull(emailDom.getElementsByTagName("TRAN_ID").item(0).getFirstChild().getNodeValue());
					}
				}
				if(emailDom.getElementsByTagName("TO").item(0) != null)
				{
					if(emailDom.getElementsByTagName("TO").item(0).getFirstChild() != null)
					{
						to = checkNull(emailDom.getElementsByTagName("TO").item(0).getFirstChild().getNodeValue());
					}
				}
				if(emailDom.getElementsByTagName("CC").item(0) != null)
				{
					if(emailDom.getElementsByTagName("CC").item(0).getFirstChild() != null)
					{
						cc = checkNull(emailDom.getElementsByTagName("CC").item(0).getFirstChild().getNodeValue());
					}
				}
				if(emailDom.getElementsByTagName("BCC").item(0) != null)
				{
					if(emailDom.getElementsByTagName("BCC").item(0).getFirstChild() != null)
					{
						bcc = checkNull(emailDom.getElementsByTagName("BCC").item(0).getFirstChild().getNodeValue());
					}
				}
				if(emailDom.getElementsByTagName("SUB").item(0) != null)
				{
					if(emailDom.getElementsByTagName("SUB").item(0).getFirstChild() != null)
					{
						sub = checkNull(emailDom.getElementsByTagName("SUB").item(0).getFirstChild().getNodeValue());
					}
				}
				if(emailDom.getElementsByTagName("BODY").item(0) != null)
				{
					if(emailDom.getElementsByTagName("BODY").item(0).getFirstChild() != null)
					{
						body = checkNull(emailDom.getElementsByTagName("BODY").item(0).getFirstChild().getNodeValue());
					}
				}
				if(emailDom.getElementsByTagName("ATTACHMENTS").item(0) != null)
				{
					if(emailDom.getElementsByTagName("ATTACHMENTS").item(0).getFirstChild() != null)
					{
						attachObjLink = checkNull(emailDom.getElementsByTagName("ATTACHMENTS").item(0).getFirstChild().getNodeValue());
					}
				}
				if( ( ( tranId != null ) && ( tranId.length() > 0 ) && ( tranId.substring(tranId.length()-1)).equals(":") ) )
				{
					tranId = tranId.substring(0,tranId.length()-1);
				}
				if(to.length() > 0)
				{
					emailString += "<TO_ADD><![CDATA["+to+"]]></TO_ADD>";
					recipients = recipients + " " +to;
				}
				if(cc.length() > 0)
				{
					emailString += "<CC_ADD><![CDATA["+cc+"]]></CC_ADD>";
					recipients = recipients + " " +cc;
				}
				if(bcc.length() > 0)
				{
					emailString += "<BCC_ADD><![CDATA["+bcc+"]]></BCC_ADD>";
					recipients = recipients + " " +bcc;
				}
				if(sub.length() > 0)
				{
					emailString += "<SUBJECT><![CDATA["+sub+"]]></SUBJECT>";
				}
				if(body.length() > 0)
				{
					//emailString += "<MESSAGE><![CDATA["+body+"]]></MESSAGE>";
					String findStr = "<img src=\"";
					String colFullName = "";
					boolean found = false;
					int currentIndex = 0;
					int nextSearchIndex = 0;
					String currColVal = "";
					int imageCntr = 0;
					
					while(body.indexOf(findStr,nextSearchIndex) != -1)
					{
						currColVal = "";
						imageCntr++;
						BaseLogger.log("3", userInfo,  null,nextSearchIndex);
						currentIndex = body.indexOf(findStr,nextSearchIndex);
						String firstPart = body.substring(0,currentIndex);
						String lastPart = body.substring(currentIndex,body.length());
						colFullName = lastPart.substring(0,lastPart.indexOf(">")+1);
						BaseLogger.log("3", userInfo,  null,"colFullName:"+colFullName);
						String sourceData = colFullName;
						String encodingPrefix = "base64,";
						int contentStartIndex = sourceData.indexOf(encodingPrefix) + encodingPrefix.length();
						byte[] imageData = Base64.decodeBase64(sourceData.substring(contentStartIndex));
						//CommonConstants.APPLICATION_CONTEXT + File.separator + "bin" + File.separator + "metadata" + File.separator;
						InputStream in = new ByteArrayInputStream(imageData);
						BufferedImage bImageFromConvert = ImageIO.read(in);
						BaseLogger.log("3", userInfo,  null,"inlineImagePath:"+imagePath);
						while(new File(imagePath+"image"+imageCntr+".png").exists())
						{
							imageCntr++;
						}
						tempImageNames.add("image"+imageCntr);
						ImageIO.write(bImageFromConvert, "png", new File(imagePath+"image"+imageCntr+".png"));	
						inlineImages = inlineImages + "<image"+imageCntr+"><![CDATA["+imagePath+"image"+imageCntr+".png"+"]]></image"+imageCntr+">";
						currColVal = "<img   src=\"cid:image"+imageCntr+"\">";
						body = firstPart + lastPart.replaceFirst(colFullName.replace("+", "\\+"), currColVal);
						nextSearchIndex = currentIndex+currColVal.length();
						in.close();
					}
					//emailString += "<INLINE_IMAGES>"+inlineImages+"</INLINE_IMAGES>";
					   mainBody =  body;
					   BaseLogger.log("3", userInfo,  null,"mainBody : " +mainBody);//Change By PriyankaC to send HTML body  in mail.
					//emailString += "<MESSAGE><![CDATA["+body+"]]></MESSAGE>";
				}
				if(attachObjLink.length() > 0)
				{
					if((attachObjLink.substring(attachObjLink.length()-1)).equals(","))
					{
						attachObjLink = attachObjLink.substring(0,attachObjLink.length()-1);
						if(jsonTranData == null || jsonTranData.equalsIgnoreCase("null") || jsonTranData.length() <= 0)
						{
							currentPkTranDom = getCurrentTranDom(tranId, userInfo, objName);
						}
						else
						{
							JSONObject jsonObject = new JSONObject(jsonTranData);
							JSONObject childJson = new JSONObject(jsonObject.get(tranId).toString());
							BaseLogger.log("3", userInfo,  null,childJson);
							jsonToXml = XML.toString(childJson);
							BaseLogger.log("3", userInfo,  null,jsonToXml);
							currentPkTranDom = genericUtility.parseString("<Detail1>"+jsonToXml+"</Detail1>");
						}
						attachementArr = attachObjLink.split(",");
						BaseLogger.log("3", userInfo,  null,"attachementArr.. " +attachementArr);
						for(int i = 0; i < attachementArr.length; i++)
						{
						   //Change By PriyankaC to send HTML body  in mail.[START]
							String[] linkParts = attachementArr[i].split("~");
						    String  attachLinks = linkParts[0]; 
							String attachType = linkParts[1];
							BaseLogger.log("3", userInfo,  null,"attachLinks.1 " +attachType +"attachLinks.2 "+attachLinks);
							if("B".equalsIgnoreCase(attachType))
							{
								String bodyAttchPath  = getAttachmentPath(objName,attachLinks,userInfo,currentPkTranDom,tranId,"html"); //Change By PriyankaC to send selected type of attachment  in mail.
								BaseLogger.log("3", userInfo,  null,"bodyAttchPath :"+bodyAttchPath);
								//reading file html from path
								String htmlContent = readFile(bodyAttchPath);
								mainBody = 	 mainBody + htmlContent;
								BaseLogger.log("3", userInfo,  null,"mainBody :"+mainBody);
							}
							else
							{
							attachmentPath = attachmentPath + getAttachmentPath(objName,attachLinks,userInfo,currentPkTranDom,tranId,"pdf")+";"; //Change By PriyankaC to send selected type of attachment  in mail.
							}
						}
						BaseLogger.log("3", userInfo,  null,"Attachment Path:"+attachmentPath);
						
						//Change By PriyankaC to send HTML body  in mail.[END]
					}
					emailString += "<EMAIL_TYPE><![CDATA[page]]></EMAIL_TYPE>";
					if(attachmentPath != null & attachmentPath.trim().length()>0)
					{
						emailString += "<XML_DATA_FILE><![CDATA["+attachmentPath+"]]></XML_DATA_FILE>";
					}
					
				}
				//Samadhan for inlineImages
				emailString += "<INLINE_IMAGES>"+inlineImages+"</INLINE_IMAGES>";
				
				emailString += "<MESSAGE><![CDATA["+mainBody+"]]></MESSAGE>"; //Change By PriyankaC to send HTML body  in mail.

				
				emailString += "<MESSAGE_TYPE><![CDATA[text/html]]></MESSAGE_TYPE>";
				emailString += "<OBJ_NAME><![CDATA[" + objName + "]]></OBJ_NAME>";
				emailString += "<REF_ID><![CDATA[" + tranId + "]]></REF_ID>";
				
				//added by amol s to append the value of template code to the emailstring -start
				emailString += "<TEMPLATE_CODE><![CDATA[" + templateCode + "]]></TEMPLATE_CODE>";
				//added by amol s to append the value of template code to the emailstring -End

				emailString += "</root>";
				BaseLogger.log("3", userInfo,  null,"emailString::@@"+emailString);
			    BaseLogger.log("3", null, null, "To:: " + to);
			    BaseLogger.log("3", null, null, "templateCode::==> " + cc);
			    BaseLogger.log("3", null, null, "BCC: " + bcc);
			    BaseLogger.log("3", null, null, "retString==>" + retString);
			    

				retString += "<MAIL><TRAN_ID>"+tranId+"</TRAN_ID>";
				if(to.length() > 0 || cc.length() > 0 || bcc.length() > 0)
				{
				    BaseLogger.log("3", null, null, "Inside the if block to test:::");

					String status = "";
					String failedReason = "";
					
					try
					{
					    BaseLogger.log("3", null, null, "Inside the TRY ==>:: "+tranXmlString);
					    
						//status = email.sendMail(emailString, null, userInfo );
					    //Changes done by Ajit to pass the transaction xml to EMail.sendMail() method on 12-Jan.
						status = email.sendMail(emailString, null, userInfo, tranXmlString );
					    BaseLogger.log("3", null, null, "Inside the METHOD CALLED ==>");

					}
					catch(Exception e)
					{
						e.printStackTrace();
						status = "N";
						failedReason = e.getMessage();
					}
					retString += "<STATUS>"+status+"</STATUS>";
					retString += "<FAILED_REASON>"+failedReason+"</FAILED_REASON>";
					if(recipients.substring(recipients.length()-1).equals(","))
					{
						recipients = recipients.substring(0, recipients.length()-1);
					}
					retString += "<RECIPIENTS>"+recipients+"</RECIPIENTS>";
				}
				else
				{
					retString += "<FAILED_REASON><![CDATA[NO_RECIPIENTS]]></FAILED_REASON>";
					retString += "<RECIPIENTS><![CDATA[NO_RECIPIENTS]]></RECIPIENTS>";
					retString += "<STATUS>N</STATUS>";
				}
				retString += "</MAIL>";
				for (String fileName : tempImageNames) 
				{
					if(new File(imagePath+fileName+".png").exists())
					{
						BaseLogger.log("3", userInfo,  null,"tempImagePathForDelete:"+imagePath);
						BaseLogger.log("3", userInfo,  null,"tempImageNameForDelete:"+fileName);
						new File(imagePath+fileName+".png").delete();
					}
				}
			}
			
		}catch(Exception e)
		{
			throw new ITMException(e);
		}
		
		finally
		{
			try {
				if (fis != null)
					fis.close();
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		retString += "</root>";
		return retString;
	}
	//Added overriden method including the transaction xml in the method paramter arguments by Ajit on 12-Jan-26 [Start]
	
	private String getEmailAddress(String emailAddrFlds, Document tranDom, UserInfoBean userInfo ) throws ITMException 
	{
		String emailAddress = "";
		NodeList detailNodeList = null;
		Node detailNode = null;
		Document detailDom = null;
		String emailAddrFldArr[] = emailAddrFlds.split(",");
		String currentAddrFld = "";
		String currentAddrVal = "";
		String currentAddrFldFull = "";
		String findStr = "<Detail1.";
		String entityType = "";
		try
		{
			detailNodeList = tranDom.getElementsByTagName("Detail1");
			detailNode = detailNodeList.item(0);
			detailDom = genericUtility.parseString(genericUtility.serializeDom(detailNode));
			
			for(int pkCntr = 0; pkCntr < emailAddrFldArr.length; pkCntr++ )
			{
				currentAddrVal="";
				currentAddrFldFull = emailAddrFldArr[pkCntr];
				if(currentAddrFldFull.startsWith(findStr))
				{
					currentAddrFld = currentAddrFldFull.substring(findStr.length(),currentAddrFldFull.lastIndexOf(">"));
					BaseLogger.log("3", userInfo,  null,currentAddrFld);
					if(detailDom.getElementsByTagName(currentAddrFld).item(0) != null)
					{
						if(detailDom.getElementsByTagName(currentAddrFld).item(0).getFirstChild() != null)
						{
							currentAddrVal = detailDom.getElementsByTagName(currentAddrFld).item(0).getFirstChild().getNodeValue();
						}
					}

				}
				else
				{
					if(currentAddrFldFull.startsWith("{"))
					{
						entityType = "";
						if (currentAddrFldFull.charAt(1) == '(' )
						{
							entityType = currentAddrFldFull.substring(currentAddrFldFull.indexOf("(")+1, currentAddrFldFull.indexOf(")"));
							currentAddrFld = currentAddrFldFull.substring(currentAddrFldFull.indexOf(")")+1, currentAddrFldFull.indexOf("}"));
							currentAddrVal = getAddressValue(entityType,currentAddrFld,tranDom, userInfo);
						}		
					}
					else
					{
						currentAddrVal = currentAddrFldFull;
					}
				}
				if(currentAddrVal != null && currentAddrVal.length()>0)
				{
					emailAddress = emailAddress + currentAddrVal +",";
				}
			}
		}catch(Exception e)
		{
			throw new ITMException(e);
		}
		return emailAddress;	
	}
	private String getAddressValue(String entityType, String argName, Document tranDom, UserInfoBean userInfo) throws ITMException 
	{
		String retEmailAddr = "";
		NodeList detailNodeList = null;
		Node detailNode = null;
		Document detailDom = null;
		String whereFieldValue = "";
		try
		{
			String masterTable = null;
			String whereFieldName = null;
			String selFieldName = null;
			AppConnectParm appConnect = new AppConnectParm();
			InitialContext ctx = new InitialContext(appConnect.getProperty());
			//DBAccessRemote dbAccess =(DBAccessRemote)ctx.lookup("ibase/DBAccessEJB/remote");
			DBAccessEJB dbAccess = new DBAccessEJB();
			if (entityType.equalsIgnoreCase("C"))
			{
				masterTable = "CUSTOMER";
				whereFieldName = "CUST_CODE";
				selFieldName = "EMAIL_ADDR";
			}
			else if (entityType.equalsIgnoreCase("S"))
			{
				masterTable = "SUPPLIER";
				whereFieldName = "SUPP_CODE";
				selFieldName = "EMAIL_ADDR";
			}
			else if (entityType.equalsIgnoreCase("E"))
			{
				masterTable = "EMPLOYEE";
				whereFieldName = "EMP_CODE";
				selFieldName = "EMAIL_ID_OFF";
			}
			else if (entityType.equalsIgnoreCase("P"))
			{
				masterTable = "SALES_PERS";
				whereFieldName = "SALES_PERS";
				selFieldName = "EMAIL_ADDR";
			}
			else if (entityType.equalsIgnoreCase("T"))
			{
				masterTable = "TRANSPORTER";
				whereFieldName = "TRAN_CODE";
				selFieldName = "EMAIL_ADDR";
			}
			else if (entityType.equalsIgnoreCase("I"))
			{
				masterTable = "SITE";
				whereFieldName = "SITE_CODE";
				selFieldName = "EMAIL_ADDR";
			}
			
			detailNodeList = tranDom.getElementsByTagName("Detail1");
			detailNode = detailNodeList.item(0);
			detailDom = genericUtility.parseString(genericUtility.serializeDom(detailNode));
			BaseLogger.log("3", userInfo,  null,"genericUtility.serializeDom(detailDom):"+genericUtility.serializeDom(detailDom));
			BaseLogger.log("3", userInfo,  null,"AgrName:"+argName);
			if(detailDom.getElementsByTagName(argName) != null) 
			{
				if(detailDom.getElementsByTagName(argName).item(0) != null)
				{
					if(detailDom.getElementsByTagName(argName).item(0).getFirstChild() != null)
					{
						whereFieldValue = detailDom.getElementsByTagName(argName).item(0).getFirstChild().getNodeValue();
					}
				}
			}
			BaseLogger.log("3", userInfo,  null,"masterTable:"+masterTable+" \nwhereFieldName:"+whereFieldName+" \nselFieldName"+selFieldName+" \nwhereFieldValue:"+whereFieldValue);
			retEmailAddr = dbAccess.getEmailAddr(selFieldName, masterTable, whereFieldName, whereFieldValue, userInfo);
			dbAccess = null;
		}
		catch(Exception e)
		{
			throw new ITMException(e);
		}
		return retEmailAddr;
	}
	private String getFormatedEmailBody(String bodyTextData, Document tranDom ) throws ITMException 
	{
		NodeList detailNodeList = null;
		Node detailNode = null;
		Document detailDom = null;
		String findStr = "&lt;Detail1.";
		String colFullName = "";
		String colName="";
		String currColVal = "";
		int currentIndex = 0;
		int nextSearchIndex = 0;
		try
		{
			detailNodeList = tranDom.getElementsByTagName("Detail1");
			if(bodyTextData != null)
			{
				detailNode = detailNodeList.item(0);
				detailDom = genericUtility.parseString(genericUtility.serializeDom(detailNode));
				
				while(bodyTextData.indexOf(findStr,nextSearchIndex) != -1)
				{
					BaseLogger.log("3", null,  null,nextSearchIndex);
					currColVal = "";
					currentIndex = bodyTextData.indexOf(findStr,nextSearchIndex);
					String firstPart = bodyTextData.substring(0,currentIndex);
					String lastPart = bodyTextData.substring(currentIndex,bodyTextData.length());
					colFullName = lastPart.substring(0,lastPart.indexOf("&gt;")+4);
					BaseLogger.log("3", null,  null,"colFullName:"+colFullName);
					
					colName = colFullName.substring(findStr.length(),colFullName.lastIndexOf("&gt;"));
					BaseLogger.log("3", null,  null,"colName:"+colName);
					
					if(detailDom.getElementsByTagName(colName).item(0) != null)
					{
						if(detailDom.getElementsByTagName(colName).item(0).getFirstChild() != null)
						{
							currColVal = detailDom.getElementsByTagName(colName).item(0).getFirstChild().getNodeValue();
						}
					}
					bodyTextData = firstPart + lastPart.replaceFirst(colFullName, currColVal);
					nextSearchIndex = currentIndex+currColVal.length();
					BaseLogger.log("3", null,  null,"bodyTextData"+bodyTextData);
				}
			}
		}catch(Exception e)
		{
			throw new ITMException(e);
		}
		return bodyTextData;	
	}
	
	private String getFormatedEmailSub(String subTextData, Document tranDom ) throws ITMException 
	{
		NodeList detailNodeList = null;
		Node detailNode = null;
		Document detailDom = null;
		String findStr = "<Detail1.";
		String colFullName = "";
		String colName="";
		String currColVal = "";
		int currentIndex = 0;
		int nextSearchIndex = 0;
		try
		{
			detailNodeList = tranDom.getElementsByTagName("Detail1");
			if(subTextData != null)
			{
				detailNode = detailNodeList.item(0);
				detailDom = genericUtility.parseString(genericUtility.serializeDom(detailNode));
				while(subTextData.indexOf(findStr,nextSearchIndex) != -1)
				{
					BaseLogger.log("3", null,  null,nextSearchIndex);
					currColVal = "";
					currentIndex = subTextData.indexOf(findStr,nextSearchIndex);
					String firstPart = subTextData.substring(0,currentIndex);
					String lastPart = subTextData.substring(currentIndex,subTextData.length());
					colFullName = lastPart.substring(0,lastPart.indexOf(">")+1);
					BaseLogger.log("3", null,  null,"colFullName:"+colFullName);
					colName = colFullName.substring(findStr.length(),colFullName.lastIndexOf(">"));
					BaseLogger.log("3", null,  null,"colName:"+colName);
					if(detailDom.getElementsByTagName(colName).item(0) != null)
					{
						if(detailDom.getElementsByTagName(colName).item(0).getFirstChild() != null)
						{
							currColVal = detailDom.getElementsByTagName(colName).item(0).getFirstChild().getNodeValue();
						}
					}
					subTextData = firstPart + lastPart.replaceFirst(colFullName, currColVal);
					nextSearchIndex = currentIndex+currColVal.length();
					BaseLogger.log("3", null,  null,"SubTextData"+subTextData);
				}
			}
		}catch(Exception e)
		{
			throw new ITMException(e);
		}
		return subTextData;	
	}
	
	private Document getCurrentTranDom(String pkValues, UserInfoBean userInfo, String objName ) throws ITMException
	{
		String tranXml = "";
		try 
		{
			//MasterDataRemote mDataRem = ( MasterDataRemote )getInitialContext().lookup( "ibase/MasterDataEJB/remote" );
			MasterDataEJB masterDataEJB = new MasterDataEJB();
			tranXml = masterDataEJB.getXMLFromDBForBrow(objName, "1", "2", pkValues, null, null, userInfo);
			masterDataEJB = null;
		}
		catch (Exception e) 
		{	
			e.printStackTrace();
			throw new ITMException(e);
		}
		return genericUtility.parseString(tranXml);
	}
	
	@Override
	public String getSelectedEmailXmlData(String objName, UserInfoBean userInfo, String formatCode, String jsonTranData, String calledFrom) throws ITMException 
	{
		BaseLogger.log("2", userInfo,  null,"[TransactionEmailTempltEJB:getSelectedEmailXmlData]Getting "
				+ "selected Email Template .....[" + calledFrom +"]"); //$NON-NLS-1$
		Connection connection = null;
		PreparedStatement stmt = null;
		ResultSet rs = null;
		String retXmlData = "<Document>"; 
		String colNameString = "";
		try
		{
			connection = getConnection(userInfo);
			String selectQuery = "SELECT FORMAT_CODE, SEND_TO, COPY_TO, BLIND_COPY, SUBJECT, BODY_TEXT, MAIL_DESCR,ATTACH_TEXT,ATTACH_TYPE,USER_ID__OWN FROM MAIL_FORMAT WHERE FORMAT_CODE = ?"; 
			stmt = connection.prepareStatement(selectQuery);
			stmt.setString(1, formatCode);
			rs = stmt.executeQuery();
					
			//Samadhan
			//colNameString = getPopHelpData(objName, userInfo,"2","1","MAILADDR");
			
			/* Changes by Gagan B. on 09-SEP-24 -- START
			Created new jsp EmailTemplate.jsp which will be used to save Email Template in MAIL_FORMAT.
			 Backend Servlets used are same as TransactionEmailTemplate.jsp 
			 -- RIARequestHandlerServlet: GET_EMAIL_TEMPLATE
			 Added additional parameter: CALLED_FROM to distuingish the call between EmailTemplate.jsp and TransactionEmailTemplate.jsp
			 */
			if (!E12GenericUtility.checkNull(calledFrom).equals("EMAIL_TEMPLATE")) {
				colNameString = getPopHelpData(objName, userInfo,"2","1","MAILADDR", jsonTranData);
				
			}
			
			BaseLogger.log("2", userInfo,  null,"[TransactionEmailTempltEJB:getSelectedEmailXmlData] colNameString..... +[" + colNameString + "]"); //$NON-NLS-1$

			lastDyanInpCol = 1;
			lastDyanSubInpCol = 1;
			while(rs.next())
			{
				retXmlData += "<FORMAT_CODE><![CDATA["+checkNull(rs.getString("FORMAT_CODE"))+"]]></FORMAT_CODE>";
				
				if (E12GenericUtility.checkNull(calledFrom).equals("EMAIL_TEMPLATE")) {
					BaseLogger.log("2", userInfo,  null,"Called from Email Template"); //$NON-NLS-1$
					
					/*
					 * Changes by Gagan B. on 08-OCT-24 to upload HTML to alfresco server in MAIL_FORMAT 
					 * object and store the doc ID in MAIL_FORMAT.BODY_TEXT -- START
					 * */
					String getDocumentURL = CommonConstants.TOMCAT_HOME + 
							"/ibase/rest/E12ExtService/getDocumentStream";
					
					Unirest.setTimeouts(0, 0);
					HttpResponse<String> getDocumentResponse = Unirest.post(getDocumentURL)
							   .header("TOKEN_ID", userInfo.getTokenID())
							   .field("DOC_ID", checkNull(rs.getString("BODY_TEXT")))
							   .asString();
					
					String statusText = getDocumentResponse.getStatusText();
					int statusCode = getDocumentResponse.getStatus();
					String responseString = getDocumentResponse.getBody().toString();
					
					BaseLogger.log("3", null, null, "Inside saveNewEmailTemplate getSelectedEmailXmlData [" + statusText + "]");
					BaseLogger.log("3", null, null, "Inside saveNewEmailTemplate getSelectedEmailXmlData [" + statusCode + "]");
					BaseLogger.log("3", null, null, "Inside saveNewEmailTemplate getSelectedEmailXmlData [" + responseString + "]");
					
					// Added by Gagan B. on 01-OCT-24 method to read the content of HTML file and return that from servlet response.
//					String bodyText = readHtmlFile(checkNull(rs.getString("BODY_TEXT")));
					String bodyText = responseString;
					/*
					 * Changes by Gagan B. on 08-OCT-24 to upload HTML to alfresco server in MAIL_FORMAT 
					 * object and store the doc ID in MAIL_FORMAT.BODY_TEXT -- END
					 * */
					
					retXmlData += "<SEND_TO><ADDRESS_FLD><COL_LABLE><![CDATA["+checkNull(rs.getString("SEND_TO"))+"]]></COL_LABLE></ADDRESS_FLD></SEND_TO>";
					retXmlData += "<COPY_TO><ADDRESS_FLD><COL_LABLE><![CDATA["+checkNull(rs.getString("COPY_TO"))+"]]></COL_LABLE></ADDRESS_FLD></COPY_TO>";
					retXmlData += "<BLIND_COPY><ADDRESS_FLD><COL_LABLE><![CDATA["+checkNull(rs.getString("BLIND_COPY"))+"]]></COL_LABLE></ADDRESS_FLD></BLIND_COPY>";
					retXmlData += "<SUBJECT><![CDATA["+checkNull(rs.getString("SUBJECT"))+"]]></SUBJECT>";
					retXmlData += "<BODY_TEXT><![CDATA["+checkNull(bodyText)+"]]></BODY_TEXT>";
					
					
				} else {
					retXmlData += "<SEND_TO>"+getColumnLableData(checkNull(rs.getString("SEND_TO")),colNameString)+"</SEND_TO>";
					retXmlData += "<COPY_TO>"+getColumnLableData(checkNull(rs.getString("COPY_TO")),colNameString)+"</COPY_TO>";
					retXmlData += "<BLIND_COPY>"+getColumnLableData(checkNull(rs.getString("BLIND_COPY")),colNameString)+"</BLIND_COPY>";
					retXmlData += "<SUBJECT><![CDATA["+getHtmlSubText(checkNull(rs.getString("SUBJECT")),colNameString)+"]]></SUBJECT>";
					retXmlData += "<BODY_TEXT><![CDATA["+getHtmlBodyText(checkNull(rs.getString("BODY_TEXT")),colNameString)+"]]></BODY_TEXT>";
				}
				/* Changes by Gagan B. on 09-SEP-24 -- END
				Created new jsp EmailTemplate.jsp which will be used to save Email Template in MAIL_FORMAT.
				 Backend Servlets used are same as TransactionEmailTemplate.jsp 
				 -- RIARequestHandlerServlet: GET_EMAIL_TEMPLATE
				 Added additional parameter: CALLED_FROM to distuingish the call between EmailTemplate.jsp and TransactionEmailTemplate.jsp
				 */
				retXmlData += "<LAST_DYNAMIC_SUB_CNT><![CDATA["+lastDyanSubInpCol+"]]></LAST_DYNAMIC_SUB_CNT>";
				retXmlData += "<LAST_DYNAMIC_CNT><![CDATA["+lastDyanInpCol+"]]></LAST_DYNAMIC_CNT>";
				retXmlData += "<MAIL_DESCR><![CDATA["+checkNull(rs.getString("MAIL_DESCR"))+"]]></MAIL_DESCR>";
				//Change By PriyankaC to send HTML body  in mail [START].
				String attachText = checkNull(rs.getString("ATTACH_TEXT"));
				String attchTextNew = "";
				if(attachText != null && attachText.length() > 0)
				{
					if(attachText.contains("~"))
					{
						attchTextNew = attachText;
					}
					else
					{
						if((attachText.substring(attachText.length()-1)).equals(","))
						{
								attachText = attachText.substring(0,attachText.length()-1);
						}
						String attacheText[] = attachText.split(",");
						for(int attachCnt = 0; attachCnt < attacheText.length ;attachCnt++)
						{
							attchTextNew = attacheText[attachCnt] + "~A" +",";
							
						}
					}
				}
			    retXmlData += "<ATTACHMENTS><![CDATA["+getAttachmentsHtml(attchTextNew,objName,userInfo)+"]]></ATTACHMENTS>";//change by PriyankaC on 20Dec2017.
			  //Change By PriyankaC to send HTML body  in mail [END].
			    //retXmlData += "<ATTACHMENTS><![CDATA["+getAttachmentsHtml(attachment,objName,userInfo)+"]]></ATTACHMENTS>";

				if(userInfo.getUserLevel().equalsIgnoreCase("0"))
				{
					retXmlData += "<DELETE_ALLOW><![CDATA[Y]]></DELETE_ALLOW>";
				}
				else
				{
					if(rs.getString("USER_ID__OWN") != null && checkNull(rs.getString("USER_ID__OWN")).equalsIgnoreCase(checkNull(userInfo.getLoginCode())) )
					{
						retXmlData += "<DELETE_ALLOW><![CDATA[Y]]></DELETE_ALLOW>";
					}
					else
					{
						retXmlData += "<DELETE_ALLOW><![CDATA[N]]></DELETE_ALLOW>";
					}
				}
			}
			if(rs != null)
			{
				rs.close();
				rs = null;
			}
			if(stmt != null)
			{
				stmt.close();
				stmt = null;
			}
			retXmlData += "</Document>"; 
		}
		catch (ITMException itme)
		{
			BaseLogger.log("0", userInfo,  null,"Exception :TransactionEmailTempltEJB :getSelectedEmailXmlData :==>"); 
			throw itme;
		}
		catch (Exception e)
		{
			BaseLogger.log("0", userInfo,  null,"Exception :TransactionEmailTempltEJB :getSelectedEmailXmlData :==>"); 
			throw new ITMException(e);
		}
		finally
		{
			try
			{
				if(connection != null)
				{
					if(stmt != null)
					{
						stmt.close();
						stmt = null;
					}
					if(rs != null)
					{
						rs.close();
						rs = null;
					}
					connection.close();
					connection = null;
				}
			}
			catch(Exception e)
			{
				System.err.println("Exception :TransactionEmailTempltEJB :getAllTemplatesHTMLData :\n"+e.getMessage()); //$NON-NLS-1$
				throw new ITMException(e);
			}
		}
		BaseLogger.log("3", userInfo,  null,"Exception :TransactionEmailTempltEJB :"
				+ "retXmlData :==>[" + retXmlData +"]");
		return retXmlData;
		
	}
	
//	@Override
//	public String getSelectedEmailXmlData(String objName, UserInfoBean userInfo, String formatCode, String jsonTranData)
//			throws ITMException {
//		
//		String retXmlData = "";
//		retXmlData = getSelectedEmailXmlData(objName, userInfo, formatCode, jsonTranData);
//		return retXmlData;
//	}
	
	private String getAttachmentsHtml(String attachText ,String objName,UserInfoBean userInfo) throws ITMException
	{
		String attachments = "";
		int attachIndex = 0;
		BaseLogger.log("2", userInfo,  null,"attachText " +attachText);
		if(attachText != null && attachText.length() > 0)
		{
			if((attachText.substring(attachText.length()-1)).equals(","))
			{
				attachText = attachText.substring(0,attachText.length()-1);
			}
			String attacheText[] = attachText.split(",");
			for(int attachCnt = 0; attachCnt < attacheText.length ;attachCnt++)
			{
				//Change By PriyankaC to send HTML body  in mail.[START]
				BaseLogger.log("3", userInfo,  null,"attachementArr.. " +attacheText[attachCnt]);
				String[] linkParts = attacheText[attachCnt].split("~");
				String attachCode  = linkParts[0]; 
				String attachType  = linkParts[1]; 
				BaseLogger.log("3", userInfo,  null,"attachCode : " +attachCode +" attachType "+attachType); 
				//Change By PriyankaC to send HTML body  in mail.[END]
				if(attacheText[attachCnt].length()>0)
				{
					String linkInfoStr = getObjLinks(objName, userInfo, attachCode.split(":")[0]);
					String linkType = "";
					String linkTitle = "";
					String linkFormNo = "";
					String linkFieldName = "";
					String reportList = "";
					Document linkInfoDoc = genericUtility.parseString(linkInfoStr);
					NodeList linksInfoLst = linkInfoDoc.getElementsByTagName("Link");

					for( int i = 0; i < linksInfoLst.getLength(); i++)
					{			
						NodeList linkNodeList = linksInfoLst.item(i).getChildNodes();
						Node formNoAttr = linksInfoLst.item(i).getAttributes().getNamedItem("formNo") ;
						Node fieldNameAttr = linksInfoLst.item(i).getAttributes().getNamedItem("fieldName");
						if(formNoAttr != null )
						{
							linkFormNo = formNoAttr.getNodeValue();
						}
						if(fieldNameAttr != null )
						{
							linkFieldName = fieldNameAttr.getNodeValue();
						}
						for(int j = 0; j < linkNodeList.getLength(); j++)
						{
							Node linkNode = linkNodeList.item(j);
							if(linkNode.getNodeName().equalsIgnoreCase("LinkType"))
							{
								if(linkNode.getFirstChild() != null) 
								{
									linkType = linkNode.getFirstChild().getNodeValue();
								}
							}
							if(linkNode.getNodeName().equalsIgnoreCase("LinkTitle"))
							{
								if(linkNode.getFirstChild() != null) 
								{
									linkTitle = linkNode.getFirstChild().getNodeValue();
								}
							}
						}
						if(linkType.equals("5"))
						{
							if(linkFieldName.equals(attachCode.split(":")[1]))
							{
								reportList = reportList + "<option selected=\"selected\" value=\""+linkFormNo+":"+linkFieldName+"\">"+linkTitle+"</option>";
							}
							else
							{
								reportList = reportList + "<option value=\""+linkFormNo+":"+linkFieldName+"\">"+linkTitle+"</option>";
							}
							
						}
					}

					attachments = attachments + "<div class=\"vR attach\"><span name=\"attachSpanCode\" class=\"vN bfK a3q\"> <div class=\"DD\"> <select onClick=\"event.stopPropagation();\" id=\"attachdoc"+attachIndex+"\" onchange=\"setSelected(this);disableAttachType(this,"+attachIndex+")\" name=\"attachdoc\" class=\"ddf\" style=\"width: 82px;\">  <option  value=\"\">--Select--</option>  "+reportList+" </select> " +
							        "<select onClick=\"event.stopPropagation();\" id=\"attachdoctype"+attachIndex+"\" onchange=\"setSelected(this)\" name=\"attachdoctype\" class=\"ddf\" style=\"width: 82px;\"> ";
					                 //Change By PriyankaC to send HTML body  in mail.[START]
									if("B".equalsIgnoreCase(attachType))
									{
										attachments+="<option selected=\"selected\"  value=\"B\"> Embed in mail body </option>";
										attachments+="<option value=\"A\"> Send as attachment</option>";
									}
									else
									{   attachments+="<option  value=\"B\"> Embed in mail body </option>";
										attachments+="<option selected=\"selected\"  value=\"A\"> Send as attachment</option>";
									}
									attachments+= "</select>"
								 +"</div>"
							     +"<div class=\"vM\" onClick=\" event.stopPropagation();removeAttachment(this);\"></div></span></div>";
									//Change By PriyankaC to send selected type of body  in mail.[START]
					}
				attachIndex++;
			}
			
		}
		BaseLogger.log("2", userInfo,  null,"attachments :" +attachments);
		return attachments;
	}
	private String checkNull(String input)
	{
		if (input == null)
		{
			input= "";
		}
		return input.trim();
	}
	
	private static String getColumnLableData(String colData,String xmlColsData) throws Exception
	{
		String columnLableData = "";
		E12GenericUtility genericUtility = new E12GenericUtility();
		Document xmlColsDom = genericUtility.parseString(xmlColsData);
		Node detailNode = null;
		NodeList detailNodeList = null;
		String[] toAddrArray = null;
		String colName = "";
		Document detailDom = null;
		String entityType = "";
		if(colData != null)
		{
			toAddrArray = colData.split(",");
			for(int i=0; i<toAddrArray.length; i++)
			{
				columnLableData +="<ADDRESS_FLD>";
				colName = toAddrArray[i];
				if(colName.indexOf("<Detail1.") != -1)
				{
					colName = 	colName.substring(9,colName.lastIndexOf(">"));
					detailNodeList = xmlColsDom.getElementsByTagName("DETAIL");
					for(int nodeCnter = 0 ;nodeCnter <detailNodeList.getLength(); nodeCnter++)
					{
						detailNode = detailNodeList.item(nodeCnter);
						detailDom = genericUtility.parseString(genericUtility.serializeDom(detailNode));
						if(colName.equals(detailDom.getElementsByTagName("Descr").item(0).getFirstChild().getNodeValue()))
						{
							BaseLogger.log("3", null,  null,detailDom.getElementsByTagName("MAILADDR").item(0).getFirstChild().getNodeValue());
							columnLableData += "<COL_LABLE>"+ detailDom.getElementsByTagName("MAILADDR").item(0).getFirstChild().getNodeValue()+"</COL_LABLE>";
							columnLableData += "<COL_NAME>"+ colName +"</COL_NAME>";
							break;
						}		
					}
				}
				else
				{
					if(colName.startsWith("{"))
					{
						entityType = "";
						if (colName.charAt(1) == '(' )
						{
							entityType = colName.substring(colName.indexOf("(")+1, colName.indexOf(")"));
							colName = colName.substring(colName.indexOf(")")+1, colName.indexOf("}"));
							detailNodeList = xmlColsDom.getElementsByTagName("DETAIL");
							for(int nodeCnter = 0 ;nodeCnter <detailNodeList.getLength(); nodeCnter++)
							{
								detailNode = detailNodeList.item(nodeCnter);
								detailDom = genericUtility.parseString(genericUtility.serializeDom(detailNode));
								if(colName.equals(detailDom.getElementsByTagName("Descr").item(0).getFirstChild().getNodeValue()))
								{
									BaseLogger.log("3", null,  null,detailDom.getElementsByTagName("MAILADDR").item(0).getFirstChild().getNodeValue());
									columnLableData += "<COL_LABLE>"+ detailDom.getElementsByTagName("MAILADDR").item(0).getFirstChild().getNodeValue()+"</COL_LABLE>";
									columnLableData += "<COL_NAME>"+ colName +"</COL_NAME>";
									columnLableData += "<ENTIEY_TYPE>"+ entityType +"</ENTIEY_TYPE>";
									break;
								}		
							}
						}		
					}
					else
					{
						columnLableData += "<COL_LABLE>"+ colName +"</COL_LABLE>";
						columnLableData += "<COL_NAME></COL_NAME>";
					}
				}
				columnLableData +="</ADDRESS_FLD>";
			}
		}
		return columnLableData;
	}
	
	private String getHtmlBodyText(String bodyTextData,String xmlColsData) throws Exception
	{
		E12GenericUtility genericUtility = new E12GenericUtility();
		Document xmlColsDom = genericUtility.parseString(xmlColsData);
		Node detailNode = null;
		NodeList detailNodeList = null;
		String colName = "";
		Document detailDom = null;
		int count = 1;
		if(bodyTextData != null)
		{
			String findStr = "&lt;Detail1.";
			String colFullName = "";
			boolean found = false;
			int currentIndex = 0;
			int nextSearchIndex = 0;
			while(bodyTextData.indexOf(findStr,nextSearchIndex) != -1)
			{
				BaseLogger.log("3", null,  null,nextSearchIndex);
				currentIndex = bodyTextData.indexOf(findStr,nextSearchIndex);
				String firstPart = bodyTextData.substring(0,currentIndex);
				String lastPart = bodyTextData.substring(currentIndex,bodyTextData.length());
				colFullName = lastPart.substring(0,lastPart.indexOf("&gt;")+4);
				BaseLogger.log("3", null,  null,"colFullName:"+colFullName);
				
				colName = colFullName.substring(findStr.length(),colFullName.lastIndexOf("&gt;"));
				BaseLogger.log("3", null,  null,"colName:"+colName);
				detailNodeList = xmlColsDom.getElementsByTagName("DETAIL");
				found = false;
				for(int nodeCnter = 0 ;nodeCnter <detailNodeList.getLength(); nodeCnter++)
				{
					
					detailNode = detailNodeList.item(nodeCnter);
					detailDom = genericUtility.parseString(genericUtility.serializeDom(detailNode));
					if(colName.equals(detailDom.getElementsByTagName("Descr").item(0).getFirstChild().getNodeValue()))
					{
						String htmlText = "<span type=\"text\" name= \"dynamicTextBox\" class=\"dynamicTextBox vN\" contenteditable=\"false\" style=\"display:inline-block\" isDiv=\"true\" id=\"bodyDyanInpCol"+count+"\" colTagValueName=\""+colFullName.replaceFirst("&lt;", "<").replace("&gt;", ">")+"\" readonly onFocus=\"gotFocus(this);\" onBlur=\"blurDynaTextBox(this);\" onkeyup=\"editableSpan(this);\" > ["+detailDom.getElementsByTagName("MAILADDR").item(0).getFirstChild().getNodeValue()+"] </span>";
						bodyTextData = firstPart + lastPart.replaceFirst(colFullName, htmlText);
						nextSearchIndex = currentIndex+htmlText.length();
						BaseLogger.log("3", null,  null,bodyTextData);
						count++;
						found = true;
						break;
					}
				}
				if(!found)
				{
					String htmlText = "";
					bodyTextData = firstPart + lastPart.replaceFirst(colFullName, htmlText);
					nextSearchIndex = currentIndex+htmlText.length();
					BaseLogger.log("3", null,  null,bodyTextData);
				}
			}
		}
		lastDyanInpCol = count;
		return bodyTextData;
	}
	
	private String getHtmlSubText(String subTextData,String xmlColsData) throws Exception
	{
		E12GenericUtility genericUtility = new E12GenericUtility();
		Document xmlColsDom = genericUtility.parseString(xmlColsData);
		Node detailNode = null;
		NodeList detailNodeList = null;
		String colName = "";
		Document detailDom = null;
		int count = 1;
		if(subTextData != null)
		{
			String findStr = "<Detail1.";
			String colFullName = "";
			boolean found = false;
			int currentIndex = 0;
			int nextSearchIndex = 0;
			while(subTextData.indexOf(findStr,nextSearchIndex) != -1)
			{
				BaseLogger.log("3", null,  null,nextSearchIndex);
				currentIndex = subTextData.indexOf(findStr,nextSearchIndex);
				String firstPart = subTextData.substring(0,currentIndex);
				String lastPart = subTextData.substring(currentIndex,subTextData.length());
				colFullName = lastPart.substring(0,lastPart.indexOf(">")+1);
				BaseLogger.log("3", null,  null,"colFullName:"+colFullName);
				
				colName = colFullName.substring(findStr.length(),colFullName.lastIndexOf(">"));
				BaseLogger.log("3", null,  null,"colName:"+colName);
				detailNodeList = xmlColsDom.getElementsByTagName("DETAIL");
				found = false;
				for(int nodeCnter = 0 ;nodeCnter <detailNodeList.getLength(); nodeCnter++)
				{
					
					detailNode = detailNodeList.item(nodeCnter);
					detailDom = genericUtility.parseString(genericUtility.serializeDom(detailNode));
					if(colName.equals(detailDom.getElementsByTagName("Descr").item(0).getFirstChild().getNodeValue()))
					{
						String htmlText = "<span type=\"text\" name= \"dynamicSubBox\" class=\"dynamicSubBox vN\" contenteditable=\"false\" style=\"display:inline-block\" isDiv=\"true\" id=\"bodyDyanSubInpCol"+count+"\" colTagValueName=\""+colFullName+"\" readonly onFocus=\"gotFocus(this);\" onBlur=\"blurDynaTextBox(this);\" onkeyup=\"editableSpan(this);\" > ["+detailDom.getElementsByTagName("MAILADDR").item(0).getFirstChild().getNodeValue()+"] </span>";
						subTextData = firstPart + lastPart.replaceFirst(colFullName, htmlText);
						nextSearchIndex = currentIndex+htmlText.length();
						BaseLogger.log("3", null,  null,subTextData);
						count++;
						found = true;
						break;
					}
				}
				if(!found)
				{
					String htmlText = "";
					subTextData = firstPart + lastPart.replaceFirst(colFullName, htmlText);
					nextSearchIndex = currentIndex+htmlText.length();
					BaseLogger.log("3", null,  null,subTextData);
				}
			}
		}
		lastDyanSubInpCol = count;
		return subTextData;
	}
	
	public String readFile( String fileName ) throws Exception
	{
		StringBuffer fileContent = new StringBuffer();
		BufferedReader bfr = null;
		try
		{
			FileInputStream fMainIn = new FileInputStream( fileName );
			bfr = new BufferedReader(new InputStreamReader(fMainIn,CommonConstants.ENCODING)); 
			String outTempStr = null;
			while((outTempStr = bfr.readLine()) != null)
			{
				fileContent.append(outTempStr);
			}
			bfr.close();
			bfr = null;
		}
		catch ( Exception e )
		{
			throw e;
		}
		finally
		{
			try
			{
				if( bfr != null )
				{
					bfr.close();
					bfr = null;
				}
			}
			catch ( Exception e )
			{
				BaseLogger.log("0", null,  null, "Exception in releasing file resource :[" + fileName + "]" );
				e.printStackTrace();
			}
		}
		return fileContent.toString();
	}
	private TreeMap<Integer, TreeMap<Integer, I18NMetadataObject>> parseMetadataObjects( Document doc) 
	{
		TreeMap< Integer, TreeMap<Integer, I18NMetadataObject> > yTextMap = new TreeMap< Integer, TreeMap<Integer, I18NMetadataObject> >();

		yTextMap = new TreeMap< Integer, TreeMap<Integer, I18NMetadataObject> >();
		NodeList txtList = doc.getElementsByTagName("TextObject");
		for (int i = 0; i < txtList.getLength(); i++)
		{
			Node eachText =(Node)txtList.item(i);
			I18NMetadataObject textObject = parseMetaObjectNode(eachText);
			textObject.setMetaType("Text");
			Integer xCordKey = textObject.getIntXCord();
			Integer yCordKey =	textObject.getIntYCord();
			textObject.setYCord(yCordKey);
			TreeMap<Integer, I18NMetadataObject> xTxtMap = yTextMap.get( yCordKey );
			if( xTxtMap == null )
			{
				xTxtMap = new TreeMap<Integer, I18NMetadataObject>();
				xTxtMap.put(xCordKey, textObject);
				yTextMap.put( yCordKey, xTxtMap );
			}
			else
			{
				while(true)
				{
					if(!xTxtMap.containsKey(xCordKey))
					{
						xTxtMap.put(xCordKey, textObject);
						break;
					}
					else
					{
						xCordKey++;
					}
				}
				yTextMap.put( yCordKey, xTxtMap );	
			}
		}

		NodeList colList = doc.getElementsByTagName("ColumnObject"); 
		for (int i = 0; i < colList.getLength(); i++)
		{
			Node eachText =(Node)colList.item(i);

			I18NMetadataObject colObject = parseMetaObjectNode(eachText);
			colObject.setMetaType("Column");

			Integer xCordKey = colObject.getIntXCord();
			Integer yCordKey =	colObject.getIntYCord();
			colObject.setYCord(yCordKey);

			TreeMap<Integer, I18NMetadataObject> xTxtMap = yTextMap.get( yCordKey );
			if( xTxtMap == null )
			{
				xTxtMap = new TreeMap<Integer, I18NMetadataObject>();
				xTxtMap.put(xCordKey, colObject);
				yTextMap.put( yCordKey, xTxtMap );
			}
			else
			{
				while(true)
				{
					if(!xTxtMap.containsKey(xCordKey))
					{
						xTxtMap.put(xCordKey, colObject);
						break;
					}
					else
					{
						xCordKey++;
					}
				}
				yTextMap.put( yCordKey, xTxtMap );
			}
		}
		return yTextMap;
	}
	
	private I18NMetadataObject parseMetaObjectNode(Node eachText) 
	{
		I18NMetadataObject metaObj = new I18NMetadataObject();
		NodeList eachTextDetail = eachText.getChildNodes();				
		for (int j=0; j < eachTextDetail.getLength(); j++ )
		{
			if ( ! eachTextDetail.item(j).getNodeName().equalsIgnoreCase( "#text" ) )
			{						
				if (eachTextDetail.item(j).getFirstChild() != null)
				{	
					Node childNode = eachTextDetail.item(j);
					String sub_nodes_name = childNode.getNodeName();
					if( "name".equalsIgnoreCase(sub_nodes_name) )
					{
						String colName = childNode.getFirstChild().getNodeValue();
						metaObj.setName(colName);
					}						
					else if ( "text".equalsIgnoreCase(sub_nodes_name) )
					{
						String text = childNode.getFirstChild().getNodeValue();
						metaObj.setText(text);
					}
				}
			}							
		} 
		return metaObj;
	}
	private String getTransID( String windowName, Connection conn ) throws ITMException
	{
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String selSql = "";
		String tranId = "";
		String tranSer = "";
		String keyString = "";
		String keyCol = "";
		String xmlValues = "";

		 try
         {
			selSql = "SELECT KEY_STRING, TRAN_ID_COL, REF_SER FROM TRANSETUP WHERE TRAN_WINDOW = ? ";
			pstmt = conn.prepareStatement(selSql);
			pstmt.setString( 1, windowName );
			rs = pstmt.executeQuery();
			if (rs.next())
			{
					keyString = rs.getString("KEY_STRING");
					keyCol = rs.getString("TRAN_ID_COL");
					tranSer = rs.getString("REF_SER");
			}
			rs.close();rs = null;
			pstmt.close();pstmt = null;
			BaseLogger.log("3", null,  null,"keyString :"+keyString);
			BaseLogger.log("3", null,  null,"keyCol :"+keyCol);
			BaseLogger.log("3", null,  null,"tranSer :"+tranSer);

			xmlValues ="<?xml version=\"1.0\" encoding=\"utf-8\"?><Root>";
			xmlValues = xmlValues + "<Header></Header>";
			xmlValues = xmlValues + "<Detail1>";
			xmlValues = xmlValues +        "<tran_id></tran_id>";
			xmlValues = xmlValues + "</Detail1></Root>";
			BaseLogger.log("3", null,  null,"xmlValues  :["+xmlValues+"]");
			TransIDGenerator tg = new TransIDGenerator(xmlValues, "BASE", CommonConstants.DB_NAME);
			tranId = tg.generateTranSeqID(tranSer, keyCol, keyString, conn);
			BaseLogger.log("3", null,  null,"tranId :"+tranId);
         }
		catch (SQLException ex)
		{
			BaseLogger.log("0", null,  null,"Exception ::" +selSql+ ex.getMessage() + ":");
			ex.printStackTrace();
			throw new ITMException(ex);
		}
		catch (Exception e)
		{
			BaseLogger.log("0", null,  null,"Exception ::" + e.getMessage() + ":");
			e.printStackTrace();
			throw new ITMException(e);
		}
		finally
		{
			try
			{
				if (rs != null)
				{
					rs.close();
					rs = null;
				}
				if (pstmt != null)
				{
					pstmt.close();
					pstmt = null;
				}
			}
			catch(Exception e){}
		}
        return tranId;
	}
	private Connection getConnection(UserInfoBean userInfo) throws ITMException 
	{
		ConnDriver connDriver = null;
		Connection conn = null;
		String transDB = userInfo.getTransDB();
		try 
		{
			connDriver = new ConnDriver();
			if(userInfo != null)
			{
				transDB = userInfo.getTransDB();
			}
			//if(transDB != null && !"null".equalsIgnoreCase(transDB.trim()) && transDB.trim().length() > 0)
			{
				conn = connDriver.getConnectDB(transDB);
			}
		} catch (Exception e) 
		{
			e.printStackTrace();
			throw new ITMException(e);
		} 
		
		return conn;
	}
	
	private InitialContext getInitialContext() throws ITMException 
	{
		InitialContext ctx = null;
		try 
		{
			BaseLogger.log("3", null,  null,"getInitialContext");
			AppConnectParm appConnect = new AppConnectParm();
			ctx = new InitialContext(appConnect.getProperty());

		}
		catch (ITMException itme)
		{
			BaseLogger.log("0", null,  null,"ITMException :TransactionEmailTempltEJB :getInitialContext :==>");
			throw itme;
		}
		catch (Exception e) 
		{
			BaseLogger.log("0", null,  null,"Exception :TransactionEmailTempltEJB :getInitialContext :==>");
			throw new ITMException(e);
		}
		return ctx;
	}
	@Override
	public String getObjLinks(String objName, UserInfoBean userInfo,String formNo) throws ITMException 
	{
		String linkInfoStr = "";
		try
		{
			//LinkControllerLocal linkControllerRemote = ( LinkControllerLocal ) this.getInitialContext().lookup( "ibase/LinkControllerEJB/local" ); //$NON-NLS-1$
			LinkControllerEJB linkControllerEJB = new LinkControllerEJB();
			linkInfoStr = linkControllerEJB.getLinkInfo(objName, formNo, userInfo);
			BaseLogger.log("3", userInfo,  null,"linkInfoStr"+linkInfoStr);
			linkControllerEJB = null;
		}
		catch(Exception e)
		{
			throw(new ITMException(e));
		}
		return linkInfoStr;
	}
	
	private String getAttachmentPath(String objName, String attachObjLink,	UserInfoBean userInfo, Document currentPkTranDom , String tranId,String attachType) throws ITMException  //Change By PriyankaC to send selected type of attachment  in mail.
	{
		String attachmentPath = "";
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		Connection conn = getConnection(userInfo);
		try
		{
			String selSql = "";
			String attachFormField[] = attachObjLink.split(":");
			String formNo = attachFormField[0];
			String formField = attachFormField[1];
			String reportFileName = "";
			String linkArgsArr[] = null;
			NodeList detailNodeList = null;
			Node  detailNode = null;
			Document detailDom = null;
			String linkAgrs = "";
			String linkTitle = "";
			selSql = "SELECT TARGET_OBJ_NAME,LINK_ARG,LINK_TITLE FROM OBJ_LINKS WHERE OBJ_NAME = ? AND FORM_NO = ? AND FIELD_NAME = ? AND LINK_TYPE = ?";
			pstmt = conn.prepareStatement(selSql);
			pstmt.setString( 1, objName );
			pstmt.setString( 2, formNo );
			pstmt.setString( 3, formField );
			pstmt.setString( 4, "5" );
			rs = pstmt.executeQuery();
			if (rs.next())
			{
				reportFileName = checkNull(rs.getString("TARGET_OBJ_NAME"));
				linkAgrs = checkNull(rs.getString("LINK_ARG"));
				linkTitle = checkNull(rs.getString("LINK_TITLE"));
			}
			String outputFilename = objName+"_"+tranId+"_"+linkTitle;
			//Added By Ravindra C on 30-3-18 for Enterprise Path
			//XSDParser xsdParser = new XSDParser(reportFileName)
			XSDParser xsdParser = new XSDParser(reportFileName, userInfo); 
			BaseLogger.log( "3", userInfo, null, "xsdParser:: ["+ xsdParser +"]" );
			String argXmlString = xsdParser.getArgumentMetaDataString();
			BaseLogger.log( "3", userInfo, null, "xsdParser.getArgumentMetaDataString():: ["+ argXmlString +"]" );
			//Changed by Prasad on 03/12/18 [userInfo related argument not getting set from email action] START
			/*HashMap<String, String> argNameTypeMap = getArgumentTypeMap(argXmlString);
			BaseLogger.log("3", userInfo,  null,"argNameTypeMap:"+argNameTypeMap);
			String reportArgString = "<Arguments><Argument id=\"x_path\" name=\"x_path\"><argType>java.lang.String</argType><value>/DocumentRoot/"+reportFileName+"</value></Argument>" +
					"<Argument id=\"design_source\" name=\"design_source\"><argType>java.lang.String</argType><value>"+reportFileName+".jrxml</value></Argument>" +
					"<Argument id=\"data_source\" name=\"data_source\"><argType>java.lang.String</argType><value>SQL</value></Argument>" +
					"<Argument id=\"bind_type\" name=\"bind_type\"><argType>java.lang.Integer</argType><value>0</value></Argument>" +
					"<Argument id=\"report_type\" name=\"report_type\"><argType>java.lang.String</argType><value>JASPER</value></Argument>" +
					"<Argument id=\"report_save_type\" name=\"report_save_type\"><argType>java.lang.String</argType><value>"+attachType.toUpperCase()+"</value></Argument>"; //Change By PriyankaC to send selected type of attachment  in mail.
			if(linkAgrs.length()>0)
			{
				linkArgsArr = linkAgrs.split(",");

				for(int argCnt = 0; argCnt < linkArgsArr.length; argCnt++)
				{
					String arg = linkArgsArr[argCnt];
					String argNameType[] = arg.split("\\.");
					String argValue = "";
					String argType = "";
					if(argNameType != null)
					{
						detailNodeList = currentPkTranDom.getElementsByTagName("Detail1");
						detailNode = detailNodeList.item(0);
						detailDom = genericUtility.parseString(genericUtility.serializeDom(detailNode));

						if(detailDom.getElementsByTagName(argNameType[0]) != null) 
						{
							if(detailDom.getElementsByTagName(argNameType[0]).item(0) != null)
							{
								if(detailDom.getElementsByTagName(argNameType[0]).item(0).getFirstChild() != null)
								{
									argValue = detailDom.getElementsByTagName(argNameType[0]).item(0).getFirstChild().getNodeValue();
								}
							}
						}
						else
						{
							argValue = argNameType[0];
						}
						if(argNameTypeMap.containsKey(argNameType[1].split(":")[1]))
						{
							argType = argNameTypeMap.get(argNameType[1].split(":")[1]);
						}
						else
						{
							argType = "java.lang."+argNameType[1].split(":")[0];
						}
						reportArgString = reportArgString +"<Argument id=\""+argNameType[1].split(":")[1]+"\" name=\""+argNameType[1].split(":")[1]+"\"><argType>"+argType+"</argType><value>"+argValue+"</value></Argument>";
					}
				}
			}
			reportArgString = reportArgString + "</Arguments>";*/
			String reportArgString = genReportArgStr( reportFileName, attachType, argXmlString, currentPkTranDom, linkAgrs, userInfo );
			//Changed by Prasad on 03/12/18 [userInfo related argument not getting set from email action] END
			BaseLogger.log( "3", userInfo, null, "ReportArgString[" + reportArgString + "]" );
			//Changed by Pankaj T on 04-01-18 [changes for multitenancy]
			JasperReportGenerator  jasperReport = new JasperReportGenerator(userInfo);
			TreeMap argMap = jasperReport.createArgMap(reportArgString);	
			BaseLogger.log("3", userInfo,  null,"TreeMap:::->"+argMap);
			jasperReport.createReport( reportFileName,argMap, xsdParser, "EmailAttachments", outputFilename);
			
			attachmentPath = ResourceConstants.REPORTDESTINATION + File.separator + "EmailAttachments" +File.separator + outputFilename+"."+attachType;
			if (rs != null)
			{
				rs.close();
				rs = null;
			}
			if (pstmt != null)
			{
				pstmt.close();
				pstmt = null;
			}
			if(conn != null)
			{
				conn.close();
				conn = null;
			}
		}
		catch(Exception e)
		{
		   throw new ITMException(e);
		}
		finally
		{
			try
			{
				if (rs != null)
				{
					rs.close();
					rs = null;
				}
				if (pstmt != null)
				{
					pstmt.close();
					pstmt = null;
				}
				if(conn != null)
				{
					conn.close();
					conn = null;
				}
			}
			catch(Exception e){}
		}
		return attachmentPath;
	}
	
	//Changed by Prasad on 03/12/18 [userInfo related argument not getting set from email action] START
	/*private HashMap<String, String> getArgumentTypeMap(String xsdString) throws Exception 
	{
		HashMap<String, String> argumentTypeMap = new HashMap<String, String>();
	
		Document doc = genericUtility.parseString(xsdString);
		NodeList argNodeList = doc.getElementsByTagName("argument");
		if( argNodeList != null )
		{
			for(int argCnt = 0; argCnt <= argNodeList.getLength(); argCnt++)
			{
				Node argNode = argNodeList.item(argCnt);
				if(argNode != null)
				{
					String name = "";
					String type = "";
					Node attribute = null;
					attribute = argNode.getAttributes().getNamedItem("name");
					if(attribute != null)
					{
						if(attribute.getFirstChild() != null)
						{
							name = attribute.getFirstChild().getNodeValue();
						}
					}
					attribute = argNode.getAttributes().getNamedItem("type");
					if(attribute != null)
					{
						if(attribute.getFirstChild() != null)
						{
							type = attribute.getFirstChild().getNodeValue();
						}
					}
					argumentTypeMap.put(name, type);
				}
			}
		}
		return argumentTypeMap;
	}*/
	
	/**
	 * Create report argument string using userInfo
	 * 
	 * @param reportFileName
	 * @param attachType
	 * @param xsdString
	 * @param transDom
	 * @param linkAgrs
	 * @param userInfo
	 * @return
	 * @throws Exception
	 */
	private String genReportArgStr( String reportFileName, String attachType, String xsdString, Document transDom, String linkAgrs, UserInfoBean userInfo ) throws Exception 
	{
		StringBuffer reportArgString = new StringBuffer();
		try 
		{
			reportArgString.append( "<Arguments>" );
			reportArgString.append( "<Argument id=\"x_path\" name=\"x_path\"><argType>java.lang.String</argType><value>/DocumentRoot/"+reportFileName+"</value></Argument>" );
			reportArgString.append( "<Argument id=\"design_source\" name=\"design_source\"><argType>java.lang.String</argType><value>"+reportFileName+".jrxml</value></Argument>" );
			reportArgString.append( "<Argument id=\"data_source\" name=\"data_source\"><argType>java.lang.String</argType><value>SQL</value></Argument>" );
			reportArgString.append( "<Argument id=\"bind_type\" name=\"bind_type\"><argType>java.lang.Integer</argType><value>0</value></Argument>" );
			reportArgString.append( "<Argument id=\"report_type\" name=\"report_type\"><argType>java.lang.String</argType><value>JASPER</value></Argument>" );
			//Change By PriyankaC to send selected type of attachment  in mail.
			reportArgString.append( "<Argument id=\"report_save_type\" name=\"report_save_type\"><argType>java.lang.String</argType><value>"+attachType.toUpperCase()+"</value></Argument>" ); 
			if ( xsdString != null && xsdString.length() > 0 )
			{
				HashMap<String, String> formValueMap = getFormValueMap( transDom );
				//BaseLogger.log( "3", userInfo, null, "formValueMap[" + formValueMap + "]" );
				
				HashMap<String, String> linkArgValueMap = getLinkArgValueMap( linkAgrs, formValueMap );
				//BaseLogger.log( "3", userInfo, null, "linkArgValueMap[" + linkArgValueMap + "]" );
				
				HashMap<String, String> userInfoMap = getUserInfoMap( userInfo );
				//BaseLogger.log( "3", userInfo, null, "userInfoMap[" + userInfoMap + "]" );
				
				Document doc = genericUtility.parseString( xsdString );
				NodeList argNodeList = doc.getElementsByTagName( "argument" );
				if( argNodeList != null )
				{
					for( int argCnt = 0; argCnt <= argNodeList.getLength(); argCnt++ )
					{
						Node argNode = argNodeList.item(argCnt);
						if(argNode != null)
						{
							String argName = "";
							String argType = "";
							String argValue = "";
							Node attribute = null;
							attribute = argNode.getAttributes().getNamedItem("name");
							if( attribute != null && attribute.getFirstChild() != null )
							{
								argName = attribute.getFirstChild().getNodeValue();
							}
							attribute = argNode.getAttributes().getNamedItem("type");
							if( attribute != null && attribute.getFirstChild() != null )
							{
								argType = attribute.getFirstChild().getNodeValue();
							}
							attribute = argNode.getAttributes().getNamedItem("value");
							if( attribute != null && attribute.getFirstChild() != null )
							{
								argValue = attribute.getFirstChild().getNodeValue();
							}
							//BaseLogger.log( "3", userInfo, null, "argName : ["+ argName +"], argType : ["+ argType +"], argValue : ["+ argValue +"]" );
							if ( linkArgValueMap != null && linkArgValueMap.containsKey( argName ) )
							{
								argValue = linkArgValueMap.get( argName );
								reportArgString.append( "<Argument id=\""+argName+"\" name=\""+argName+"\"><argType>"+argType+"</argType><value>"+argValue+"</value></Argument>" );
							}
							else if ( userInfoMap != null && userInfoMap.containsKey( argValue.toLowerCase() ) )
							{
								argValue = userInfoMap.get( argValue.toLowerCase() );
								reportArgString.append( "<Argument id=\""+argName+"\" name=\""+argName+"\"><argType>"+argType+"</argType><value>"+argValue+"</value></Argument>" );
							}
							//reportArgString.append( "<Argument id=\""+argName+"\" name=\""+argName+"\"><argType>"+argType+"</argType><value>"+argValue+"</value></Argument>" );
						}
					}
				}
			}
			reportArgString.append( "</Arguments>" );
		}
		catch (Exception e) 
		{
			BaseLogger.log( "0", userInfo, null, "Exception :: genReportArgStr : ["+ e.getMessage() +"]" );
			e.printStackTrace();
		}
		return reportArgString.toString();
	}
	
	/**
	 * create form values map of first form 
	 * 
	 * @param transactionDom
	 * @return
	 * @throws Exception
	 */
	private HashMap<String, String> getFormValueMap( Document transactionDom ) throws Exception 
	{
		HashMap<String, String> formValueMap = new HashMap<String, String>();
		if( transactionDom != null )
		{
			NodeList detailNodeList = transactionDom.getElementsByTagName("Detail1");
			Node parentNode = detailNodeList.item( 0 );
			NodeList childNodeList = parentNode.getChildNodes();
			for ( int childNodeCtr = 0; childNodeCtr < childNodeList.getLength(); childNodeCtr++ )
			{
				Node childNode = childNodeList.item( childNodeCtr );
				if ( childNode != null && childNode.getNodeType() == Node.ELEMENT_NODE )
				{
					String nodeName = childNode.getNodeName();
					String nodeValue = "";
					if( childNode.getFirstChild() != null )
					{
						nodeValue = childNode.getFirstChild().getNodeValue();
					}
					formValueMap.put( nodeName, nodeValue );
				}
			}
		}
		return formValueMap;
	}
	
	/**
	 * create link argument map
	 * 
	 * @param linkAgrs
	 * @param formValueMap
	 * @return
	 * @throws Exception
	 */
	private HashMap<String, String> getLinkArgValueMap( String linkAgrs, HashMap<String, String> formValueMap ) throws Exception 
	{
		HashMap<String, String> linkArgValueMap = new HashMap<String, String>();

		if( linkAgrs.length() > 0 )
		{
			String[] linkArgsArr = linkAgrs.split(",");
			for( int argCnt = 0; argCnt < linkArgsArr.length; argCnt++ )
			{
				String arg = linkArgsArr[argCnt];
				String argNameType[] = arg.split("\\.");
				if( argNameType != null )
				{
					String fieldName = argNameType[0];
					String argName = argNameType[1].split(":")[1];
					String argValue = fieldName;
					if ( formValueMap != null && formValueMap.containsKey( fieldName ) )
					{
						argValue = formValueMap.get( fieldName );
					}
					linkArgValueMap.put( argName, argValue );
				}
			}
		}
		return linkArgValueMap;
	}
	
	private HashMap<String, String> getUserInfoMap( UserInfoBean userInfo )
	{
		HashMap<String, String> userInfoMap = new HashMap<String, String>();
		try
		{
			if ( userInfo != null )
			{
				String user = userInfo.getLoginCode();		
				String entityCode = userInfo.getEntityCode();
				String profileId = userInfo.getProfileId();
				String empCode = userInfo.getEmpCode();
				String reportTo = userInfo.getReportTo();
				String deptCode = userInfo.getDeptCode();
				String userLev = userInfo.getUserLevel();
				String userType = userInfo.getUserType();
				String loginSite = userInfo.getSiteCode();
				if ( entityCode == null )
				{
					entityCode = "";
				}
				if ( user == null )
				{
					user = "";
				}
				
				userInfoMap.put( "login_site", loginSite );
				userInfoMap.put( "login_code", user );
				userInfoMap.put( "entity_code", entityCode );
				userInfoMap.put( "profile_id", profileId );
				userInfoMap.put( "report_to", reportTo );
				userInfoMap.put( "dept_code", deptCode );
				userInfoMap.put( "user_lev", userLev );
				userInfoMap.put( "user_type", userType );
				userInfoMap.put( "emp_code", empCode );
			}
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		return userInfoMap;
	}
	//Changed by Prasad on 03/12/18 [userInfo related argument not getting set from email action] END
	
	 //Added by Gagan B. on 01-OCT-24 method to read the content of HTML file -- START
    public static String readHtmlFile(String filePath) throws IOException {
        return new String(Files.readAllBytes(Paths.get(filePath)));
    }
    //Added by Gagan B. on 01-OCT-24 method to read the content of HTML file -- END

	
}
