<%@ include file="../../EgTrackerAJSON.jsp" %>
<%@ page import = "com.eg.UpdateAndTransmitUserInfo"%>
<%@ page import = "com.eg.EgCrypt"%>
<%@ page import = "com.eg.UploadCustomImage"%>
<%@ page import = "com.egurkha.*"%>
<%@ page import = "java.util.StringTokenizer"%>
<%@ page import = "java.io.*"%>
<%@ page import = "com.eg.EgDbAdapterTypeUI"%>
<%@ page import = "com.eg.EgServicesInfo"%>
<%@ page import = "egurkha.EgDbAdapterUI"%>
<%@ page import = "com.egurkha.ini.IniUI" %>
<%@ page import = "com.eg.IniFile" %>
<%@ page import = "com.eg.EgCloneUser" %>
<%@ page import = "com.eg.EgDateInfo"%>
<%@ page import = "com.eg.EgInstallInfo" %>
<%@ page import = "com.egurkha.util.DateUtil" %>
<%@ page import = "com.egurkha.util.StringUtils"%>
<%@ page import = "com.egurkha.EgUserRole" %>
<%@ page import="com.eg.EgURLEncoder"%>
<%@ page import = "com.egurkha.admin.AuditLogThread"%>
<%@ page import = "com.eg.EgMemCheck"%>
<%@ page import = "com.eg.EgManagersIniForManager"%>
<%@ page import = "com.eg.TransmitInfosToAllSMs"%>
<%@ page import = "com.eg.EgConfigFilesSync"%>
<%@ page import ="com.egurkha.monitor.EgComponentUserMappingBean"%>

<%@ page language="java" contentType="application/json; charset=UTF-8" pageEncoding="UTF-8" %>
<%@ page import = "net.sf.json.*"%>

<%@ page import="com.egurkha.admin.mfa.EgMailHelper"%>
<%@ page import="com.egurkha.admin.mfa.GoogleAuthenticator"%>


<jsp:useBean id="user" scope="page" class="egurkha.UserBean"/>
<jsp:useBean id="ecumb" scope="page" class="com.egurkha.monitor.EgComponentUserMappingBean" />

<%!
	String  str_con="";
	String  str_usercon="";
	String  uname="";
	String  upass="";
	String userAuthentication="";
%>

<%
	JSONObject rootObj = new JSONObject();
	rootObj.put("success","true");
	JSONObject hiddenFields = new JSONObject();
	JSONObject errorObj = new JSONObject();

	response.setHeader("Cache-Control","no-store");
	response.setHeader("Pragma","no-cache");
	response.setDateHeader("Expires", -1);
	response.setContentType("application/json");

	String str_query="";
	UpdateAndTransmitUserInfo updateAndTransmitUserInfo =   new UpdateAndTransmitUserInfo();

	if(request.getParameter("assousers")!=null && ((String)request.getParameter("assousers")).length()>0)
	{
		str_query = "insert into user_relation values('"+request.getParameter("uname")+"','"+request.getParameter("assousers")+"')";
		updateAndTransmitUserInfo.dbupdate(str_query);
	}


	/* code for 2fa starts here */
	boolean is2faCFlagEnabled = false;
	IniFile egMFAIniFile = new IniFile(EgInstallInfo.getInstallDir() + "/manager/config/eg_mfa.ini");

	String is2FAEnabled = egMFAIniFile.getValue("2FA_SETTINGS","Is2FAEnabled");

	if (is2FAEnabled != null && (is2FAEnabled.equalsIgnoreCase("yes") || is2FAEnabled.equalsIgnoreCase("true")))
	{
		String twoFAOptionFlag = egMFAIniFile.getValue("2FA_SETTINGS","TwoFAOptionFlag");

		if (twoFAOptionFlag != null && twoFAOptionFlag.equalsIgnoreCase("c"))
		{
			is2faCFlagEnabled = true;
		}
	}
	/* code for 2fa ends here */
	
	String userModel = "";
	String org = "";
	String  utype="";
	String  uvalidtill ="";
	String  mailid="";
	String	comma=",";
	String  tomailid="";
	String  ccmailid="";
	String  bccmailid="";
	String customScript="";//add by sunder
	String scrtemp="";
	String  escmailid="";
	String	cctemp="";
	String	bcctemp="";
	String  alerttype="";
	String alarm_type = "";
	String  msgmode="";
	String  notify="";
	String  high="";
	String  low="";
	String  medium="";
	String alarm_h = "";
	String alarm_m = "";
	String alarm_l = "";
	String  newWindow="";
	String  showMeasureLinks="";
	String [] sites = null;
	String [] segments = null;
	String  months ="";
	String  never  = "";
	String  execCommands="";
	String timVal = "";

	EgServicesInfo servicesInfo = new EgServicesInfo("manager");
	boolean isFilterMailAlertsEnabled = servicesInfo.isFilterMailAlertsEnabled();
	servicesInfo = null;

	boolean flag_createuser;
	boolean flag_savealarm;
	boolean flag_siteadd;
	boolean flag_segadd;
	boolean flag_monuser;
	String  remotecontrolenabled="false";
	EgUserPreferences eg_pref = null;
	String uiFile = "eg_ui.ini";
	String s_iniFile_dir = EgInstallInfo.getInstallDir()+ "/manager/config/";
	IniFile egUI = new IniFile(s_iniFile_dir + uiFile);
	String currentDateFormat = egUI.getValue("CURRENT_DATE_FORMAT","selectedDateFormat");
	String dispDate = null;
	String comFormat = null;
	
	Vector sess_vec = new Vector();
	String domainName=request.getParameter("domain");
	if (domainName==null || domainName.equals("null"))
		domainName="";
	String idpName=request.getParameter("idpName");
	if (idpName==null || idpName.equals("null"))
		idpName="";
	uname=request.getParameter("uname");
	uname = com.egurkha.util.StringUtils.decodeSecurityChar(uname);
	upass=request.getParameter("upass");
	upass = com.egurkha.util.StringUtils.decodeSecurityChar(upass);
	upass = upass.trim();
	timVal = request.getParameter("timeOpt");
	
	boolean hasSsoLoginEnabled = true;
	IniFile ssoIniObj = new IniFile(s_iniFile_dir+"eg_samlsso.ini");
	String enableSSOLogin = ssoIniObj.getValue("SAML_SSO","SSO_ENABLED");
	if(enableSSOLogin!=null && (enableSSOLogin.equalsIgnoreCase("yes") || enableSSOLogin.equalsIgnoreCase("true")))
	{
		hasSsoLoginEnabled = true;
	}
	rootObj.put("isSAMLLoginEnabled",hasSsoLoginEnabled);

	
	userAuthentication=request.getParameter("authentication");
	if (StringUtils.isNull(userAuthentication) && hasSsoLoginEnabled)
	{
		userAuthentication=request.getParameter("authenticationSAML");
	}

	/* code for 2fa starts here */
	boolean isSSOSelected = false;
	if (userAuthentication == null || userAuthentication.equalsIgnoreCase("Domain") || userAuthentication.equalsIgnoreCase("Eg"))
	{
		isSSOSelected = false;
	}
	else if (userAuthentication != null && userAuthentication.equalsIgnoreCase("SAML"))
	{
		isSSOSelected = true;
	}
	/* code for 2fa ends here */

	ArrayList extensionList = new ArrayList();
	extensionList.add("gif");
	extensionList.add("jpeg");
	extensionList.add("jpg");
	extensionList.add("png");

	String operationType=request.getParameter("operation");
	String grpName=request.getParameter("grpname");
	String loginLogo=request.getParameter("loginImageUploadStatusForAudit");
	String monitorLogo=request.getParameter("monitorImageUploadStatusForAudit");
	String reporterLogo=request.getParameter("reporterImageUploadStatusForAudit");
	String configLogo=request.getParameter("configMgmtImageUploadStatusForAudit");

	if (operationType != null && operationType.equalsIgnoreCase("Groupname"))
	{
		grpName = uname;
		uname = "";
	}

	String[] logoCheck;
	String config_repo_image="s";
	if((reporterLogo!=null && reporterLogo.equals("yes")) || (configLogo!=null && configLogo.equals("yes")))
	{
		config_repo_image="d";
	}
	logoCheck = request.getParameterValues("logoCheck");
	if(logoCheck!=null && logoCheck.length>0)
	{
		String check=logoCheck[0];
		if(check.equals("yes"))
		{
			if(monitorLogo.equals("yes"))
			{
				reporterLogo="yes";
				configLogo="yes";
				String tempstruname=uname;
				if (isSSOSelected)
				{
					tempstruname=idpName.toLowerCase()+"_"+tempstruname;
				}
				else if (operationType != null && (operationType.equalsIgnoreCase("Group") || operationType.equalsIgnoreCase("Groupname")))
				{
					if (grpName != null && grpName.length() > 0)
					{
						//grpName = StringUtils.replace(grpName," ","");
						tempstruname = domainName.toLowerCase()+"_"+grpName;
					}
				}
				else
				{
					if(domainName!=null && !domainName.equals(""))
					{
						tempstruname = StringUtils.replace(tempstruname," ","");
						tempstruname=domainName.toLowerCase()+"_"+tempstruname;
					}
				}
				
				tempstruname = StringUtils.replace(tempstruname," ","");

				String extension = "";

				for (int ext = 0; ext < extensionList.size(); ext++)
				{
					String strExtension = (String)extensionList.get(ext);
					File sourceFile = new File(EgInstallInfo.getInstallDir()+"/manager/tomcat/webapps/final/monitor/eg_images/"+tempstruname+"_monitor."+strExtension);
					if (sourceFile.exists())
					{
						extension = strExtension;
						break;
					}
				}

				String mointorPath=EgInstallInfo.getInstallDir()+"/manager/tomcat/webapps/final/monitor/eg_images/"+tempstruname+"_monitor."+extension;
				String reporterPath=EgInstallInfo.getInstallDir()+"/manager/tomcat/webapps/final/reporter/images/"+tempstruname+"_reporter."+extension;
				String configPath=EgInstallInfo.getInstallDir()+"/manager/tomcat/webapps/final/config/images/"+tempstruname+"_config."+extension;

				try
				{
					File monitorFile=new File(mointorPath);
					File reporterFile=new File(reporterPath);
					File configFile=new File(configPath);
					
					InputStream inStream = new FileInputStream(monitorFile);
					OutputStream outStream1 =new FileOutputStream(reporterFile);
					OutputStream outStream2=new FileOutputStream(configFile);
					
					byte fileContent[] = new byte[(int)monitorFile.length()];
					int length=fileContent.length;
					inStream.read(fileContent);
					//baos.read(fileContent);
					outStream1.write(fileContent, 0, length);
					outStream2.write(fileContent, 0, length);

					inStream.close();
					outStream1.close();
					outStream2.close();

					if(EgInstallInfo.isClusterSupported)
					{
						//If clustering is supported inform other managers about the new Image.
						UploadCustomImage customImage = new UploadCustomImage();
						String s_dstFile1="manager/tomcat/webapps/final/reporter/images/"+tempstruname+"_reporter."+extension;
						String s_dstFile2="manager/tomcat/webapps/final/config/images/"+tempstruname+"_config."+extension;
						customImage.getCustomImage(s_dstFile1,fileContent);
						customImage.getCustomImage(s_dstFile2,fileContent);
						customImage = null;
					}
				}
				catch(Exception er)
				{
					er.printStackTrace();
					System.out.println("Error in creating duplicate logos for config "+er);
				}
			}
		}
		else
		{
			config_repo_image="d";
		}
	}
	else
	{
		config_repo_image="d";
	}
	if (userAuthentication==null || userAuthentication.equalsIgnoreCase("Eg"))
	{
		upass=EgCrypt.encrypt(upass);
		domainName="";
	}
	else if (userAuthentication.equalsIgnoreCase("SAML"))
	{
		uname = "samlsso/"+idpName +"/"+uname;
		upass="NONE";
		upass=EgCrypt.encrypt(upass);
		domainName="";
	}
	else
	{
		if (operationType != null && (operationType.equalsIgnoreCase("Group") || operationType.equalsIgnoreCase("Groupname")))
		{
			if (grpName != null && grpName.length() > 0)
			{
				uname = domainName + "/Grp/" + grpName;
			}
		}
		else
		{
			uname=domainName+"/"+uname;
		}
		upass="NONE";
		upass=EgCrypt.encrypt(upass);
	}

	if (uname != null && uname.indexOf("'") != -1)
	{
		String tempUser = uname;
		uname = StringUtils.replace(uname,"'","^");
		IniFile ini_write = EgConfigFilesSync.getInstance(EgInstallInfo.getInstallDir() + "/manager/config/eg_ui.ini",true);
		ini_write.setValue("USER_DBUSER_MAP",tempUser,uname);
		ini_write.setValue("DBUSER_USER_MAP",uname,tempUser); // reverse user mapping
		ini_write.saveFile();
		EgConfigFilesSync.releaseInstance(ini_write);
	}
	utype=request.getParameter("utype");
	tomailid=request.getParameter("tomailid");
	ccmailid=request.getParameter("ccmailid");
	bccmailid=request.getParameter("bccmailid");
	escmailid=request.getParameter("escmailid");
	never = request.getParameter("Never");
	String changePwd = request.getParameter("changePwd");
	if (changePwd == null || changePwd.trim().length() == 0)
	{
		changePwd = "false";
	}
	if ((userAuthentication == null || userAuthentication.equalsIgnoreCase("Eg")) && changePwd != null && changePwd.trim().length() > 0)
	{
		IniFile mgrMiscIni = EgConfigFilesSync.getInstance(EgInstallInfo.getInstallDir() + "/manager/config/eg_mgrmisc.ini",true);
		mgrMiscIni.setValue("CHANGE_PASSWORD",uname,changePwd);
		mgrMiscIni.saveFile();
		EgConfigFilesSync.releaseInstance(mgrMiscIni);
	}

	if (utype == null)
	{
		utype = "EnterpriseAdmin";
	}

	uvalidtill = request.getParameter("tilldate");
	String timeZone = request.getParameter("timeZone");
	String dateFormat=request.getParameter("userDataFormat");
	String timeZoneAndDateFormat=null;
	String mailSender = request.getParameter("mailSenders");
	uvalidtill=request.getParameter("dateforpro");
	String count1=request.getParameter("count");
	execCommands=request.getParameter("execcommands");
	customScript=request.getParameter("customScript");
	int cnt=Integer.parseInt(count1);
	
	userModel = request.getParameter("userModel");
	rootObj.put("userModel",userModel);

	IniFile egMgrMisc = new IniFile(EgInstallInfo.getInstallDir() + "/manager/config/eg_mgrmisc.ini");

	String ShareCompsAcrossOU = egMgrMisc.getValue("MISC_ARGS","ShareCompsAcrossOU");
	if (ShareCompsAcrossOU != null && ShareCompsAcrossOU.trim().length() > 0)
	{
		rootObj.put("ShareCompsAcrossOU",ShareCompsAcrossOU);
	}
	else
	{
		rootObj.put("ShareCompsAcrossOU","false");
	}

	org = request.getParameter("org");
	org = com.egurkha.util.StringUtils.decodeSecurityChar(org);
	IniFile egUUID = new IniFile(s_iniFile_dir + "eg_uuid.ini");
	EgUuidInfo egUuidInfo = new EgUuidInfo();

	Vector getAllRoles = EgUserRole.getAllRoles();

	boolean isShareRole = false;
	if (org != null && !org.equalsIgnoreCase("egenterprise"))
	{
		isShareRole = egUuidInfo.isShareRole(utype,getAllRoles);
	}
	rootObj.put("isShareRole",isShareRole);

	if (org == null)
	{
		String userId = _user.getLoginID();
		if (!egUuidInfo.isUser(userId))
		{
			org = userId;
		}
		else
		{
			org = egUuidInfo.getDirectDependentOU(userId);
		}
	}

	// added for all component access and monitor access is true 
	// if allcomp acces is false show services and seg , if monitor access is true show alarms,notify.msgmode,remote control
	EgUserRole eg = EgUserRole.getRoleObject(utype,getAllRoles);
	boolean hasmonitoraccess = eg.hasMonitorAccess();
	boolean hasallcompaccess = eg.hasAllComponentAccess();
	rootObj.put("hasallcompaccess",new Boolean(hasallcompaccess));
	rootObj.put("hasmonitoraccess",new Boolean(hasmonitoraccess));

	if(hasmonitoraccess)
	{
		high=request.getParameter("high");
		low=request.getParameter("low");
		medium=request.getParameter("medium");
	}

	String mailShift = request.getParameter("mailshift");
	String smsShift = request.getParameter("smsshift");
	String escShift = request.getParameter("escshift");
	String execshift = request.getParameter("Execshift");

	String measureInMailMode = request.getParameter("measure_in_mail_mode");
	String ddInMailMode = request.getParameter("dd_in_mail_mode");

	String mailFilterOption = request.getParameter("mail_filter_option");
	mailFilterOption = (mailFilterOption==null || mailFilterOption.trim().length()==0)?"All_Elements":mailFilterOption;

	mailShift = (mailShift != null && mailShift.length()>0)?mailShift:"no";
	smsShift = (smsShift != null && smsShift.length()>0)?smsShift:"no";
	escShift = (escShift != null && escShift.length()>0)?escShift:"no";
	execshift = (execshift !=null && execshift.length()>0)?execshift:"no";
	measureInMailMode = (measureInMailMode==null)?"NO":measureInMailMode;
	if(measureInMailMode!=null && measureInMailMode.trim().length()==0)
		measureInMailMode="NO";
	ddInMailMode = (ddInMailMode==null)?"NO":ddInMailMode;
	if(ddInMailMode!=null && ddInMailMode.trim().length()==0)
		ddInMailMode="NO";
	ArrayList daysList = new ArrayList();
	ArrayList shiftsList = new ArrayList();
	boolean isAlarmEnabled = true;

	//if(high == null  && low == null && medium == null)
	//{
	//	isAlarmEnabled = false;
	//}

	if((high == null || high == "") && (low == null || low == "") && (medium == null || medium == ""))
	{
		isAlarmEnabled = false;
	}

	if (!isAlarmEnabled || mailShift.equals("no"))
	{
		mailShift = "default";
	}
	else
	{
		daysList = new ArrayList();
		shiftsList = new ArrayList();
		for (int i=0;i<5;i++)
		{
			String tmpDay = request.getParameter("mailday"+i);
			if (tmpDay == null)
				continue;

			String tmpShift = request.getParameter("mailshift"+i);
			daysList.add(tmpDay);
			shiftsList.add(tmpShift);
		}
		mailShift = getShiftPeriods(daysList,shiftsList);
	}

	if (!isAlarmEnabled || smsShift.equals("no"))
	{
		smsShift = "default";
	}
	else
	{
		daysList = new ArrayList();
		shiftsList = new ArrayList();
		for (int i=0;i<5;i++)
		{
			String tmpDay = request.getParameter("smsday"+i);
			if (tmpDay == null)
				continue;

			String tmpShift = request.getParameter("smsshift"+i);
			daysList.add(tmpDay);
			shiftsList.add(tmpShift);
		}
		smsShift = getShiftPeriods(daysList,shiftsList);
	}

	if (!isAlarmEnabled || escShift.equals("no"))
	{
		escShift = "default";
	}
	else
	{
		daysList = new ArrayList();
		shiftsList = new ArrayList();
		for (int i=0;i<5;i++)
		{
			String tmpDay = request.getParameter("escday"+i);
			if (tmpDay == null)
				continue;
			String tmpShift = request.getParameter("escshift"+i);
			daysList.add(tmpDay);
			shiftsList.add(tmpShift);
		}
		escShift = getShiftPeriods(daysList,shiftsList);
	}
	if(!isAlarmEnabled || execshift.equals("no"))
	{
		execshift="default";
	}
	else
	{
		daysList = new ArrayList();
		shiftsList = new ArrayList();
		for (int i=0;i<5;i++)
		{
			String tmpDay = request.getParameter("Execday"+i);
			if (tmpDay == null)
				continue;
			String tmpShift = request.getParameter("Execshift"+i);
			daysList.add(tmpDay);
			shiftsList.add(tmpShift);
		}
		execshift = getShiftPeriods(daysList,shiftsList);
	}

	// aruna - modified - start
	StringTokenizer token = new StringTokenizer (ccmailid, comma);
	StringBuffer ccmail = new StringBuffer();
	StringBuffer bccmail = new StringBuffer();

	int tempcount = token.countTokens();
	String cc = "cc:";
	for (int i=0;token.hasMoreTokens(); i++)
	{
		cctemp = token.nextToken();
		ccmail.append (cc);
		ccmail.append (cctemp);
		//if (i+1 < count)
		if(tempcount!=(i+1))
			ccmail.append (comma);
	}
	token = new StringTokenizer (bccmailid, comma);
	tempcount = token.countTokens();
	String bcc = "bcc:";
	for (int i=0;token.hasMoreTokens(); i++)
	{
		bcctemp = token.nextToken();
		bccmail.append (bcc);
		bccmail.append (bcctemp);

		//if (i+1 < count)
		if(tempcount!=(i+1))
			bccmail.append (comma);
	}

	if(tomailid != null && !tomailid.equals(""))
	{
		mailid = "To:" + tomailid;
	}
	if(ccmail != null && !((ccmail.toString()).equals("")))
	{
		mailid = mailid+comma+ccmail.toString();
	}
	if(bccmail != null && !((bccmail.toString()).equals("")))
	{
		mailid = mailid+comma+bccmail.toString();
	}
	// aruna - modified - end

	if(hasmonitoraccess)
	{
		StringTokenizer stoken = new StringTokenizer (ccmailid, comma);
		//stoken = new StringTokenizer (bccmailid, ",");
		
		// aruna - modified - start
		//StringBuffer ccmail = new StringBuffer();
		//StringBuffer bccmail = new StringBuffer();
		// aruna - modified - end

		StringBuffer moreEscMail=new StringBuffer();
		StringBuffer escmail = new StringBuffer();
		StringBuffer ScriptBuff=new StringBuffer();//add by sunder
		if(high != null || low != null || medium != null)
		{
			int count = stoken.countTokens();

			// aruna - modified - start
			//String cc = "cc:";
			//for (int i=0;stoken.hasMoreTokens(); i++)
			//{
				//cctemp = stoken.nextToken();
				//ccmail.append (cc);
				//ccmail.append (cctemp);
				////if (i+1 < count)
				//if(count!=(i+1))
					//ccmail.append (comma);
			//}
			//stoken = new StringTokenizer (bccmailid, comma);
			//count = stoken.countTokens();
			//String bcc = "bcc:";
			//for (int i=0;stoken.hasMoreTokens(); i++)
			//{
				//bcctemp = stoken.nextToken();
				//bccmail.append (bcc);
				//bccmail.append (bcctemp);

				////if (i+1 < count)
				//if(count!=(i+1))
					//bccmail.append (comma);
			//}
			// aruna - modified - end
			
				stoken = new StringTokenizer (customScript, comma);
				count = stoken.countTokens();
				String script="cmd:";
				for (int i=0;stoken.hasMoreTokens(); i++)
				{
					scrtemp = stoken.nextToken();
					ScriptBuff.append (script);
					ScriptBuff.append (scrtemp);

					if(count!=(i+1))
						ScriptBuff.append (comma);
				}
			if(escmailid!=null && !escmailid.equals(""))
			stoken = new StringTokenizer (escmailid, comma);
			count = stoken.countTokens();
			StringTokenizer colonTokens = null;
			String escColon = null, esctemp = null, escStr = null;
			String colon = ":";
			String ESC = "Esc1";

			for (int i=0;stoken.hasMoreTokens(); i++)
			{
				esctemp = stoken.nextToken();
				colonTokens = new StringTokenizer (esctemp, colon);
				if (colonTokens.countTokens() == 2)
				{
					escStr = ESC+colonTokens.nextToken();
				}
				escmail.append(ESC).append(colon).append(colonTokens.nextToken());
				//if (i+1 < count)
				if(count!=(i+1))
					escmail.append (comma);
			}
			for(int j=0;j<cnt;j++)
			{
				String mail=request.getParameter("email"+j);
				if(mail!=null)
				{
					stoken = new StringTokenizer (mail, comma);
					ESC = "Esc"+(j+2);
					count = stoken.countTokens();
					StringBuffer sb=new StringBuffer();
					
					for (int k=0;stoken.hasMoreTokens(); k++)
					{
						esctemp = stoken.nextToken();
						sb.append(ESC).append(colon).append(esctemp);
					  if(count!=(k+1))
						sb.append (comma);
					}
					moreEscMail.append(sb.toString());
					//if(cnt!=(j+1))
					if (j+1 < cnt)
						moreEscMail.append(comma);
				}
			}
		}
		//else
		//{
			//tomailid ="";
		//}
	
		//mailid = "To:" + tomailid + comma +ccmail.toString() + bccmail.toString() + escmail.toString()+comma+moreEscMail.toString();
	
		// aruna - modified - start
		//if(tomailid != null && !tomailid.equals(""))
		//{
			//mailid = "To:" + tomailid;
		//}
		//if(ccmail != null && !((ccmail.toString()).equals("")))
		//{
			//mailid = mailid+comma+ccmail.toString();
		//}
		//if(bccmail != null && !((bccmail.toString()).equals("")))
		//{
			//mailid = mailid+comma+bccmail.toString();
		//}
		// aruna - modified - end
		if(escmail != null && !((escmail.toString()).equals("")))
		{
			mailid = mailid+comma+escmail.toString();
		}
		if(moreEscMail != null && !((moreEscMail.toString()).equals("")))
		{
			mailid = mailid+comma+moreEscMail.toString();
		}
		if(ScriptBuff!=null && !((ScriptBuff.toString()).equals("")))
		{
			mailid=mailid+comma+ScriptBuff.toString();
		}
	}

	// aruna - modified - start
	//if(!hasmonitoraccess)
	//{
		//mailid = "";
	//}
	// aruna - modified - end

	boolean remoteEnabled = EgMemInfo.remoteEnabled;

	if(hasmonitoraccess)
	{
		notify=request.getParameter("notify");
		if(notify==null) notify="-";
		msgmode=request.getParameter("msgmode");	
		
		if(msgmode==null) msgmode="-";

		if (utype != null && !utype.equals("AlarmViewer") && !utype.equals("SuperAlarmViewer") && remoteEnabled)
		{
			remotecontrolenabled=request.getParameter("remotecontrol");
			if (remotecontrolenabled != null && remotecontrolenabled.equalsIgnoreCase("true"))
			{
				remotecontrolenabled=remotecontrolenabled+"#"+execCommands;
			}
		}
		if(high != null)
			alerttype +="H";
		if(medium != null)
			alerttype += "I";
		if(low != null)
			alerttype += "L";

		alarm_h = request.getParameter("alarm_h");
		alarm_m = request.getParameter("alarm_m");
		alarm_l = request.getParameter("alarm_l");
		if(alarm_h!=null)
			alarm_type += alarm_h;
		if(alarm_m!=null)
			alarm_type  += alarm_m;
		if(alarm_l!=null)
			alarm_type += alarm_l;
		eg_pref = EgUserPreferences.getUserPreferences(uname);
	}

	AuditLogThread auditLogThread = new AuditLogThread();
	auditLogThread.setValue("Category","Admin");
	auditLogThread.setValue("User_id",_user.getLoginID());
	auditLogThread.setValue("Host_ip",_user.getUserIP(session.getId()));
	auditLogThread.setValue("Session_id",session.getId());
	auditLogThread.setValue("Module","User Management");	

	try
	{
		str_usercon=user.setConnection();
		flag_monuser=user.checkMonitorUser(); // has to be defined and monitor count monUserCount() query has to be changed in //UserBean class
		if(!flag_monuser)
		{
			user.releaseConnection(false);
			auditLogThread.setValue("Description","You have exceeded the number of users allowed by your license!");
			auditLogThread.setValue("Activity","Add User");		
			auditLogThread.sendItToDB();

			rootObj.put("requestStatus","failed");
			errorObj.put("title",_mapping.getTextDescription("admin.error.Add new user"));
			errorObj.put("message1",_mapping.getTextDescription("admin.error.You have exceeded the number of users allowed by your license"));
			errorObj.put("message2",_mapping.getTextDescription("admin.error.To support additional users")+", "+_mapping.getTextDescription("admin.error.please contact")+" <b class='font_bold'>license@eginnovations.com</b>");
			rootObj.put("errors",errorObj);
			out.println(rootObj.toString());
			return;
		}
		if((never != null) && (never.equals("Never")))
			uvalidtill = "12/12/9999";

		flag_createuser=updateAndTransmitUserInfo.addUser(uname,upass,utype,uvalidtill,mailid,alerttype,notify,msgmode,remotecontrolenabled,timVal);
		
		if (org.equalsIgnoreCase("egenterprise"))
		{
			org = org.toLowerCase();
		}

		if(flag_createuser)
		{
			IniUI ui = (IniUI)com.egurkha.ini.IniUI.getInstance();
			String refreshTime = ui.getRefreshTime("Default");

			if(refreshTime==null || refreshTime.length()==0)
			refreshTime = "60";

			String user_id = request.getParameter("uname");
			String timelineVal = request.getParameter("timeOpt");
			String language = request.getParameter("langName");
			if(language!=null && language.trim().length()>0)
				language.trim();
			String alarmdelete = request.getParameter("alarmdelete");
			String acknowledgment = request.getParameter("acknowledgment");
			newWindow = request.getParameter("newWindow");
			String monitorHomePage = request.getParameter("monitorHomePage");

			IniFile uuuidIni_write = EgConfigFilesSync.getInstance(EgInstallInfo.getInstallDir() + "/manager/config/eg_uuid.ini",true);
			if (userModel.equalsIgnoreCase("User"))
			{
				uuuidIni_write.setValue("ORGANIZATION_MAPPING",uname,org);
				boolean isShareRoleUser = false;
				if (org != null && !org.equalsIgnoreCase("egenterprise"))
				{
					isShareRoleUser = egUuidInfo.isShareRole(utype,getAllRoles);
				}
				if (isShareRoleUser)
				{
					ArrayList aListUserAttributes = new ArrayList();
					ArrayList aListCategoriesForReplication = new ArrayList();
					aListUserAttributes.add(uname);
					aListUserAttributes.add(upass);
					aListUserAttributes.add(uvalidtill);
					aListUserAttributes.add(mailid);

					aListUserAttributes.add(timeZone);
					aListUserAttributes.add(language);

					aListUserAttributes.add(org);

					aListCategoriesForReplication.add("Infrastructure_Elements");
					//aListCategoriesForReplication.add("Maintenance_Policies");

					EgCloneUser EgCloneUserObj = new EgCloneUser(org,uname,upass);
					EgCloneUserObj.setAttributes(aListUserAttributes,aListCategoriesForReplication);
					ArrayList clonedResults = EgCloneUserObj.cloneUser();
				}
			}
			else if (userModel.equalsIgnoreCase("Organization") || userModel.equalsIgnoreCase("SubOrganization"))
			{
				String uuidKey = GoogleAuthenticator.getRandomSecretKey();
				uuidKey = StringUtils.replace(uuidKey," ","");

				boolean check = false;
				String existingUUID [] = uuuidIni_write.getVariables("UUID");
				ArrayList randomKey = existingUUID == null?new ArrayList():new ArrayList(Arrays.asList(existingUUID));

				if (randomKey != null && randomKey.size() > 0)
				{
					while (!check)
					{
						boolean flag = randomKey.contains(uuidKey);
						if (flag)
						{
							uuidKey = GoogleAuthenticator.getRandomSecretKey();
						}
						else
						{
							check = true;
							break;
						}
					}
				}
				uuuidIni_write.setValue("UUID",uuidKey,EgCrypt.encrypt(uname+"\""+uvalidtill));
				uuuidIni_write.setValue("ORG_EXPIRY_DATE",uname,uvalidtill);

				if (userModel.equalsIgnoreCase("Organization"))
				{
					uuuidIni_write.setValue("ORG_UUID",uname,uuidKey);
				}
				else
				{
					uuuidIni_write.setValue("ORGANIZATION_MAPPING",uname,org);
					if (egUuidInfo.isSuperOrg(org))
					{
						uuuidIni_write.setValue(org,uname,uuidKey);
					}
					else
					{
						String superOrgName = egUuidInfo.getSuperOU(org);
						uuuidIni_write.setValue(superOrgName,uname,uuidKey);
					}
				}

				//set default license - start
				boolean isMgrConcUserBased = EgInstallInfo.isconcurrentUserLicense;
				boolean isMgrNamedUserBased = EgInstallInfo.isnamedUserLicense;
				String isMgrUsedBased = "false";

				if (isMgrConcUserBased || isMgrNamedUserBased)
				{
					isMgrUsedBased = "true";
				}

				String orgNameForLicenseCheck = "egenterprise";
				if (!userModel.equalsIgnoreCase("Organization"))
				{
					orgNameForLicenseCheck = org;
				}

				//getting total license count of manager
				CertValidator cert = new CertValidator();
				int totalMonitorsCount = cert.getAllowedTotalCount();
				int basicMonitorsCount = cert.getAllowedBasicCount();
				int networkMonitorsCount = cert.getAllowedNetworkDevicesCount();
				int userBasedCount = 0;
				int monitorUsersCount = EgMemInfo.users;
				
				EgUsersInfo obj = new EgUsersInfo();
				ArrayList aListData = null;
				if (isMgrUsedBased.equalsIgnoreCase("true"))
				{
					long mgrConcUserCount = EgInstallInfo.allowedConcUsers;
					long mgrNamedUserCount = EgInstallInfo.allowedNamedUsers;
					String AllowedCount = isMgrConcUserBased ? String.valueOf(mgrConcUserCount) : String.valueOf(mgrNamedUserCount);
					if (!AllowedCount.equals("-"))
					{
						userBasedCount = Integer.parseInt(AllowedCount);
					}
					aListData = obj.getRemoteUserCount();
					if (aListData == null || aListData.size() ==0)
					{
						aListData = obj.getRemoteUserCount(true);
					}
					if(aListData != null && aListData.size()>0)
					{
						AllowedCount = (String)aListData.get(1);
						userBasedCount = Integer.parseInt(AllowedCount);
					}
					
					if (AllowedCount.equals("-") || AllowedCount.equals("-1"))
					{
						userBasedCount = -1;
					}
				}

				ArrayList dependentOuLicenseList = new ArrayList();
				dependentOuLicenseList.add(String.valueOf(totalMonitorsCount));
				dependentOuLicenseList.add(String.valueOf(basicMonitorsCount));
				dependentOuLicenseList.add(String.valueOf(networkMonitorsCount));
				dependentOuLicenseList.add(String.valueOf(userBasedCount));
				dependentOuLicenseList.add(String.valueOf(monitorUsersCount));

				IniFile userCompMapIniread = new IniFile(EgInstallInfo.getInstallDir()+"/manager/config/eg_usercompmapping.ini");
				String[] userNameVars = userCompMapIniread.getVariables("Users_Allowed_Count");
				ArrayList availUsersList = new ArrayList(Arrays.asList(userNameVars));

				ArrayList userAllowedLimits = new ArrayList();

				if (availUsersList.contains(orgNameForLicenseCheck))
				{
					String value = userCompMapIniread.getValue("Users_Allowed_Count",orgNameForLicenseCheck);
					value = EgCrypt.decrypt(value);
					userAllowedLimits = StringUtils.egTokenizer(value,"#");
				}
				else
				{
					List orgNames = egUuidInfo.getOrgNames(orgNameForLicenseCheck);
					for (int i=0; i<orgNames.size(); i++)
					{
						String orgName = orgNames.get(i).toString().trim();
						String value = userCompMapIniread.getValue("Users_Allowed_Count",orgName);
						if (value != null && value.length()>0)
						{
							value = EgCrypt.decrypt(value);
							userAllowedLimits = StringUtils.egTokenizer(value,"#");
							break;
						}
					}
				}

				if (userAllowedLimits != null && userAllowedLimits.size() > 0)
				{
					String totMonDef = userAllowedLimits.get(0).toString();
					String basicMonDef = userAllowedLimits.get(1).toString();
					String networkDevDef = userAllowedLimits.get(2).toString();
					String userBasedDef = "";
					String userCntDef = "";
					if (isMgrUsedBased.equalsIgnoreCase("true") || userAllowedLimits.size()==5)
					{
						userBasedDef = userAllowedLimits.get(3).toString();
						userCntDef = userAllowedLimits.get(4).toString();
					}
					else
					{
						userBasedDef = "0";
						userCntDef = userAllowedLimits.get(3).toString();
					}

					dependentOuLicenseList = new ArrayList();
					dependentOuLicenseList.add(totMonDef);
					dependentOuLicenseList.add(basicMonDef);
					dependentOuLicenseList.add(networkDevDef);
					dependentOuLicenseList.add(userBasedDef);
					dependentOuLicenseList.add(userCntDef);
				}

				String value = "";
				//String defaultLicenseVar [] = egMgrMisc.getVariables("DEFAULT_LICENSING_POLICY");
				String defaultLicenseVar [] = new String[]{"TotalMonitors","BasicMonitors","NetworkDevices","UserBased","MonitorUsers"};
				if (defaultLicenseVar != null && defaultLicenseVar.length > 0)
				{
					for (int i=0;i<defaultLicenseVar.length;i++)
					{
						String licenceStr = defaultLicenseVar[i];
						String licenseCount = egMgrMisc.getValue("DEFAULT_LICENSING_POLICY",licenceStr);
						if (licenceStr.equalsIgnoreCase("UserBased") && isMgrUsedBased.equalsIgnoreCase("false"))
						{
							value += "0" + "#";
						}
						else
						{
							if (dependentOuLicenseList != null && dependentOuLicenseList.size() > 0)
							{
								String ouLicenseLimit = (String)dependentOuLicenseList.get(i);
								if (!licenseCount.equalsIgnoreCase(ouLicenseLimit))
								{
									int ouLicenseCnt = Integer.parseInt(ouLicenseLimit);
									int licenseCnt = Integer.parseInt(licenseCount);
									if (ouLicenseCnt != -1 && ouLicenseCnt < licenseCnt)
									{
										licenseCount = String.valueOf(ouLicenseCnt);
									}
								}
							}
							value += licenseCount + "#";
						}
					}
					value = value.substring(0,value.length()-1);
					value = EgCrypt.AESencrypt(value);

					if (value != null && !value.equals(""))
					{
						IniFile userCompMapIni = EgConfigFilesSync.getInstance(EgInstallInfo.getInstallDir()+"/manager/config/eg_usercompmapping.ini");
						userCompMapIni.setValue("Users_Allowed_Count",uname,value);
						userCompMapIni.saveFile();
						EgConfigFilesSync.releaseInstance(userCompMapIni);
					}
				}
				//set default license - end
			}
			String interestedDomains=request.getParameter("interestedDomains");
			if (interestedDomains != null && interestedDomains.length() > 0)
			{
				uuuidIni_write.setValue("COMPONENT_TYPE_PREFERENCES",uname,interestedDomains);
			}
			uuuidIni_write.saveFile();
			EgConfigFilesSync.releaseInstance(uuuidIni_write);

			if (interestedDomains != null && interestedDomains.length() > 0)
			{
				String dispInterestedDomains = "";
				StringTokenizer st = new StringTokenizer(interestedDomains,",");
				while (st.hasMoreTokens())
				{
					dispInterestedDomains = dispInterestedDomains + _mapping.getComponentTypeDescription(st.nextToken()) + ",";
				}
				if (dispInterestedDomains.endsWith(","))
				{
					dispInterestedDomains = dispInterestedDomains.substring(0,dispInterestedDomains.length()-1);
				}
				auditLogThread.setCurrentValue("24~~Auto associate component types",dispInterestedDomains);
			}

			// null check done by aruna - start
			String tmpMonitorHomePage = "";
			if(monitorHomePage != null)
			{
				tmpMonitorHomePage = new String(monitorHomePage);
			}
			// null check done by aruna - end
			String monitorHomePageOption = request.getParameter("selectedMonHomeOpt");
			if(StringUtils.isNull(monitorHomePageOption))
				monitorHomePageOption="default";
			if(monitorHomePage==null || monitorHomePage.trim().length()==0 || (monitorHomePageOption != null && monitorHomePageOption.equalsIgnoreCase("dynamic")))
			{
				String user_role_name=eg.getRoleName();
				if(user_role_name!=null && (user_role_name.equals("AlarmViewer") || user_role_name.equals("SuperAlarmViewer")))
				{
					monitorHomePage="AlarmViewer";
				}
				else
				{
					monitorHomePage="Monitor Dashboard";
				}
			}

			//**Dashboard privilege permission--starts**//

			String userDashboardCreationPrivilege = request.getParameter("dashboardPrivilege");			
			String privilegeEntry = "yes";
			if(userDashboardCreationPrivilege != null && userDashboardCreationPrivilege.equalsIgnoreCase("false"))
			{
			   privilegeEntry = "no";
			}
			
			IniFile customDashboardIniObj = EgConfigFilesSync.getInstance(EgInstallInfo.getInstallDir() + "/manager/config/eg_customdashboard.ini",true);

			customDashboardIniObj.setValue("USER_DASHBOARD_CREATION_PRIVILEGE",uname,privilegeEntry);
			customDashboardIniObj.saveFile();

			EgConfigFilesSync.releaseInstance(customDashboardIniObj);

			auditLogThread.setCurrentValue("25~~Allow user to create mydashboard",privilegeEntry.equalsIgnoreCase("yes")?"Yes":"No");

			//**Dashboard privilege permission--ends**//
			//showMeasureLinks = request.getParameter("measureLink");
			showMeasureLinks = "false";

			/*Description Field- start*/
			IniFile egMgrMiscWr = EgConfigFilesSync.getInstance(EgInstallInfo.getInstallDir() + "/manager/config/eg_mgrmisc.ini",true);
			String isDescEnabled = egMgrMiscWr.getValue("MISC_ARGS","ShowUserDescription");
			if(isDescEnabled != null && isDescEnabled.equalsIgnoreCase("yes"))
			{
				String description = request.getParameter("description");
				if(description != null && description.length()>0)
				{
					egMgrMiscWr.setValue("USER_DESCRIPTION",uname,description);
					egMgrMiscWr.saveFile();
				}
			}
			/* User Password History Storage - STARTS 
			 * by Meena.V
			 */
			if(userAuthentication == null || userAuthentication.equalsIgnoreCase("Eg"))
			{
				String isPwdHistoryEnabled = egUI.getValue("MISC_ARGS","PwdMinHistoryEnable");
				if(isPwdHistoryEnabled != null && (isPwdHistoryEnabled.equalsIgnoreCase("yes") || isPwdHistoryEnabled.equalsIgnoreCase("true")))
				{
					String userPass=request.getParameter("upass");
					if(userPass != null && userPass.length()>0)
					{
						userPass = userPass.trim();
						String userFinalPwdHistoryVal = EgCrypt.encrypt(userPass);
						egMgrMiscWr.setValue("Password_History",uname,userFinalPwdHistoryVal);
						egMgrMiscWr.saveFile();
					}
				}
			}
			/* User Password History Storage - ENDS */
			EgConfigFilesSync.releaseInstance(egMgrMiscWr);
			/*Description Field- end*/
			
			IniFile egUi = new IniFile(EgInstallInfo.getInstallDir() + "/manager/config/eg_ui.ini");
			String aSkin = egUi.getValue("DEFAULT_SKINS","adminSkin");
			String mSkin = egUi.getValue("DEFAULT_SKINS","monitorSkin");
			String rSkin = egUi.getValue("DEFAULT_SKINS","reporterSkin");
			String cSkin = egUi.getValue("DEFAULT_SKINS","configSkin");
			String dSkin = egUi.getValue("DEFAULT_SKINS","desktopSkin");

			if(aSkin==null || aSkin.equals("")) aSkin = "blue";
			if(mSkin==null || mSkin.equals("")) mSkin = "blue";	
			if(rSkin==null || rSkin.equals("")) rSkin = "blue";
			if(cSkin==null || cSkin.equals("")) cSkin = "blue";
			if(dSkin==null || dSkin.equals("")) dSkin = "blue";

			if(language == null || language.equalsIgnoreCase("null") || language.trim().length() == 0 )
			{
				language = egUi.getValue("DEFAULT_LANGUAGE","defaultLanguage");
			}
			String tempstruname=user_id;
			if (operationType != null && (operationType.equalsIgnoreCase("Group") || operationType.equalsIgnoreCase("Groupname")))
			{
				if (grpName != null && grpName.length() > 0)
				{
					tempstruname = domainName.toLowerCase()+"_"+grpName;
				}
			}
			else
			{
				if(domainName!=null && !domainName.equals(""))
				{
					tempstruname=domainName.toLowerCase()+"_"+tempstruname;
				}
			}
			if(loginLogo!=null && loginLogo.equalsIgnoreCase("yes"))
			{
				loginLogo="c";
			}
			else
			{
				loginLogo="d";
				//when logo change to default, delete the logo if it exits 
				
				if(tempstruname!=null && !tempstruname.equals(""))
				{
					for (int ext = 0; ext < extensionList.size(); ext++)
					{
						String strExtension = (String)extensionList.get(ext);
						File fi = new File(EgInstallInfo.getInstallDir()+"/manager/tomcat/webapps/final/admin/eg_images/"+tempstruname+"_login."+strExtension);
						if (fi.exists())
						{
							boolean success = fi.delete();
						}
					}
				}
			}
			if(monitorLogo!=null && monitorLogo.equalsIgnoreCase("yes"))
			{
				monitorLogo="c";
			}
			else
			{
				monitorLogo="d";
				//when logo change to default, delete the logo if it exits 
				if(tempstruname!=null && !tempstruname.equals(""))
				{
					for (int ext = 0; ext < extensionList.size(); ext++)
					{
						String strExtension = (String)extensionList.get(ext);
						File fi = new File(EgInstallInfo.getInstallDir()+"/manager/tomcat/webapps/final/monitor/eg_images/"+tempstruname+"_monitor."+strExtension);
						if (fi.exists())
						{
							boolean success = fi.delete();
						}
					}
				}
			}
			if(reporterLogo!=null && reporterLogo.equalsIgnoreCase("yes"))
			{
				reporterLogo="c";
			}
			else
			{
				reporterLogo="d";
				if(tempstruname!=null && !tempstruname.equals(""))
				{
					for (int ext = 0; ext < extensionList.size(); ext++)
					{
						String strExtension = (String)extensionList.get(ext);
						File fi = new File(EgInstallInfo.getInstallDir()+"/manager/tomcat/webapps/final/reporter/images/"+tempstruname+"_reporter."+strExtension);
						if (fi.exists())
						{
							boolean success = fi.delete();
						}
					}
				}
			}
			if(configLogo!=null && configLogo.equalsIgnoreCase("yes"))
			{
				configLogo="c";
			}
			else
			{
				configLogo="d";
				if(tempstruname!=null && !tempstruname.equals(""))
				{
					for (int ext = 0; ext < extensionList.size(); ext++)
					{
						String strExtension = (String)extensionList.get(ext);
						File fi = new File(EgInstallInfo.getInstallDir()+"/manager/tomcat/webapps/final/config/images/"+tempstruname+"_config."+strExtension);
						if (fi.exists())
						{
							boolean success = fi.delete();
						}
					}
				}
			}

			//String tempLogo=monitorLogo+"\\"+reporterLogo+"\\"+configLogo;
			mailSender = (mailSender != null && mailSender.length()>0)?mailSender:"default";
			String timeZoneOnly=timeZone;
			String dateFormatOnly=dateFormat;
			timeZone=timeZone+"$@$"+dateFormat;
			
			String insertQuery="insert into user_pref values('"+uname+"','"+language+"','"+aSkin+"','"+mSkin+"','"+rSkin+"','"+cSkin+"','"+refreshTime+"','"+monitorHomePage+"','"+alarmdelete+"','"+acknowledgment+"','"+showMeasureLinks+"','"+timeZone+"','"+mailSender+"','"+dSkin+"','"+mailShift+"','"+smsShift+"','"+escShift+"','"+measureInMailMode+"','"+ddInMailMode+"','"+execshift+"','"+loginLogo+"\\"+monitorLogo+"\\"+reporterLogo+"\\"+configLogo+"\\"+config_repo_image+"','"+monitorHomePageOption+"')";

			updateAndTransmitUserInfo.dbupdate(insertQuery);
			if(monitorHomePageOption != null && monitorHomePageOption.equalsIgnoreCase("dynamic"))
			{
				IniFile ini_write1 = EgConfigFilesSync.getInstance(EgInstallInfo.getInstallDir() + "/manager/config/eg_customdashboard.ini",true);
				ini_write1.setValue("USER_DOMAIN_MAPPING",uname,tmpMonitorHomePage);
				ini_write1.saveFile();
				EgConfigFilesSync.releaseInstance(ini_write1);
			}

			if(hasmonitoraccess)
			{
				flag_savealarm = updateAndTransmitUserInfo.setUIAlarms(uname,alarm_type);
			}

			IniFile egUISave = new IniFile(s_iniFile_dir + uiFile);
			String showUsers=egUISave.getValue("ALARM_HISTORY","Show_Users");
			String updateUsersHash = egUISave.getValue("ALARM_HISTORY","UserCompsMapping");
			String curr_date=null;
			if((showUsers!=null && (showUsers.equalsIgnoreCase("true") || showUsers.equalsIgnoreCase("yes"))) || (updateUsersHash!=null && (updateUsersHash.equalsIgnoreCase("true") || updateUsersHash.equalsIgnoreCase("yes"))))
			{
				curr_date=String.valueOf(new java.util.Date());
				if(ecumb.hashLastComponentUserUpdated!=null && ecumb.hashLastComponentUserUpdated.size()>0)
				{
					ecumb.hashLastComponentUserUpdated.put("Updated",(String)curr_date);
				}
				else
				{
					ecumb.hashLastComponentUserUpdated=new Hashtable();
					ecumb.hashLastComponentUserUpdated.put("Updated",(String)curr_date);
				}
			}

			if(EgInstallInfo.isClusterSupported && ((showUsers!=null && (showUsers.equalsIgnoreCase("true") || showUsers.equalsIgnoreCase("yes"))) || (updateUsersHash!=null && (updateUsersHash.equalsIgnoreCase("true") || updateUsersHash.equalsIgnoreCase("yes")))) && curr_date!=null)
			{
				//upload the result file to all other managers
				EgManagersIniForManager mi = EgManagersIniForManager.getInstance();
				if(mi.isPrimaryManager())
				{
					TransmitInfosToAllSMs transmitInfoToSecondaryManagers = null;
					transmitInfoToSecondaryManagers =  TransmitInfosToAllSMs.getInstance();
					Vector param = new Vector();
					param.add(curr_date);

					Vector info = new Vector();
					info.add("UserCompUpdate");
					info.add(param);

					transmitInfoToSecondaryManagers.setData(info);
				}
			}

			/* code for Mail Filter Option starts */
			//- added by Saravanan.A - start
			if(mailFilterOption!=null && mailFilterOption.trim().length()>0)
			{
				IniFile egMAIL = new IniFile(s_iniFile_dir + "eg_mailalert.ini",true);
				boolean isMFO=egMAIL.setValue("MailFilter_Option",uname.trim(),mailFilterOption);
				egMAIL.saveFile();

				if(mailFilterOption !=null && mailFilterOption.equalsIgnoreCase("All_Elements"))
					auditLogThread.setCurrentValue("22~~Configure email/SMS filters for","All elements");
				else if(mailFilterOption !=null && mailFilterOption.equalsIgnoreCase("Descriptors_Only"))
					auditLogThread.setCurrentValue("22~~Configure email/SMS filters for","Descriptors only");
			}
			//---end---


			// for 2fa - start here
			if (!isSSOSelected && is2faCFlagEnabled)
			{
				IniFile egMFAIniFilePtr = EgConfigFilesSync.getInstance(EgInstallInfo.getInstallDir()+"/manager/config/eg_mfa.ini",true);
				String twofaOTPModeFlagVal = egMFAIniFilePtr.getValue("2FA_SETTINGS","TwoFAOTPModeFlag");
				String secretKey = GoogleAuthenticator.getRandomSecretKey();
				String encryptedSecretKey = EgCrypt.encrypt(secretKey);

				String tempUsrMailid = tomailid;
				String encryptedUserID = EgCrypt.encrypt(uname);

				egMFAIniFilePtr.setValue("2FAEnabledUsers",encryptedUserID,encryptedUserID);
				egMFAIniFilePtr.setValue(encryptedUserID,"EnabledMode",EgCrypt.encrypt(twofaOTPModeFlagVal));
				egMFAIniFilePtr.setValue(encryptedUserID,"SecretKey",encryptedSecretKey);

				if (twofaOTPModeFlagVal != null && twofaOTPModeFlagVal.equalsIgnoreCase("ga") && tempUsrMailid != null && tempUsrMailid.trim().length() > 0)
				{
					String mailSubject = "Two Factor Authentication";
					String bodyContent = "2-step verification has been enforced as the security standard enterprise-wide, for securing accesses to the eG Enterprise system. The secret key for your eG Enterprise user name <b>'"+uname+"'</b> is <b>"+secretKey+"</b>. Please refer to the attached document to know how to register this secret key in the Google Authenticator app for generating a time-based OTP. Use the OTP generated by Google authenticator as verification code to validate your eG Enterprise login.";

					EgMailHelper mailObj = new EgMailHelper(tempUsrMailid);
					mailObj.setAttachmentFile(EgInstallInfo.getInstallDir()+"/manager/tomcat/webapps/final/docs/GoogleAuthenticatorGuide.docx");
					int mailStatus = mailObj.sendMail(mailSubject, bodyContent);

					if (mailStatus == 0)
					{
						rootObj.put("TwoFAMailSend","success");
					}
					else if (mailStatus == 1 || mailStatus == 2 || mailStatus == 3 || mailStatus == 4)
					{
						String errorMsg = "Problem occured while sending Secret Key to the user/group mail ID.";
						rootObj.put("TwoFAMailSend","failed");
						rootObj.put("MailSendErrMsg",errorMsg);
					}
				}
				else if (twofaOTPModeFlagVal != null && twofaOTPModeFlagVal.equalsIgnoreCase("mail") && tempUsrMailid != null && tempUsrMailid.trim().length() > 0)
				{
					String mailSubject = "Two Factor Authentication";
					String bodyContent = "2-step verification has been enforced as the security standard enterprise-wide, for securing accesses to the eG Enterprise system. When logging into the eG web console, use the time-based verification code sent to this email ID to validate your user login.";

					EgMailHelper mailObj = new EgMailHelper(tempUsrMailid);
					int mailStatus = mailObj.sendMail(mailSubject, bodyContent);
					if (mailStatus == 0)
					{
						rootObj.put("TwoFAMailSend","success");
					}
					else if (mailStatus == 1 || mailStatus == 2 || mailStatus == 3 || mailStatus == 4)
					{
						String errorMsg = "Problem occured while sending two factor authentication message to the user/group mail ID.";
						rootObj.put("TwoFAMailSend","failed");
						rootObj.put("MailSendErrMsg",errorMsg);
					}
				}
				egMFAIniFilePtr.saveFile();
				EgConfigFilesSync.releaseInstance(egMFAIniFilePtr);
			}
			// for 2fa - end here


			/* code for auditlog starts */
			auditLogThread.setCurrentValue("ColumnName","User Added");
			if(domainName.length()==0)
				domainName = "Local";
			else
				auditLogThread.setCurrentValue("05~~Password","******");

			if(userAuthentication == null || userAuthentication.equals("Eg"))
			{
				auditLogThread.setCurrentValue("02~~User Authentication","Local");
			}
			else if(userAuthentication.equals("SAML"))
			{
				auditLogThread.setCurrentValue("02~~User Authentication",userAuthentication);
			}
			else
			{
				auditLogThread.setCurrentValue("02~~User Authentication","Domain");
				auditLogThread.setCurrentValue("03~~Domain",domainName);
			}
			auditLogThread.setCurrentValue("01~~Role",utype);
			auditLogThread.setCurrentValue("03~~Entity type",userModel);
			if (uname != null && uname.indexOf("/Grp/") != -1)
			{
				String grpDelimiter = "/Grp/";
				int idx = uname.indexOf(grpDelimiter);
				String str_uname_A = uname.substring(0,idx);
				int nextIdx = idx + grpDelimiter.length();
				String str_uname_B = uname.substring(nextIdx);
				String userName = str_uname_A + "/" + str_uname_B + " (Group)";
				auditLogThread.setCurrentValue("04~~ID",userName);
			}
			else
			{
				if (uname.startsWith("samlsso/"))
				{
					String idpUserName = uname;
					int idx = idpUserName.indexOf("/");
					idpUserName = idpUserName.substring(idx+1);
					idpUserName = idpUserName + " (SAML)";
					auditLogThread.setCurrentValue("04~~ID",idpUserName);
				}
				else
				{
					auditLogThread.setCurrentValue("04~~ID",uname);
				}
			}
			if (userModel != null && !userModel.equalsIgnoreCase("Organization"))
			{
				if (org != null && org.indexOf("/Grp/") != -1)
				{
					String grpDelimiter = "/Grp/";
					int idx = org.indexOf(grpDelimiter);
					String str_uname_A = org.substring(0,idx);
					int nextIdx = idx + grpDelimiter.length();
					String str_uname_B = org.substring(nextIdx);
					String userName = str_uname_A + "/" + str_uname_B + " (Group)";
					auditLogThread.setCurrentValue("04~~Belongs to",userName);
				}
				else
				{
					if (org.startsWith("samlsso/"))
					{
						String idpUserName = org;
						int idx = idpUserName.indexOf("/");
						idpUserName = idpUserName.substring(idx+1);
						idpUserName = idpUserName + " (SAML)";
						auditLogThread.setCurrentValue("04~~Belongs to",idpUserName);
					}
					else
					{
						auditLogThread.setCurrentValue("04~~Belongs to",org);
					}
				}
			}
			if ((userAuthentication == null || userAuthentication.equalsIgnoreCase("Eg")) && changePwd != null && changePwd.trim().length() > 0)
			{
				auditLogThread.setCurrentValue("05~~Allow user to modify password",changePwd.equalsIgnoreCase("true")?"Yes":"No");
			}

			if(timelineVal !=null)
			{
				if (timelineVal.equals("-1"))
				{
					timelineVal = "Unlimited";
				}
				auditLogThread.setCurrentValue("20~~Reporter Restricted Timeline",timelineVal);
			}


			if(never != null && never.equals("Never"))
				auditLogThread.setCurrentValue("Expiry Date","Never");
			else
				auditLogThread.setCurrentValue("06~~Expiry Date",request.getParameter("tilldate"));

					
					 		/* Timezone Prakash.K start */
				if(timeZone != null && !timeZone.equalsIgnoreCase("null"))
					auditLogThread.setCurrentValue("07~~Time Zone",timeZoneOnly);
							/* Timezone Prakash.K finish */


							/* DateFormat Prakash.K start */
				if(timeZone != null && !timeZone.equalsIgnoreCase("null"))
					auditLogThread.setCurrentValue("08~~DateFormat",dateFormatOnly);
							/* DateFormat Prakash.K finish */

					

			boolean checkSMS = false;
			if(high != null && high.equals("high"))
			{
				auditLogThread.setCurrentValue("09~~Alarm By Mail/SMS","Critical");
				checkSMS = true;
			}
			if(medium != null && medium.equals("medium"))
			{
				auditLogThread.setCurrentValue("09~~Alarm By Mail/SMS","Major");
				checkSMS = true;
			}
			if(low != null && low.equals("low"))
			{
				auditLogThread.setCurrentValue("09~~Alarm By Mail/SMS","Minor");
				checkSMS = true;
			}

			if(checkSMS)
			{
				if(escmailid != null && escmailid.length()>0)
				{
					StringTokenizer tokens = new StringTokenizer(escmailid,",");
					while(tokens.hasMoreTokens())
					{
						String str = (String) tokens.nextToken();
						auditLogThread.setCurrentValue("10~~Escalation Mail ID",str);
					}
				}

				String toMailIds = request.getParameter("tomailid");
				String ccMailIds = request.getParameter("ccmailid");
				String bccMailIds = request.getParameter("bccmailid");

				ArrayList arrayList = new ArrayList();

				if(toMailIds != null && toMailIds.length()>0)
					arrayList.add("To:"+toMailIds);

				if(ccMailIds != null && ccMailIds.length()>0)
					arrayList.add("Cc:"+ccMailIds);

				if(bccMailIds != null && bccMailIds.length()>0)
					arrayList.add("Bcc:"+bccMailIds);

				for(int i=0;i<arrayList.size();i++)
				{
					String label = "";
					String ids = (String) arrayList.get(i);
					StringTokenizer tokens = new StringTokenizer(ids,",");

					while(tokens.hasMoreTokens())
					{
						String str = (String) tokens.nextToken();
						int colonIndex = str.indexOf(":");
						if(colonIndex > -1)
						{
							label = str.substring(0,colonIndex);
							str = "<b>" + label + "</b>" + str.substring(colonIndex);
						}
						else
						{
							String space="";
							for(int sp=0;sp<label.length();sp++)
							{
								space = space + "&nbsp;";
							}
							str = "&nbsp;&nbsp;&nbsp;" + space + str;
						}
						auditLogThread.setCurrentValue("11~~Mail ID/Mobile Number",str);
					}
				}

				if(notify !=null && notify.equalsIgnoreCase("C"))
					auditLogThread.setCurrentValue("12~~Type Of Notification","Complete List");
				if(notify !=null && notify.equalsIgnoreCase("N"))
					auditLogThread.setCurrentValue("12~~Type Of Notification","New");

				if(msgmode !=null && msgmode.equals("H"))
					auditLogThread.setCurrentValue("13~~Message Mode","Html");
				if(msgmode !=null && msgmode.equals("T"))
					auditLogThread.setCurrentValue("14~~Message Mode","Text");

				
				String mailSenders = request.getParameter("mailSenders");
				if(mailSenders != null && !mailSenders.equalsIgnoreCase("null"))
					auditLogThread.setCurrentValue("15~~Mail Senders",mailSenders);

			}
			if(alarm_h != null && alarm_h.equals("H"))
				auditLogThread.setCurrentValue("16~~Alarm Display","Critical");
			if(alarm_m != null && alarm_m.equals("I"))
				auditLogThread.setCurrentValue("16~~Alarm Display","Major");
			if(alarm_l != null && alarm_l.equals("L"))
				auditLogThread.setCurrentValue("16~~Alarm Display","Minor");

			if(request.getParameter("remotecontrol") !=null && request.getParameter("remotecontrol").equalsIgnoreCase("true"))
			{
				auditLogThread.setCurrentValue("17~~Remote Control","Enable");
				String execcommands = request.getParameter("execcommands");
				if(execcommands != null && execcommands.equalsIgnoreCase("true"))
					auditLogThread.setCurrentValue("18~~Remote Command Execution","Any commands");
				else
					auditLogThread.setCurrentValue("18~~Remote Command Execution","Configured commands only");
			}
			else if(hasmonitoraccess)
			{
				auditLogThread.setCurrentValue("17~~Remote Control","Disable");
			}

			if(alarmdelete != null)
				auditLogThread.setCurrentValue("19~~Allow Alarms Deletion",alarmdelete.equalsIgnoreCase("true")?"Yes":"No");

			if(acknowledgment != null)
				auditLogThread.setCurrentValue("20~~Allow Alarm Acknowledgement",acknowledgment.trim().equalsIgnoreCase("true")?"Yes":"No");

			if(hasmonitoraccess)
			{
				if(monitorHomePage!=null)
					auditLogThread.setCurrentValue("20~~Monitor Home Page",monitorHomePage.trim());
			}

			if(newWindow != null)
				auditLogThread.setCurrentValue("21~~Open New Window",newWindow.trim().equalsIgnoreCase("true")?"Yes":"No");

			if(checkSMS)
			{
				if(measureInMailMode !=null && measureInMailMode.equalsIgnoreCase("GRAPH"))
					auditLogThread.setCurrentValue("22~~Include measure details in mail alerts","Graph");
				else if(measureInMailMode !=null && measureInMailMode.equalsIgnoreCase("DATA"))
					auditLogThread.setCurrentValue("22~~Include measure details in mail alerts","Data");
				else if(measureInMailMode !=null && measureInMailMode.trim().length()>0 && hasmonitoraccess)
					auditLogThread.setCurrentValue("22~~Include measure details in mail alerts","No");

				if(ddInMailMode !=null && ddInMailMode.equalsIgnoreCase("NO"))
					auditLogThread.setCurrentValue("23~~Include detailed diagnosis in mail alerts","No");
				else if(ddInMailMode !=null && ddInMailMode.equalsIgnoreCase("YES"))
					auditLogThread.setCurrentValue("23~~Include detailed diagnosis in mail alerts","Yes");
				else if(ddInMailMode !=null && ddInMailMode.trim().length()>0 && hasmonitoraccess)
					auditLogThread.setCurrentValue("23~~Include detailed diagnosis in mail alerts","No");

			}
			/* code for auditlog ends */

			rootObj.put("isURLForwarded",new Boolean(false));
			rootObj.put("isAlarmEnabled",new Boolean(isAlarmEnabled));
			rootObj.put("isFilterMailAlertsEnabled",new Boolean(isFilterMailAlertsEnabled));
			rootObj.put("username",uname);
			String ausers = "";
			if (request.getParameter("assousers") != null)
			{
				ausers = request.getParameter("assousers");
			}
			rootObj.put("assousers",ausers);
			rootObj.put("utype",utype);
			if(!hasallcompaccess)
			{
				/* code for auditlog starts */
				if (uname != null && uname.indexOf("/Grp/") != -1)
				{
					String grpDelimiter = "/Grp/";
					int idx = uname.indexOf(grpDelimiter);
					String str_uname_A = uname.substring(0,idx);
					int nextIdx = idx + grpDelimiter.length();
					String str_uname_B = uname.substring(nextIdx);
					String grp_Name = str_uname_A + "/" + str_uname_B;
					auditLogThread.setValue("Description","Group "+grp_Name+" has been created with role "+utype);
				}
				else
				{
					if (uname.startsWith("samlsso/"))
					{
						String idpUserName = uname;
						int idx = idpUserName.indexOf("/");
						idpUserName = idpUserName.substring(idx+1);
						idpUserName = idpUserName + " (SAML)";
						auditLogThread.setValue("Description","User "+idpUserName+" has been created with role "+utype);
					}
					else
					{
						auditLogThread.setValue("Description","User "+uname+" has been created with role "+utype);
					}
				}
				auditLogThread.setValue("Activity","Add User");
				auditLogThread.sendItToDB();
				/* code for auditlog ends */

				session.removeValue("mode");
				//session.putValue("mode","add");
				session.putValue("mode","change");
				session.putValue("operation","add"); //krishnamurthi

				rootObj.put("requestStatus","success");
				JSONObject resultMsg = new JSONObject();
				if (operationType != null && (operationType.equalsIgnoreCase("Group") || operationType.equalsIgnoreCase("Groupname")))
				{
					resultMsg.put("title",_mapping.getTextDescription("admin.user.Add new group"));
					resultMsg.put("message1",_mapping.getTextDescription("admin.user.New group has been created"));
				}
				else
				{
					resultMsg.put("title",_mapping.getTextDescription("admin.user.Add new user"));
					resultMsg.put("message1",_mapping.getTextDescription("admin.user.New user has been created"));
				}
				rootObj.put("result",resultMsg);
				user.releaseConnection(false);
				out.println(rootObj.toString());
				return;
			}
			else if(isAlarmEnabled && isFilterMailAlertsEnabled)
			{
				rootObj.put("requestStatus","success");
				JSONObject resultMsg = new JSONObject();
				if (operationType != null && (operationType.equalsIgnoreCase("Group") || operationType.equalsIgnoreCase("Groupname")))
				{
					resultMsg.put("title",_mapping.getTextDescription("admin.user.Add new group"));
					resultMsg.put("message1",_mapping.getTextDescription("admin.user.New group has been created"));
				}
				else
				{
					resultMsg.put("title",_mapping.getTextDescription("admin.user.Add new user"));
					resultMsg.put("message1",_mapping.getTextDescription("admin.user.New user has been created"));
				}
				rootObj.put("result",resultMsg);
				rootObj.put("isURLForwarded",new Boolean(true));
				out.println(rootObj.toString());
				return;
			}
			else
			{
				/* code for auditlog starts */
				if (uname != null && uname.indexOf("/Grp/") != -1)
				{
					String grpDelimiter = "/Grp/";
					int idx = uname.indexOf(grpDelimiter);
					String str_uname_A = uname.substring(0,idx);
					int nextIdx = idx + grpDelimiter.length();
					String str_uname_B = uname.substring(nextIdx);
					String grp_Name = str_uname_A + "/" + str_uname_B;
					auditLogThread.setValue("Description","Group "+grp_Name+" has been created with role "+utype);
				}
				else
				{
					if (uname.startsWith("samlsso/"))
					{
						String idpUserName = uname;
						int idx = idpUserName.indexOf("/");
						idpUserName = idpUserName.substring(idx+1);
						idpUserName = idpUserName + " (SAML)";
						auditLogThread.setValue("Description","User "+idpUserName+" has been created with role "+utype);
					}
					else
					{
						auditLogThread.setValue("Description","User "+uname+" has been created with role "+utype);
					}
				}
				auditLogThread.setValue("Activity","Add User");
				auditLogThread.sendItToDB();
				/* code for auditlog ends */

				rootObj.put("requestStatus","success");
				JSONObject resultMsg = new JSONObject();
				if (operationType != null && (operationType.equalsIgnoreCase("Group") || operationType.equalsIgnoreCase("Groupname")))
				{
					resultMsg.put("title",_mapping.getTextDescription("admin.user.Add new group"));
					resultMsg.put("message1",_mapping.getTextDescription("admin.user.New group has been created"));
				}
				else
				{
					resultMsg.put("title",_mapping.getTextDescription("admin.user.Add new user"));
					resultMsg.put("message1",_mapping.getTextDescription("admin.user.New user has been created"));
				}
				user.releaseConnection(false);
				rootObj.put("result",resultMsg);
				out.println(rootObj.toString());
				return;
			}
		}
		else
		{
			/* code for auditlog starts */
			auditLogThread.setValue("Description","User " + uname + " has not been added");

			auditLogThread.setValue("Activity","Add User");
			auditLogThread.sendItToDB();
			/* code for auditlog ends */
			user.releaseConnection(false);

			rootObj.put("requestStatus","failed");

			if (operationType != null && operationType.equalsIgnoreCase("Group"))
			{
				errorObj.put("title",_mapping.getTextDescription("admin.error.Add new group"));
				errorObj.put("message1",_mapping.getTextDescription("admin.error.Group could not be created"));
				errorObj.put("message2",_mapping.getTextDescription("admin.error.Please make sure database is accessible from the manager application"));
			}
			else
			{
				errorObj.put("title",_mapping.getTextDescription("admin.error.Add new user"));
				errorObj.put("message1",_mapping.getTextDescription("admin.error.User could not be created"));
				errorObj.put("message2",_mapping.getTextDescription("admin.error.Please make sure database is accessible from the manager application"));
			}

			rootObj.put("errors",errorObj);
			out.println(rootObj.toString());
			return;
		}
	} // End Of Try Block
	catch(Exception e)
	{
		/* code for auditlog starts */
		auditLogThread.setValue("Description","Problem while adding user");
		auditLogThread.setValue("Activity","Add User");
		auditLogThread.sendItToDB();
		/* code for auditlog ends */
	}
%>
<%!
	private String getShiftPeriods(ArrayList dayList,ArrayList shiftList)
	{
		String result ="";
		for (int x=0;x<dayList.size();x++)
		{
			String tmpDay = dayList.get(x).toString();
			StringTokenizer tknr = new StringTokenizer(tmpDay,",");
			String tmp ="";
			while(tknr.hasMoreTokens())
			{
				String day = tknr.nextToken();
				if (day.equals("Sun"))
				{
					tmp = "1,";
				}
				else if (day.equals("Mon"))
				{
					tmp += "2,";
				}
				else if (day.equals("Tue"))
				{
					tmp += "3,";
				}
				else if (day.equals("Wed"))
				{
					tmp += "4,";
				}
				else if (day.equals("Thu"))
				{
					tmp += "5,";
				}
				else if (day.equals("Fri"))
				{
					tmp += "6,";
				}
				else if(day.equals("Sat"))
				{
					tmp += "7";
				}
			}
			if (tmp.endsWith(","))
			{
				tmp = tmp.substring(0,tmp.length()-1);
			}
			 result += tmp+"#"+shiftList.get(x).toString()+"|";
		}
		if (result.endsWith("|"))
		{
			result = result.substring(0,result.length()-1);
		}
		return result;
	}
%>




