<%@ include file="../../EgTrackerAJSON.jsp"%>
<%@ page import = "net.sf.json.*"%>
<%@ page import = "java.util.*" %>
<%@ page import = "com.egurkha.ini.IniUI" %>
<%@ page import = "com.egurkha.util.*" %>
<%@ page import = "com.eg.DeleteTTFilterElements"%>
<%@ page import = "com.egurkha.admin.AuditLogThread"%>
<%@ page import = "com.egurkha.admin.ComponentAdd"%>
<%@ page import = "com.egurkha.admin.UserAssociateComponent"%>
<%@ page import = "com.egurkha.monitor.EgComponentUserMappingBean"%>
<%@ page import = "com.egurkha.monitor.EgCustomDashboardModel"%>
<%@ page import = "com.egurkha.SLA.DAO.EgSLADashBoardDAO"%>
<%@ page import = "egurkha.reporter.ErUserData"%>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>


<jsp:useBean id="tpbean" scope="request" class="egurkha.EgTestParamBean"/>
<jsp:useBean id="manager" scope="request" class="egurkha.ConfigBean"/>
<jsp:useBean id="servicer" scope="request" class="egurkha.ServiceBean"/>
<jsp:useBean id="EgConfigTopo1" scope="page" class="egurkha.ConfigTopology"/>
<jsp:useBean id="EgconfTopo1forVm" scope="page" class="egurkha.ConfigTopology"/>
<jsp:useBean id="user" scope="request" class="egurkha.UserBean"/>
<jsp:useBean id="trans" scope="request" class="egurkha.TransactionBean"/>
<jsp:useBean id="trans1" scope="request" class="egurkha.TransactionBean"/>
<jsp:useBean class="com.egurkha.admin.UserDetailsBean" id="userDetails" scope="page"/>
<jsp:useBean id="ecumb" scope="page" class="com.egurkha.monitor.EgComponentUserMappingBean" />
<jsp:useBean id="menu" scope="page" class="egurkha.ConfigBean"/>

<%
	JSONObject rootObj = new JSONObject();
	JSONObject errorObj = new JSONObject();
	JSONArray errArray = new JSONArray();

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

	EgConfigTopo1.createFile("eg_services.ini");
	int compSize = Integer.parseInt(EgConfigTopo1.getValues("MISC_ARGS","MaxManagedComponentsForDisc"));
	EgRoleInfo egRoleInfo = EgRoleInfo.getInstance(session.getId(),(String)session.getAttribute("sess_userid"));
	String[] sTypes = egRoleInfo.getServerTypes();
	EgUsersInfo usersInfo = new EgUsersInfo();
	EgDiscInfo egDiscInfo = new EgDiscInfo("manager");
	EgExternalInfo extInfoObj = new EgExternalInfo("manager");
	String[] extAgents = extInfoObj.getAllExternalAgents();
	String[] remAgents = extInfoObj.getAllRemoteAgents();
	ArrayList userVdiTypes = usersInfo.getAllUserBasedCompTypes();
	boolean hasLimitExceeded=false;
	boolean isNamedUsersCert = EgInstallInfo.isnamedUserLicense;
	String tempManage = "";
	String isProceed = "";
	ArrayList prevUnmngCmpWithTypes = new ArrayList();

	/* for user-comp mapping - START*/
	int usrLicStatus = 0;
	String userExtAgent = "";
	String loginUserID = _user.getLoginID();
	boolean isMspModel = EgUuidInfo.isMspModel();
	boolean autoCreateZoneForUser = EgUuidInfo.autoCreateZone();
	boolean allowZoneAssociation = false;
	boolean shareNickAcrossOU = EgUuidInfo.shareNickAcrossOU();
	String userCompMap = EgConfigInfo.egMgrConfigDir + "eg_usercompmapping.ini";
	EgMappingInfo mappingInfo = new EgMappingInfo(_user.getLanguage());
	EgUserElementsInfo userElemInfo = new EgUserElementsInfo();
	UserAssociateComponent uacObj = new UserAssociateComponent(_user.getLoginID(),_user.getUserIP(session.getId()),session.getId());
	uacObj.setRequestFrom("manageunmanage");
	ErUserData erUser;
	EgCertUsage egCertUsage = new EgCertUsage();
	EgUuidInfo uuidInfo = new EgUuidInfo();
	Hashtable userServCompsMap = new Hashtable();
	ArrayList usersList = new ArrayList();
	ArrayList allLimCompAccessUsers = egCertUsage.getAllLimitedCompAccessUsers(true);
	boolean isLimitedAdmin = (allLimCompAccessUsers != null && allLimCompAccessUsers.contains(loginUserID));
	String _srvtype = request.getParameter("srvtype");
	if(_srvtype == null)
	{
		_srvtype = "";
	}
	if (shareNickAcrossOU)
	{
		usersList.addAll(allLimCompAccessUsers);
	}
	else
	{
		String org_name = uuidInfo.isSuperOrg(loginUserID) ? loginUserID : uuidInfo.getSuperOU(loginUserID);
		if(org_name != null && !org_name.equals(""))
		{
			usersList = new ArrayList(uuidInfo.getAllUsersUnderOrg(org_name));
			usersList.retainAll(allLimCompAccessUsers);
			if (org_name.equalsIgnoreCase("egenterprise"))
			{
				ArrayList defOrgDefUsersList = User.getDefaultUsers();
				usersList.removeAll(defOrgDefUsersList);
			}
			usersList.add(org_name);
		}
		usersList.addAll(uuidInfo.getUnmanagedCompUsersList(_srvtype));
	}
	//if (isMspModel)
	if (isLimitedAdmin)
	{
		for(int i=0; i<usersList.size(); i++)
		{
			String user_Id = (String)usersList.get(i);
			erUser = new ErUserData(user_Id,false);
			ArrayList userServCompsList1 = new ArrayList();
			if (user_Id.equalsIgnoreCase("egenterprise"))
			{
				userServCompsList1 = uuidInfo.getDefaultOrganizationCompList();
			}
			else
			{
				userServCompsList1 = new ArrayList(erUser.getAllUserComponents(2));
			}
			if(userServCompsList1 != null && userServCompsList1.size()>0)
			{
				userServCompsList1 = getUserCompsNick(userServCompsList1,_srvtype);
				if(userServCompsList1 != null && userServCompsList1.size()>0)
				{
					userServCompsMap.put(user_Id,userServCompsList1);
				}
			}
		}
	}
	/* for user-comp mapping - END*/

	IniFile iniui = new IniFile(EgInstallInfo.getInstallDir()+ "/manager/config/eg_ui.ini");
	String delVCFromVCDisc = iniui.getValue("MISC_ARGS","delVCFromVCDisc");
	IniUI ui = IniUI.getInstance();	
	boolean isEnableSLA = ui.isSLAEnabled();
	EgSLADashBoardDAO slaDashBoardDAO = null;
	if(isEnableSLA)
	{
		if(slaDashBoardDAO == null)
		{
			slaDashBoardDAO = new EgSLADashBoardDAO();
		}
	}

	Vector managedAllComps = egDiscInfo.getAllManagedComponents();
	if (managedAllComps != null && (managedAllComps.size() > compSize))
	{
		hasLimitExceeded = true;
	}
	/*int cnt=0;
	if (sTypes != null && sTypes.length > 0)
	{
		for (int st=0;st<sTypes.length;st++)
		{
			String[] strComps = egRoleInfo.getAllServersOfType(sTypes[st]);
			if (strComps.length > 0)
			{
				cnt = cnt + strComps.length;
				if (cnt > compSize)
				{
					hasLimitExceeded = true;
					break;
				}
			}
		}
	}*/
	UpdateAndTransmitTopoInfo delFromDB = new UpdateAndTransmitTopoInfo();
	String eGInstallDir = EgInstallInfo.getInstallDir();
	//Vector aggregateManagedComponents = new Vector();
	String srvtype = "";
	String activeCompTypes = request.getParameter("activeCompTypes");
	srvtype = request.getParameter("srvtype");
	String fromValue = request.getParameter("from");
	String doAction = request.getParameter("doAction");

	String fromWizard = request.getParameter("fromWizard");
	if (StringUtils.isNull(fromWizard))
	{
		fromWizard = "";
	}
	
	boolean showDiscoveryTree = false;
	if (fromValue == null)
	{
		fromValue = "";
	}
	if (fromValue.equalsIgnoreCase("comp"))
	{
		showDiscoveryTree = true;
	}

	// from new discovery page
	ArrayList allServerstoManage = new ArrayList();
	ArrayList newServers = null;
	if (fromValue.equalsIgnoreCase("newServerDiscovery"))
	{
		newServers = (ArrayList)session.getAttribute("newServers");
		if (newServers != null && newServers.size() > 0)
		{
			allServerstoManage.addAll(newServers);
		}
	}
	else
	{
		allServerstoManage.add(srvtype);
	}
	IniFile serviceInfo = new IniFile(eGInstallDir + "/manager/config/eg_services.ini");
	IniFile discoverInfo = new IniFile(eGInstallDir + "/manager/config/eg_discover.ini");
	
	String[] agentlessInfo = serviceInfo.getVariables("DEFAULT_AGENTLESS_SETTINGS");
	List agentlessInfoList = new ArrayList();
	if (agentlessInfo != null)
	{
		agentlessInfoList = new ArrayList(Arrays.asList(agentlessInfo));
	}
	
	String tmpManServers = "";
	String tmpManServerswithType = "";
	String tmpUnManServers = "";
	String tmpUnManServerswithType = "";
	Hashtable sessionHashTable = new Hashtable();
	List serversInfo = new ArrayList();
	if (fromValue.equalsIgnoreCase("newServerDiscovery"))
	{
		menu.createFile("eg_discover.ini");
	}

	String unmanagedNickCache = request.getParameter("funmanage");
	if (unmanagedNickCache == null) unmanagedNickCache = "";

	String tempManageStr = request.getParameter("fmanage");
	String monitorLastSession=(String)session.getAttribute("monitorLastSession");
	String newUrlLink=" ";
	String strHostName="";
	String strcurrentTab=" ";
	String urlLink=" ";

	if(monitorLastSession!=null && monitorLastSession.trim().length()>0)
	{
		if(monitorLastSession.indexOf('?') == -1)
		{
			newUrlLink=monitorLastSession;
		}
		else
		{
			newUrlLink=monitorLastSession.substring(0,monitorLastSession.indexOf('?'));
			urlLink = monitorLastSession.substring(monitorLastSession.indexOf('?')+1);
		}

		StringTokenizer multiTokenizer = new StringTokenizer(urlLink,"&");
		while(multiTokenizer.hasMoreTokens())
		{
			String param = multiTokenizer.nextToken();
			int ind = param.indexOf("=");
			if (ind < 0)
				continue;
			String reqparam =param.substring(0,ind);
			String paramValue = param.substring(ind+1);

			if(reqparam.equals("tab"))
			{
				String currentTab = paramValue;
				if(currentTab != null && currentTab.trim().length()>0)
				{
					strcurrentTab=com.eg.EgURLDecoder.decode(currentTab, "UTF-8");
				}
			}
			else if(reqparam.equals("host"))
			{
				String hostValue = paramValue;
				if(hostValue != null && hostValue.trim().length()>0)
				{
					strHostName=com.eg.EgURLDecoder.decode(hostValue, "UTF-8");
				}
			}

		}
	}

	// Fix starts here
	// Issue : When comps have been searched from managed comp list and unmanaged, then all excluded tests for all comps under the type will get included
	//EgDiscInfo egDiscInfo = new EgDiscInfo("manager");
	//String searchStr = request.getParameter("strManagedSearch");
	String manageComps = "";
	String[] managedComps = egDiscInfo.getAllServersOfType(srvtype);//egRoleInfo.getAllServersOfType(srvtype);
	String userTempManageStr = request.getParameter("fmanage");
	String userTempUnManageStr = request.getParameter("funmanage");
	String userManagewithcomptype = request.getParameter("fmanagewithcomptype");

	// filtering manage/unamange comps - decide whether doing managing or unmanaging or both the operations.
	boolean isManage = false;
	boolean isUnmanage = false;
	ArrayList currMgdCompList = new ArrayList();
	ArrayList currUnMgdCompList = new ArrayList();
	// Check with previous(sessionParam) manage comps with the current(requestParam) manage comps and filter to get exact component which is going to unmange
	if (userTempManageStr != null && userTempManageStr.length()>0)
	{
		currMgdCompList = StringUtils.egTokenizer(userTempManageStr,",",false,false,true);
		Vector managedCompsListPrev = (Vector) session.getAttribute("managed");
		if (managedCompsListPrev != null && managedCompsListPrev.size()>0)
		{
			for (int m=0; m<managedCompsListPrev.size(); m++)
			{
				String tempCName = managedCompsListPrev.get(m).toString().trim();
				tempCName = tempCName.substring(tempCName.indexOf(":")+1);
				currMgdCompList.remove(tempCName);
			}
		}
		userTempManageStr = "";
		if (currMgdCompList.size() > 0)
		{
			for (int m=0; m<currMgdCompList.size(); m++)
			{
				userTempManageStr += currMgdCompList.get(m).toString().trim() + ",";
			}
			userTempManageStr = userTempManageStr.substring(0,userTempManageStr.lastIndexOf(","));
			isManage = true;
		}
	}
	// Check with previous(sessionParam) unmanage comps with the current(requestParam) manage one and filter to get exact component which is going to manage
	if (userTempUnManageStr != null && userTempUnManageStr.length()>0)
	{
		currUnMgdCompList = StringUtils.egTokenizer(userTempUnManageStr,",",false,false,true);
		Vector unmanagedCompsListPrev = (Vector) session.getAttribute("unmanaged");
		if (unmanagedCompsListPrev != null && unmanagedCompsListPrev.size()>0)
		{
			currUnMgdCompList.removeAll(unmanagedCompsListPrev);
		}
		userTempUnManageStr = "";
		if (currUnMgdCompList.size() > 0)
		{
			for (int m=0; m<currUnMgdCompList.size(); m++)
			{
				userTempUnManageStr += currUnMgdCompList.get(m).toString().trim() + ",";
			}
			userTempUnManageStr = userTempUnManageStr.substring(0,userTempUnManageStr.lastIndexOf(","));
			isUnmanage = true;
		}
	}

	boolean isThruSearch = false;
	if (!fromValue.equalsIgnoreCase("newServerDiscovery"))
	{
		isThruSearch = true;
		List unManCompList = new ArrayList();
		List manCompList = new ArrayList();
		if (managedComps!= null)
		{
			for (int m=0; m<managedComps.length; m++)
			{
				String tmp = managedComps[m];
				tmp = tmp.substring(tmp.indexOf(":")+1);
				manCompList.add(tmp);
			}
		}
		if (tempManageStr != null)
		{
			StringTokenizer manCompsStt = new StringTokenizer(tempManageStr,",");
			while(manCompsStt.hasMoreTokens())
			{
				String tmpComp = manCompsStt.nextToken(); 
				if (!manCompList.contains(tmpComp))
				{
					manCompList.add(tmpComp);
				}
			}
		}
		//String unmanagedComps = request.getParameter("funmanage");
		String unmanagedComps = unmanagedNickCache;
		if (unmanagedComps != null)
		{
			StringTokenizer unManComps = new StringTokenizer(unmanagedComps,",");
			while(unManComps.hasMoreTokens())
			{
				String comp = unManComps.nextToken();
				unManCompList.add(comp);
			}
			manCompList.removeAll(unManCompList);
		}
		
		if (manCompList.size() > 0)
		{
			for (int m=0; m<manCompList.size(); m++)
			{
				String temp = manCompList.get(m).toString();
				manageComps += temp+",";
			}
			manageComps = manageComps.substring(0,manageComps.length()-1);
		}
		tempManageStr = manageComps;

		if (isLimitedAdmin)
		{
			String user_id = _user.getLoginID();
			String[] userManagedComps = StringUtils.getTokens(userTempManageStr,",");
			ArrayList manCompArrList = new ArrayList();
			if (userManagedComps != null)
			{
				int userManagedCompsLen = userManagedComps.length;
				for (int m=0; m<userManagedCompsLen; m++)
				{
					String t = userManagedComps[m];
					String var = srvtype + ":" + t;
					manCompArrList.add(var);
				}

				List orgList = uuidInfo.getOrgNames(user_id);
				int orgListLen = (orgList != null) ? orgList.size() : 0;
				String mamCompsStr = manCompArrList.toString();
				mamCompsStr = mamCompsStr.substring(0,mamCompsStr.length()-1);
				for (int y=0; y<orgListLen; y++)
				{
					String org_id = orgList.get(y).toString().trim();
					GroupCertValidator grpCert = new GroupCertValidator(org_id);
					usrLicStatus = grpCert.checkBulkMonitors (srvtype,org_id,manCompArrList);
					if (usrLicStatus != 1)
					{
						String compsForLog = manCompArrList.toString();
						compsForLog = compsForLog.substring(1,compsForLog.length()-1);
						grpCert.errorLogWrite(org_id,compsForLog,"managing");
						break;
					}
				}
			}
		}
	}
	
	ArrayList emulatedList = extInfoObj.getEmulatedTypes();
	Object [] emuClient = extInfoObj.getClientEmulatingAgents();
	boolean clientEmuComps = false;
	if(userTempManageStr != null && userTempManageStr.length()>0)
	{
		boolean isNickShared = false;
		ArrayList manCompLowerList = new ArrayList();
		String s_host_name = "";
		StringTokenizer manCompsStrTkns = new StringTokenizer(userTempManageStr,",");
		while(manCompsStrTkns.hasMoreTokens())
		{
			String tmpComp = manCompsStrTkns.nextToken();
			tmpComp = tmpComp.substring(0,tmpComp.indexOf(":"));
			tmpComp = tmpComp.toLowerCase();
			if (!manCompLowerList.contains(tmpComp))
			{
				manCompLowerList.add(tmpComp);
			}
		}
		/**
		 * Alert - when managing the other user's nick.
		 */
		if(isMspModel && !shareNickAcrossOU)
		{
			ArrayList usersSharedAgents = new ArrayList();
			Hashtable orgUsersNickMap = uuidInfo.getAllUsersNickMap(true,true);
			if(orgUsersNickMap != null && manCompLowerList != null && manCompLowerList.size()>0)
			{
				String user_name = loginUserID;
				if(!orgUsersNickMap.containsKey(user_name))
				{
					user_name = uuidInfo.getSuperOU(loginUserID);
				}
				if (user_name !=null && (!user_name.equalsIgnoreCase("eGEnterprise") && !loginUserID.equalsIgnoreCase("admin")))
				{
					Enumeration enu = orgUsersNickMap.keys();
					while(enu.hasMoreElements())
					{
						String orgName = (String)enu.nextElement();
						if(!orgName.equalsIgnoreCase(user_name))
						{
							Vector nickList = (Vector)orgUsersNickMap.get(orgName);
							if(nickList != null)
							{
								Vector nicksListLower = new Vector();
								int nicListSize = nickList.size();
								for (int a=0; a < nicListSize; a++)
								{
									String nickLower = nickList.get(a).toString().toLowerCase();
									if (!nicksListLower.contains(nickLower))
									{
										nicksListLower.add(nickLower);
									}
								}
								nicksListLower.retainAll(manCompLowerList);
								if(nicksListLower != null && nicksListLower.size() > 0)
								{
									usersSharedAgents.add(orgName);
									s_host_name = nicksListLower.toString();
									s_host_name = s_host_name.substring(1,s_host_name.length()-1); 
								}
							}
						}
					}
				}
			}
			if(usersSharedAgents != null && usersSharedAgents.size() > 0)
			{
				isNickShared = true;
				rootObj.put("success","true");
				rootObj.put("requestStatus","failed");
				errorObj.put("title",_mapping.getTextDescription("admin.server.Manage/UnManage components"));
				errorObj.put("message1",_mapping.getTextDescription("admin.error.The nick name")+" ("+s_host_name+") "+_mapping.getTextDescription("admin.error.you are trying to manage is already existing")+". ");
				errorObj.put("message2",_mapping.getTextDescription("admin.error.You are not allowed to managed this component")+".");
				rootObj.put("errors",errorObj);
				out.println(rootObj.toString());
				return;
			}
		}
		/**
		 * Alert - when managing client emulated component without a client emulated external agent.
		 */
		if(emulatedList.contains(srvtype))
		{
			clientEmuComps = true;
			if (emuClient != null && emuClient.length > 0)
			{
				String u_name = _user.getLoginID();
				EgUserElementsInfo userElemInfoObj = new EgUserElementsInfo();
				ArrayList tempCliEmuExtAgents = new ArrayList(Arrays.asList(emuClient));
				ArrayList usersCliEmuExtAgents = new ArrayList();
				if(isLimitedAdmin)
				{
					usersCliEmuExtAgents = userElemInfoObj.getExternalAgentsForUser(u_name);
					usersCliEmuExtAgents.retainAll(tempCliEmuExtAgents);
				}
				else
				{
					usersCliEmuExtAgents.addAll(tempCliEmuExtAgents);
				}
				if (usersCliEmuExtAgents != null)
				{
					emuClient = (String[])usersCliEmuExtAgents.toArray(new String[0]);
				}
			}
			if(emuClient.length == 0)
			{
				rootObj.put("success","true");
				rootObj.put("requestStatus","failed");
				errorObj.put("title",_mapping.getTextDescription("admin.error.Manage / Unmanage"));
				errorObj.put("title",_mapping.getTextDescription("admin.server.Manage/UnManage components"));
				errorObj.put("message1",_mapping.getTextDescription("admin.error.Currently, there are no external agents with client emulation capability enabled")+".");
				errorObj.put("message2",_mapping.getTextDescription("admin.error.This component can be managed only after an external agent with client emulation capability is added")+".");
				rootObj.put("errors",errorObj);
				out.println(rootObj.toString());
				return;
			}
		}
	}

	HashMap tmpMap = isValidNickIPMap(tempManageStr,srvtype);
	if (((Boolean)tmpMap.get("hasRestrictedNicks")).booleanValue())
	{
		ArrayList restrictedComps = (ArrayList)tmpMap.get("restrictedComps");
		int compsCount = restrictedComps.size();
		String compsList = restrictedComps.toString();
		compsList = compsList.substring(1,compsList.length()-1);
		rootObj.put("success","true");
		rootObj.put("hasRestrictedNicks",new Boolean(true));
		errorObj.put("title",_mapping.getTextDescription("admin.error.Manage / Unmanage"));
		if (((ArrayList)tmpMap.get("removableNicks")).size() > 0)
		{
			ArrayList listCount = (ArrayList)tmpMap.get("removableNicks");
			String removableNicksStr = listCount.toString();
			removableNicksStr = removableNicksStr.substring(1,removableNicksStr.length()-1);
			if (listCount.size() == 1)
			{
				errorObj.put("message1",_mapping.getTextDescription("admin.error.The following nick name you are trying to manage is already existing with a different case")+".");
			}
			else
			{
				errorObj.put("message1",_mapping.getTextDescription("admin.error.The following nick names you are trying to manage are already existing with different case")+".");
			}
			errorObj.put("message2",removableNicksStr);
		}
		else
		{
			if (compsCount == 1)
			{
				errorObj.put("message1",_mapping.getTextDescription("admin.error.The following nick name is already assigned to a different HostIP/Name")+".");
			}
			else
			{
				errorObj.put("message1",_mapping.getTextDescription("admin.error.The following nick names are already assigned to different HostIPs/Names")+".");
			}
			errorObj.put("message2",compsList);
		}
		rootObj.put("errorStack",errorObj);
		if (tmpMap.get("newCompStr").toString().length() > 0)
		{
			unmanagedNickCache = unmanagedNickCache + ","+tmpMap.get("newCompStr").toString();
		}
		if (tmpMap.get("finalServersStr").toString().length() == 0 && unmanagedNickCache.length() == 0)
		{
			rootObj.put("requestStatus","success");
			out.println(rootObj.toString());
			return;
		}
	}
	//Follwing fix is specific to Fiducia. 
	//During unmanage,Any user based comp nick matches with external agent nick,then we have to block the unmanage operation. 
	Vector unmanagedCompsPrev = (Vector) session.getAttribute("unmanaged");
	ArrayList prevUnManComps = new ArrayList();
	if (unmanagedCompsPrev!=null)
	{
		for (int u=0; u < unmanagedCompsPrev.size(); u++)
		{
			String temp = (String)unmanagedCompsPrev.get(u);
			prevUnManComps.add(temp.trim());
			prevUnmngCmpWithTypes.add(srvtype+":"+temp.trim());
		}
	}
	ArrayList newlyUnManComps = new ArrayList();
	if (unmanagedNickCache != null)
	{
		StringTokenizer stt = new StringTokenizer(unmanagedNickCache,",");
		while (stt.hasMoreTokens())
		{
			newlyUnManComps.add(stt.nextToken());
		}
		newlyUnManComps.removeAll(prevUnManComps);
	}
	if (usersInfo.isExtCheck() && userVdiTypes.contains(srvtype))
	{
		ArrayList newlyUnManCompNicks = new ArrayList();
		for (int n=0; n < newlyUnManComps.size(); n++)
		{
			String nick = (String)newlyUnManComps.get(n);
			int idx = nick.indexOf(":");
			if(idx > -1)
				nick = nick.substring(0,idx);
			newlyUnManCompNicks.add(nick);
		}
	
		ArrayList badNicks = new ArrayList();
		for (int a=0; a<extAgents.length; a++)
		{
			if (newlyUnManCompNicks.contains(extAgents[a]))
			{
				badNicks.add(extAgents[a]);
			}
		}
		if (badNicks.size() > 0)
		{
			rootObj.put("success","true");
			rootObj.put("hasRestrictedNicks",new Boolean(true));
			errorObj.put("title",_mapping.getTextDescription("admin.error.Manage / Unmanage"));
			if(badNicks.size()==1)
			{
				errorObj.put("message1",_mapping.getTextDescription("admin.error.The following nick name you are trying to unmanage is already assigned to an external agent")+".");
			}
			else
			{
				errorObj.put("message1",_mapping.getTextDescription("admin.error.The following nick names you are trying to unmanage are already assigned to external agents")+".");
			}
			String badNicksStr = badNicks.toString();
			badNicksStr = badNicksStr.substring(1,badNicksStr.length()-1);
			errorObj.put("message2",badNicksStr);
			rootObj.put("errorStack",errorObj);
			rootObj.put("requestStatus","success");
			out.println(rootObj.toString());
			return;
		}
	}

	//Fix to restrict a external comp to manage when its nick name has already been assigned to an agenteless component and vice versa.
	tempManageStr = tmpMap.get("finalServersStr").toString();
	tmpMap = monitoringApproachCheck(tempManageStr,srvtype,agentlessInfoList);
	if (((Boolean)tmpMap.get("hasRestrictedNicks")).booleanValue())
	{
		ArrayList restrictedComps = (ArrayList)tmpMap.get("restrictedComps");
		int compsCount = restrictedComps.size();
		String compsList = restrictedComps.toString();
		compsList = compsList.substring(1,compsList.length()-1);
		rootObj.put("success","true");
		rootObj.put("hasRestrictedNicks",new Boolean(true));
		errorObj.put("title",_mapping.getTextDescription("admin.error.Manage / Unmanage"));
		if (((Boolean)tmpMap.get("isExternalType")).booleanValue())
		{
			if (compsCount == 1)
			{
				errorObj.put("message1",_mapping.getTextDescription("admin.error.The nick name of the following component has already been assigned to one or more agentless components")+".");
			}else
			{
				errorObj.put("message1",_mapping.getTextDescription("admin.error.The nick names of the following components have already been assigned to one or more agentless components")+".");
			}
		}
		else
		{
			if (compsCount == 1)
			{
				errorObj.put("message1",_mapping.getTextDescription("admin.error.The nick name of the following component has already been assigned to one or more network devices")+".");
			}
			else
			{
				errorObj.put("message1",_mapping.getTextDescription("admin.error.The nick names of the following components have already been assigned to one or more network devices")+".");
			}
		}
		errorObj.put("message2",compsList);
		rootObj.put("errorStack",errorObj);
		if (tmpMap.get("finalServersStr").toString().length() == 0 && unmanagedNickCache.length() == 0)
		{
			rootObj.put("requestStatus","success");
			out.println(rootObj.toString());
			return;
		}
	}

	ArrayList compList = new ArrayList();
	int compListSize = 0;
	JSONArray aListAlreadyExists = new JSONArray();
	IniFile infraIni = null;
	String fmanServ = userTempManageStr;
	String funmanServ = userTempUnManageStr;
	if (fmanServ != null && fmanServ.length()>0)
	{
		String[] manTokens = StringUtils.getTokens(fmanServ, ",");
		if (manTokens.length == 1)
		{
			fmanServ = manTokens[0];
			int indx = fmanServ.lastIndexOf(":");
			if (indx > -1)
			{
				String fmanPort = fmanServ.substring(indx+1);
				if (fmanPort.equalsIgnoreCase("NULL"))
				{
					fmanServ = fmanServ.substring(0,indx);
				}
			}
		}
	}
	if (funmanServ != null && funmanServ.length()>0)
	{
		String[] unManTokens = StringUtils.getTokens(funmanServ, ",");
		if (unManTokens.length == 1)
		{
			funmanServ = unManTokens[0];
			int indx = funmanServ.lastIndexOf(":");
			if (indx > -1)
			{
				String fmanPort = funmanServ.substring(indx+1);
				if (fmanPort.equalsIgnoreCase("NULL"))
				{
					funmanServ = funmanServ.substring(0,indx);
				}
			}
		}
	}
	for (int p=0;p<allServerstoManage.size();p++)
	{
		srvtype = (String)allServerstoManage.get(p);
		if (srvtype == null) continue;
		if (fromValue.equalsIgnoreCase("newServerDiscovery"))
		{
			String[] selectedServers = request.getParameterValues(srvtype);
			if (selectedServers == null || selectedServers.length == 0)
			{
				System.out.println("SelectedServers for "+srvtype +" is Null");
				continue;
			}

			String[] servers = menu.getVariables(srvtype);
			Arrays.sort(servers,String.CASE_INSENSITIVE_ORDER);
			if (doAction != null && doAction.equalsIgnoreCase("unmanage"))
			{
				List UnmanagedList = Arrays.asList(selectedServers);
				serversInfo = Arrays.asList(selectedServers);
				for(int i=0; i<servers.length; i++)
				{
					if(servers[i].startsWith("Format:") || servers[i].startsWith("#New|"))
					{
						continue;
					}
					else if (servers[i].startsWith("#Unmanage|"))
					{
						continue;
					}
					else
					{
						String srv = servers[i].substring(servers[i].indexOf(":")+1);
						if (!UnmanagedList.contains(srv.trim()))
						{
							tmpManServers = tmpManServers + srv + ",";
							String tmp_type = srvtype +":"+ srv;
							tmpManServerswithType = tmpManServerswithType + tmp_type + ",";
						}
					}
				}
				for (int j= 0;j<selectedServers.length;j++)
				{
					tmpUnManServers = tmpUnManServers + selectedServers[j] + ",";
					String tmpType = srvtype +":"+selectedServers[j];
					tmpUnManServerswithType = tmpUnManServerswithType + tmpType + ",";
				}
			}
			else
			{
				List ManagedList = Arrays.asList(selectedServers);
				serversInfo = Arrays.asList(selectedServers);
				for(int i=0; i<servers.length; i++)
				{
					if(servers[i].startsWith("#Unmanage|") || servers[i].startsWith("#New|"))
					{
						String s = servers[i].substring(servers[i].indexOf(":")+1);
						if (!ManagedList.contains(s.trim()))
						{
							tmpUnManServers = tmpUnManServers + s + ",";
							String tmp_type = srvtype +":"+s;
							tmpUnManServerswithType = tmpUnManServerswithType + tmp_type + ",";
						}
						continue;
					}
				}

				for (int j= 0;j<selectedServers.length;j++)
				{
					tmpManServers = tmpManServers + selectedServers[j] + ",";
					String tmpType = srvtype +":"+selectedServers[j];
					tmpManServerswithType = tmpManServerswithType + tmpType + ",";
				}
			}

			if (!tmpManServers.equals(""))
			{
				tmpManServers = tmpManServers.substring(0,tmpManServers.length()-1);
			}
			if (!tmpManServerswithType.equals(""))
			{
				tmpManServerswithType = tmpManServerswithType.substring(0,tmpManServerswithType.length()-1);
			}

			if (!tmpUnManServers.equals(""))
			{
				tmpUnManServers = tmpUnManServers.substring(0,tmpUnManServers.length()-1);
			}
			if (!tmpUnManServerswithType.equals(""))
			{
				tmpUnManServerswithType = tmpUnManServerswithType.substring(0,tmpUnManServerswithType.length()-1);
			}
		}

		String[] comps = discoverInfo.getVariables(srvtype);
		List preManagedList = new ArrayList();
		if (comps != null)
		{
			for (int i=0; i<comps.length; i++)
			{
				String strComp = comps[i];
				if (strComp.startsWith(srvtype+":"))
				{
					strComp = strComp.substring(strComp.indexOf(":")+1);
					strComp = strComp.substring(0,strComp.indexOf(":"));
					preManagedList.add(strComp);
				}
			}
		}
		EgCustomDashboardModel customDashboardModel=new EgCustomDashboardModel();
		/* code for auditlog starts */
		AuditLogThread auditLogThread = new AuditLogThread();
		auditLogThread.setValue("Category","Admin");
		auditLogThread.setValue("User_id",_user.getLoginID());
		auditLogThread.setValue("Host_ip",_user.getUserIP(session.getId()));
		auditLogThread.setValue("Session_id",session.getId());
		auditLogThread.setValue("Module","Component Manage/Unmanage/Delete");
		auditLogThread.setValue("Activity","Manage/Unmanage Components");

		boolean isManaged = false;
		boolean isUnmanaged = false;

		Hashtable nickIPMap = new Hashtable();
		Hashtable hTableAllNicksIp = new Hashtable();

		if (!fromValue.equalsIgnoreCase("newServerDiscovery"))
		{
			tempManage = tmpMap.get("finalServersStr").toString();
		}
		else
		{
			tempManage = tmpManServers;
		}

		if (tempManage == null)
		{
			tempManage = "";
		}
		Vector managedVector = (Vector) session.getAttribute("managed");
		ArrayList mngComp = new ArrayList();
		if (delVCFromVCDisc.equalsIgnoreCase("true") || delVCFromVCDisc.equalsIgnoreCase("Yes"))
		{
			List tempManageList = StringUtils.egTokenizer(tempManage,",");
			if (tempManageList != null && tempManageList.size() > 0)
			{
				for (int m=0;m<tempManageList.size();m++)
				{
					String tmpMngData = (String)tempManageList.get(m);
					String servWithComp = srvtype+":"+tmpMngData;
					if (!managedVector.contains(servWithComp))
					{
						mngComp.add(tmpMngData);
					}
				}
			}
		}
		nickIPMap = egDiscInfo.getNickIpMap();
		hTableAllNicksIp = egDiscInfo.getAllNicksIpMap();
		ArrayList aListNickAlreadyExists = new ArrayList();
		String strAlreadyExists = "";
		StringTokenizer managedTokens = new StringTokenizer(tempManage,",");
		String fmanage = request.getParameter("fmanage");
		StringTokenizer userManagedComp = new StringTokenizer(fmanage,",");
		ArrayList userManagedCompList = new ArrayList();
		while(userManagedComp.hasMoreTokens())
		{
			String tmpComp = userManagedComp.nextToken(); 
			if (!userManagedCompList.contains(tmpComp))
			{
				userManagedCompList.add(tmpComp);
			}
		}
		while(managedTokens.hasMoreTokens())
		{
			String token = (String) managedTokens.nextToken();
			String strNick = token.substring(0,token.indexOf(":"));
			if(!managedVector.contains(srvtype+":"+token))
			{
				if (nickIPMap.containsKey(strNick))
				{
					String managedIP = (String)nickIPMap.get(strNick);
					String manAndUnManIp = (String)hTableAllNicksIp.get(strNick);
					if (manAndUnManIp != null && manAndUnManIp.indexOf(":")>-1)
					{
						StringTokenizer st = new StringTokenizer(manAndUnManIp,":");
						while (st.hasMoreTokens())
						{
							String thisTok = st.nextToken();
							if (thisTok.equals(managedIP))
							{
								String removeNull = "";
								String strForResultsPage = "";
								if (token.indexOf(":NULL")>-1)
								{
									removeNull = token.substring(0,token.indexOf(":NULL"));
									strForResultsPage = removeNull;
								}
								else
								{
									removeNull = token;
									strForResultsPage = token.substring(0,token.indexOf(":"))+"$#"+token.substring(token.indexOf(":")+1);
								}
								if (strAlreadyExists.equals(""))
								{
									strAlreadyExists = strForResultsPage;
								}
								else
								{
									strAlreadyExists = strAlreadyExists+", "+strForResultsPage;
								}
								aListNickAlreadyExists.add(removeNull);
								break;
							}
						}
					}
				}
				if (aListNickAlreadyExists.size()>0)
				{
					continue;
				}
				else
				{
					if(userManagedCompList.contains(token)) //In audit log to display server of corresponding user.
					{
						isManaged = true;
						if(token.endsWith(":NULL"))
						{
							auditLogThread.setCurrentValue("01~~Managed Components",token.substring(0,token.lastIndexOf(":")));
						}
						else
						{
							auditLogThread.setCurrentValue("01~~Managed Components",token);
						}
					}
					//aggregateManagedComponents.add((srvtype + ":" + token));
				}
			}
		}
		boolean isAggregationSupported = EgInstallInfo.isAggregationSupported();
		ArrayList newlyUnmanagedComponents = new ArrayList();
		String tempUnmanage = "";
		if (!fromValue.equalsIgnoreCase("newServerDiscovery"))
		{
			//tempUnmanage = request.getParameter("funmanage");
			tempUnmanage = unmanagedNickCache;
		}
		else
		{
			tempUnmanage = tmpUnManServers;
		}
		if (tempUnmanage == null) tempUnmanage = "";
		Vector unmanagedVector = (Vector) session.getAttribute("unmanaged");
		StringTokenizer unmanagedTokens = new StringTokenizer(tempUnmanage,",");
		EgAggregateInfo aggregateInfo = new EgAggregateInfo("manager");
		Hashtable individualAggreateMap=null;
		if(isAggregationSupported && !srvtype.startsWith("Agg_"))
		{
			individualAggreateMap = new Hashtable();
			while(unmanagedTokens.hasMoreTokens())
			{
				String token = (String) unmanagedTokens.nextToken();
				if(!unmanagedVector.contains(token))
				{
					isUnmanaged = true;
					if(token.endsWith(":NULL"))
					{
						auditLogThread.setCurrentValue("02~~Unmanaged Components",token.substring(0,token.lastIndexOf(":")));
					}
					else
					{
						auditLogThread.setCurrentValue("02~~Unmanaged Components",token);
					}
					String individualComponent = srvtype+":"+token;
					newlyUnmanagedComponents.add(individualComponent);
					List aggComponentList = aggregateInfo.getAssociatedAggList(individualComponent);
					if(aggComponentList !=null && !aggComponentList.isEmpty())
					{
						individualAggreateMap.put(individualComponent,aggComponentList);
					}
				}
			}
		}
		else
		{
			while(unmanagedTokens.hasMoreTokens())
			{
				String token = (String) unmanagedTokens.nextToken();
				if(!unmanagedVector.contains(token))
				{
					isUnmanaged = true;
					if(token.endsWith(":NULL"))
					{
						auditLogThread.setCurrentValue("02~~Unmanaged Components",token.substring(0,token.lastIndexOf(":")));
					}
					else
					{
						auditLogThread.setCurrentValue("02~~Unmanaged Components",token);
					}
				}
			}
		}

		if(isManaged && isUnmanaged)
		{
			auditLogThread.setValue("Activity","Manage/Unmanage Components");
			auditLogThread.setValue("Description","Components of type "+"$ctype$:"+srvtype+" have been managed and unmanaged");
		}
		else if(isUnmanaged)
		{
			auditLogThread.setValue("Activity","Unmanage Components");
			auditLogThread.setValue("Description","Components of type "+"$ctype$:"+srvtype+" have been unmanaged");
		}
		else if(isManaged)
		{
			auditLogThread.setValue("Activity","Manage Components");
			auditLogThread.setValue("Description","Components of type "+"$ctype$:"+srvtype+" have been managed");
		}
		/* code for auditlog ends */

		EgExternalInfo externalInfo = new EgExternalInfo("manager");
		String unmanage = "";
		String manage = "";
		String unmanagewithcomptype = "";
		String managewithcomptype = "";
		String unmantomanlist="";
		
		String strTok = "";
		String val = "";
		String tmpVal = "";
		StringTokenizer st = null;
		boolean removeUnmanage = false;

		String s_res = "";
		Vector v_servers = new Vector();
		Vector v_sites = new Vector();
		List allSegCop = null;

		ArrayList aggregateComponents = null;
		ArrayList unmanagedAggComponents = null;
		//if(EgInstallInfo.isAggregationSupported())
		//{
			//if(newlyUnmanagedComponents.size()>0)
			//{
				//aggregateComponents = aggregateInfo.getAggComponentsForMembers(newlyUnmanagedComponents);
				//if(aggregateComponents != null && !aggregateComponents.isEmpty())
				//{
					//unmanagedAggComponents = new ArrayList();
					//String allow = null;
					//ArrayList display = new ArrayList();
					//ArrayList hide = new ArrayList();
					//for(int i=0;i<aggregateComponents.size();i++)
					//{
						//String comp = (String)aggregateComponents.get(i);
						//if(comp.startsWith("Unmanage|"))
						//{
							//if(allow==null)
							//{
								//allow = "yes";
							//}
							//comp = comp.substring(comp.indexOf("|")+1);
							//unmanagedAggComponents.add(comp);
							//continue;
						//}
						//else
						//{
							//allow = "no";
						//}
						//comp = comp.substring(0,comp.lastIndexOf(":"));
						//String comptype = comp.substring(0,comp.indexOf(":"));
						//comp = comp.substring(comp.indexOf(":")+1);
						//hide.add(comptype+":"+comp+":NULL"); 
						//display.add(_mapping.getComponentTypeDescription(comptype)+":"+comp); 
					//}
					//if(allow != null && allow.equals("no"))
					//{
						//String isAlertRequired = iniui.getValue("MISC_ARGS","AggAlertBeforeDeleteOrUnmanageComp");
						//if(isAlertRequired==null || (isAlertRequired.equalsIgnoreCase("yes") || isAlertRequired.equalsIgnoreCase("true")))
						//{
							//if(display != null && !display.isEmpty())
							//{
								//String new_diplay = "";
								//String tempAggComp = "";
								//for (int j=0;j<display.size();j++)
								//{
									//String a_comp = (String)display.get(j);
									//if(a_comp != null && a_comp.startsWith("Unmanage|"))
									//{
										//a_comp = a_comp.substring(a_comp.indexOf("|")+1);
										//a_comp = a_comp.substring(0,a_comp.lastIndexOf(":"));
										//int a_comp_col = a_comp.indexOf(":");
										//String a_comptype = a_comp.substring(0,a_comp_col);
										//String a_compnick = a_comp.substring(a_comp_col+1);
										//new_diplay = _mapping.getComponentTypeDescription(a_comptype) + ":" + a_compnick;
									//}
									//else
									//{
										//new_diplay = a_comp;
									//}

									//tempAggComp = tempAggComp + "&nbsp;<a class=\"eg_monlink\" href= 'aggNewServer.jsp?reqfrom=comp_mng_umng&activeCompTypes="+activeCompTypes+"&fromWizard="+fromWizard+"&serverGategory=-1&modifyserver=true&comptype="+srvtype+"&qctr=1&isAggregateLink=true&servers="+EgURLEncoder.encode((String)hide.get(j),"UTF-8")+"' style=\"text-decoration:none\">"+new_diplay+"</a>";
									//tempAggComp = tempAggComp + ",";
								//}
								//tempAggComp = tempAggComp.substring(0,tempAggComp.lastIndexOf(","));

								//rootObj.put("success","true");
								//rootObj.put("requestStatus","failed");
								//errorObj.put("title",_mapping.getTextDescription("admin.error.Manage / Unmanage"));
								//if (newlyUnmanagedComponents.size() > 1)
								//{
									//errorObj.put("message1",_mapping.getTextDescription("admin.error.Components cannot be unmanaged or deleted")+".");
									//if (tempAggComp.indexOf(',') > -1)
									//{
										//errorObj.put("message2",_mapping.getTextDescription("admin.error.The selected components are associated to the following aggregate components :")+" "+"<b>"+tempAggComp+"</b>.");
										//errorObj.put("message3",_mapping.getTextDescription("admin.error.The components can be unmanaged or deleted only after disassociating them from the above aggregate components"+"."));
									//}
									//else
									//{
										//errorObj.put("message2",_mapping.getTextDescription("admin.error.The selected components are associated to the following aggregate component :")+" "+"<b>"+tempAggComp+"</b>.");
										//errorObj.put("message3",_mapping.getTextDescription("admin.error.The components can be unmanaged or deleted only after disassociating them from the above aggregate component"+"."));
									//}
								//}
								//else
								//{
									//errorObj.put("message1",_mapping.getTextDescription("admin.error.Component cannot be unmanaged or deleted")+".");
									//if (tempAggComp.indexOf(',') > -1)
									//{
										//errorObj.put("message2",_mapping.getTextDescription("admin.error.The selected component is associated to the following aggregate components :")+" "+"<b>"+tempAggComp+"</b>.");
										//errorObj.put("message3",_mapping.getTextDescription("admin.error.The component can be unmanaged or deleted only after disassociating it from the above aggregate components"+"."));
									//}
									//else
									//{
										//errorObj.put("message2",_mapping.getTextDescription("admin.error.The selected component is associated to the following aggregate component :")+" "+"<b>"+tempAggComp+"</b>.");
										//errorObj.put("message3",_mapping.getTextDescription("admin.error.The component can be unmanaged or deleted only after disassociating it from the above aggregate component"+"."));
									//}
								//}
								//break;
							//}
						//}
					//}
				//}
				//if(aggregateComponents != null && !aggregateComponents.isEmpty())
				//{
					//if(unmanagedAggComponents != null && !unmanagedAggComponents.isEmpty())
					//{
						//aggregateComponents.removeAll(unmanagedAggComponents);
					//}
					//if(!aggregateComponents.isEmpty())
					//{
						//String aggCompType = null;
						//String nickNames = null;
						//int aggCompCount = aggregateComponents.size();
						//for(int i=0;i<aggCompCount;i++)
						//{
							//String aggregateComponent = (String) aggregateComponents.get(i);
							//String typenick = aggregateComponent.substring(0,aggregateComponent.lastIndexOf(":"));
							//int sep = typenick.indexOf(":");
							//String type = typenick.substring(0,sep);
							//String nick = typenick.substring(sep+1);
							//if(aggCompType==null)
							//{
								//aggCompType = type;
								//nickNames = nick;
							//}
							//else if((i+1)==aggCompCount)
							//{
								//nickNames += " and "+nick;
							//}
							//else
							//{
								//nickNames += ","+nick;
							//}
						//}
						//nickNames = nickNames + " of " + _mapping.getComponentTypeDescription(aggCompType);
						//EgGroupInfo groupinfo = new EgGroupInfo();
						//EgTopoInfo egTopoInfo = groupinfo.getTopoInfoObject();//new EgTopoInfo("manager");
						//String zonename[] = null;
						//String groupname = null;
						//String segments[] = null;
						//ArrayList siteList = null;
						//boolean dontProceed=false;
						//for(int i=0;i<aggregateComponents.size();i++)
						//{
							//String aggregateComponent = (String) aggregateComponents.get(i);
							//String thisAggNick = aggregateComponent.substring(aggregateComponent.indexOf(":")+1,aggregateComponent.lastIndexOf(":"));
							//zonename = groupinfo.getZoneNameForComponent(aggregateComponent, true);
							//if(zonename != null && zonename.length>0)
							//{
								//rootObj.put("success","true");
								//rootObj.put("requestStatus","failed");
								//Vector vecaggzone=new Vector();
								//for (int j=0;j<zonename.length;j++)
								//{
									//vecaggzone.add(zonename[j]);
								//}
								//String tempAggZone = "";
								//for (int j=0;j<vecaggzone.size();j++)
								//{
									//tempAggZone = tempAggZone + "&nbsp;<a class=\"eg_monlink\" href= 'EgComponentZones.jsp?comefrom=comp_mng_umng&activeCompTypes="+activeCompTypes+"&comptype="+srvtype+"&fromWizard="+fromWizard+"&qctr=0&mode=modify&zone="+EgURLEncoder.encode((String)vecaggzone.get(j),"UTF-8")+"' style=\"text-decoration:none\">"+(String)vecaggzone.get(j)+"</a>";
									//tempAggZone = tempAggZone + ",";
								//}
								//tempAggZone = tempAggZone.substring(0,tempAggZone.lastIndexOf(","));
								////System.out.println(aggregateComponent + " is associated to zone(s) " + display);
								//errorObj.put("title",_mapping.getTextDescription("admin.error.Manage / Unmanage"));
								//if (newlyUnmanagedComponents.size() > 1)
								//{
									//errorObj.put("message1",_mapping.getTextDescription("admin.error.Components cannot be unmanaged or deleted")+".");
									//if (thisAggNick.indexOf(',') > -1)
									//{
										//errorObj.put("message2",_mapping.getTextDescription("admin.error.The selected components are associated to the following aggregate components :")+" "+"<b>"+nickNames +"</b>. " + thisAggNick + " " +_mapping.getTextDescription("admin.error.aggregate components is associated to zone :")+" "+"<b>"+tempAggZone +"</b>." );
										//errorObj.put("message3",_mapping.getTextDescription("admin.error.The components can be unmanaged or deleted only after disassociating them from the above aggregate components"+"."));
									//}
									//else
									//{
										//errorObj.put("message2",_mapping.getTextDescription("admin.error.The selected components are associated to the following aggregate component :")+" "+"<b>"+nickNames +"</b>. " + thisAggNick + " " +_mapping.getTextDescription("admin.error.aggregate component is associated to zone :")+" "+"<b>"+tempAggZone +"</b>." );
										//errorObj.put("message3",_mapping.getTextDescription("admin.error.The components can be unmanaged or deleted only after disassociating them from the above aggregate component"+"."));
									//}
								//}
								//else
								//{
									//errorObj.put("message1",_mapping.getTextDescription("admin.error.Component cannot be unmanaged or deleted")+".");
									//if (thisAggNick.indexOf(',') > -1)
									//{
										//errorObj.put("message2",_mapping.getTextDescription("admin.error.The selected component is associated to the following aggregate components :")+" "+"<b>"+nickNames +"</b>. " + thisAggNick + " " +_mapping.getTextDescription("admin.error.aggregate components is associated to zone :")+" "+"<b>"+tempAggZone +"</b>." );
										//errorObj.put("message3",_mapping.getTextDescription("admin.error.The component can be unmanaged or deleted only after disassociating it from the above aggregate components"+"."));
									//}
									//else
									//{
										//errorObj.put("message2",_mapping.getTextDescription("admin.error.The selected component is associated to the following aggregate component :")+" "+"<b>"+nickNames +"</b>. " + thisAggNick + " " +_mapping.getTextDescription("admin.error.aggregate component is associated to zone :")+" "+"<b>"+tempAggZone +"</b>." );
										//errorObj.put("message3",_mapping.getTextDescription("admin.error.The component can be unmanaged or deleted only after disassociating it from the above aggregate component"+"."));
									//}
								//}
								//dontProceed=true;
								//break;
							//}
							//groupname = groupinfo.getGroupNameForComponent(aggregateComponent);
							//if(groupname != null && groupname.length()>0)
							//{
								//String tempAggGroup = "";
								//StringTokenizer stag = new StringTokenizer(groupname,",");
								//Vector vecagggroup = new Vector();
								//while (stag.hasMoreTokens())
								//{
									//vecagggroup.add(stag.nextToken());
								//}
								//for (int j=0;j<vecagggroup.size();j++)
								//{
									//tempAggGroup = tempAggGroup + "&nbsp;<a class=\"eg_monlink\" href= 'EgComponentGroups.jsp?comefrom=comp_mng_umng&activeCompTypes="+activeCompTypes+"&comptype="+srvtype+"&fromWizard="+fromWizard+"&qctr=0&mode=modify&group="+EgURLEncoder.encode((String)vecagggroup.get(j),"UTF-8")+"' style=\"text-decoration:none\">"+(String)vecagggroup.get(j)+"</a>";
									//tempAggGroup = tempAggGroup + ",";
								//}
								//tempAggGroup = tempAggGroup.substring(0,tempAggGroup.lastIndexOf(","));
								////System.out.println(aggregateComponent + " is associated to group " + groupname);
								//rootObj.put("success","true");
								//rootObj.put("requestStatus","failed");
								//errorObj.put("title",_mapping.getTextDescription("admin.error.Manage / Unmanage"));
								//if (newlyUnmanagedComponents.size() > 1)
								//{
									//errorObj.put("message1",_mapping.getTextDescription("admin.error.Components cannot be unmanaged or deleted")+".");
									//if (thisAggNick.indexOf(',') > -1)
									//{
										//errorObj.put("message2",_mapping.getTextDescription("admin.error.The selected components are associated to the following aggregate components :")+" "+"<b>"+nickNames +"</b>. " + thisAggNick + " " +_mapping.getTextDescription("admin.error.aggregate components is associated to group :")+" "+"<b>"+tempAggGroup +"</b>." );
										//errorObj.put("message3",_mapping.getTextDescription("admin.error.The components can be unmanaged or deleted only after disassociating them from the above aggregate components"+"."));
									//}
									//else
									//{
										//errorObj.put("message2",_mapping.getTextDescription("admin.error.The selected components are associated to the following aggregate component :")+" "+"<b>"+nickNames +"</b>. " + thisAggNick + " " +_mapping.getTextDescription("admin.error.aggregate component is associated to group :")+" "+"<b>"+tempAggGroup +"</b>." );
										//errorObj.put("message3",_mapping.getTextDescription("admin.error.The components can be unmanaged or deleted only after disassociating them from the above aggregate component"+"."));
									//}
								//}
								//else
								//{
									//errorObj.put("message1",_mapping.getTextDescription("admin.error.Component cannot be unmanaged or deleted")+".");
									//if (thisAggNick.indexOf(',') > -1)
									//{
										//errorObj.put("message2",_mapping.getTextDescription("admin.error.The selected component is associated to the following aggregate components :")+" "+"<b>"+nickNames +"</b>. " + thisAggNick + " " +_mapping.getTextDescription("admin.error.aggregate components is associated to group :")+" "+"<b>"+tempAggGroup +"</b>." );
										//errorObj.put("message3",_mapping.getTextDescription("admin.error.The component can be unmanaged or deleted only after disassociating it from the above aggregate components"+"."));
									//}
									//else
									//{
										//errorObj.put("message2",_mapping.getTextDescription("admin.error.The selected component is associated to the following aggregate component :")+" "+"<b>"+nickNames +"</b>. " + thisAggNick + " " +_mapping.getTextDescription("admin.error.aggregate component is associated to group :")+" "+"<b>"+tempAggGroup +"</b>." );
										//errorObj.put("message3",_mapping.getTextDescription("admin.error.The component can be unmanaged or deleted only after disassociating it from the above aggregate component"+"."));
									//}
								//}
								//dontProceed=true;
								//break;
							//}
							//siteList = egTopoInfo.getSitesForComponent(aggregateComponent);
							//if(siteList != null && !siteList.isEmpty())
							//{
								//rootObj.put("success","true");
								//rootObj.put("requestStatus","failed");
								//String tempAggSer = "";
								//for (int j=0;j<siteList.size();j++)
								//{
									//tempAggSer = tempAggSer + "&nbsp;<a class=\"eg_monlink\" href= 'EgComponentGroups.jsp?comefrom=comp_mng_umng&activeCompTypes="+activeCompTypes+"&comptype="+srvtype+"&fromWizard="+fromWizard+"&qctr=0&mode=modify&group="+EgURLEncoder.encode((String)siteList.get(j),"UTF-8")+"' style=\"text-decoration:none\">"+(String)siteList.get(j)+"</a>";
									//tempAggSer = tempAggSer + ",";
								//}
								//tempAggSer = tempAggSer.substring(0,tempAggSer.lastIndexOf(","));
								////System.out.println(aggregateComponent + " is associated to site(s)/service(s) " + display);
								//errorObj.put("title",_mapping.getTextDescription("admin.error.Manage / Unmanage"));
								//if (newlyUnmanagedComponents.size() > 1)
								//{
									//errorObj.put("message1",_mapping.getTextDescription("admin.error.Components cannot be unmanaged or deleted")+".");
									//if (thisAggNick.indexOf(',') > -1)
									//{
										//errorObj.put("message2",_mapping.getTextDescription("admin.error.The selected components are associated to the following aggregate components :")+" "+"<b>"+nickNames +"</b>. " + thisAggNick + " " +_mapping.getTextDescription("admin.error.aggregate components is associated to service :")+" "+"<b>"+tempAggSer +"</b>." );
										//errorObj.put("message3",_mapping.getTextDescription("admin.error.The components can be unmanaged or deleted only after disassociating them from the above aggregate components"+"."));
									//}
									//else
									//{
										//errorObj.put("message2",_mapping.getTextDescription("admin.error.The selected components are associated to the following aggregate component :")+" "+"<b>"+nickNames +"</b>. " + thisAggNick + " " +_mapping.getTextDescription("admin.error.aggregate component is associated to service :")+" "+"<b>"+tempAggSer +"</b>." );
										//errorObj.put("message3",_mapping.getTextDescription("admin.error.The components can be unmanaged or deleted only after disassociating them from the above aggregate component"+"."));
									//}
								//}
								//else
								//{
									//errorObj.put("message1",_mapping.getTextDescription("admin.error.Component cannot be unmanaged or deleted")+".");
									//if (thisAggNick.indexOf(',') > -1)
									//{
										//errorObj.put("message2",_mapping.getTextDescription("admin.error.The selected component is associated to the following aggregate components :")+" "+"<b>"+nickNames +"</b>. " + thisAggNick + " " +_mapping.getTextDescription("admin.error.aggregate components is associated to service :")+" "+"<b>"+tempAggSer +"</b>." );
										//errorObj.put("message3",_mapping.getTextDescription("admin.error.The component can be unmanaged or deleted only after disassociating it from the above aggregate components"+"."));
									//}
									//else
									//{
										//errorObj.put("message2",_mapping.getTextDescription("admin.error.The selected component is associated to the following aggregate component :")+" "+"<b>"+nickNames +"</b>. " + thisAggNick + " " +_mapping.getTextDescription("admin.error.aggregate component is associated to service :")+" "+"<b>"+tempAggSer +"</b>." );
										//errorObj.put("message3",_mapping.getTextDescription("admin.error.The component can be unmanaged or deleted only after disassociating it from the above aggregate component"+"."));
									//}
								//}
								//dontProceed=true;
								//break;
							//}
							//segments = egTopoInfo.getSegmentsForComponent(aggregateComponent);
							//if(segments != null && segments.length>0 && !segments[0].equalsIgnoreCase("NULL"))
							//{
								//Vector vecaggseg=new Vector();
								//for (int j=0;j<segments.length;j++)
								//{
									//vecaggseg.add(segments[j]);
								//}
								//String tempAggSeg = "";
								//for (int j=0;j<vecaggseg.size();j++)
								//{
									//tempAggSeg = tempAggSeg + "&nbsp;<a class=\"eg_monlink\" href= 'EgComponentSegments.jsp?returnTo=comp_mng_umng&activeCompTypes="+activeCompTypes+"&comptype="+srvtype+"&fromWizard="+fromWizard+"&qctr=0&mode=modify&segment="+EgURLEncoder.encode((String)vecaggseg.get(j),"UTF-8")+"' style=\"text-decoration:none\">"+(String)vecaggseg.get(j)+"</a>";
									//tempAggSeg = tempAggSeg + ",";
								//}
								//tempAggSeg = tempAggSeg.substring(0,tempAggSeg.lastIndexOf(","));
								//rootObj.put("success","true");
								//rootObj.put("requestStatus","failed");
								//errorObj.put("title",_mapping.getTextDescription("admin.error.Manage / Unmanage"));
								//if (newlyUnmanagedComponents.size() > 1)
								//{
									//errorObj.put("message1",_mapping.getTextDescription("admin.error.Components cannot be unmanaged or deleted")+".");
									//if (thisAggNick.indexOf(',') > -1)
									//{
										//errorObj.put("message2",_mapping.getTextDescription("admin.error.The selected components are associated to the following aggregate components :")+" "+"<b>"+nickNames +"</b>. " + thisAggNick + " " +_mapping.getTextDescription("admin.error.aggregate components is associated to segment :")+" "+"<b>"+tempAggSeg+"</b>." );
										//errorObj.put("message3",_mapping.getTextDescription("admin.error.The components can be unmanaged or deleted only after disassociating them from the above aggregate components"+"."));
									//}
									//else
									//{
										//errorObj.put("message2",_mapping.getTextDescription("admin.error.The selected components are associated to the following aggregate component :")+" "+"<b>"+nickNames +"</b>. " + thisAggNick + " " +_mapping.getTextDescription("admin.error.aggregate component is associated to segment :")+" "+"<b>"+tempAggSeg+"</b>." );
										//errorObj.put("message3",_mapping.getTextDescription("admin.error.The components can be unmanaged or deleted only after disassociating them from the above aggregate component"+"."));
									//}
								//}
								//else
								//{
									//errorObj.put("message1",_mapping.getTextDescription("admin.error.Component cannot be unmanaged or deleted")+".");
									//if (thisAggNick.indexOf(',') > -1)
									//{
										//errorObj.put("message2",_mapping.getTextDescription("admin.error.The selected component is associated to the following aggregate components :")+" "+"<b>"+nickNames +"</b>. " + thisAggNick + " " +_mapping.getTextDescription("admin.error.aggregate components is associated to segment :")+" "+"<b>"+tempAggSeg+"</b>." );
										//errorObj.put("message3",_mapping.getTextDescription("admin.error.The component can be unmanaged or deleted only after disassociating it from the above aggregate components"+"."));
									//}
									//else
									//{
										//errorObj.put("message2",_mapping.getTextDescription("admin.error.The selected component is associated to the following aggregate component :")+" "+"<b>"+nickNames +"</b>. " + thisAggNick + " " +_mapping.getTextDescription("admin.error.aggregate component is associated to segment :")+" "+"<b>"+tempAggSeg+"</b>." );
										//errorObj.put("message3",_mapping.getTextDescription("admin.error.The component can be unmanaged or deleted only after disassociating it from the above aggregate component"+"."));
									//}
								//}
								//dontProceed=true;
								//break;
							//}
						//}
						//if(dontProceed)
						//{
							////Aggregate component is associated with some elements(zone/service/segment/group). Don't unmanaged these individual components until they are disassociated from aggregate components.
							//break;
						//}
					//}
				//}
			//}
			////String server_type = request.getParameter("srvtype");
			//String server_type = srvtype;
			//if(aggregateInfo.getAggregateTypes().contains(server_type))
			//{
				////............................. For Aggrgate Site Servers (Begin) .......................
				//EgDiscInfo discInfo = new EgDiscInfo("manager");
				//EgTopoInfo topoinfo = new EgTopoInfo("manager");	
				//ArrayList siteServers = discInfo.getSiteServers();
				//if(siteServers.contains(server_type))
				//{
					//unmantomanlist = request.getParameter("unmantomanlist");
					//if (unmantomanlist == null)
					//{
						//unmantomanlist = "";
					//}
					//if(unmantomanlist!=null && unmantomanlist.length()>0)
					//{
						//IniFile aggregateInfoSync = EgConfigFilesSync.getInstance(EgInstallInfo.getInstallDir()+"/manager/config/eg_aggregate.ini",true);
						//ArrayList unManComp = StringUtils.egTokenizer(unmantomanlist,",");
						//for(int j=0;j<unManComp.size();j++)
						//{
							//String tokenList = (String)unManComp.get(j);
							//String tmpStr = server_type+":"+tokenList+":NULL";
							//if(aggregateInfo.isAggregateSiteSupported(tmpStr))
							//{
								//ArrayList list = aggregateInfo.getAllUnmanagedAggregateComponents(tmpStr);
								//for(int k=0;k<list.size();k++)
								//{
									//String tmp = (String) list.get(k);
									//ArrayList al = topoinfo.getSitesForComponent(tmp);
									//if(al.size()==0)
										//aggregateInfoSync.setValue("SITE_SUPPORT",tmpStr,"no");
								//}
							//}
						//}
						//aggregateInfoSync.saveFile();
						//EgConfigFilesSync.releaseInstance(aggregateInfoSync);
					//}
				//}
				////............................. For Aggrgate Site Servers (End) .......................
			//}
		//}
		/* For aggregate test frequency setting ends */

		//Variables for license check
		Vector err_msg = new Vector();
		Vector oldManServers = new Vector();
		Vector newManServers = new Vector();
		Vector oldUnmanServers = new Vector();
		Vector newDiscServers = new Vector();
		Vector newUnmanServers = new Vector();
		Vector updateManServers = new Vector();
		Vector finalServers = new Vector();
		Vector tmpServers = new Vector();
		Vector updateServers = new Vector();
		ArrayList al = new ArrayList();
		boolean update = false;
		boolean callBasicErrorPage = false;
		Vector finalSvrs = new Vector();
		int status = 0;
		UpdateAndTransmitUserInfo userinfo = new UpdateAndTransmitUserInfo();

		//unmanage = request.getParameter("funmanage");
		//manage = request.getParameter("fmanage");
		if (isThruSearch)
		{
			manage = tempManage;
		}
		//unmanagewithcomptype = request.getParameter("funmanagewithcomptype");
		//managewithcomptype = request.getParameter("fmanagewithcomptype");

		if (!fromValue.equalsIgnoreCase("newServerDiscovery"))
		{
			//unmanage = request.getParameter("funmanage");
			unmanage = unmanagedNickCache;
		}
		else
		{
			unmanage = tmpUnManServers;
		}

		if (unmanage == null)
		{
			unmanage = "";
		}

		if (!fromValue.equalsIgnoreCase("newServerDiscovery"))
		{
			manage = tmpMap.get("finalServersStr").toString();
		}
		else
		{
			manage = tmpManServers;
		}
		if (!fromValue.equalsIgnoreCase("newServerDiscovery"))
		{
			unmanagewithcomptype = request.getParameter("funmanagewithcomptype");
		}
		else
		{
			unmanagewithcomptype = tmpUnManServerswithType;
		}
		if (unmanagewithcomptype == null)
		{
			unmanagewithcomptype = "";
		}

		if (!fromValue.equalsIgnoreCase("newServerDiscovery"))
		{
			managewithcomptype = request.getParameter("fmanagewithcomptype");
		}
		else
		{
			managewithcomptype = tmpManServerswithType;
		}

		List managedCompsExist = new ArrayList();
		List managedCompsNew = new ArrayList();
		if (managedComps!=null)
		{
			for (int m=0; m<managedComps.length; m++)
			{
				String comp =managedComps[m];
				int idx = comp.indexOf(":");
				if (idx > -1)
				{
					comp = comp.substring(idx+1);
				}
				managedCompsExist.add(comp);
			}
		}
		StringTokenizer  strTozr = new StringTokenizer(manage,",");
		while (strTozr.hasMoreTokens())
		{
			String token = strTozr.nextToken();
			managedCompsNew.add(token);
		}
		managedCompsNew.removeAll(managedCompsExist);

		// To remove the External URLs configured for the unmanaged and deleted servers.
		if(v_servers!=null && !v_servers.isEmpty())
		{
			for(int i=0;i<v_servers.size();i++)
			{
				String unmanageSerevrName = (String)v_servers.get(i);
				String unmanageHostName = "";
				if(unmanageSerevrName.indexOf(":")>0)
				{
					unmanageHostName = unmanageSerevrName.substring(unmanageSerevrName.indexOf(":")+1,unmanageSerevrName.length());
				}
				IniFile eg_externalURL = new IniFile(EgInstallInfo.getInstallDir() + "/manager/config/eg_externalURL.ini",true);
				if(unmanageSerevrName!=null && unmanageSerevrName.length()>0 && unmanageHostName!=null && unmanageHostName.length()>0)
				{
					String serverTypeForTool = "";
					serverTypeForTool = unmanagewithcomptype.substring(0,unmanagewithcomptype.indexOf(":"));
					String toolForServer=eg_externalURL.getValue("MONITORING TOOLS",unmanageSerevrName);
					if(toolForServer==null || toolForServer.equals(""))
						continue;
					StringTokenizer toolToken = new StringTokenizer(toolForServer,",");
					int countTokens = toolToken.countTokens();
					while(toolToken.hasMoreTokens())
					{
						String tokenString = toolToken.nextToken();
						if(tokenString!=null && tokenString.length()>0)
						{
							eg_externalURL.deleteValue(serverTypeForTool,unmanageHostName+":"+tokenString);
						}
					}
					if(toolForServer!=null && toolForServer.length()>0)
					{
						eg_externalURL.deleteValue("MONITORING TOOLS",unmanageSerevrName);
					}
					eg_externalURL.saveFile(true);
				}
			}
		}
		/****************************************ZONE,SERVICE,SEGMENT,GROUP STARTS******************************************/
		boolean allow = false;
		isProceed = request.getParameter("isProceed");
		String[] tokens = StringUtils.getTokens(unmanagewithcomptype, ",");
		compList.addAll(Arrays.asList(tokens));
		compList.removeAll(prevUnmngCmpWithTypes);
		compListSize = compList.size();
		EntityHelper helper = new EntityHelper(compList);
		helper.setRequestFrom("manageunmanage");
		if (isProceed == null || isProceed.length() == 0)
		{
			String strDisplay = "";
			String msg1 = "";
			String msg2 = "";
			Hashtable resultTable = helper.getCompAssociatedEntities();
			Set zoneList = (HashSet)resultTable.get("zone");
			Set grpList = (HashSet)resultTable.get("group");
			Set segList = (HashSet)resultTable.get("segment");
			Set servList = (HashSet)resultTable.get("service");
			Set mgdAggList = (HashSet)resultTable.get("ManagedAggregate");
			Set unmgdAggList = (HashSet)resultTable.get("UnmanagedAggregate");

			if (zoneList != null)
			{
				int zoneSize = zoneList.size();
				if (zoneSize > 0)
				{
					String key = (zoneSize > 1) ? "Zones" : "Zone";
					strDisplay += key + ", ";
				}
			}
			if (grpList != null)
			{
				int grpSize = grpList.size();
				if (grpSize > 0)
				{
					String key = (grpSize > 1) ? "Groups" : "Group";
					strDisplay += key + ", ";
				}
			}
			if (segList != null)
			{
				int segSize = segList.size();
				if (segSize > 0)
				{
					String key = (segSize > 1) ? "Segments" : "Segment";
					strDisplay += key + ", ";
				}
			}
			if (servList != null)
			{
				int servSize = servList.size();
				if (servSize > 0)
				{
					String key = (servSize > 1) ? "Services" : "Service";
					strDisplay += key + ", ";
				}
			}
			if (mgdAggList != null || unmgdAggList != null)
			{
				int maggSize = mgdAggList.size();
				int uaggSize = unmgdAggList.size();
				if (maggSize > 0 || uaggSize > 0)
				{
					String key = (maggSize > 1 || uaggSize > 1) ? "Aggregates" : "Aggregate";
					strDisplay += key + ", ";
				}
			}
			strDisplay = (strDisplay.length()>0) ? strDisplay.substring(0, strDisplay.lastIndexOf(",")) : strDisplay; 
			String entities = (strDisplay.indexOf(",") > -1) ? "entities" : "entity";

			if (compListSize > 1 || currUnMgdCompList.size() > 1)
			{
				msg1 = _mapping.getTextDescription("admin.error.The chosen components are associated to") +" : "
						+ strDisplay + ".&nbsp;<span style='cursor:pointer;align:left;' onclick=\"javascript:appCtn.viewAssociatedEntities('unmanage')\">"+_mapping.getTextDescription("admin.filter.Click here")+"&nbsp;<img src='/final/images/spacer.gif' style='cursor:hand;vertical-align:text-bottom;' class='iconClickHere' />&nbsp;</span><span>"+_mapping.getTextDescription("admin.error.to know more about the entities that will be affected")+".</span><br/><br/>";
				msg2 = _mapping.getTextDescription("admin.error.Would you still like to unmanage the chosen components")+"?";
			}
			else
			{
				String msgStr = _mapping.getTextDescription("admin.error.The component")+"&nbsp;'"+funmanServ+"'&nbsp;"+_mapping.getTextDescription("admin.error.is associated to");
				msg1 = msgStr+": "+strDisplay +".&nbsp;";
				msg1 = msg1 + "<span style='cursor:pointer;align:left;' onclick=\"javascript:appCtn.viewAssociatedEntities('unmanage')\">" + _mapping.getTextDescription("admin.filter.Click here")+"&nbsp;<img src='/final/images/spacer.gif' style='cursor:hand;vertical-align:text-bottom;' class='iconClickHere'/></span>";
				msg1 = msg1 + "<span>&nbsp;" + _mapping.getTextDescription("admin.error.to know more about the entities that will be affected")+".</span><br/><br/>";

				msg2 = _mapping.getTextDescription("admin.error.Would you still like to unmanage the component")+"&nbsp;'"+funmanServ+"'?";
			}
			errorObj.put("title",_mapping.getTextDescription("admin.server.Manage/Unmanage components"));
			errorObj.put("message1",msg1);
			errorObj.put("message2",msg2);
			allow = (strDisplay.length()>0);
			errorObj.put("allow",allow);
		}
		/****************************************ZONE,SERVICE,SEGMENT,GROUP ENDS******************************************/

		if (allow)
		{
			rootObj.put("success","true");
			rootObj.put("requestStatus","failed");
			break;
		}
		else
		{
			//The following line is to ensure that the stopDiscovery & startDiscovery runs inside a sync block
			infraIni = EgConfigFilesSync.getInstance(EgInstallInfo.getInstallDir() + "/manager/config/eg_infrastructure.ini");
			servicer.stopDiscovery();
			oldManServers.clear();
			oldUnmanServers.clear();
			newManServers.clear();
			newUnmanServers.clear();
			newDiscServers.clear();
			EgGroupInfo groupinfo = new EgGroupInfo();
			EgTopoInfo egTopoInfo = groupinfo.getTopoInfoObject();//new EgTopoInfo("manager");
			System.out.println("groupinfo zone object :: "+groupinfo.getZoneNameForComponent(unmanagewithcomptype));

			//To populate newManServers
			st = new StringTokenizer(manage,",");
			Vector v_managedserver=new Vector();
			while(st.hasMoreTokens())
			{
				strTok = st.nextToken().trim();
				if (!aListNickAlreadyExists.contains(strTok))
				{
					updateManServers.add(strTok);
					updateManServers.add(strTok);
					if(!newManServers.contains(strTok))
						newManServers.add(strTok);
					if (!v_managedserver.contains(strTok))
					{
						v_managedserver.add(strTok);
					}
				}
			}

			for(int i=0; i<newManServers.size(); i++)
			{
				strTok = (String)newManServers.get(i);
				if(!finalSvrs.contains(strTok))
					finalSvrs.add(strTok);

				strTok = strTok.substring(0,strTok.indexOf(":"));
				if(!finalServers.contains(strTok))
					finalServers.add(strTok);
			}

			//Basic Agent Check
			// new to put the new code for eg_external.ini
			String type1 = servicer.getAlOption();
			boolean flag11 = false;
			if(type1 == null)
				flag11 = false;
			else if(type1.equalsIgnoreCase("yes"))
				flag11 = true;
			else
				flag11 = false;

			boolean userLicExceeded = false;
			status = user.checkBasicAgentCount(srvtype,finalSvrs,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)
				{
					callBasicErrorPage = true;
					userLicExceeded = true;
				}
			}

			if(flag11) // default is agentless
			{
				EgSpecsInfo specsinfo1 = new EgSpecsInfo("manager");
				boolean flag12=false;
				if(srvtype != null) 
					flag12 = specsinfo1.isAgentlessServer(srvtype);
				if (flag12 && agentlessInfoList.contains(srvtype) && !userLicExceeded)
				{
					if (user.checkAlServers (srvtype,finalServers, finalSvrs))
					{
						EgConfigTopo1.createFile("eg_external.ini");
						String defaultRemoteAgent[] = EgConfigTopo1.getVariables("Eg_Remote_Agents");
						ArrayList extEntries = new ArrayList();
						if(defaultRemoteAgent != null && defaultRemoteAgent.length > 0)
						{
							IniFile extIni = new IniFile(EgConfigInfo.egMgrConfigDir + "eg_external.ini");
							for(int kk =0;kk<finalServers.size();kk++)
							{
								String value = (String)finalServers.get(kk);
								if (preManagedList.contains(value))
								{
									continue;
								}

								String temp12 = EgConfigTopo1.getValues("Remote_Agent_Mapping_Section", value);
								if (StringUtils.isNull(temp12))
								{
									if (isLimitedAdmin)
									{
										String user_id = _user.getLoginID();
										ArrayList usersRemAgents = userElemInfo.getRemoteAgentsForUser(user_id);
										if(usersRemAgents != null && usersRemAgents.size()>0)
										{
											temp12 = usersRemAgents.get(0).toString();
										}
										else
										{
											temp12 = defaultRemoteAgent[0];
										}
									}
									else
									{
										temp12 = defaultRemoteAgent[0];
									}
								}
								//EgConfigTopo1.setValues("Remote_Agent_Mapping_Section", value, temp12);
								extEntries.add(new IniHelper("Remote_Agent_Mapping_Section", value, temp12));
								String alTokens = EgConfigTopo1.getValues("Agentless_Infos_Section", value);
								String pwd="NONE";
								String useral="None";
								String modeal="None";
								String osal = "None";
								String sshport = "22";
								String authType = "None";
								String keyFile ="None";

								//if (agentlessInfoList.contains(srvtype))// Only the server type exist under 'DEFAULT_AGENTLESS_SETTINGS'
								//{
									String strVal = serviceInfo.getValue("DEFAULT_AGENTLESS_SETTINGS",srvtype);
									strVal = (strVal!=null)?strVal:"";
									StringTokenizer stt = new StringTokenizer(strVal,",");
									if(stt.countTokens()>=4)
									{
										useral = stt.nextToken();
										pwd = stt.nextToken();
										osal = stt.nextToken();
										modeal = stt.nextToken();
										if(stt.hasMoreTokens())
										{
											authType = stt.nextToken();
											//keyFile = stt.nextToken();
										}
										if(stt.hasMoreTokens())
										{
											keyFile = stt.nextToken();
										}
									}
								//}

								if(alTokens == null || alTokens.length() == 0)
								{
									pwd = EgCrypt.decrypt(pwd);
									pwd = EgCrypt.encrypt(pwd);
								}
								else
								{
									StringTokenizer st1 = new StringTokenizer(alTokens,",");
									useral = (String)st1.nextToken();
									pwd = (String)st1.nextToken();
									modeal = (String)st1.nextToken();
									osal = (String)st1.nextToken();
									if(st1.hasMoreTokens())
										sshport = (String)st1.nextToken();
									else
										sshport ="";
									if(st1.hasMoreTokens())
										authType =(String)st1.nextToken();
									if(st1.hasMoreTokens())
										keyFile = (String)st1.nextToken();
									pwd = EgCrypt.decrypt(pwd);
									pwd = EgCrypt.encrypt(pwd);
								}
								if(sshport != null && !sshport.equals(""))
								{
									//EgConfigTopo1.setValues("Agentless_Infos_Section", value, useral+","+pwd+","+modeal+","+osal+","+sshport);
									extEntries.add(new IniHelper("Agentless_Infos_Section", value, useral+","+pwd+","+modeal+","+osal+","+sshport+","+authType+","+keyFile));
								}
								else
								{
									//EgConfigTopo1.setValues("Agentless_Infos_Section", value, useral+","+pwd+","+modeal+","+osal);
									extEntries.add(new IniHelper("Agentless_Infos_Section", value, useral+","+pwd+","+modeal+","+osal));
								}
							}
						}

						if (extEntries.size() > 0)
						{
							IniFile discWr = EgConfigFilesSync.getInstance(eGInstallDir + "/manager/config/eg_external.ini");
							for(int e=0; e < extEntries.size(); e++)
							{
								IniHelper iniHelr = (IniHelper) extEntries.get(e);
								String sub = iniHelr.getSubject();
								String key = iniHelr.getVariable();
								String value = iniHelr.getValue();
								discWr.setValue(sub,key,value);
							}
							discWr.saveFile();
							EgConfigFilesSync.releaseInstance(discWr);
						}
						//EgConfigTopo1.saveFile();
					}
					else
					{
						status = 6;
						callBasicErrorPage = true;
						rootObj.put("success","true");
						rootObj.put("requestStatus","failed");
						errorObj.put("title",_mapping.getTextDescription("admin.error.Manage/Unmanage Components"));
						/* code for auditlog starts */
						if (compList.size() > 1)
						{
							auditLogThread.setCurrentValue("ColumnName", "Components chosen for manage/unmanage/delete");
						}
						else
						{
							auditLogThread.setCurrentValue("ColumnName", "Component chosen for manage/unmanage/delete");
						}
						if (usersInfo.isUserBasedLicense())
						{
							if (isNamedUsersCert)
							{
								auditLogThread.setValue("Description","You are exceeding the total number of agentless components or named users permitted by your license");
								errorObj.put("message1",_mapping.getTextDescription("admin.error.You are exceeding the total number of agentless components or named users permitted by your license")+".");
							}
							else
							{
								auditLogThread.setValue("Description","You are exceeding the total number of agentless components or concurrent users permitted by your license");
								errorObj.put("message1",_mapping.getTextDescription("admin.error.You are exceeding the total number of agentless components or concurrent users permitted by your license")+".");
							}
							
							errorObj.put("message2",_mapping.getTextDescription("admin.discovery.To upgrade your license to support additional agentless components")+", "+_mapping.getTextDescription("admin.error.please contact")+" <b>license@eginnovations.com</b>");
						}
						else
						{
							auditLogThread.setValue("Description","You are exceeding the total number of agentless components permitted by your license");
							errorObj.put("message2",_mapping.getTextDescription("admin.error.You are exceeding the total number of agentless components permitted by your license")+".");
							errorObj.put("message2",_mapping.getTextDescription("admin.discovery.To upgrade your license to support additional agentless components")+", "+_mapping.getTextDescription("admin.error.please contact")+" <b>license@eginnovations.com</b>");
						}					
						auditLogThread.sendItToDB();
						/* code for auditlog ends */
						break;
					}
				}
			}
			ArrayList threshList = new ArrayList();
			if (!callBasicErrorPage)
			{
					//status = user.checkBasicAgentCount(srvtype,finalSvrs,1,"","","","");
					//if(status == 1)
						//update = true;
					//else if(status == 2 || status == 3 || status == 4 || status == 5 || status == 6)
						//callBasicErrorPage = true;

				//manager.createFile("eg_discover.ini","save");
				//To unmange
				String[] vars_agg = aggregateInfo.getVariables(EgAggregateInfo.aggComponent);
				IniFile aggregateInfoSync = EgConfigFilesSync.getInstance(EgInstallInfo.getInstallDir()+"/manager/config/eg_aggregate.ini",true);
				st = new StringTokenizer(unmanage,",");
				oldUnmanServers = (Vector)session.getValue("unmanaged");
				while (st.hasMoreTokens())
				{
					String s = st.nextToken();
					if (oldUnmanServers != null &&
						!oldUnmanServers.contains(s))
					{
						newUnmanServers.add(s);
						if(srvtype != null && s != null && srvtype.startsWith("Agg_"))
						{
							//aggregateInfo.unmanageAggregateComponent(srvtype+":"+s);//changed now
							String compName = srvtype+":"+s;
							int index = compName.indexOf(":");
							if(index > 0 && compName.lastIndexOf(":") > index)
							{
								for(int k=0;k<vars_agg.length;k++)
								{
									String variable=vars_agg[k];
									String aggComp="";
									int ind = variable.indexOf("#");
									if (ind>0)
									{
										aggComp=variable.substring(0,ind);
										if(compName.equals(aggComp))
										{
											String unmngVar="#Unmanage|"+variable;
											aggregateInfoSync.setValue(EgAggregateInfo.aggComponent,unmngVar,"associated");
											aggregateInfoSync.deleteValue(EgAggregateInfo.aggComponent,variable);
											aggregateInfoSync.deleteValue(EgAggregateInfo.compAssociation,compName);
										}
									}
								}
							}
						}
					}
				}
				aggregateInfoSync.saveFile();
				EgConfigFilesSync.releaseInstance(aggregateInfoSync);
				newDiscServers = (Vector)session.getValue("newDiscSrvrs");
				st = new StringTokenizer(manage,",");
				while (st.hasMoreTokens())
				{
					String s = st.nextToken();
					if(newDiscServers != null && newDiscServers.contains(s))
					{
						newDiscServers.remove(s);
					}
				}
				if(newDiscServers != null && newDiscServers.size() > 0)
				{
					for(int u=0;u<newDiscServers.size();u++)
					{
						String newUnmanageComp=(String)newDiscServers.get(u);
						if(newUnmanServers != null && !newUnmanServers.contains(newUnmanageComp))
						{
							newUnmanServers.add(newUnmanageComp);
						}
					}
				}
				//EgConfigTopo1.createFile("eg_external.ini", "true");
				IniFile externalWr = EgConfigFilesSync.getInstance(eGInstallDir+"/manager/config/eg_external.ini");
				IniFile virCompWr = EgConfigFilesSync.getInstance(eGInstallDir+"/manager/config/eg_virtualcomponents.ini");
				String [] vmvars = externalWr.getVariables("VIRTUAL_MAPPING");
				boolean fileSave = false;

				//vmware starts
				for(int co=0;co<newUnmanServers.size();co++)
				{
					String serverName = (String)newUnmanServers.get(co);
					serverName = srvtype+":"+serverName;

					for (int v=0; v<vmvars.length; v++)
					{
						String thisVar = vmvars[v];
						String vmval = externalWr.getValue("VIRTUAL_MAPPING", thisVar);
						if (vmval==null)
							continue;
						if (vmval.equals(serverName))
						{
							externalWr.deleteValue("VIRTUAL_MAPPING", thisVar);
							fileSave = true;
						}
					}
					externalWr.deleteValue("VIRTUAL_MAPPING", serverName);

					//Alagu added for vmware
					Vector virtualserver =new Vector();
					String esxServerHost[] =externalInfo.getVirtualServerHosts();
					if (esxServerHost!=null && esxServerHost.length>0)
					{
						virtualserver.addAll(Arrays.asList(esxServerHost));
					}
					for (int m=0;m<virtualserver.size();m++)
					{
						String virtserver=(String)virtualserver.get(m);
						if (serverName.equals(virtserver))
						{
							Vector v_virtualcomps=externalInfo.getvmWareComponents(virtserver);
							for (int a=0;a<v_virtualcomps.size();a++)
							{
								String thisVar = (String)v_virtualcomps.get(a);
								virCompWr.deleteValue("Virtual_Components", thisVar);
								fileSave = true;
							}
						}
					}

					virCompWr.deleteValue("Virtual_Components", serverName);
					//Vector v_virtualServers =externalInfo.getvmWareHosts();
					String [] v_virtualServers = externalWr.getVariables("Virtual_Hosts");
					if (v_virtualServers!=null && v_virtualServers.length>0)
					{
						for (int m=0;m<v_virtualServers.length;m++)
						{
							if (serverName.equals(v_virtualServers[m]))
							{
								externalWr.deleteValue("Virtual_Hosts", v_virtualServers[m]);
								fileSave = true;
							}
						}
					}
					//Alagu ends
					//vmware ends
					//Added by karthika -for cloud
					Vector cloudserver =new Vector();
					String cloudServerHost[] =externalInfo.getCloudServerHosts();
					if (cloudServerHost!=null && cloudServerHost.length>0)
					{
						cloudserver.addAll(Arrays.asList(cloudServerHost));
					}
					for (int mn=0;mn<cloudserver.size();mn++)
					{
						String cldserver=(String)cloudserver.get(mn);
						if (serverName.equals(cldserver))
						{
							Vector v_cloudcomps=externalInfo.getCloudComponents(cldserver);
							for (int a=0;a<v_cloudcomps.size();a++)
							{
								String thisVar = (String)v_cloudcomps.get(a);
								externalWr.deleteValue("Cloud_Components", thisVar);
								fileSave = true;
							}
						}
					}

					String [] v_cloudServers = externalWr.getVariables("Cloud_Hosts");
					if (v_cloudServers!=null && v_cloudServers.length>0)
					{
						for (int m=0;m<v_cloudServers.length;m++)
						{
							if (serverName.equals(v_cloudServers[m]))
							{
								externalWr.deleteValue("Cloud_Hosts", v_cloudServers[m]);
								fileSave = true;
							}
						}
					}
					//cloud ends

					//added by karthika for vmware
					EgconfTopo1forVm.createSyncFile("eg_vm.ini","save"); 
					String []vmGuestComp = EgconfTopo1forVm.getVariables("Vm_Os");
					boolean updated = false;
					if (vmGuestComp!=null && vmGuestComp.length>0)
					{
						for (int jk=0; jk<vmGuestComp.length; jk++)
						{
							if (vmGuestComp[jk].startsWith(serverName))
							{
								EgconfTopo1forVm.deleteSpecValue("Vm_Os",vmGuestComp[jk]);
								updated = true;
							}
						}
						if (updated)
							EgconfTopo1forVm.saveFile();
					}
					EgconfTopo1forVm.releaseInstance();
					//end
				}
				virCompWr.saveFile();
				EgConfigFilesSync.releaseInstance(virCompWr);
				externalWr.saveFile();
				EgConfigFilesSync.releaseInstance(externalWr);

				//if(newUnmanServers.size() > 0) //Commented by Krishamurthi - 14/01/2008
				//{
				//manager.createFileTopology("eg_topology.ini","save"); // No purpose / Nothing will happen, can comment.
				//trans.createFile("eg_disable.ini","save");
				//trans1.createFile("eg_testinfo.ini","save");
				//}

				// To post all values for removal of #new
				manager.createSyncFile("eg_discover.ini","save");
				if(isLimitedAdmin)
				{
					String comptoRemoveNew = request.getParameter("fmanage");
					ArrayList compToRemNew = new ArrayList();
					if (comptoRemoveNew != null)
					{
						StringTokenizer manCompsStt = new StringTokenizer(comptoRemoveNew,",");
						while(manCompsStt.hasMoreTokens())
						{
							String tmpComp = manCompsStt.nextToken(); 
							compToRemNew.add(tmpComp);						
						}
					}
					manager.setSrvrNew(srvtype,compToRemNew);
				}
				else
				{
					manager.setSrvrNew(srvtype);
				}
				manager.saveFile();
				manager.releaseInstance();
				//To unmange
				StringTokenizer st1 = null;
				ArrayList aListUnmanage = new ArrayList();
				ArrayList userIdList = new ArrayList();
				ArrayList unmngCompList = new ArrayList();
				ArrayList usrCompIniEntries = new ArrayList();
				IniFile userCompIni = new IniFile(userCompMap);
				if(newUnmanServers.size()>0)
				{
					//IniFile zoneIni = null;
					//zoneIni = new IniFile(installDir + "/manager/config/eg_group.ini", true);
					//ArrayList groupIniEntries = new ArrayList();
					ArrayList compsToUnmng = new ArrayList();
					//EgGroupInfo groupinfo = new EgGroupInfo();
					String [] qryBucket = new String [newUnmanServers.size()];
					boolean isDBUpdated = false;
					//ErUserData erUser;
					for (int r=0; r<newUnmanServers.size(); r++)
					{
						strTok = (String) newUnmanServers.get(r);
						strTok = strTok.trim();
						threshList.add(strTok);
						//manager.setSrvrUnm(srvtype,strTok);
						aListUnmanage.add(srvtype);
						aListUnmanage.add(strTok);
						//removeUnmanage = manager.removeUnmanage(srvtype,strTok);
						qryBucket[r] = "DELETE FROM user_serv WHERE serv_name = '" + strTok + "' AND serv_type = '" + srvtype + "'";
						isDBUpdated = userinfo.deleteFromDb(qryBucket[r]);
						/*if (isDBUpdated)
						{
							String compWithType =srvtype+":"+strTok;
							String zoneName = groupinfo.getZoneNameForComponent(compWithType);
							String groupName = groupinfo.getGroupNameForComponent(compWithType);
							if(zoneName != null && zoneName.length()>0)
							{
								String compVar = compWithType+"#"+zoneName;
								//zoneIni.deleteValue("ZONE_DETAILS",compVar);
								groupIniEntries.add(new IniHelper("ZONE_DETAILS",compVar));
							}
							if(groupName != null && groupName.length()>0)
							{
								//zoneIni.deleteValue("GROUP_DETAILS",compWithType);
								groupIniEntries.add(new IniHelper("GROUP_DETAILS",compWithType));
							}
						}
						else
						{
							break;
						}*/

						try
						{
							qryBucket[r] = "DELETE FROM user_vm WHERE serv_name = '" + strTok + "' AND serv_type = '" + srvtype + "'";
							isDBUpdated = userinfo.deleteFromDb(qryBucket[r]);
						}
						catch(Exception e)
						{
							e.printStackTrace();
						}

						//User-Comp Mapping changing #New comps
						userIdList = getUserId(usersList,srvtype+":"+strTok);
						if(userIdList != null)
						{
							int usrsIdLen = userIdList.size();
							for(int u=0; u<usrsIdLen; u++)
							{
								String user_Id = userIdList.get(u).toString().trim();
								String tempNewVar = "#New|"+srvtype+":"+strTok;
								String tempNewVal = userCompIni.getValue(user_Id,tempNewVar);
								if(tempNewVal != null && tempNewVal.length()>0)
								{
									unmngCompList.add(tempNewVar);
									usrCompIniEntries.add(new IniHelper(user_Id,tempNewVar));
								}
							}
						}
					}

					//if (groupIniEntries.size() > 0)
					//{
						//IniFile groupIniWrite = EgConfigFilesSync.getInstance(eGInstallDir+"/manager/config/eg_group.ini");
						//for (int g=0; g < groupIniEntries.size(); g++)
						//{
							//IniHelper iniHelpr = (IniHelper) groupIniEntries.get(g);
							//String sub = iniHelpr.getSubject();
							//String key = iniHelpr.getVariable();
							//groupIniWrite.deleteValue(sub,key);
						//}
						//if (isDBUpdated)
							//groupIniWrite.saveFile();
						//EgConfigFilesSync.releaseInstance(groupIniWrite);
					//}
					
					if (isDBUpdated)
					{
						//removes variables in eg_mgrmisc.ini file while unmanaging the components
						IniFile mgrMiscIni = EgConfigFilesSync.getInstance(EgInstallInfo.getInstallDir() + "/manager/config/eg_mgrmisc.ini");
						String[] variableArr = mgrMiscIni.getVariables("ASSOCIATED_CORRECTIVE_SCRIPTS");
						HashSet variableSet = new HashSet();
						int listSize = aListUnmanage.size();
						String cType = "";
						String strComp = "";
						ArrayList userIdList2 = new ArrayList();
						manager.createSyncFile("eg_discover.ini","save");
						for (int i=0;i<listSize;i=i+2)
						{
							cType = (String)aListUnmanage.get(i);
							strComp = (String)aListUnmanage.get(i+1);
							int idx_val = strComp.indexOf(":");
							String compNickName = strComp.substring(0, idx_val);
							String s_varName = cType + ":" + compNickName;
							if (variableArr != null && variableArr.length > 0)
							{
								for (int j=0; j<variableArr.length; j++)
								{
									String variableStr = variableArr[j];
									if (variableStr.startsWith(s_varName))
									{
										variableSet.add(variableStr);
									}
								}
							}
						//	if(isLimitedAdmin)
						//	{
						//		manager.setSrvrUnm(cType,strComp,"#New");
						//	}
						//	else
						//	{
								manager.setSrvrUnm(cType,strComp);//unmanage comps @ eg_discover.ini
						//	}
							userIdList2 = getUserIdForUnmanage(usersList,userServCompsMap,cType+":"+strComp);
							if(userIdList2 != null)
							{
								int usrsIdLen2 = userIdList2.size();
								ArrayList userServCompsList = new ArrayList();
								for(int u=0; u<usrsIdLen2; u++)
								{
									String usrID = userIdList2.get(u).toString().trim();
									String tempUserVar = cType + ":" + strComp;
									String userVal = userCompIni.getValue(usrID,tempUserVar);
									if (userVal.length() > 0)
									{
										usrCompIniEntries.add(new IniHelper(usrID,tempUserVar));
										userVal = "";
									}
									userServCompsList = (ArrayList)userServCompsMap.get(usrID);
									if(userServCompsList != null && userServCompsList.contains(tempUserVar))
									{
										userVal = discoverInfo.getValue(cType,tempUserVar);
									}
									if(unmngCompList.contains("#New|"+tempUserVar))
									{
										userVal = discoverInfo.getValue(cType,"#New|"+tempUserVar);
									}
									if (userVal.length() > 0)// && !usrID.equalsIgnoreCase("eGEnterprise")
									{
										compsToUnmng.add(usrID);
										compsToUnmng.add("#Unmanage|"+tempUserVar);
										compsToUnmng.add(userVal);
										//if(isMspModel)
										{
											List userOrg = uuidInfo.getOrgNames(usrID);//String userOrg = uuidInfo.getOrgName(usrID);
											//if(userOrg != null && !userOrg.equals("") && !userOrg.equalsIgnoreCase("eGEnterprise"))
											if(userOrg != null && userOrg.size() > 0)
											{
												userOrg.remove("egenterprise");
												Iterator userOrgItr = userOrg.iterator();
												while (userOrgItr.hasNext())
												{
													String userOrgName = (String)userOrgItr.next();
													compsToUnmng.add(userOrgName);
													compsToUnmng.add("#Unmanage|"+tempUserVar);
													compsToUnmng.add(userVal);
												}
											}
										}
									}
								}
							}
						}
						manager.saveFile();
						manager.releaseInstance();
						Vector allVariableVec = new Vector(variableSet);
						if (allVariableVec != null && allVariableVec.size() > 0)
						{
							mgrMiscIni.deleteValues("ASSOCIATED_CORRECTIVE_SCRIPTS", allVariableVec);
						}
						mgrMiscIni.saveFile();
						EgConfigFilesSync.releaseInstance(mgrMiscIni);

						//User-Comp Mapping : unmanage comps @ eg_usercompmapping.ini
						int compsToUnmngSize = compsToUnmng.size();
						if(compsToUnmngSize > 0)
						{
							IniFile userCompIniWrite = EgConfigFilesSync.getInstance(userCompMap);
							for(int c=0; c<compsToUnmngSize; c=c+3)
							{
								String _usrId = (String)compsToUnmng.get(c);
								String _usrVar = (String)compsToUnmng.get(c+1);
								String _usrVal = (String)compsToUnmng.get(c+2);
								userCompIniWrite.setValue(_usrId,_usrVar,_usrVal);
							}
							userCompIniWrite.saveFile();
							EgConfigFilesSync.releaseInstance(userCompIniWrite);
						}
						//zoneIni.saveFile();

						//To disassociate components from all entities like groups, segments, services zones and aggregates.
						if (isProceed != null && isProceed.equalsIgnoreCase("true"))
						{
							String entity = "", entityName = "";
							Set auditDelSet = new HashSet();
							ArrayList resultWinList = new ArrayList();
							HashMap auditModSet = new HashMap();
							HashMap hm = helper.dissociateCompFromAllEntity();
							Iterator en = hm.keySet().iterator();
							while (en.hasNext())
							{
								String key = en.next().toString().trim();
								HashMap elemMap = (HashMap)hm.get(key);
								if (elemMap != null)
								{
									boolean isModified = false;
									boolean isDeleted = false;
									ArrayList keyTkns = StringUtils.egTokenizer(key,":",false,false,true);
									String dispCType = mappingInfo.getComponentTypeDescription(keyTkns.get(0).toString());
									String dispCName = keyTkns.get(1).toString();
									String dispPort = keyTkns.get(2).toString();
									key = dispCType + ":" + dispCName;
									if (!dispPort.equalsIgnoreCase("NULL"))
									{
										key += ":" + dispPort;
									}
									if (keyTkns.get(0).toString().equalsIgnoreCase("Oracle_server"))
									{
										key += ":" + keyTkns.get(3).toString();
									}

									String resultWinStr = "";
									if (elemMap.size()>0)
									{
										resultWinStr = key + "|$|";
									}
									String zoneModStr = "", grpModStr = "", servModStr = "", segModStr = "", servGrpModStr = "", maggModStr = "", uaggModStr = "";
									String zoneDelStr = "", grpDelStr = "", servDelStr = "", segDelStr = "", servGrpDelStr = "", maggDelStr = "", uaggDelStr = "";
									Iterator map = elemMap.keySet().iterator();
									while (map.hasNext())
									{
										String configStr = map.next().toString().trim();
										String actionPerformed = elemMap.get(configStr).toString().toLowerCase().trim();
										int actionPos = configStr.indexOf(":");
										if (actionPos > -1)
										{
											entityName = configStr.substring(actionPos+1).trim();
											entity = configStr.substring(0,actionPos);
										}

										if (entity.equalsIgnoreCase("Zone"))
										{
											if (actionPerformed.equalsIgnoreCase("deleted"))
											{
												isDeleted = true;
												zoneDelStr += entityName + "|#|";
												auditDelSet.add("Zone"+"|$|"+entityName);
											}
											else
											{
												isModified = true;
												zoneModStr += entityName + "|#|";
												String temp = "Zone"+"|$|"+entityName;
												if (auditModSet.containsKey(temp))
												{
													String tempKey = (String)auditModSet.get(temp);
													tempKey += "," + key;
													auditModSet.put(temp,tempKey);
												}
												else
												{
													auditModSet.put(temp,key);
												}
											}
										}
										if (entity.equalsIgnoreCase("ServiceGroup"))
										{
											if (actionPerformed.equalsIgnoreCase("deleted"))
											{
												isDeleted = true;
												servGrpDelStr += entityName + "|#|";
												auditDelSet.add("Service group"+"|$|"+entityName);
											}
											else
											{
												isModified = true;
												servGrpModStr += entityName + "|#|";
												String temp = "Service group"+"|$|"+entityName;
												if (auditModSet.containsKey(temp))
												{
													String tempKey = (String)auditModSet.get(temp);
													tempKey += "," + key;
													auditModSet.put(temp,tempKey);
												}
												else
												{
													auditModSet.put(temp,key);
												}
											}
										}
										if (entity.equalsIgnoreCase("Service"))
										{
											if (actionPerformed.equalsIgnoreCase("deleted"))
											{
												isDeleted = true;
												servDelStr += entityName + "|#|";
												auditDelSet.add("Service"+"|$|"+entityName);
											}
											else
											{
												isModified = true;
												servModStr += entityName + "|#|";
												String temp = "Service"+"|$|"+entityName;
												if (auditModSet.containsKey(temp))
												{
													String tempKey = (String)auditModSet.get(temp);
													tempKey += "," + key;
													auditModSet.put(temp,tempKey);
												}
												else
												{
													auditModSet.put(temp,key);
												}
											}
										}
										if (entity.equalsIgnoreCase("Segment"))
										{
											if (actionPerformed.equalsIgnoreCase("deleted"))
											{
												isDeleted = true;
												segDelStr += entityName + "|#|";
												auditDelSet.add("Segment"+"|$|"+entityName);
											}
											else
											{
												isModified = true;
												segModStr += entityName + "|#|";
												String temp = "Segment"+"|$|"+entityName;
												if (auditModSet.containsKey(temp))
												{
													String tempKey = (String)auditModSet.get(temp);
													tempKey += "," + key;
													auditModSet.put(temp,tempKey);
												}
												else
												{
													auditModSet.put(temp,key);
												}
											}
										}
										if (entity.equalsIgnoreCase("Group"))
										{
											if (actionPerformed.equalsIgnoreCase("deleted"))
											{
												isDeleted = true;
												grpDelStr += entityName + "|#|";
												auditDelSet.add("Group"+"|$|"+entityName);
											}
											else
											{
												isModified = true;
												grpModStr += entityName + "|#|";
												String temp = "Group"+"|$|"+entityName;
												if (auditModSet.containsKey(temp))
												{
													String tempKey = (String)auditModSet.get(temp);
													tempKey += "," + key;
													auditModSet.put(temp,tempKey);
												}
												else
												{
													auditModSet.put(temp,key);
												}
											}
										}
										if (entity.equalsIgnoreCase("ManagedAggregate"))
										{
											if (actionPerformed.equalsIgnoreCase("deleted"))
											{
												isDeleted = true;
												maggDelStr += entityName + "|#|";
												auditDelSet.add("Managed Aggregate"+"|$|"+entityName);
											}
											else
											{
												isModified = true;
												maggModStr += entityName + "|#|";
												String temp = "Managed Aggregate"+"|$|"+entityName;
												if (auditModSet.containsKey(temp))
												{
													String tempKey = (String)auditModSet.get(temp);
													tempKey += "," + key;
													auditModSet.put(temp,tempKey);
												}
												else
												{
													auditModSet.put(temp,key);
												}
											}
										}
										if (entity.equalsIgnoreCase("UnmanagedAggregate"))
										{
											if (actionPerformed.equalsIgnoreCase("deleted"))
											{
												isDeleted = true;
												uaggDelStr += entityName + "|#|";
												auditDelSet.add("Unmanaged Aggregate"+"|$|"+entityName);
											}
											else
											{
												isModified = true;
												uaggModStr += entityName + "|#|";
												String temp = "Unmanaged Aggregate"+"|$|"+entityName;
												if (auditModSet.containsKey(temp))
												{
													String tempKey = (String)auditModSet.get(temp);
													tempKey += "," + key;
													auditModSet.put(temp,tempKey);
												}
												else
												{
													auditModSet.put(temp,key);
												}
											}
										}
									}
									if (isModified)
									{
										resultWinStr += "Modified" + "$#$";
										if (zoneModStr.length()>0)
										{
											zoneModStr = zoneModStr.substring(0,zoneModStr.lastIndexOf("|#|"));
											resultWinStr += "Zone" + "|@|" + zoneModStr + "|:|";
										}
										if (servGrpModStr.length()>0)
										{
											servGrpModStr = servGrpModStr.substring(0,servGrpModStr.lastIndexOf("|#|"));
											resultWinStr += "Service Group" + "|@|" + servGrpModStr + "|:|";
										}
										if (servModStr.length()>0)
										{
											servModStr = servModStr.substring(0,servModStr.lastIndexOf("|#|"));
											resultWinStr += "Service" + "|@|" + servModStr + "|:|";
										}
										if (segModStr.length()>0)
										{
											segModStr = segModStr.substring(0,segModStr.lastIndexOf("|#|"));
											resultWinStr += "Segment" + "|@|" + segModStr + "|:|";
										}
										if (grpModStr.length()>0)
										{
											grpModStr = grpModStr.substring(0,grpModStr.lastIndexOf("|#|"));
											resultWinStr += "Group" + "|@|" + grpModStr + "|:|";
										}
										if (maggModStr.length()>0)
										{
											maggModStr = maggModStr.substring(0,maggModStr.lastIndexOf("|#|"));
											resultWinStr += "Managed Aggregate" + "|@|" + maggModStr + "|:|";
										}
										if (uaggModStr.length()>0)
										{
											uaggModStr = uaggModStr.substring(0,uaggModStr.lastIndexOf("|#|"));
											resultWinStr += "Unmanaged Aggregate" + "|@|" + uaggModStr + "|:|";
										}
										resultWinStr += "|hash|";
									}

									if(isDeleted)
									{
										resultWinStr += "Deleted" + "$#$";
										if (zoneDelStr.length()>0)
										{
											zoneDelStr = zoneDelStr.substring(0,zoneDelStr.lastIndexOf("|#|"));
											resultWinStr += "Zone" + "|@|" + zoneDelStr + "|:|";
										}
										if (servGrpDelStr.length()>0)
										{
											servGrpDelStr = servGrpDelStr.substring(0,servGrpDelStr.lastIndexOf("|#|"));
											resultWinStr += "Service Group" + "|@|" + servGrpDelStr + "|:|";//|hash| 
										}
										if (servDelStr.length()>0)
										{
											servDelStr = servDelStr.substring(0,servDelStr.lastIndexOf("|#|"));
											resultWinStr += "Service" + "|@|" + servDelStr + "|:|";
										}
										if (segDelStr.length()>0)
										{
											segDelStr = segDelStr.substring(0,segDelStr.lastIndexOf("|#|"));
											resultWinStr += "Segment" + "|@|" + segDelStr + "|:|";
										}
										if (grpDelStr.length()>0)
										{
											grpDelStr = grpDelStr.substring(0,grpDelStr.lastIndexOf("|#|"));
											resultWinStr += "Group" + "|@|" + grpDelStr + "|:|";
										}
										if (maggDelStr.length()>0)
										{
											maggDelStr = maggDelStr.substring(0,maggDelStr.lastIndexOf("|#|"));
											resultWinStr += "Managed Aggregate" + "|@|" + maggDelStr + "|:|";
										}
										if (uaggDelStr.length()>0)
										{
											uaggDelStr = uaggDelStr.substring(0,uaggDelStr.lastIndexOf("|#|"));
											resultWinStr += "Unmanaged Aggregate" + "|@|" + uaggDelStr + "|:|";
										}
									}
									if (resultWinStr.length()>0)
									{
										resultWinList.add(resultWinStr);
									}
								}
							}
							if (resultWinList != null && resultWinList.size()>0)
							{
								String elemList = resultWinList.toString();
								elemList = elemList.substring(1,elemList.length()-1);
								rootObj.put("elemList",elemList);
							}
							/* code for auditlog starts */
							if (auditModSet != null)
							{
								Iterator setItr = auditModSet.keySet().iterator();
								while (setItr.hasNext())
								{
									String auditStr = setItr.next().toString();
									String auditStrVal = auditModSet.get(auditStr).toString();
									ArrayList auditList = StringUtils.egTokenizer(auditStr,"|$|",false,true,true);
									ArrayList auditValList = StringUtils.egTokenizer(auditStrVal,",",false,true,true);
									if (auditList != null && auditList.size()>0)
									{
										String auditEntity = auditList.get(0).toString();
										String auditEntityName = auditList.get(1).toString();
										if (auditEntityName.endsWith(":NULL"))
										{
											String entCType = auditEntityName.substring(0,auditEntityName.indexOf(":"));
											entCType = _mapping.getComponentTypeDescription(entCType);
											String entCName = auditEntityName.substring(auditEntityName.indexOf(":")+1);
											entCName = entCName.substring(0,entCName.indexOf(":NULL"));
											auditEntityName = entCName + " (" + entCType + ")";
										}
										String auditComp = auditValList.toString();
										auditComp = auditComp.substring(1,auditComp.length()-1);
										if (!auditDelSet.contains(auditEntity+"|$|"+auditEntityName))
										{
											auditLogThread.setCurrentValue("03~~Modified "+auditEntity+"s",auditEntityName);
										}

									}
								}
							}
							if (auditDelSet != null)
							{
								Iterator setItr = auditDelSet.iterator();
								while (setItr.hasNext())
								{
									String auditStr = setItr.next().toString();
									ArrayList auditList = StringUtils.egTokenizer(auditStr,"|$|",false,true,true);
									if (auditList != null && auditList.size()>0)
									{
										String auditEntity = auditList.get(0).toString();
										String auditEntityName = auditList.get(1).toString();
										if (auditEntityName.endsWith(":NULL"))
										{
											String entCType = auditEntityName.substring(0,auditEntityName.indexOf(":"));
											entCType = _mapping.getComponentTypeDescription(entCType);
											String entCName = auditEntityName.substring(auditEntityName.indexOf(":")+1);
											entCName = entCName.substring(0,entCName.indexOf(":NULL"));
											auditEntityName = entCName + " (" + entCType + ")";
										}
										auditLogThread.setCurrentValue("04~~Deleted "+auditEntity+"s",auditEntityName);
									}
								}
							}
							/* code for auditlog ends */
						}
					}
					else
					{
						rootObj.put("success","true");
						rootObj.put("requestStatus","failed");
						//manager.releaseInstance();
						if (compList.size() > 1)
						{
							auditLogThread.setCurrentValue("ColumnName", "Components chosen for manage/unmanage/delete");
							errorObj.put("title",_mapping.getTextDescription("admin.error.Manage / Unmanage"));
							errorObj.put("message1",_mapping.getTextDescription("admin.error.Components cannot be unmanaged or deleted")+".");
							errorObj.put("message2",_mapping.getTextDescription("admin.error.The DB operation is failed and thus the components cannot be managed/unmanaged or deleted")+".");
						}
						else
						{
							auditLogThread.setCurrentValue("ColumnName", "Component chosen for manage/unmanage/delete");
							errorObj.put("title",_mapping.getTextDescription("admin.error.Manage / Unmanage"));
							errorObj.put("message1",_mapping.getTextDescription("admin.error.Component cannot be unmanaged or deleted")+".");
							errorObj.put("message2",_mapping.getTextDescription("admin.error.The DB operation is failed and thus the component cannot be managed/unmanaged or deleted")+".");
						}
						auditLogThread.setValue("Description","DB operation is failed");
						auditLogThread.sendItToDB();
						break;
					}
				}
				if (delVCFromVCDisc.equalsIgnoreCase("true") || delVCFromVCDisc.equalsIgnoreCase("Yes"))
				{
					if (srvtype.equals("Virtual_center"))
					{
						//IniFile vcmap = EgConfigFilesSync.getInstance(EgInstallInfo.getInstallDir() + "/manager/config/eg_vcmapping.ini");
						IniFile vcmap = new IniFile(EgInstallInfo.getInstallDir() + "/manager/config/eg_vcmapping.ini");
						String[] vcmapSub = vcmap.getSubjects();
						List vcmapList = Arrays.asList(vcmapSub);

						IniFile sevicesIni = EgConfigFilesSync.getInstance(EgInstallInfo.getInstallDir() + "/manager/config/eg_services.ini");
						for(int c =0; c < newUnmanServers.size(); c++)
						{
							String comp = (String)newUnmanServers.get(c);
							if (comp.contains(":NULL"))
							{
								comp = comp.substring(0,comp.indexOf(":NULL"));
							}
							if (vcmapList.contains(comp))
							{
								rootObj.put("success","true");
								rootObj.put("requestStatus","failed");
								if (compList.size() > 1)
								{
									auditLogThread.setValue("Description","Components of $ctype$:"+srvtype+" cannot be deleted as One/more tests have been configured to use on this vCenter Server");
									errorObj.put("title",_mapping.getTextDescription("admin.server.Unmanage components"));
									errorObj.put("message1",_mapping.getTextDescription("admin.error.Components cannot be unmanaged")+".");
								}
								else
								{
									auditLogThread.setValue("Description","Component of $ctype$:"+srvtype+" cannot be deleted as One/more tests have been configured to use on this vCenter Server");
									errorObj.put("title",_mapping.getTextDescription("admin.server.Unmanage component"));
									errorObj.put("message1",_mapping.getTextDescription("admin.error.Component cannot be unmanaged")+".");
								}
								auditLogThread.sendItToDB();
								errorObj.put("message2",_mapping.getTextDescription("admin.error.One/more tests have been configured to use on this vCenter Server")+".");
								break;
							}
							else
							{
								sevicesIni.deleteValue("VIRTUAL_CENTER",comp);
							}
						}
						sevicesIni.saveFile();
						EgConfigFilesSync.releaseInstance(sevicesIni);
					}
				}

				/********************************************************/
				//- delete excluded component entry from eg_mailalert.ini when the component is unmanaged.
				//- added by maruthu - start
				ArrayList delServListForFilter = new ArrayList();
				for(int i=0;i<newUnmanServers.size();i++)
				{
					String comp = (String)newUnmanServers.get(i);
					delServListForFilter.add(srvtype+":"+comp);
				}
				DeleteMailFilterElements delMailFilterElements = new DeleteMailFilterElements();
				delMailFilterElements.removeElementsFromMailFilter(delServListForFilter);
				//end
				//- delete excluded component entry from eg_TroubleTicketFilter.ini when the component is unmanaged.

				DeleteTTFilterElements delTTFilterElements = new DeleteTTFilterElements();
				delTTFilterElements.removeElementsFromMailFilter(null,delServListForFilter);
				//end

				if (delVCFromVCDisc.equalsIgnoreCase("true") || delVCFromVCDisc.equalsIgnoreCase("Yes"))
				{
					if (mngComp != null && !mngComp.isEmpty())
					{
						ArrayList extIniEntries = new ArrayList();
						for (int k=0;k<mngComp.size();k++)
						{
							String tmp = (String)mngComp.get(k);
							String tempVc = tmp.substring(0,tmp.indexOf(":NULL"));
							tempVc = tempVc.substring(tempVc.indexOf(":")+1);
							if (srvtype.equals("Virtual_center"))
							{
								String Ssl = "True";
								String uName = "$unconfigured";
								String uPass = "$unconfigured";
								String isDiscovery = "Yes";
								String webPort = "443";
								//String hostVMType = "ServerVMs";
								extIniEntries.add(new IniHelper(IniHelper.SET,"VIRTUAL_CENTER", tempVc, Ssl+"#"+uName+"#"+uPass+"#"+isDiscovery+"#"+webPort));
							}
							if (extIniEntries.size() > 0)
							{
								IniFile externalWrite = EgConfigFilesSync.getInstance(EgInstallInfo.getInstallDir() + "/manager/config/eg_services.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))
										{
											externalWrite.setValue(subject,key,value);
										}
									}
								}
								externalWrite.saveFile();
								EgConfigFilesSync.releaseInstance(externalWrite);
							}
						}
					}
				}
				oldManServers = (Vector)session.getValue("managed");

				for(int i=0; i<oldManServers.size(); i++)
				{
					tmpVal = (String)oldManServers.get(i);
					val = tmpVal.substring(tmpVal.indexOf(":")+1);
					if(!newManServers.contains(val))
					{
						if(!tmpServers.contains(tmpVal))
							tmpServers.add(tmpVal);
					}
				}

				if(!callBasicErrorPage)
				{
					if (usersInfo.isUserBasedLicense() && userVdiTypes.contains(srvtype))
					{
						update = true;
					}
					else
					{
						int monTargets = user.getMonitoredTargets();
						if(monTargets == -1)
							update = true;
						else
						{
							updateServers = user.getFinalServers(tmpServers,finalServers);
							for(int i=0; i<finalServers.size(); i++)
							{
								if(!updateServers.contains(finalServers.get(i)))
									updateServers.add(finalServers.get(i));
							}
							if(updateServers.size() <= monTargets)
								update = true;
							else 
							{
								update = false;
								/* code for auditlog starts */
								if (compList.size() > 1)
								{
									auditLogThread.setCurrentValue("ColumnName", "Components chosen for manage/unmanage/delete");
								}
								else
								{
									auditLogThread.setCurrentValue("ColumnName", "Component chosen for manage/unmanage/delete");
								}
								auditLogThread.setValue("Description","You have exceeded the number of monitored targets allowed by your license");
								auditLogThread.sendItToDB();
								/* code for auditlog ends */
														
								rootObj.put("success","true");
								rootObj.put("requestStatus","failed");
								errorObj.put("title",_mapping.getTextDescription("admin.server.Manage/UnManage components"));
								errorObj.put("message1",_mapping.getTextDescription("admin.error.You have exceeded the number of monitored targets allowed by your license")+".");
								errorObj.put("message2",_mapping.getTextDescription("admin.error.To monitor additional targets")+", "+_mapping.getTextDescription("admin.error.please contact")+" <b>license@eginnovations.com</b>");
								break;
							}
						}
					}
					String managedIPs = "";
					String managedNicks = "";
					if (managedCompsNew != null)
					{
						for(int m=0; m<managedCompsNew.size(); m++)
						{
							String compNew = managedCompsNew.get(m).toString();
							int idx = compNew.indexOf(":");
							if (idx > -1)
							{
								compNew = compNew.substring(0,idx);
								managedNicks += compNew +",";
								compNew = (String)hTableAllNicksIp.get(compNew);
								managedIPs += compNew +",";
							}
						}
						if (managedIPs.endsWith(","))
						{
							managedIPs = managedIPs.substring(0,managedIPs.length()-1);
						}
						if (managedNicks.endsWith(","))
						{
							managedNicks = managedNicks.substring(0,managedNicks.length()-1);
						}
					}
					if(update)
					{
						//To manage
						st = new StringTokenizer(manage,",");
						String strNickName = "";
						String port = "";
						IniFile externalIniWr = EgConfigFilesSync.getInstance(eGInstallDir+"/manager/config/eg_external.ini");
						ArrayList userIdList3 = new ArrayList();
						Hashtable resultMap = new Hashtable();

						manager.createSyncFile("eg_discover.ini","save");
						while(st.hasMoreTokens())
						{
							strTok = st.nextToken().trim();
							if (strTok.indexOf(":NULL")>1)
							{
								strNickName =  strTok.substring(0,strTok.indexOf(":NULL"));
							}
							else
							{
								strNickName = strTok;
							}
							if (aListNickAlreadyExists.contains(strNickName))
							{
								continue;
							}
							manager.setSrvrMn(srvtype,strTok);
							updateUuidIni(uuidInfo,strNickName);
							if (clientEmuComps && (emuClient != null && emuClient.length>0))
							{
								String strNickTok = strTok.substring(0,strTok.indexOf(":"));
								String clntEmuAgnt = externalIniWr.getValue("Test_Mapping_Section",strNickTok);
								if (clntEmuAgnt == null || clntEmuAgnt.trim().equals(""))
								{
									String emuClientAgent = (String)emuClient[0];
									externalIniWr.setValue("Test_Mapping_Section",strNickTok,emuClientAgent);
								}
							}
							if(srvtype != null && strTok != null && srvtype.startsWith("Agg_"))
							{
								//aggregateInfo.manageAggregateComponent(srvtype+":"+strTok);
								String compName = srvtype+":"+strTok;
								int ind=compName.indexOf(":");
								if(compName.indexOf(":")>0 && compName.lastIndexOf(":")>ind)
								{
									IniFile EgConfigFilesSync_inner = EgConfigFilesSync.getInstance(EgInstallInfo.getInstallDir()+"/manager/config/eg_aggregate.ini",true);
									String[] vars = aggregateInfo.getVariables(EgAggregateInfo.aggComponent);
									for(int k=0;k<vars.length;k++)
									{
										String variable=vars[k];
										String aggComp="";
										if(variable.startsWith("#Unmanage") && variable.lastIndexOf("#")>0)
										{
											aggComp=variable.substring(variable.indexOf("|")+1,variable.lastIndexOf("#"));
											if(compName.equals(aggComp))
											{
												String managedVar=variable.substring(variable.indexOf("|")+1);
												EgConfigFilesSync_inner.setValue(EgAggregateInfo.aggComponent,managedVar,"associated");
												EgConfigFilesSync_inner.deleteValue(EgAggregateInfo.aggComponent,variable);
											}
										}
									}
									EgConfigFilesSync_inner.saveFile();
									EgConfigFilesSync.releaseInstance(EgConfigFilesSync_inner);
								}
							}
							//User-Comp Mapping : Manage @ eg_usercompmapping.ini
							userIdList3 = getUserId(usersList,srvtype+":"+strTok);
							ArrayList refinedUserIdList3 = getRefinedUsers(uuidInfo,userIdList3);
							if(userIdList3 != null)
							{
								int usrsIdLen3 = userIdList3.size();
								for(int u=0; u<usrsIdLen3; u++)
								{
									String usrID = userIdList3.get(u).toString().trim();
									String unmanVar = "#Unmanage|"+srvtype+":"+strTok;
									String unmanVal = userCompIni.getValue(usrID,unmanVar);
									if(unmanVal != null && unmanVal.equals("") && unmanVal.length() == 0)
									{
										unmanVar = "#New|"+srvtype+":"+strTok;
										unmanVal = userCompIni.getValue(usrID,unmanVar);
									}
									if (unmanVal != null && !unmanVal.equals("") && unmanVal.length() > 0)
									{
										usrCompIniEntries.add(new IniHelper(usrID,unmanVar));
										//if(isLimitedAdmin && usrID.equalsIgnoreCase(loginUserID))
										{
											String strNickTok = strTok.substring(0,strTok.indexOf(":"));
											userExtAgent = externalIniWr.getValue("Test_Mapping_Section",strNickTok);
											if (userExtAgent != null && !userExtAgent.equals(""))
											{
												externalIniWr.setValue("Test_Mapping_Section",strNickTok,userExtAgent);
											}
											else
											{
												ArrayList usersExtAgents = userElemInfo.getExternalAgentsForUser(usrID);
												if(usersExtAgents != null && usersExtAgents.size()>0)
												{
													userExtAgent = usersExtAgents.get(0).toString();
													externalIniWr.setValue("Test_Mapping_Section",strNickTok,userExtAgent);
												}
											}
										}
									}
								}
							}
							int refusrsIdLen3 = (refinedUserIdList3 != null) ? refinedUserIdList3.size() : 0;
							for(int usrIdx=0; usrIdx<refusrsIdLen3; usrIdx++)
							{
								String usrID = refinedUserIdList3.get(usrIdx).toString().trim();
								Hashtable argsMap = new Hashtable();
								argsMap.put("userid",usrID);
								argsMap.put("componenttype",srvtype);
								argsMap.put("components",strTok);
								argsMap.put("autoassociatetype","no");
								HashMap strStatus = uacObj.AssociateComponent(argsMap,true);
								//If autoCreateZoneForUser is set to true, then assign the component(s) to the user's zone.
								if (autoCreateZoneForUser && strStatus != null && strStatus.containsKey("eG_CLI_Res_0286"))
								{
									ArrayList uList = (ArrayList)strStatus.get("eG_CLI_Res_0286");
									if (!uList.contains(usrID))
									{
										continue;
									}
									argsMap = new Hashtable();
									argsMap.put("userid",usrID);
									argsMap.put("stype",srvtype);
									argsMap.put("compname",strTok);
									resultMap = uacObj.AutoAssociateComponentToZone(argsMap);
								}
							}
							
							if(srvtype != null && strTok != null && srvtype.startsWith("Agg_"))
							{
								aggregateInfo.manageAggregateComponent(srvtype+":"+strTok);
							}
						}
						externalIniWr.saveFile();
						EgConfigFilesSync.releaseInstance(externalIniWr);
						manager.saveFile();
						manager.releaseInstance();

						//associate zones to user and for zone audit log
						if (isLimitedAdmin && autoCreateZoneForUser && 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();
						}

						/*
						 * Check eg_external.ini to see if its nick exists in the eg_external.ini 
						 * in the LHS of the Internal_Agent_Mapping section. If so, delete the 
						 * appropriate entry from this eg_external.ini file.
						 *
						 * This nick should not be managing another server type
						 */
						//tpbean.createFile("eg_maintenance.ini","save");
						tpbean.createFile("eg_maintenance.ini");
						EgDiscInfo discInfo = new EgDiscInfo("manager");
						//EgConfigTopo1.createFile("eg_external.ini","save");
						ArrayList externalEntries = new ArrayList();
						String[] maintenanceVars1 =  tpbean.getVariables("SERVERS");
						String[] QuickmaintenanceVars =  tpbean.getVariables("UNPLANNED_POLICY_MAPPING");
						List maintenanceVars=new ArrayList();

						if(maintenanceVars1!=null)
						{
								maintenanceVars.addAll(Arrays.asList(maintenanceVars1));
								Collections.sort(maintenanceVars,String.CASE_INSENSITIVE_ORDER);
						}

						if(QuickmaintenanceVars!=null)
						{
							maintenanceVars.addAll(Arrays.asList(QuickmaintenanceVars));
							Collections.sort(maintenanceVars,String.CASE_INSENSITIVE_ORDER);
						}
						String thisComponent="";
						IniFile maintenanceWr = EgConfigFilesSync.getInstance(eGInstallDir + "/manager/config/eg_maintenance.ini");
						customDashboardModel.createCustomDashboardIniObject();
						try
						{
							for (Iterator i=tmpServers.iterator(); i.hasNext(); )
							{
								String tmpServer = (String)i.next();
								String server = Server.getServerNameWithoutPort(tmpServer, true);
								String serverName = Server.getServerNameWithoutPort(server);
								List serversWithNick = discInfo.getServerTypesForNick(serverName);
								/*
								 * Only this server type is being managed
								 */
								 customDashboardModel.deleteUnmanagedComponent(tmpServer);
								if(isEnableSLA)
								{
									 slaDashBoardDAO.deleteUnmanagedComponentForSLA(tmpServer);
								}
								if (serversWithNick == null || serversWithNick.size() == 0 || serversWithNick.size() == 1)
								{
									String compType= tmpServer.substring(0, tmpServer.indexOf(":"));
									// For removing the entries in eg_maintenance.ini when the component is unmanaged
									//tpbean.deleteValues("SERVERS",serverName);//maintenance.ini will have only host name. so to have hostname without port - lavanya
									if(tmpServer.indexOf(":")>0)
									{
										thisComponent=tmpServer.substring(tmpServer.indexOf(":")+1);
									}
									for (int j=0;j<maintenanceVars.size();j++)
									{
										String tmpVar =(String) maintenanceVars.get(j);
										tmpVar=tmpVar.trim();
										if (tmpVar.equals(thisComponent)) // Component 
										{
											maintenanceWr.deleteValue("SERVERS",thisComponent);
											maintenanceWr.deleteValue("UNPLANNED_POLICY_MAPPING",thisComponent);
										}
										if(tmpVar.indexOf("#") == -1 && tmpVar.indexOf(":") == -1 ) // Host
										{
											String thisHostName = tmpServer.substring(tmpServer.indexOf(":")+1,tmpServer.lastIndexOf(":"));
											if(compType!=null &&compType.equals("Oracle_server"))
											{
												thisHostName=thisHostName.substring(0,thisHostName.indexOf(":"));
											}
											maintenanceWr.deleteValue("SERVERS",thisHostName);
											maintenanceWr.deleteValue("UNPLANNED_POLICY_MAPPING",thisHostName);
										}
										if (tmpVar.indexOf("#") > 0 && tmpVar.indexOf(":") == -1) // Test For Host
										{
											String thisHostName = tmpServer.substring(tmpServer.indexOf(":")+1,tmpServer.lastIndexOf(":"));
											if(compType!=null &&compType.equals("Oracle_server"))
											{
												thisHostName=thisHostName.substring(0,thisHostName.indexOf(":"));
											}
											if (tmpVar.startsWith(thisHostName+"#"))
											{
												maintenanceWr.deleteValue("SERVERS",tmpVar);
												maintenanceWr.deleteValue("UNPLANNED_POLICY_MAPPING",tmpVar);
											}
										}
										if (tmpVar.indexOf("#") > 0 && tmpVar.indexOf(":") > 0) // Test For Component
										{
											if (tmpVar.startsWith(thisComponent+"#"))
											{
												maintenanceWr.deleteValue("SERVERS",tmpVar);
												maintenanceWr.deleteValue("UNPLANNED_POLICY_MAPPING",tmpVar);
											}
										}
									}
									/*
									if(serverName.indexOf(":")!=-1)
									{
										String thisHostName = serverName.substring(0, serverName.lastIndexOf(":"));
										tpbean.deleteValues("SERVERS",thisHostName);
									}
									*/
									//EgConfigTopo1.deleteSpecValue("Internal_Agent_Mapping", serverName);
									//EgConfigTopo1.deleteSpecValue("Test_Mapping_Section", serverName);
									ArrayList sameNickCompsWithinType = egDiscInfo.getServersForHost(serverName,true);
									if (sameNickCompsWithinType != null)
									{
										sameNickCompsWithinType.removeAll(newlyUnmanagedComponents);
										if (sameNickCompsWithinType.size() == 0)
										{
											externalEntries.add(new IniHelper(IniHelper.DELETE,"Internal_Agent_Mapping", serverName,""));
										}							
									}

									//externalEntries.add(new IniHelper(IniHelper.DELETE,"Test_Mapping_Section", serverName,""));
								}
							}
						}
						catch(Throwable t)
						{
							t.printStackTrace();
						}
						finally
						{
							//EgConfigTopo1.saveFile();
							//tpbean.saveFile();
							maintenanceWr.saveFile();
							EgConfigFilesSync.releaseInstance(maintenanceWr);
							customDashboardModel.releaseCustomDashboardIniObj();
							//manager.saveFile();
							//manager.releaseInstance();
						}
						//manager.saveFileTopology();
						//Added by alagu for vmware

						//String serverType=request.getParameter("server");
						//String serverType=request.getParameter("srvtype");
						String serverType=srvtype;
						Hashtable nickip=discInfo.getNickIpMap();
						if(v_managedserver != null && v_managedserver.size() > 0)
						{
							Vector v_virtservers=externalInfo.getVirtualServers();
							if(v_virtservers.contains(serverType))
							{
								for (int m=0;m<v_managedserver.size(); m++)
								{
									String server = (String)v_managedserver.get(m);
									String serverName = Server.getServerNameWithoutPort(server);
									if(nickip!=null )
									{
										String ip=(String)nickip.get(serverName);
										if (ip!=null)
										{
											//EgConfigTopo1.setValues("Virtual_Hosts",serverType+":"+server,ip);
											externalEntries.add(new IniHelper(IniHelper.SET,"Virtual_Hosts",serverType+":"+server,ip));		
										}
									}
								}
							}
							v_virtservers = null;
						}
						//alagu ends here
					
						//karthika for cloud components
						if(v_managedserver != null && v_managedserver.size() > 0)
						{
							Vector v_cloudservers=externalInfo.getCloudServers();
							if(v_cloudservers.contains(serverType))
							{
								for (int m=0;m<v_managedserver.size(); m++)
								{
									String server = (String)v_managedserver.get(m);
									String serverName = Server.getServerNameWithoutPort(server);
									if(nickip!=null )
									{
										String ip=(String)nickip.get(serverName);
										if (ip!=null)
										{
											//EgConfigTopo1.setValues("Cloud_Hosts",serverType+":"+server,ip);
											externalEntries.add(new IniHelper(IniHelper.SET,"Cloud_Hosts",serverType+":"+server,ip));
										}
									}
								}
								
							}
							v_cloudservers = null;
						}
						nickip = null;
						 // cloud ends here

						if (externalEntries.size() > 0)
						{
							IniFile externalWrite = EgConfigFilesSync.getInstance(eGInstallDir +"/manager/config/eg_external.ini");
							for (int e=0; e < externalEntries.size(); e++)
							{
								IniHelper iniHelper = (IniHelper) externalEntries.get(e);
								String iniAction = iniHelper.getAction();
								String sub = iniHelper.getSubject();
								String key = iniHelper.getVariable();
								String value = iniHelper.getValue();
								if (iniAction != null)
								{
									if (iniAction.equals(IniHelper.SET))
									{
										externalWrite.setValue(sub,key,value);
									}
									else if (iniAction.equals(IniHelper.DELETE))
									{
										externalWrite.deleteValue(sub,key);
									}
								}
							}
							externalWrite.saveFile();
							EgConfigFilesSync.releaseInstance(externalWrite);
						}

						trans.createSyncFile("eg_disable.ini","save");
						for (Iterator i=tmpServers.iterator(); i.hasNext(); )
						{
							String s_tmpServer  = (String)i.next();
							String s_srvname = s_tmpServer.substring(s_tmpServer.indexOf(":")+1);
							String server = Server.getServerNameWithoutPort(s_tmpServer, true);
							String serverName = Server.getServerNameWithoutPort(server);
							List serversWithNick = discInfo.getServerTypesForNick(serverName);
							trans.updateDisableIni(s_srvname,srvtype,serverName,serversWithNick);
							//trans1.updateTestInfoIni(s_srvname,srvtype,serverName,serversWithNick);
						}
						trans.saveFileAndReleaseInstance();
						trans1.createSyncFile("eg_testinfo.ini","save");
						trans1.updateTestInfoIni(tmpServers,srvtype);
						trans1.saveFileAndReleaseInstance();

						/* [FORBIDDEN_SERVERS] entry are removed form eg_disable.ini,when you manage		 the components-->S.Andrews  */
						/*
						EgConfigTopo1.createFile("eg_disable.ini","save");
						for(Iterator i = updateManServers.iterator();i.hasNext();){
							String serverName = (String)i.next();	
							String new_var = serverName+"#"+srvtype+"#"+serverName.substring(0,serverName.indexOf(":"));
							EgConfigTopo1.deleteSpecValue("FORBIDDEN_SERVERS",new_var);
						}
						EgConfigTopo1.saveFile();
						*/
					

						// To delete the specific thresholds and descriptor thresholds for the unmanaged components
						//Start
						if(threshList != null && threshList.size() >0)
						{
							for(int g=0; g<threshList.size(); g++)
							{
								//String serverName = Server.getServerNameWithoutPort((String)threshList.get(g));
								//List arr = discInfo.getServerTypesForNick(serverName);
								// If there are other servers with same hostname/nickname
								// Don't delete entries from thresholds.ini
								//if(arr.size() > 0)
								//	continue;

								String str = (String)threshList.get(g);
								user.deleteSpecificThresholds(str);
								descGrp.deleteUnmanagedComponentFromInfoGroup(str);
							}
							//descGrp.saveFile();
						}
						//End
						// To delete the specific password profiles for the unmanaged components
						//Start
						EgPwdProfile pwdProf = new EgPwdProfile();
						ArrayList newlyUnmanCompsList = new ArrayList();
						for(int n=0; n<newlyUnManComps.size(); n++)
						{
							String comp = (String)newlyUnManComps.get(n);
							newlyUnmanCompsList.add(srvtype+":"+comp);
						}
						pwdProf.removeSpecificCompsDetails(newlyUnmanCompsList);
						//End

						if (hasLimitExceeded)
						{
							servicer.startDiscovery("1");
						}
						else
						{
							servicer.startDiscovery("1",true);
						}
						EgConfigFilesSync.releaseInstance(infraIni);

						if(monitorLastSession != null && newUrlLink != null && newUrlLink.indexOf("com.eg.EgDashboardController")>-1 && strcurrentTab != null && (strcurrentTab.equals("LayerModel") || strcurrentTab.equals("System") || strcurrentTab.equals("Network") || strcurrentTab.equals("Application")))
						{
							if(strHostName!=null && unmanagedNickCache!=null && unmanagedNickCache.equals(strHostName))
							{
								session.removeAttribute("monitorLastSession");
							}
						}
						/*
						 * Update the UserRegistry here
						 */
						//UserRegistry registry = UserRegistry.getInstance();
						registry.updateAllUserMaps();
						Vector v=new Vector();
						List extAgentList = new ArrayList();
						List remAgentList = new ArrayList();
						if (extAgents != null)
						{
							extAgentList = Arrays.asList(extAgents);
						}
						if (remAgents != null)
						{
							remAgentList = Arrays.asList(remAgents);
						}
						for (int r=0; r<newUnmanServers.size(); r++)
						{
							String str = (String) newUnmanServers.get(r);
							str = str.trim();
							String serverName = Server.getServerNameWithoutPort(str);
							List servertype=discInfo.getServerTypesForNick(serverName);
							if(servertype.size()==0 && !extAgentList.contains(serverName) && !remAgentList.contains(serverName))
							{
								v.addElement(serverName);
							}
						}
						if(v!=null && (!v.isEmpty()))
						{
							AgentConfig agentConfig=AgentConfig.getAgentConfig();
							for(int j=0; j<v.size();j++)
							{
								String serverName = (String)v.get(j);
								agentConfig.removeAgentElement(serverName);
							}
							
						}
						//if(EgInstallInfo.isAggregationSupported())
						//{
							///*
								//When individual components are unmanaged,we have to remove them from unmanaged aggregate components.
								//Sometimes unmanged aggregate components might have been created by using all these individual components 
								//which are about to be unmanaged. In this circumstances, we have to remove the unmanaged aggregate 
								//components from eG System. If only some of selected individual components were used in unmanaged 
								//aggregate components, we have to remove them from unmanaged aggregate components. 
								//Below code does this.
							//*/
							//if(!srvtype.startsWith("Agg_") && (unmanagedAggComponents != null && !unmanagedAggComponents.isEmpty() || aggregateComponents != null && !aggregateComponents.isEmpty()))
							//{
								//ArrayList deletedAggComps = new ArrayList();
								//IniFile EgConfigFilesSync_inner = EgConfigFilesSync.getInstance(EgInstallInfo.getInstallDir()+"/manager/config/eg_aggregate.ini",true);
								//IniFile discIniObj = EgConfigFilesSync.getInstance(EgInstallInfo.getInstallDir() + "/manager/config/eg_discover.ini");
								//boolean updated = false;
								//int unmanagedCount = unmanagedAggComponents.size();
								//for(int kk=0;kk<unmanagedCount;kk++)
								//{
									//String alreadyUnmanagedAggComp = (String) unmanagedAggComponents.get(kk);
									//List associatedNormalComps = aggregateInfo.getUnmanagedAssociatedComponents(alreadyUnmanagedAggComp, true);
									//if(associatedNormalComps != null && compList.containsAll(associatedNormalComps))
									//{
										//deletedAggComps.add(alreadyUnmanagedAggComp);
										//EgConfigFilesSync_inner.deleteValue("SITE_SUPPORT",alreadyUnmanagedAggComp);
										//discIniObj.deleteValue("Agg_"+srvtype,"#Unmanage|"+alreadyUnmanagedAggComp);
										//if(alreadyUnmanagedAggComp.startsWith("Unmanage|"))
										//{
											//auditLogThread.setCurrentValue("Deleted Unmanaged Aggregate Component(s)", "$ctype$:"+alreadyUnmanagedAggComp.substring(alreadyUnmanagedAggComp.indexOf("|")+1,alreadyUnmanagedAggComp.lastIndexOf(":")));
										//}
										//else
										//{
											//auditLogThread.setCurrentValue("Deleted Aggregate Component(s)", "$ctype$:"+alreadyUnmanagedAggComp.substring(0,alreadyUnmanagedAggComp.lastIndexOf(":")));
										//}
										//updated=true;
									//}
								//}
								//String zonename[] = null;
								//String groupname = null;
								//String segments[] = null;
								//ArrayList siteList = null;
								//for(int kk=0;kk<aggregateComponents.size();kk++)
								//{
									//String aggregateComponent = (String) aggregateComponents.get(kk);
									//zonename = groupinfo.getZoneNameForComponent(aggregateComponent, true);
									//if(zonename != null && zonename.length>0)
									//{
										////System.out.println(aggregateComponent + " is associated to zone " + zonename);
										//continue;
									//}
									//groupname = groupinfo.getGroupNameForComponent(aggregateComponent);
									//if(groupname != null && groupname.length()>0)
									//{
										////System.out.println(aggregateComponent + " is associated to group " + groupname);
										//continue;
									//}
									//siteList = egTopoInfo.getSitesForComponent(aggregateComponent);
									//if(siteList != null && !siteList.isEmpty())
									//{
										////System.out.println(aggregateComponent + " is associated to site/service " + siteList);
										//continue;
									//}
									//segments = egTopoInfo.getSegmentsForComponent(aggregateComponent);
									//if(segments != null && segments.length==1 && !segments[0].equals("NULL"))
									//{
										////System.out.println(aggregateComponent + " is associated to segment " + segments[0]);
										//continue;
									//}
									//List associatedNormalComps = aggregateInfo.getAssociatedComponents(aggregateComponent, true);
									//if(associatedNormalComps != null && compList.containsAll(associatedNormalComps))
									//{
										//String query = "DELETE FROM user_serv WHERE serv_name = '" + aggregateComponent.substring(aggregateComponent.indexOf(":")+1) + "' AND serv_type = '" + "Agg_"+srvtype + "'";
										//boolean isDBUpdated = userinfo.deleteFromDb(query);
										//if(isDBUpdated)
										//{
											//deletedAggComps.add(aggregateComponent);
											//EgConfigFilesSync_inner.deleteValue("SITE_SUPPORT",aggregateComponent);
											//discIniObj.deleteValue("Agg_"+srvtype,aggregateComponent);
											//if(aggregateComponent.startsWith("Unmanage|"))
											//{
												//auditLogThread.setCurrentValue("Deleted Unmanaged Aggregate Component(s)", "$ctype$:"+aggregateComponent.substring(aggregateComponent.indexOf("|")+1,aggregateComponent.lastIndexOf(":")));
											//}
											//else
											//{
												//auditLogThread.setCurrentValue("Deleted Aggregate Component(s)", "$ctype$:"+aggregateComponent.substring(0,aggregateComponent.lastIndexOf(":")));
											//}
											//updated=true;
										//}
									//}
								//}
								//if(updated)
								//{
									//discIniObj.saveFile();
								//}
								//EgConfigFilesSync.releaseInstance(discIniObj);						
								//String[] agg_comps = aggregateInfo.getVariables(EgAggregateInfo.aggComponent);
								//String[] compAssociation_vars = aggregateInfo.getVariables(EgAggregateInfo.compAssociation);
								//String[] ui_compAssociation = aggregateInfo.getVariables("UI_COMPONENT_ASSOCIATION");
								//String[] anchor_agg_comps = aggregateInfo.getVariables(EgAggregateInfo.anchorComponent);
								//String compStr = null;
								//for(int kk=0; kk<compList.size(); kk++)
								//{
									//String component = (String)compList.get(kk);//Generic_server:vladimir:NULL
									////aggregateInfo.deleteComponentsFromAggregateComponents(component);//changed now							
									//if(agg_comps != null)
									//{
										//StringTokenizer strTokens = new StringTokenizer(component,",");
										//while (strTokens.hasMoreTokens())
										//{
											//String s = strTokens.nextToken();
											//if ((agg_comps != null) && (agg_comps.length > 0))
											//{
												//for(int i=0;i<agg_comps.length;i++)
												//{
													//if (agg_comps[i].indexOf(s) != -1)
													//{
														//EgConfigFilesSync_inner.deleteValue(EgAggregateInfo.aggComponent,agg_comps[i]);
													//}
												//}
											//}
											//if(compAssociation_vars != null)
											//{
												//for(int i=0;i<compAssociation_vars.length;i++)
												//{
													//if (compAssociation_vars[i].startsWith(s+"#"))
													//{
														//EgConfigFilesSync_inner.deleteValue(EgAggregateInfo.compAssociation,compAssociation_vars[i]);//jamesthomas
													//}
												//}
											//}
											//if ((ui_compAssociation != null) && (ui_compAssociation.length > 0))
											//{
												//for(int i=0;i<ui_compAssociation.length;i++)
												//{
													//if (ui_compAssociation[i].startsWith(s+"#"))
													//{
														//EgConfigFilesSync_inner.deleteValue("UI_COMPONENT_ASSOCIATION",ui_compAssociation[i]);//jamesthomas
													//}
												//}
											//}
											//if ((anchor_agg_comps != null) && (anchor_agg_comps.length > 0))
											//{
												//for(int i=0;i<anchor_agg_comps.length;i++)
												//{
													//if (anchor_agg_comps[i].startsWith(s+"#"))
													//{
														//EgConfigFilesSync_inner.deleteValue(EgAggregateInfo.anchorComponent,anchor_agg_comps[i]);//jamesthomas
													//}
												//}
											//}
										//}
									//}
									//if(individualAggreateMap != null && individualAggreateMap.containsKey(component))
									//{
										//List cList = (List)individualAggreateMap.get(component);
										//if(cList !=null && !cList.isEmpty())
										//{
											//String array[] = StringUtils.getTokens(component,":");
											//String individualNick = array[1];
											//int count=cList.size();
											//for(int mic2=0;mic2<count;mic2++)
											//{
												//String agg_comp = (String)cList.get(mic2);
												//agg_comp=agg_comp.substring(0,agg_comp.lastIndexOf(":"));
												//if(count==1)
												//{
													//if(agg_comp.startsWith("Unmanage|"))
													//{
														//auditLogThread.setCurrentValue(individualNick+" component has been deleted from unmanaged aggregate component","$ctype$:"+agg_comp.substring(agg_comp.indexOf("|")+1));
													//}
													//else
													//{
														//auditLogThread.setCurrentValue(individualNick+" component has been deleted from aggregate component","$ctype$:"+agg_comp);
													//}
												//}
												//else
												//{
													//if(agg_comp.startsWith("Unmanage|"))
													//{
														//auditLogThread.setCurrentValue(individualNick+" component has been deleted from unmanaged aggregate components","$ctype$:"+agg_comp.substring(agg_comp.indexOf("|")+1));
													//}
													//else
													//{
														//auditLogThread.setCurrentValue(individualNick+" component has been deleted from aggregate components","$ctype$:"+agg_comp);

													//}
												//}
											//}
										//}
									//}
									//component = component.substring(component.indexOf(":")+1);//vladimir:NULL
									//component = component.substring(0,component.indexOf(":")+1);//vladimir:
									//if(compStr == null)
									//{
										//compStr = "#"+component;
									//}
									//else
									//{
										//compStr += ",#" + component;
									//}
								//}
								////aggregateInfo.deleteFromAggregateTestInfosExcluded(compStr);
								////aggregateInfo.saveFile();
								//String[] agg_test_infos = aggregateInfo.getVariables(EgAggregateInfo.testInfoExclude);
								//if (agg_test_infos != null)
								//{
									//StringTokenizer strTokens = new StringTokenizer(compStr,",");
									//while (strTokens.hasMoreTokens())
									//{
										//String temp_test = strTokens.nextToken();
										//for(int i=0;i<agg_test_infos.length;i++)
										//{
											//if (agg_test_infos[i].indexOf(temp_test) != -1)
											//{
												//EgConfigFilesSync_inner.deleteValue(EgAggregateInfo.testInfoExclude,agg_test_infos[i]);
											//}
										//}
									//}
								//}

								////if empty aggregate components found, remove them from associations
								////UI_COMPONENT_ASSOCIATION
								//String ui_component_association[] = aggregateInfo.getVariables("UI_COMPONENT_ASSOCIATION");
								//Hashtable uICompHt = new Hashtable();
								//if(ui_component_association != null && ui_component_association.length>0)
								//{
									//for(int m=0;m<ui_component_association.length;m++)
									//{
										//String cmp = ui_component_association[m];
										//if(cmp.startsWith("Agg_"+srvtype+":"))
										//{
											//int idx = cmp.indexOf("#");
											//uICompHt.put(cmp.substring(0,idx),cmp);
										//}
									//}
								//}
								////COMPONENT_ASSOCIATION
								//String component_association[] = aggregateInfo.getVariables("COMPONENT_ASSOCIATION");
								//Hashtable CompAssoHt = new Hashtable();
								//if(component_association != null && component_association.length>0)
								//{
									//for(int m=0;m<component_association.length;m++)
									//{
										//String cmp = component_association[m];
										//if(cmp.startsWith("Agg_"+srvtype+":"))
										//{
											//int idx = cmp.indexOf("#");
											//CompAssoHt.put(cmp.substring(0,idx),cmp);
										//}
									//}
								//}
								////ANCHOR_COMPONENT
								//String anchor_components[] = aggregateInfo.getVariables("ANCHOR_COMPONENT");
								//Hashtable anchorHt = new Hashtable();
								//if(anchor_components != null && anchor_components.length>0)
								//{
									//for(int m=0;m<anchor_components.length;m++)
									//{
										//String cmp = anchor_components[m];
										//if(cmp.startsWith("Agg_"+srvtype+":"))
										//{
											//int idx = cmp.indexOf("#");
											//anchorHt.put(cmp.substring(0,idx),cmp);
										//}
									//}
								//}
								//for(int kk=0;kk<aggregateComponents.size();kk++)
								//{
									//String tmp = (String)aggregateComponents.get(kk);
									//List tempList = aggregateInfo.getAssociatedComponents(tmp, true);
									//if(tempList == null || tempList.isEmpty())
									//{
										//if(uICompHt.containsKey(tmp))
										//{
											//EgConfigFilesSync_inner.deleteValue("UI_COMPONENT_ASSOCIATION",(String)uICompHt.get(tmp));
										//}
										//if(CompAssoHt.containsKey(tmp))
										//{
											//EgConfigFilesSync_inner.deleteValue("COMPONENT_ASSOCIATION",(String)CompAssoHt.get(tmp));
										//}
										//if(anchorHt.containsKey(tmp))
										//{
											//EgConfigFilesSync_inner.deleteValue("ANCHOR_COMPONENT",(String)anchorHt.get(tmp));
										//}
									//}
								//}
								////aggregateInfo.saveFile();
								//EgConfigFilesSync_inner.saveFile();
								//EgConfigFilesSync.releaseInstance(EgConfigFilesSync_inner);
								
								//if(!deletedAggComps.isEmpty())
								//{
									//EgCustomDashboardModel customDashboardModel_a=new EgCustomDashboardModel();
									//customDashboardModel_a.createCustomDashboardIniObject();
									//try
									//{
										//int count = deletedAggComps.size();
										//for(int i=0;i<count;i++)
										//{
											//String tmpServer = (String)deletedAggComps.get(i);
											//if(tmpServer.startsWith("Unmanage|"))
											//{
												//tmpServer=tmpServer.substring(tmpServer.indexOf("|")+1);
											//}
											//customDashboardModel_a.deleteUnmanagedComponent(tmpServer);
										//}
									//}
									//catch(Exception e)
									//{
										//e.printStackTrace();
									//}
									//finally
									//{
										//customDashboardModel_a.releaseCustomDashboardIniObj();
									//}
								//}
							//}
						//}
						/* code for auditlog starts */
						if(isManaged || isUnmanaged)
							auditLogThread.sendItToDB();
						/* code for auditlog ends */

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

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

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

										transmitInfoToSecondaryManagers.setData(info);
									}
						}
						aListAlreadyExists.addAll(aListNickAlreadyExists);

						UnmanagedAgentsInfo uai = new UnmanagedAgentsInfo();
						uai.updateAgentDetail(managedIPs, managedNicks);
					}
					else
					{
						//manager.releaseInstance();
					}
				}
				else
				{
					//manager.releaseInstance();
				}
				if (usrCompIniEntries.size() > 0)
				{
					IniFile userCompIniWrite = EgConfigFilesSync.getInstance(userCompMap);
					for (int g=0; g < usrCompIniEntries.size(); g++)
					{
						IniHelper iniHelpr = (IniHelper) usrCompIniEntries.get(g);
						String sub = iniHelpr.getSubject();
						String key = iniHelpr.getVariable();
						userCompIniWrite.deleteValue(sub,key);
					}
					userCompIniWrite.saveFile();
					EgConfigFilesSync.releaseInstance(userCompIniWrite);
				}
			}
			else
			{
				EgConfigFilesSync.releaseInstance(infraIni);
			}
			if (callBasicErrorPage)
			if(status == 2 || usrLicStatus == 3)
			{
				rootObj.put("success","true");
				rootObj.put("requestStatus","failed");
				/* code for auditlog starts */
				if (compList.size() > 1)
				{
					auditLogThread.setCurrentValue("ColumnName", "Components chosen for manage/unmanage/delete");
				}
				else
				{
					auditLogThread.setCurrentValue("ColumnName", "Component chosen for manage/unmanage/delete");
				}
				auditLogThread.setValue("Description","You are exceeding the number of premium agents allowed by your license");
				auditLogThread.sendItToDB();
				/* code for auditlog ends */

				errorObj.put("title",_mapping.getTextDescription("admin.server.Manage/UnManage components"));
				errorObj.put("message1",_mapping.getTextDescription("admin.error.You are exceeding the number of premium agents allowed by your license")+".");
				errorObj.put("message2",_mapping.getTextDescription("admin.discovery.To upgrade your license to support additional premium agents")+", "+_mapping.getTextDescription("admin.error.please contact")+" <b>license@eginnovations.com</b>");
				break;
			}
			else if(status == 3)
			{
				rootObj.put("success","true");
				rootObj.put("requestStatus","failed");
				/* code for auditlog starts */
				if (compList.size() > 1)
				{
					auditLogThread.setCurrentValue("ColumnName", "Components chosen for manage/unmanage/delete");
				}
				else
				{
					auditLogThread.setCurrentValue("ColumnName", "Component chosen for manage/unmanage/delete");
				}
				auditLogThread.setValue("Description","You are exceeding the total number of agents permitted by your license");
				auditLogThread.sendItToDB();
				/* code for auditlog ends */

				errorObj.put("title",_mapping.getTextDescription("admin.server.Manage/UnManage components"));
				errorObj.put("message1",_mapping.getTextDescription("admin.error.You are exceeding the total number of agents permitted by your license")+".");
				errorObj.put("message2",_mapping.getTextDescription("admin.discovery.To upgrade your license to support additional agents")+", "+_mapping.getTextDescription("admin.error.please contact")+" <b>license@eginnovations.com</b>");
				break;
			}
			else if(status == 4)
			{
				rootObj.put("success","true");
				rootObj.put("requestStatus","failed");
				/* code for auditlog starts */
				if (compList.size() > 1)
				{
					auditLogThread.setCurrentValue("ColumnName", "Components chosen for manage/unmanage/delete");
				}
				else
				{
					auditLogThread.setCurrentValue("ColumnName", "Component chosen for manage/unmanage/delete");
				}
				auditLogThread.setValue("Description","You are exceeding the total number of applications permitted by your license");
				auditLogThread.sendItToDB();
				/* code for auditlog ends */

				errorObj.put("title",_mapping.getTextDescription("admin.server.Manage/UnManage components"));
				errorObj.put("message1",_mapping.getTextDescription("admin.error.You are exceeding the total number of applications permitted by your license")+".");
				errorObj.put("message2",_mapping.getTextDescription("admin.discovery.To upgrade your license to support additional applications")+", "+_mapping.getTextDescription("admin.error.please contact")+" <b>license@eginnovations.com</b>");
				break;
			}
			else if(status == 5 || usrLicStatus == 4)
			{
				rootObj.put("success","true");
				rootObj.put("requestStatus","failed");
				/* code for auditlog starts */
				if (compList.size() > 1)
				{
					auditLogThread.setCurrentValue("ColumnName", "Components chosen for manage/unmanage/delete");
				}
				else
				{
					auditLogThread.setCurrentValue("ColumnName", "Component chosen for manage/unmanage/delete");
				}
				auditLogThread.setValue("Description","You are exceeding the total number of network devices permitted by your license");
				auditLogThread.sendItToDB();
				/* code for auditlog ends */

				errorObj.put("title",_mapping.getTextDescription("admin.server.Manage/UnManage components"));
				errorObj.put("message1",_mapping.getTextDescription("admin.error.You are exceeding the total number of network devices permitted by your license")+".");
				errorObj.put("message2",_mapping.getTextDescription("admin.discovery.To upgrade your license to support additional network devices")+", "+_mapping.getTextDescription("admin.error.please contact")+" <b>license@eginnovations.com</b>");
				break;
			}
			else if(status == 6 || usrLicStatus == 5)
			{
				rootObj.put("success","true");
				rootObj.put("requestStatus","failed");
				/* code for auditlog starts */
				if (compList.size() > 1)
				{
					auditLogThread.setCurrentValue("ColumnName", "Components chosen for manage/unmanage/delete");
				}
				else
				{
					auditLogThread.setCurrentValue("ColumnName", "Component chosen for manage/unmanage/delete");
				}
				if(isNamedUsersCert)
				{
					auditLogThread.setValue("Description","You are exceeding the total number of named users permitted by your license");
				}
				else
				{
					auditLogThread.setValue("Description","You are exceeding the total number of concurrent users permitted by your license");
				}
				auditLogThread.sendItToDB();
				/* code for auditlog ends */

				//You are exceeding the total number of named users permitted by your license
				errorObj.put("title",_mapping.getTextDescription("admin.server.Manage/UnManage components"));
				if (isNamedUsersCert)
				{
					errorObj.put("message1",_mapping.getTextDescription("admin.error.You are exceeding the total number of named users permitted by your license")+".");
					errorObj.put("message2",_mapping.getTextDescription("admin.discovery.To upgrade your license to support additional named users")+", "+_mapping.getTextDescription("admin.error.please contact")+" <b>license@eginnovations.com</b>");
				}
				else
				{
					errorObj.put("message1",_mapping.getTextDescription("admin.error.You are exceeding the total number of concurrent users permitted by your license")+".");
					errorObj.put("message2",_mapping.getTextDescription("admin.discovery.To upgrade your license to support additional concurrent users")+", "+_mapping.getTextDescription("admin.error.please contact")+" <b>license@eginnovations.com</b>");
				}
				break;
			}
			if(usrLicStatus == 2)
			{
				rootObj.put("success","true");
				rootObj.put("requestStatus","failed");
				/* code for auditlog starts */
				if (compList.size() > 1)
				{
					auditLogThread.setCurrentValue("ColumnName", "Components chosen for manage/unmanage/delete");
				}
				else
				{
					auditLogThread.setCurrentValue("ColumnName", "Component chosen for manage/unmanage/delete");
				}
				auditLogThread.setValue("Description","You are exceeding the Total/Basic monitors permitted by your license");
				auditLogThread.sendItToDB();
				/* code for auditlog ends */

				errorObj.put("title",_mapping.getTextDescription("admin.server.Manage/UnManage components"));
				errorObj.put("message1",_mapping.getTextDescription("admin.error.You are exceeding the Total/Basic monitors permitted by your license")+".");
				errorObj.put("message2",_mapping.getTextDescription("admin.discovery.To upgrade your license to support additional basic/premium monitors")+", "+_mapping.getTextDescription("admin.error.please contact")+" <b>license@eginnovations.com</b>");
				break;
			}
		}
		oldManServers.clear();
		oldUnmanServers.clear();
		newUnmanServers.clear();
		newManServers.clear();
		finalServers.clear();
		updateServers.clear();
		tmpServers.clear();
		tmpManServers = "";
		tmpManServerswithType = "";
		tmpUnManServers = "";
		tmpUnManServerswithType = "";
		if (rootObj.containsKey("requestStatus"))
		{
			break;
		}
	}
	if (infraIni != null)
	{
		EgConfigFilesSync.releaseInstance(infraIni);
	}
	if (!rootObj.containsKey("requestStatus"))
	{
		String resMsg = "";
		if (fmanServ != null && fmanServ.length()>0 && isManage)
		{
			resMsg = _mapping.getTextDescription("admin.server.The component")+ "&nbsp;'"+fmanServ+"'&nbsp;"+_mapping.getTextDescription("admin.server.has been");
		}
		else if (funmanServ != null && funmanServ.length()>0 && isUnmanage)
		{
			resMsg = _mapping.getTextDescription("admin.server.The component")+ "&nbsp;'"+funmanServ+"'&nbsp;"+_mapping.getTextDescription("admin.server.has been");
		}
		if (compListSize > 1 || currUnMgdCompList.size() > 1 || currMgdCompList.size() > 1 || (isManage && isUnmanage))
		{
			resMsg = _mapping.getTextDescription("admin.server.The chosen components have been");
		}
		if (isManage && isUnmanage)
		{
			resMsg += "&nbsp;" + _mapping.getTextDescription("admin.server.managed/unmanaged successfully");
		}
		else if (isManage)
		{
			resMsg += "&nbsp;" + _mapping.getTextDescription("admin.server.managed successfully");
		}
		else if (isUnmanage)
		{
			resMsg += "&nbsp;" + _mapping.getTextDescription("admin.server.unmanaged successfully");
		}
		if (isProceed != null && isProceed.equalsIgnoreCase("true"))
		{
			resMsg += ". " + "<span style='cursor:pointer;align:left' onclick=\"javascript:appCtn.viewAssociatedEntities('showMod')\">"+_mapping.getTextDescription("admin.filter.Click here")+"&nbsp;<img src='/final/images/spacer.gif' style='cursor:hand;vertical-align:text-bottom;' class='iconClickHere' />&nbsp;</span><span>"+_mapping.getTextDescription("admin.error.to know more about the entities that are affected")+"</span>";
		}
		if (resMsg == null || resMsg.length() == 0)
		{
			resMsg = _mapping.getTextDescription("admin.server.Component has been managed/unmanaged successfully");
		}
		rootObj.put("success","true");
		rootObj.put("requestStatus","success");
		JSONObject resultMsg = new JSONObject();
		resultMsg.put("title",_mapping.getTextDescription("admin.server.Manage/Unmanage components"));
		resultMsg.put("message1",resMsg+".");
		rootObj.put("result",resultMsg);
		rootObj.put("aListAlreadyExists",aListAlreadyExists);
	}
	else
	{
		rootObj.put("errors",errorObj);
	}
	out.println(rootObj.toString());
%>
<%!
	public int containsHowMany(List list1, ArrayList list2)
	{
		int count = 0;
		if(list1 == null || list2 == null)
			return count;
		if(list1.size() == 0 || list2.size() == 0)
			return count;
		for(int i=0;i<list1.size();i++)
		{
			String each = (String)list1.get(i);
			if(list2.contains(each))
			{
				count++;
				if(count == 2)
				{
					break;
				}
			}
		}
		return count;
	}

	public boolean deleteFromDB(String componentName, UpdateAndTransmitTopoInfo topoInfo)
	{
	 return (topoInfo.deleteFromDb("delete from user_serv where serv_name='"+componentName.substring(componentName.indexOf(":")+1)+"' and serv_type='"+componentName.substring(0,componentName.indexOf(":"))+"'"));

	}

	public String getAsRow(Vector vecArray)
	{
		String tmpRow = "";
		for(int i = 0;i<vecArray.size();i++)
		{
			String tmpSite = (String)vecArray.get(i);
			if (tmpRow.equals(""))
			{
				tmpRow = "<b> "+tmpSite;
			}
			else
			{
				tmpRow = tmpRow + ", "+tmpSite;
			}
		}
		tmpRow = tmpRow + " </b>";
		return tmpRow;
	}

	public HashMap monitoringApproachCheck(String componenetStr,String componentType,List agentlessInfoList)
	{
		HashMap result = new HashMap();
		ArrayList restrictedComps = new ArrayList();
		EgSpecsInfo specsinfo1 = new EgSpecsInfo("manager");
		String[] externalTypes = specsinfo1.getAllExternalServerTypes();
		ArrayList extTypesList = new ArrayList();
		if (externalTypes != null)
		{
			extTypesList = new ArrayList(Arrays.asList(externalTypes));
		}

		if (!agentlessInfoList.contains(componentType) && !extTypesList.contains(componentType))
		{
			result.put("hasRestrictedNicks",new Boolean(false));
			result.put("finalServersStr",(componenetStr==null?"":componenetStr));
			result.put("restrictedComps",restrictedComps);
			return result;
		}

		EgExternalInfo externalInfo = new EgExternalInfo("manager");
		String[] remComps = externalInfo.getRemoteComponents();
		ArrayList agentlessCompsList = new ArrayList();
		String nickStr = "";
		if(remComps != null)
		{
			agentlessCompsList = new ArrayList(Arrays.asList(remComps));
		}

		EgDiscInfo egDiscInfo = new EgDiscInfo("manager");
		StringTokenizer componenetStrToken = new StringTokenizer(componenetStr,",");
		while(componenetStrToken.hasMoreTokens())
		{
			String nickNameStr = (String)componenetStrToken.nextToken();
			String nickAlone = nickNameStr;
			int colonIdx = nickAlone.indexOf(":");
			if (colonIdx > 0)
			{
				nickAlone = nickAlone.substring(0,colonIdx);
			}

			List mappedComponentTypesForNicks = egDiscInfo.getServerTypesForNick(nickAlone);
			if (mappedComponentTypesForNicks == null) mappedComponentTypesForNicks = new ArrayList();

			if (mappedComponentTypesForNicks.contains(componentType)) mappedComponentTypesForNicks.remove(componentType);
			if (mappedComponentTypesForNicks.size() == 0)
			{
				nickStr += nickNameStr + ",";
			}
			else
			{
				boolean isExternalCompExist = false;
				Iterator it1 = mappedComponentTypesForNicks.iterator();
				while(it1.hasNext())
				{
					String componentStr = (String)it1.next();
					if (extTypesList.contains(componentStr))
					{
						isExternalCompExist = true;
						break;
					}
				}

				if (agentlessInfoList.contains(componentType) && isExternalCompExist)
				{
					restrictedComps.add(nickAlone);
				}
				else if (extTypesList.contains(componentType) && agentlessCompsList.contains(nickAlone))
				{
					restrictedComps.add(nickAlone);
				}
				else
				{
					nickStr += nickNameStr + ",";
				}
			}
		}
		if (nickStr.indexOf(",") != -1) nickStr = nickStr.substring(0,nickStr.length()-1);
		boolean hasUnkowns = false;
		if (restrictedComps.size() > 0) hasUnkowns = true;

		result.put("hasRestrictedNicks",new Boolean(hasUnkowns));
		result.put("finalServersStr",nickStr);
		result.put("isExternalType",new Boolean(extTypesList.contains(componentType)));
		result.put("restrictedComps",restrictedComps);
		return result;
	}

	private HashMap isValidNickIPMap(String componenetStr,String componentType)
	{
		HashMap result = new HashMap();
		ArrayList restrictedComps = new ArrayList();
		ArrayList removableNicks = new ArrayList();
		if (componenetStr == null || componenetStr.length() == 0)
		{
			result.put("hasRestrictedNicks",new Boolean(false));
			result.put("finalServersStr",(componenetStr==null?"":componenetStr));
			result.put("restrictedComps",restrictedComps);
			return result;
		}

		String nickStr = "";
		String newCompStr = "";
		EgDiscInfo egDiscInfo2 = new EgDiscInfo("manager");
		Hashtable nickIPMap = egDiscInfo2.getNickIpMap();

		IniFile disciverIni = new IniFile(EgInstallInfo.getInstallDir() + "/manager/config/eg_discover.ini");
		StringTokenizer componenetStrToken = new StringTokenizer(componenetStr,",");
		ArrayList nicksList = new ArrayList();
		ArrayList nicksLowList = new ArrayList();
		while(componenetStrToken.hasMoreTokens())
		{
			String nickNameStr = (String)componenetStrToken.nextToken();
			String nickAlone = nickNameStr;
			int colonIdx = nickAlone.indexOf(":");
			if (colonIdx > 0)
			{
				nickAlone = nickAlone.substring(0,colonIdx);
			}
			String tmpNickLower = nickAlone.toLowerCase();
			if (!nicksLowList.contains(tmpNickLower))
			{
				nicksLowList.add(tmpNickLower);
				nicksList.add(nickAlone);
			}
			else
			{
				if(!nicksList.contains(nickAlone))
				{
					if (nickNameStr != null && nickNameStr.endsWith(":NULL"))
					{
						nickNameStr = nickNameStr.substring(0,nickNameStr.indexOf(":NULL"));
					}
					removableNicks.add(nickNameStr);
					continue;
				}
			}
			if (!isNickValid(disciverIni,nickAlone))
			{
				newCompStr += nickNameStr + ",";
				if (nickNameStr != null && nickNameStr.endsWith(":NULL"))
				{
					nickNameStr = nickNameStr.substring(0,nickNameStr.indexOf(":NULL"));
				}
				//restrictedComps.add(nickNameStr);
				removableNicks.add(nickNameStr);
				continue;
			}

			boolean isNew = false;
			String unmanageStr = disciverIni.getValue(componentType,"#Unmanage|"+componentType+":"+nickNameStr);
			if (unmanageStr == null || unmanageStr.length() == 0)
			{
				unmanageStr = disciverIni.getValue(componentType,"#New|"+componentType+":"+nickNameStr);
				isNew = true;
			}
			String hostIP = "";
			if (unmanageStr == null || unmanageStr.length() == 0)
			{
				nickStr += nickNameStr + ",";
				continue;
			}
			else
			{
				StringTokenizer unmanageCompToken = new StringTokenizer(unmanageStr,",");
				String serverStr = unmanageCompToken.nextToken();
				hostIP = unmanageCompToken.nextToken();
			}

			if (nickIPMap.get(nickAlone) == null)
			{
				nickStr += nickNameStr + ",";
				continue;
			}
			else if (nickIPMap.get(nickAlone).toString().equals(hostIP))
			{
				nickStr += nickNameStr + ",";
				continue;
			}
			else
			{
				if (isNew) newCompStr += nickNameStr + ",";
				if (nickNameStr != null && nickNameStr.endsWith(":NULL"))
				{
					nickNameStr = nickNameStr.substring(0,nickNameStr.indexOf(":NULL"));
				}
				restrictedComps.add(nickNameStr);
			}
		}
		if (nickStr.endsWith(",")) nickStr = nickStr.substring(0,nickStr.length()-1);
		if (newCompStr.endsWith(",")) newCompStr = newCompStr.substring(0,newCompStr.length()-1);
		boolean hasUnkowns = false;
		if (restrictedComps.size() > 0 || removableNicks.size() > 0) hasUnkowns = true;

		result.put("hasRestrictedNicks",new Boolean(hasUnkowns));
		result.put("finalServersStr",nickStr);
		result.put("restrictedComps",restrictedComps);
		result.put("newCompStr",newCompStr);
		result.put("removableNicks",removableNicks);
		return result;
	}

	private boolean isNickValid(IniFile tmpFile, String nickName)
	{
		boolean isAllowed = true;
		boolean isChecked = false;
		String[] subjects = tmpFile.getSubjects();
		int scount = subjects.length;
		for (int j = 0;j<scount;j++)
		{
			String[] servers = tmpFile.getVariables(subjects[j]);
			if (servers == null) continue;
			int vcount = servers.length;
			for(int i=0; i<vcount; i++)
			{
				if(servers[i].startsWith("Format:") || servers[i].startsWith("#"))
				{
					continue;
				}
				else
				{
					if (servers[i].indexOf(":") == -1) continue;
					String srvNick = servers[i].substring(servers[i].indexOf(":")+1);
					if (srvNick.indexOf(":") != -1) srvNick = srvNick.substring(0,srvNick.indexOf(":"));
					if (srvNick.equalsIgnoreCase(nickName))
					{
						if (srvNick.equals(nickName))
						{
							isAllowed = true;
							isChecked = true;
							break;
						}
						else
						{
							isAllowed = false;
							isChecked = true;
							break;
						}
					}
				}
			}
			if (!isAllowed && isChecked) break;
			//if (isChecked) break;
		}
		return isAllowed;
	}

	public ArrayList getUserId(ArrayList limitedUserList, String mgdComp)
	{
		String givenSrvType = (mgdComp.indexOf(":") > -1) ? mgdComp.substring(0,mgdComp.indexOf(":")) : mgdComp;
		String givenNick = (mgdComp.indexOf(":") > -1) ? mgdComp.substring(mgdComp.indexOf(":")+1) : mgdComp;
		IniFile userCompMapIni = new IniFile(EgConfigInfo.egMgrConfigDir + "eg_usercompmapping.ini");
		ArrayList userId_List = new ArrayList();
		String[] subjects = userCompMapIni.getSubjects();
		if(subjects != null)
		{
			int subLen = subjects.length;
			for(int s=0; s<subLen; s++)
			{
				if(limitedUserList.contains(subjects[s]))
				{
					String[] variables = userCompMapIni.getVariables(subjects[s]);
					if(variables != null)
					{
						int varLen = variables.length;
						for(int v=0; v<varLen; v++)
						{
							String tmpComp = variables[v];
							if (tmpComp.startsWith("#"))
							{
								String tempCompVar = tmpComp.substring(tmpComp.indexOf("|")+1);
								String srvrType = tempCompVar.substring(0,tempCompVar.indexOf(":"));
								String nick = tempCompVar.substring(tempCompVar.indexOf(":")+1);
								if(srvrType.equals(givenSrvType) && nick.equals(givenNick))
								{
									if(!userId_List.contains(subjects[s]))
									{
										userId_List.add(subjects[s]);
									}
								}
							}
						}
					}
				}
			}
		}
		return userId_List;
	}

	public ArrayList getUserIdForUnmanage(ArrayList limitedUserList, Hashtable allUsersCompMap, String mgdComp)
	{
		ArrayList userId_List = new ArrayList();
		String givenSrvType = (mgdComp.indexOf(":") > -1) ? mgdComp.substring(0,mgdComp.indexOf(":")) : mgdComp;
		if(limitedUserList != null)
		{
			userId_List = getUserId(limitedUserList,mgdComp);
			int limitedUserListLen = limitedUserList.size();
			for(int s=0; s<limitedUserListLen; s++)
			{
				String subject = (String)limitedUserList.get(s);
				ArrayList usrMgdVarsList = getUserCompsNick((ArrayList)allUsersCompMap.get(subject),givenSrvType);
				if(usrMgdVarsList != null)
				{
					if(usrMgdVarsList.contains(mgdComp))
					{
						if(!userId_List.contains(subject))
						{
							userId_List.add(subject);
						}
					}
				}
			}
		}
		return userId_List;
	}

	public ArrayList getUserCompsNick(ArrayList compMapSrvList, String givenSrvType)
	{
		ArrayList resultList = new ArrayList();
		if(compMapSrvList != null && givenSrvType != null && !givenSrvType.equals(""))
		{
			int compListLen = compMapSrvList.size();
			for (int x=0; x<compListLen; x++)
			{
				String tempCompMapVal = compMapSrvList.get(x).toString();
				String tempCompMapValStr = tempCompMapVal.substring(0,tempCompMapVal.indexOf(":"));
				if(tempCompMapValStr.equals(givenSrvType))
				{
					resultList.add(tempCompMapVal);
				}
			}
		}
		return resultList;
	}

	//Deleting agent nick at eg_uuid.ini when component nick matches with agent nick during component manage.
	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);
		}
	}

	public ArrayList getRefinedUsers(EgUuidInfo uuidInfo, ArrayList allUsersList)
	{
		ArrayList resultList = new ArrayList();
		ArrayList refinedUsersList = new ArrayList();
		ArrayList refinedOrgsList = new ArrayList();
		if (allUsersList == null || allUsersList.size() == 0)
		{
			return resultList;
		}
		int lis_size = allUsersList.size();
		for (int n=0; n<lis_size; n++)
		{
			String usr_name = allUsersList.get(n).toString().trim();
			if (uuidInfo.isUser(usr_name) && uuidInfo.hasOURole(usr_name))
			{
				ArrayList temp_co_usrlist = uuidInfo.getSharedRoleCoUsersList(usr_name);
				String temp_usr_name = temp_co_usrlist.get(0).toString();
				if (!refinedUsersList.contains(temp_usr_name))
				{
					refinedUsersList.add(temp_usr_name);
				}
			}
			else if (uuidInfo.isUser(usr_name) && !uuidInfo.hasOURole(usr_name))
			{
				if (!refinedUsersList.contains(usr_name))
				{
					refinedUsersList.add(usr_name);
				}
			}
			else if (uuidInfo.isOrg(usr_name))
			{
				if (!refinedOrgsList.contains(usr_name))
				{
					refinedOrgsList.add(usr_name);
				}
			}
		}
		for (int y=0; y<refinedUsersList.size(); y++)
		{
			String temp_user = refinedUsersList.get(y).toString().trim();
			String temp_dep_OU = uuidInfo.getDirectDependentOU(temp_user);
			refinedOrgsList.remove(temp_dep_OU);
		}
		if (refinedUsersList != null && refinedUsersList.size()>0)
		{
			resultList.addAll(refinedUsersList);
		}
		if (refinedOrgsList != null && refinedOrgsList.size()>0)
		{
			resultList.addAll(refinedOrgsList);
		}
		return resultList;
	}
%>


