<%
/**
 *	Processing page for EgNewServer.jsp
 *
 *	@author		Sridevi.T
 *	@created	7/09/2000
 *	@modified	26/03/2003	Sandhya		NICKNAMES
 *				23/04/2003	Arun		Disallow nickname change if already used in a topology
 *				24/04/2003	Arun		Sandhya made me revert to singleserver checks because the results page
 *										was not shown properly.
 *				25/04/2003	Arun		Nickname changes are saved in all relevant INIs and DB tables
 *				26/04/2003	Saravanan	Srinivas made me revert to single server checks!
 *				05/09/2003	Arun		Update UserRegistry when a new segment is added
 *				26/05/2004	Arun		Updates Internal_agent_mapping in eg_external.ini when
 *										different nicknames are managed by the same agent.
 *				09/07/2004	Arun		Updated eg_external.ini if client emulation is set for the component.
 *				15/07/2004	Arun		Changes made to Remote/External agents should be reflected in the DB.
 */
%>

<%@ include file="../../EgTrackerAJSON.jsp"%>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>

<%@ page import = "java.sql.*" %>

<%@ page import = "com.egurkha.admin.ComponentAdd"%>
<%@ page import = "com.egurkha.admin.UpdateNicknames" %>
<%@ page import = "com.egurkha.admin.AuditLogThread"%>
<%@ page import = "com.egurkha.admin.UserAssociateComponent"%>
<%@ page import = "com.egurkha.admin.RemoteAgent"%>
<%@ page import = "com.egurkha.util.StringUtils"%>
<%@ page import = "com.eg.EgTopoInfo"%>
<%@ page import = "egurkha.EgUIUtils"%>
<%@ page import = "egurkha.EgDBConnectUI"%>
<%@ page import = "egurkha.TestConfigSpecsBean"%>
<%@ page import = "egurkha.EgDbAdapterUI"%>
<%@ page import = "egurkha.ServerBean"%>
<%@ page import = "egurkha.LayerBean"%>
<%@ page import = "net.sf.json.JSONObject"%>
<%@ page import = "net.sf.json.JSONArray"%>
<%@ page import = "java.util.UUID"%>

<%!
	/*****************************************************************
	* below method is copied from EgSpecsInfo.java
	* public String findTest ()
	* 	find a the right test in the test mapping section
	*	e.g., ProcessTest:: or ProcessTest:Web_server:...
	******************************************************************/
	public String findTest(String test, String server,String vars[])
	{
		int c = vars.length;
		StringBuffer sb = new StringBuffer(128);
		synchronized (sb)
		{
			sb.append(test);
			sb.append(":");
			sb.append(server);
			sb.append(":");
		}
		String s = sb.toString();
		for (int i = 0; i < c; i++)
		{
			if (vars[i].startsWith(s))
				return (vars[i]);
		}
		StringBuffer sb2 = new StringBuffer(128);
		synchronized (sb2)
		{
			sb2.append(test);
			sb2.append("::");
		}
		s = sb2.toString();
		for (int i = 0; i < c; i++)
		{
			if (vars[i].startsWith(s))
				return (vars[i]);
		}
		return (null);
	}
%>
<%
	response.setHeader("Cache-Control","no-store");
	response.setHeader("Pragma","no-cache");
	response.setDateHeader("Expires", -1);
	response.setContentType("application/json;charset=UTF-8");
%>

<%
	JSONObject rootJSON = new JSONObject();
	rootJSON.put("success","true");
	String selectedServerGroup = request.getParameter("selectedServerGroup");
	if (selectedServerGroup == null)
	{
		selectedServerGroup = "-1";
	}
	String stype = request.getParameter("stype");
	String treeViewSrc = request.getParameter("treeViewSrc");
	String fromResultPage = request.getParameter("fromResultPage");
	String isExistingAggType = request.getParameter("isExistingAggType");
	String dispCompName = request.getParameter("dispCompName");
	String mserver = request.getParameter("modifyserver");
	String oldhostname=request.getParameter("oldhostname");
	rootJSON.put("selectedServerGroup",selectedServerGroup);
	rootJSON.put("selectedServer",stype);
		
	boolean isAggregateLink = stype != null && stype.startsWith("Agg_");
	EgUsersInfo usersInfo = new EgUsersInfo();
	boolean isNamedUsersCert = EgInstallInfo.isnamedUserLicense;

	if(isExistingAggType != null && isExistingAggType.equals("false"))
	{
		// Block is common for this and aggAddAllp.jsp pages - starts
		int count=1;
		EgAggregateInfo aggregateInfo = new EgAggregateInfo("manager");
		String aggServerTypes[] = new String[count];
		aggServerTypes[0] = stype;
		ArrayList templates = aggregateInfo.getAllTestTemplates();
		Hashtable testMeasureCount = new Hashtable();
		for(int m=0;m<templates.size();m++)
		{
			String test_template_name = templates.get(m).toString();
			String ntm[] = aggregateInfo.getVariables(test_template_name);//ntm - normal test measures
			if(ntm != null && ntm.length>0)
			{
				String atm=aggregateInfo.getValue(test_template_name,ntm[0]);//atm - aggregate test measures
				if(atm != null && atm.indexOf(":")>0)
				{
					testMeasureCount.put(atm.substring(0,atm.indexOf(":")),(ntm.length+""));
				}
			}
		}
		IniFile specsIniFile = new IniFile(EgInstallInfo.getInstallDir() + "/manager/config/eg_specs.ini");
		String test_spec_var[] = null;		
		Vector TEST_SPECIFICATION_VAR = specsIniFile.getVariables("TEST_SPECIFICATION",true);
		Vector TEST_SPECIFICATION_VAL = specsIniFile.getAllValues("TEST_SPECIFICATION");

		String default_enabled_normal_tests = specsIniFile.getValue("TEST_MAPPING",stype.substring(4));
		String dents[] = StringUtils.getTokens(default_enabled_normal_tests,",");
		ArrayList dentsList = new ArrayList();
		if(dents != null && dents.length>0)
		{
			for(int m=0;m<dents.length;m++)
			{
				if(dents[m].endsWith("_cf"))
					continue;
				dentsList.add(dents[m]);//default enabled normal performance tests
			}
		}
		//specsIniFile = null;
		default_enabled_normal_tests = null;
		ArrayList defaultEnabledTemplates = aggregateInfo.getDefaultEnbaledTemplates();
		Hashtable testMappingHt = new Hashtable();
		Hashtable defaultTestMappingHt = new Hashtable();
		Hashtable testSpecification = new Hashtable();
		Hashtable mytable = new Hashtable();
		String n_type = stype.substring(4);
		String testPeriod = null;
		Hashtable testPeriodMapping = new Hashtable();
		for(int i=0;i<TEST_SPECIFICATION_VAR.size();i++)
		{
			String tmp = (String)TEST_SPECIFICATION_VAR.get(i);
			if(tmp.indexOf("::")>-1)
			{
				continue;
			}
			if(tmp.indexOf(":"+n_type+":")>0)
			{
				testPeriod = (String)TEST_SPECIFICATION_VAL.get(i);
				testPeriod = testPeriod.substring(testPeriod.lastIndexOf(",")+1).trim();
				if(testPeriod.length()==0)
				{
					testPeriod = "300";
				}
				String normalTestName = tmp.substring(0,tmp.indexOf(":"));
				testPeriodMapping.put(normalTestName,testPeriod);
				if(mytable.containsKey(n_type))
				{
					ArrayList filter = (ArrayList) mytable.get(n_type);
					filter.add(tmp);
				}
				else
				{
					ArrayList filter = new ArrayList();
					filter.add(tmp);
					mytable.put(n_type,filter);
				}
			}
		}
		specsIniFile = null;
		String displayName[] = new String[count];
		String imageType[] = new String[count];
		String layers[] = new String[count];
		Arrays.fill(imageType,"aggregate");
		boolean error = false;
		int errorIndex = 0;
		EgTablesInfo tablesInfo = new EgTablesInfo("manager");

		String aggServerType = null;
		String normalServerType = null;
		String layerLeves[] = null;
		String layer = null;
		String levelStr = null;
		ArrayList layersForServer = null;
		String aggTestsStr = null;
		String defAggTestsStr = null;
		Hashtable antest = null;
		String a_test = null;
		String n_test = null;

		String test_spec = "";
		String agg_test_spec = "";
		String dummy123 = "";

		String m_count = "";
		String spec_val = null;

		String normalTestName = null;
		String rat = null;
		String layersStr = "";
		Hashtable nickHt = null;
		boolean testsAssociated = true;
		for(int i=0;i<aggServerTypes.length;i++)
		{
			aggServerType = aggServerTypes[i];
			normalServerType = aggServerType.substring(aggServerType.indexOf("_")+1);
			ArrayList normalServerList = new ArrayList();
			normalServerList.add(normalServerType);
			nickHt = aggregateInfo.getDisplayNames(normalServerList);
			if(nickHt.containsKey(normalServerType))
			{
				displayName[i] = (String) nickHt.get(normalServerType);
			}
			else
			{
				String display = normalServerType;
				if(display.indexOf("_")>-1)
				{
					String tmp[] = StringUtils.getTokens(display,"_");
					display = "";
					for(int j=0;j<tmp.length;j++)
					{
						display+=tmp[j];
					}
				}
				if(display.length()<=6)
				{
					displayName[i] = display.toUpperCase();
				}
				else
				{
					displayName[i] = display.substring(0,6).toUpperCase();
				}
			}
			layersForServer = tablesInfo.getLayersForComponent(normalServerType);
			int layersCount = layersForServer.size();
			layerLeves = new String[layersCount];
			for(int j=0;j<layersCount;j++)
			{
				layer = (String)layersForServer.get(j);
				levelStr = tablesInfo.getLevelForLayer(normalServerType, layer);
				try
				{
					int level = Integer.parseInt(levelStr.trim());
					if(layersCount==1)
					{
						if(level == -1)
						{
							layerLeves[0] = layer;
						}
						else
						{
							layerLeves[level] = layer;
						}
					}
					else
					{
						layerLeves[++level] = layer;
					}
				}
				catch(Exception e)
				{
					error=true;
					errorIndex=i;
					break;
				}
			}
			if(error)
				break;
			layersForServer.clear();
			layersForServer = new ArrayList(Arrays.asList(layerLeves));
			Collections.reverse(layersForServer);
			layersStr = "";
			for(int s=0;s<layersForServer.size();s++)
			{
				layersStr += (String)layersForServer.get(s)+",";
			}
			layersStr = layersStr.substring(0,layersStr.length()-1);
			layers[i] = layersStr;
			aggTestsStr = null;
			defAggTestsStr = null;
			antest = new Hashtable();

			ArrayList validAggTests = aggregateInfo.getValidAggTests(aggServerType);
			ArrayList validTemplateTests = aggregateInfo.getValidTemplateTests(aggServerType);
			for(int k=0;k<validTemplateTests.size();k++)
			{
				normalTestName = (String)validTemplateTests.get(k);
				rat = aggregateInfo.getRelatedAggregateTest(normalTestName);
				if(!StringUtils.isNull(rat))
				{
					validAggTests.remove(rat);
					antest.put(rat,normalTestName);
					if(aggTestsStr==null)
					{
						aggTestsStr = rat;
					}
					else
					{
						aggTestsStr += ","+rat;
					}
					if(defaultEnabledTemplates.contains(normalTestName+"_Template"))
					{
						if(defAggTestsStr==null)
						{
							if(dentsList != null && !dentsList.isEmpty() && dentsList.contains(normalTestName))
							{
								defAggTestsStr = rat;
							}
						}
						else if(dentsList != null && !dentsList.isEmpty() && dentsList.contains(normalTestName))
						{
							defAggTestsStr += ","+rat;
						}
					}
				}
			}
			if(defAggTestsStr==null)
			{
				defAggTestsStr="";
			}
			for(int k=0;k<validAggTests.size();k++)//remaining aggregate tests to be assigned to this component type
			{
				rat = (String) validAggTests.get(k);
				normalTestName = aggregateInfo.getTestName(rat);
				antest.put(rat,normalTestName);
				testMeasureCount.put(rat,(aggregateInfo.getMeasuresForTest(rat).size()+""));
				if(StringUtils.isNull(aggTestsStr))
				{
					aggTestsStr = rat;
				}
				else
				{
					aggTestsStr += ","+rat;
				}
			}
			Iterator itr_2 = antest.keySet().iterator();
			while(itr_2.hasNext())
			{
				try
				{
					a_test = (String) itr_2.next();
					n_test = (String)antest.get(a_test);
					if(!mytable.containsKey(normalServerType))
					{
						break;
					}
					ArrayList alist = (ArrayList)mytable.get(normalServerType);
					if(alist == null || alist.size()==0)
					{
						error=true;
						errorIndex=i;
						break;
					}
					test_spec_var = (String[])alist.toArray(new String[alist.size()]);
					test_spec = findTest(n_test,normalServerType,test_spec_var);
					boolean portBased = false;
					int sindex = TEST_SPECIFICATION_VAR.indexOf(test_spec);
					if(sindex>-1)
					{
						String dummyStr = (String)TEST_SPECIFICATION_VAL.get(sindex);
						if(dummyStr.indexOf(" -port ")>-1)
						{
							portBased = true;
						}
					}
					agg_test_spec = test_spec;
					dummy123 = ":"+normalServerType+":";
					if(test_spec != null && test_spec.indexOf(dummy123)>0)
					{
						agg_test_spec = StringUtils.replace(agg_test_spec,n_test,a_test);
						agg_test_spec = StringUtils.replace(agg_test_spec,normalServerType,aggServerType);
						m_count = (String)testMeasureCount.get(a_test);
						if(portBased)
						{
							spec_val = "$hostName,-auto, -host $hostIp -port $portNo -excludeDescriptor none -aggregateDescriptor true -agentless y -rptName $hostName -mCount "+m_count+", "+(String)testPeriodMapping.get(n_test);
						}
						else
						{
							spec_val = "$hostName,-auto, -host $hostIp -excludeDescriptor none -aggregateDescriptor true -agentless y -rptName $hostName -mCount "+m_count+", "+(String)testPeriodMapping.get(n_test);
						}
						testSpecification.put(agg_test_spec,spec_val);
					}
				}
				catch(Exception e)
				{
					e.printStackTrace();
					error=true;
					errorIndex=i;
					break;
				}
			}
			mytable.clear();
			if(error)
				break;
			if(!StringUtils.isNull(aggTestsStr))
			{
				defaultTestMappingHt.put(aggServerType,aggTestsStr);
				testMappingHt.put(aggServerType,defAggTestsStr);
			}
			else
			{
				testsAssociated=false;
			}
		}
		/*
			work to write everything into ini files starts
		*/
		boolean discoverUpdated = false;
		boolean tablesUpdated = false;
		boolean specsUpdated = false;
		UpdateAndTransmitICInfo updateICInfo = new UpdateAndTransmitICInfo();
		if(!error && testsAssociated)
		{
			Vector specVec = new Vector();
			specVec.add(testMappingHt);
			specVec.add(defaultTestMappingHt);
			specVec.add(testSpecification);
			if(updateICInfo.createAggregateImages(aggServerTypes,displayName,imageType))
			{
				discoverUpdated=true;
				if(updateICInfo.updateLayersForAggregateServer(aggServerTypes,layers))
				{
					tablesUpdated = true;
					if(updateICInfo.updateSpecsForServer(specVec))
					{
						specsUpdated = true;
					}
				}
			}
		}
		if(!specsUpdated)
		{
			aggregateInfo.saveFile();
			for(int i=0;i<aggServerTypes.length;i++)
			{
				updateICInfo.removeServer(aggServerTypes[i]);
			}
			rootJSON.put("requestStatus","failed");
			JSONObject obj = new JSONObject();
			obj.put("Error_Title",_mapping.getTextDescription("admin.error.Add Aggregate Component"));
			obj.put("Error_URL","EgAggregateTree.jsp");
			obj.put("Error_Msg_Count","2");
			obj.put("Error_Msg_1",_mapping.getTextDescription("admin.error.Possible Reason"));
			if(!testsAssociated)
			{
				obj.put("Error_Msg_2",_mapping.getTextDescription("admin.error.No aggregate tests found to create component type")+" <b>"+_mapping.getComponentTypeDescription(aggServerTypes[errorIndex])+"</b>.");
			}
			else if(error)
			{
				obj.put("Error_Msg_2",_mapping.getTextDescription("admin.error.Error while assigning layers to aggregate component type")+" "+_mapping.getComponentTypeDescription(aggServerTypes[errorIndex])+".");				
			}
			else if(!discoverUpdated)
			{
				obj.put("Error_Msg_2",_mapping.getTextDescription("admin.error.Unabel to create new image for aggregate component type")+".");		
			}
			else if(!tablesUpdated)
			{
				obj.put("Error_Msg_2",_mapping.getTextDescription("admin.error.Unable to add entries into ini file eg_tables")+".");
			}
			else if(!specsUpdated)
			{
				obj.put("Error_Msg_2",_mapping.getTextDescription("admin.error.Unable to add entries into ini file eg_specs")+".");
			}
			rootJSON.put("Error_Info",obj);
		}
		else
		{
			for(int k=0;k<aggServerTypes.length;k++)
			{
				String server = aggServerTypes[k];
				aggregateInfo.setValue("AGGREGATE_TYPES",server,"yes");
				aggregateInfo.setValue("COMPONENT_TYPE_MAPPING",server,server.substring(server.indexOf("_")+1));
			}
			aggregateInfo.saveFile();
			aggregateInfo = new EgAggregateInfo("manager");
		}
		// Block is common for this and aggAddAllp.jsp pages - ends
	}
	
	egurkha.ConfigTopology EgConfigTopo = new egurkha.ConfigTopology();
	egurkha.ServiceBean servicer = new egurkha.ServiceBean();
	egurkha.UserBean user = new egurkha.UserBean();
	egurkha.TestConfigSpecsBean testlist = new egurkha.TestConfigSpecsBean();

%>


<%!
	EgAggregateInfo aggregateInfo = new EgAggregateInfo("manager");  //skm

	private String removeSpaces(List l)
	{
		StringBuffer strBuffer = new StringBuffer();
		for(int i=0;i<l.size();i++)
		{
			strBuffer.append(((String)l.get(i)).trim());
			strBuffer.append(",");
		}
		String tempStr = strBuffer.toString().trim();
		return tempStr.substring(0,tempStr.length()-1);
	}
	//skm
%>

<%
	EgConfigTopo.createFile("eg_services.ini");
	int compSize = Integer.parseInt(EgConfigTopo.getValues("MISC_ARGS","MaxManagedComponentsForDisc"));
	EgRoleInfo egRoleInfo = EgRoleInfo.getInstance(session.getId(),(String)session.getAttribute("sess_userid"));
	EgDiscInfo egDiscInfo = new EgDiscInfo("manager");
	String[] sTypes = egRoleInfo.getServerTypes();
	boolean hasLimitExceeded=false;
	Vector managedAllComps = egDiscInfo.getAllManagedComponents();
	if (managedAllComps != null && (managedAllComps.size() > compSize))
	{
		hasLimitExceeded = true;
	}
	/* for user-comp mapping - START*/
	int usrLicStatus = 0;
	//String userExtAgent = "";
	String user_id = _user.getLoginID();
	EgCertUsage egCertUsage = new EgCertUsage();
	ArrayList usersList = egCertUsage.getAllLimitedCompAccessUsers(true);
	boolean isLimitedAdmin = (usersList != null && usersList.contains(user_id));
	boolean isMspModel = EgUuidInfo.isMspModel();
	String userCompMap = EgConfigInfo.egMgrConfigDir + "eg_usercompmapping.ini";
	UserAssociateComponent uacObj = new UserAssociateComponent(_user.getLoginID(),_user.getUserIP(session.getId()),session.getId());
	EgUuidInfo uuidInfo = new EgUuidInfo();
	/* for user-comp mapping - END*/

	/*int cnt=0;
	if (sTypes != null && sTypes.length > 0)
	{
		for (int st=0;st<sTypes.length;st++)
		{
			String[] strComps = egRoleInfo.getAllServersOfType(sTypes[st]);
			if (strComps.length > 0)
			{
				cnt = cnt + strComps.length;
				if (cnt > compSize)
				{
					hasLimitExceeded = true;
					break;
				}
			}
		}
	}*/
	String junk = "";
	String var = "";
	String new_var = "";
	String new_var_name = "";
	String hsid = "";
	String prevSid = null;
	String strCombine = "";
	boolean needSave = false;
	//String stype = request.getParameter("stype");
	String hostip = request.getParameter("hostip");
	String hostname = "";
	String sportno = request.getParameter("sportno");
	String hportno = request.getParameter("hportno");
	if(mserver == null || !mserver.equals("true"))
	{
		hportno = sportno;
	}
	String mtscheck = request.getParameter("mts");
	String strPass = request.getParameter("strPass");
	String action = request.getParameter("action");

	//Issue :Add comp1. Then add comp2 to same server by clickhere option in comp1 Result page. comp1 get removed.
	if(!StringUtils.isNull(fromResultPage) && fromResultPage.equals("true"))
	{
		oldhostname = "";
	}
	String remoteAgent = "";
	//String remoteAgent = request.getParameter("remoteAgent");
	//String rumRemAgent = request.getParameter("rumRemAgent");
	String rumUrl = "";
	String rumService = "";
	String remoteUser = request.getParameter("aluser");
	String remotepwd = request.getParameter("alpwd");
	String remotemode = request.getParameter("almode");
	String remotealos = request.getParameter("alos");
	String sshPort = request.getParameter("sshPort");
	String remoteType = request.getParameter("enableRemoteAgent");
	String remoteEncrypt = request.getParameter("alencrypt");
	String remoteKeyFile = request.getParameter("alkeyfile");
	/*....... For Auto Topology .... (Start)*/
	String frmTopology = request.getParameter("frmTopology");
	String frmPage = request.getParameter("frmPage");
	String topoSegName = request.getParameter("topoSegName");
	String initPort = request.getParameter("initPort");
	/*....... For Auto Topology .... (End)*/
	String hostNameToCertCheck = oldhostname;
	String server_type = request.getParameter("servertype");
	String server_name = request.getParameter("servername");
	boolean addHostAsAgent = false;
	IniFile extObj = new IniFile(EgInstallInfo.getInstallDir()+"/manager/config/eg_external.ini");
	Vector nickAloneServerList = extObj.getVariables("NickName_Alone_Servers",true);

	String[] compAgentGenVars = extObj.getVariables("Auto_Agent_Creation");
	ArrayList compAgentGenVarsList = new ArrayList();
	if(compAgentGenVars != null && compAgentGenVars.length > 0)
	{
		compAgentGenVarsList = new ArrayList(Arrays.asList(compAgentGenVars));
	}
	if(stype != null && stype != "")
	{
		if(stype.equals("Real_user_monitor"))
		{
			String isJavaSelected = request.getParameter("isJavaSelected");
			String isDotNetSelected = request.getParameter("isDotNetSelected");
			String isOthersSelected = request.getParameter("isOthersSelected");
			StringBuffer sbf = new StringBuffer();
			if(isJavaSelected.equals("true"))
				sbf.append("Java").append(",");
			if(isDotNetSelected.equals("true"))
				sbf.append("Dotnet").append(",");
			if(isOthersSelected.equals("true"))
				sbf.append("Others").append(",");;
			String selectedLanguages = sbf.toString();
			if(selectedLanguages != null && selectedLanguages.length() > 0)
				selectedLanguages = selectedLanguages.substring(0,selectedLanguages.lastIndexOf(","));
			remoteAgent = request.getParameter("rumRemAgent");
			rumUrl = request.getParameter("rumUrl");
			rumService = request.getParameter("rumService");
			hostname= request.getParameter("rumNickName");
			server_name = hostname + server_name;
			remoteType = "true";
			remotemode = "Perfmon";
			sportno = "NULL";
			if(rumUrl != null && rumUrl != "")
			{
				IniFile testsIniwr = 	EgConfigFilesSync.getInstance(EgInstallInfo.getInstallDir()+"/manager/config/eg_tests.ini");
				
				if(mserver!=null &&  mserver.equals("true"))
				{
					if(dispCompName!=null && !dispCompName.trim().equals(hostname))
					{
						testsIniwr.deleteValue("Real_user_monitor_URL_Mapping",dispCompName);
						testsIniwr.setValue("Real_user_monitor_URL_Mapping",hostname,rumUrl);
						String old_siteName=testsIniwr.getValue("Real_user_Website_Mapping",dispCompName);
						if(old_siteName!=null && old_siteName.equals(""))
						{
							testsIniwr.deleteValue("Real_user_Website_Mapping",dispCompName);
							testsIniwr.setValue("Real_user_Website_Mapping",hostname,old_siteName);
						}
					}
					else
					{
						testsIniwr.setValue("Real_user_monitor_URL_Mapping",hostname,rumUrl);
						testsIniwr.setValue("RUM_Language_Mapping",hostname,selectedLanguages);
					}
				}
				else
				{
					testsIniwr.setValue("Real_user_monitor_URL_Mapping",hostname,rumUrl);
					testsIniwr.setValue("RUM_Language_Mapping",hostname,selectedLanguages);
				}
				testsIniwr.saveFile();
				EgConfigFilesSync.releaseInstance(testsIniwr);
			}
		}
		else
		{
			remoteAgent = request.getParameter("remoteAgent");
			hostname = request.getParameter("hostname");
			
			if(stype.equalsIgnoreCase("NodeJS"))
			{
				UUID compUUID = UUID.randomUUID();
				String compGUID=compUUID.toString()+"-"+System.currentTimeMillis();
				Hashtable nickIpMap= egDiscInfo.getNickIpMap();
				String agentHostIP="localhost";
				if(remoteAgent!=null && remoteAgent.length()>0){
					agentHostIP =(String)nickIpMap.get(remoteAgent);
				}
				IniFile testsIniwr = 	EgConfigFilesSync.getInstance(EgInstallInfo.getInstallDir()+"/manager/config/eg_tests.ini");
				String compName = hostname + ":" + sportno;
				if(oldhostname!=null && oldhostname.length() > 0){
					String oldhostPort=request.getParameter("hportno");
					compGUID=testsIniwr.getValue("NODE_COMPONENT_ID_MAPPING",oldhostname+":"+oldhostPort);
					testsIniwr.deleteValue("NODE_COMPONENT_ID_MAPPING",oldhostname+":"+oldhostPort);

					String temp =testsIniwr.getValue("NODE_COMPONENT_ID_MAPPING",compGUID);
					testsIniwr.deleteValue("NODE_COMPONENT_ID_MAPPING",temp);
				}
				testsIniwr.setValue("NODE_COMPONENT_ID_MAPPING",compName,compGUID);
				testsIniwr.setValue("NODE_COMPONENT_ID_MAPPING",compGUID,compName);
				testsIniwr.saveFile();
				EgConfigFilesSync.releaseInstance(testsIniwr);
				ArrayList attNodeList=new ArrayList();
				rootJSON.put("hostName",hostname);
				rootJSON.put("portNo",sportno);
				rootJSON.put("nodeGUID",compGUID);
				rootJSON.put("agentHostIP",agentHostIP);
			}
		}
		if(compAgentGenVarsList != null && compAgentGenVarsList.contains(stype))//For remote Agent Add
		{
			addHostAsAgent = true;
		}
	}

	//Nickname formation with suffix for special comp types
	IniFile mgrmiscIni =  new IniFile(EgInstallInfo.getInstallDir() + "/manager/config/eg_mgrmisc.ini");
	String splComponents[] = mgrmiscIni.getVariables("Microsoft_Components");
	ArrayList splCompList = new ArrayList(Arrays.asList(splComponents));
	if (stype != null && splCompList.contains(stype))
	{
		String hostnameSuffix = request.getParameter("hostnameSuffix");
		String hostSuffix = (hostname.length()>4) ? hostname.substring(hostname.length()-4) : "";
		if (hostnameSuffix != null && hostnameSuffix.length()>0 && (!hostSuffix.equalsIgnoreCase(hostnameSuffix)))
		{
			hostname += hostnameSuffix;
		}
	}

	String[] nickAloneTypes = extObj.getVariables("NickName_Alone_Servers");
	List nickAloneTypesList = new ArrayList();
	boolean hideHostIPField = false;
	if (nickAloneTypes != null)
	{
		nickAloneTypesList = Arrays.asList(nickAloneTypes);
	}
	if (nickAloneTypesList.contains(stype))
	{
		hideHostIPField = true; 
	}
	if (hideHostIPField && (hostip == null || hostip.trim().equals("")))
	{
		hostip = hostname;
	}

	rootJSON.put("host_IP",hostip);
	rootJSON.put("host_Name",hostname);
	String host_ip = request.getParameter("hostIp");
	if (hostNameToCertCheck!= null && hostNameToCertCheck.trim().length() < 1)
	{
		hostNameToCertCheck = hostname;
	}
	IniFile serIni = new IniFile(EgInstallInfo.getInstallDir() + "/manager/config/eg_services.ini");
	String servers[] = serIni.getVariables("AGENTLESS_SERVERS");
	ArrayList agentlessServers = null; // contains the list of agentless servers
	if (servers != null)
	{
		agentlessServers = new ArrayList(Arrays.asList(servers));
	}
	if (remoteType == null && agentlessServers != null && agentlessServers.contains(stype))
	{
		remoteType = "true";
	}

	String addCompForDiscovery = serIni.getValue("MISC_ARGS","AddComponentForDiscovery");
	
	//String remote_vmware = request.getParameter("remote_vmware");
	String vmwarehostentry = request.getParameter("vmwarehostentry");
	String siteSupport = request.getParameter("siteflag");				//.....For AggregateSite

	EgServicesInfo servicesInfo = new EgServicesInfo("manager");
	boolean isAllowHostName = servicesInfo.isAllowHostNames();
	
	/* code for auditlog starts */
	String auditNos = "01~~";
	String isAggType = request.getParameter("isAggregateType");
	boolean isAggregateType = (isAggType != null && isAggType.equals("true")?true:false);
	//String mserver = request.getParameter("modifyserver");
	boolean modifying = (mserver != null && mserver.equals("true"));
	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());
	if(frmTopology !=null && frmTopology.equals("yes"))
	{
		if(frmPage!= null && frmPage.equalsIgnoreCase("configSeg"))
		{
			auditLogThread.setValue("Module","Configured Segments");
		}
		else if(frmPage!= null && frmPage.equalsIgnoreCase("DiscSeg")) 
		{
			auditLogThread.setValue("Module","Discovered Segments");
		}
	}
	else
	{
		auditLogThread.setValue("Module","Components");
	}

	if(isAggregateType)
	{
		remoteType = "true";
		remotemode = "Aggregate";
	}
	if(modifying)
	{		
		if(stype.endsWith("_ex"))
			auditLogThread.setValue("Description","Component "+hostname + " of type " +stype + " has been modified");
		else
			auditLogThread.setValue("Description","Component "+hostname + " of type " +"$ctype$:"+stype + " has been modified");
		auditLogThread.setValue("Activity","Modify Component");
	}
	else
	{
		if(stype.endsWith("_ex"))
		{
			auditLogThread.setValue("Description","Component "+hostname + " of type " +stype + " has been created");
		}
		else
		{
			if(!addHostAsAgent)
			{
				auditLogThread.setValue("Description","Component "+hostname + " of type " +"$ctype$:"+stype + " has been created");
			}
		}
		auditLogThread.setValue("Activity","Add Component");
	}
	/* code for auditlog ends */

	//for esx server
	String underVmware =request.getParameter("underVmware");
	String esxServer = request.getParameter("esxServer");
	//karthika for cloud
	String underCloud =request.getParameter("underCloud");
	String cloudServer = request.getParameter("cloudServer");

	if (underCloud != null && underCloud.equals("on")) // New ExtUI change 
	{
		underCloud = "true";
	}
	else
	{
		underCloud = "false";
	}
	

	if (underVmware != null && underVmware.equals("on")) // New ExtUI change 
	{
		underVmware = "true";
	}
	else
	{
		underVmware = "false";
	}
	
	String isPassive = request.getParameter("isPassive");
	if(isPassive == null)
		isPassive = "false";
	else
		isPassive = isPassive.toLowerCase();
		
	if (isPassive.equalsIgnoreCase("yes") || isPassive.equalsIgnoreCase("true"))
		isPassive = "true";
	else
		isPassive = "false";

	String intAgentMode = "";
	String currAgents = "";

	StringTokenizer st;
	String serverType = null;
	String oldAlias = null;
	String oldPort = null;
	String sid = request.getParameter("sid");
	String currAgent = request.getParameter("currAgents");
	intAgentMode = request.getParameter("intAgentMode");
	String s_nicks = "";
	EgExternalInfo externalInfo = new EgExternalInfo("manager");
	String prevRemAgent = externalInfo.getRemoteAgentForHost(hostname);
	if (oldhostname != null && oldhostname.length()>0)
	{
		prevRemAgent = externalInfo.getRemoteAgentForHost(oldhostname);
	}
	
	if (StringUtils.isNull(intAgentMode))
	{
		intAgentMode = "auto";
	}
	int index = strPass.indexOf(":");
	if (index > -1)
	{
		st = new StringTokenizer(strPass, ":");
		serverType = st.nextToken();
		oldAlias = st.nextToken();
		oldPort = st.nextToken();
		if (serverType.equals("Oracle_server"))
		{
			oldPort += ":"+sid;
		}
	}

	boolean remainTypeCheck = false;


	String[] allNicks = null;
	boolean allServers = (action != null && action.equals("allservers"));

	EgDiscInfo egdiscInfo = new EgDiscInfo("manager");
	ArrayList allNickNoCase = egdiscInfo.getAllNicks();
	boolean newNickAdded = !allNickNoCase.contains(hostname.toLowerCase());
	String[] oracleServers = egdiscInfo.getAllServersOfType("Oracle_server");
	
	String modify = request.getParameter("modify");
	modify = (modify != null && modify.equalsIgnoreCase("yes"))?"yes":"no";

	if (allServers)
	{
		Hashtable ht = new EgDiscInfo2("manager").getIpNickMap();
		s_nicks = (String)ht.get(hostip);
		if (s_nicks != null)
		{
			String[] tokens = StringUtils.getTokens(s_nicks, ":");
			if(modify.equals("yes"))
			{
				s_nicks = oldhostname;
				allNicks = new String[1];
				allNicks[0] = s_nicks;
			}
			else
			{
				allNicks = new String[tokens.length];
				System.arraycopy(tokens, 0, allNicks, 0, tokens.length);
			}
		}
	}
	else
	{
		allNicks = new String[1];
		allNicks[0] = oldhostname;
	}
	Hashtable agentsForOldHosts = externalInfo.getAgentsForHosts(allNicks);
	if (serverType == null)
	{
		serverType = stype;
		oldPort = sportno;
	}
	//strPass is the original value
	String variableName = strPass;

	Vector sess_vec = new Vector();
	if(isAggregateLink)
	{
		sess_vec.add(_mapping.getTextDescription("admin.server.Add/Modify Aggregate Components"));
		if(!StringUtils.isNull(treeViewSrc))
		{
			sess_vec.add("EgDispServer.jsp?qctr=1&server="+stype+"&treeViewSrc="+treeViewSrc);
		}
		else
		{
			sess_vec.add("EgDispServer.jsp?qctr=1&server="+stype);
		}
		sess_vec.add(_mapping.getTextDescription("admin.server.Add/Modify Aggregate Components"));
	}
	else
	{
		sess_vec.add(_mapping.getTextDescription("admin.server.Add/Modify components"));
		if(!StringUtils.isNull(treeViewSrc))
		{
			sess_vec.add("EgDispServer.jsp?qctr=1&server="+stype+"&treeViewSrc="+treeViewSrc+"&selectedServerGroup="+selectedServerGroup);
		}
		else
		{
			sess_vec.add("EgDispServer.jsp?qctr=1&server="+stype+"&selectedServerGroup="+selectedServerGroup);
		}
		sess_vec.add(_mapping.getTextDescription("admin.server.Add/Modify components"));
	}
	if(action != null && !action.equals("null") && !action.equals(""))
	//if(!allServers)
	{
		sess_vec.add(_mapping.getTextDescription("admin.server.Parameters configured for")+" "+_mapping.getComponentTypeDescription(stype));
		if(isAggregateLink)
		{
			sess_vec.add(_mapping.getTextDescription("admin.server.Aggregate component type")+" : "+_mapping.getComponentTypeDescription(stype));
		}
		else
		{
			sess_vec.add(_mapping.getTextDescription("admin.server.Component type")+" : "+_mapping.getComponentTypeDescription(stype));
		}
		if(hostip != null && !hostip.equals("0.0.0.0"))
		{
			if(isAllowHostName)
			{
				sess_vec.add(_mapping.getTextDescription("admin.server.Host IP/Name")+"     : "+hostip);
			}
			else
			{
				sess_vec.add(_mapping.getTextDescription("admin.server.Host IP")+"     : "+hostip);
			}
		}
		sess_vec.add(_mapping.getTextDescription("admin.server.Nick name")+"   : "+removeNull(hostname)); 
		/* code for auditlog starts */
		EgDiscInfo discInfo = new EgDiscInfo("manager");
		ArrayList siteServers = discInfo.getSiteServers();
		if(session.getAttribute("type").toString().equals("new"))
		{
			if(stype.endsWith("_ex"))
				auditLogThread.setCurrentValue(auditNos+"Component Type",stype);
			else
			{
				if(isAggregateLink)
				{
					auditLogThread.setCurrentValue(auditNos+"Aggregate component Type","$ctype$:"+stype);
				}
				else
				{
					auditLogThread.setCurrentValue(auditNos+"Component Type","$ctype$:"+stype);
				}
			}
			if (!isAggregateType && !hideHostIPField)	
			{
				auditNos = "02~~";
				if (isAllowHostName)
				{
					auditLogThread.setCurrentValue(auditNos+"Host IP/Name",hostip);
				}
				else
				{
					auditLogThread.setCurrentValue(auditNos+"Host IP",hostip);
				}
			}
			auditNos = (auditNos.equals("02~~")) ? "03~~" : "02~~" ;
			auditLogThread.setCurrentValue(auditNos+"Nick Name",hostname);
			if(isAggregateType)
			{
				if(siteServers.contains(stype))
				{
					String auditSiteValue = siteSupport.equals("true")?"Yes":"No";
					auditLogThread.setCurrentValue("Site Support",auditSiteValue);
				}
			}
		}
		else
		{
			auditNos = (auditNos.equals("02~~")) ? "03~~" : "02~~" ;
			String temp = request.getParameter("olderhostname");
			String oldSiteSupport = request.getParameter("oldsitesupport");
			if(temp == null || temp.equalsIgnoreCase("null"))
				temp = request.getParameter("oldhostname");
			auditLogThread.setPreviousValue(auditNos+"Nick Name",temp);
			if(isAggregateType)
			{
				if(siteServers.contains(stype))
				{
					String auditSiteValue = oldSiteSupport.equals("true")?"Yes":"No";
					auditLogThread.setPreviousValue("Site Support",auditSiteValue);
						auditSiteValue = siteSupport.equals("true")?"Yes":"No";
					auditLogThread.setCurrentValue("Site Support",auditSiteValue);
				}
			}
			auditLogThread.setCurrentValue(auditNos+"Nick Name",hostname);
			
			/* ------- THIS COMMENTED BLOCK IS HANDLED @ [UpdateNickNames.java] ------ */
			/* code starts */
			/* do not remove */
			/* when a component nick name is changed, it has to be reflected in Aggregate components */ 
			/*if(temp != null && !temp.equals(hostname))
			{
				ArrayList aggServerTypes = new ArrayList();
				ArrayList aggIniEntries = new ArrayList();
				IniFile aggWr = EgConfigFilesSync.getInstance(EgConfigInfo.egMgrConfigDir + "eg_aggregate.ini");
				String[] aggreagetComponents = aggWr.getVariables("AGGREGATE_COMPONENTS");
				if(aggreagetComponents !=null && aggreagetComponents.length>0)
				{
					for(int i=0;i<aggreagetComponents.length;i++)
					{
						String key = aggreagetComponents[i];
						String searchString = ":"+temp+":";								
						if(key.indexOf(searchString)!=-1)
						{
							String firstPart = key.substring(0,key.indexOf("#")+1);
							String secondPart = key.substring(key.indexOf("#")+1);
							secondPart = secondPart.substring(secondPart.indexOf(":")+1);
							String secondaryKey = ":" + firstPart + secondPart + ":";
							String keyValue = aggWr.getValue("AGGREGATE_COMPONENTS",aggreagetComponents[i]);
							//aggregateInfo.deleteValue("AGGREGATE_COMPONENTS",aggreagetComponents[i]);
							aggIniEntries.add(new IniHelper(IniHelper.DELETE,"AGGREGATE_COMPONENTS",aggreagetComponents[i],""));
							String replaceWith = ":"+hostname+":";
							key = StringUtils.replace(key,searchString,replaceWith);
							//aggregateInfo.setValue("AGGREGATE_COMPONENTS",key,keyValue);
							aggIniEntries.add(new IniHelper(IniHelper.SET,"AGGREGATE_COMPONENTS",key,keyValue));
							//aggregateInfo.saveFile();
							String[] aggregateTestInfosExclude = aggWr.getVariables("AGGREGATE_TEST_INFOS_EXCLUDED");
							if(aggregateTestInfosExclude != null && aggregateTestInfosExclude.length>0)
							{
								for(int idx=0;idx<aggregateTestInfosExclude.length;idx++)
								{
									String key1 = aggregateTestInfosExclude[idx];
									if(key1.indexOf(secondaryKey)>0)
									{
										String keyValue1 = aggWr.getValue("AGGREGATE_TEST_INFOS_EXCLUDED",key1);
										//aggregateInfo.deleteValue("AGGREGATE_TEST_INFOS_EXCLUDED",key1);
										aggIniEntries.add(new IniHelper(IniHelper.DELETE,"AGGREGATE_TEST_INFOS_EXCLUDED",key1,""));
										String searchString1 = "#" + temp + ":";
										String replaceWith1 = "#" + hostname + ":";
										String key12 = StringUtils.replace(key1,searchString1,replaceWith1);
										//aggregateInfo.setValue("AGGREGATE_TEST_INFOS_EXCLUDED",key12,keyValue1);
										//aggregateInfo.saveFile();
										aggIniEntries.add(new IniHelper(IniHelper.SET,"AGGREGATE_TEST_INFOS_EXCLUDED",key12,keyValue1));
									}
								}
							}
						}
					}
				}
				if (aggIniEntries.size() > 0)
				{
					//IniFile aggWr = EgConfigFilesSync.getInstance(EgConfigInfo.egMgrConfigDir + "eg_aggregate.ini");
					for (int agg=0;agg < aggIniEntries.size(); agg++)
					{
						IniHelper iniHelper= (IniHelper)aggIniEntries.get(agg);
						String iniAction = iniHelper.getAction();
						String sub = iniHelper.getSubject();
						String key = iniHelper.getVariable();
						String val = iniHelper.getValue();
						if (iniAction != null)
						{
							if (iniAction.equals(IniHelper.SET))
							{
								aggWr.setValue(sub,key,val);
							}
							else if (iniAction.equals(IniHelper.DELETE))
							{
								aggWr.deleteValue(sub,key);
							}
						}
					}
					aggWr.saveFile();
					//EgConfigFilesSync.releaseInstance(aggWr);
				}
				EgConfigFilesSync.releaseInstance(aggWr);
			}*/
			/* end of code */
		}
		/* code for auditlog ends */
	}

	//flag is a hidden parameter used to check for servers with no port
	//don't add sportno to sess_vec when PORT NO field is not displayed
	String flag = request.getParameter("flag");
	if(action != null && !action.equals("null") && !action.equals(""))
	//if (!allServers)
	{
		if(flag != null && flag.length()>0)
		{
			if(flag.equals("true"))
			{
				sportno = "NULL";
				hportno = "NULL";
			}
			else
			{
				auditNos = (auditNos.equals("03~~")) ? "04~~" : "03~~" ;
				sess_vec.add(_mapping.getTextDescription("admin.server.Port number")+" : "+sportno);
				/* code for auditlog starts */
				auditLogThread.setCurrentValue(auditNos+"Port Number",sportno);
				if(modifying)
				{
					String previousPortNumber = request.getParameter("previousportnumber");
					if(previousPortNumber !=null)
						auditLogThread.setPreviousValue(auditNos+"Port Number",previousPortNumber);
				}
				
				/* code for auditlog ends */
			}
		}
	}
	//For Virtual Server Host
		
	//egExtIni.createFile("eg_external.ini","save");
	IniFile extIniWr = null;
	extIniWr = EgConfigFilesSync.getInstance(EgConfigInfo.egMgrConfigDir + "eg_external.ini");
	Vector virtualServers =externalInfo.getVirtualServers();
	if (virtualServers!=null && virtualServers.size()>0 && virtualServers.contains(stype))
	{
		extIniWr.setValue("Virtual_Hosts",stype+":"+hostname+":"+sportno,hostip);
	}
	//Added by karthika for Cloud servers
	Vector cloudServers = externalInfo.getCloudServers();
	if (cloudServers!=null && cloudServers.size()>0 && cloudServers.contains(stype))
	{
		extIniWr.setValue("Cloud_Hosts",stype+":"+hostname+":"+sportno,hostip);
	}
	extIniWr.saveFile();
	EgConfigFilesSync.releaseInstance(extIniWr);

	//end
	if(stype.equals("Oracle_server"))
	{
		auditNos = (auditNos.equals("04~~")) ? "05~~" : "04~~" ;
		sid = request.getParameter("sid");		//New SID
		hsid = request.getParameter("hsid");	//Old SID
		if (action != null && !action.equals("null") && !action.equals(""))
		//if (!allServers)
		{
			sess_vec.add(_mapping.getTextDescription("admin.server.Sid")+" : "+sid);
		}
		if(variableName != null && !variableName.equals(""))
			variableName = variableName.substring(0,variableName.lastIndexOf(":"));
		/* code for auditlog starts */
		auditLogThread.setCurrentValue(auditNos+"SID",sid);
		if(modifying)
		{
			String previousSID = request.getParameter("previoussid");
			if(previousSID !=null && !previousSID.equals("null"))
				auditLogThread.setPreviousValue(auditNos+"SID",previousSID);
		}
		/* code for auditlog starts */
	}
	//When a server is deleted,it gets added in eg_disable.ini
	//A deleted server can only be manually added.
	//To manually add a deleted server,delete the corresponding server from
	//eg_disable.ini.This has to be done only when a new server is added.
	//New code
	String type =(String)session.getAttribute("type");
	if(type.equals("new") || modifying)
	{
		//EgConfigTopo.createFile("eg_disable.ini","save");
		IniFile disableIniWr = EgConfigFilesSync.getInstance(EgConfigInfo.egMgrConfigDir + "eg_disable.ini");
		if(!stype.equals("Oracle_server"))
		{
			var = stype + ":" + hostname + ":" + sportno;
			new_var_name = hostname.substring(hostname.indexOf(":")+1);
			new_var = hostname+":"+sportno+"#"+stype+"#"+new_var_name;
			//EgConfigTopo.deleteSpecValue("Deleted_Servers",var);
			disableIniWr.deleteValue("Deleted_Servers",var);
			/* [FORBIDDEN_SERVERS] entry are removed form eg_disable.ini,when you manage (Or) add the components-->S.Andrews	 */
			//EgConfigTopo.deleteSpecValue("FORBIDDEN_SERVERS",new_var);
		}
		else if(sid.indexOf(",")>=0)
		{
			st = new StringTokenizer(sid,",");
			int count = st.countTokens();
			for(int j=0; j<count; j++)
			{
				String tok = st.nextToken().trim();
				var  = stype +":" + hostname + ":" + sportno + ":" + tok;
				//EgConfigTopo.deleteSpecValue("Deleted_Servers",var);
				disableIniWr.deleteValue("Deleted_Servers",var);
				new_var_name = hostname.substring(hostname.indexOf(":")+1);
				new_var = hostname+":"+sportno+":"+tok+"#"+stype+"#"+new_var_name;
				//EgConfigTopo.deleteSpecValue("FORBIDDEN_SERVERS",new_var);
			}
		}
		else
		{
			var  = stype +":" + hostname + ":" + sportno + ":" + sid;
			//EgConfigTopo.deleteSpecValue("Deleted_Servers",var);
			disableIniWr.deleteValue("Deleted_Servers",var);
			new_var_name = hostname.substring(hostname.indexOf(":")+1);
			new_var = hostname+":"+sportno+":"+sid+"#"+stype+"#"+new_var_name;
			//EgConfigTopo.deleteSpecValue("FORBIDDEN_SERVERS",new_var);
		}

		disableIniWr.saveFile();
		EgConfigFilesSync.releaseInstance(disableIniWr);
	}
	if (stype.equals("IIS_web_server") || stype.equals("IIS_ssl_server"))
	{
		if(action != null && !action.equals("null") && !action.equals(""))
		//if (!allServers)
		{
			//get null when MTS Enabled options is disabled
			if(modifying && mtscheck == null)
			{
				if(request.getParameter("isMTSEnabled") != null && request.getParameter("isMTSEnabled").equals("Yes"))
				{
					mtscheck = "Yes";
				}
			}//end
				
			if (mtscheck==null||mtscheck.equalsIgnoreCase("null")||mtscheck.length()<=0)
				mtscheck="NONE";
			sess_vec.add(_mapping.getTextDescription("admin.server.MTS Enabled")+" : "+mtscheck);
			if(!modifying)
				auditLogThread.setCurrentValue("MTS Enabled",mtscheck);
		}
	}
	//Initialising the service bean and stopping discovery
	//To ensure integrity
	//The following line is to ensure that the stopDiscovery & startDiscovery runs inside a sync block
	IniFile infraIni = EgConfigFilesSync.getInstance(EgInstallInfo.getInstallDir() + "/manager/config/eg_infrastructure.ini");
	servicer.stopDiscovery();
	//EgConfigTopo.createFile("eg_discover.ini","save");
	strPass = stype+":"+hostname+":"+sportno;

	if (sportno != null && !sportno.equals("null") && !sportno.equals(""))
	{
		if(!StringUtils.isNull(oldhostname))
		{
			strCombine = stype+":"+oldhostname +":"+hportno;
		}
		else
		{
			strCombine = stype+":"+hostname +":"+hportno;
		}
	}
	else
	{
		if(!StringUtils.isNull(oldhostname))
		{
			strCombine = stype+":"+oldhostname +":NULL";
		}
		else
		{
			strCombine = stype+":"+hostname +":NULL";
		}
	}

	//set properties to eg_agent component test for auto manage
	/*if(action != null && !action.equals("null") && !action.equals(""))
	{
		if(stype != null && stype.equals("eG_Agent") && type.equals("new") )
		{
			String jvm_port = "-Jmx_Remote_Port local";
			String alert_logFile = "-alertFile error_log";
			String searchPart = "-searchpattern "+"Warnings:*WARN*|Errors:*ERROR*";
			String processPart = "-process eGAgent:*java*EgMain*";
			String line = jvm_port+" "+alert_logFile+" "+searchPart+" "+processPart;
		//	System.out.println(" EgNewServerpJson line : "+line);
		//	System.out.println(" EgNewServerpJson strPass : "+strPass);
			//String var_line = stype+":"+hostname+":"+sportno;
			String discParamCompMap = EgConfigInfo.egMgrConfigDir + "eg_discoveryParams.ini";
			IniFile discParamWrite = EgConfigFilesSync.getInstance(discParamCompMap);
			discParamWrite.setValue(stype,strPass,line);
			discParamWrite.saveFile();
			EgConfigFilesSync.releaseInstance(discParamWrite);
			//System.out.println(" EgNewServerpJson release eg_discoveryParams instances..");
		}
	}*/

	//added - checking SID whn modify the nick name to existing name.
	String SIDCheckForSameNick = null;
	//end
	Vector userCompIniDelList = new Vector();
	IniFile discWrite = EgConfigFilesSync.getInstance(EgConfigInfo.egMgrConfigDir + "eg_discover.ini");
	/*IniFile userCompIniWrite = EgConfigFilesSync.getInstance(userCompMap);*/
	if(action != null && !action.equals("null") && !action.equals(""))
	//if (!allServers)
	{
		//EgConfigTopo.deleteSpecValue(stype,strCombine);
		if(stype.equals("Oracle_server"))
		{
			if(!StringUtils.isNull(hsid))
			{
				String[] oldSidTokens = StringUtils.getTokens(hsid, ",");
				for (int a=0; a<oldSidTokens.length; a++)
				{
					String temp =strCombine +":"+ oldSidTokens[a].trim();
					discWrite.deleteValue(stype,temp);
					if (isLimitedAdmin)
						userCompIniDelList.add(temp);
						/*userCompIniWrite.deleteValue(user_id,temp);*/
				}
			}
			else
			{
				discWrite.deleteValue(stype,strCombine);
				if (isLimitedAdmin)
					userCompIniDelList.add(strCombine);
					/*userCompIniWrite.deleteValue(user_id,strCombine);*/
			}
		}
		else
		{
			discWrite.deleteValue(stype,strCombine);
			if (isLimitedAdmin)
				userCompIniDelList.add(strCombine);
				/*userCompIniWrite.deleteValue(user_id,strCombine);*/
		}

		//Delete the existing value
		String strVar[] = EgConfigTopo.getVariables(stype);
		if (strVar!=null)
		for(int i_ctr = 0 ;i_ctr < strVar.length ; i_ctr++)
		{
			if(stype.equals("Oracle_server"))
			{
				if(variableName != null && !variableName.equals(""))
				{
					if(strVar[i_ctr].startsWith(strCombine) || strVar[i_ctr].startsWith(variableName))
					{
						/*
						 * Before deleting the spec value, get the SID of the resulting nickname, so that
						 * if such SIDs exist, they are not lost
						 */
						String temp = EgConfigTopo.getValues(stype, strVar[i_ctr]);
						if (temp != null && !temp.trim().equals(""))
						{
							String anSid = temp.substring(temp.lastIndexOf(",")+1);
							if (prevSid == null)
							{
								prevSid = anSid;
							}
							else
							{
								List list = Arrays.asList(StringUtils.getTokens(prevSid, ","));
								if (list.indexOf(anSid) == -1)
								{
									prevSid = prevSid +","+ anSid;
								}
							}
							//added - checking SID whn modify the nick name to existing name.
							List currSIDList = Arrays.asList(StringUtils.getTokens(sid, ","));
							if (currSIDList.indexOf(anSid) == -1)
							{
								if(SIDCheckForSameNick == null)
									SIDCheckForSameNick = anSid+",";
								else
									SIDCheckForSameNick += anSid + ",";
							}
							//end
						}


						//EgConfigTopo.deleteSpecValue(stype,strVar[i_ctr]);
						discWrite.deleteValue(stype,strVar[i_ctr]);
						if (isLimitedAdmin)
							userCompIniDelList.add(strVar[i_ctr]);
							/*userCompIniWrite.deleteValue(user_id,strVar[i_ctr]);*/
					}
				}
			}
			else
			{
				if(strVar[i_ctr].equals(variableName))
				{
					//EgConfigTopo.deleteSpecValue(stype,strVar[i_ctr]);
					discWrite.deleteValue(stype,strVar[i_ctr]);
					if (isLimitedAdmin)
						userCompIniDelList.add(strVar[i_ctr]);
						/*userCompIniWrite.deleteValue(user_id,strVar[i_ctr]);*/
					if(mtscheck != null)
					{
						String hname = variableName.substring(variableName.indexOf(":")+1, variableName.lastIndexOf(":"));
						String ss[] = EgConfigTopo.getVariables("MTS_server");
						for(int a=0; a<ss.length; a++)
						{
							if(ss[a].startsWith("Format:"))
								continue;
							st = new StringTokenizer(ss[a],":");
							st.nextToken();
							if((st.nextToken()).equalsIgnoreCase(hname))
							{
								//EgConfigTopo.deleteSpecValue("MTS_server",ss[a]);
								discWrite.deleteValue("MTS_server",ss[a]);
								if (isLimitedAdmin)
									userCompIniDelList.add(ss[a]);
									/*userCompIniWrite.deleteValue(user_id,ss[a]);*/
							}
						}
					}
				}
			}
		}
	}
	/*
	 *	Write the new value
	 */
	if(action != null && !action.equals("null") && !action.equals(""))
	//if (!allServers)
	{
		/*
		 *	Set values only for a specific server
		 */
		if(!stype.equals("Oracle_server"))
		{

			if (nickAloneServerList.contains(stype) && !hostip.equals(hostname))
			{
				hostip = hostname;
			}

			if(stype.equals("Real_user_monitor"))
				strCombine = stype+","+"0.0.0.0"+","+hostname+","+sportno;
			else
				strCombine = stype+","+hostip+","+hostname+","+sportno;
			
			if(mtscheck != null)
			{
				//delete and setvalues(IIS servers)
				//EgConfigTopo.deleteSpecValue(stype,"#Unmanage|"+strPass);
				//EgConfigTopo.deleteSpecValue(stype,"#New|"+strPass);
				//EgConfigTopo.setValues(stype,strPass,strCombine+","+isPassive);

				discWrite.deleteValue(stype,"#Unmanage|"+strPass);
				discWrite.deleteValue(stype,"#New|"+strPass);
				discWrite.setValue(stype,strPass,strCombine+","+isPassive);
				updateUuidIni(uuidInfo,hostname);
				if (isLimitedAdmin)
				{
					userCompIniDelList.add("#Unmanage|"+strPass);
					userCompIniDelList.add("#New|"+strPass);
					/*userCompIniWrite.deleteValue(user_id,"#Unmanage|"+strPass);
					userCompIniWrite.deleteValue(user_id,"#New|"+strPass);*/
					//userCompIniWrite.setValue(user_id,strPass,strCombine+","+isPassive);
				}
				if(mtscheck.equals("Yes"))
				{

					//delete and setvalues(MTS_server)
					strCombine = "MTS_server"+","+hostip+","+hostname+","+"NULL";
					strPass = "MTS_server"+":"+hostname+":"+"NULL";
					//EgConfigTopo.deleteSpecValue("MTS_server","#Unmanage|"+strPass);
					//EgConfigTopo.deleteSpecValue("MTS_server","#New|"+strPass);
					//EgConfigTopo.setValues("MTS_server",strPass,strCombine+","+isPassive);

					discWrite.deleteValue("MTS_server","#Unmanage|"+strPass);
					discWrite.deleteValue("MTS_server","#New|"+strPass);
					discWrite.setValue("MTS_server",strPass,strCombine+","+isPassive);
					updateUuidIni(uuidInfo,hostname);
					if (isLimitedAdmin)
					{
						userCompIniDelList.add("#Unmanage|"+strPass);
						userCompIniDelList.add("#New|"+strPass);
						/*userCompIniWrite.deleteValue(user_id,"#Unmanage|"+strPass);
						userCompIniWrite.deleteValue(user_id,"#New|"+strPass);*/
						//userCompIniWrite.setValue(user_id,strPass,strCombine+","+isPassive);
					}
				}
			}
			else
			{
				//EgConfigTopo.deleteSpecValue(stype,"#Unmanage|"+strPass);
				//EgConfigTopo.deleteSpecValue(stype,"#New|"+strPass);
				//EgConfigTopo.setValues(stype,strPass,strCombine+","+isPassive); //set the new values into discover.ini

				discWrite.deleteValue(stype,"#Unmanage|"+strPass);
				discWrite.deleteValue(stype,"#New|"+strPass);
				if (isLimitedAdmin)
				{
					userCompIniDelList.add("#Unmanage|"+strPass);
					userCompIniDelList.add("#New|"+strPass);
					/*userCompIniWrite.deleteValue(user_id,"#Unmanage|"+strPass);
					userCompIniWrite.deleteValue(user_id,"#New|"+strPass);*/
				}
				if(stype.equals("Real_user_monitor") && mserver!=null)
				{
					if(mserver.equals("true"))
					{
						StringTokenizer s_tokenizer = new StringTokenizer(strPass,":");
						s_tokenizer.nextToken();
						String c_comp=s_tokenizer.nextToken();
						if(dispCompName!=null && !dispCompName.trim().equals(c_comp))
						{
							discWrite.deleteValue(stype,"Real_user_monitor:"+dispCompName+":NULL");
							discWrite.setValue(stype,strPass,strCombine+","+isPassive);
							if (isLimitedAdmin)
							{
								//userCompIniDelList.add("Real_user_monitor:"+dispCompName+":NULL");
								/*userCompIniWrite.deleteValue(user_id,"Real_user_monitor:"+dispCompName+":NULL");*/
								//userCompIniWrite.setValue(user_id,strPass,strCombine+","+isPassive);
							}
						}
						else
						{
							discWrite.setValue(stype,strPass,strCombine+","+isPassive);
							//if (isLimitedAdmin)
								//userCompIniWrite.setValue(user_id,strPass,strCombine+","+isPassive);
						}
					}
					
					 //set the new values into discover.ini
				}
				else
				{
					discWrite.setValue(stype,strPass,strCombine+","+isPassive); //set the new values into discover.ini
					updateUuidIni(uuidInfo,hostname);
					//if (isLimitedAdmin)
						//userCompIniWrite.setValue(user_id,strPass,strCombine+","+isPassive);
					
					if(addHostAsAgent)
					{
						RemoteAgent remAgent = new RemoteAgent();
						String addAsAgentDesc = "";
						String remStatus = "";
						for(int k=0; k<compAgentGenVars.length; k++)
						{
							String cType = compAgentGenVars[k];
							if(cType.equals(stype))
							{
								String compAgentVal = extObj.getValue("Auto_Agent_Creation",cType);
								if(compAgentVal.equalsIgnoreCase("remote"))
								{
									remStatus = remAgent.add(hostip,hostname);
								}
								if(remStatus.equals("0#eG_CLI_0024"))
								{
									addAsAgentDesc = "A "+"$ctype$:"+stype +" component and a remote agent with nickname "+hostname+" has been created";
								}
								else
								{
									if(modifying)
									{
										addAsAgentDesc = "Component "+hostname + " of type " +"$ctype$:"+stype + " has been modified";
									}
									else
									{
										addAsAgentDesc = "Component "+hostname + " of type " +"$ctype$:"+stype + " has been created";
									}
								}
								auditLogThread.setValue("Description",addAsAgentDesc);
							}
						}
					}
				}
				
			}
		}
		else //for Oracle_server types
		{
			if (prevSid == null && sid != null)
			{
				/*
				 * When a server is added for the first time, the prevSid value will be null
				 * sid contains the name of the SID being used.
				 */
				prevSid = sid;
				hsid = sid;
			}
			String[] sidTokens = StringUtils.getTokens(prevSid, ",");
			for (int a=0; a<sidTokens.length; a++)
			{
				String temp = strPass +":"+ sidTokens[a].trim();
				//strCombine = stype+","+hostip+","+hostname+","+sportno+","+isPassive+","+sidTokens[a];
				//EgConfigTopo.deleteSpecValue(stype,"#Unmanage|"+temp);
				//EgConfigTopo.deleteSpecValue(stype,"#New|"+temp);
				
				discWrite.deleteValue(stype,"#Unmanage|"+temp);
				discWrite.deleteValue(stype,"#New|"+temp);
				if (isLimitedAdmin)
				{
					userCompIniDelList.add("#Unmanage|"+temp);
					userCompIniDelList.add("#New|"+temp);
					/*userCompIniWrite.deleteValue(user_id,"#Unmanage|"+temp);
					userCompIniWrite.deleteValue(user_id,"#New|"+temp);*/
				}
				
				//EgConfigTopo.setValues(stype, temp, strCombine);
			}

			//added - checking SID whn modify the nick name to existing name.
			if(SIDCheckForSameNick != null)
			{
				sid = SIDCheckForSameNick + sid;
			}
			//end

			sidTokens = StringUtils.getTokens(sid, ",");
			//EgConfigTopo.deleteSpecValue(stype,"#Unmanage|"+strPass);
			//EgConfigTopo.deleteSpecValue(stype,"#New|"+strPass);
			discWrite.deleteValue(stype,"#Unmanage|"+strPass);
			discWrite.deleteValue(stype,"#New|"+strPass);
			if (isLimitedAdmin)
			{
				userCompIniDelList.add("#Unmanage|"+strPass);
				userCompIniDelList.add("#New|"+strPass);
				/*userCompIniWrite.deleteValue(user_id,"#Unmanage|"+strPass);
				userCompIniWrite.deleteValue(user_id,"#New|"+strPass);*/
			}
			for (int a=0; a<sidTokens.length; a++)
			{
				String temp = strPass +":"+ sidTokens[a].trim();
				strCombine = stype+","+hostip+","+hostname+","+sportno+","+isPassive+","+sidTokens[a];
				//EgConfigTopo.deleteSpecValue(stype,"#Unmanage|"+temp);
				//EgConfigTopo.deleteSpecValue(stype,"#New|"+temp);
				//EgConfigTopo.setValues(stype, temp, strCombine);
				discWrite.deleteValue(stype,"#Unmanage|"+temp);
				discWrite.deleteValue(stype,"#New|"+temp);
				discWrite.setValue(stype, temp, strCombine);
				if (isLimitedAdmin)
				{
					userCompIniDelList.add("#Unmanage|"+temp);
					userCompIniDelList.add("#New|"+temp);
					/*userCompIniWrite.deleteValue(user_id,"#Unmanage|"+temp);
					userCompIniWrite.deleteValue(user_id,"#New|"+temp);*/
					//userCompIniWrite.setValue(user_id,temp,strCombine);
				}
			}
			updateUuidIni(uuidInfo,hostname);
		}	
		String currentIspassive = request.getParameter("isPassive");
		String previousIsPassive = request.getParameter("previousispassive");

		if (previousIsPassive == null)
		{
			previousIsPassive = "No";
		}
		if (currentIspassive == null)
		{
			currentIspassive = "No";
		}
		if(!previousIsPassive.equals(""))
		{
			auditLogThread.setCurrentValue("Is Passive",currentIspassive);
			if(modifying)
			{				
				if(previousIsPassive != null && !previousIsPassive.equals("null"))
					auditLogThread.setPreviousValue("Is Passive",previousIsPassive);
			}
		}			
	}
	boolean callErrorPage = true;
	boolean callBasicErrorPage = false;
	boolean update = false;
	Vector err_msg = new Vector();
	ArrayList al = new ArrayList();
	int status = 0;

	err_msg.clear();

	/**** REMOTE AGENT CODE********/
	boolean isCTypeExternal = true;
	EgSpecsInfo specs = new EgSpecsInfo("manager");
	String[] testsForType = specs.getTestsForServer(stype);
	if (testsForType != null)
	{
		for (int a=0; a<testsForType.length; a++)
		{
			if (!specs.isTestExternal(testsForType[a],stype))
			{
				isCTypeExternal = false;
				break;
			}
		}
	}

	boolean needCertCheck = true;
	ArrayList userVdiTypes = usersInfo.getAllUserBasedCompTypes();
	if (usersInfo.isUserBasedLicense() && modifying && userVdiTypes.contains(stype))
	{ //No need for license check,If you are going to modify a vdi(User based) comp in an user based license setup.
		needCertCheck = false;
	}

	if (needCertCheck && isLimitedAdmin)
	{
		String licenseChkAction = (modifying) ? "modifying" : "adding";
		String component = stype+":"+hostNameToCertCheck+":"+hportno;//strPass;
		List orgList = uuidInfo.getOrgNames(user_id);
		int orgListLen = (orgList != null) ? orgList.size() : 0;
		for (int y=0; y<orgListLen; y++)
		{
			String org_id = orgList.get(y).toString().trim();
			GroupCertValidator grpCert = new GroupCertValidator(org_id);
			usrLicStatus = grpCert.checkMonitor (stype,org_id,component);
			grpCert.setLicenseCheckAction(licenseChkAction);
			if (usrLicStatus != 1)
			{
				grpCert.errorLogWrite(org_id,component,licenseChkAction);
				break;
			}
		}
	}

	if (remoteType != null && remoteType.equalsIgnoreCase("true"))
	{
		EgDiscInfo discInfo = new EgDiscInfo("manager");
		EgSpecsInfo specsInfo = new EgSpecsInfo("manager");
		// get manager IP
		String managerHost = specsInfo.getEGServer();
		specsInfo = null;
		EgExternalAgent e =new  EgExternalAgent(discInfo, managerHost, true);
		e.buildExternalFile();
		e = null;
		boolean alCertCheck = true;
		if (needCertCheck)
		{
			alCertCheck = user.checkAlServers (hostNameToCertCheck,stype);
		}
		if (alCertCheck)
		{
			if(remotemode != null)
			{
				if(remotemode.equalsIgnoreCase("SNMP"))
				{
					remoteUser="NotApplicable";
					remotepwd="NotApplicable";
				}
				//if(isLimitedAdmin && !userExtAgent.equals(""))
				//{
					//remoteAgent = userExtAgent;
				//}
				extIniWr = EgConfigFilesSync.getInstance(EgConfigInfo.egMgrConfigDir + "eg_external.ini");
				extIniWr.deleteValue("Remote_Agent_Mapping_Section",hostname);
				extIniWr.deleteValue("Agentless_Infos_Section",hostname);
				extIniWr.setValue("Remote_Agent_Mapping_Section",hostname,remoteAgent);
				extIniWr.saveFile();
				//EgConfigFilesSync.releaseInstance(extIniWr);
				
				//egExtIni.createFile("eg_external.ini","save");
				//egExtIni.deleteSpecValue("Remote_Agent_Mapping_Section",hostname);
				//egExtIni.deleteSpecValue("Agentless_Infos_Section",hostname);

				//egExtIni.setValues("Remote_Agent_Mapping_Section",hostname,remoteAgent);
				

				if (remoteUser == null || remoteUser.equals("") || remoteUser.equalsIgnoreCase("null"))
				{
					remoteUser = "None";
				}

				if (remotepwd == null || remotepwd.equals("") || remotepwd.equalsIgnoreCase("null"))
				{
					remotepwd = "None";
				}
				if (remoteEncrypt == null || remoteEncrypt.equals("") || remoteEncrypt.equalsIgnoreCase("null"))
				{
					remoteEncrypt = "None";
				}
				if (remoteKeyFile == null || remoteKeyFile.equals("") || remoteKeyFile.equalsIgnoreCase("null"))
				{
					remoteKeyFile = "None";
				}

				StringBuffer value = new StringBuffer(32);
				value.append(remoteUser);
				value.append(EgConstants.COMMA);

				if (remotepwd != null) // && !remotepwd.equalsIgnoreCase("null"))
				{
					remotepwd = EgCrypt.decrypt(remotepwd);
					remotepwd = EgCrypt.encrypt(remotepwd);
				}

				value.append(remotepwd);
				value.append(EgConstants.COMMA);
				value.append(remotemode);
				value.append(EgConstants.COMMA);
				value.append(remotealos);
				value.append(EgConstants.COMMA);
			
				if(!isAggregateType)
				{
					if(modifying)
					{
						//String oldenableRemoteAgent = request.getParameter("oldenableRemoteAgent");
						//if(oldenableRemoteAgent !=null && !oldenableRemoteAgent.equalsIgnoreCase("null") && oldenableRemoteAgent.trim().length()>0)
						//{
						//	if(oldenableRemoteAgent.trim().equalsIgnoreCase("true") || oldenableRemoteAgent.trim().equalsIgnoreCase("yes"))
						//		oldenableRemoteAgent ="Yes";
						//	else if(oldenableRemoteAgent.trim().equalsIgnoreCase("false") || oldenableRemoteAgent.trim().equalsIgnoreCase("no"))
						//		oldenableRemoteAgent ="No";
						//	auditLogThread.setPreviousValue("Agentless",oldenableRemoteAgent);
						//}
						if (prevRemAgent != null && prevRemAgent.trim().equals(""))
						{							
							auditLogThread.setPreviousValue("Agentless","No");
						}
						else
						{
							auditLogThread.setPreviousValue("Agentless","Yes");
						}
					}
					if(request.getParameter("enableRemoteAgent") != null && request.getParameter("enableRemoteAgent").equals("true"))
					{
						auditLogThread.setCurrentValue("Agentless","Yes");
					}
				}

				Hashtable operatingSystems = new Hashtable();
				//IniFile externalIni = new IniFile(EgInstallInfo.getInstallDir() + "/manager/config/eg_external.ini");
				String variables[] = extIniWr.getVariables("Default_Operating_Systems");
				Vector values = extIniWr.getAllValues("Default_Operating_Systems");
				if(variables != null && variables.length>0)
				{
					for(int ind=0;ind<variables.length;ind++)
						operatingSystems.put(variables[ind],values.get(ind));
				}
				Vector valuesSpecific = extIniWr.getAllValues("Specific_Operating_Systems");
				if(valuesSpecific != null && valuesSpecific.size()>0)
				{
					for(int ind=0;ind<valuesSpecific.size();ind++)
					{
						String valueStr = (String) valuesSpecific.get(ind);
						operatingSystems.put(valueStr.substring(0,valueStr.indexOf(":")),valueStr.substring(valueStr.indexOf(":")+1));			
					}
				}
				operatingSystems.put("other","Other");

				if(!isAggregateType && !stype.equals("Real_user_monitor"))
				{
					if(modifying)
					{
						String olderOSName = request.getParameter("olderosname");
						olderOSName = (String)operatingSystems.get(olderOSName.trim().toLowerCase());
						if(olderOSName !=null && !olderOSName.equalsIgnoreCase("null") && olderOSName.trim().length()>0)
						{
							auditLogThread.setPreviousValue("OS",olderOSName);
							remainTypeCheck = true;
						}
						else
						{
							auditLogThread.setPreviousValue("OS","None");
						}
					}
					String remoteOS = remotealos;
					if (operatingSystems.containsKey(remotealos))
					{
						remoteOS = operatingSystems.get(remotealos).toString();
					}
					auditLogThread.setCurrentValue("OS",remoteOS);
				}

				if(!isAggregateType)
				{
					if(modifying)
					{
						String olderModeName = request.getParameter("oldermodename");
						if(olderModeName !=null && !olderModeName.equalsIgnoreCase("null") && olderModeName.trim().length()>0)
						{
							auditLogThread.setPreviousValue("Mode",olderModeName.trim());
							remainTypeCheck = true;
						}
					}
					auditLogThread.setCurrentValue("Mode",remotemode);
				}
				if(modifying)
				{
					String olderRemoteAgentName = prevRemAgent;
					if(olderRemoteAgentName !=null && !olderRemoteAgentName.equalsIgnoreCase("null") && olderRemoteAgentName.trim().length()>0)
					{
						auditLogThread.setPreviousValue("Remote Agent",olderRemoteAgentName.trim());
						remainTypeCheck = true;
					}
					else
					{
						auditLogThread.setPreviousValue("Remote Agent","-");
					}
				}
				auditLogThread.setCurrentValue("Remote Agent",remoteAgent);

				if(!remotemode.equalsIgnoreCase("SNMP") && !remotemode.equalsIgnoreCase("Perfmon") && !remotemode.equalsIgnoreCase("other"))
				{
					if(!remoteUser.equals("NotApplicable"))
					{
						if(!isAggregateType)
						{
							auditLogThread.setCurrentValue("User",remoteUser);
							if(modifying)
							{
								String preUser = request.getParameter("$_aluser");
								if(preUser !=null && !preUser.equalsIgnoreCase("null") && preUser.trim().length()>0)
								{
									auditLogThread.setPreviousValue("User",preUser.trim());
									remainTypeCheck = true;
								}
							}
						}
					}
								
					if(!remotepwd.equals("NotApplicable"))
					{
						/*
						auditLogThread.setCurrentValue("Password","******");
						String newPassword = EgCrypt.decrypt(remotepwd);
						String oldPassword = EgCrypt.decrypt(request.getParameter("$_alpwd"));

						if(modifying)
						{			
							if(newPassword.equals(oldPassword))
								auditLogThread.setPreviousValue("Password","******");
							else
								auditLogThread.setPreviousValue("Password","*****");
						}
						*/
					}
				}
				if (StringUtils.isNull(sshPort) || sshPort.equalsIgnoreCase(EgConstants.NULL_STRING))
				{
					/*
					 * Set the default SSH port if "null" or empty
					 */
					value.append("22");
				}
				else
				{
					value.append(sshPort);
					/* code for auditlog starts*/
					if(modifying)
					{
						auditLogThread.setPreviousValue("Remote Port",request.getParameter("$_sshPort"));
						remainTypeCheck = true;
					}
					auditLogThread.setCurrentValue("Remote Port",sshPort);
					/* code for auditlog ends*/
				}
				value.append(EgConstants.COMMA);
				value.append(remoteEncrypt);
				value.append(EgConstants.COMMA);
				value.append(remoteKeyFile);

				//extIniWr = EgConfigFilesSync.getInstance(EgConfigInfo.egMgrConfigDir + "eg_external.ini");
				extIniWr.setValue("Agentless_Infos_Section", hostname, value.toString());
				extIniWr.saveFile();
				EgConfigFilesSync.releaseInstance(extIniWr);
			}
			else
			{
				//deleteSpecValue(String subject,String variable)
				//Delete the entry from eg_external.ini
				//egExtIni.createFile("eg_external.ini","save");
				//egExtIni.deleteSpecValue("Remote_Agent_Mapping_Section",hostname);
				//egExtIni.deleteSpecValue("Agentless_Infos_Section",hostname);
			}

			//e = new EgExternalAgent(discInfo, managerHost, true);
			//ArrayList a = new ArrayList();
			//a.add(hostname);
			//e.buildExternalFile(a);
			//discInfo = null;
			//e = null;

			//Vmware Vcenter eg_services.ini entries
			if (addCompForDiscovery != null && (addCompForDiscovery.trim().equalsIgnoreCase("yes") || addCompForDiscovery.trim().equalsIgnoreCase("true")))
			{
				//IniFile serviceWrite = EgConfigFilesSync.getInstance(EgConfigInfo.egMgrConfigDir + "eg_services.ini");
				IniFile servReadModeIni = new IniFile(EgConfigInfo.egMgrConfigDir + "eg_services.ini");
				ArrayList discCompList = new ArrayList();

				if (!com.egurkha.util.StringUtils.isNull(stype) && stype.equals("Virtual_center"))
				{
					String vCs[] =  servReadModeIni.getVariables("VIRTUAL_CENTER");
					List vCList = new ArrayList();
					if (vCs != null)
					{
						for (int v=0; v<vCs.length; v++)
						{
							vCList.add(vCs[v].toLowerCase());
						}
					}
					String vCenterValue =  "True#$unconfigured#$unconfigured#No#443";
					if (!vCList.contains(hostip.toLowerCase()))
					{
						discCompList.add(new IniHelper("VIRTUAL_CENTER",hostip,vCenterValue));
						//serviceWrite.setValue("VIRTUAL_CENTER", hostip, vCenterValue);
						//serviceWrite.saveFile();
					}
				}
				else if (!com.egurkha.util.StringUtils.isNull(stype) && stype.equals("Redhat_linux_mgr"))
				{
					String rhevs[] =  servReadModeIni.getVariables("RHEV");
					List rhevList = new ArrayList();
					if (rhevs != null)
					{
						for (int v=0; v<rhevs.length; v++)
						{
							rhevList.add(rhevs[v].toLowerCase());
						}
					}
					String rhevValue =  "True#$unconfigured#$unconfigured#No#443#internal";
					if (!rhevList.contains(hostip.toLowerCase()))
					{
						discCompList.add(new IniHelper("RHEV",hostip,rhevValue));
						//serviceWrite.setValue("RHEV", hostip, rhevValue);
						//serviceWrite.saveFile();
					}
				}
				else if (!com.egurkha.util.StringUtils.isNull(stype) && stype.equals("hmc_server"))
				{
					String hmcs[] =  servReadModeIni.getVariables("HMC");
					List hmcList = new ArrayList();
					if (hmcs != null)
					{
						for (int v=0; v<hmcs.length; v++)
						{
							hmcList.add(hmcs[v].toLowerCase());
						}
					}
					String pseriesValue =  "True#$unconfigured#$unconfigured#No#$unconfigured";
					if (!hmcList.contains(hostip.toLowerCase()))
					{
						discCompList.add(new IniHelper("HMC",hostip,pseriesValue));
						//serviceWrite.setValue("HMC", hostip, pseriesValue);
						//serviceWrite.saveFile();
					}
				}
				//EgConfigFilesSync.releaseInstance(serviceWrite);
				if (discCompList.size()>0)
				{
					IniFile serviceWrite = EgConfigFilesSync.getInstance(EgConfigInfo.egMgrConfigDir + "eg_services.ini");
					for (int s=0;s<discCompList.size() ;s++ )
					{
						IniHelper iniHelper = (IniHelper)discCompList.get(s);
						String sub = iniHelper.getSubject();
						String key = iniHelper.getVariable();
						String val = iniHelper.getValue();
						serviceWrite.setValue(sub, key, val);
					}
					serviceWrite.saveFile();
					EgConfigFilesSync.releaseInstance(serviceWrite);
				}
			}

		}
		else
		{
			if (discWrite != null)
				EgConfigFilesSync.releaseInstance(discWrite);
			discInfo = null;
			e = null;
			callBasicErrorPage = true;
			rootJSON.put("requestStatus","failed");
			JSONObject obj = new JSONObject();
			obj.put("Error_Title",_mapping.getTextDescription("admin.error.Add new component"));
			if(!StringUtils.isNull(treeViewSrc))
			{
				obj.put("Error_URL","EgDispServer.jsp?qctr=1&server="+stype+"&treeViewSrc="+treeViewSrc+"&selectedServerGroup="+selectedServerGroup);	
			}
			else
			{
				obj.put("Error_URL","EgDispServer.jsp?qctr=1&server="+stype+"&selectedServerGroup="+selectedServerGroup);
			}
			String msg = _mapping.getTextDescription("admin.error.You are exceeding the total/premium monitors permitted by your license")+"!";
			if (usersInfo.isUserBasedLicense())
			{
				msg += " "+_mapping.getTextDescription("admin.error.or")+" ";
				if (isNamedUsersCert)
				{
					msg += _mapping.getTextDescription("admin.error.You are exceeding the total number of named users permitted by your license")+"!";
				}
				else
				{
					msg += _mapping.getTextDescription("admin.error.You are exceeding the total number of concurrent users permitted by your license")+"!";
				}
			}
			obj.put("Error_Msg_Count","2");
			obj.put("Error_Msg_1",msg);
			msg = " "+_mapping.getTextDescription("admin.error.To upgrade your license to support additional agentless components")+", ";
			msg += _mapping.getTextDescription("admin.error.please contact") +" <b>license@eginnovations.com</b>";
			obj.put("Error_Msg_2",msg);
			if(frmTopology !=null && frmTopology.equals("yes"))
			{
				//err_msg.add("frmTopology");
			}
			//session.setAttribute("vec_Errors",err_msg);
			//response.sendRedirect("EgErrors.jsp");
			/* code for auditlog starts */
			if (usersInfo.isUserBasedLicense())
			{
				if (isNamedUsersCert)
				{
					auditLogThread.setValue("Description","You are exceeding either the total/premium monitors or named users permitted by your license");
				}
				else
				{
					auditLogThread.setValue("Description","You are exceeding either the total/premium monitors or concurrent users permitted by your license");
				}
			}
			else
			{
				auditLogThread.setValue("Description","You are exceeding the total/premium monitors permitted by your license");
			}
			auditLogThread.sendItToDB();
			/* code for auditlog ends */
			rootJSON.put("Error_Info",obj);
		}
	}
	else if (!isCTypeExternal)
	{
		/*
		 * the user has shifted from agentless to agentbased.
		 * so delete the entries from the eg_external.ini file
		 */
		//egExtIni.createFile("eg_external.ini","save");
		//egExtIni.deleteSpecValue("Remote_Agent_Mapping_Section",hostname);
		//egExtIni.deleteSpecValue("Agentless_Infos_Section",hostname);
		//egExtIni.saveFile();
		extIniWr = EgConfigFilesSync.getInstance(EgConfigInfo.egMgrConfigDir + "eg_external.ini");
		extIniWr.deleteValue("Remote_Agent_Mapping_Section",hostname);
		extIniWr.deleteValue("Agentless_Infos_Section",hostname);
		extIniWr.saveFile();
		EgConfigFilesSync.releaseInstance(extIniWr);
		
		/* code for auditlog starts */
		//if(intAgentMode !=null && intAgentMode.equalsIgnoreCase("manual"))
		{
			String tempIntAgentMode = request.getParameter("intAgentMode");
			if(tempIntAgentMode != null && !StringUtils.isNull(tempIntAgentMode))
				auditLogThread.setCurrentValue("Internal Agent Assignment",intAgentMode);
			String previousIntAgentMode = request.getParameter("previousintagentmode");
			
			if(modifying)
			{
				//String previousIntAgentMode = request.getParameter("previousintagentmode");
				if(previousIntAgentMode !=null && previousIntAgentMode.length()>0)
					auditLogThread.setPreviousValue("Internal Agent Assignment",previousIntAgentMode);
			}
		}
		/* code for auditlog ends */

		/* code for auditlog starts */

			if (!isAggregateType)	
			{
				//if(modifying && request.getParameter("enableRemoteAgent") != null && request.getParameter("enableRemoteAgent").equals("false"))
				//{
				//	String oldenableRemoteAgent = request.getParameter("oldenableRemoteAgent");
				//	if(oldenableRemoteAgent.trim().equalsIgnoreCase("true") || oldenableRemoteAgent.trim().equalsIgnoreCase("yes"))
				//		oldenableRemoteAgent ="Yes";
				//	else if(oldenableRemoteAgent.trim().equalsIgnoreCase("false") || oldenableRemoteAgent.trim().equalsIgnoreCase("no"))
				//		oldenableRemoteAgent ="No";
				//	auditLogThread.setPreviousValue("Agentless",oldenableRemoteAgent);
				//}
				if (modifying)
				{
					if (prevRemAgent != null && prevRemAgent.trim().equals(""))
					{
						auditLogThread.setPreviousValue("Agentless","No");
					}
					else
					{
						auditLogThread.setPreviousValue("Agentless","Yes");
					}
				}
				String enableRmtAgent = request.getParameter("enableRemoteAgent");
				if(enableRmtAgent == null || enableRmtAgent.equals("false"))
				{
					auditLogThread.setCurrentValue("Agentless","No");
				}
			}
		/* code for auditlog ends */
	}

	/**** REMOTE AGENT CODE********/

	if(!callBasicErrorPage)
	{
		rootJSON.put("requestStatus","failed");
		JSONObject obj = new JSONObject();
		obj.put("Error_Title",_mapping.getTextDescription("admin.error.Add new component"));
		//err_msg.add(_mapping.getTextDescription("admin.error.Add new component"));
		if(!StringUtils.isNull(treeViewSrc))
		{
			obj.put("Error_URL","EgDispServer.jsp?qctr=1&server="+stype+"&treeViewSrc="+treeViewSrc+"&selectedServerGroup="+selectedServerGroup);
			//err_msg.add("EgDispServer.jsp?qctr=1&server="+stype+"&treeViewSrc="+treeViewSrc+"&selectedServerGroup="+selectedServerGroup);
		}
		else
		{
			obj.put("Error_URL","EgDispServer.jsp?qctr=1&server="+stype+"&selectedServerGroup="+selectedServerGroup);
			//err_msg.add("EgDispServer.jsp?qctr=1&server="+stype+"&selectedServerGroup="+selectedServerGroup);
		}

		//err_msg.add(_mapping.getTextDescription("admin.error.Add new component"));

		//Pass an empty vector to the method below
		Vector v = new Vector();
		if (needCertCheck)
		{
			if (intAgentMode.equalsIgnoreCase("auto"))
				status = user.checkBasicAgentCount(stype,v,0,hostip,hostNameToCertCheck,hportno,sid); // check with Sara
			else {
				status = user.checkBasicAgentCount(stype,v,-1,hostip,hostNameToCertCheck+'#'+currAgent,hportno,sid); // check with Sara -- this is a manual addition
			}
		}else
		{
			status = 1;
		}
		//status = 2;
		if(status == 1)
		{
			update = true;
		}
		else if(status == 2 || status == 3 || status == 4 || status == 5 || status == 6)
		{
			callBasicErrorPage = true;
		}

		if (isLimitedAdmin && !callBasicErrorPage)
		{
			if (usrLicStatus == 1) 
			{
				update = true;
			}
			else if(usrLicStatus == 2 || usrLicStatus == 3 || usrLicStatus == 4  || usrLicStatus == 5)
			{
				update = false;
				callBasicErrorPage = true;
			}
		}

		if(!callBasicErrorPage)
		{			
			if(usersInfo.isUserBasedLicense() && userVdiTypes.contains(stype))
			{
				update = true;
			}
			else
			{
				if(user.checkManagedIpCount())
				{
					update = true;
				}
				else
				{
					al.clear();
					al = user.getManagedIp(0);

					if(al != null && al.size() > 0)
					{
						for(int i=0; i<al.size(); i++)
						{
							var = (String)al.get(i);
							var = var.substring(0,var.indexOf(":"));
							if(var.equals(hostname))
							{
								callErrorPage = false;
								break;
							}
						}
					}

					if(callErrorPage)
					{
						if (discWrite != null)
							EgConfigFilesSync.releaseInstance(discWrite);
						/*if (userCompIniWrite != null)
							EgConfigFilesSync.releaseInstance(userCompIniWrite);*/

						update = false;
						if (remoteType != null && remoteType.equalsIgnoreCase("true"))
						{
							EgDiscInfo discInfo = new EgDiscInfo("manager");
							EgSpecsInfo specsInfo = new EgSpecsInfo("manager");
							// get manager IP
							String managerHost = specsInfo.getEGServer();
							specsInfo = null;
							EgExternalAgent e =new  EgExternalAgent(discInfo, managerHost, true);
							e.buildExternalFile();
							discInfo = null;
							e = null;
						}
						obj.put("Error_Msg_1",_mapping.getTextDescription("admin.error.You have exceeded the number of monitored targets allowed by your license!"));
						obj.put("Error_Msg_2"," "+_mapping.getTextDescription("admin.error.To monitor additional targets")+", "+_mapping.getTextDescription("admin.error.please contact")+" <b>license@eginnovations.com</b>");
						//err_msg.add(_mapping.getTextDescription("admin.error.You have exceeded the number of monitored targets allowed by your license!"));
						//err_msg.add(" "+_mapping.getTextDescription("admin.error.To monitor additional targets")+", "+_mapping.getTextDescription("admin.error.please contact")+" <b>license@eginnovations.com</b>");
						if(frmTopology !=null && frmTopology.equals("yes"))
						{
							//err_msg.add("frmTopology");
						}
						rootJSON.put("Error_Info",obj);
						//session.setAttribute("vec_Errors",err_msg);
						//response.sendRedirect("EgErrors.jsp");
						/* code for auditlog starts */
						auditLogThread.setValue("Description","You have exceeded the number of monitored targets allowed by your license");
						auditLogThread.sendItToDB();
						/* code for auditlog ends */
					}
					else
					{
						update = true;
					}
				}
			}
		}
		else
		{
			if (remoteType != null && remoteType.equalsIgnoreCase("true"))
			{
				EgDiscInfo discInfo = new EgDiscInfo("manager");
				EgSpecsInfo specsInfo = new EgSpecsInfo("manager");
				// get manager IP
				String managerHost = specsInfo.getEGServer();
				specsInfo = null;
				EgExternalAgent e =new  EgExternalAgent(discInfo, managerHost, true);
				e.buildExternalFile();
				discInfo = null;
				e = null;
			}
			if (discWrite != null)
				EgConfigFilesSync.releaseInstance(discWrite);
			/*if (userCompIniWrite != null)
				EgConfigFilesSync.releaseInstance(userCompIniWrite);*/
			
			if(status == 2 || usrLicStatus == 3)
			{
				//err_msg.add(_mapping.getTextDescription("admin.error.You are exceeding the number of premium agents allowed by your license!"));
				//err_msg.add(" "+_mapping.getTextDescription("admin.error.To upgrade your license to support additional premium agents")+", ");
				//err_msg.add(_mapping.getTextDescription("admin.error.please contact")+" <b>license@eginnovations.com</b>");
				obj.put("Error_Msg_1",_mapping.getTextDescription("admin.error.You are exceeding the number of premium monitors allowed by your license")+"!");
				String msg = " "+_mapping.getTextDescription("admin.error.To upgrade your license to support additional premium monitors")+", ";
				msg+=_mapping.getTextDescription("admin.error.please contact")+" <b>license@eginnovations.com</b>";
				obj.put("Error_Msg_2",msg);
				if(frmTopology !=null && frmTopology.equals("yes"))
				{
					err_msg.add("frmTopology");
				}
				//session.setAttribute("vec_Errors",err_msg);
				//response.sendRedirect("EgErrors.jsp");
				/* code for auditlog starts */
				auditLogThread.setValue("Description","You are exceeding the number of premium monitors allowed by your license");
				auditLogThread.sendItToDB();
				/* code for auditlog ends */
				rootJSON.put("Error_Info",obj);
			}
			else if(status == 3)
			{
				//err_msg.add(_mapping.getTextDescription("admin.error.You are exceeding the total number of agents permitted by your license!"));
				//err_msg.add(" "+_mapping.getTextDescription("admin.error.To upgrade your license to support additional agents")+", ");
				//err_msg.add(_mapping.getTextDescription("admin.error.please contact")+" <b>license@eginnovations.com</b>");
				String msg  = " "+_mapping.getTextDescription("admin.error.To upgrade your license to support additional monitors")+", ";
				msg += _mapping.getTextDescription("admin.error.please contact")+" <b>license@eginnovations.com</b>";
				obj.put("Error_Msg_1",_mapping.getTextDescription("admin.error.You are exceeding the total number of monitors permitted by your license or the license is invalid")+". ");
				obj.put("Error_Msg_2",msg);
				rootJSON.put("Error_Info",obj);
				if(frmTopology !=null && frmTopology.equals("yes"))
				{
					err_msg.add("frmTopology");
				}
				//session.setAttribute("vec_Errors",err_msg);
				//response.sendRedirect("EgErrors.jsp");
				/* code for auditlog starts */
				auditLogThread.setValue("Description","You are exceeding the total number of monitors permitted by your license");
				auditLogThread.sendItToDB();
				/* code for auditlog ends */
			}
			else if(status == 4)
			{
				//err_msg.add(_mapping.getTextDescription("admin.error.You are exceeding the total number of applications permitted by your license!"));
				//err_msg.add(" "+_mapping.getTextDescription("admin.error.To upgrade your license to support additional applications")+", ");
				//err_msg.add(_mapping.getTextDescription("admin.error.please contact")+" <b>license@eginnovations.com</b>");
				String msg  = " "+_mapping.getTextDescription("admin.error.To upgrade your license to support additional applications")+", ";
				msg += _mapping.getTextDescription("admin.error.please contact")+" <b>license@eginnovations.com</b>";
				obj.put("Error_Msg_1",_mapping.getTextDescription("admin.error.You are exceeding the total number of applications permitted by your license")+"!");
				obj.put("Error_Msg_2",msg);
				rootJSON.put("Error_Info",obj);
				if(frmTopology !=null && frmTopology.equals("yes"))
				{
					err_msg.add("frmTopology");
				}
				//session.setAttribute("vec_Errors",err_msg);
				//response.sendRedirect("EgErrors.jsp");
				/* code for auditlog starts */
				auditLogThread.setValue("Description","You are exceeding the total number of applications permitted by your license");
				auditLogThread.sendItToDB();
				/* code for auditlog ends */				
			}
			else if(status == 5 || usrLicStatus == 4)
			{
				//err_msg.add(_mapping.getTextDescription("admin.error.You are exceeding the total number of network devices permitted by your license!"));
				//err_msg.add(" "+_mapping.getTextDescription("admin.error.To upgrade your license to support additional network devices")+", ");
				//err_msg.add(_mapping.getTextDescription("admin.error.please contact")+" <b>license@eginnovations.com</b>");
				String msg  = " "+_mapping.getTextDescription("admin.error.To upgrade your license to support additional network devices")+", ";
				msg += _mapping.getTextDescription("admin.error.please contact")+" <b>license@eginnovations.com</b>";
				obj.put("Error_Msg_1",_mapping.getTextDescription("admin.error.You are exceeding the total number of network devices permitted by your license")+"!");
				obj.put("Error_Msg_2",msg);
				rootJSON.put("Error_Info",obj);
				if(frmTopology !=null && frmTopology.equals("yes"))
				{
					err_msg.add("frmTopology");
				}
				//session.setAttribute("vec_Errors",err_msg);
				//response.sendRedirect("EgErrors.jsp");
				/* code for auditlog starts */
				auditLogThread.setValue("Description","You are exceeding the total number of network devices permitted by your license");
				auditLogThread.sendItToDB();
				/* code for auditlog ends */				
			}
			else if(status == 6 || usrLicStatus == 5)
			{
				//err_msg.add(_mapping.getTextDescription("admin.error.You are exceeding the total number of named users permitted by your license!"));
				//err_msg.add(" "+_mapping.getTextDescription("admin.error.To upgrade your license to support additional named users")+", ");
				//err_msg.add(_mapping.getTextDescription("admin.error.please contact")+" <b>license@eginnovations.com</b>");
				String msg  = " "+_mapping.getTextDescription("admin.error.To upgrade your license to support additional named users")+", ";
				if (!isNamedUsersCert)
				{
					msg  = " "+_mapping.getTextDescription("admin.error.To upgrade your license to support additional concurrent users")+", ";
				}
				msg += _mapping.getTextDescription("admin.error.please contact")+" <b>license@eginnovations.com</b>";
				if(isNamedUsersCert)
				{
					obj.put("Error_Msg_1",_mapping.getTextDescription("admin.error.You are exceeding the total number of named users permitted by your license")+"!");
				}
				else
				{
					obj.put("Error_Msg_1",_mapping.getTextDescription("admin.error.You are exceeding the total number of concurrent users permitted by your license")+"!");
				}
				obj.put("Error_Msg_2",msg);
				rootJSON.put("Error_Info",obj);
				
				if(frmTopology !=null && frmTopology.equals("yes"))
				{
					err_msg.add("frmTopology");
				}
				session.setAttribute("vec_Errors",err_msg);
				
				/* code for auditlog starts */
				if(isNamedUsersCert)
				{
					auditLogThread.setValue("Description","You are exceeding the total number of named users permitted by your license");
				}
				else
				{
					auditLogThread.setValue("Description","You are exceeding the total number of concurrent users permitted by your license");
				}
				auditLogThread.sendItToDB();
				/* code for auditlog ends */			
			}
			if(usrLicStatus == 2)
			{
				String msg  = " "+_mapping.getTextDescription("admin.error.To upgrade your license to support additional total/basic monitors")+", ";
				msg += _mapping.getTextDescription("admin.error.please contact")+" <b>license@eginnovations.com</b>";
				obj.put("Error_Msg_1",_mapping.getTextDescription("admin.error.You are exceeding the total number of total/basic monitors permitted by your license")+"!");
				obj.put("Error_Msg_2",msg);
				rootJSON.put("Error_Info",obj);
				if(frmTopology !=null && frmTopology.equals("yes"))
				{
					err_msg.add("frmTopology");
				}
				/* code for auditlog starts */
				auditLogThread.setValue("Description","You are exceeding the total number of total/basic monitors permitted by your license");
				auditLogThread.sendItToDB();
				/* code for auditlog ends */
			}
		}
	}

	String fromHomePopup = request.getParameter("fromHomePopup");
	if ((fromHomePopup != null && fromHomePopup.length() > 0 && fromHomePopup.equalsIgnoreCase("yes")) || (frmTopology != null && frmTopology.length() > 0 && frmTopology.equalsIgnoreCase("yes")))
	{
		if (!oldhostname.equals(hostname))
		{
			String port = request.getParameter("portnumber");
			if (port == null || port.equalsIgnoreCase("null"))
			{
				port = "NULL";
			}
			String tmpVar = "#New|"+stype+":"+oldhostname+":"+port;
			//EgConfigTopo.deleteSpecValue(stype,tmpVar);
			discWrite.deleteValue(stype,tmpVar);
			userCompIniDelList.add(tmpVar);
		}

		// Change the Nick / Port in eg_autotopology.ini, if Nick / Port is changed
		if(frmTopology!=null && frmTopology.equalsIgnoreCase("yes"))
		{
			if(initPort!=null && !initPort.equals(sportno) || 
				hostname!=null && !hostname.equals(oldhostname))
			{
				EgTopoInfo.newHostName = hostname;
				EgTopoInfo.newPortValue = sportno;
				changeNickInAutoTopology(stype ,hostname, oldhostname, initPort, sportno, topoSegName);
			}
		}
	}

	//---Delete from DB-----
	UpdateAndTransmitTopoInfo delFromDB = new UpdateAndTransmitTopoInfo();
	removeOldEntries(newNickAdded, hostname, delFromDB);

	/*
	String prevExtAgents = request.getParameter("prevExtAgents");
	String selExtAgents = request.getParameter("extAgents");
	String[] prevAgentTokens = StringUtils.getTokens(prevExtAgents, EgConstants.COMMA);
	String[] selAgentTokens = StringUtils.getTokens(selExtAgents, EgConstants.COMMA);
	if (selExtAgents != null)
	{
		selExtAgents = StringUtils.getUniqueArrayAsString(selAgentTokens);
	}

	List agentsToBeRemoved = new LinkedList();
	agentsToBeRemoved.addAll(Arrays.asList(prevAgentTokens));
	agentsToBeRemoved.removeAll(Arrays.asList(selAgentTokens));
	*/

	List agentsToBeRemoved = new LinkedList();
	String prevExtAgents = request.getParameter("prevExtAgents");
	if(!StringUtils.isNull(prevExtAgents))
		agentsToBeRemoved.addAll(Arrays.asList(StringUtils.getTokens(prevExtAgents, EgConstants.COMMA)));

	String selExtAgents = request.getParameter("extAgents");
	if(!StringUtils.isNull(selExtAgents))
		agentsToBeRemoved.removeAll(Arrays.asList(StringUtils.getTokens(selExtAgents, EgConstants.COMMA)));

	/*
	 * Add remote agent to the list of agents to be removed if changed
	 */
	//String prevRemAgent = request.getParameter("prevRemAgent");
	if (!StringUtils.isNull(remoteAgent)
		&& !remoteAgent.equalsIgnoreCase("null")
		&& !prevRemAgent.equals(remoteAgent))
	{
		agentsToBeRemoved.add(prevRemAgent);
	}

	if (update)
	{
		if (addCompForDiscovery != null && (addCompForDiscovery.trim().equalsIgnoreCase("yes") || addCompForDiscovery.trim().equalsIgnoreCase("true")))
		{
			//Vmware Vcenter eg_services.ini entries
			//IniFile serviceWrite = EgConfigFilesSync.getInstance(EgConfigInfo.egMgrConfigDir + "eg_services.ini");
			IniFile servReadModeIni = new IniFile(EgConfigInfo.egMgrConfigDir + "eg_services.ini");
			ArrayList discCompList = new ArrayList();
			if (!com.egurkha.util.StringUtils.isNull(stype) && stype.equals("Virtual_center"))
			{
				String[] vCs =  servReadModeIni.getVariables("VIRTUAL_CENTER");
				List vCList = new ArrayList();
				if (vCs != null)
				{
					for (int v=0; v<vCs.length; v++)
					{
						vCList.add(vCs[v].toLowerCase());
					}
				}
				String vCenterValue =  "True#$unconfigured#$unconfigured#No#443";
				if(!vCList.contains(hostip.toLowerCase()))
				{
					discCompList.add(new IniHelper("VIRTUAL_CENTER",hostip,vCenterValue));
					//serviceWrite.setValue("VIRTUAL_CENTER", hostip, vCenterValue);
					//serviceWrite.saveFile();
				}
			}
			else if (!com.egurkha.util.StringUtils.isNull(stype) && stype.equals("Redhat_linux_mgr"))
			{
				String[] rhevs = servReadModeIni.getVariables("RHEV");
				List rhevList = new ArrayList();
				if (rhevs != null)
				{
					for (int v=0; v<rhevs.length; v++)
					{
						rhevList.add(rhevs[v].toLowerCase());
					}
				}
				String rhevValue =  "True#$unconfigured#$unconfigured#No#443#internal";
				if (!rhevList.contains(hostip.toLowerCase()))
				{
					discCompList.add(new IniHelper("RHEV",hostip,rhevValue));
					//serviceWrite.setValue("RHEV", hostip, rhevValue);
					//serviceWrite.saveFile();
				}
			}
			//EgConfigFilesSync.releaseInstance(serviceWrite);
			if (discCompList.size()>0)
			{
				IniFile serviceWrite = EgConfigFilesSync.getInstance(EgConfigInfo.egMgrConfigDir + "eg_services.ini");
				for (int s=0;s<discCompList.size() ;s++ )
				{
					IniHelper iniHelper = (IniHelper)discCompList.get(s);
					String sub = iniHelper.getSubject();
					String key = iniHelper.getVariable();
					String val = iniHelper.getValue();
					serviceWrite.setValue(sub, key, val);
				}
				serviceWrite.saveFile();
				EgConfigFilesSync.releaseInstance(serviceWrite);
			}
		}

		if (agentsToBeRemoved.size() > 0)
		{
			UpdateAndTransmitTrendInfo trendInfo = new UpdateAndTransmitTrendInfo();
			Vector param = new Vector();
			param.add("Egnewserverp");
			param.add(agentsToBeRemoved);
			param.add(hostname);
			trendInfo.removeAgentForTarget(param);
		}

		//EgConfigTopo.saveFile();
		discWrite.saveFile();		
		EgConfigFilesSync.releaseInstance(discWrite);
		/*userCompIniWrite.saveFile();		
		EgConfigFilesSync.releaseInstance(userCompIniWrite);*/

		if (isLimitedAdmin)
		{
			//If autoCreateZoneForUser is set to true, then assign the component(s) to the user's zone.
			boolean autoCreateZoneForUser = EgUuidInfo.autoCreateZone();

			Hashtable argsMap = new Hashtable();
			Hashtable resultMap = new Hashtable();
			String resultStr = "";
			String compName = hostname + ":" + sportno;

			if(stype.equals("Oracle_server"))
			{
				ArrayList currSidList = (sid != null) ? StringUtils.egTokenizer(sid,",",false,true,true) : new ArrayList();
				if(modifying)
				{
					String previousSID = request.getParameter("previoussid");
					ArrayList prevSidList =  (previousSID != null) ? StringUtils.egTokenizer(previousSID,",",false,true,true) : new ArrayList();
					currSidList.removeAll(prevSidList);
				}
				String[] sidTokens = (String[])currSidList.toArray(new String[currSidList.size()]);
				for (int a=0; a<sidTokens.length; a++)
				{
					compName = hostname + ":" + sportno + ":" + sidTokens[a];
					argsMap = new Hashtable();
					argsMap.put("userid",user_id);
					argsMap.put("componenttype",stype);
					argsMap.put("components",compName);
					argsMap.put("autoassociatetype","no");
					resultStr = uacObj.AssociateComponent(argsMap);
					if (autoCreateZoneForUser && resultStr.length()>0 && resultStr.equalsIgnoreCase("eG_CLI_Res_0286"))
					{
						argsMap = new Hashtable();
						argsMap.put("userid",user_id);
						argsMap.put("stype",stype);
						argsMap.put("compname",compName);
						resultMap = uacObj.AutoAssociateComponentToZone(argsMap);
					}
				}
			}
			else if (!modifying)
			{
				argsMap = new Hashtable();
				argsMap.put("userid",user_id);
				argsMap.put("componenttype",stype);
				argsMap.put("components",compName);
				argsMap.put("autoassociatetype","no");
				resultStr = uacObj.AssociateComponent(argsMap);
				if (autoCreateZoneForUser && resultStr.length()>0 && resultStr.equalsIgnoreCase("eG_CLI_Res_0286"))
				{
					argsMap = new Hashtable();
					argsMap.put("userid",user_id);
					argsMap.put("stype",stype);
					argsMap.put("compname",compName);
					resultMap = uacObj.AutoAssociateComponentToZone(argsMap);
				}
			}

			//for zone audit log
			if (autoCreateZoneForUser && resultStr.length()>0 && resultStr.equalsIgnoreCase("eG_CLI_Res_0286") && resultMap != null && !resultMap.isEmpty())
			{
				IniFile mgrMiscIni = new IniFile(EgInstallInfo.getInstallDir() + "/manager/config/eg_mgrmisc.ini");
				String associatedUsers = "";
				String associaedZones = "", disAssociatedZones = "";
				Enumeration enMapKeys = resultMap.keys();
				while (enMapKeys.hasMoreElements())
				{
					String userName = (String)enMapKeys.nextElement();
					String zoneName = mgrMiscIni.getValue("Auto_Created_Zone_User_Map",userName);
					if (zoneName == null || zoneName.trim().length() == 0)
					{
						zoneName = userName;
					}
					String resultStr2 = (String)resultMap.get(userName);
					if (!resultStr2.startsWith("eG_CLI_Err"))
					{
						associaedZones += zoneName + ",";
						associatedUsers += userName + ",";
					}
					else
					{
						disAssociatedZones += zoneName + ",";
					}
				}
				String descMsg = "";
				AuditLogThread auditLogThread2 = new AuditLogThread();
				auditLogThread2.setValue("Category","Admin");
				auditLogThread2.setValue("User_id",_user.getLoginID());
				auditLogThread2.setValue("Host_ip",_user.getUserIP(session.getId()));
				auditLogThread2.setValue("Session_id",session.getId());
				auditLogThread2.setValue("Module","Zones");
				auditLogThread2.setValue("Activity","Auto Zone Configuration");
				if (associaedZones != null && associaedZones.length()>0)
				{
					associaedZones = associaedZones.substring(0,associaedZones.length()-1);
					associatedUsers = associatedUsers.substring(0,associatedUsers.length()-1);
					if (associaedZones.indexOf(",") > -1)
					{
						descMsg = "Zones "+ associaedZones +" have been added/modified and associated to the users "+associatedUsers+" successfully";
					}
					else
					{
						descMsg = "Zone "+ associaedZones +" has been added/modified and associated to the user "+associatedUsers+" successfully";
					}
				}
				if (disAssociatedZones != null && disAssociatedZones.length()>0)
				{
					disAssociatedZones = disAssociatedZones.substring(0,disAssociatedZones.length()-1);
					if (disAssociatedZones.indexOf(",") > -1)
					{
						descMsg += "Zones "+ disAssociatedZones +" have not been added/modified";
					}
					else
					{
						descMsg += "Zone "+ disAssociatedZones +" has not been added/modified";
					}
				}
				auditLogThread2.setValue("Description", descMsg);
				auditLogThread2.sendItToDB();
			}
		}
		else //only for admin with AllComponentAccess and Rmt/Ext-agent Managemtent permission
		{
			String AlreadyAsoociatedUserList1 = request.getParameter("AlreadyAsoociatedUserList");
			if(AlreadyAsoociatedUserList1!=null && AlreadyAsoociatedUserList1!= "")
			{
				StringTokenizer AlreadyAsoociatedUserList = new StringTokenizer(AlreadyAsoociatedUserList1,",");
				String compName = hostname + ":" + sportno;
				String resultStr = "";
				if(AlreadyAsoociatedUserList.countTokens() > 0)
				{
					Hashtable argsMap = new Hashtable();
				//	Iterator it = AlreadyAsoociatedUserList.iterator();
					while(AlreadyAsoociatedUserList.hasMoreTokens())
					{
						String UnAme=AlreadyAsoociatedUserList.nextToken().toString();
						argsMap = new Hashtable();
						argsMap.put("userid",UnAme);
						argsMap.put("componenttype",stype);
						argsMap.put("components",compName);
						argsMap.put("autoassociatetype","no");
						resultStr = uacObj.AssociateComponent(argsMap);
					}
				}
			}
		}
		//Admin Check ends -here

		EgDiscInfo discInfos = new EgDiscInfo("manager");
		EgSpecsInfo specsInfos = new EgSpecsInfo("manager");
		// get manager IP
		String managerHosts = specsInfos.getEGServer();
		specsInfos = null;
		EgExternalAgent ex = new  EgExternalAgent(discInfos, managerHosts, true);
		ex = new EgExternalAgent(discInfos, managerHosts, true);
		ArrayList aList = new ArrayList();
		aList.add(hostname);
		ex.buildExternalFile(aList);
		discInfos = null;
		ex = null;
		//Nickname change
		Vector v_types = new Vector();
		if (allServers)
		{
			sess_vec = new Vector();
			sess_vec.add(_mapping.getTextDescription("admin.server.Add/Modify components"));
			if(!StringUtils.isNull(treeViewSrc))
			{
				sess_vec.add("EgDispServer.jsp?qctr=1&server="+stype+"&treeViewSrc="+treeViewSrc+"&selectedServerGroup="+selectedServerGroup);
			}
			else
			{
				sess_vec.add("EgDispServer.jsp?qctr=1&server="+stype+"&selectedServerGroup="+selectedServerGroup);
			}

			sess_vec.add(_mapping.getTextDescription("admin.server.Add/Modify components"));
	
			EgDiscInfo2 discInfo = new EgDiscInfo2("manager",true);
			if (modify.equals("yes"))
			{
				v_types = discInfo.updateAllServers(hostip,hostname,oldhostname);
			}
			else
			{
				v_types = discInfo.updateAllServers(hostip,hostname);
			}
			discInfo = null;

			if(v_types.size() > 0)
			{
				sess_vec.add(_mapping.getTextDescription("admin.server.The components have been updated with")+" '" + removeNull(hostname) + "' "+_mapping.getTextDescription("admin.server.as host/nick name in the following component types.")+" ");
				String compTypes ="";
				for(int i=0; i<v_types.size(); i++)
				{
					String tmpCompType = _mapping.getComponentTypeDescription((String)v_types.get(i));	
					compTypes = compTypes+tmpCompType+",";  
				}
				compTypes = compTypes.substring(0,compTypes.length()-1);	
				sess_vec.add(compTypes.trim());
			}
			else
			{
				sess_vec.add(_mapping.getTextDescription("admin.server.Parameters configured for")+" "+_mapping.getComponentTypeDescription(stype));
				sess_vec.add("<br>"+_mapping.getTextDescription("admin.server.Component type")+"	: "+_mapping.getComponentTypeDescription(stype));
				if(!hostip.equals("0.0.0.0"))
				{
					if(isAllowHostName)
					{
						sess_vec.add("<br>"+_mapping.getTextDescription("admin.server.Host IP/Name")+"			: "+hostip);	
					}
					else
					{
						sess_vec.add("<br>"+_mapping.getTextDescription("admin.server.Host IP")+"			: "+hostip);
					}
				}
				sess_vec.add("<br>"+_mapping.getTextDescription("admin.server.Nick name")+"			: "+removeNull(hostname));
			}
		}
		//End of Nickname change
		/*
		 * Modify files here one by one
		 */

		ArrayList aListOracleServers = null;
		if(oracleServers != null && oracleServers.length > 0)
		{
			if (allNicks != null && allNicks.length > 0)
			{
				for(int c=0;c<oracleServers.length;c++)
				{
					String oracleNick = oracleServers[c].trim();
					for(int a=0;a<allNicks.length;a++)
					{
						if(oracleNick.endsWith(":"+allNicks[a]))
						{
							if(aListOracleServers == null)
								aListOracleServers = new ArrayList();
							aListOracleServers.add(oracleNick.substring(oracleNick.indexOf(":")+1));
							break;
						}
					}
				}
			}
		}
		oracleServers = null;

		UpdateNicknames  updateNicknames = new UpdateNicknames ();
		
		//Updating eg_apmGuid.ini 
		String[] valuesForGuid = new String[6];
		valuesForGuid[0] = serverType;
		valuesForGuid[1] = hostip;
		valuesForGuid[2] = hostname;
		valuesForGuid[3] = oldAlias;
		valuesForGuid[4] = sportno;
		valuesForGuid[5] = oldPort;
		updateNicknames.updateApmGuidIni(modify.equals("yes"),allServers,valuesForGuid,uuidInfo,user_id);
		
		if (variableName != null && variableName.indexOf(":") != -1)
		{
			String[] values;
			if (allServers)
			{
				String nicks = s_nicks;
				values = new String[7];
				values[0] = serverType;
				values[1] = hostname;
				values[2] = oldAlias;
				if (serverType.equals("Oracle_server") && (sportno.indexOf(":")==-1))
				{
					values[3] = sportno+":"+hsid;
				}else
				values[3] = sportno;
				values[4] = oldPort;
				values[5] = nicks;
				values[6] = null;
			}
			else
			{
				values = new String[6];
				values[0] = serverType;
				values[1] = hostname;
				values[2] = oldAlias;
				if (serverType.equals("Oracle_server") && (sportno.indexOf(":")==-1))
				{
					values[3] = sportno+":"+hsid;
				}else
				values[3] = sportno;
				values[4] = oldPort;
				values[5] = null;
			}

			int iniLoc = values.length-1;
			String[] iniFiles = {
						"eg_disable.ini", "true"
						,"eg_discover.ini","true"
						,"eg_thresholds.ini", "true"
						,"eg_topology.ini", "true"
						,"js_topology.ini","true"
						,"eg_group.ini", "true"
						,"eg_external.ini", "true"
						,"eg_infogroup.ini","true"
						,"eg_maintenance.ini","true"
						,"eg_testinfo.ini","true"
						,"eg_mailalert.ini","true"
						,"eg_TroubleTicketFilter.ini","true"
						,"eg_report.ini","true"
						,"eg_hmcmapping.ini","true"
						,"eg_vcmapping.ini","true"
						,"eg_rhevmapping.ini","true"
						,"eg_autotopology.ini","true"
						,"eg_pwdprofile.ini","true"
						//,"eg_usercompmapping.ini","true"
						,"eg_aggregate.ini","true"
						,"eg_customdashboard.ini","true"
						,"eg_autodelete.ini","true"
						,"eg_mgrmisc.ini","true"
								};
			
//-----------------Stalin 21/06/07-------------------------------
			if(hostname != null && oldhostname != null)
			//Delete Variables from eg_topology.ini, DB, eg_disable.ini 
			{
				//IniFile topoInfoIni = new IniFile(EgConfigInfo.egMgrConfigDir + "eg_topology.ini", true);
				IniFile topoInfoIni = EgConfigFilesSync.getInstance(EgConfigInfo.egMgrConfigDir + "eg_topology.ini");
				String[] topoIniVariables =  topoInfoIni.getVariables("TEST_GROUPS");
				needSave = false;
				for(int i=0; i < topoIniVariables.length; i++)
				{
				
					String tempVar= topoIniVariables[i];
					String tempTopoHost1 = (tempVar.substring(tempVar.indexOf("::")+2,tempVar.indexOf("#")));
					String tempTopoHost2 = tempTopoHost1.substring(0,tempTopoHost1.indexOf(":")); 
					if(tempTopoHost2.equals(oldhostname))
					{
						topoInfoIni.deleteValue("TEST_GROUPS", tempVar);
						needSave = true;
					}
				}
				if (needSave)
					topoInfoIni.saveFile();
				EgConfigFilesSync.releaseInstance(topoInfoIni);

				String infos = null;
				String[] arr_tList = testlist.getTestList(stype);//all tests of given server
				List list = Arrays.asList(arr_tList);
				//IniFile specsIni = new IniFile(EgConfigInfo.egMgrConfigDir + "eg_specs.ini", true);
				IniFile specsIni = new IniFile(EgConfigInfo.egMgrConfigDir + "eg_specs.ini");
				Vector specsIniVariables = specsIni.getAllValues ("CONFIG_FGENERIC_TESTS");
				Enumeration enm = specsIniVariables.elements();
				while(enm.hasMoreElements())
				{
					String tempSpecsVar = (String)enm.nextElement();
					StringTokenizer tokens = new StringTokenizer(tempSpecsVar,",");
					String specsTestToken = null;
					while(tokens.hasMoreTokens())
					{
						specsTestToken = tokens.nextToken();
						if(list.contains(specsTestToken))
						{
							infos = specsTestToken+"_INFOS";
							String delQuery = "delete from "+infos+" where trgt_host ='"+oldhostname+"'";
							delFromDB.deleteFromDb(delQuery);
						}
					}

				}
				//---Delete from eg_disable.ini------
				//IniFile disIni = new IniFile(EgConfigInfo.egMgrConfigDir + "eg_disable.ini", true);
				//IniFile disIni = new IniFile(EgConfigInfo.egMgrConfigDir + "eg_disable.ini");
				IniFile disIni = EgConfigFilesSync.getInstance(EgConfigInfo.egMgrConfigDir + "eg_disable.ini");
				String[] disIniVariables =  disIni.getVariables("Disabled_servers");
				ArrayList entriesToDelete = new ArrayList();
				for(int i=0; i < disIniVariables.length; i++)
				{
					String tempVar= disIniVariables[i];
				//	String tempDist = (tempVar.substring(tempVar.indexOf("::")+2,tempVar.lastIndexOf(":")));
					String xx = tempVar.substring(tempVar.indexOf("::")+2);
					int ind = xx.lastIndexOf(":");
					String tempDist = null;
					if (ind >=0)
						tempDist = xx.substring(0,ind);
					else
						tempDist = xx;
					if(tempDist.equals(oldhostname))
					{
						entriesToDelete.add(new IniHelper("Disabled_servers",tempVar));
						//disIni.deleteValue("Disabled_servers", tempVar);
					}
				}
				//disIni.saveFile();
				if (entriesToDelete.size() > 0)
				{
					//IniFile disableIni = EgConfigFilesSync.getInstance(EgConfigInfo.egMgrConfigDir + "eg_disable.ini");
					for (int n=0; n <entriesToDelete.size(); n++)
					{
						IniHelper iniHelper = (IniHelper)entriesToDelete.get(n);
						String sub = iniHelper.getSubject();
						String key = iniHelper.getVariable();
						disIni.deleteValue(sub, key);
					}
					disIni.saveFile();
					//EgConfigFilesSync.releaseInstance(disIni);
				}
				EgConfigFilesSync.releaseInstance(disIni);
			}
//-----------------------------------------------		
			updateNicknames.setOracleServers_NickAsSID(aListOracleServers);
			for (int a=0; a<iniFiles.length; a+=2)
			{
				values[iniLoc] = iniFiles[a];
				Boolean modifyValue = Boolean.valueOf(iniFiles[a+1]);
				if (allServers)
				{
					updateNicknames.modifyIniForAllServers(null, values, modifyValue.booleanValue());
				}
				else
				{
					boolean useType = true;
					//if you have a component name withoiut port, update the inifile details over here! - pandian
					if (a == 2 || 
						a==4 || 
						a==12 || 
						a==14)
						useType = false;
					updateNicknames.modifyIni(null, values, modifyValue.booleanValue(),useType);
				}			
			}
			values[iniLoc] = "eg_agents.ini";
			List agentsForOldHost = (List)agentsForOldHosts.get(values[2]);
			updateNicknames.modifyAgentsIni(agentsForOldHost,values);
			/*
			 * Now modify the database. If all servers are chosen, then those comp_name rows must be retrieved
			 */
			updateNicknames.modifyDb(values);
			updateNicknames.modifyTopoDb(values);
		}
		else if (allServers && variableName != null && !(variableName.indexOf(":") != -1))
		{
			String[] values;
			String nicks = s_nicks;
			String[] iniFiles = {
						"eg_disable.ini", "true"
						,"eg_discover.ini","true"
						,"eg_thresholds.ini", "true"
						,"eg_topology.ini", "true"
						,"js_topology.ini","true"
						,"eg_group.ini", "true"
						,"eg_external.ini", "true"
						,"eg_infogroup.ini","true"
						,"eg_maintenance.ini","true"
						,"eg_testinfo.ini","true"
						,"eg_mailalert.ini","true"
						,"eg_TroubleTicketFilter.ini","true"
						,"eg_report.ini","true"
						,"eg_hmcmapping.ini","true"
						,"eg_vcmapping.ini","true"
						,"eg_rhevmapping.ini","true"
						,"eg_autotopology.ini","true"
						,"eg_pwdprofile.ini","true"
						//,"eg_usercompmapping.ini","true"
						,"eg_aggregate.ini","true"
						,"eg_customdashboard.ini","true"
						,"eg_autodelete.ini","true"
						,"eg_mgrmisc.ini","true"
								};
			values = new String[7];
			values[0] = serverType;
			values[1] = hostname;
			values[2] = oldAlias;
			values[3] = sportno;
			values[4] = oldPort;
			values[5] = nicks;

			for (int a=0; a<iniFiles.length; a+=2)
			{
				values[6] = iniFiles[a];
				Boolean modifyValue = Boolean.valueOf(iniFiles[a+1]);
				updateNicknames.setOracleServers_NickAsSID(aListOracleServers);
				updateNicknames.modifyIniForAllServers(null, values, modifyValue.booleanValue());
			}
			updateNicknames.modifyDb(values);
			updateNicknames.modifyTopoDb(values);

			List agentsForOldHost = null;
			values[values.length-1] = "eg_agents.ini";
			if (allNicks != null && allNicks.length > 0)
			{
				for(int b=0;b<allNicks.length;b++)
				{
					values[2] = allNicks[b];
					agentsForOldHost = (List)agentsForOldHosts.get(allNicks[b]);
					updateNicknames.modifyAgentsIni(agentsForOldHost,values);
				}
			}
			agentsForOldHost = null;
		}
		agentsForOldHosts = null;
		updateNicknames = null;
		boolean allExternalTests = true;
		EgSpecsInfo specsInfo = new EgSpecsInfo("manager");

		String aggType = request.getParameter("isAggregateType"); //skm

		if (aggType.equalsIgnoreCase("true"))	
		{
			//egExtIni.createFile("eg_external.ini","save");
			extIniWr = EgConfigFilesSync.getInstance(EgConfigInfo.egMgrConfigDir + "eg_external.ini");
			// Add the user specified external agent(s)
			String[] extAgent = request.getParameterValues("extAgents");
			if (extAgent != null && extAgent.length > 0)
			{
				extIniWr.setValue("Test_Mapping_Section", hostname, StringUtils.getUniqueArrayAsString(extAgent));
			}

			//vmwarehosts starts here
			if (stype.equals("VMware_guest"))
			{
				if (vmwarehostentry!=null && !vmwarehostentry.equals("-1"))
				{
					extIniWr.setValue("VIRTUAL_MAPPING", stype+":"+hostname+":"+sportno, vmwarehostentry);
				}else if (vmwarehostentry!=null && vmwarehostentry.equals("-1"))
				{
					extIniWr.deleteValue("VIRTUAL_MAPPING", stype+":"+hostname+":"+sportno);
				}
			}
			//vmwarehosts ends here

			extIniWr.saveFile();
			EgConfigFilesSync.releaseInstance(extIniWr);

			String old_hostname = request.getParameter("oldhostname");

			String associated_comps = request.getParameter("fassociate");
			/* code for auditlog starts */
			StringTokenizer tokens = new StringTokenizer(associated_comps,",");
			Set serverSet = new TreeSet();
			while(tokens.hasMoreTokens())
			{
				String serverTypes = tokens.nextToken().toString();
				auditLogThread.setCurrentValue("Associated Components","$ctype$:"+serverTypes);//new
				serverTypes = serverTypes.substring(0,serverTypes.indexOf(":"));
				if(!serverSet.contains(serverTypes))
				{
					auditLogThread.setCurrentValue("Component Types","$ctype$:"+serverTypes);
					serverSet.add(serverTypes);
				}
			}
			//auditLogThread.setCurrentValue("Associated Components",associated_comps);
			if(modifying)
			{
				String exAssociatedComponents = request.getParameter("$_associated");
				serverSet = new TreeSet();
				if(exAssociatedComponents != null && exAssociatedComponents.trim().length()>0)
				{
					///auditLogThread.setPreviousValue("Associated Components",exAssociatedComponents);
					tokens = new StringTokenizer(exAssociatedComponents,",");
					while(tokens.hasMoreTokens())
					{
						String serverTypes = tokens.nextToken().toString();
						auditLogThread.setPreviousValue("Associated Components","$ctype$:"+serverTypes);
						serverTypes = serverTypes.substring(0,serverTypes.indexOf(":"));
						if(!serverSet.contains(serverTypes))
						{
							auditLogThread.setPreviousValue("Component Types","$ctype$:"+serverTypes);
							serverSet.add(serverTypes);
						}
					}
				}
			}
			/* code for auditlog ends */
			StringTokenizer associated_tokens = new StringTokenizer(associated_comps,",");

			IniFile aggWrite = EgConfigFilesSync.getInstance(EgConfigInfo.egMgrConfigDir + "eg_aggregate.ini");
			String comptype_hostname = stype + ":" + old_hostname + ":" + sportno + "#";
			String[] agg_comps = aggWrite.getVariables("AGGREGATE_COMPONENTS");
			ArrayList aggEntries = new ArrayList();
			if ((agg_comps != null) && (agg_comps.length > 0))
			{
				for(int i=0;i<agg_comps.length;i++)
				{
					if (agg_comps[i].startsWith(comptype_hostname))
					{
						aggEntries.add(new IniHelper(IniHelper.DELETE,"AGGREGATE_COMPONENTS",agg_comps[i],""));
					}
				}
			}

			comptype_hostname = stype + ":" + hostname + ":" + sportno + "#";
			while (associated_tokens.hasMoreTokens())
			{
				aggEntries.add(new IniHelper(IniHelper.SET,"AGGREGATE_COMPONENTS", comptype_hostname+associated_tokens.nextToken(), "associated"));
			}
			String[] associations = aggWrite.getVariables("COMPONENT_ASSOCIATION");
			if ((associations != null) && (associations.length > 0))
			{
				for(int i=0;i<associations.length;i++)
				{
					if (associations[i].startsWith(stype + ":" + old_hostname + ":" + sportno))
					{
						aggEntries.add(new IniHelper(IniHelper.DELETE,"COMPONENT_ASSOCIATION", associations[i], ""));
					}
				}
			}

			if(stype.startsWith("Agg_"))
			{
				String elementType = request.getParameter("elementType");
				String elementName = request.getParameter("elementName");
				String memberComponent = request.getParameter("memberComponent");
				if(memberComponent != null && (memberComponent=memberComponent.trim()).length()>0 && 
					!memberComponent.equalsIgnoreCase("null"))
				{
					//EgGroupInfo groupInfo = new EgGroupInfo();
					IniFile groupInfo = EgConfigFilesSync.getInstance(EgInstallInfo.getInstallDir()+"/manager/config/eg_group.ini");
					String key = stype+":"+hostname+":"+sportno+"#"+elementName;
					if(memberComponent.equalsIgnoreCase("yes"))
					{
						groupInfo.setValue("ZONE_DETAILS",key,elementName);
					}
					else if(memberComponent.equalsIgnoreCase("no"))
					{
						groupInfo.deleteValue("ZONE_DETAILS",key);
					}
					groupInfo.saveFile();
					EgConfigFilesSync.releaseInstance(groupInfo);
				}
				if(!StringUtils.isNull(elementType) && !elementType.equals("-1") && !StringUtils.isNull(elementName) && !elementName.equals("-1"))
				{
					aggEntries.add(new IniHelper(IniHelper.SET,"COMPONENT_ASSOCIATION",stype + ":" + hostname + ":" + sportno+"#"+elementType+"#"+elementName,elementType+"#"+elementName));
					/* deleting anchor component from [ANCHOR_COMPONENT] if components were added for this element name */
					String anchorComp = request.getParameter("anchorComp");
					if(!StringUtils.isNull(anchorComp))
					{
						String anchor_variables[] = aggWrite.getVariables("ANCHOR_COMPONENT");
						if(anchor_variables != null && anchor_variables.length > 0)
						{
							for(int i=0;i<anchor_variables.length;i++)
							{
								String anchor_variable = anchor_variables[i];
								if (anchor_variable.startsWith(stype+":") && anchor_variable.endsWith("#"+elementType+"#"+elementName))
								{
									aggEntries.add(new IniHelper(IniHelper.DELETE,"ANCHOR_COMPONENT",anchor_variable,""));
								}
							}
						}
						if(anchorComp.equals("yes"))
						{
							aggEntries.add(new IniHelper(IniHelper.SET,"ANCHOR_COMPONENT",stype + ":" + hostname + ":" + sportno+"#"+elementType+"#"+elementName,elementType+"#"+elementName));
						}
					}
					//deleting anchor component block ends
				}
			}
			String fromTree = request.getParameter("fromTree");
			if(!StringUtils.isNull(fromTree) && fromTree.equals("No") && stype.startsWith("Agg_"))
			{
				agg_comps = aggWrite.getVariables("UI_COMPONENT_ASSOCIATION");
				if ((agg_comps != null) && (agg_comps.length > 0))
				{
					for(int i=0;i<agg_comps.length;i++)
					{
						if (agg_comps[i].startsWith(comptype_hostname))
						{
							aggEntries.add(new IniHelper(IniHelper.DELETE,"UI_COMPONENT_ASSOCIATION",agg_comps[i],""));
						}
					}
				}
				String type_name = request.getParameter("type_name");
				String type_members = request.getParameter("type_members");
				if(!StringUtils.isNull(type_name) && !type_name.equals("-1") && !StringUtils.isNull(type_members) && !type_members.equals("-1"))
				{
					aggEntries.add(new IniHelper(IniHelper.SET,"UI_COMPONENT_ASSOCIATION",stype + ":" + hostname + ":" + sportno+"#"+type_name+"#"+type_members,type_name+"#"+type_members));
				}
			}
			if (aggEntries.size() > 0)
			{
				//IniFile aggWrite = EgConfigFilesSync.getInstance(EgConfigInfo.egMgrConfigDir + "eg_aggregate.ini");
				for (int agg=0; agg < aggEntries.size(); agg++)
				{
					IniHelper iniHelper = (IniHelper)aggEntries.get(agg);
					String iniAction = iniHelper.getAction();
					String sub = iniHelper.getSubject();
					String key = iniHelper.getVariable();
					String val = iniHelper.getValue();

					if (iniAction != null)
					{
						if (iniAction.equals(IniHelper.SET))
						{
							aggWrite.setValue(sub,key,val);
						}
						else if (iniAction.equals(IniHelper.DELETE))
						{
							aggWrite.deleteValue(sub,key);
						}
					}
				}			
				aggWrite.saveFile();
				//EgConfigFilesSync.releaseInstance(aggWrite);
			}
			EgConfigFilesSync.releaseInstance(aggWrite);

		} //skm
		else
		{
			String[] testsForServer = specsInfo.getTestsForServer(stype);
			if (testsForServer != null)
			{
				for (int a=0; a<testsForServer.length; a++)
				{
					if (!specsInfo.isTestExternal(testsForServer[a],stype))
					{
						allExternalTests = false;
						break;
					}
				}
			}
		}

		String oldIntAgent = (String)session.getAttribute("int_agent");
		session.removeAttribute("int_agent");

		if(!StringUtils.isNull(oldIntAgent) || !StringUtils.isNull(currAgent)) 
		{
			if(currAgent == null)
				currAgent = hostname;
			else if(oldIntAgent == null)
				oldIntAgent = hostname;

			/* code for auditlog starts */
			String prevAgents = request.getParameter("previousIntAgent");
			if(prevAgents != null && prevAgents.length()>0)
				auditLogThread.setPreviousValue("Internal Agent",prevAgents);
			auditLogThread.setCurrentValue("Internal Agent",currAgent);
			/* code for auditlog ends */
			//IniFile testinfoptrR = new IniFile(EgConfigInfo.egMgrConfigDir + "eg_testinfo.ini");
			IniFile testinfoptrW =EgConfigFilesSync.getInstance(EgConfigInfo.egMgrConfigDir + "eg_testinfo.ini");
			String [] vars = testinfoptrW.getVariables(oldIntAgent);
			if(vars != null && vars.length > 0)
			{
				//IniFile testinfoptrW =EgConfigFilesSync.getInstance(EgConfigInfo.egMgrConfigDir + "eg_testinfo.ini");
				needSave = false;
				for(int g=0;g<vars.length;g++)
				{
					if(vars[g].indexOf(":"+hostname+":") > -1 || vars[g].indexOf("::"+hostname+"#") > -1)
					{
						testinfoptrW.deleteValue(oldIntAgent, vars[g]);
						testinfoptrW.setValue(currAgent, vars[g], "disabled");
						needSave = true;
					}
				}
				if (needSave)
					testinfoptrW.saveFile();
				//EgConfigFilesSync.releaseInstance(testinfoptrW);		
			}
			EgConfigFilesSync.releaseInstance(testinfoptrW);
		}
		ArrayList extIniEntries = new ArrayList();
		if(!allExternalTests)
		{
			//egExtIni.createFile("eg_external.ini","save");
			if (intAgentMode.equalsIgnoreCase("manual"))
			{
			/*
			 *	New code : The user explicitly chooses a current agent to map to.
			 *	The mapped-to current agent is specified in eg_external.ini
			 */
				currAgents = currAgent;
				//egExtIni.deleteSpecValue("Internal_Agent_Mapping", oldAlias);
				//egExtIni.setValues("Internal_Agent_Mapping", hostname, currAgent);
				extIniEntries.add(new IniHelper(IniHelper.DELETE,"Internal_Agent_Mapping", oldAlias,""));
				extIniEntries.add(new IniHelper(IniHelper.SET,"Internal_Agent_Mapping", hostname, currAgent));
			}
			else //if (intAgentMode.equalsIgnoreCase("auto"))
			{
			/*
			 *	New code : If an internal agent is going to be assigned automatically,
			 *	remove the entry of this agent if present in the Internal_Agent_Mapping
			 *	section in eg_external.ini
			 */
				//egExtIni.deleteSpecValue("Internal_Agent_Mapping", hostname);
				extIniEntries.add(new IniHelper(IniHelper.DELETE,"Internal_Agent_Mapping", hostname,""));
			}
		}

		/*
		 * Add the user specified external agent
		 */
		String[] extAgent = request.getParameterValues("extAgents");
		String extAgentStr = request.getParameter("extAgents");
		if (extAgent != null && extAgent.length > 0)
		{
			try
			{
				String externalAgent = StringUtils.getUniqueArrayAsString(extAgent);
				//egExtIni.setValues("Test_Mapping_Section", hostname, StringUtils.getUniqueArrayAsString(extAgent));
				//if (isLimitedAdmin && !userExtAgent.equals(""))
				//{
					//externalAgent = userExtAgent;
				//}
				extIniEntries.add(new IniHelper(IniHelper.SET,"Test_Mapping_Section", hostname, externalAgent));

				/* code for auditlog starts */
				if(modifying)
				{
					auditLogThread.setPreviousValue("External Agents",prevExtAgents);
				}
				auditLogThread.setCurrentValue("External Agents",externalAgent);	
				/* code for auditlog ends */
			}
			catch(Exception e)
			{
				e.printStackTrace();
			}
		}

		//vmwarehosts starts here
		if (stype.equals("VMware_guest"))
		{
			if (vmwarehostentry!=null && !vmwarehostentry.equals("-1"))
			{
				//egExtIni.setValues("VIRTUAL_MAPPING", stype+":"+hostname+":"+sportno, vmwarehostentry);
				extIniEntries.add(new IniHelper(IniHelper.SET,"VIRTUAL_MAPPING", stype+":"+hostname+":"+sportno, vmwarehostentry));
			}else if (vmwarehostentry!=null && vmwarehostentry.equals("-1"))
			{
				//egExtIni.deleteSpecValue("VIRTUAL_MAPPING", stype+":"+hostname+":"+sportno);
				extIniEntries.add(new IniHelper(IniHelper.DELETE,"VIRTUAL_MAPPING", stype+":"+hostname+":"+sportno,""));
			}
		}
		//vmwarehosts ends here

		//vmware EsxServer hosts starts here
		
		//for vmware esx server
		if(underVmware!=null && underVmware.equalsIgnoreCase("true"))
		{
			if(esxServer !=null && !esxServer.equals("-1"))
			{
				if(sid!=null && sid.length()>0)
				{
					//egExtIni.setValues("Virtual_Components", stype+":"+hostname+":"+sportno+":"+sid, esxServer);
					extIniEntries.add(new IniHelper(IniHelper.SET,"Virtual_Components", stype+":"+hostname+":"+sportno+":"+sid, esxServer));
				}
				else
				{
					//egExtIni.setValues("Virtual_Components", stype+":"+hostname+":"+sportno, esxServer);
					extIniEntries.add(new IniHelper(IniHelper.SET,"Virtual_Components", stype+":"+hostname+":"+sportno, esxServer));
				}
				/* code for auditlog starts */
				if(modifying)
				{
					String previousVirtualServer = request.getParameter("previousvirtualserver");
					if(previousVirtualServer !=null && !previousVirtualServer.equalsIgnoreCase("null") && previousVirtualServer.trim().length()>0)
						auditLogThread.setPreviousValue("Virtual Servers",previousVirtualServer);
				}
				auditLogThread.setCurrentValue("Virtual Servers",esxServer);
				/* code for auditlog ends */
			}
		}
		//karthika for cloud
		if(underCloud!=null && underCloud.equalsIgnoreCase("true"))
		{
			if(cloudServer !=null && !cloudServer.equals("-1"))
			{
				if(sid!=null && sid.length()>0)
				{
					//egExtIni.setValues("Cloud_Components", stype+":"+hostname+":"+sportno+":"+sid, cloudServer);
					extIniEntries.add(new IniHelper(IniHelper.SET,"Cloud_Components", stype+":"+hostname+":"+sportno+":"+sid, cloudServer));
				}
				else
				{
					//egExtIni.setValues("Cloud_Components", stype+":"+hostname+":"+sportno, cloudServer);
					extIniEntries.add(new IniHelper(IniHelper.SET,"Cloud_Components", stype+":"+hostname+":"+sportno, cloudServer));
				}
				/* code for auditlog starts */
				if(modifying)
				{
					String previousCloudServer = request.getParameter("previouscloudserver");
					if(previousCloudServer !=null && !previousCloudServer.equalsIgnoreCase("null") && previousCloudServer.trim().length()>0)
					{
						int idx = previousCloudServer.indexOf(":");
						if (idx > -1)
						{
							String tmpPrvCloud = previousCloudServer.substring(0,idx);
							tmpPrvCloud = _mapping.getComponentTypeDescription(tmpPrvCloud)+":"+previousCloudServer.substring(idx+1);
							if (tmpPrvCloud.toLowerCase().endsWith(":null"))
								tmpPrvCloud = tmpPrvCloud.substring(0,tmpPrvCloud.lastIndexOf(":"));
							auditLogThread.setPreviousValue("Cloud Servers",tmpPrvCloud);
						}
						else
						{
							auditLogThread.setPreviousValue("Cloud Servers","-");
						}
					}
				}
				int idx = cloudServer.indexOf(":");
				if(idx > -1)
				{
					String tmpCloudServer = cloudServer.substring(0,idx);
					tmpCloudServer = _mapping.getComponentTypeDescription(tmpCloudServer)+":"+cloudServer.substring(idx+1);
					if (tmpCloudServer.toLowerCase().endsWith(":null"))
						tmpCloudServer = tmpCloudServer.substring(0,tmpCloudServer.lastIndexOf(":"));
					auditLogThread.setCurrentValue("Cloud Servers",tmpCloudServer);
				}
				else
				{
					auditLogThread.setCurrentValue("Cloud Servers","-");
				}
				
				/* code for auditlog ends */
			}
		}
		if(!type.equals("new") && underCloud!=null && underCloud.equalsIgnoreCase("false"))
		{
			String variable = null;
			if(sid!=null && sid.length()>0)
			{
				variable = stype+":"+hostname+":"+sportno+":"+sid;
				//egExtIni.deleteSpecValue("Cloud_Components",variable);
				extIniEntries.add(new IniHelper(IniHelper.DELETE,"Cloud_Components",variable,""));
			}
			else
			{
				variable = stype+":"+hostname+":"+sportno;
				//egExtIni.deleteSpecValue("Cloud_Components",variable);
				extIniEntries.add(new IniHelper(IniHelper.DELETE,"Cloud_Components",variable,""));
			}
			variable = null;
		}
		
		/* code for auditlog starts */
		if(underCloud!=null && !underCloud.equalsIgnoreCase("null") && underCloud.trim().length()>0 && !underCloud.equalsIgnoreCase("false"))
		{				
			if(modifying)
			{
				String previousCloudEvn = request.getParameter("previouscloudenvironment");
				if(previousCloudEvn !=null && !previousCloudEvn.equalsIgnoreCase("null"))
					auditLogThread.setPreviousValue("Cloud Environment",changeTrueToYesAndFalseToNo(previousCloudEvn));
			}
			auditLogThread.setCurrentValue("Cloud Environment",changeTrueToYesAndFalseToNo(underCloud));
		}
		//auditLogThread.sendItToDB();
		/* code for auditlog ends */
		// cloud ends here
		if(!type.equals("new") && underVmware!=null && underVmware.equalsIgnoreCase("false"))
		{
			String variable = null;
			if(sid!=null && sid.length()>0)
			{
				variable = stype+":"+hostname+":"+sportno+":"+sid;
				//egExtIni.deleteSpecValue("Virtual_Components",variable);
				extIniEntries.add(new IniHelper(IniHelper.DELETE,"Virtual_Components",variable,""));
			}
			else
			{
				variable = stype+":"+hostname+":"+sportno;
				//egExtIni.deleteSpecValue("Virtual_Components",variable);
				extIniEntries.add(new IniHelper(IniHelper.DELETE,"Virtual_Components",variable,""));
			}
			variable = null;
		}
		
		/* code for auditlog starts */
		if(underVmware!=null && !underVmware.equalsIgnoreCase("null") && underVmware.trim().length()>0 && !underVmware.equalsIgnoreCase("false"))
		{				
			if(modifying)
			{
				String previousVirtualEvn = request.getParameter("previousvirtualenvironment");
				if(previousVirtualEvn !=null && !previousVirtualEvn.equalsIgnoreCase("null"))
					auditLogThread.setPreviousValue("Virtual Environment",changeTrueToYesAndFalseToNo(previousVirtualEvn));
			}
			auditLogThread.setCurrentValue("Virtual Environment",changeTrueToYesAndFalseToNo(underVmware));
		}	
		//auditLogThread.sendItToDB();
		/* code for auditlog ends */
		if (extIniEntries.size() > 0)
		{
			IniFile externalWrite = EgConfigFilesSync.getInstance(EgConfigInfo.egMgrConfigDir + "eg_external.ini");
			IniFile virCompWrite = EgConfigFilesSync.getInstance(EgConfigInfo.egMgrConfigDir + "eg_virtualcomponents.ini");
			for (int n=0; n<extIniEntries.size(); n++)
			{
				IniHelper iniHelper = (IniHelper)extIniEntries.get(n);
				String iniAction = iniHelper.getAction();
				String subject = iniHelper.getSubject();
				String key = iniHelper.getVariable();
				String value = iniHelper.getValue();
				if(iniAction != null)
				{
					if (iniAction.equals(IniHelper.SET))
					{
						if(subject != null && subject.equalsIgnoreCase("Virtual_Components"))
							virCompWrite.setValue(subject,key,value);
						else
							externalWrite.setValue(subject,key,value);

					}
					else if (iniAction.equals(IniHelper.DELETE))
					{
						if(subject != null && subject.equalsIgnoreCase("Virtual_Components"))
							virCompWrite.deleteValue(subject,key);
						else
							externalWrite.deleteValue(subject,key);
					}
				}
			}
			externalWrite.saveFile();
			EgConfigFilesSync.releaseInstance(externalWrite);
			virCompWrite.saveFile();
			EgConfigFilesSync.releaseInstance(virCompWrite);
		}
		if(frmTopology !=null && frmTopology.equals("yes"))
		{
			sess_vec.add("frmTopology"+"::"+topoSegName);
		}
		//session.setAttribute("compType",server_type);
		//session.setAttribute("compName",server_name);
		//session.setAttribute("hostIp",host_ip);
		//session.setAttribute("vec_Results",sess_vec);
		rootJSON.put("compType",server_type);
		rootJSON.put("compName",server_name);
		if(stype != null && stype != "")
		{
			if(stype.equals("Real_user_monitor"))
			{
				rootJSON.put("hostIp", "0.0.0.0");
			}
			else
			{
				rootJSON.put("hostIp",host_ip);
			}
		}


	//	UpdateVcConfig updateVcConfig = new UpdateVcConfig();
		if (modifying) // If modify component
		{
			// IsPassive Fix starts here
			String preIsPassive = request.getParameter("previousispassive");
			//IniFile agentsIni = new IniFile(EgInstallInfo.getInstallDir() + "/manager/config/eg_agents.ini");
			IniFile agentsIni = EgConfigFilesSync.getInstance(EgInstallInfo.getInstallDir() + "/manager/config/eg_agents.ini");
			if (preIsPassive != null && !preIsPassive.equalsIgnoreCase("null"))
			{
				preIsPassive = (preIsPassive.equalsIgnoreCase("true") || preIsPassive.equalsIgnoreCase("yes"))?"true":"false";
				if (!preIsPassive.equalsIgnoreCase(isPassive)) // If isPassive value has changed
				{
					
					List agentsList = new ArrayList();
					String agent = externalInfo.getAgentFor(hostname);
					if (StringUtils.isNull(agent)) // For Internal Agent check
					{
						agent = externalInfo.getRemoteAgentForHost(hostname);
					}
					if (StringUtils.isNull(agent)) // For Remote Agent check
					{
						agent = hostname;
					}
					agentsList.add(agent);
					String[] extAgents = externalInfo.getExternalAgentsForHost(hostname);
					if (extAgents != null && extAgents.length > 0)
					{
						agentsList.addAll(Arrays.asList(extAgents)); 
					}
					String[] tests = specsInfo.getTestsForServer(stype);
					List testsList = new ArrayList(Arrays.asList(tests));
					ArrayList iniEntries = new ArrayList();
					for (int j=0; j<agentsList.size(); j++) //relevant subjects from eg_agents.ini
					{
						String agentSub = (String)agentsList.get(j);
						String[] vars = agentsIni.getVariables(agentSub);
						for (int k=0; k < vars.length; k++)
						{
							String variable = vars[k];
							String tmpTestName = variable.substring(0,variable.indexOf(":"));
							if (testsList.contains(tmpTestName)) //relevant tests 
							{
								if(variable.endsWith(":"+hostname+":"+sportno) || variable.endsWith(":"+hostname) || variable.indexOf(":"+hostname+":"+sportno+":") > 0) // nick name check
								{
									String value = agentsIni.getValue(agentSub,variable);
									if (value.startsWith("-manual") && value.toLowerCase().indexOf("-ispassive") > 0)
									{
										int passiveIndex = value.toLowerCase().indexOf("-ispassive");
										String tmpStr1 = value.substring(0,passiveIndex+10).trim();
										String tmpStr2 = value.substring(passiveIndex+10).trim();
										tmpStr2 = tmpStr2.substring(tmpStr2.indexOf(" ")+1);
										value = tmpStr1+" "+isPassive+" "+tmpStr2;
										//agentsIni.setValue(agentSub,variable,value);
										iniEntries.add(new IniHelper(agentSub,variable,value));
									}
								}
							}
						}
					}
					if (iniEntries.size() > 0)// Have entries to update agents.ini?
					{
						//IniFile agentsFile = EgConfigFilesSync.getInstance(EgInstallInfo.getInstallDir() + "/manager/config/eg_agents.ini");
						for (int n=0;n<iniEntries.size(); n++)
						{
							IniHelper iniHelper = (IniHelper)iniEntries.get(n);
							String sub = iniHelper.getSubject();
							String key = iniHelper.getVariable();
							String val = iniHelper.getValue();
							agentsIni.setValue(sub,key,val);
						}
						agentsIni.saveFile();
						//EgConfigFilesSync.releaseInstance(agentsIni);
					}					
				}
			}
		//  Comment reason: Nick name change should not affect -virtual_center param in agents.ini, since the value is Host IP/Name(from services.ini) 
		//	if (stype.equals("Virtual_center"))
		//	{
		//		updateVcConfig.changeVcConfig(hostname,oldhostname);
		//	}
			//IniFile testInfoToRead = new IniFile(EgInstallInfo.getInstallDir()+"/manager/config/eg_testinfo.ini");
			IniFile testInfoToWrite = EgConfigFilesSync.getInstance(EgInstallInfo.getInstallDir()+"/manager/config/eg_testinfo.ini");
			//If we change Remote agent / External agent(s) for a component, then need to retain disabled descriptors information to the newly associated agents.
			//External agent related fix
			if (prevExtAgents != null && extAgent != null)
			{
				//List currExtList = new ArrayList(Arrays.asList(extAgent));
				List currExtList = new ArrayList(StringUtils.egTokenizer(extAgentStr,","));
				List prevExtList = new ArrayList();
				List varsToHandle = new ArrayList();
				StringTokenizer strTzr = new StringTokenizer(prevExtAgents,",");
				while(strTzr.hasMoreTokens())
				{
					prevExtList.add(strTzr.nextToken());
				}
				if (prevExtList.size() > 0)
				{
					String agentName = (String)prevExtList.get(0);
					String[] vars = testInfoToWrite.getVariables(agentName);
					for (int j=0; j < vars.length; j++)
					{
						var = vars[j];
						String testName = var.substring(0,var.indexOf(":"));
						if (!specsInfo.isExternalTest(testName,stype))
						{
							continue;
						}
						if (var.indexOf(":"+hostname+"#") > -1 || var.indexOf(":"+hostname+":") > -1)
						{
							String val = testInfoToWrite.getValue(agentName,var);
							varsToHandle.add(var+"="+val);
						}
					}
				}
				for (int i=currExtList.size()-1;i >= 0; i--)
				{
					String currExt = (String)currExtList.get(i);
					if (prevExtList.contains(currExt))
					{
						currExtList.remove(currExt); 
						prevExtList.remove(currExt);
					}
				}
				if (currExtList.size() > 0)//List of subjects, where the relevant entries have to be saved
				{
					//testInfoToWrite = EgConfigFilesSync.getInstance(EgInstallInfo.getInstallDir()+"/manager/config/eg_testinfo.ini");
					for (int n=0; n<currExtList.size(); n++)
					{
						String agentName = (String)currExtList.get(n);
						for (int m=0; m < varsToHandle.size(); m++)
						{
							String strTmp = (String)varsToHandle.get(m);
							String tmpVar = strTmp.substring(0,strTmp.indexOf("="));
							String tmpVal = strTmp.substring(strTmp.indexOf("=")+1);
							testInfoToWrite.setValue(agentName,tmpVar,tmpVal);
						}						
					}
					testInfoToWrite.saveFile();
					//EgConfigFilesSync.releaseInstance(testInfoToWrite);
					
				}
				if (prevExtList.size() > 0) //List of subjects, where the relevant entries have to be removed
				{
					//testInfoToWrite = EgConfigFilesSync.getInstance(EgInstallInfo.getInstallDir()+"/manager/config/eg_testinfo.ini");
					for (int n=0; n<prevExtList.size(); n++)
					{
						String agentName = (String)prevExtList.get(n);
						String[] vars = testInfoToWrite.getVariables(agentName);
						for (int j=0; j < vars.length; j++)
						{
							var = vars[j];
							String testName = var.substring(0,var.indexOf(":"));
							if (!specsInfo.isExternalTest(testName,stype))
							{
								continue;
							}
							if (var.indexOf(":"+hostname+"#") > -1 || var.indexOf(":"+hostname+":") > -1)
							{
								testInfoToWrite.deleteValue(agentName,var);
							}
						}
					}
					testInfoToWrite.saveFile();
					//EgConfigFilesSync.releaseInstance(testInfoToWrite);
				}
			}
			ArrayList iniEntriesList = new ArrayList();
			//Remote agent related fix			
			String oldAgentName = request.getParameter("olderRmtAgtForTestInfo");
			if (oldAgentName == null)
				oldAgentName ="";
			if (StringUtils.isNull(remoteType))
				remoteType ="false";

			if (oldAgentName.equals("") && remoteAgent!=null && remoteType!=null && remoteType.equals("true")) // AgentBased --> Agentless
			{
				String varArr[] = testInfoToWrite.getVariables(hostname);
				if (varArr != null)
				{
					List tmpList = new ArrayList();
					//testInfoToWrite = EgConfigFilesSync.getInstance(EgInstallInfo.getInstallDir()+"/manager/config/eg_testinfo.ini");
						
					for (int i=0; i < varArr.length; i++)
					{
						var = varArr[i];
						String testName = var.substring(0,var.indexOf(":"));
						if (specsInfo.isExternalTest(testName,stype))
						{
							continue;
						}
						String val = testInfoToWrite.getValue(hostname,var);
						testInfoToWrite.setValue(remoteAgent,var,val);
						testInfoToWrite.deleteValue(hostname,var);
					}
					testInfoToWrite.saveFile();
					//EgConfigFilesSync.releaseInstance(testInfoToWrite);

					//To retain Test Configurations
					String[] vars = agentsIni.getVariables(hostname);
					Vector vals = agentsIni.getAllValues(hostname);
					for (int i=0; i < vars.length; i++)
					{
						String variable = vars[i];
						String testName = variable.substring(0,variable.indexOf(":"));
						if (specs.isTestInternal(testName,stype))
						{
							String value = (String)vals.get(i);
							if (value.startsWith("-manual"))
							{
								iniEntriesList.add(new IniHelper(remoteAgent,variable,value));							
							}
						}
					}	
				}
			}
			else
			{
				String newAgentName = "";
				if (oldAgentName != null && remoteAgent == null && remoteType!=null && remoteType.equals("false")) // Agentless --> AgentBased
				{
					 newAgentName = hostname;
					//To retain Test Configurations
					String[] vars = agentsIni.getVariables(oldAgentName);
					Vector vals = agentsIni.getAllValues(oldAgentName);
					for (int i=0; i < vars.length; i++)
					{
						String variable = vars[i];
						String testName = variable.substring(0,variable.indexOf(":"));
						if (specs.isTestInternal(testName,stype))
						{
							if (variable.indexOf(":"+hostname+":") > -1 || variable.endsWith(":"+hostname)) // nick name check
							{
								String value = (String)vals.get(i);
								if (value.startsWith("-manual"))
								{
									iniEntriesList.add(new IniHelper(hostname,variable,value));							
								}
							}
						}
					}					 
				}
				else if (oldAgentName != null && oldAgentName.length() > 0 && remoteAgent!=null && remoteType.equals("true")) // Agentless --> Agentless
				{
					newAgentName = remoteAgent;
				}
				boolean isRemoteUpdated = true;
				if (oldAgentName.equals(newAgentName))
				{
					isRemoteUpdated = false;
				}
				if (isRemoteUpdated)
				{
					String varArr[] = testInfoToWrite.getVariables(oldAgentName);
					if (varArr != null)
					{
						List tmpList = new ArrayList();
						for (int i=0; i < varArr.length; i++)
						{
							var = varArr[i];
							String testName = var.substring(0,var.indexOf(":"));
							if (specsInfo.isExternalTest(testName,stype))
							{
								continue;
							}
							if (var.indexOf(":"+hostname+"#") > -1 || var.indexOf(":"+hostname+":") > -1)
							{
								String val = testInfoToWrite.getValue(oldAgentName,var);
								tmpList.add(var+"="+val);
							}
						}
						//testInfoToWrite = EgConfigFilesSync.getInstance(EgInstallInfo.getInstallDir()+"/manager/config/eg_testinfo.ini");
						for (int j=0;j<tmpList.size();j++)
						{
							String keyValue = (String)tmpList.get(j);
							String key = keyValue.substring(0,keyValue.indexOf("="));
							String value = keyValue.substring(keyValue.indexOf("=")+1);
							testInfoToWrite.setValue(newAgentName,key,value);
							testInfoToWrite.deleteValue(oldAgentName,key);
						}
						testInfoToWrite.saveFile();
						//EgConfigFilesSync.releaseInstance(testInfoToWrite);
					}
				}
			}
			EgConfigFilesSync.releaseInstance(testInfoToWrite);
			//Fix ends to retain disabled discriptor information

			// Fix starts to retain the test configuration details while changing the Remote/External/Internal agent
			// Remote agent
			String oldRemoteAgent = request.getParameter("olderremoteagentname");
			String newRemoteAgent = remoteAgent;
			
			if (oldRemoteAgent!=null && newRemoteAgent!=null && !oldRemoteAgent.equals(newRemoteAgent))// If remote agent changed
			{
				String[] vars = agentsIni.getVariables(oldRemoteAgent);
				for (int i=0; i < vars.length; i++)
				{
					String variable = vars[i];
					if (variable.indexOf(":"+hostname+":") > -1 || variable.endsWith(":"+hostname)) // nick name check
					{
						String value = agentsIni.getValue(oldRemoteAgent,variable);
						if (value.startsWith("-manual"))
						{
							iniEntriesList.add(new IniHelper(newRemoteAgent,variable,value));							
						}
					}					
				}					
			}			
			// External agents
			if(extAgent != null && extAgent.length>0)
			{
				String currExtAgents = StringUtils.getUniqueArrayAsString(extAgent);
				if (prevExtAgents != null && !prevExtAgents.equals(currExtAgents))
				{
					ArrayList prevAgentsList = StringUtils.egTokenizer(prevExtAgents,",");
					ArrayList currAgentsList = StringUtils.egTokenizer(currExtAgents,",");
					String anyOnePrevAgent = (String)prevAgentsList.get(0);
					String[] vars = agentsIni.getVariables(anyOnePrevAgent);	
					for (int j=0;j<currAgentsList.size();j++)
					{
						String currIntAgent = (String)currAgentsList.get(j);
						if (prevAgentsList.contains(currIntAgent))// This agent is not new assigned one
						{
							continue; 
						}
												
						for (int i=0; i < vars.length; i++)
						{
							String variable = vars[i];
							if (variable.indexOf(":"+hostname+":") > -1 || variable.endsWith(":"+hostname))// nick name check
							{
								String value = agentsIni.getValue(anyOnePrevAgent,variable);
								if (value.startsWith("-manual"))
								{
									iniEntriesList.add(new IniHelper(currIntAgent,variable,value));							
								}
							}					
						}
					}
				}
			}
			//Internal agent
			String preIntAgent = request.getParameter("prevAgents");
			if(intAgentMode.equals("auto"))
			{
				preIntAgent = request.getParameter("previousIntAgent");
				currAgent = oldhostname;
			}
			if (preIntAgent == null)
				preIntAgent = "";
			if (!preIntAgent.equals(currAgent))
			{
				String[] vars = agentsIni.getVariables(preIntAgent);
				for (int i=0; i < vars.length; i++)
				{
					String variable = vars[i];
					if (variable.indexOf(":"+hostname+":") > -1 || variable.endsWith(":"+hostname)) // nick name check
					{
						String value = agentsIni.getValue(preIntAgent,variable);
						if (value.startsWith("-manual"))
						{
							iniEntriesList.add(new IniHelper(currAgent,variable,value));							
						}
					}					
				}				
			}
				
			if (iniEntriesList.size() > 0)
			{
				//IniFile agentsFile = EgConfigFilesSync.getInstance(EgInstallInfo.getInstallDir() + "/manager/config/eg_agents.ini");
				for (int j=0; j<iniEntriesList.size(); j++)
				{
					IniHelper iniHlpr = (IniHelper)iniEntriesList.get(j);
					String sub = iniHlpr.getSubject();
					String key = iniHlpr.getVariable();
					String val = iniHlpr.getValue();
					agentsIni.setValue(sub,key,val);
				}
				agentsIni.saveFile();
				//EgConfigFilesSync.releaseInstance(agentsIni);
			}
			EgConfigFilesSync.releaseInstance(agentsIni);
		}
		// Fix ends to retain the test configuration details while changing the remote/External/Internal agent
		// IsPassive Fix ends here

		Vector addModify = new Vector();
		addModify.add(hostip);
		addModify.add(hostname);
		addModify.add(intAgentMode);
		addModify.add(currAgents);
		addModify.add(remoteAgent);
		session.setAttribute("addModify",addModify);
		if (hasLimitExceeded)
		{
			servicer.startDiscovery("1");
		}
		else
		{
			servicer.startDiscovery("1",true);
		}
		if(isExistingAggType != null && isExistingAggType.equals("false"))
		{
			while(true)
			{
				if(!EgUpdateRegistry.isRunning)
				{
					//synchronized(EgUpdateRegistry.syncString)
					{
						EgUpdateRegistry.lastCheckTime=0;
						registry.updateAllUserMaps();
					}
					break;
				}
			}
		}
		else
		{
			registry.updateAllUserMaps();
		}

		//............................. Code Starts for Aggregate Site Servers (Begin).......................
		if(isAggregateType)
		{
			//IniFile aggIni = new IniFile(EgInstallInfo.getInstallDir() + "/manager/config/eg_aggregate.ini",true);
			IniFile aggIni = EgConfigFilesSync.getInstance(EgInstallInfo.getInstallDir() + "/manager/config/eg_aggregate.ini");

			if(siteSupport != null && siteSupport.equals("true"))
			{
				boolean result = aggIni.setValue("SITE_SUPPORT",stype+":"+hostname+":NULL","yes");
				if(oldhostname!=null && !oldhostname.equals(hostname))
					aggIni.deleteValue("SITE_SUPPORT",stype+":"+oldhostname+":NULL");
			}
			else
			{
				aggIni.deleteValue("SITE_SUPPORT",stype+":"+hostname+":NULL");
			}
			aggIni.saveFile();
			EgConfigFilesSync.releaseInstance(aggIni);
		}
		//............................. Code Starts for Aggregate Site Servers (End).......................
		//String fwdPage = (remote_vmware!=null && remote_vmware.equals("Yes"))? "Egnewremoteagentsp.jsp?mode=add&ip="+hostip+"&nick="+hostname+"&from=compadd":(isAggregateLink?"EgResults.jsp?location=AggregatesAddAll":"EgResults.jsp");
		String fwdPage = isAggregateLink?"EgResults.jsp?location=AggregatesAddAll":"EgResults.jsp";
		if(!StringUtils.isNull(treeViewSrc))
		{
			if(fwdPage.indexOf("EgResults.jsp?")!=-1)
			{
				fwdPage+="&from=ManUnMan";
			}
			else
				fwdPage+="?from=ManUnMan";
		}
		rootJSON.put("requestStatus","success");
		if(modifying)
		{
			rootJSON.put("Result_info",_mapping.getTextDescription("admin.server.Component has been modified successfully")+".");
			if(remoteAgent != null)
			{
				session.setAttribute("prevSelectedRemAgents",remoteAgent);
			}
			if(selExtAgents != null)
			{
				session.setAttribute("prevSelectedExtAgents",selExtAgents);
			}
			if(esxServer != null)
			{
				session.setAttribute("prevSelectedVirtualHost",esxServer);
			}
			if(cloudServer != null)
			{
				session.setAttribute("prevSelectedCloudServ",cloudServer);
			}
		}
		else
		{
			rootJSON.put("Result_info",_mapping.getTextDescription("admin.server.Component has been added successfully")+".");
			if(remoteAgent != null)
			{
				session.setAttribute("prevSelectedRemAgents",remoteAgent);
			}
			if(selExtAgents != null)
			{
				session.setAttribute("prevSelectedExtAgents",selExtAgents);
			}
			if(esxServer != null)
			{
				session.setAttribute("prevSelectedVirtualHost",esxServer);
			}
			if(cloudServer != null)
			{
				session.setAttribute("prevSelectedCloudServ",cloudServer);
			}
		}

		UnmanagedAgentsInfo uai = new UnmanagedAgentsInfo();
		uai.updateAgentDetail(hostip, hostname);
	}
	EgConfigFilesSync.releaseInstance(infraIni);
	if (discWrite != null)
		EgConfigFilesSync.releaseInstance(discWrite);

	//For usercompmapping ini deletion - starts
	if (isLimitedAdmin && userCompIniDelList != null)
	{
		List orgList = uuidInfo.getOrgNames(user_id);
		int orgListLen = (orgList != null) ? orgList.size() : 0;
		IniFile userCompIniWrite = EgConfigFilesSync.getInstance(userCompMap);
		for (int y=0; y<orgListLen; y++)
		{
			String org_id = orgList.get(y).toString().trim();
			userCompIniWrite.deleteValues(org_id,userCompIniDelList);
		}
		userCompIniWrite.saveFile();
		EgConfigFilesSync.releaseInstance(userCompIniWrite);
	}
	//For usercompmapping ini deletion - ends

	/* code for auditlog ends */
	auditLogThread.sendItToDB();
	/* code for auditlog ends */

	//Microsoft Office 365, Microsoft Sharepoint Online & Microsoft Exchange Online - after modification alert
	if (stype != null && splCompList.contains(stype))
	{
		ArrayList allCompsUnderSplTypes = egDiscInfo.getAllHostsOfTypes(splCompList);
		int pos = (modifying) ? oldhostname.lastIndexOf("_") : hostname.lastIndexOf("_");
		if (pos > -1)
		{
			String remainingComps = "";
			String strWithoutSuffix = (modifying) ? oldhostname.substring(0,pos) : hostname.substring(0,pos);
			Vector microsoftSuffixNameValues = mgrmiscIni.getAllValues("Microsoft_Components");
			ArrayList threeHostList = new ArrayList();
			int suffixNamesize = microsoftSuffixNameValues.size();
			for(int i=0;i<suffixNamesize;i++)
			{
				String microsoftSuffixVal = (String)microsoftSuffixNameValues.get(i);
				String threeHostListNames = strWithoutSuffix+microsoftSuffixVal;
				threeHostList.add(threeHostListNames);
			}
			String _suffixStr = hostname.substring(pos+1);
			if (modifying)
			{
				for(int i=0;i<suffixNamesize;i++)
				{
					String microsoftSuffixVal = (String)microsoftSuffixNameValues.get(i);
					String splcmpVal = splComponents[i];
					if (!stype.equalsIgnoreCase(splcmpVal) && allCompsUnderSplTypes.contains(strWithoutSuffix+microsoftSuffixVal) && remainTypeCheck)
					{
						remainingComps += splcmpVal + ",";
					}
				}  
			}
			else
			{
				for(int i=0;i<suffixNamesize;i++)
				{
					String microsoftSuffixVal = (String)microsoftSuffixNameValues.get(i);
					String splcmpVal = splComponents[i];
					if (!stype.equalsIgnoreCase(splcmpVal) && (!allCompsUnderSplTypes.contains(strWithoutSuffix+microsoftSuffixVal) || remainTypeCheck))
					{
						remainingComps += splcmpVal + ",";
					}
				} 
			}
			if (!remainingComps.equals(""))
			{
				remainingComps = remainingComps.substring(0,remainingComps.length()-1);
			}
			rootJSON.put("remainingTypes",remainingComps);
		}
	}

	/*
	 * Update the settings for all user IDs.
	 */
	//UserRegistry registry = UserRegistry.getInstance();
	registry.updateAllUserMaps();
	out.println(rootJSON);
%>

<%!
	public String changeTrueToYesAndFalseToNo(String value)
	{
		if(value.equalsIgnoreCase("true") || value.equalsIgnoreCase("yes"))
			value = "Yes";
		else if(value.equalsIgnoreCase("false") || value.equalsIgnoreCase("no"))
			value = "No";
		return value;
	}
	public void removeOldEntries(boolean newNickAdded, String s_host_name, UpdateAndTransmitTopoInfo topoinfo)
	{
		if (newNickAdded)
		{
			ArrayList queryList = new ArrayList();
			queryList.add("delete from measure_last where trgt_host='"+s_host_name+"'");
			queryList.add("delete from metatest where comp_name like '"+s_host_name+":%'");
			for (int j=0; j<queryList.size(); j++)
			{
				String thisQry = (String) queryList.get(j);
				topoinfo.deleteFromDb(thisQry);
			}
		}
	}

	public String removeNull(String server)
	{
		server = (server != null)?server:"";
		if (server.endsWith(":NULL"))
			server = server.substring(0,server.indexOf(":NULL"));
		return server; 
	}

	public void changeNickInAutoTopology (String serverType, String newHostname , String oldHostName,										  String oldPort , String newPort, String topoSegmentName)
	{
		String iniFileName = EgInstallInfo.getInstallDir()+"/manager/config/eg_autotopology.ini";
		IniFile autoTopoIni = EgConfigFilesSync.getInstance(iniFileName,true);
		try
		{
			String[] allLines = autoTopoIni.getLinesUnderSubject(topoSegmentName);
			if(allLines!=null && allLines.length > 0)
			{
				int len = allLines.length;
				if(oldPort == null)
					oldPort = newPort;
				String searchString = serverType+":"+oldHostName+":"+oldPort;
				String modifiedString = serverType+":"+newHostname+":"+newPort;
				for(int k =0;k<len;k++)
				{
					String line = allLines[k];
					int index = line.indexOf(searchString);
					int searchLen  = searchString.length();
					if(index > -1)
					{
						if(index == 0)
						{
							String rhs = line.substring(line.indexOf("=")+1);
							autoTopoIni.setValue(topoSegmentName,modifiedString,rhs);
							autoTopoIni.deleteValue(topoSegmentName,searchString);
						}
						else
						{
							StringBuffer resultBuffer = new StringBuffer();
							String beforeString = line.substring(0,index);
							String afterString = line.substring(index + searchLen);
							resultBuffer.append(beforeString);
							resultBuffer.append(modifiedString);
							resultBuffer.append(afterString);
							String lhs = resultBuffer.substring(0,resultBuffer.indexOf("="));
							String rhs = resultBuffer.substring(resultBuffer.indexOf("=")+1);
							autoTopoIni.setValue(topoSegmentName,lhs,rhs);
						}
					}
				}
			}
		}
		catch(Exception e)
		{
			System.out.println("Exception Occured in changeNickInAutoTopology Method ");
			e.printStackTrace();
		}
		finally
		{
			autoTopoIni.saveFile();
			EgConfigFilesSync.releaseInstance(autoTopoIni);
		}
	}

	//Deleting agent nick at eg_uuid.ini when component nick matches with agent nick during component add/modify.
	public void updateUuidIni(EgUuidInfo uuidInfo, String hostname)
	{
		if (hostname != null && hostname.length()>0)
		{
			int pos = hostname.indexOf(":");
			hostname = (pos > -1) ? hostname.substring(0,pos) : hostname;
			uuidInfo.removeAgentNick(hostname);
		}
	}

%>

