<%
/**
 *	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.UpdateNicknames" %>
<%@ page import = "com.egurkha.admin.AuditLogThread"%>
<%@ page import = "com.egurkha.admin.UserAssociateComponent"%>
<%@ page import = "com.egurkha.util.StringUtils"%>
<%@ 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"%>

<%!
	/*****************************************************************
	* 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");
%>

<%
	boolean remoteAgentChangedForAuditlog = true;
	boolean autoAssociateCompForAuditlog = true;
	boolean anchorChangedForAuditlog = false;
	boolean individualCompsChangedForAuditlog = true;
	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");
	rootJSON.put("selectedServerGroup",selectedServerGroup);
	rootJSON.put("selectedServer",stype);
	EgServicesInfo servicesInfo = new EgServicesInfo("manager");
	EgTesterInfo testerInfo = new EgTesterInfo("manager");
	boolean externalAgentRunsAllAggTests = testerInfo.externalAgentRunsAllAggTests();
	boolean isAggregateLink = true;
	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++)
			{
				String dent = dents[m].trim();
				if(dent.endsWith("_cf"))
					continue;
				dentsList.add(dent);//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);
//			if(layersForServer == null || layersForServer.isEmpty())
//			{
//				//component type is created from integration console, but no layers are associated with it.
//				//for example, component type "james_ex" is there without layers.
//				//but user has created components for this component type james_ex.
//				error=true;
//				errorIndex=i;
//				break;
//			}
//			int layersCount = layersForServer.size();
//			//layerLeves = new String[layersCount];
//			//int arrayIndex = -1;
//			Hashtable layerLevel = new Hashtable();
//			for(int j=0;j<layersCount;j++)
//			{
//				layer = (String)layersForServer.get(j);
//				levelStr = tablesInfo.getLevelForLayer(normalServerType, layer);
//				try
//				{
//					int level = Integer.parseInt(levelStr.trim());
//					layerLevel.put(layer,levelStr.trim());
//					/*if(layersCount==1)
//					{
//						if(level == -1)
//						{
//							layerLeves[0] = layer;
//						}
//						else
//						{
//							layerLeves[level] = layer;
//						}
//					}
//					else
//					{
//						layerLeves[++arrayIndex] = 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++)
//			{
//				String lay = (String)layersForServer.get(s);
//				layersStr += lay+":"+(String)layerLevel.get(lay)+",";
//			}
//			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))
				{
					String ratArray[] = aggregateInfo.getRelatedAggregateTest(normalTestName,false);
					if(ratArray != null && ratArray.length>1)
					{
						for(int m=0;m<ratArray.length;m++)
						{
							rat = ratArray[m];
							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;
								}
							}
						}
					}
					else
					{
						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)
					{
						String mykey = a_test+"::";
						String descriptorAggregation = "true";
						for(int z=0;z<TEST_SPECIFICATION_VAR.size();z++)
						{
							String tmp = (String)TEST_SPECIFICATION_VAR.get(z);
							if(tmp.startsWith(mykey))
							{
								descriptorAggregation = (String)TEST_SPECIFICATION_VAL.get(z);
								descriptorAggregation = descriptorAggregation.substring(descriptorAggregation.indexOf("-aggregateDescriptor")+20);
								descriptorAggregation = descriptorAggregation.trim();
								descriptorAggregation = descriptorAggregation.substring(0,descriptorAggregation.indexOf(" "));
								break;
							}
						}
						agg_test_spec = a_test + agg_test_spec.substring(agg_test_spec.indexOf(":"));
						agg_test_spec = StringUtils.replace(agg_test_spec,normalServerType,aggServerType);
						m_count = (String)testMeasureCount.get(a_test);
						if(portBased)
						{
							if(externalAgentRunsAllAggTests)
							{
								spec_val = "$EG_SERVER,-auto, -host $hostIp -port $portNo -action_on_descriptors include -include_descriptors all -excludeDescriptor none -aggregateDescriptor "+descriptorAggregation+" -agentless y -rptName $hostName -mCount "+m_count+", "+(String)testPeriodMapping.get(n_test);
							}
							else
							{
								spec_val = "$hostName,-auto, -host $hostIp -port $portNo -action_on_descriptors include -include_descriptors all -excludeDescriptor none -aggregateDescriptor "+descriptorAggregation+" -agentless y -rptName $hostName -mCount "+m_count+", "+(String)testPeriodMapping.get(n_test);
							}
						}
						else
						{
							if(externalAgentRunsAllAggTests)
							{
								spec_val = "$EG_SERVER,-auto, -host $hostIp -action_on_descriptors include -include_descriptors all -excludeDescriptor none -aggregateDescriptor "+descriptorAggregation+" -agentless y -rptName $hostName -mCount "+m_count+", "+(String)testPeriodMapping.get(n_test);
							}
							else
							{
								spec_val = "$hostName,-auto, -host $hostIp -action_on_descriptors include -include_descriptors all -excludeDescriptor none -aggregateDescriptor "+descriptorAggregation+" -agentless y -rptName $hostName -mCount "+m_count+", "+(String)testPeriodMapping.get(n_test);
							}
						}
						if(agg_test_spec.endsWith(":$sid"))
						{
							agg_test_spec = agg_test_spec.substring(0,agg_test_spec.lastIndexOf(":$sid"));
						}
						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))
			{
				aggTestsStr="";
			}
			if(StringUtils.isNull(defAggTestsStr))
			{
				defAggTestsStr="";
			}
//			if(!StringUtils.isNull(aggTestsStr))
//			{
				defaultTestMappingHt.put(aggServerType,aggTestsStr);
				if(defAggTestsStr.length()==0)
					testMappingHt.put(aggServerType,aggTestsStr);
				else
					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)
		{
			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
		{
			IniFile aggregateInfoSync = EgConfigFilesSync.getInstance(EgInstallInfo.getInstallDir()+"/manager/config/eg_aggregate.ini",true);
			for(int k=0;k<aggServerTypes.length;k++)
			{
				String server = aggServerTypes[k];
				aggregateInfoSync.setValue("AGGREGATE_TYPES",server,"yes");
				aggregateInfoSync.setValue("COMPONENT_TYPE_MAPPING",server,server.substring(server.indexOf("_")+1));
			}
			aggregateInfoSync.saveFile();
			EgConfigFilesSync.releaseInstance(aggregateInfoSync);
		}
		// 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();

%>
<%!
	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);
	}
%>

<%
	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.contains(user_id));//!egRoleInfo.hasAllComponentAccess();
	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*/
	String junk = "";
	String var = "";
	String new_var = "";
	String new_var_name = "";
	String hsid = "";
	String prevSid = null;
	String strCombine = "";
	boolean needSave = false;
	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");
	String oldhostname = request.getParameter("oldhostname");

	//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 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");
	String frmTopology = request.getParameter("frmTopology");
	String frmPage = request.getParameter("frmPage");
	String topoSegName = request.getParameter("topoSegName");
	String initPort = request.getParameter("initPort");
	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");
	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
	String[] splCompArr = new String[]{"MS_Office_365","Microsoft_Sharepoint_Online","MSExchangeOnline","MS_Skype_Online"};
	ArrayList splCompList = new ArrayList(Arrays.asList(splCompArr));
	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 vmwarehostentry = request.getParameter("vmwarehostentry");
	String siteSupport = request.getParameter("siteflag");
	boolean isAllowHostName = servicesInfo.isAllowHostNames();
	String auditNos = "01~~";
	String isAggType = "true";
	boolean isAggregateType = true;
	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","Add/Modify Servers");
	}

	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");
	}
	String underVmware =request.getParameter("underVmware");
	String esxServer = request.getParameter("esxServer");
	String underCloud =request.getParameter("underCloud");
	String cloudServer = request.getParameter("cloudServer");

	if (underCloud != null && underCloud.equals("on"))
	{
		underCloud = "true";
	}
	else
	{
		underCloud = "false";
	}
	if (underVmware != null && underVmware.equals("on"))
	{
		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"));
	}

	// Aggregate component is already added and unmanged.
	// Unknowingly, user is trying to add the same aggregate component again.
	// We have to remove the existing entires from eg_aggregate.ini file.
	boolean alreadyUnmanagedCompIsBeingAdded=false;
	IniFile aggWrCommon = EgConfigFilesSync.getInstance(EgConfigInfo.egMgrConfigDir + "eg_aggregate.ini");
	String[] aggreagetComponents1 = aggWrCommon.getVariables("AGGREGATE_COMPONENTS");
	if(aggreagetComponents1 !=null)
	{
		ArrayList aggIniEntries = new ArrayList();
		String unmanagedCompKey ="#Unmanage|"+stype+":"+hostname+":NULL#";
		for(int i=0;i<aggreagetComponents1.length;i++)
		{
			String tempVar=aggreagetComponents1[i];
			if(tempVar.startsWith(unmanagedCompKey))
			{
				alreadyUnmanagedCompIsBeingAdded=true;
				aggIniEntries.add(new IniHelper(IniHelper.DELETE,"AGGREGATE_COMPONENTS",tempVar,""));
			}
		}
		if(alreadyUnmanagedCompIsBeingAdded)
		{
			String[] aggregateTestInfosExclude = aggWrCommon.getVariables("AGGREGATE_TEST_INFOS_EXCLUDED");
			if(aggregateTestInfosExclude != null)
			{
				unmanagedCompKey=":"+stype+":"+hostname+":NULL#";
				for(int i=0;i<aggregateTestInfosExclude.length;i++)
				{
					String tempVar = aggregateTestInfosExclude[i];
					if(tempVar.indexOf(unmanagedCompKey)>0)
					{
						aggIniEntries.add(new IniHelper(IniHelper.DELETE,"AGGREGATE_TEST_INFOS_EXCLUDED",tempVar,""));
					}
				}
			}
			unmanagedCompKey=stype+":"+hostname+":NULL#";
			String[] uiComponentAssociations = aggWrCommon.getVariables("UI_COMPONENT_ASSOCIATION");
			if(uiComponentAssociations != null)
			{
				for(int i=0;i<uiComponentAssociations.length;i++)
				{
					String tempVar = uiComponentAssociations[i];
					if(tempVar.startsWith(unmanagedCompKey))
					{
						aggIniEntries.add(new IniHelper(IniHelper.DELETE,"UI_COMPONENT_ASSOCIATION",tempVar,""));
					}
				}
			}
			String[] component_association = aggWrCommon.getVariables("COMPONENT_ASSOCIATION");
			if(component_association != null)
			{
				for(int i=0;i<component_association.length;i++)
				{
					String tempVar = component_association[i];
					if(tempVar.startsWith(unmanagedCompKey))
					{
						aggIniEntries.add(new IniHelper(IniHelper.DELETE,"COMPONENT_ASSOCIATION",tempVar,""));
					}
				}
			}
			String[] anchor_component = aggWrCommon.getVariables("ANCHOR_COMPONENT");
			if(anchor_component != null)
			{
				for(int i=0;i<anchor_component.length;i++)
				{
					String tempVar = anchor_component[i];
					if(tempVar.startsWith(unmanagedCompKey))
					{
						aggIniEntries.add(new IniHelper(IniHelper.DELETE,"ANCHOR_COMPONENT",tempVar,""));
					}
				}
			}
		}
		if(aggIniEntries.size() > 0)
		{
			for (int i=0;i<aggIniEntries.size();i++)
			{
				IniHelper iniHelper= (IniHelper)aggIniEntries.get(i);
				String iniAction = iniHelper.getAction();
				String sub = iniHelper.getSubject();
				String key = iniHelper.getVariable();
				String val = iniHelper.getValue();
				if(iniAction != null)
				{
					if (iniAction.equals(IniHelper.SET))
					{
						aggWrCommon.setValue(sub,key,val);
					}
					else if (iniAction.equals(IniHelper.DELETE))
					{
						aggWrCommon.deleteValue(sub,key);
					}
				}
			}
			aggWrCommon.saveFile();
		}
	}
	EgConfigFilesSync.releaseInstance(aggWrCommon);
	if(action != null && !action.equals("null") && !action.equals(""))
	{
		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));
		EgDiscInfo discInfo = new EgDiscInfo("manager");
		ArrayList siteServers = discInfo.getSiteServers();
		if(isAggregateType && siteServers!= null && siteServers.size() >0 && siteServers.contains(stype.substring(stype.indexOf("_")+1)))
		{
			siteSupport = "true";
		}
		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);
		}
		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);
			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)
				{
					String associated_comps = request.getParameter("fassociate");
					String tArray[] = StringUtils.getTokens(associated_comps,",");
					ArrayList alist = new ArrayList();
					alist.addAll(Arrays.asList(tArray));

					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);
							boolean nowAssociated = alist.contains(secondPart);

							secondPart = secondPart.substring(secondPart.indexOf(":")+1);
							String secondaryKey = ":" + firstPart + secondPart + ":";
							String keyValue = aggWr.getValue("AGGREGATE_COMPONENTS",aggreagetComponents[i]);
							aggIniEntries.add(new IniHelper(IniHelper.DELETE,"AGGREGATE_COMPONENTS",aggreagetComponents[i],""));
							if(!nowAssociated)
							{
								continue;
							}
							String replaceWith = ":"+hostname+":";
							key = StringUtils.replace(key,searchString,replaceWith);
							aggIniEntries.add(new IniHelper(IniHelper.SET,"AGGREGATE_COMPONENTS",key,keyValue));
							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);
										aggIniEntries.add(new IniHelper(IniHelper.DELETE,"AGGREGATE_TEST_INFOS_EXCLUDED",key1,""));
										String searchString1 = "#" + temp + ":";
										String replaceWith1 = "#" + hostname + ":";
										String key12 = StringUtils.replace(key1,searchString1,replaceWith1);
										aggIniEntries.add(new IniHelper(IniHelper.SET,"AGGREGATE_TEST_INFOS_EXCLUDED",key12,keyValue1));
									}
								}
							}
						}
					}
				}
				if(aggIniEntries.size() > 0)
				{
					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);
			}
		}
	}

	//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);
				auditLogThread.setCurrentValue(auditNos+"Port Number",sportno);
				if(modifying)
				{
					String previousPortNumber = request.getParameter("previousportnumber");
					if(previousPortNumber !=null)
						auditLogThread.setPreviousValue(auditNos+"Port Number",previousPortNumber);
				}
			}
		}
	}
	//For Virtual Server Host

	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);
	}
	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);
	//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)
	{
		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;
			disableIniWr.deleteValue("Deleted_Servers",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;
				disableIniWr.deleteValue("Deleted_Servers",var);
				new_var_name = hostname.substring(hostname.indexOf(":")+1);
				new_var = hostname+":"+sportno+":"+tok+"#"+stype+"#"+new_var_name;
			}
		}
		else
		{
			var  = stype +":" + hostname + ":" + sportno + ":" + sid;
			disableIniWr.deleteValue("Deleted_Servers",var);
			new_var_name = hostname.substring(hostname.indexOf(":")+1);
			new_var = hostname+":"+sportno+":"+sid+"#"+stype+"#"+new_var_name;
		}

		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();
	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";
		}
	}

	//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");
	if(action != null && !action.equals("null") && !action.equals(""))
	//if (!allServers)
	{
		discWrite.deleteValue(stype,strCombine);
		if (isLimitedAdmin)
		{
			userCompIniDelList.add(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 + ",";
							}
						}
						discWrite.deleteValue(stype,strVar[i_ctr]);
						if (isLimitedAdmin)
						{
							userCompIniDelList.add(strVar[i_ctr]);
						}
					}
				}
			}
			else
			{
				if(strVar[i_ctr].equals(variableName))
				{
					discWrite.deleteValue(stype,strVar[i_ctr]);
					if (isLimitedAdmin)
					{
						userCompIniDelList.add(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))
							{
								discWrite.deleteValue("MTS_server",ss[a]);
								if (isLimitedAdmin)
								{
									userCompIniDelList.add(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"))
		{
			strCombine = stype+","+hostip+","+hostname+","+sportno;
			if(mtscheck != null)
			{
				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);
				}
				if(mtscheck.equals("Yes"))
				{
					strCombine = "MTS_server"+","+hostip+","+hostname+","+"NULL";
					strPass = "MTS_server"+":"+hostname+":"+"NULL";
					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);
					}
				}
			}
			else
			{
				discWrite.deleteValue(stype,"#Unmanage|"+strPass);
				discWrite.deleteValue(stype,"#New|"+strPass);
				if (isLimitedAdmin)
				{
					userCompIniDelList.add("#Unmanage|"+strPass);
					userCompIniDelList.add("#New|"+strPass);
				}
				discWrite.setValue(stype,strPass,strCombine+","+isPassive); //set the new values into discover.ini
				updateUuidIni(uuidInfo,hostname);
			}
		}
		String myTemp = request.getParameter("isPassive");
		if(myTemp != null && !myTemp.equals("null"))
		{
			auditLogThread.setCurrentValue("Is Passive",isPassive.substring(0,1).toUpperCase()+isPassive.substring(1));
			if(modifying)
			{
				String previousIsPassive = request.getParameter("previousispassive");
				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;
	//}

	IniFile egTests = new IniFile(EgInstallInfo.getInstallDir() + "/manager/config/eg_tests.ini");
	String aggAgent = egTests.getValue("AGENTS_FOR_AGGREGATE_COMPONENTS","ExternalAgentRunsAllAggTests");
	if (aggAgent != null &&(aggAgent.equalsIgnoreCase("yes") || aggAgent.equalsIgnoreCase("true")))
	{
		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)
			{
				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";
				}
				extIniWr = EgConfigFilesSync.getInstance(EgConfigInfo.egMgrConfigDir + "eg_external.ini");
				extIniWr.deleteValue("Remote_Agent_Mapping_Section",hostname);
				extIniWr.deleteValue("Agentless_Infos_Section",hostname);
				if(!externalAgentRunsAllAggTests)
				{
					extIniWr.setValue("Remote_Agent_Mapping_Section",hostname,remoteAgent);
				}
				extIniWr.saveFile();
				if (remoteUser == null || (remoteUser.equals("") || remoteUser.equalsIgnoreCase("null")))
				{
					remoteUser = "None";
				}

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

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

				if (remotepwd != 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(request.getParameter("enableRemoteAgent") != null && request.getParameter("enableRemoteAgent").equals("true"))
					{
						auditLogThread.setCurrentValue("Agentless","Yes");
					}
				}

				Hashtable operatingSystems = new Hashtable();
				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)
				{
					if(modifying)
					{
						String olderOSName = request.getParameter("olderosname");
						if(olderOSName !=null && !olderOSName.equalsIgnoreCase("null") && olderOSName.trim().length()>0)
							auditLogThread.setPreviousValue("OS",(String)operatingSystems.get(olderOSName.trim().toLowerCase()));
						else
							auditLogThread.setPreviousValue("OS","None");
					}
					auditLogThread.setCurrentValue("OS",(String)operatingSystems.get(remotealos));
				}

				if(!isAggregateType)
				{
					if(modifying)
					{
						String olderModeName = request.getParameter("oldermodename");
						if(olderModeName !=null && !olderModeName.equalsIgnoreCase("null") && olderModeName.trim().length()>0)
							auditLogThread.setPreviousValue("Mode",olderModeName.trim());
					}
					auditLogThread.setCurrentValue("Mode",remotemode);
				}
				if(modifying)
				{
					remoteAgentChangedForAuditlog = false;
					String olderRemoteAgentName = request.getParameter("olderremoteagentname");
					if(olderRemoteAgentName !=null && !olderRemoteAgentName.equalsIgnoreCase("null") && olderRemoteAgentName.trim().length()>0)
						auditLogThread.setPreviousValue("03~~Remote Agent",olderRemoteAgentName.trim());
					remoteAgentChangedForAuditlog = !(olderRemoteAgentName.trim().equals(remoteAgent));
				}
				auditLogThread.setCurrentValue("03~~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());
							}
						}
					}
				}
				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);
					if(modifying)
					{
						auditLogThread.setPreviousValue("Remote Port",request.getParameter("$_sshPort"));
					}
					auditLogThread.setCurrentValue("Remote Port",sshPort);
				}
				if(!externalAgentRunsAllAggTests)
				{
					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);
			}
		}
		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 components")+", ";
			msg += _mapping.getTextDescription("admin.error.please contact") +" <b>license@eginnovations.com</b>";
			obj.put("Error_Msg_2",msg);
			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();
			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
		 */
		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);
		//if(intAgentMode !=null && intAgentMode.equalsIgnoreCase("manual"))
		{
			String tempIntAgentMode = request.getParameter("intAgentMode");
			if(tempIntAgentMode != null && !StringUtils.isNull(tempIntAgentMode))
				auditLogThread.setCurrentValue("Internal Agent Assignment",intAgentMode);

			if(modifying)
			{
				String previousIntAgentMode = request.getParameter("previousintagentmode");
				if(previousIntAgentMode !=null && previousIntAgentMode.length()>0)
					auditLogThread.setPreviousValue("Internal Agent Assignment",previousIntAgentMode);
			}
		}
		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(request.getParameter("enableRemoteAgent") != null && request.getParameter("enableRemoteAgent").equals("false"))
			{
				auditLogThread.setCurrentValue("Agentless","No");
			}
		}
	}

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

	if(!callBasicErrorPage)
	{
		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);
		}
		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;
			usrLicStatus=1;
		}
		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(!needCertCheck || 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);
						}
						update = false;
						if (remoteType != null && remoteType.equalsIgnoreCase("true"))
						{
							EgDiscInfo discInfo = new EgDiscInfo("manager");
							EgSpecsInfo specsInfo = new EgSpecsInfo("manager");
							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>");
						rootJSON.put("Error_Info",obj);
						auditLogThread.setValue("Description","You have exceeded the number of monitored targets allowed by your license");
						auditLogThread.sendItToDB();
					}
					else
					{
						update = true;
					}
				}
			}
		}
		else
		{
			if (remoteType != null && remoteType.equalsIgnoreCase("true"))
			{
				EgDiscInfo discInfo = new EgDiscInfo("manager");
				EgSpecsInfo specsInfo = new EgSpecsInfo("manager");
				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(status == 2 || usrLicStatus == 3)
			{
				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");
				}
				auditLogThread.setValue("Description","You are exceeding the number of premium monitors allowed by your license");
				auditLogThread.sendItToDB();
				rootJSON.put("Error_Info",obj);
			}
			else if(status == 3)
			{
				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");
				}
				auditLogThread.setValue("Description","You are exceeding the total number of monitors permitted by your license");
				auditLogThread.sendItToDB();
			}
			else if(status == 4)
			{
				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");
				}
				auditLogThread.setValue("Description","You are exceeding the total number of applications permitted by your license");
				auditLogThread.sendItToDB();
			}
			else if(status == 5 || usrLicStatus == 4)
			{
				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");
				}
				auditLogThread.setValue("Description","You are exceeding the total number of network devices permitted by your license");
				auditLogThread.sendItToDB();
			}
			else if(status == 6 || usrLicStatus == 5)
			{
				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);
				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();
			}
			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");
				}
				auditLogThread.setValue("Description","You are exceeding the total number of total/basic monitors permitted by your license");
				auditLogThread.sendItToDB();
			}
		}
	}

	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;
			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);
	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
	 */
	if (!StringUtils.isNull(remoteAgent)
		&& !remoteAgent.equalsIgnoreCase("null")
		&& !prevRemAgent.equals(remoteAgent))
	{
		agentsToBeRemoved.add(prevRemAgent);
	}

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

		discWrite.saveFile();
		EgConfigFilesSync.releaseInstance(discWrite);
		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;

			List orgList = uuidInfo.getOrgNames(user_id);
			String orgNames = orgList.toString();
			orgNames = orgNames.substring(1,orgNames.length()-1);
			String directSubOrg = uuidInfo.getDirectDependentOU(user_id);

			if(stype.equals("Oracle_server"))
			{
				// dummy block for aggregate component
			}
			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);
				}
			}
			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();
			}
		}

		EgDiscInfo discInfos = new EgDiscInfo("manager");
		EgSpecsInfo specsInfos = new EgSpecsInfo("manager");
		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 ();
		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 = 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");
				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 = 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 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));
					}
				}
				if (entriesToDelete.size() > 0)
				{
					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);
			}
			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 = "true";
		if(aggType.equalsIgnoreCase("true"))
		{
			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));
			}
			extIniWr.saveFile();
			EgConfigFilesSync.releaseInstance(extIniWr);

			String old_hostname = request.getParameter("oldhostname");
			String associated_comps = request.getParameter("fassociate");
			String currentCompArray[] = StringUtils.getTokens(associated_comps,",");
			ArrayList currentCompListTemp = new ArrayList();
			currentCompListTemp.addAll(Arrays.asList(currentCompArray));
			Collections.sort(currentCompListTemp);
			currentCompArray = (String[])currentCompListTemp.toArray(new String[currentCompListTemp.size()]);
			ArrayList currentCompList = new ArrayList();
			for(int k=0;k<currentCompArray.length;k++)
			{
				String serverTypes = currentCompArray[k];
				currentCompList.add(serverTypes);
				if(serverTypes.endsWith(":NULL"))
				{
					auditLogThread.setCurrentValue("07~~Associated Components","$ctype$:"+serverTypes.substring(0,serverTypes.lastIndexOf(":")));
				}
				else
				{
					auditLogThread.setCurrentValue("07~~Associated Components","$ctype$:"+serverTypes);//new
				}
			}
			if(modifying)
			{
				individualCompsChangedForAuditlog = false;
				String exAssociatedComponents = request.getParameter("$_associated");
				if(exAssociatedComponents != null && exAssociatedComponents.trim().length()>0)
				{
					String previousCompArray[] = StringUtils.getTokens(exAssociatedComponents,",");
					ArrayList previousCompList = new ArrayList();
					previousCompList.addAll(Arrays.asList(previousCompArray));
					Collections.sort(previousCompList);
					previousCompArray = (String[])previousCompList.toArray(new String[previousCompList.size()]);
					for(int k=0;k<previousCompArray.length;k++)
					{
						String serverTypes = previousCompArray[k];
						if(!individualCompsChangedForAuditlog && !currentCompList.contains(serverTypes))
						{
							individualCompsChangedForAuditlog = true;
						}
						if(serverTypes.endsWith(":NULL"))
						{
							auditLogThread.setPreviousValue("07~~Associated Components","$ctype$:"+serverTypes.substring(0,serverTypes.lastIndexOf(":")));
						}
						else
						{
							auditLogThread.setPreviousValue("07~~Associated Components","$ctype$:"+serverTypes);
						}
					}
				}
			}
			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], ""));
					}
				}
			}
			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"))
			{
				autoAssociateCompForAuditlog = false;
				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") && elementType.equalsIgnoreCase("zone"))
				{
					String wasMemberComponent = request.getParameter("wasMemberComponent");
					if(wasMemberComponent == null || wasMemberComponent.trim().length()== 0 || wasMemberComponent.equalsIgnoreCase("null"))
					{
						autoAssociateCompForAuditlog = true;
						auditLogThread.setCurrentValue("06~~Auto associate this component to this zone",memberComponent.equalsIgnoreCase("yes")?"Yes":"No");
					}
					else
					{
						wasMemberComponent = wasMemberComponent.equals("true")? "yes":"no";
						if(!memberComponent.equals(wasMemberComponent))
						{
							autoAssociateCompForAuditlog = true;
							auditLogThread.setPreviousValue("06~~Auto associate this component to this zone",wasMemberComponent.equalsIgnoreCase("yes")?"Yes":"No");
							auditLogThread.setCurrentValue("06~~Auto associate this component to this zone",memberComponent.equalsIgnoreCase("yes")?"Yes":"No");
						}
					}
				}
			}
			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));
					}

					String anchorLabel = "05~~"+Character.toUpperCase(elementType.charAt(0)) + elementType.substring(1)  + " aggregate of this type for this zone";

					String wasAnchorComponent = request.getParameter("wasAnchorComponent");
					if(wasAnchorComponent == null || (wasAnchorComponent=wasAnchorComponent.trim()).length()==0 || wasAnchorComponent.equalsIgnoreCase("null"))
					{
						anchorChangedForAuditlog = true;
						auditLogThread.setCurrentValue("04~~Component created from "+elementType.toLowerCase(),elementName);
						auditLogThread.setCurrentValue(anchorLabel,anchorComp.equalsIgnoreCase("yes")?"Yes":"No");
					}
					else
					{
						wasAnchorComponent = wasAnchorComponent.equals("true")? "Yes":"No";
						anchorComp = anchorComp.equals("yes")? "Yes":"No";
						if(!anchorComp.equals(wasAnchorComponent))
						{
							anchorChangedForAuditlog = true;
							auditLogThread.setPreviousValue(anchorLabel,wasAnchorComponent);
							auditLogThread.setCurrentValue(anchorLabel,anchorComp);
						}
					}
				}
				//deleting anchor component block ends
			}
			else
			{
				String comptype_hostname_2 = stype + ":" + oldhostname + ":" + sportno + "#";
				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) || agg_comps[i].startsWith(comptype_hostname_2))
						{
							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)
			{
				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);
		}
		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;

			String prevAgents = request.getParameter("prevAgents");
			if(prevAgents != null && prevAgents.length()>0)
				auditLogThread.setPreviousValue("Internal Agent",prevAgents);
			auditLogThread.setCurrentValue("Internal Agent",currAgent);
			IniFile testinfoptrW =EgConfigFilesSync.getInstance(EgConfigInfo.egMgrConfigDir + "eg_testinfo.ini");
			String [] vars = testinfoptrW.getVariables(oldIntAgent);
			if(vars != null && vars.length > 0)
			{
				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);
		}
		ArrayList extIniEntries = new ArrayList();
		if(!allExternalTests)
		{
			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;
				extIniEntries.add(new IniHelper(IniHelper.DELETE,"Internal_Agent_Mapping", oldAlias,""));
				extIniEntries.add(new IniHelper(IniHelper.SET,"Internal_Agent_Mapping", hostname, currAgent));
			}
			else
			{
			/*
			 *	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
			 */
				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);
				extIniEntries.add(new IniHelper(IniHelper.SET,"Test_Mapping_Section", hostname, externalAgent));
				if(modifying)
				{
					auditLogThread.setPreviousValue("External Agents",prevExtAgents);
				}
				auditLogThread.setCurrentValue("External Agents",externalAgent);
			}
			catch(Exception e)
			{
				e.printStackTrace();
			}
		}
		if(underVmware!=null && underVmware.equalsIgnoreCase("true"))
		{
			if(esxServer !=null && !esxServer.equals("-1"))
			{
				if(sid!=null && sid.length()>0)
				{
					extIniEntries.add(new IniHelper(IniHelper.SET,"Virtual_Components", stype+":"+hostname+":"+sportno+":"+sid, esxServer));
				}
				else
				{
					extIniEntries.add(new IniHelper(IniHelper.SET,"Virtual_Components", stype+":"+hostname+":"+sportno, esxServer));
				}
				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);
			}
		}
		if(underCloud!=null && underCloud.equalsIgnoreCase("true"))
		{
			if(cloudServer !=null && !cloudServer.equals("-1"))
			{
				if(sid!=null && sid.length()>0)
				{
					extIniEntries.add(new IniHelper(IniHelper.SET,"Cloud_Components", stype+":"+hostname+":"+sportno+":"+sid, cloudServer));
				}
				else
				{
					extIniEntries.add(new IniHelper(IniHelper.SET,"Cloud_Components", stype+":"+hostname+":"+sportno, cloudServer));
				}
			}
		}
		if(!type.equals("new") && underCloud!=null && underCloud.equalsIgnoreCase("false"))
		{
			String variable = null;
			if(sid!=null && sid.length()>0)
			{
				variable = stype+":"+hostname+":"+sportno+":"+sid;
				extIniEntries.add(new IniHelper(IniHelper.DELETE,"Cloud_Components",variable,""));
			}
			else
			{
				variable = stype+":"+hostname+":"+sportno;
				extIniEntries.add(new IniHelper(IniHelper.DELETE,"Cloud_Components",variable,""));
			}
			variable = null;
		}
		if(!type.equals("new") && underVmware!=null && underVmware.equalsIgnoreCase("false"))
		{
			String variable = null;
			if(sid!=null && sid.length()>0)
			{
				variable = stype+":"+hostname+":"+sportno+":"+sid;
				extIniEntries.add(new IniHelper(IniHelper.DELETE,"Virtual_Components",variable,""));
			}
			else
			{
				variable = stype+":"+hostname+":"+sportno;
				extIniEntries.add(new IniHelper(IniHelper.DELETE,"Virtual_Components",variable,""));
			}
			variable = null;
		}
		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);
		}
		rootJSON.put("compType",server_type);
		rootJSON.put("compName",server_name);
		rootJSON.put("hostIp","0.0.0.0");

		rootJSON.put("compType",stype);
		String selectedCategory = request.getParameter("selectedCategory");
		if(selectedCategory == null || (selectedCategory=selectedCategory.trim()).length()==0 || selectedCategory.equalsIgnoreCase("null"))
		{	selectedCategory = "-1";
		}
		rootJSON.put("selectedCategory",selectedCategory);
		UpdateVcConfig updateVcConfig = new UpdateVcConfig();
		if (modifying) // If modify component
		{
			// IsPassive Fix starts here
			String preIsPassive = request.getParameter("previousispassive");
			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;
										iniEntries.add(new IniHelper(agentSub,variable,value));
									}
								}
							}
						}
					}
					if (iniEntries.size() > 0)// Have entries to update 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();
					}
				}
			}
			if (stype.equals("Virtual_center"))
			{
				updateVcConfig.changeVcConfig(hostname,oldhostname);
			}
			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(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
				{
					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();
				}
				if (prevExtList.size() > 0) //List of subjects, where the relevant entries have to be removed
				{
					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();
				}
			}

			//Remote agent related fix
			String oldAgentName = request.getParameter("olderremoteagentname");
			if (oldAgentName == null)
				oldAgentName ="";
			if (oldAgentName.equals("") && remoteAgent!=null && remoteType!=null && remoteType.equals("true")) // AgentBased --> Agentless
			{
				String varArr[] = testInfoToWrite.getVariables(hostname);
				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;
						}
						String val = testInfoToWrite.getValue(hostname,var);
						testInfoToWrite.setValue(remoteAgent,var,val);
						testInfoToWrite.deleteValue(hostname,var);
					}
					testInfoToWrite.saveFile();
				}
			}
			else
			{
				String newAgentName = "";
				if (oldAgentName != null && remoteAgent == null && remoteType!=null && remoteType.equals("false")) // Agentless --> AgentBased
				{
					 newAgentName = hostname;
				}
				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);
							}
						}
						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);
			//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;
			ArrayList iniEntriesList = new ArrayList();
			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 (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)
			{
				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);
		}
		// 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);
		}
		EgConfigFilesSync.releaseInstance(infraIni);
		if(isExistingAggType != null && isExistingAggType.equals("false"))
		{
			while(true)
			{
				if(!EgUpdateRegistry.isRunning)
				{
					//synchronized(EgUpdateRegistry.syncString)
					{
						EgUpdateRegistry.lastCheckTime=0;
						registry.updateAllUserMaps();
					}
					break;
				}
			}
		}
		else
		{
			registry.updateAllUserMaps();
		}
		if(isAggregateType)
		{
			IniFile aggIni = EgConfigFilesSync.getInstance(EgInstallInfo.getInstallDir() + "/manager/config/eg_aggregate.ini");

			if(siteSupport != null && siteSupport.equals("true"))
			{
				EgTopoInfo topoInfo = new EgTopoInfo("manager");
				String siteAssociated="no";
				String associated_comps_now = request.getParameter("fassociate");
				if(associated_comps_now != null && (associated_comps_now=associated_comps_now.trim()).length()>0)
				{
					StringTokenizer acn = new StringTokenizer(associated_comps_now,",");
					while(acn.hasMoreTokens())
					{
						String comp_associated = acn.nextToken();
						ArrayList siteArrayList = topoInfo.getSitesForComponent(comp_associated);
						if(siteArrayList != null && !siteArrayList.isEmpty())
						{
							siteAssociated="yes";
							break;
						}
					}
				}
				boolean result = aggIni.setValue("SITE_SUPPORT",stype+":"+hostname+":NULL",siteAssociated);
				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);
		}
		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")+".");
		}
		else
		{
			rootJSON.put("Result_info",_mapping.getTextDescription("admin.server.Component has been added successfully")+".");
		}
	}

	if (discWrite != null)
		EgConfigFilesSync.releaseInstance(discWrite);

	if(remoteAgentChangedForAuditlog || autoAssociateCompForAuditlog || anchorChangedForAuditlog || individualCompsChangedForAuditlog)
	{
		auditLogThread.sendItToDB();
	}
	/*
	 * Update the settings for all user IDs.
	 */
	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)
		{
			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);
		}
	}

%>

