<%@ include file="../../EgTrackerAJSON.jsp"%>
<%@ page import = "com.egurkha.admin.AuditLogThread"%>
<%@ page import="java.util.*" %>
<%@ page import="com.eg.EgInstallInfo" %>
<%@ page import = "egurkha.EgDbAdapterUI" %>
<%@ page import = "com.eg.EgDbAdapterTypeUI" %>
<%@ page import = "egurkha.*" %>
<%@ page import = "com.eg.*" %>
<%@ page import = "java.io.*" %>
<%@ page import="com.egurkha.util.StringUtils"%>
<%@ page import = "net.sf.json.*"%>
<%@ page language="java" contentType="application/json; charset=UTF-8" pageEncoding="UTF-8" %>
<jsp:useBean id="change" scope="page" class="egurkha.ServiceBean"/>
<jsp:useBean id="configTopo" scope="page" class="egurkha.ConfigTopology"/>

<%
	JSONObject rootObj = new JSONObject();
	rootObj.put("success","true");
	JSONObject errorObj = new JSONObject();
	response.setHeader("Cache-Control","no-store");
	response.setHeader("Pragma","no-cache");
	response.setDateHeader("Expires", -1);
	response.setContentType("application/json");

	String refferalURL = request.getParameter("refferalURL");
	String actionType = request.getParameter("actionType");
	if (refferalURL == null) refferalURL = "";

	/* code for auditlog starts */
	boolean auditFlag = false;
	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","Default Test Configuration");
	/* code for auditlog ends */

	EgDiscInfo discInfo = new EgDiscInfo("manager");
	EgExternalInfo externalInfo = new EgExternalInfo("manager");
	String agFile = "eg_agents.ini";
	String agFile_dir = EgInstallInfo.getInstallDir() + "/manager/config/";
	//IniFile agIniFile = new IniFile(agFile_dir + agFile,true);
	EgConfigInfo configInfo = new EgConfigInfo("manager");
	IniFile testIniFileWr = null;

	String from = request.getParameter("from");
	if(from == null)
		from = "";


	if(from.equals("changeSettings")||from.equals("commonsettings")||from.equals("changeSnmp"))
	{
		Vector sess_vec = new Vector();
		Vector v_comp = new Vector();
		configTopo.createFile("eg_services.ini");
		if(from.equals("changeSettings"))
		{
			auditLogThread.setValue("Activity","General settings");
			String previousRDperiod = request.getParameter("$_periodIndex");
			String previousDiscTimeOut = request.getParameter("$_discTimeoutIndex");
			String previousICMP = request.getParameter("$_icmpfordiscovery");
			String previousDHCP = request.getParameter("$_dhcpEnv");
			//String previousFQDN = request.getParameter("$_fqdn");
			String rdperiod=request.getParameter("period");
			String disctimeout = request.getParameter("disctimeout");
			String icmpfordiscovery = request.getParameter("icmp");
			String isThisDHCP = request.getParameter("dhcp");
			//String needFQDN = request.getParameter("fqdn");
			String previousRDC = request.getParameter("$_rediscoverComponents");
			String rediscoverComponents = request.getParameter("rediscoverComponents");
			String pattentype = request.getParameter("pattentype");
			String wildcardpatten = request.getParameter("wildcardpatten");
			if (rediscoverComponents == null || rediscoverComponents.length() == 0) rediscoverComponents = "no";
			if (pattentype == null || pattentype.length() == 0) pattentype = "Include";
			if (wildcardpatten == null || wildcardpatten.length() == 0) wildcardpatten = "";
			pattentype = pattentype +"|$|"+wildcardpatten;

			String previousreDiscoveryPeriod = "None";
			if(previousRDperiod.equals("30"))
				previousreDiscoveryPeriod = "30 Min";
			else if(previousRDperiod.equals("60"))
				previousreDiscoveryPeriod = "1 Hour";
			else if(previousRDperiod.equals("180"))
				previousreDiscoveryPeriod = "3 Hours";
			else if(previousRDperiod.equals("360"))
				previousreDiscoveryPeriod = "6 Hours";
			else if(previousRDperiod.equals("1440"))
				previousreDiscoveryPeriod = "1 Day";
			else if(previousRDperiod.equals("10080"))
				previousreDiscoveryPeriod = "1 Week";
			auditLogThread.setPreviousValue("Re-discovery period",previousreDiscoveryPeriod);
			String reDiscoveryPeriod = "None";
			if(rdperiod.equals("30"))
				reDiscoveryPeriod = "30 Min";
			else if(rdperiod.equals("60"))
				reDiscoveryPeriod = "1 Hour";
			else if(rdperiod.equals("180"))
				reDiscoveryPeriod = "3 Hours";
			else if(rdperiod.equals("360"))
				reDiscoveryPeriod = "6 Hours";
			else if(rdperiod.equals("1440"))
				reDiscoveryPeriod = "1 Day";
			else if(rdperiod.equals("10080"))
				reDiscoveryPeriod = "1 Week";
			auditLogThread.setCurrentValue("Re-discovery period",reDiscoveryPeriod);
			
			if(previousDiscTimeOut.equals("250"))
				auditLogThread.setPreviousValue("Type Of Network","LAN");
			else
				auditLogThread.setPreviousValue("Type Of Network","WAN");
			
			if(disctimeout.equals("250"))
				auditLogThread.setCurrentValue("Type Of Network","LAN");		
			else
				auditLogThread.setCurrentValue("Type Of Network","WAN");
			
			auditLogThread.setPreviousValue("ICMP enabled",previousICMP);
			auditLogThread.setCurrentValue("ICMP enabled",icmpfordiscovery);

			auditLogThread.setPreviousValue("DHCP Environment",previousDHCP);
			auditLogThread.setCurrentValue("DHCP Environment",isThisDHCP);

			auditLogThread.setPreviousValue("Re-discover deleted components",previousRDC);
			auditLogThread.setCurrentValue("Re-discover deleted components",rediscoverComponents);

			//auditLogThread.setPreviousValue("Allow FQDN",previousFQDN);
			//auditLogThread.setCurrentValue("Allow FQDN",needFQDN);

			auditLogThread.setValue("Description","General settings have been changed");
			/* code for audit log ends */

			String currentCommunity = request.getParameter("Community");
			String previousCommunity = request.getParameter("$_Community");
			if(!(currentCommunity.equals(previousCommunity)))
				auditFlag = true;

			if(previousCommunity == null)
				previousCommunity = "NONE";

			/* code for audit log starts */
			auditLogThread.setPreviousValue("SNMP Community Strings",previousCommunity);
			/* code for audit log ends */

			if(currentCommunity == null)
				currentCommunity = "NONE";

			/* code for audit log starts */
			auditLogThread.setCurrentValue("SNMP Community Strings",currentCommunity);
			auditLogThread.setValue("Description","General settings have been changed");
			/* code for audit log ends */

			String uiFileStr = "eg_services.ini";
			String serviceFileDir = EgInstallInfo.getInstallDir() + "/manager/config/";
			IniFile serviceWrObj = EgConfigFilesSync.getInstance(serviceFileDir + uiFileStr,true);
			serviceWrObj.setValue("MISC_ARGS","RediscoverDeletedComponents",rediscoverComponents);
			serviceWrObj.setValue("MISC_ARGS","DiscoveryIncludeOrExcludePatten",pattentype);
			serviceWrObj.saveFile();
			EgConfigFilesSync.releaseInstance(serviceWrObj);

			change.createAdmin();
			change.setRdperiod(rdperiod);
			change.setDiscTimeout(disctimeout);

			if(!(icmpfordiscovery.equals(previousICMP)))
				auditFlag = true;
			if(!(rdperiod.equals(previousRDperiod)))
				auditFlag = true;
			if(!(disctimeout.equals(previousDiscTimeOut)))
				auditFlag = true;

			if(!(isThisDHCP.equals(previousDHCP)))
				auditFlag = true;
			//if (!(needFQDN.equals(previousFQDN)))
			//	auditFlag = true;
			change.setIcmpForDiscovery(icmpfordiscovery);
			change.setDHCPEnvoirnment(isThisDHCP);
			//change.setFQDNInfo(needFQDN);

			// Setting up the SNMP strings
			String communitystrings=request.getParameter("Community");
			if(communitystrings != null && communitystrings.indexOf(",")>=0)
			{
				communitystrings = communitystrings.replace(',',':');
			}
			change.createAdmin();
			change.setCommunityStrings(communitystrings);

			//Setting up the server types and IP ranges
			String newiprange = request.getParameter("iprange");
			if (newiprange == null ) newiprange = "";

			StringBuffer newip = new StringBuffer();
			StringTokenizer toks = new StringTokenizer(newiprange,"\n");
			while(toks.hasMoreTokens())
			{
				newip.append(toks.nextToken());
				if (toks.hasMoreTokens()) newip.append(",");
			}
			change.setAllIpranges(StringUtils.removeISOControlChar(newip.toString()));
			String automanage = request.getParameter("autoManage");
			if (automanage == null) automanage = "No";

			change.setAutomanage(automanage);

			// to store credentials
			String uiFile = "eg_services.ini";
			String s_iniFile_dir = EgInstallInfo.getInstallDir() + "/manager/config/";
			IniFile serviceWr = EgConfigFilesSync.getInstance(s_iniFile_dir + uiFile,true);
			String windowsUser = request.getParameter("winuser");
			String windowsPassword = request.getParameter("winpass");
			String SSHuser = request.getParameter("sshuser");
			String SSHpassword = request.getParameter("sshpass");
			String winDomain = request.getParameter("windomain");
			String credentialSettings=request.getParameter("credential");
			if(credentialSettings==null)
				credentialSettings="no";

			if(windowsUser==null || windowsUser.length()==0)
				windowsUser="none";
			if(windowsPassword==null|| windowsPassword.length()==0)
				windowsPassword="none";
			if(SSHuser==null|| SSHuser.length()==0)
				SSHuser="none";
			if(SSHpassword==null|| SSHpassword.length()==0)
				SSHpassword="none";
			if(winDomain==null|| winDomain.length()==0)
				winDomain="none";
			
			String encryptedWinPass ="none";
			String decryptedWinPass ="none";
			if(!windowsPassword.equalsIgnoreCase("none"))
			{
				String strTokenSaltWP = EgCrypt.decrypt(windowsPassword);
				if (strTokenSaltWP.indexOf("~EG~") != -1)
				{
					windowsPassword = strTokenSaltWP.substring(0,strTokenSaltWP.indexOf("~EG~"));
				}

				encryptedWinPass = EgCrypt.encrypt(windowsPassword);
			}	
			String encryptedSSHPass ="none";
			String decryptedSSHPass ="none";
			if(!SSHpassword.equalsIgnoreCase("none"))
			{
				String strTokenSaltSSH = EgCrypt.decrypt(SSHpassword);
				if (strTokenSaltSSH.indexOf("~EG~") != -1)
				{
					SSHpassword = strTokenSaltSSH.substring(0,strTokenSaltSSH.indexOf("~EG~"));
				}
				encryptedSSHPass = EgCrypt.encrypt(SSHpassword);
			}
			if(!winDomain.equalsIgnoreCase("none"))
				windowsUser=winDomain+"\\"+windowsUser;
			
			if(credentialSettings.equalsIgnoreCase("yes"))
			{
				serviceWr.setValue("DISCOVERY_CREDENTIAL","Windows",windowsUser+","+encryptedWinPass);	
				serviceWr.setValue("DISCOVERY_CREDENTIAL","SSH",SSHuser+","+encryptedSSHPass);
			}
			serviceWr.setValue("DISCOVERY_CREDENTIAL","FlagEnabled",credentialSettings);

			// snmpv3 properties starts
			String snmpVersion = request.getParameter("snmpversion");
			String dataOverTcp = request.getParameter("dataOverTcp");
			if (dataOverTcp == null)
			{
				dataOverTcp = "no";
			}
			serviceWr.setValue("MISC_ARGS","DataOverTcp",dataOverTcp);

			if (snmpVersion != null && snmpVersion.equalsIgnoreCase("v3"))
			{
				String snmpUserName = request.getParameter("SnmpUserName");
				String SnmpUserPass = request.getParameter("SnmpUserPass");
				String snmpAuthType = request.getParameter("snmpAuthType");
				String encType = request.getParameter("encType");
				String snmpEncAuth = request.getParameter("snmpEncAuth");
				String snmpEncPass = request.getParameter("snmpEncPass");
				serviceWr.setValue("MISC_ARGS","DiscoverySNMPVersion",snmpVersion);
				serviceWr.setValue("MISC_ARGS","SnmpUserName",snmpUserName);
				serviceWr.setValue("MISC_ARGS","SnmpUserPass",SnmpUserPass);
				serviceWr.setValue("MISC_ARGS","SnmpAuthType",snmpAuthType);
				serviceWr.setValue("MISC_ARGS","EncType",encType);
				if (encType != null && encType.equalsIgnoreCase("yes"))
				{
					serviceWr.setValue("MISC_ARGS","SnmpEncAuth",snmpEncAuth);
					serviceWr.setValue("MISC_ARGS","SnmpEncPass",snmpEncPass);
				}
			}
			else
			{
				serviceWr.setValue("MISC_ARGS","DiscoverySNMPVersion",snmpVersion);
			}
			// snmpv3 properties ends
			serviceWr.saveFile();
			EgConfigFilesSync.releaseInstance(serviceWr);

			rootObj.put("requestStatus","success");
			JSONObject resultMsg = new JSONObject();
			resultMsg.put("title",_mapping.getTextDescription("admin.discovery.Start Discovery"));
			resultMsg.put("message1",_mapping.getTextDescription("admin.discovery.Preferences have been changed"));
			rootObj.put("result",resultMsg);
			auditLogThread.sendItToDB();
			out.println(rootObj.toString());
			return;
		}

		if(from.equals("commonsettings"))
		{
			change.createAdmin();
			String currentDiscBase = request.getParameter("discbase");
			String previousDiscBase = request.getParameter("$_discBase");

			change.setDiscBase(currentDiscBase);
			if(!(currentDiscBase.equals(previousDiscBase)))
			{
				auditFlag = true;
				change.setDiscBaseChange("TRUE");
			}
			if(previousDiscBase.equalsIgnoreCase("IP"))
				auditLogThread.setPreviousValue("Index components using","IP address");
			else
				auditLogThread.setPreviousValue("Index components using","Host name");
			if(currentDiscBase.equalsIgnoreCase("IP"))
				auditLogThread.setCurrentValue("Index components using","IP address");
			else
				auditLogThread.setCurrentValue("Index components using","Host name");

			String[] c_types = request.getParameterValues("c_types");
			String[] tmpServers;
			String serversContainer = request.getParameter("c_types");
			StringTokenizer srvTokens = new StringTokenizer(serversContainer,",");
			int srvCount = 0;
			ArrayList serverList = new ArrayList();
			while(srvTokens.hasMoreTokens())
			{
				serverList.add((String)srvTokens.nextToken());
			}
			String [] serverkArr = (String[])serverList.toArray(new String[0]);
			change.setServertypes(serverkArr);
			change.setServertypesBasedOnPriority(serverkArr,"HIGH_PRIORITY_COMPONENTS");
			change.setServertypesBasedOnPriority(serverkArr,"LOW_PRIORITY_COMPONENTS");

			/* code for audit log starts */
			auditLogThread.setValue("Activity","Port settings");
			// Setting up the server ports
			ArrayList newList = null;
			ArrayList oldList = new ArrayList();

			String newPortValues[] = request.getParameterValues("Ports");
			newList = new ArrayList(Arrays.asList(newPortValues));
			String oldPortValues[] = request.getParameterValues("$_Ports");

			if(oldPortValues != null && oldPortValues.length>0 && newPortValues != null && newPortValues.length>0)
			{
				for(int i=0;i<oldPortValues.length;i++)
				{
					String previousValue = oldPortValues[i];
					int $Index = previousValue.indexOf("$");
					String label = previousValue.substring(0,$Index);
					String value = previousValue.substring($Index+1);
					oldList.add(value);
					if(value !=null && value.trim().length()>0)
					{
						value = value.trim();
						auditLogThread.setPreviousValue(label,value);
						String tmp = newPortValues[i];
						if(tmp !=null && tmp.trim().length()>0)
						{
							tmp = tmp.trim();
							auditLogThread.setCurrentValue(label,tmp);
						}
					}
				}
			}
			if(newList.removeAll(oldList))
			{
				if(newList.size()>0)
				{
					auditFlag = true;
				}
			}
			String noportservers[] = configTopo.getVariables("NOPORT_SERVERS");
			if(newList.size()>0)
			{
				String[] newportvals=request.getParameterValues("Ports"); 
				String[] servers = request.getParameterValues("serverName");

				for(int i=0; i<newportvals.length; i++)
				{
					if(newportvals[i] != null && newportvals[i].indexOf(",")>=0)
					{
						newportvals[i] = newportvals[i].replace(',',':');
					}
				}
				change.setPortvals(servers,newportvals);
			}
			auditLogThread.setValue("Description","Port preferences for discovery have been changed");
			change.commitChanges();

			String uiFile = "eg_services.ini";
			String s_iniFile_dir = EgInstallInfo.getInstallDir() + "/manager/config/";
			String allowDuplicates = request.getParameter("allowDuplicates");
			if(allowDuplicates==null) allowDuplicates="true";
			IniFile serviceWr = EgConfigFilesSync.getInstance(s_iniFile_dir + uiFile,true);
			serviceWr.setValue("DISCOVERY_SETTINGS","allowDuplicates",allowDuplicates);
			serviceWr.saveFile();
			EgConfigFilesSync.releaseInstance(serviceWr);

			rootObj.put("requestStatus","success");
			JSONObject resultMsg = new JSONObject();
			resultMsg.put("title",_mapping.getTextDescription("admin.discovery.Start Discovery"));
			resultMsg.put("message1",_mapping.getTextDescription("admin.discovery.Preferences have been changed"));
			rootObj.put("result",resultMsg);
			auditLogThread.sendItToDB();
			out.println(rootObj.toString());
			return;
		}
	}

	String uiFile = "eg_services.ini";
	String s_iniFile_dir = EgInstallInfo.getInstallDir() + "/manager/config/";
	IniFile testIniFile = new IniFile(s_iniFile_dir + uiFile);	
	String sub = "";
	if ( from != null && from.startsWith("hmc"))
		sub = "HMC";
	else if (from != null && from.startsWith("cloud"))
		sub = "PUBLIC_CLOUDS";
	else if (from != null && from.startsWith("nut"))
		sub = "NUTANIX";
	else if (from != null && from.startsWith("xms"))
		sub = "EMC_XtremIO_4x";
	else
		sub = "VIRTUAL_CENTER";
	String[] allKeys = testIniFile.getVariables(sub);

	/* code for audit log starts */
	String selVcenterIP = request.getParameter("ipAdd");
	String oldMem = request.getParameter("$_memory");
	/* code for audit log ends */
	if (from.equals("cloudAddCloudDiscovery") || from.equals("cloudAdd") )
	{
		Vector sess_vec = new Vector();
		String account = request.getParameter("account");
		String accessKey = request.getParameter("accessKey");
		String isDis = request.getParameter("isDiscovery");
		String secretKey = request.getParameter("secretKey");
		String strTokenSaltAK = EgCrypt.decrypt(accessKey);
		if (strTokenSaltAK.indexOf("~EG~") != -1)
		{
			accessKey = strTokenSaltAK.substring(0,strTokenSaltAK.indexOf("~EG~"));
		}
		accessKey = EgCrypt.encrypt(accessKey);


		strTokenSaltAK = EgCrypt.decrypt(secretKey);
		if (strTokenSaltAK.indexOf("~EG~") != -1)
		{
			secretKey = strTokenSaltAK.substring(0,strTokenSaltAK.indexOf("~EG~"));
		}

		secretKey = EgCrypt.encrypt(secretKey);
		String subVal = accessKey+"#"+secretKey+"#"+isDis;
		testIniFileWr = EgConfigFilesSync.getInstance(s_iniFile_dir + uiFile,true);
		testIniFileWr.setValue(sub,account,subVal);
		testIniFileWr.saveFile();
		EgConfigFilesSync.releaseInstance(testIniFileWr);

		//change.stopDiscovery();
		//change.startDiscovery("5", true);
		rootObj.put("requestStatus","success");
		JSONObject resultMsg = new JSONObject();
		resultMsg.put("title",_mapping.getTextDescription("admin.discovery.Start Discovery"));
		resultMsg.put("message1",_mapping.getTextDescription("admin.Discovery.Details has been added successfully"));
		rootObj.put("result",resultMsg);
		out.println(rootObj.toString());
		return ;
	}
	else if (from.equals("cloudModifyCloudDiscovery") || from.equals("cloudModify") )
	{
		Vector sess_vec = new Vector();
		String account = request.getParameter("account");
		String accessKey = request.getParameter("accessKey");
		String isDis = request.getParameter("isDiscovery");
		String secretKey = request.getParameter("secretKey");
		String strTokenSalt = EgCrypt.decrypt(accessKey);
		if (strTokenSalt.indexOf("~EG~") != -1)
		{
			accessKey = strTokenSalt.substring(0,strTokenSalt.indexOf("~EG~"));
		}
		accessKey = EgCrypt.encrypt(accessKey);

		strTokenSalt = EgCrypt.decrypt(secretKey);
		if (strTokenSalt.indexOf("~EG~") != -1)
		{
			secretKey = strTokenSalt.substring(0,strTokenSalt.indexOf("~EG~"));
		}
		secretKey = EgCrypt.encrypt(secretKey);
		String subVal = accessKey+"#"+secretKey+"#"+isDis;
		testIniFileWr = EgConfigFilesSync.getInstance(s_iniFile_dir + uiFile,true);
		testIniFileWr.setValue(sub,account,subVal);
		testIniFileWr.saveFile();
		EgConfigFilesSync.releaseInstance(testIniFileWr);

		//change.stopDiscovery();
		//change.startDiscovery("5", true);
		rootObj.put("requestStatus","success");
		JSONObject resultMsg = new JSONObject();
		resultMsg.put("title",_mapping.getTextDescription("admin.discovery.Start Discovery"));
		resultMsg.put("message1",_mapping.getTextDescription("admin.Discovery.details has been modified successfully"));
		rootObj.put("result",resultMsg);
		out.println(rootObj.toString());
		return ;
	}

	if(from.equals("memory"))
	{
		String mem=request.getParameter("memory");

		/* code for audit log starts */
		auditLogThread.setValue("Activity","Memory settings");
		auditLogThread.setPreviousValue("03~~Memory settings ",""+oldMem);
		auditLogThread.setCurrentValue("03~~Memory settings ","" +mem);
		if(!(mem.equals(oldMem)))
			auditFlag = true;
		/* code for audit log ends */

		mem=mem+"M";
		testIniFileWr = EgConfigFilesSync.getInstance(s_iniFile_dir + uiFile,true);
		testIniFileWr.setValue("EXEC","VcDiscover_Mem",mem);
		testIniFileWr.saveFile();
		EgConfigFilesSync.releaseInstance(testIniFileWr);
		/* code for audit log starts */
		auditLogThread.setValue("Description","Memory settings have been configured successfully");
		/* code for audit log ends */
	}

	String server = "";
	if(from.startsWith("hmc"))
	{
		server = "HMC";
	}
	else if (from.startsWith("nut"))
	{
		server = "Nutanix";
	}
	else if (from.startsWith("virtual"))
	{
		server = "vCenter";
	}

	if(from.equals("nutAdd") || from.equals("hmcAdd")||from.equals("add")||from.equals("hmcModify")||from.equals("modify")||from.equals("modifyEsxDiscovery")||from.equals("addEsxDiscovery")||from.equals("hmcModifyHmcDiscovery")||from.equals("hmcAddHmcDiscovery") || from.equals("xmsadd"))
	{
		try
		{
			String subVal = "";
			Vector sess_vec = new Vector();
			String UPass = request.getParameter("pass");
			String strTokenSaltUP = EgCrypt.decrypt(UPass);
			if (strTokenSaltUP.indexOf("~EG~") != -1)
			{
				UPass = strTokenSaltUP.substring(0,strTokenSaltUP.indexOf("~EG~"));
			}

			String curPwd = UPass;
			String ipAddress = request.getParameter("ipAdd");
			String UName = request.getParameter("uname");
			String hName = request.getParameter("hName");
			String ssl = request.getParameter("ssl");
			String isDis = request.getParameter("isDiscovery");
			String webPort = request.getParameter("webport");
			//String serverType = request.getParameter("srvType");

			if(ipAddress != null && UName != null && UPass != null && ssl != null && isDis != null)
			{
				UPass = EgCrypt.encrypt(UPass);
				boolean ipExists=false;
				for(int i=0;i<allKeys.length;i++)
				{
					String s=allKeys[i];
					if(ipAddress.equalsIgnoreCase(s))
					{
						ipExists = true;
					}
				}

				if(from.equals("add") || from.equals("nutAdd") || from.equals("hmcAdd") || from.equals("addEsxDiscovery") || from.equals("hmcAddHmcDiscovery") || from.equals("xmsadd"))
				{
					if(ipExists)
					{
						auditLogThread.setValue("Activity","Existing IP");
						ipExists = false;

						rootObj.put("requestStatus","failed");
						errorObj.put("title",_mapping.getTextDescription("admin.discovery.Add new")+" "+server);
						errorObj.put("message1",ipAddress+" "+_mapping.getTextDescription("admin.discovery.already exists")+". "+_mapping.getTextDescription("admin.discovery.Try to add another"));

						auditLogThread.setValue("Description",ipAddress+" already exists.Update another "+ server);
						auditLogThread.sendItToDB();
						rootObj.put("errors",errorObj);
						out.println(rootObj);
						return;
					}
					else
					{
						auditFlag = true;
						if(from.startsWith("hmc"))
							subVal = ssl+"#"+UName+"#"+UPass+"#"+isDis+"#"+hName;
						else if(from.startsWith("xms"))
							subVal = ssl+"#"+UName+"#"+UPass+"#"+isDis;
						//else if(from.startsWith("add"))
							//subVal = ssl+"#"+UName+"#"+UPass+"#"+isDis+"#"+webPort+"#"+serverType;
						else
							subVal = ssl+"#"+UName+"#"+UPass+"#"+isDis+"#"+webPort;
						testIniFileWr = EgConfigFilesSync.getInstance(s_iniFile_dir + uiFile,true);
						testIniFileWr.setValue(sub,ipAddress,subVal);
						testIniFileWr.saveFile();
						EgConfigFilesSync.releaseInstance(testIniFileWr);
						if(from.equalsIgnoreCase("add") || from.equalsIgnoreCase("hmcAdd") || from.equalsIgnoreCase("nutAdd") || from.equalsIgnoreCase("xmsadd"))
						{
							String conSSL = ssl.equalsIgnoreCase("True")?"Yes":"No";
							if(from.equalsIgnoreCase("add"))
							{
								auditLogThread.setCurrentValue("ColumnName","vCenter Added");
								auditLogThread.setValue("Activity","Add vCenter discovery");
								auditLogThread.setCurrentValue("00~~vCenter identity (IP or Host name)",ipAddress);
								auditLogThread.setCurrentValue("01~~Use SSL to connect to vCenter",conSSL);
								auditLogThread.setCurrentValue("02~~Web Port",webPort);
								auditLogThread.setCurrentValue("03~~Discover ESX hosts using this vCenter",isDis);
								auditLogThread.setCurrentValue("04~~Username to connect to vCenter",UName);
								auditLogThread.setCurrentValue("05~~Password for the user","*****");
								auditLogThread.setValue("Description","vCenter preferences have been added successfully");
							}
							else if(from.equalsIgnoreCase("nutAdd"))
							{
								auditLogThread.setCurrentValue("ColumnName","Nutanix Prism Added");
								auditLogThread.setValue("Activity","Add Nutanix Prism discovery");
								auditLogThread.setCurrentValue("00~~Nutanix Prism identity (IP or Host Name)",ipAddress);
								auditLogThread.setCurrentValue("01~~Use SSL to connect to Nutanix Prism",conSSL);
								auditLogThread.setCurrentValue("02~~Web Port",webPort);
								auditLogThread.setCurrentValue("03~~Discover Nutanix Acropolis or Vmware vSphere servers",isDis);
								auditLogThread.setCurrentValue("04~~Username to connect to nutanix prism",UName);
								auditLogThread.setCurrentValue("05~~Password for the user","*****");
								auditLogThread.setValue("Description","Nutanix prism preferences have been added successfully");
							}
							else if(from.equalsIgnoreCase("xmsadd"))
							{
								auditLogThread.setCurrentValue("ColumnName","XMS Identity Added");
								auditLogThread.setValue("Activity","Add XMS IP details");
								auditLogThread.setCurrentValue("00~~XMS identity (IP or Host name)",ipAddress);
								auditLogThread.setCurrentValue("01~~Use SSL to connect to XMS",conSSL);
								auditLogThread.setCurrentValue("02~~Discover EMC XtremIO hosts using this XMS",isDis);
								auditLogThread.setCurrentValue("03~~Username to connect to XMS",UName);
								auditLogThread.setCurrentValue("04~~Password for the user","*****");
								auditLogThread.setValue("Description","XMS preferences have been added successfully");
							}
							else
							{
								auditLogThread.setValue("Activity","Add HMC discovery");
								auditLogThread.setCurrentValue("ColumnName","HMC Added");
								auditLogThread.setCurrentValue("00~~IP address of Hardware management console",ipAddress);
								auditLogThread.setCurrentValue("01~~Host Name of Hardware management console",hName);
								auditLogThread.setCurrentValue("02~~Use SSL to connect to HMC",conSSL);
								auditLogThread.setCurrentValue("03~~Discover pSeries servers using this HMC",isDis);
								auditLogThread.setCurrentValue("04~~Username to connect to HMC ( i.e hscroot )",UName);
								auditLogThread.setCurrentValue("05~~Password for the user","*****");
								auditLogThread.setValue("Description","HMC preferences have been added successfully");
							}

							rootObj.put("requestStatus","success");
							JSONObject resultMsg = new JSONObject();
							if (from.equalsIgnoreCase("add"))
							{
								resultMsg.put("title",_mapping.getTextDescription("admin.server.Add vCenter"));
							}
							else if (from.equalsIgnoreCase("nutAdd"))
							{
								resultMsg.put("title",_mapping.getTextDescription("admin.server.Add Nutanix Prism"));
							}
							else
							{
								resultMsg.put("title",_mapping.getTextDescription("admin.server.Add HMC"));
							}
							resultMsg.put("message1",_mapping.getTextDescription("admin.discovery.Details has been added successfully"));
							rootObj.put("result",resultMsg);

							if(auditFlag)
								auditLogThread.sendItToDB();

							out.println(rootObj.toString());
							return;
						}
					}
				}
				else if(from.equals("modify") || from.equals("hmcModify") || from.equals("modifyEsxDiscovery") || from.equals("hmcModifyHmcDiscovery"))
				{
					/* code for audit log starts */
					String curSSL = request.getParameter("ssl");
					String curisDiscovery = request.getParameter("isDiscovery");
					String curUname = request.getParameter("uname");
					String checkSSL = curSSL.equalsIgnoreCase("True")?"Yes":"No";
					String curHname = request.getParameter("hName");
					String preSSL = request.getParameter("$_ssl");
					String preisDiscovery = request.getParameter("$_isDiscovery");
					String preUname = request.getParameter("$_uname");
					String preUPass = request.getParameter("$_confpasswd");
					String preWebPort = request.getParameter("$_webport");
					String preHname = request.getParameter("$_hName");
					
					/*code for audit log ends*/
					IniFile agIniFile = EgConfigFilesSync.getInstance(agFile_dir + agFile,true);
					// Code starts for VC Comp Modification
					if(from.startsWith("hmc"))
					{
						/* code for audit log starts */
						if(!((checkSSL.equals(preSSL)) && (curisDiscovery.equals(preisDiscovery)) && (curUname.equals(preUname)) && (curPwd.equals(preUPass)) && (curHname.equals(preHname))))
						{
							auditFlag = true;
						}
						auditLogThread.setValue("Activity","Modify HMC discovery");
						auditLogThread.setPreviousValue("00~~Host Name of Hardware management console",preHname);
						auditLogThread.setCurrentValue("00~~Host Name of Hardware management console",curHname);
						auditLogThread.setPreviousValue("01~~Use SSL to connect to HMC",preSSL);
						auditLogThread.setCurrentValue("01~~Use SSL to connect to HMC",ssl.equalsIgnoreCase("True")?"Yes":"No");
						auditLogThread.setPreviousValue("02~~Discover pSeries servers using this HMC",preisDiscovery);
						auditLogThread.setCurrentValue("02~~Discover pSeries servers using this HMC",isDis);
						auditLogThread.setPreviousValue("03~~Username to connect to HMC ( i.e hscroot )",preUname);
						auditLogThread.setCurrentValue("03~~Username to connect to HMC ( i.e hscroot )",UName);
						if(!(preUPass.equals(curPwd)))
						{
							auditLogThread.setPreviousValue("04~~Password for the user ","*****");
							auditLogThread.setCurrentValue("04~~Password for the user ","******");
						}
						auditLogThread.setValue("Description","HMC for "+ selVcenterIP +" preferences have been modified successfully");
						
						if(auditFlag)
							auditLogThread.sendItToDB();
						/*code for audit log ends*/

						String[] hmcComps = discInfo.getAllServersOfType("hmc_server");
						for (int i=0; i<hmcComps.length; i++)
						{
							String hmcVar = hmcComps[i];
							String hmcVal[] = discInfo.getFieldValuesForServer("hmc_server",hmcVar);
							ArrayList hmcValList = new ArrayList();
							for (int p=0; p<hmcVal.length; p++)
							{
								hmcValList.add(hmcVal[p].toLowerCase());
							}
							ArrayList agents = new ArrayList();
							if (hmcValList.contains(ipAddress.toLowerCase())) //Check this VC is added as a component thru Add/Modify
							{
								String hmc = hmcVar.substring(hmcVar.indexOf(":")+1);
								hmc = hmc.substring(0,hmc.indexOf(":"));
								agents = new ArrayList(externalInfo.getAgentsForHost(hmc));
								for (int j=0; j<agents.size(); j++)
								{
									String agent = agents.get(j).toString();
									String[] agentVars = agIniFile.getVariables(agent);
									for (int k=0; k<agentVars.length; k++)
									{
										String agentVar = agentVars[k];
										String agentVal = agIniFile.getValue(agent,agentVar);
										if (agentVal.toLowerCase().indexOf("-hmc_user") > 0)
										{
											String valHost = agentVal.substring(agentVal.indexOf("-host")+5).trim();
											valHost = valHost.substring(0,valHost.indexOf(" ")).trim();
											String agentVarLower = agentVar.toLowerCase();

											if(agentVarLower.indexOf(":"+ipAddress.toLowerCase()+":") > 0 || 
												agentVarLower.endsWith(":"+ipAddress.toLowerCase()) || 
												valHost.equalsIgnoreCase(ipAddress)) // IP / Host name / Nick , any one equals with HMC, then do.
											{
												String strTmp1 = agentVal.substring(0,agentVal.toLowerCase().indexOf("-hmc_user")+9).trim();
												String strTmp2 = agentVal.substring(agentVal.toLowerCase().indexOf("-hmc_user")+9).trim();
												strTmp2 = strTmp2.substring(strTmp2.indexOf(" ")).trim();
												agentVal = strTmp1 + " " + UName + " " + strTmp2;

												int hmcPwdIndex = agentVal.toLowerCase().indexOf("-hmc_password");
												if (hmcPwdIndex > -1)
												{
													strTmp1 = agentVal.substring(0,hmcPwdIndex+13).trim();
													strTmp2 = agentVal.substring(hmcPwdIndex+13).trim();
													strTmp2 = strTmp2.substring(strTmp2.indexOf(" ")).trim();
													agentVal = strTmp1 + " " + UPass + " " + strTmp2;
												}
												int sslIndex = agentVal.toLowerCase().indexOf("-ssl");
												if (sslIndex > -1)
												{
													strTmp1 = agentVal.substring(0,sslIndex+4).trim();
													strTmp2 = agentVal.substring(sslIndex+4).trim();
													strTmp2 = strTmp2.substring(strTmp2.indexOf(" ")).trim();
													agentVal = strTmp1 + " " + ssl.toLowerCase() + " " + strTmp2;
												}
												agIniFile.setValue(agent,agentVar,agentVal);
											}
										}
									}
								}
								agIniFile.saveFile();
							}
						}
					}
					else
					{
						/*code for audit log starts*/
						if(!((checkSSL.equals(preSSL)) && (curisDiscovery.equals(preisDiscovery)) && (curUname.equals(preUname)) && (curPwd.equals(preUPass)) && (webPort.equals(preWebPort))))
						{
							auditFlag = true;
						}
						auditLogThread.setValue("Activity","Modify vCenter discovery");
						auditLogThread.setPreviousValue("00~~Use SSL to connect to vCenter",preSSL);
						auditLogThread.setCurrentValue("00~~Use SSL to connect to vCenter",ssl.equalsIgnoreCase("True")?"Yes":"No");
						auditLogThread.setPreviousValue("01~~Web Port",preWebPort);
						auditLogThread.setCurrentValue("01~~Web Port",webPort);
						auditLogThread.setPreviousValue("02~~Discover ESX hosts using this vCenter",preisDiscovery);
						auditLogThread.setCurrentValue("02~~Discover ESX hosts using this vCenter",isDis);
						auditLogThread.setPreviousValue("03~~Username to connect to vCenter",preUname);
						auditLogThread.setCurrentValue("03~~Username to connect to vCenter",UName);
						if(!(preUPass.equals(curPwd)))
						{
							auditLogThread.setPreviousValue("04~~Password for the user ","*****");
							auditLogThread.setCurrentValue("04~~Password for the user ","******");
						}
						auditLogThread.setValue("Description","vCenter for "+ selVcenterIP +" preferences have been modified successfully");
						if (auditFlag)
							auditLogThread.sendItToDB();
						/*code for audit log ends*/
						String[] vCComps = discInfo.getAllServersOfType("Virtual_center");
						for (int i=0; i<vCComps.length; i++)
						{
							String vcVar = vCComps[i];
							String vcVal[] = discInfo.getFieldValuesForServer("Virtual_center",vcVar);
							ArrayList vcValList = new ArrayList();
							for (int p=0; p<vcVal.length; p++)
							{
								vcValList.add(vcVal[p].toLowerCase());
							}
							ArrayList agents = new ArrayList();
							if (vcValList.contains(ipAddress.toLowerCase())) //Check this VC is added as a component thru Add/Modify
							{
								String vc = vcVar.substring(vcVar.indexOf(":")+1);
								vc = vc.substring(0,vc.indexOf(":"));
								agents = new ArrayList(externalInfo.getAgentsForHost(vc));
								for (int j=0; j<agents.size(); j++)
								{
									String agent = agents.get(j).toString();
									String[] agentVars = agIniFile.getVariables(agent);
									for (int k=0; k<agentVars.length; k++)
									{
										String agentVar = agentVars[k];
										String agentVal = agIniFile.getValue(agent,agentVar);
										if (agentVal.toLowerCase().indexOf("-vc_user") > 0)
										{
											String valHost = agentVal.substring(agentVal.indexOf("-host")+5).trim();
											valHost = valHost.substring(0,valHost.indexOf(" ")).trim();
											String agentVarLower = agentVar.toLowerCase();

											if(agentVarLower.indexOf(":"+ipAddress.toLowerCase()+":") > 0 || 
												agentVarLower.endsWith(":"+ipAddress.toLowerCase()) || 
												valHost.equalsIgnoreCase(ipAddress)) // IP / Host name / Nick , any one equals with VC, then do.
											{
												String strTmp1 = agentVal.substring(0,agentVal.toLowerCase().indexOf("-vc_user")+8).trim();
												String strTmp2 = agentVal.substring(agentVal.toLowerCase().indexOf("-vc_user")+8).trim();
												strTmp2 = strTmp2.substring(strTmp2.indexOf(" ")).trim();
												agentVal = strTmp1 + " " + UName + " " + strTmp2;

												int vcPwdIndex = agentVal.toLowerCase().indexOf("-vc_password");
												if (vcPwdIndex > -1)
												{
													strTmp1 = agentVal.substring(0,vcPwdIndex+12).trim();
													strTmp2 = agentVal.substring(vcPwdIndex+12).trim();
													strTmp2 = strTmp2.substring(strTmp2.indexOf(" ")).trim();
													agentVal = strTmp1 + " " + UPass + " " + strTmp2;
												}
												int sslIndex = agentVal.toLowerCase().indexOf("-ssl");
												if (sslIndex > -1)
												{
													strTmp1 = agentVal.substring(0,sslIndex+4).trim();
													strTmp2 = agentVal.substring(sslIndex+4).trim();
													strTmp2 = strTmp2.substring(strTmp2.indexOf(" ")).trim();
													agentVal = strTmp1 + " " + ssl.toLowerCase() + " " + strTmp2;
												}
												int webPortIndex = agentVal.toLowerCase().indexOf("-webport");
												if (webPortIndex > -1)
												{
													strTmp1 = agentVal.substring(0,webPortIndex+8).trim();
													strTmp2 = agentVal.substring(webPortIndex+8).trim();
													strTmp2 = strTmp2.substring(strTmp2.indexOf(" ")).trim();
													agentVal = strTmp1 + " " + webPort + " " + strTmp2;
												}
												agIniFile.setValue(agent,agentVar,agentVal);
											}
										}
									}
								}
								agIniFile.saveFile();
							}
						}
					}
					//Code ends for VC Comp Modification
					if(from.startsWith("hmc"))
						subVal = ssl+"#"+UName+"#"+UPass+"#"+isDis+"#"+hName;
					else
						subVal = ssl+"#"+UName+"#"+UPass+"#"+isDis+"#"+webPort;
					testIniFileWr = EgConfigFilesSync.getInstance(s_iniFile_dir + uiFile,true);
					String checkOldEntry = testIniFileWr.getValue(sub,ipAddress);
					if (checkOldEntry == null || !checkOldEntry.equalsIgnoreCase(subVal))
					{
						testIniFileWr.setValue(sub,ipAddress,subVal);
						testIniFileWr.saveFile();
					}
					EgConfigFilesSync.releaseInstance(testIniFileWr);
					//change.stopDiscovery();

					ArrayList typeList = new ArrayList();
					String componentTypeEsx = "";
					if(from.startsWith("hmc"))
					{
						typeList.add("hmc_server");
						typeList.add("pSeries_server");
						componentTypeEsx = "hmc_server,pSeries_server";
					}
					else
					{
						typeList.add("VmEsx_i_server");
						typeList.add("Virtual_center");
						typeList.add("VmVdi_i_server");
						componentTypeEsx = "VmEsx_i_server,Virtual_center,VmVdi_i_server";
					}
					boolean append=false;
					String testName="";
					String testParams="";
					String testPeriod="";
					String tempParams="";
					String paramName="";
					String paramValue="";
					String tmpStr="";
					StringTokenizer st=null;
					StringTokenizer st1=null;

					EgSpecsInfo egSpecs = new EgSpecsInfo("manager");
					ArrayList testEnabled = new ArrayList();
					ArrayList testListForAuditlog = new ArrayList();
					ArrayList compListForAuditlog = new ArrayList();
					ArrayList listOfComponents = null;
					EgRoleInfo ri = EgRoleInfo.getInstance(session.getId(),(String)session.getAttribute("sess_userid"));

					for(int h=0;h<typeList.size();h++)
					{
						Hashtable nickAgentMap = new Hashtable();
						String thisType = (String) typeList.get(h);
						listOfComponents = new ArrayList(Arrays.asList(ri.getAllServersOfType(thisType)));
						if(listOfComponents != null && listOfComponents.size()>0)
						{
							for(int j=0;j<listOfComponents.size();j++)
							{
								String nickName = (String)listOfComponents.get(j);
								nickName = nickName.substring(nickName.indexOf(":")+1);
								List agentList = getAgents(thisType, nickName);
								if(agentList != null && agentList.size() >0)
								{
									for(int k=0;k<agentList.size();k++)
									{
										ArrayList agentNameList = new ArrayList();
										agentNameList.add(nickName);
										String thisSubject = (String) agentList.get(k);
										if(nickAgentMap.containsKey(thisSubject))
										{
											ArrayList lst = (ArrayList) nickAgentMap.get(thisSubject);
											if(!lst.contains(nickName))
												lst.add(nickName);
											nickAgentMap.put(thisSubject, lst);
										}
										else
										{
											nickAgentMap.put(thisSubject, agentNameList);
										}
									}
								}
							}
						}

						String[] strTests = egSpecs.getTestsForServer(thisType);
						if (strTests != null && strTests.length > 0)
						{
							testEnabled = new ArrayList(Arrays.asList(strTests));
						}

						ArrayList availPatterns = new ArrayList();
						Enumeration ee = nickAgentMap.keys();
						if(from.startsWith("hmc"))
						{
							while(ee.hasMoreElements())
							{
								String thisElement = (String) ee.nextElement();
								String [] variables = agIniFile.getVariables(thisElement);
								ArrayList nickList = (ArrayList) nickAgentMap.get(thisElement);
								for(int j=0;nickList != null && j<nickList.size();j++)
								{
									String thisNick = (String) nickList.get(j);
									for (int k=0;k<testEnabled.size();k++)
									{
										String thisTest = (String) testEnabled.get(k);
										String thisPattern = getResultantPattern(thisType,thisNick,thisTest,variables);
										if(thisPattern != null && !thisPattern.equals("null") && thisPattern.length() > 0)
										{
											String value = agIniFile.getValue(thisElement,thisPattern);
											int hmcIndex = value.toLowerCase().indexOf("-hmc_server");
											if (hmcIndex > -1)
											{
												String tmpStr1 = value.substring(0,hmcIndex + "-hmc_server".length()).trim();
												String tmpStr2 = value.substring(hmcIndex + "-hmc_server".length() +1).trim();
												String hmc_server = tmpStr2.substring(0,tmpStr2.indexOf(" ")).trim();
												if (hmc_server.equals(ipAddress))
												{
													int esxUserIndex = value.toLowerCase().indexOf("-hmc_user");
													if (esxUserIndex > -1)
													{
														tmpStr1 = value.substring(0,esxUserIndex + "-hmc_user".length()).trim();
														tmpStr2 = value.substring(esxUserIndex + "-hmc_user".length() +1).trim();
														tmpStr2 = tmpStr2.substring(tmpStr2.indexOf(" ")).trim();
														value = tmpStr1 + " "+UName+ " "+tmpStr2;
													}
													int esxPwdIndex = value.toLowerCase().indexOf("-hmc_password");
													if(esxPwdIndex > -1)
													{
														tmpStr1 = value.substring(0,esxPwdIndex + "-hmc_password".length()).trim();
														tmpStr2 = value.substring(esxPwdIndex + "-hmc_password".length() +1).trim();
														tmpStr2 = tmpStr2.substring(tmpStr2.indexOf(" ")).trim();
														value = tmpStr1 + " "+UPass+ " "+tmpStr2;
													}
													int sslIndex = value.toLowerCase().indexOf("-ssl");
													if (sslIndex > -1)
													{
														tmpStr1 = value.substring(0,sslIndex + "-ssl".length()).trim();
														tmpStr2 = value.substring(sslIndex + "-ssl".length() +1).trim();
														tmpStr2 = tmpStr2.substring(tmpStr2.indexOf(" ")).trim();
														value = tmpStr1 + " "+ssl.toLowerCase()+ " "+tmpStr2;
													}
													agIniFile.setValue(thisElement,thisPattern,value);
													if (!testListForAuditlog.contains(thisTest))
														testListForAuditlog.add(thisTest);

													if (!compListForAuditlog.contains(thisNick))
														compListForAuditlog.add(thisNick);
												}
											}
											agIniFile.saveFile();
										}
									}
								}
							}
						}
						else
						{
							while(ee.hasMoreElements())
							{
								String thisElement = (String) ee.nextElement();
								String [] variables = agIniFile.getVariables(thisElement);
								ArrayList nickList = (ArrayList) nickAgentMap.get(thisElement);
								for(int j=0;nickList != null && j<nickList.size();j++)
								{
									String thisNick = (String) nickList.get(j);
									for (int k=0;k<testEnabled.size();k++)
									{
										String thisTest = (String) testEnabled.get(k);
										String thisPattern = getResultantPattern(thisType,thisNick,thisTest,variables);
										if(thisPattern != null && !thisPattern.equals("null") && thisPattern.length() > 0)
										{
											String value = agIniFile.getValue(thisElement,thisPattern);
											int vCenterIndex = value.toLowerCase().indexOf("-virtual_center");
											if (vCenterIndex > -1)
											{
												String tmpStr1 = value.substring(0,vCenterIndex + "-virtual_center".length()).trim();
												String tmpStr2 = value.substring(vCenterIndex + "-virtual_center".length() +1).trim();
												String virtual_center = tmpStr2.substring(0,tmpStr2.indexOf(" ")).trim();
												if (virtual_center.equals(ipAddress))
												{
													int esxUserIndex = value.toLowerCase().indexOf("-esx_user");
													if (esxUserIndex > -1)
													{
														tmpStr1 = value.substring(0,esxUserIndex + "-esx_user".length()).trim();
														tmpStr2 = value.substring(esxUserIndex + "-esx_user".length() +1).trim();
														tmpStr2 = tmpStr2.substring(tmpStr2.indexOf(" ")).trim();
														value = tmpStr1 + " "+UName+ " "+tmpStr2;
													}
													int esxPwdIndex = value.toLowerCase().indexOf("-esx_password");
													if(esxPwdIndex > -1)
													{
														tmpStr1 = value.substring(0,esxPwdIndex + "-Esx_password".length()).trim();
														tmpStr2 = value.substring(esxPwdIndex + "-Esx_password".length() +1).trim();
														tmpStr2 = tmpStr2.substring(tmpStr2.indexOf(" ")).trim();
														value = tmpStr1 + " "+UPass+ " "+tmpStr2;
													}
													int sslIndex = value.toLowerCase().indexOf("-ssl");
													if (sslIndex > -1)
													{
														tmpStr1 = value.substring(0,sslIndex + "-ssl".length()).trim();
														tmpStr2 = value.substring(sslIndex + "-ssl".length() +1).trim();
														tmpStr2 = tmpStr2.substring(tmpStr2.indexOf(" ")).trim();
														value = tmpStr1 + " "+ssl.toLowerCase()+ " "+tmpStr2;
													}
													int webPortIndex = value.toLowerCase().indexOf("-webport");
													if(webPortIndex > -1)
													{
														tmpStr1 = value.substring(0,webPortIndex + "-webport".length()).trim();
														tmpStr2 = value.substring(webPortIndex + "-webport".length() +1).trim();
														tmpStr2 = tmpStr2.substring(tmpStr2.indexOf(" ")).trim();
														value = tmpStr1 + " "+webPort+ " "+tmpStr2;
													}

													agIniFile.setValue(thisElement,thisPattern,value);
													if (!testListForAuditlog.contains(thisTest))
														testListForAuditlog.add(thisTest);

													if (!compListForAuditlog.contains(thisNick))
														compListForAuditlog.add(thisNick);
												}
											}
											agIniFile.saveFile();
										}
									}
								}
							}
						}
					}
					EgConfigFilesSync.releaseInstance(agIniFile);
					if(testListForAuditlog != null && testListForAuditlog.size() > 0)
					{
						for(int i=0; i<testListForAuditlog.size(); i++)
						{
							String auditStr = (String) testListForAuditlog.get(i);
							if(auditStr != null && auditStr.length() > 0 && auditFlag)
							{
								auditLogThread.setCurrentValue("05~~Auto configured test(s)","$test$:"+auditStr);
							}
						}
					}

					if(compListForAuditlog != null && compListForAuditlog.size() > 0)
					{
						Server serverName = new Server();
						for(int i=0; i<compListForAuditlog.size(); i++)
						{
							String auditStr = (String) compListForAuditlog.get(i);
							auditStr = auditStr.substring(0,auditStr.indexOf(":"));
							if(auditStr != null && auditStr.length() > 0 && auditFlag)
							{
								auditLogThread.setCurrentValue("06~~Auto configured host(s)",auditStr);
							}
						}
					}
					//change.startDiscovery("1", true);
					if(from.equals("modify") || from.equals("hmcModify"))
					{
						rootObj.put("requestStatus","success");
						JSONObject resultMsg = new JSONObject();
						resultMsg.put("title",_mapping.getTextDescription("admin.discovery.Modify")+" "+server);
						resultMsg.put("message1",_mapping.getTextDescription("admin.discovery.Details has been modified successfully"));
						rootObj.put("result",resultMsg);
						out.println(rootObj.toString());
						return ;
					}
				}
			}
		}
		catch(Exception e)
		{
			System.out.println("Exception in vCenter auto discover"+e);
			e.printStackTrace();
		}
	}

	IniFile agIniFileRe = new IniFile(agFile_dir + agFile);
	if(from.equals("delete") || from.equals("hmcDelete") || from.equals("cloudDelete"))
	{
		Vector sess_vec = new Vector();
		String vc = request.getParameter("vc");
		String hmc = request.getParameter("hmc");
		//change.stopDiscovery();
		ArrayList vCentersList = new ArrayList();
		ArrayList esxiCompsList = new ArrayList();
		ArrayList vdiCompsList = new ArrayList();
		ArrayList awsCloudlist = new ArrayList();
		ArrayList awsRegionlist = new ArrayList();
		ArrayList totalCCstoDelete = new ArrayList();
		ArrayList dontDeleteList = new ArrayList();
		ArrayList totalVCstoDelete = new ArrayList();
		ArrayList pSeriesList = new ArrayList();
		ArrayList hmcServersList = new ArrayList();
		ArrayList totalHmcToDelete = new ArrayList();
		if (from.equals("hmcDelete"))
		{
			String[] pSeries = discInfo.getAllServersOfType("pSeries_server");
			String[] hmcServers = discInfo.getAllServersOfType("hmc_server");
			boolean deleteHmc = false;
			if (pSeries != null)
			{
				pSeriesList = new ArrayList(Arrays.asList(pSeries));
			}
			if (hmcServers != null)
			{
				hmcServersList = new ArrayList(Arrays.asList(hmcServers));
			}
			if (pSeriesList.size() == 0 && hmcServersList.size() == 0 )
			{
				deleteHmc = true;
				StringTokenizer stt = new StringTokenizer(hmc,",");
				while (stt.hasMoreTokens())
				{
					totalHmcToDelete.add(stt.nextToken());
				}
			}
			else
			{
				ArrayList tmpList = new ArrayList();
				ArrayList agents = new ArrayList();

				String CompType = "pSeries_server";
				for (int i=0; i<pSeriesList.size(); i++)
				{
					String esxi = (String)pSeriesList.get(i);
					esxi = esxi.substring(esxi.indexOf(":")+1);
					tmpList.addAll(getAgents(CompType,esxi));
				}
				for (int i=0; i<tmpList.size(); i++) // removing duplicates
				{
					String agent = (String) tmpList.get(i);
					if (!agents.contains(agent))
						agents.add(agent);
				}
				StringTokenizer ss=new StringTokenizer(hmc,",");
				while(ss.hasMoreTokens())
				{
					String hmcIp=ss.nextToken();
					deleteHmc = true;
					totalHmcToDelete.add(hmcIp);

					for (int i=0; i<agents.size(); i++) // pSeries comps
					{
						String[] allLines=agIniFileRe.getLinesUnderSubject((String)agents.get(i));
						if(allLines != null && allLines.length > 0)
						{
							for(int j=0; j<allLines.length; j++)
							{
								String testParameters=allLines[j];
								int hmcIndex = testParameters.toLowerCase().indexOf("-hmc_server");
								if (hmcIndex > -1)
								{
									String tmpHmcIp = testParameters.substring(hmcIndex + "-hmc_server".length()+1).trim();
									tmpHmcIp = tmpHmcIp.substring(0,tmpHmcIp.indexOf(" ")).trim();
									if (tmpHmcIp.equalsIgnoreCase(hmcIp))
									{
										dontDeleteList.add(hmcIp);
										deleteHmc=false;
										break;
									}
								}
							}
							if (!deleteHmc) break;
						}
					}

					for (int i=0; i<hmcServers.length; i++) // added hmc components
					{
						String hmcServer = hmcServers[i];
						String[] fieldValues = discInfo.getFieldValuesForServer("hmc_server",hmcServer);
						ArrayList fieldList = new ArrayList(Arrays.asList(fieldValues));
						if (fieldList.contains(hmcIp))
						{
							if (!dontDeleteList.contains(hmcIp))
								dontDeleteList.add(hmcIp);
						}
					}
				}
			}
		}
		else if (from.equals("cloudDelete")) //for cloud starts here --- karthika
		{

			vc = request.getParameter("account")==null?"":request.getParameter("account");
			String[] awsCloud = discInfo.getAllServersOfType("AWS_EC2_Cloud");
			String[] awsRegion = discInfo.getAllServersOfType("AWS_EC2_Region"); //doubts VmVdi_i_server
			boolean deleteCC = false;
			if (awsCloud != null)
			{
				awsCloudlist = new ArrayList(Arrays.asList(awsCloud));
			}
			if (awsRegion != null)
			{
				awsRegionlist = new ArrayList(Arrays.asList(awsRegion));
			}
			if (awsCloudlist.size() == 0 && awsRegionlist.size() == 0)
			{
				deleteCC = true;
				StringTokenizer stt = new StringTokenizer(vc,",");
				while (stt.hasMoreTokens())
				{
					totalCCstoDelete.add(stt.nextToken());
				}
			}
			else
			{
				ArrayList tmpList = new ArrayList();
				ArrayList agents = new ArrayList();

				String CompType = "AWS_EC2_Region";
				for (int i=0; i<awsRegionlist.size(); i++)
				{
					String ec2reg = (String)awsRegionlist.get(i);
					ec2reg = ec2reg.substring(ec2reg.indexOf(":")+1);
					tmpList.addAll(getAgents(CompType,ec2reg));
				}
				
				for (int i=0; i<tmpList.size(); i++) // removing duplicates
				{
					String agent = (String) tmpList.get(i);
					if (!agents.contains(agent))
						agents.add(agent);
				}
				
				StringTokenizer ss=new StringTokenizer(vc,",");
				while(ss.hasMoreTokens())
				{
					String awsAccName=ss.nextToken();
					deleteCC = true;
					totalCCstoDelete.add(awsAccName);
					for (int i=0; i<agents.size(); i++) // AWS_EC2_Region comps
					{
						String[] allLines=agIniFileRe.getLinesUnderSubject((String)agents.get(i));
						if(allLines != null && allLines.length > 0)
						{
							for(int j=0; j<allLines.length; j++)
							{
								String testParameters=allLines[j];
								int vCenterIndex = testParameters.toLowerCase().indexOf("-host");
								if (vCenterIndex > -1)
								{
									String tmpip = testParameters.substring(vCenterIndex + "-host".length()+1).trim();
									tmpip = tmpip.substring(0,tmpip.indexOf(" ")).trim();
									String tempAwsAccName = awsAccName+"/";
									if (tmpip.startsWith(tempAwsAccName))
									{
										dontDeleteList.add(awsAccName);
										deleteCC=false;
										break;
									}
								}
							}
							if (!deleteCC) break;
						}
					}
					
					for (int i=0; i<awsCloud.length; i++) // added vc components
					{
						String awsAcc = awsCloud[i];
						String[] fieldValues = discInfo.getFieldValuesForServer("AWS_EC2_Cloud",awsAcc);
						ArrayList fieldList = new ArrayList(Arrays.asList(fieldValues));
						if (fieldList.contains(awsAccName))
						{
							if (!dontDeleteList.contains(awsAccName))
								dontDeleteList.add(awsAccName);
						}
					}
				}
			
			}
		}
		else
		{
			String[] vCenters = discInfo.getAllServersOfType("Virtual_center");
			String[] esxiComps = discInfo.getAllServersOfType("VmEsx_i_server");
			String[] vdiComps = discInfo.getAllServersOfType("VmVdi_i_server"); //doubts VmVdi_i_server
			boolean deleteVC = false;

			if (vCenters != null)
			{
				vCentersList = new ArrayList(Arrays.asList(vCenters));
			}
			if (esxiComps != null)
			{
				esxiCompsList = new ArrayList(Arrays.asList(esxiComps));
			}
			if (vdiComps != null)
			{
				vdiCompsList = new ArrayList(Arrays.asList(vdiComps));
			}

			if (vCentersList.size() == 0 && esxiCompsList.size() == 0 && vdiCompsList.size() == 0)
			{
				deleteVC = true;
				StringTokenizer stt = new StringTokenizer(vc,",");
				while (stt.hasMoreTokens())
				{
					totalVCstoDelete.add(stt.nextToken());
				}
			}
			else
			{
				ArrayList tmpList = new ArrayList();
				ArrayList agents = new ArrayList();

				String CompType = "VmEsx_i_server";
				for (int i=0; i<esxiCompsList.size(); i++)
				{
					String esxi = (String)esxiCompsList.get(i);
					esxi = esxi.substring(esxi.indexOf(":")+1);
					tmpList.addAll(getAgents(CompType,esxi));
				}
				CompType = "VmVdi_i_server";
				for (int i=0; i<vdiCompsList.size(); i++)
				{
					String vdi = (String)vdiCompsList.get(i);
					vdi = vdi.substring(vdi.indexOf(":")+1);
					tmpList.addAll(getAgents(CompType,vdi));
				}
				for (int i=0; i<tmpList.size(); i++) // removing duplicates
				{
					String agent = (String) tmpList.get(i);
					if (!agents.contains(agent))
						agents.add(agent);
				}

				StringTokenizer ss=new StringTokenizer(vc,",");
				while(ss.hasMoreTokens())
				{
					String vcIp=ss.nextToken();
					deleteVC = true;
					totalVCstoDelete.add(vcIp);
					for (int i=0; i<agents.size(); i++) // Esxi and vdi comps
					{
						String[] allLines=agIniFileRe.getLinesUnderSubject((String)agents.get(i));
						if(allLines != null && allLines.length > 0)
						{
							for(int j=0; j<allLines.length; j++)
							{
								String testParameters=allLines[j];
								int vCenterIndex = testParameters.toLowerCase().indexOf("-virtual_center");
								if (vCenterIndex > -1)
								{
									String tmpip = testParameters.substring(vCenterIndex + "-virtual_center".length()+1).trim();
									tmpip = tmpip.substring(0,tmpip.indexOf(" ")).trim();
									if (tmpip.equalsIgnoreCase(vcIp))
									{
										dontDeleteList.add(vcIp);
										deleteVC=false;
										break;
									}
								}
							}
							if (!deleteVC) break;
						}
					}

					for (int i=0; i<vCenters.length; i++) // added vc components
					{
						String vCenter = vCenters[i];
						String[] fieldValues = discInfo.getFieldValuesForServer("Virtual_center",vCenter);
						ArrayList fieldList = new ArrayList(Arrays.asList(fieldValues));
						if (fieldList.contains(vcIp))
						{
							if (!dontDeleteList.contains(vcIp))
								dontDeleteList.add(vcIp);
						}
					}
				}
			}
		}
		//change.startDiscovery("1", true);
		if (from.equals("hmcDelete"))
		{
			auditLogThread.setValue("Activity","Delete HMC discovery");
			String name = "";
			String hmcmap = "eg_hmcmapping.ini";
			//IniFile hmcIniFile = new IniFile(agFile_dir + hmcmap,true);
			IniFile hmcIniFile = EgConfigFilesSync.getInstance(agFile_dir + hmcmap,true);
			String dontDeleteHmcs = dontDeleteList.toString();
			dontDeleteHmcs = dontDeleteHmcs.substring(1,dontDeleteHmcs.length() -1);
			
			totalHmcToDelete.removeAll(dontDeleteList);
			testIniFileWr = EgConfigFilesSync.getInstance(s_iniFile_dir + uiFile,true);
			for (int i=0; i<totalHmcToDelete.size(); i++)
			{
				String hmcdelete = (String)totalHmcToDelete.get(i);
				testIniFileWr.deleteValue(sub,hmcdelete);
				hmcIniFile.deleteSubject(hmcdelete);
				testIniFileWr.saveFile();
				hmcIniFile.saveFile();
			}
			EgConfigFilesSync.releaseInstance(testIniFileWr);
			EgConfigFilesSync.releaseInstance(hmcIniFile);
			String hmcDeleted = totalHmcToDelete.toString();
			hmcDeleted = hmcDeleted.substring(1,hmcDeleted.length() - 1);

			if (totalHmcToDelete.size() > 0)
			{
				auditFlag = true;
				auditLogThread.setCurrentValue("ColumnName","HMC Deleted");
				auditLogThread.setCurrentValue("00~~IP address of Hardware management console","" +hmcDeleted);
				if(hmcDeleted.indexOf(",")>0)
				{
					auditLogThread.setValue("Description","HMC IPs have been deleted");
				}
				else
				{
					auditLogThread.setValue("Description","HMC IP has been deleted");
				}
				
				auditLogThread.sendItToDB();
				rootObj.put("requestStatus","success");
				JSONObject resultMsg = new JSONObject();
				resultMsg.put("title",_mapping.getTextDescription("admin.server.Auto Discovery"));
				resultMsg.put("message1",_mapping.getTextDescription("admin.discovery.Details has been deleted successfully"));
				rootObj.put("result",resultMsg);
			}
			if(dontDeleteList.size() > 0)
			{
				AuditLogThread auditlog = new AuditLogThread();
				auditlog.setValue("Category","Admin");
				auditlog.setValue("User_id",_user.getLoginID());
				auditlog.setValue("Host_ip",_user.getUserIP(session.getId()));
				auditlog.setValue("Session_id",session.getId());
				auditlog.setValue("Module","Default Test Configuration");
				auditLogThread.setCurrentValue("ColumnName","HMC Deleted");
				auditlog.setCurrentValue("00~~IP address of Hardware management console","" +dontDeleteHmcs);
				auditlog.setValue("Activity","Delete HMC discovery");
				sess_vec.addElement(_mapping.getTextDescription("admin.discovery.You cannot delete the following")+" "+server+" "+dontDeleteHmcs+". "+_mapping.getTextDescription("admin.discovery.One/more tests have been configured to use on this HMC Server"));
				auditlog.setValue("Description"," One/more tests have been configured to use on this "+server);
				auditlog.sendItToDB();

				rootObj.put("requestStatus","failed");
				errorObj.put("title",_mapping.getTextDescription("admin.server.Auto Discovery"));
				errorObj.put("message1",_mapping.getTextDescription("admin.discovery.You cannot delete the following")+" "+server+" "+dontDeleteHmcs+". "+_mapping.getTextDescription("admin.discovery.One/more tests have been configured to use on this HMC Server"));
			}
		}
		else if (from.equals("cloudDelete"))
		{

			auditLogThread.setValue("Activity","Delete Cloud Center discovery");
			String name = "";
			String cldmap = "eg_cloudmapping.ini";
			//IniFile cldIniFile = new IniFile(agFile_dir + cldmap,true);
			IniFile cldIniFile = EgConfigFilesSync.getInstance(agFile_dir + cldmap,true);
			String dontDeleteCCs = dontDeleteList.toString();
			dontDeleteCCs = dontDeleteCCs.substring(1,dontDeleteCCs.length() -1);
			totalCCstoDelete.removeAll(dontDeleteList);
			testIniFileWr = EgConfigFilesSync.getInstance(s_iniFile_dir + uiFile,true);
			for (int i=0; i<totalCCstoDelete.size(); i++)
			{
				String vc2delete = (String)totalCCstoDelete.get(i);
				testIniFileWr.deleteValue(sub,vc2delete);
				cldIniFile.deleteSubject(vc2delete);
				testIniFileWr.saveFile();
				cldIniFile.saveFile();
			}
			EgConfigFilesSync.releaseInstance(testIniFileWr);
			EgConfigFilesSync.releaseInstance(cldIniFile);
			String cldsDeleted = totalCCstoDelete.toString();
			cldsDeleted = cldsDeleted.substring(1,cldsDeleted.length() - 1);
			if (totalCCstoDelete.size() > 0)
			{
				auditFlag = true;
				auditLogThread.setCurrentValue("ColumnName","Cloud Account Deleted");
				auditLogThread.setCurrentValue("00~~Deleted Cloud Account ","" +cldsDeleted);
				auditLogThread.setValue("Description","The Cloud Account have been deleted");
				sess_vec.addElement(cldsDeleted +" - "+server+" "+_mapping.getTextDescription("admin.discovery.Details has been deleted successfully"));
				auditLogThread.sendItToDB();

				rootObj.put("requestStatus","success");
				JSONObject resultMsg = new JSONObject();
				resultMsg.put("title",_mapping.getTextDescription("admin.server.Auto Discovery"));
				resultMsg.put("message1",_mapping.getTextDescription("admin.discovery.Details has been deleted successfully"));
				rootObj.put("result",resultMsg);
			}

			if(dontDeleteList.size() > 0)
			{
				AuditLogThread auditlog = new AuditLogThread();
				auditlog.setValue("Category","Admin");
				auditlog.setValue("User_id",_user.getLoginID());
				auditlog.setValue("Host_ip",_user.getUserIP(session.getId()));
				auditlog.setValue("Session_id",session.getId());
				auditlog.setValue("Module","Default Test Configuration");
				auditlog.setCurrentValue("ColumnName","Cloud Center Deleted");
				auditlog.setCurrentValue("00~~Cloud Center IP/Host ","" +dontDeleteCCs);
				auditlog.setValue("Activity","Delete Cloud Center discovery");
				auditlog.setValue("Description"," One/more tests have been configured to use on this "+server);
				auditlog.sendItToDB();

				rootObj.put("requestStatus","failed");
				errorObj.put("title",_mapping.getTextDescription("admin.server.Auto Discovery"));
				errorObj.put("message1",_mapping.getTextDescription("admin.discovery.You cannot delete the following")+" "+server+" "+dontDeleteCCs+". "+_mapping.getTextDescription("admin.discovery.One/more tests have been configured to use on this AWS Cloud Account"));
			}
		}
		else
		{
			auditLogThread.setValue("Activity","Delete vCenter discovery");
			String name = "";
			String vcmap = "eg_vcmapping.ini";
			//IniFile vcIniFile = new IniFile(agFile_dir + vcmap,true);
			String dontDeleteVCs = dontDeleteList.toString();
			dontDeleteVCs = dontDeleteVCs.substring(1,dontDeleteVCs.length() -1);

			totalVCstoDelete.removeAll(dontDeleteList);
			testIniFileWr = EgConfigFilesSync.getInstance(s_iniFile_dir + uiFile,true);
			IniFile vcIniFile = EgConfigFilesSync.getInstance(agFile_dir + vcmap,true);
			for (int i=0; i<totalVCstoDelete.size(); i++)
			{
				String vc2delete = (String)totalVCstoDelete.get(i);
				testIniFileWr.deleteValue(sub,vc2delete);
				vcIniFile.deleteSubject(vc2delete);
				testIniFileWr.saveFile();
				vcIniFile.saveFile();
			}
			EgConfigFilesSync.releaseInstance(testIniFileWr);
			EgConfigFilesSync.releaseInstance(vcIniFile);
			String vcsDeleted = totalVCstoDelete.toString();
			vcsDeleted = vcsDeleted.substring(1,vcsDeleted.length() - 1);
			if (totalVCstoDelete.size() > 0)
			{
				auditFlag = true;
				auditLogThread.setCurrentValue("ColumnName","vCenter Deleted");
				auditLogThread.setCurrentValue("00~~Deleted vCenter IP/Host","" +vcsDeleted);
				auditLogThread.setValue("Description","The vCenter IP/Hosts have been deleted");
				sess_vec.addElement(vcsDeleted +" - "+server+" "+_mapping.getTextDescription("admin.discovery.Details has been deleted successfully"));
				auditLogThread.sendItToDB();
				rootObj.put("requestStatus","success");
				JSONObject resultMsg = new JSONObject();
				resultMsg.put("title",_mapping.getTextDescription("admin.server.Auto Discovery"));
				resultMsg.put("message1",_mapping.getTextDescription("admin.discovery.Details has been deleted successfully"));
				rootObj.put("result",resultMsg);
			}
			if(dontDeleteList.size() > 0)
			{
				AuditLogThread auditlog = new AuditLogThread();
				auditlog.setValue("Category","Admin");
				auditlog.setValue("User_id",_user.getLoginID());
				auditlog.setValue("Host_ip",_user.getUserIP(session.getId()));
				auditlog.setValue("Session_id",session.getId());
				auditlog.setValue("Module","Default Test Configuration");
				auditlog.setCurrentValue("ColumnName","vCenter Deleted");
				auditlog.setCurrentValue("00~~vCenter IP/Host ","" +dontDeleteVCs);
				auditlog.setValue("Activity","Delete vCenter discovery");
				auditlog.setValue("Description"," One/more tests have been configured to use on this "+server);
				auditlog.sendItToDB();

				rootObj.put("requestStatus","failed");
				errorObj.put("title",_mapping.getTextDescription("admin.server.Auto Discovery"));
				errorObj.put("message1",_mapping.getTextDescription("admin.discovery.You cannot delete the following")+" "+server+" "+dontDeleteVCs+". "+_mapping.getTextDescription("admin.discovery.One/more tests have been configured to use on this vCenter Server"));
			}
		}
		out.println(rootObj.toString());
		return;
	}

	if(from.equals("addEsxDiscovery") || from.equals("modifyEsxDiscovery") || from.equals("hmcAddHmcDiscovery") || from.equals("hmcModifyHmcDiscovery"))
	{
		String ipAddress = request.getParameter("ipAdd");
		String UName = request.getParameter("uname");
		String ssl = request.getParameter("ssl");
		String isDis = request.getParameter("isDiscovery");
		String conSSL = ssl.equalsIgnoreCase("True")?"Yes":"No";
		auditFlag = true;
		if(from.equals("hmcAddHmcDiscovery") || from.equals("hmcModifyHmcDiscovery"))
		{
			if(from.equals("hmcAddHmcDiscovery") && auditFlag)
			{
				/* code for audit lof starts */
				String hName = request.getParameter("hName");
				auditLogThread.setValue("Activity","Add HMC discovery");
				auditLogThread.setCurrentValue("ColumnName","HMC Added");
				auditLogThread.setCurrentValue("00~~IP address of Hardware management console",ipAddress);
				auditLogThread.setCurrentValue("01~~Host Name of Hardware management console",hName);
				auditLogThread.setCurrentValue("02~~Use SSL to connect to HMC",conSSL);
				auditLogThread.setCurrentValue("03~~Discover pSeries servers using this HMC",isDis);
				auditLogThread.setCurrentValue("04~~Username to connect to HMC ( i.e hscroot)",UName);
				auditLogThread.setCurrentValue("05~~Password for the user","*****");
				auditLogThread.setValue("Description","HMC details has been added and pSeries Discovery started successfully ");
				auditLogThread.sendItToDB();
				/* code for audit lof ends */
			}
			//change.stopDiscovery();
			//change.startDiscovery("4", true);
		}
		else
		{
			if(from.equals("addEsxDiscovery") && auditFlag)
			{
				/* code for audit lof starts */
				String webPort = request.getParameter("webport");
				auditLogThread.setValue("Activity","Add vCenter discovery");
				auditLogThread.setCurrentValue("ColumnName","vCenter Added");
				auditLogThread.setCurrentValue("00~~vCenter identity (IP or Host name)",ipAddress);
				auditLogThread.setCurrentValue("01~~Use SSL to connect to vCenter",conSSL);
				auditLogThread.setCurrentValue("02~~Web Port",webPort);
				auditLogThread.setCurrentValue("03~~Discover ESX hosts using this vCenter",isDis);
				auditLogThread.setCurrentValue("04~~Username to connect to vCenter",UName);
				auditLogThread.setCurrentValue("05~~Password for the user","*****");
				auditLogThread.setValue("Description","vCenter details has been added and Esx Discovery started successfully ");
				auditLogThread.sendItToDB();
				/* code for audit lof ends */
			}
			if(EgDiscoveryManager.KillVcDiscoveryProcess())
			{
				//change.stopDiscovery();
				//change.startDiscovery("3", true);
			}
			PrintWriter f = null;
			try
			{
				f = new PrintWriter(new FileWriter(configInfo.egDiscTrackingFile, true));
				f.close();
			}
			catch (Exception e)
			{
				if (f != null)
				{
					try
					{
						f.close();
					}
					catch (Exception ex)
					{
					}
				}
			}
		}
	}
	else if (!from.startsWith("cloud"))
	{
		if(auditFlag)
			auditLogThread.sendItToDB();

		if (from.equalsIgnoreCase("memory"))
		{
			rootObj.put("requestStatus","success");
			JSONObject resultMsg = new JSONObject();
			resultMsg.put("title",_mapping.getTextDescription("admin.discovery.Configure Memory"));
			resultMsg.put("message1",_mapping.getTextDescription("admin.discovery.Memory has been configured successfully"));
			rootObj.put("result",resultMsg);
			out.println(rootObj.toString());
			return ;
		}
	}
%>

<%!
	EgExternalInfo egExternalInfo = new EgExternalInfo("manager");

	//provide a set of agents(internal or remote agent,external agent(s)) for a component
	private List getAgents(String componentType,String componentName)
	{
		List agentsList = new ArrayList();
		Hashtable internalAgentMap = egExternalInfo.getInternalAgentMap();
		String tempCompType = new String(componentType);
		String tempCompName = new String(componentName);
		String agentNickName = "";
		boolean isRemote = false;
		if (tempCompName.indexOf(":") > -1)
		{
			if (tempCompType.equals("Oracle_server"))
			{
				tempCompName = tempCompName.substring(0,tempCompName.indexOf(":"));
			}
			else
			{
				tempCompName = tempCompName.substring(0,tempCompName.lastIndexOf(":"));
			}
		}
		// To fetch the exact agent for the selected component - start
		isRemote = egExternalInfo.isRemoteBased(tempCompName);
		if (isRemote)
		{
			//Agentless
			agentNickName = egExternalInfo.getRemoteAgentForHost(tempCompName);
		}
		else
		{
			//Auto or Manual
			String agentName = egExternalInfo.getAgentFor(tempCompName);
			if (agentName != null) //Manual
			{
				if (internalAgentMap != null && internalAgentMap.containsKey(agentName))
				{
					agentNickName = (String)internalAgentMap.get(agentName);
				}
				else
				{
					agentNickName = agentName;
				}
			}
			else //Auto
			{
				agentNickName = tempCompName;
			}
		}
		//adding an internal agent (or) a remote agent
		agentsList.add(agentNickName);
		// To fetch the exact agent for the selected component - end

		//To fetch the external agent for the selected component type - starts
		boolean hasExternalAgent = egExternalInfo.hasExternalAgent(tempCompName);
		if (hasExternalAgent)
		{
			String extAgents[] = egExternalInfo.getExternalAgentsForHost(tempCompName);
			//adding one or more external agent(s)
			agentsList.addAll(Arrays.asList(extAgents));
		}
		//To fetch the external agent for the selected component type - ends

		return agentsList;
	}

	private String getResultantPattern(String componentType, String compName, String testName, String[] testVariables)
	{
		String tempResultantPattern = null;
		String specificPattern_A = testName + ":" + componentType + ":" + compName;
		String specificPattern_B = testName + ":" + componentType + ":" + compName.substring(0,compName.indexOf(":"));
		String defaultPattern_A = testName + "::" + compName;
		String defaultPattern_B = testName + "::" + compName.substring(0,compName.indexOf(":"));
		List listTestVariables = Arrays.asList(testVariables);
		if(listTestVariables.contains(specificPattern_A))
		{
			tempResultantPattern = specificPattern_A;
		}
		else if(listTestVariables.contains(specificPattern_B))
		{
			tempResultantPattern = specificPattern_B;
		}
		else if(listTestVariables.contains(defaultPattern_A))
		{
			tempResultantPattern = defaultPattern_A;
		}
		else if(listTestVariables.contains(defaultPattern_B))
		{
			tempResultantPattern = defaultPattern_B;
		}
		return tempResultantPattern;
	}
%>