<%
/*
*		Name			:	EgHostCheck.jsp
*		Purpose			:	To list the host names given for a particular ip address and check if the given hostname is present in the host names list.
							If present we alert the user about the hostname and ask for confirmation for using the same host name for the server or not.
*		CreationDate	:	18/12/2001
*/
%>
<%@ include file="../../EgTrackerAJSON.jsp"%>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>

<%@ page import="com.egurkha.ini.IniUI"%>
<%@ page import="com.egurkha.util.StringUtils"%>
<%@ page import="com.egurkha.admin.AuditLogThread"%>
<%@ page import="net.sf.json.JSONObject"%>
<%@ page import="net.sf.json.JSONArray"%>
<%@ page import= "egurkha.EgUIUtils"%>
<%
	response.setHeader("Cache-Control","no-store");
	response.setHeader("Pragma","no-cache");
	response.setDateHeader("Expires", -1);
	response.setContentType("application/json;charset=UTF-8");
%>

<%
	JSONObject rootJSON = new JSONObject();
	rootJSON.put("success","true");
	JSONObject  hiddens = new JSONObject();
	IniFile egdisc = new IniFile(EgConfigInfo.egMgrConfigDir+"eg_discover.ini");
	IniFile extIni = new IniFile(EgConfigInfo.egMgrConfigDir+"eg_external.ini");
	Vector temp_v_host_name = null;
	Vector v_host_name1 = new Vector();
	Vector v_host_name_nocase = new Vector();
	//component case issue. dont allow components to have same name with different case
	EgDiscInfo egDiscInfo = new EgDiscInfo("manager");
	ArrayList al_all_hosts=egDiscInfo.getAllHostsWithPort();
	String s_host_ip = "";
	String s_host_name = "";
	s_host_ip = request.getParameter("hostip");
	s_host_name = request.getParameter("hostname");
	String isRum = request.getParameter("isRumServer");
	String rumAgent = request.getParameter("rumRemAgent");
	String rumURL = request.getParameter("rumUrl");
	String dispCompName = request.getParameter("dispCompName");
	String mserver = request.getParameter("modifyserver");
	boolean isRumServer = false;
	boolean isNodeServer = false;
	String monitorLastSession="";
	String newUrlLink="";
	String strCompType="";
	String strHostName="";
	String oldNick="";

	if(isRum != null && isRum != "")
	{
		if(isRum.equals("yes"))
		{
			isRumServer = true;
			s_host_ip = "0.0.0.0";
			s_host_name = request.getParameter("rumNickName");
		}
	}
	String s_server_name = request.getParameter("server");
	String s_server_type = request.getParameter("stype");
	if(s_server_type != null && s_server_type.equalsIgnoreCase("nodejs"))
	{
		isNodeServer = true;
	}
	String s_sid=request.getParameter("sid");
	String oldhostname = request.getParameter("oldhostname");
	String port_for_asset = request.getParameter("hportno");
	String sPortNo = request.getParameter("sportno");
	if (s_server_name!= null && s_server_name.equalsIgnoreCase("new"))
		port_for_asset = sPortNo;

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

	String lowerCaseHostName=request.getParameter("lowerCaseHostName");
	String newHostName = request.getParameter("newHostName");
	String siteflag = request.getParameter("siteflag");
	String treeViewSrc = request.getParameter("treeViewSrc");
	String fromResultPage = request.getParameter("fromResultPage");
	String serverNameWithPort = s_host_name;
	String user_id = _user.getLoginID();
	EgRoleInfo egRoleInfo = EgRoleInfo.getInstance(session.getId(),user_id);

	String[] nickAloneTypes = extIni.getVariables("NickName_Alone_Servers");
	List nickAloneTypesList = new ArrayList();
	if (nickAloneTypes != null)
	{
		nickAloneTypesList = Arrays.asList(nickAloneTypes);
	}
	if (nickAloneTypesList.contains(s_server_type) && (s_host_ip == null || s_host_ip.trim().equals("")) )
	{
		s_host_ip = s_host_name;
	}

	if (s_server_name != null && s_server_name.equals("new"))
	{
		oldhostname = "";
	}
//	String mserver = request.getParameter("modifyserver");
	boolean isModifyServer = false;
	if(mserver != null && mserver.equals("true"))
	{
		isModifyServer = true;
	}
	if (port_for_asset == null || port_for_asset == "null")
		serverNameWithPort = s_host_name+":NULL";
	else
		serverNameWithPort = s_host_name+":"+port_for_asset;

	String selectedServerGroup = request.getParameter("selectedServerGroup");
	if (selectedServerGroup == null)
	{
		selectedServerGroup = "";
	}
	/*....... For Auto Topology .... (Start)*/
	String frmTopology = request.getParameter("frmTopology");
	String topoSegName = request.getParameter("topoSegName");
	String initialPortNo = request.getParameter("portnumber");
	/*....... For Auto Topology .... (End)*/
	

	if (lowerCaseHostName!=null && lowerCaseHostName.equals("true"))
		s_host_name = newHostName;

	EgAggregateInfo aggregateInfo = new EgAggregateInfo("manager"); //skm
	EgExternalInfo externalInfo = new EgExternalInfo("manager");
	Vector aggTypes = aggregateInfo.getAggregateTypes();
	boolean exist=false;

	egurkha.EgUIUtils uiUtils = new egurkha.EgUIUtils();
	v_host_name1 = uiUtils.getAllHostsForIp(s_host_ip,s_host_name,splCompList);
	ArrayList userComponent = egRoleInfo.getAllServerNicks();
	Vector ext = externalInfo.getAllExternalHostsForIP(s_host_ip,s_host_name);
	Vector rem = externalInfo.getAllRemoteHostsForIP(s_host_ip,s_host_name);

	if(v_host_name1 == null)
		v_host_name1 = new Vector();

	Vector  v_host_name = new Vector();
	if (v_host_name1!=null)
	{
		for(int i=0;i<v_host_name1.size();i=i+2)
		{
			String curElmt = ((String)v_host_name1.get(i)).toLowerCase();
			String boolVal = ((String)v_host_name1.get(i+1)).toLowerCase();
			if((userComponent.contains(curElmt) || boolVal.equals("false")) && !curElmt.equals(oldhostname))
				//1.userComponent.contains(curElmt) --> to check the nick name alerady associated to userTo display only the compo's associated to the user / its org.
				//2 .if ip address for nick name found --> to check the nick name already associated, if so then check boolean variable.
			{
				v_host_name.add(curElmt);
				v_host_name.add(boolVal);
			}
		}
	}

	temp_v_host_name = new Vector(v_host_name1);

	if(ext != null)
		temp_v_host_name = getUniqueHosts(temp_v_host_name,ext);

	if(rem != null)
		temp_v_host_name = getUniqueHosts(temp_v_host_name,rem);


	if (v_host_name!=null)
	{
		for (int i=0; i<v_host_name.size(); i++)
		{
			String thisName = ((String)v_host_name.get(i)).toLowerCase();
			v_host_name_nocase.add(thisName);
		}
	}

	int nameIndex = v_host_name_nocase.indexOf(s_host_name.toLowerCase());

	if(v_host_name.size() > 0)
	{
		for(int vi=0;vi<v_host_name.size();vi++)
		{
			String host_na=(String)v_host_name_nocase.get(vi);
			exist=s_host_name.toLowerCase().equalsIgnoreCase(host_na);
			if(exist)
				break;
		}
	}
	if(isRumServer || isNodeServer)
		v_host_name_nocase = new Vector();
	if(!exist)
	{
		for(int vi=0;vi<temp_v_host_name.size();vi=vi+2)
		{
			String host_na=(String)temp_v_host_name.get(vi);
			exist=s_host_name.equalsIgnoreCase(host_na);
			if(exist)
			{
				nameIndex = (nameIndex == -1?vi:nameIndex);
				break;
			}
		}
	}


	boolean nickManaged =false;
	Hashtable nickIPMap=egDiscInfo.getNickIpMap(true,"");
	String existingHostOrIP = "";
	ArrayList allNicks=egDiscInfo.getAllNicks();
	boolean newNickAdded = !allNicks.contains(s_host_name.toLowerCase());
	Enumeration keys = nickIPMap.keys();
	while (keys.hasMoreElements())
	{
		String thisKey = (String) keys.nextElement();
		if (thisKey.equalsIgnoreCase(s_host_name))
		{
			String thisIp = (String)nickIPMap.get(thisKey);
			if (!thisIp.equals(s_host_ip))
			{
				existingHostOrIP = thisIp;
				nickManaged = true;
			}
		}
	}
	ArrayList allNicksList = new ArrayList(nickIPMap.keySet());
	ArrayList allNicksListLower = new ArrayList();
	int nickListSize = allNicksList.size();
	for (int a=0; a <nickListSize ; a++)
	{
		String nickLower = allNicksList.get(a).toString().toLowerCase();
		allNicksListLower.add(nickLower);
	}
	boolean isCompAlreadyExist = egDiscInfo.isComponentExist(s_server_type,serverNameWithPort);

	EgUuidInfo uuidInfo = new EgUuidInfo();
	EgCertUsage egCertUsage = new EgCertUsage();
	ArrayList usersList = egCertUsage.getAllLimitedCompAccessUsers(true);
	boolean isLimitedAdmin = (usersList != null && usersList.contains(user_id));
	boolean isMspModel = EgUuidInfo.isMspModel();
	boolean shareNickAcrossOU = EgUuidInfo.shareNickAcrossOU();
	ArrayList allCompNicks = egRoleInfo.getAllServerNicks();
	boolean isNickShared = false;
	
	EgUserRole role = EgUserRole.getRoleObject(_user.getLoginType());
	long adminPerm = role.getAdminPerm();

	long COMP_ADD_MODIFY = EgUserPermission.COMPONENT_MANAGEMENT;
	boolean CompMgmt = ((adminPerm & COMP_ADD_MODIFY) == COMP_ADD_MODIFY);

	long EXT_REM_CONFIG= EgUserPermission. EXTERNAL_REMOTE_AGENT_CONFIG;
	boolean AgentMgmt = ((adminPerm & EXT_REM_CONFIG) == EXT_REM_CONFIG);

	if(!isLimitedAdmin && ( CompMgmt || AgentMgmt ) && !(oldhostname.equals(s_host_name)))  //only for admin with AllComponentAccess and Rmt/Ext-agent Managemtent permission
	{
		EgUuidInfo uuidinfo = new EgUuidInfo();
		ArrayList OrgWithGivenNick = new ArrayList();
		JSONArray OrgWithNickGiven = new JSONArray();
		OrgWithGivenNick=uuidinfo.getSuperUsersOfGivenNick(s_host_name);
		if(OrgWithGivenNick!=null && OrgWithGivenNick.size() > 0)
		{
			OrgWithNickGiven.add(OrgWithGivenNick);
			rootJSON.put("AlreadyAsoociatedFlag",true);
			rootJSON.put("CompoAlreadyAssoUser",OrgWithNickGiven);
		}
	
	}
	if(isMspModel)// && !shareNickAcrossOU)
	{
		ArrayList usersSharedAgents = new ArrayList();
		Hashtable orgUsersNickMap = uuidInfo.getAllUsersNickMap(true,true);
		String s_host_name_LowerCase = s_host_name.toLowerCase();
		if(orgUsersNickMap != null)
		{
			String user_name = user_id;
			if(!orgUsersNickMap.containsKey(user_name))
			{
				user_name = uuidInfo.getSuperOU(user_id);
			}
			if(user_name != null && (!user_id.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();
								nicksListLower.add(nickLower);
							}
							if(nicksListLower.contains(s_host_name_LowerCase))
							{
								usersSharedAgents.add(orgName);
							}
						}
					}
				}
			}
		}
		if(usersSharedAgents != null && usersSharedAgents.size() > 0)
		{
			isNickShared = true;
			String super_org = uuidInfo.isSuperOrg(user_id) ? user_id : uuidInfo.getSuperOU(user_id);
			String suggested_nick = uuidInfo.getUniqueNickName(egDiscInfo,s_host_name);
			rootJSON.put("requestStatus","failed");
			JSONObject obj = new JSONObject();
			obj.put("error_Title",_mapping.getTextDescription("admin.server.Add/Modify Component"));
			obj.put("error_Msg_Count","2");
			
			if(isModifyServer && !v_host_name_nocase.contains(s_host_ip.toLowerCase()))
			{
				String hostname = "";
				for(int i=1;i < temp_v_host_name.size();i=i+2)
				{
					if(((String)temp_v_host_name.get(i)).equals("false"))
					{
						hostname = (String)temp_v_host_name.get(i-1);
						break;
					}
				}
				rootJSON.put("error_type","alert");
				obj.put("error_Msg_1",_mapping.getTextDescription("admin.server.The nick name")+" ("+s_host_name+") "+_mapping.getTextDescription("admin.server.you are trying to add/modify is already associated with a component")+" ("+hostname+").");
				obj.put("error_Msg_2",_mapping.getTextDescription("admin.server.Please provide a different nick name")+".");
				rootJSON.put("error_Info",obj);
			}
			else
			{
				rootJSON.put("error_type","confirmNickSuggestion");
				obj.put("error_Msg_1",_mapping.getTextDescription("admin.error.The nick name")+" ("+s_host_name+") "+_mapping.getTextDescription("admin.error.you are trying to add/modify is already existing")+". ");
				obj.put("error_Msg_2",_mapping.getTextDescription("admin.server.Would you like to use the nick name")+" '"+suggested_nick+"'?");
				obj.put("IP",s_host_ip);
				obj.put("nickName",suggested_nick);

				String url = "EgnewserverpJson.jsp?action=singleserver&hostname="+EgURLEncoder.encode(suggested_nick,"UTF-8")+"&"+request.getQueryString()+"&treeViewSrc="+treeViewSrc+"&servertype="+EgURLEncoder.encode(s_server_type,"UTF-8")+"&servername="+EgURLEncoder.encode(serverNameWithPort,"UTF-8")+"&hostIp="+s_host_ip+"&oldhostname="+EgURLEncoder.encode(oldhostname,"UTF-8");
				if(frmTopology!=null && frmTopology.equals("yes"))
				{
					url = url + "&topoSegName="+EgURLEncoder.encode(topoSegName,"UTF-8")+"&initPort="+initialPortNo;
				}
				obj.put("forward_URL",url);
				rootJSON.put("error_Info",obj);

				hiddens.put("treeViewSrc",treeViewSrc);
				hiddens.put("fromResultPage",fromResultPage);
				hiddens.put("server_type",s_server_type);
				hiddens.put("initPort",initialPortNo);
				Enumeration en = request.getParameterNames();
				while(en.hasMoreElements())
				{
					String name = (String)en.nextElement();
					String [] val2 = request.getParameterValues(name);
					String val ="";
					if (val!=null && val2.length==1)
						val = request.getParameter(name);
					else
						val = com.egurkha.util.StringUtils.getUniqueArrayAsString(val2);
					hiddens.put(name,val);
				}
				rootJSON.put("hiddenValues",hiddens);
			}
			out.println(rootJSON);
			return;
		}
	}

	/*
	 * Client Emulation Types - nick sharing validation - Starts
	 */
	if(s_host_name != null)
	{
		ArrayList emulatedList = externalInfo.getEmulatedTypes();
		boolean emuNickFound = false;
		boolean nonEmuNickFound = false;
		if(emulatedList.contains(s_server_type))
		{
			ArrayList nonEmulatedNickList = egDiscInfo.getAllHostsExceptTypes(emulatedList);
			if(nonEmulatedNickList != null && nonEmulatedNickList.size()>0)
			{
				for(int e=0; e<nonEmulatedNickList.size(); e++)
				{
					String tempNonEmuNick = (String)nonEmulatedNickList.get(e);
					if(s_host_name.equalsIgnoreCase(tempNonEmuNick))
					{
						nonEmuNickFound = true;
						break;
					}
				}
			}
		}
		else
		{
			ArrayList emulatedNickList = egDiscInfo.getAllHostsOfTypes(emulatedList);
			if(emulatedNickList != null && emulatedNickList.size()>0)
			{
				for(int e=0; e<emulatedNickList.size(); e++)
				{
					String tempEmuNick = (String)emulatedNickList.get(e);
					if(s_host_name.equalsIgnoreCase(tempEmuNick))
					{
						emuNickFound = true;
						break;
					}
				}
			}
		}
		if(emuNickFound || nonEmuNickFound)
		{
			String msg = "admin.server.Since the nickname '"+s_host_name+"' is already associated with emulated component types, you are not allowed to use the same for other component types";
			if(nonEmuNickFound)
			{
				msg = "admin.server.Since the nickname '"+s_host_name+"' is already associated with non emulated component types, you are not allowed to use the same for emulated component types";
			}
			rootJSON.put("requestStatus","failed");
			rootJSON.put("error_type","alert");
			JSONObject obj = new JSONObject();
			obj.put("error_Title",_mapping.getTextDescription("admin.server.Add/Modify Component"));
			obj.put("error_Msg_Count","2");
			obj.put("error_Msg_1",_mapping.getTextDescription("admin.server.Possible reason")+":");
			obj.put("error_Msg_2",_mapping.getTextDescription(msg)+".");
			rootJSON.put("error_Info",obj);
			out.println(rootJSON);
			return;
		}
	}
	/*
	 * Client Emulation Types - nick sharing validation - Ends
	 */

	if (!isNickShared && !newNickAdded && !isCompAlreadyExist && !isModifyServer) // Existing nick name
	{
		if (!allNicksList.contains(s_host_name)) // Existing nick name but case differs
		{
			int idx = allNicksListLower.indexOf(s_host_name.toLowerCase());
			if (idx > -1)
			{
				String existingNick = allNicksList.get(idx).toString();
				String existingIP = nickIPMap.get(existingNick).toString();
				List serverList = egDiscInfo.getServerTypesForNick(existingNick,true,"");
				String componentTypeStr = "";
				if(serverList.isEmpty()) // when nick name associate to agent 
				{
					String[] extAgt = externalInfo.getAllExternalAgents();
					List extAgtList  = new ArrayList();
					if(extAgt!=null)
					{
						extAgtList= Arrays.asList(extAgt);
					}
					if(extAgtList.contains(existingNick))
					{
						componentTypeStr = "Agent Type :  External Agent";
					}
					else
					{
						componentTypeStr = "Agent Type : Remote Agent";
					}
				}
				if(serverList != null && !serverList.isEmpty())
				{
					componentTypeStr = "Component Type : ";
					int sSize = serverList.size();
					for (int s=0; s<sSize; s++)
					{
						String compType = (String)serverList.get(s);
						componentTypeStr += _mapping.getComponentTypeDescription(compType)+", ";
						if (s == 2)
						{
							break;
						}
					}
					if (sSize > 3)
					{
						componentTypeStr +="...";
					}
				} 
				componentTypeStr = componentTypeStr.trim();
				if (componentTypeStr.endsWith(","))
				{
					componentTypeStr = componentTypeStr.substring(0,componentTypeStr.length()-1);
				}
				rootJSON.put("requestStatus","failed");
				rootJSON.put("error_type","confirm");
				JSONObject obj = new JSONObject();
				obj.put("error_Title",_mapping.getTextDescription("admin.server.Add/Modify Component"));
				obj.put("error_URL","");
				obj.put("error_Msg_Count","2");
				obj.put("error_Msg_1",_mapping.getTextDescription("admin.error.The nick name")+" ("+s_host_name+") "+_mapping.getTextDescription("admin.error.you are trying to add is already associated in the following manner")+"."); 
				obj.put("IP",existingIP);
				obj.put("nickName",existingNick);
				obj.put("compTypes",componentTypeStr);
				obj.put("error_Msg_2",_mapping.getTextDescription("admin.server.Do you wish to use this existing  Host IP/name and Nick name for the component")+"?");
				//obj.put("error_Msg_3",_mapping.getTextDescription("admin.server.to choose a different Nick name please click Cancel"));

				String	ur = "EgnewserverpJson.jsp?action=singleserver&hostname="+EgURLEncoder.encode(existingNick,"UTF-8")+"&"+request.getQueryString()+"&treeViewSrc="+treeViewSrc+"&servertype="+EgURLEncoder.encode(s_server_type,"UTF-8")+"&servername="+EgURLEncoder.encode(serverNameWithPort,"UTF-8")+"&hostIp="+existingNick+"&oldhostname="+EgURLEncoder.encode(oldhostname,"UTF-8");
				if(frmTopology!=null && frmTopology.equals("yes"))
				{
					ur = ur + "&topoSegName="+EgURLEncoder.encode(topoSegName,"UTF-8")+"&initPort="+initialPortNo;
				}
									
				obj.put("forward_URL",ur);
				rootJSON.put("error_Info",obj);

				hiddens.put("treeViewSrc",treeViewSrc);
				hiddens.put("fromResultPage",fromResultPage);
				hiddens.put("server_type",s_server_type);
				hiddens.put("initPort",initialPortNo);

				Enumeration en = request.getParameterNames();
				while(en.hasMoreElements())
				{
					String name = (String)en.nextElement();
					String [] val2 = request.getParameterValues(name);
					String val ="";
					if (val!=null && val2.length==1)
						val = request.getParameter(name);
					else
						val = com.egurkha.util.StringUtils.getUniqueArrayAsString(val2);
					hiddens.put(name,val);
				}

				rootJSON.put("hiddenValues",hiddens);
				out.println(rootJSON);
				return;
			}
		}		
	}
	else if (!isNickShared && isModifyServer)
	{
		oldNick = oldhostname;
		String newNick = s_host_name;
		String newNickLower = s_host_name.toLowerCase();
		
		monitorLastSession=(String)session.getAttribute("monitorLastSession");
		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);
			}
			
			if(urlLink!=null && urlLink.trim().length()>0)
			{
				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 != null && reqparam.equals("comptype"))
					{
						String compType = paramValue;
						if(compType != null && compType.trim().length()>0)
						{
							strCompType=com.eg.EgURLDecoder.decode(compType, "UTF-8");
						}
					}
					else if(reqparam.equals("host"))
					{
						String hostValue = paramValue;
						if(hostValue != null && hostValue.trim().length()>0)
						{
							String hostName=com.eg.EgURLDecoder.decode(hostValue, "UTF-8");
							if(hostName.indexOf(':') == -1)
							{
								strHostName=hostName;
							}
							else
							{
								strHostName=hostName.substring(0,hostName.indexOf(':'));
							}
						}
					}
				}
			}
		}


		ArrayList allNicksLower = new ArrayList();
		for (int a=0; a<allNicksList.size(); a++)
		{
			String nick = allNicksList.get(a).toString().toLowerCase();
			allNicksLower.add(nick);
		}
		if (oldNick.equalsIgnoreCase(newNick))
		{
			if (allNicksLower.contains(newNickLower) && !allNicksList.contains(newNick))
			{
				String existing = allNicksList.get(allNicksLower.indexOf(newNickLower)).toString();
				rootJSON.put("requestStatus","failed");
				rootJSON.put("error_type","alert");
				JSONObject obj = new JSONObject();
				obj.put("error_Title",_mapping.getTextDescription("admin.server.Add/Modify Component"));
				obj.put("error_Msg_Count","2");
				obj.put("error_Msg_1",_mapping.getTextDescription("admin.error.The nick name")+" ("+newNick+") "+_mapping.getTextDescription("admin.error.you are trying to add is already existing in different case")+" ("+existing+") under same type.");
				obj.put("error_Msg_2",_mapping.getTextDescription("admin.server.Please choose a different nick name"));
				rootJSON.put("error_Info",obj);
				out.println(rootJSON);
				return;
			}
		}
	}

	/* 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","Add/Modify Servers");
	auditLogThread.setValue("Activity","Server Configuration");
	/* code for auditlog ends */
	
	String vars[] = egdisc.getVariables(s_server_type);
	ArrayList newUnmangeNicks = new ArrayList();
	if (vars != null)
	{
		for(int k=0; k<vars.length; k++)
		{
			String var = vars[k];
			if(var.startsWith("#"))
			{
				StringTokenizer st = new StringTokenizer(var,":");
				st.nextToken(); // Type
				String nick = st.nextToken();
				nick =nick.toLowerCase();
				if (!newUnmangeNicks.contains(nick))
				{
					newUnmangeNicks.add(nick);
				}
			}
		}
	}
	String nickAlone = s_host_name;
	int colonIdx = nickAlone.indexOf(":");
	if (colonIdx > 0)
	{
		nickAlone = nickAlone.substring(0,colonIdx);
	}
	String[] remComps = externalInfo.getRemoteComponents();
	ArrayList agentlessCompsList = new ArrayList();
	if(remComps != null)
	{
		agentlessCompsList = new ArrayList(Arrays.asList(remComps));
	}
	ArrayList extCompsList = egDiscInfo.getAllExternalHosts();
	ArrayList agentBasedCompsList = egDiscInfo.getAllComponentNicks(false);
	agentBasedCompsList.removeAll(agentlessCompsList);
	agentBasedCompsList.removeAll(extCompsList);
	agentBasedCompsList.removeAll(newUnmangeNicks);
	String remoteType = request.getParameter("enableRemoteAgent");
	EgSpecsInfo specsInfo = new EgSpecsInfo("manager");
	String[] externalTypes = specsInfo.getAllExternalServerTypes();
	ArrayList extTypesList = new ArrayList();
	if (externalTypes != null)
	{
		extTypesList = new ArrayList(Arrays.asList(externalTypes));
	}
	boolean isExternalComp = false;
	boolean isAgentlessComp = false;
	boolean isAgentBasedComp = false;
	if (extTypesList.contains(s_server_type))
	{
		isExternalComp = true;
	}
	if (remoteType != null && remoteType.equalsIgnoreCase("true"))
	{
		isAgentlessComp = true;
	}
	if (!isExternalComp && !isAgentlessComp)
	{
		isAgentBasedComp = true;
	}

	boolean canCheck = true;
	if(!isNickShared && isModifyServer)
	{
		List servTypesList = egDiscInfo.getServerTypesForNick(nickAlone);
		if(servTypesList != null && servTypesList.size() < 2 && servTypesList.contains(s_server_type))
		{
			canCheck = false;
		}
	}
	if(canCheck)
	{
		if(agentlessCompsList.contains(nickAlone) && (isAgentBasedComp || isExternalComp))
		{
			rootJSON.put("requestStatus","failed");
			rootJSON.put("error_type","alert");
			JSONObject obj = new JSONObject();
			obj.put("error_Title",_mapping.getTextDescription("admin.server.Add/Modify Component"));
			obj.put("error_Msg_Count","2");
			obj.put("error_Msg_1",_mapping.getTextDescription("admin.server.Possible reason")+":");
			if (isModifyServer)
			{
				obj.put("error_Msg_2",_mapping.getTextDescription("admin.server.You cannot change the monitoring approach of this component, because its nick name has already been assigned to an agentless component")+".");
			}
			else
			{
				List serverList = egDiscInfo.getServerTypesForNick(s_host_name);
					String componentTypeStr = "";
					if(serverList != null)
					{
						int sSize = serverList.size();
						for (int s=0; s<sSize; s++)
						{
							String compType = (String)serverList.get(s);
							componentTypeStr += _mapping.getComponentTypeDescription(compType)+", ";
							if (s == 2)
							{
								break;
							}
						}
						if (sSize > 3)
						{
							componentTypeStr +="...";
						}
					} 
					componentTypeStr = componentTypeStr.trim();
					if (componentTypeStr.endsWith(","))
					{
						componentTypeStr = componentTypeStr.substring(0,componentTypeStr.length()-1);
					}
				obj.put("error_Msg_2",_mapping.getTextDescription("admin.server.You are trying to add a component with a nick name that has already been assigned to an agentless component under the component type (")+componentTypeStr+"). "+_mapping.getTextDescription("admin.server.Please use a different nick name")+".");
			}
			rootJSON.put("error_Info",obj);
			out.println(rootJSON);
			return;
		}
		else if (isAgentlessComp && (agentBasedCompsList.contains(nickAlone) || extCompsList.contains(nickAlone)))
		{
			rootJSON.put("requestStatus","failed");
			rootJSON.put("error_type","alert");
			JSONObject obj = new JSONObject();
			obj.put("error_Title",_mapping.getTextDescription("admin.server.Add/Modify Component"));
			obj.put("error_Msg_Count","2");
			obj.put("error_Msg_1",_mapping.getTextDescription("admin.server.Possible reason")+":");
			if (isModifyServer)
			{
				obj.put("error_Msg_2",_mapping.getTextDescription("admin.server.You cannot change the monitoring approach of this component, because its nick name has already been assigned to an agent-based or network component")+".");
			}
			else
			{
				List serverList = egDiscInfo.getServerTypesForNick(s_host_name);
				String componentTypeStr = "";
				if(serverList != null)
				{
					int sSize = serverList.size();
					for (int s=0; s<sSize; s++)
					{
						String compType = (String)serverList.get(s);
						componentTypeStr += _mapping.getComponentTypeDescription(compType)+", ";
						if (s == 2)
						{
							break;
						}
					}
					if (sSize > 3)
					{
						componentTypeStr +="...";
					}
				} 
				componentTypeStr = componentTypeStr.trim();
				if (componentTypeStr.endsWith(","))
				{
					componentTypeStr = componentTypeStr.substring(0,componentTypeStr.length()-1);
				}
				obj.put("error_Msg_2",_mapping.getTextDescription("admin.server.You are trying to add a component with a nick name that has already been assigned to an agent-based or network component under the component type (")+componentTypeStr+"). "+_mapping.getTextDescription("admin.server.Please use a different nick name")+".");
			}
			rootJSON.put("error_Info",obj);
			out.println(rootJSON);
			return;
		}
	}

	if(s_server_name != null && s_host_name != null && (s_server_name.equals("new") || isModifyServer) && IniUI.isEgReservedKeyword(s_host_name))
	{
		//Vector sess_vec = new Vector();
		//sess_vec.removeAllElements();
		//sess_vec.addElement(_mapping.getTextDescription("admin.server.Add/Modify Component"));
		rootJSON.put("requestStatus","failed");
		rootJSON.put("error_type","alert");
		JSONObject obj = new JSONObject();
		obj.put("error_Title",_mapping.getTextDescription("admin.server.Add/Modify Component"));
		if(!StringUtils.isNull(treeViewSrc))
		{
			//sess_vec.addElement("EgDispServer.jsp?qctr=1&server="+ s_server_type+"&isAggregateLink="+s_server_type.startsWith("Agg_")+"&treeViewSrc="+treeViewSrc+"&selectedServerGroup="+selectedServerGroup);
			obj.put("error_URL","EgDispServer.jsp?qctr=1&server="+ s_server_type+"&isAggregateLink="+s_server_type.startsWith("Agg_")+"&treeViewSrc="+treeViewSrc+"&selectedServerGroup="+selectedServerGroup);
		}
		else
		{
			obj.put("error_URL","EgDispServer.jsp?qctr=1&server="+ s_server_type+"&isAggregateLink="+s_server_type.startsWith("Agg_")+"&selectedServerGroup="+selectedServerGroup);
			//sess_vec.addElement("EgDispServer.jsp?qctr=1&server="+ s_server_type+"&isAggregateLink="+s_server_type.startsWith("Agg_")+"&selectedServerGroup="+selectedServerGroup);
		}
		obj.put("error_Msg_Count","2");
		obj.put("error_Msg_1",_mapping.getTextDescription("admin.server.Possible reason")+":");
		obj.put("error_Msg_2","'"+s_host_name+"' "+_mapping.getTextDescription("admin.server.is an eG defined keyword choose another name")+".");
		//sess_vec.addElement(_mapping.getTextDescription("admin.server.Possible reason")+":");
		//sess_vec.addElement("'"+s_host_name+"' "+_mapping.getTextDescription("admin.server.is an eG defined keyword choose another name")+".");
		if(frmTopology!=null && frmTopology.equals("yes"))
		{
			//sess_vec.add("frmTopology");
		}
		//session.setAttribute("vec_Errors",sess_vec);
		rootJSON.put("error_Info",obj);
		out.println(rootJSON);
		return;
	}

	if (!(nickManaged || (v_host_name_nocase.size() > 0 && !exist)))
	{
		if(s_server_name != null && s_server_name.equalsIgnoreCase("new"))
		{
			boolean isManagedServer = false;
			String arr_comps[]=egDiscInfo.getAllServersOfType(s_server_type);
			String s_port = request.getParameter("hportno");
			if (s_server_name.equalsIgnoreCase("new"))
				s_port = sPortNo;
			String s_key ="";
			if(s_port==null) s_port = "NULL";
			if(arr_comps != null)
			{
				if(s_sid!=null && s_sid.length()>0)
				{
					s_key = s_server_type+ ":" + s_host_name + ":" + s_port + ":" + s_sid;
				}
				else
				{
					s_key = s_server_type+ ":" + s_host_name + ":" + s_port;
				}
				for(int i=0;i<arr_comps.length;i++)
				{
					if(arr_comps[i].equalsIgnoreCase(s_key))
					{
						isManagedServer = true;
						break;
					}
				}
			}
			String tmpPort = "";
			if (s_port != null && !s_port.equalsIgnoreCase("null"))
			{
				tmpPort = ":"+s_port;
			}
			if(isManagedServer)
			{
				//Vector sess_vec = new Vector();
				//sess_vec.add(_mapping.getTextDescription("admin.server.Add/Modify Component"));
				rootJSON.put("requestStatus","failed");
				rootJSON.put("error_type","alert");
				JSONObject obj = new JSONObject();
				obj.put("error_Title",_mapping.getTextDescription("admin.server.Add/Modify Component"));
				if(!StringUtils.isNull(treeViewSrc))
				{
					//sess_vec.add("EgDispServer.jsp?qctr=1&server="+ s_server_type+"&isAggregateLink="+s_server_type.startsWith("Agg_")+"&treeViewSrc="+treeViewSrc+"&selectedServerGroup="+selectedServerGroup);
					obj.put("error_URL","EgDispServer.jsp?qctr=1&server="+ s_server_type+"&isAggregateLink="+s_server_type.startsWith("Agg_")+"&treeViewSrc="+treeViewSrc+"&selectedServerGroup="+selectedServerGroup);
				}
				else
				{
					//sess_vec.add("EgDispServer.jsp?qctr=1&server="+ s_server_type+"&isAggregateLink="+s_server_type.startsWith("Agg_")+"&selectedServerGroup="+selectedServerGroup);
					obj.put("error_URL","EgDispServer.jsp?qctr=1&server="+ s_server_type+"&isAggregateLink="+s_server_type.startsWith("Agg_")+"&selectedServerGroup="+selectedServerGroup);
				}
				obj.put("error_Msg_Count","2");
				//obj.put("error_Msg_1",_mapping.getTextDescription("admin.server.Component already managed."));
				obj.put("error_Msg_1","");
				obj.put("error_Msg_2",_mapping.getTextDescription("admin.server.The component")+" '"+s_host_name+tmpPort+"' ("+_mapping.getComponentTypeDescription(s_server_type)+") "+_mapping.getTextDescription("admin.server.you are trying to add is already managed")+".");
				//sess_vec.add(_mapping.getTextDescription("admin.server.Component already managed."));
				//sess_vec.add(_mapping.getTextDescription("admin.server.The component")+" '"+s_host_name+tmpPort+"' ("+_mapping.getComponentTypeDescription(s_server_type)+") "+_mapping.getTextDescription("admin.server.you are trying to add is already managed")+".");
				if(frmTopology!=null && frmTopology.equals("yes"))
				{
					//sess_vec.add("frmTopology");
				}
				//session.setAttribute("vec_Errors",sess_vec);
				rootJSON.put("error_Info",obj);
				/* code for auditlog starts */
				auditLogThread.setCurrentValue("ColumnName","Component Already Managed");
				auditLogThread.setCurrentValue("Component type","$ctype$:"+s_server_type);
				auditLogThread.setCurrentValue("Component name",s_host_name);
				auditLogThread.setCurrentValue("Port number",s_port);
				auditLogThread.setValue("Description","Component was not added as it had been already managed");
				auditLogThread.sendItToDB();
				/* code for auditlog ends */
				out.println(rootJSON);
				return;
			}
		}

		boolean caseIssue = (nameIndex!=-1) && !temp_v_host_name.contains(s_host_name);
		UpdateAndTransmitUserInfo userinfo = new UpdateAndTransmitUserInfo();

		if ((lowerCaseHostName == null || !lowerCaseHostName.equals("true")) && caseIssue)
		{
			if (allNicks == null || !allNicks.contains(s_host_name.toLowerCase()))
			{
				removeOldEntries(newNickAdded, s_host_name, userinfo);
				rootJSON.put("requestStatus","success");
				rootJSON.put("forward",true);
				rootJSON.put("forward_URL","EgnewserverpJson.jsp?action=allservers&"+request.getQueryString()+"&treeViewSrc="+treeViewSrc+"&oldhostname="+EgURLEncoder.encode(oldhostname,"UTF-8"));
			}
		}
		else
		{
			removeOldEntries(newNickAdded, s_host_name, userinfo);
			String ur ="EgnewserverpJson.jsp?action=singleserver&hostname="+EgURLEncoder.encode(s_host_name,"UTF-8")+"&"+request.getQueryString()+"&treeViewSrc="+treeViewSrc+"&servertype="+EgURLEncoder.encode(s_server_type,"UTF-8")+"&servername="+EgURLEncoder.encode(serverNameWithPort,"UTF-8")+"&hostIp="+s_host_ip+"&oldhostname="+EgURLEncoder.encode(oldhostname,"UTF-8");
			if(frmTopology!=null && frmTopology.equals("yes"))
			{
				ur = ur + "&topoSegName="+EgURLEncoder.encode(topoSegName,"UTF-8")+"&initPort="+initialPortNo;
			}
			rootJSON.put("requestStatus","success");
			rootJSON.put("forward",true);
			rootJSON.put("forward_URL",ur);
		}
	}
	if(!nickManaged && s_server_type.startsWith("Agg_"))
	{
		UpdateAndTransmitUserInfo userinfo = new UpdateAndTransmitUserInfo();
		removeOldEntries(newNickAdded, s_host_name, userinfo);
		String url ="EgnewserverpJson.jsp?action=singleserver&hostname="+EgURLEncoder.encode(s_host_name,"UTF-8")+"&"+request.getQueryString()+"&treeViewSrc="+treeViewSrc+"&oldhostname="+EgURLEncoder.encode(oldhostname,"UTF-8");
		rootJSON.put("requestStatus","success");
		rootJSON.put("forward",true);
		rootJSON.put("forward_URL",url);
	}
	//hiddens.put("qstring",request.getQueryString());
	hiddens.put("treeViewSrc",treeViewSrc);
	hiddens.put("fromResultPage",fromResultPage);
	//hiddens.put("server_name",s_server_name);
	hiddens.put("server_type",s_server_type);
	hiddens.put("initPort",initialPortNo);

	Enumeration en = request.getParameterNames();
	while(en.hasMoreElements())
	{
		String name = (String)en.nextElement();
		String [] val2 = request.getParameterValues(name);
		String val ="";
		if (val!=null && val2.length==1)
		{
			val = request.getParameter(name);
		}
		else if(name.equals("alpwd") || name.equals("$_alpwd"))
		{
			val = EgUIUtils.decodeSecurityChar(request.getParameter(name));
		}
		else
		{
			val = com.egurkha.util.StringUtils.getUniqueArrayAsString(val2);
		}
		hiddens.put(name,val);
	}
	boolean caseCheck = true;
	if (s_host_name.equals(oldhostname))
	{
		caseCheck = false;
	}
	//if(nickManaged || (v_host_name_nocase.size() > 0 && !exist))
	if(caseCheck && (nickManaged || v_host_name_nocase.size() > 0))
	{
		String hostname = "";
		String dispHostName = "";
		boolean proceed = true;

		for(int i=1;i < temp_v_host_name.size();i=i+2)
		{
			if(((String)temp_v_host_name.get(i)).equals("false"))
			{
				proceed = false;
				hostname = (String)temp_v_host_name.get(i-1);
				break;
			}
		}

		if(hostname.length() > 0)
		{
			Hashtable nickIPMapTemp = egDiscInfo.getAllNicksIpMap();
			Hashtable lowerCaseNickIPMap = new Hashtable();
			Hashtable originalNickMap = new Hashtable();
			if(nickIPMapTemp != null)
			{
				dispHostName = (String)nickIPMapTemp.get(s_host_name);
				if (dispHostName == null)
				{
					Enumeration eunmMap  = nickIPMapTemp.keys();
					while(eunmMap.hasMoreElements())
					{
						String key = (String)eunmMap.nextElement();
						String value = (String)nickIPMapTemp.get(key);
						lowerCaseNickIPMap.put(key.toLowerCase(),value);
						originalNickMap.put(key.toLowerCase(),key);
					}
				}
				dispHostName = (String)lowerCaseNickIPMap.get(s_host_name.toLowerCase());
				if(dispHostName != null)
				{
					dispHostName = (String)originalNickMap.get(s_host_name.toLowerCase());
				}
				else
				{
					dispHostName = s_host_name;
				}
			}
		}
		hiddens.put("hostcheck","true");

		String enable="";
		String port=request.getParameter("hportno");
		//String sPortNo = request.getParameter("sportno");
		if (s_server_name.equalsIgnoreCase("new"))
			port = sPortNo;
		if( port!=null &&!port.equals(sPortNo))
		{
			enable="disabled";
		}
		if(!s_server_name.equalsIgnoreCase("new"))
		{
			enable="disabled";
		}
		rootJSON.put("proceed",proceed);
		rootJSON.put("main_Msg_Title",s_host_ip+" "+_mapping.getTextDescription("admin.server.IP is already mapped to the following nick name(s)")+":");
		boolean isIpNotShared = true;
	//	Vector v_host_name_only = new Vector();
		
		if(proceed)
		{
			JSONArray gridData = new JSONArray();
			for(int i=0;i < v_host_name.size();i=i+2)
			{
				String compName = (String)v_host_name.get(i);
			//	v_host_name_only.add(compName);
				JSONObject gridVal = new JSONObject();
				gridVal.put("column_1",compName);
				gridData.add(gridVal);
			}
			rootJSON.put("gridData",gridData);
			
			if(isLimitedAdmin)
			{
				for(int u=0; u<v_host_name1.size(); u=u+2)
				{
					if(allCompNicks.contains(v_host_name1.get(u)))
					{
						isIpNotShared = true;
					}
					else
					{
						isIpNotShared = false;
						break;
					}
				}
			}
		}
		if(v_host_name_nocase.contains(s_host_name.toLowerCase()))
		{
			if(proceed)
			{
				if(v_host_name_nocase.size() >= 2)
				{	
					if (!allNicksList.contains(s_host_name)) // Existing nick name but case differs
					{
						int idx = allNicksListLower.indexOf(s_host_name.toLowerCase());
						if (idx > -1)
						{
							String existingNick = allNicksList.get(idx).toString();
							String existingIP = nickIPMap.get(existingNick).toString();
							List serverList = egDiscInfo.getServerTypesForNick(existingNick,true,"");
							String componentTypeStr = "Component Type";
							if(serverList != null)
							{
								int sSize = serverList.size();
								for (int s=0; s<sSize; s++)
								{
									String compType = (String)serverList.get(s);
									componentTypeStr += _mapping.getComponentTypeDescription(compType)+", ";
									if (s == 2)
									{
										break;
									}
								}
								if (sSize > 3)
								{
									componentTypeStr +="...";
								}
							} 
							componentTypeStr = componentTypeStr.trim();
							if (componentTypeStr.endsWith(","))
							{
								componentTypeStr = componentTypeStr.substring(0,componentTypeStr.length()-1);
							}
							rootJSON.put("requestStatus","failed");
							rootJSON.put("error_type","alert");
							JSONObject obj = new JSONObject();
							obj.put("error_Title",_mapping.getTextDescription("admin.server.Add/Modify Component"));
							obj.put("error_URL","");
							obj.put("error_Msg_Count","2");
							obj.put("error_Msg_1",_mapping.getTextDescription("admin.error.The nick name")+" ("+s_host_name+") "+_mapping.getTextDescription("admin.error.you are trying to add is already associated in the following manner")+"."); 
							obj.put("IP",existingIP);
							obj.put("nickName",existingNick);
							obj.put("compTypes",componentTypeStr);
							obj.put("error_Msg_2",_mapping.getTextDescription("admin.server.Please choose a different nick name")+".");
							rootJSON.put("error_Info",obj);
						}
					}
					else
					{
						rootJSON.put("requestStatus","failed");
						rootJSON.put("error_type","radio");
						rootJSON.put("radio_Msg_Title",_mapping.getTextDescription("admin.server.The nick name")+" ("+s_host_name+") "+_mapping.getTextDescription("admin.server.you have added is already present in this list"));
						rootJSON.put("radio1_Msg",_mapping.getTextDescription("admin.server.Do you wish to continue adding the same nick name for this component?"));
						rootJSON.put("radio1_value","singleserver");
						if(isLimitedAdmin && !isIpNotShared)
						{
							enable = "disabled";
						}
						rootJSON.put("radio2_Msg",_mapping.getTextDescription("admin.server.Do you wish to continue adding the same nick name for this component and apply for all components?"));
						rootJSON.put("radio2_value","allservers");
						rootJSON.put("radio2_enable",enable);
					}
				}
				else
				{
					UpdateAndTransmitUserInfo userinfo = new UpdateAndTransmitUserInfo();
					removeOldEntries(newNickAdded, s_host_name, userinfo);
					String ur ="EgnewserverpJson.jsp?action=singleserver&hostname="+EgURLEncoder.encode(s_host_name,"UTF-8")+"&"+request.getQueryString()+"&treeViewSrc="+treeViewSrc+"&servertype="+EgURLEncoder.encode(s_server_type,"UTF-8")+"&servername="+EgURLEncoder.encode(serverNameWithPort,"UTF-8")+"&hostIp="+s_host_ip+"&oldhostname="+EgURLEncoder.encode(oldhostname,"UTF-8");;
					if(frmTopology!=null && frmTopology.equals("yes"))
					{
						ur = ur + "&topoSegName="+EgURLEncoder.encode(topoSegName,"UTF-8")+"&initPort="+initialPortNo;
					}
					rootJSON.put("requestStatus","success");
					rootJSON.put("forward",true);
					rootJSON.put("forward_URL",ur);
				}
			}
			else
			{
				
				rootJSON.put("requestStatus","failed");
			//	rootJSON.put("error_type","alert");
				rootJSON.put("error_type","confirm");
				JSONObject obj = new JSONObject();
				List serverList =egDiscInfo.getServerTypesForNick(s_host_name,true,"");
				String temp =  "";//s_host_name;
				if(serverList.isEmpty())  //MODIFYING THE CASE OF NICK NAME THIS CHECKS OCCURS TO GET THE COMPONENT TYPE WHERE NICK EXIST ALREADY (BOTH NICK NAME AND HOST NAME ARE SAME BUT DIFFRNT IN CASE )
				{
					int idx = allNicksListLower.indexOf(s_host_name.toLowerCase());
					if (idx > -1)
					{
						String existingNick = allNicksList.get(idx).toString();
						String existingIP = nickIPMap.get(existingNick).toString();
						temp = existingIP;
						serverList = egDiscInfo.getServerTypesForNick(existingNick,true,"");
					}
				}
				else
				{
					temp = nickIPMap.get(s_host_name).toString();
				}
				String componentTypeStr = "Component Type : ";
				if(serverList != null)
				{
					int sSize = serverList.size();
					for (int s=0; s<sSize; s++)
					{
						String compType = (String)serverList.get(s);
						componentTypeStr += _mapping.getComponentTypeDescription(compType)+", ";
						if (s == 2)
						{
							break;
						}
					}
					if (sSize > 3)
					{
						componentTypeStr +="...";
					}
				} 
				componentTypeStr = componentTypeStr.trim();
				if (componentTypeStr.endsWith(","))
				{
					componentTypeStr = componentTypeStr.substring(0,componentTypeStr.length()-1);
				}
				obj.put("error_Title",_mapping.getTextDescription("admin.server.Add/Modify Component"));
				obj.put("error_URL","");
				obj.put("error_Msg_Count","2");
				//	obj.put("error_Msg_1",_mapping.getTextDescription("admin.server.The nick name")+" ("+s_host_name+") "+_mapping.getTextDescription("admin.server.you are trying to add is already associated with a component")+" ("+hostname+").");
				obj.put("error_Msg_1",_mapping.getTextDescription("admin.error.The nick name")+" ("+s_host_name+") "+_mapping.getTextDescription("admin.error.you are trying to add/modify is already associated in the following manner")+"."); 
				obj.put("IP",temp);
				obj.put("compTypes",componentTypeStr);
				obj.put("nickName",dispHostName);
				obj.put("error_Msg_2",_mapping.getTextDescription("admin.server.Do you wish to use this existing  Host IP/name and Nick name for the component")+"?");
				String	ur = "EgnewserverpJson.jsp?action=singleserver&hostname="+EgURLEncoder.encode(s_host_name,"UTF-8")+"&"+request.getQueryString()+"&treeViewSrc="+treeViewSrc+"&servertype="+EgURLEncoder.encode(s_server_type,"UTF-8")+"&servername="+EgURLEncoder.encode(serverNameWithPort,"UTF-8")+"&hostIp="+temp+"&oldhostname="+EgURLEncoder.encode(oldhostname,"UTF-8");
				if(frmTopology!=null && frmTopology.equals("yes"))
				{
					ur = ur + "&topoSegName="+EgURLEncoder.encode(topoSegName,"UTF-8")+"&initPort="+initialPortNo;
				}
									
				obj.put("forward_URL",ur);
				rootJSON.put("error_Info",obj);
				
				}
		}
		else if(!v_host_name_nocase.contains(s_host_name.toLowerCase()))
		{
			if(proceed)
			{
				String radioValue = "singleserver"; 
				if(!s_server_name.equalsIgnoreCase("new"))
					radioValue ="allservers";

				ArrayList nicks = egDiscInfo.getAllComponentNicks(false);
				int count = 0;
				for (int i=0;i<nicks.size();i++)
				{
					String nick = (String)nicks.get(i);
					if (nick.equalsIgnoreCase(oldhostname))
						count++;
					if(count > 1)
						break;
				}

				if (count > 1)
				{
					radioValue = "allservers";
				}
				else
				{
					radioValue = "singleserver";
				}
				rootJSON.put("requestStatus","failed");
				rootJSON.put("error_type","radio");
				rootJSON.put("radio_Msg_Title",_mapping.getTextDescription("admin.server.The nick name")+" ("+s_host_name+") "+_mapping.getTextDescription("admin.server.you have added is not present in the below list"));
				rootJSON.put("radio1_value",radioValue);
				rootJSON.put("radio1_checked",true);
				
				//rootJSON.put("radio_Msg_2",_mapping.getTextDescription("admin.server.Do you wish to continue adding the same host name for this component and apply for all components?"));
			
				if(s_server_name.equalsIgnoreCase("new"))
				{
					rootJSON.put("radio1_Msg",_mapping.getTextDescription("admin.server.Do you wish to add the new nick name for this component alone?"));
				}
				else
				{
					if (v_host_name_nocase.size() >= 2)
					{
						rootJSON.put("radio1_Msg",_mapping.getTextDescription("admin.server.Do you wish to rename all the components that have the old nick name?"));
						hiddens.put("modify","yes");
					}
					else
					{
						UpdateAndTransmitUserInfo userinfo = new UpdateAndTransmitUserInfo();
						removeOldEntries(newNickAdded, s_host_name, userinfo);
						String ur = "";
						if(radioValue.equalsIgnoreCase("singleserver"))
						{
							ur ="EgnewserverpJson.jsp?action=singleserver&hostname="+EgURLEncoder.encode(s_host_name,"UTF-8")+"&"+request.getQueryString()+"&treeViewSrc="+treeViewSrc+"&servertype="+EgURLEncoder.encode(s_server_type,"UTF-8")+"&servername="+EgURLEncoder.encode(serverNameWithPort,"UTF-8")+"&hostIp="+s_host_ip+"&oldhostname="+EgURLEncoder.encode(oldhostname,"UTF-8");
							if(frmTopology!=null && frmTopology.equals("yes"))
							{
								ur = ur + "&topoSegName="+EgURLEncoder.encode(topoSegName,"UTF-8")+"&initPort="+initialPortNo;
							}
						}
						else if(radioValue.equalsIgnoreCase("allservers"))
						{
							ur = "EgnewserverpJson.jsp?action=allservers&"+request.getQueryString()+"&treeViewSrc="+treeViewSrc+"&oldhostname="+EgURLEncoder.encode(oldhostname,"UTF-8");
						}
						rootJSON.put("requestStatus","success");
						rootJSON.put("forward",true);
						rootJSON.put("forward_URL",ur);
					}
				}
				if(isLimitedAdmin && !isIpNotShared)
				{
					enable = "disabled";
				}
				rootJSON.put("radio2_Msg",_mapping.getTextDescription("admin.server.Do you wish to add the new nick name for this component and apply for all components?"));
				rootJSON.put("radio2_value","allservers");
				rootJSON.put("radio2_enable",enable);
%>
				
<%
			}
			else
			{
				/* code for auditlog starts */
				auditLogThread.setCurrentValue("ColumnName","Component Already Managed");
				auditLogThread.setCurrentValue("01~~Component type","$ctype$:"+s_server_type);
				auditLogThread.setCurrentValue("02~~Component name",s_host_name);
				if(s_host_ip != null && !s_host_ip.equals("0.0.0.0"))
				{
					auditLogThread.setCurrentValue("03~~IP in which component to be managed",s_host_ip);
				}

				if(hostname != null && hostname.equals("0.0.0.0"))
				{
					List aggCompTypes = egDiscInfo.getServerTypesForNick(dispHostName);
					rootJSON.put("requestStatus","failed");
					rootJSON.put("error_type","alert");
					JSONObject obj = new JSONObject();
					obj.put("error_Title",_mapping.getTextDescription("admin.server.Add/Modify Component"));
					obj.put("error_URL","");
					obj.put("error_Msg_Count","2");
					obj.put("error_Msg_1",_mapping.getTextDescription("admin.error.The host/nick name")+" ("+s_host_name+") "+_mapping.getTextDescription("admin.error.you are trying to add is already associated with an aggregate component in the following manner")+".");
					obj.put("error_Msg_2",_mapping.getTextDescription("admin.server.Please choose a different host/nick name"));					

					if(aggCompTypes != null && !aggCompTypes.isEmpty())
					{
						JSONArray aggArray = new JSONArray();
						for(int i=0;i<aggCompTypes.size();i++)
						{
							String aggCompType = (String) aggCompTypes.get(i);
							auditLogThread.setCurrentValue("Component already managed","$ctype$:"+aggCompType+":"+dispHostName);
							JSONObject obj2 = new JSONObject();
							obj2.put("compType",_mapping.getComponentTypeDescription(aggCompType));
							obj2.put("comoName",dispHostName);
							aggArray.add(obj2);
						}
					}
					rootJSON.put("error_Info",obj);
					auditLogThread.setValue("Description","Component was not added as it had been already managed");
					auditLogThread.sendItToDB();
					/* code for auditlog ends */
				}
				else
				{
					auditLogThread.setCurrentValue("IP in which component already managed",hostname);
					auditLogThread.setValue("Description","Component was not added as it had been already managed");
					auditLogThread.sendItToDB();
					/* code for auditlog ends */
					List serverList =egDiscInfo.getServerTypesForNick(s_host_name,true,"");
					String componentTypeStr = "";
					if(serverList.isEmpty())  //WHEN MODIFYING THE CASE OF NICK NAME THIS CHECKS OCCURS TO GET THE COMPONENT TYPE WHERE NICK EXIST ALREADY
					{
						int idx = allNicksListLower.indexOf(s_host_name.toLowerCase());
						if (idx > -1)
						{
							String existingNick = allNicksList.get(idx).toString();
							String existingIP = nickIPMap.get(existingNick).toString();
							serverList = egDiscInfo.getServerTypesForNick(existingNick,true,"");
							if(serverList.isEmpty())
							{
								String[] extAgt = externalInfo.getAllExternalAgents();
								List extAgtList  = new ArrayList();
								if(extAgt!=null)
								{
									extAgtList= Arrays.asList(extAgt);
								}
								if(extAgtList.contains(existingNick))
								{
									componentTypeStr = "Agent Type :  External Agent";
								}
								else
								{
									componentTypeStr = "Agent Type : Remote Agent";
								}
							}
						}
					}
					if(serverList != null && !serverList.isEmpty())
					{
						int sSize = serverList.size();
						componentTypeStr = "Component Type : ";
						for (int s=0; s<sSize; s++)
						{
							String compType = (String)serverList.get(s);
							componentTypeStr += _mapping.getComponentTypeDescription(compType)+", ";
							if (s == 2)
							{
								break;
							}			
						}
						if (sSize > 3)
						{
							componentTypeStr +="...";
						}						 
					} 
					componentTypeStr = componentTypeStr.trim();
					if (componentTypeStr.endsWith(","))
					{
						componentTypeStr = componentTypeStr.substring(0,componentTypeStr.length()-1);
					}
					rootJSON.put("requestStatus","failed");
					rootJSON.put("error_type","alert");
					JSONObject obj = new JSONObject();
					obj.put("error_Title",_mapping.getTextDescription("admin.server.Add/Modify Component"));
					obj.put("error_URL","");
					obj.put("error_Msg_Count","2");
					obj.put("error_Msg_1",_mapping.getTextDescription("admin.error.The nick name")+" ("+s_host_name+") "+_mapping.getTextDescription("admin.error.you are trying to add is already associated in the following manner")+"."); 
					obj.put("IP",hostname);
					obj.put("compTypes",componentTypeStr);
					obj.put("nickName",dispHostName);
					obj.put("error_Msg_2",_mapping.getTextDescription("admin.server.Please choose a different nick name"));
					rootJSON.put("error_Info",obj);
				}
			}
		}
		//hiddens.put("qstring",request.getQueryString());
		hiddens.put("server_name",s_server_name);
		hiddens.put("server_type",s_server_type);
	}
	else
	{
		boolean caseIssue = (nameIndex!=-1) && !temp_v_host_name.contains(s_host_name);
		if ((lowerCaseHostName==null || !lowerCaseHostName.equals("true")) && caseIssue)
		{
			if(allNicks != null && allNicks.contains(s_host_name.toLowerCase()))
			{
				newHostName = (String)temp_v_host_name.get(nameIndex);
				rootJSON.put("requestStatus","failed");
				//rootJSON.put("error_type","confirm");
				rootJSON.put("error_type","alert");
				JSONObject obj = new JSONObject();
				obj.put("error_Title",_mapping.getTextDescription("admin.server.Add/Modify Component"));
				obj.put("error_URL","");
				obj.put("error_Msg_Count","2");
				obj.put("error_Msg_1",_mapping.getTextDescription("admin.error.The host/nick name")+" ("+s_host_name+") "+_mapping.getTextDescription("admin.error.you are trying to add is already associated with the IP")+" ("+s_host_ip+"). ");//+_mapping.getTextDescription("admin.error.in the following manner"));
				obj.put("IP",s_host_ip);
				obj.put("nickName",newHostName);
				//obj.put("error_Msg_2",_mapping.getTextDescription("admin.server.Do you wish to use the old host/nick name")+" ("+newHostName+") "+_mapping.getTextDescription("admin.server.for this IP address"));
				obj.put("error_Msg_2",_mapping.getTextDescription("admin.server.Please choose a different host/nick name"));
				rootJSON.put("error_Info",obj);
			}
		}
	}
	
	if(monitorLastSession != null && newUrlLink != null && newUrlLink.indexOf("com.eg.EgDashboardController")>-1)
	{
		if(s_server_type != null && strCompType != null && s_server_type.equals(strCompType) && oldNick!=null && strHostName!=null && oldNick.equals(strHostName))
		{
			session.removeAttribute("monitorLastSession");
		}
	}

	rootJSON.put("hiddenValues",hiddens);
	out.println(rootJSON);
%>

<%!
	public void removeOldEntries(boolean newNickAdded, String s_host_name, UpdateAndTransmitUserInfo userinfo)
	{
		if (newNickAdded)
		{
			ArrayList queryList = new ArrayList();
			queryList.add("delete from measure_last where trgt_host='"+s_host_name+"'");
			queryList.add("delete from metatest where comp_name like '"+s_host_name+":%'");
			for (int j=0; j<queryList.size(); j++)
			{
				String thisQry = (String) queryList.get(j);
				userinfo.deleteFromDb(thisQry);
			}
		}
	}
	public Vector getUniqueHosts(Vector v_host_name,Vector hosts)
	{
		for(int i=0;i<hosts.size();i=i+2)
		{
			String temp1 = (String)hosts.get(i);
			String temp2 = (String)hosts.get(i+1);
			if(!v_host_name.contains(temp1))
			{
				v_host_name.add(temp1);
				v_host_name.add(temp2);
			}
		}
		return v_host_name;
	}
%>


