<%
/*
 *	Name		:	EgServerListJSON.jsp
 *	Purpose		:	To view all agents' current status
 *	Navigation	:	Home > [Click here to get the license details] > [Agent Status]
 */
%>

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

<%@ page import="egurkha.UserBean" %>
<%@ page import="com.eg.EgUsersInfo"%>
<%@ page import="com.eg.EgLicenseInfo"%>
<%@ page import="com.eg.EgRoleInfo"%>
<%@ page import="com.eg.EgServerList"%>
<%@ page import="com.eg.IniFile"%>
<%@ page import="com.egurkha.util.StringUtils"%>

<%@ page import="java.util.ArrayList"%>
<%@ page import="java.util.Collections"%>
<%@ page import="java.util.Hashtable"%>
<%@ page import="java.util.StringTokenizer"%>

<%@ page import="org.json.simple.JSONObject"%>
<%@ page import="org.json.simple.JSONArray"%>
<%@ page import="org.json.simple.parser.JSONParser"%>

<%
	response.setHeader("Cache-Control","no-store");
	response.setHeader("Pragma","no-cache");
	response.setDateHeader("Expires", -1);
	response.setContentType("application/json;charset=UTF-8");
%>
<%!
	String USER_COMP_AGENTS = "Agents for user licensed types";
	String[] agentTypes = {"BasicAgents","PremiumAgents", "ExternalAgents", "RemoteAgents",USER_COMP_AGENTS};
	String[] agentStatus = {"All","Running","NotRunning"};
%>
<%
	EgRoleInfo roleInfo = EgRoleInfo.getInstance(sessionID,_user.getLoginID());
	EgUsersInfo usersInfo = new EgUsersInfo();
	boolean isUserBasedCert = false;
	if (usersInfo.getUserAllowedCount() > 0)
	{
		isUserBasedCert = true;
	}
	JSONObject rootJSON = new JSONObject();
	JSONArray agentTypesAry = new JSONArray();
	for (int a=0; a<agentTypes.length; a++)
	{
		String agentType = agentTypes[a];
		if (!isUserBasedCert && agentType.equals(USER_COMP_AGENTS))
		{
			continue;
		}
		JSONObject obj = new JSONObject();
		obj.put("valueField",agentType);
		obj.put("displayField",_mapping.getTextDescription("admin.agents."+agentType));
		agentTypesAry.add(obj);
	}
	rootJSON.put("agentTypes",agentTypesAry);
	//For CSV
	List csvData = new ArrayList();

	String start = request.getParameter("start");
	String pageLimit = request.getParameter("limit");
	String pageNo = request.getParameter("page");
	String filter = request.getParameter("filter");
	boolean isSearchEnable = false;
	String searchStr = "";

	if(!StringUtils.isNull(filter))
	{
		//JSONParser parser = new JSONParser();
		//JSONArray jsonArr = (JSONArray) parser.parse(filter);
		//JSONObject jsonObj = (JSONObject) jsonArr.get(0);
		//searchStr = jsonObj.get("value").toString();

		searchStr = StringUtils.decodeSecurityChar(filter);
		if ((!StringUtils.isNull(searchStr)))
		{
			isSearchEnable = true;
		}
	}

	int maxPageItems = 50;
	if (!StringUtils.isNull(pageLimit))
	{
		maxPageItems = Integer.parseInt(pageLimit);
	}

	csvData.add(_mapping.getTextDescription("admin.agents.Agents Status Report"));
	csvData.add("");

	String agentType = request.getParameter("agent"); // Agent Type
	if (StringUtils.isNull(agentType))
	{
		agentType = agentTypes[0];
	}
	rootJSON.put("agentType",agentType);
	String mappingType = _mapping.getTextDescription("admin.agents."+agentType);
	csvData.add(_mapping.getTextDescription("admin.agents.Agent type")+","+mappingType);
	JSONArray agentsSts = new JSONArray();
	for (int s=0;s<agentStatus.length;s++)
	{
		String status = agentStatus[s];
		JSONObject obj = new JSONObject();
		obj.put("valueField",status);
		obj.put("displayField",_mapping.getTextDescription("admin.agents."+status));
		agentsSts.add(obj);
	}
	rootJSON.put("agentStatus",agentsSts);

	String agentState=request.getParameter("status"); // Agent status
	if (StringUtils.isNull(agentState))
	{
		agentState = agentStatus[0];
	}
	rootJSON.put("agentState",agentState);

	String mappingStatus = _mapping.getTextDescription("admin.agents."+agentState);
	csvData.add(_mapping.getTextDescription("admin.agents.Agent status")+","+mappingStatus);
	csvData.add("");
	//Only when search option is enabled, 'hostname' & 'search'
	//will be obtained
	String hostname = request.getParameter("hostname");
	if(hostname == null)
		hostname = "";
	String search = request.getParameter("search");
	if(search == null)
		search = "false";

	rootJSON.put("hostname",hostname);
	rootJSON.put("search",search);
	EgLicenseInfo licInfo = new EgLicenseInfo();
	UserBean userBean = new UserBean();
	boolean hasAllCompAccess = roleInfo.hasAllComponentAccess(); // For Limited admin
	boolean isLimitedAdmin = !hasAllCompAccess;
	EgServerList serverList = new EgServerList();
	int totalAgentCount = 0;
	if (hasAllCompAccess)
	{
		totalAgentCount = (licInfo.getExternalAgents()).size() + (licInfo.getBasicAgents()).size() + (licInfo.getPremiumAgents()).size() + (licInfo.getRemoteAgents()).size();
	}
	else
	{
		totalAgentCount = (roleInfo.getExternalAgents()).size() + (roleInfo.getBasicAgents()).size() + (roleInfo.getPremiumAgents()).size() + (roleInfo.getRemoteAgents()).size();
	}
	rootJSON.put("totalAgentCount",totalAgentCount);

	ArrayList agentList = new ArrayList();
	ArrayList sharedAgents = new ArrayList();
	ArrayList allAgents = roleInfo.getTotalAgents();
	ArrayList srchTokens = new ArrayList();

	if(agentType.equalsIgnoreCase("ExternalAgents"))
			agentList = hasAllCompAccess ? licInfo.getExternalAgents() : roleInfo.getExternalAgents();
	else if(agentType.equalsIgnoreCase("BasicAgents"))
		agentList = hasAllCompAccess ? licInfo.getBasicAgents() : roleInfo.getBasicAgents();
	else if(agentType.equalsIgnoreCase("PremiumAgents"))
	{
		agentList = hasAllCompAccess ? userBean.getPremiumAgents() : roleInfo.getPremiumAgents();
	}
	else if(agentType.equalsIgnoreCase("RemoteAgents"))
		agentList = hasAllCompAccess ? licInfo.getRemoteAgents() : roleInfo.getRemoteAgents();
	else if (agentType.equalsIgnoreCase(USER_COMP_AGENTS))
	{
		agentList = hasAllCompAccess ? userBean.getPremiumAgents(true) : roleInfo.getPremiumAgents(true);
	}

	if(search.equals("true"))
	{
		StringTokenizer st1 = new StringTokenizer(hostname);
		while (st1.hasMoreTokens())
		{
			String Token = st1.nextToken().trim();
			if (Token.equals("") || Token.length() == 0)
				continue;
			srchTokens.add(Token);
		}
	}

	int eventCount = 0;
	int offsetCount = 0;

	List csvAssignHosts = new ArrayList();
	if(agentList == null || agentList.size() == 0)
	{
		rootJSON.put("noManagedHostsFound",true);
		csvData.add("-No Agents Found-");
	}
	else
	{
		ArrayList aList = serverList.getAgentListFromDB();
		String currList[] = serverList.getTargetNames();
		Map allAgentsMap = serverList.getAgentList(agentList,aList,currList,agentState);
		agentList = new ArrayList(allAgentsMap.keySet());
		eventCount = agentList.size();
		rootJSON.put("totalProperty",eventCount);
		rootJSON.put("selectedUserCount",eventCount);

		boolean isNickShared = false;
		if(agentType.equalsIgnoreCase("ExternalAgents"))
		{
			sharedAgents = getUsersSharedAgents(agentList,roleInfo,true,false);
		}
		else if(agentType.equalsIgnoreCase("RemoteAgents"))
		{
			sharedAgents = getUsersSharedAgents(agentList,roleInfo,false,true);
		}
		else
		{
			sharedAgents = getUsersSharedAgents(agentList,roleInfo,false,false);
		}

		if(isLimitedAdmin && sharedAgents != null && sharedAgents.size() > 0)
		{
			isNickShared = true;
		}
		boolean autoIpNameCheck = (new EgServicesInfo("manager")).autoIpNameCheck();
		ArrayList allCompNicks = roleInfo.getAllServerNicks(); // For Limited admin
		Hashtable nick_ip_map = new com.eg.EgDiscInfo("manager").getNickIpMap();
		if(nick_ip_map == null)
		{
			nick_ip_map = new Hashtable();
		}

		Hashtable debug_status = getAgentDebug("AGENT_OUTPUT_STATUS");
		Vector compNickList = disableIPList();
		JSONArray disabledIpObj = new JSONArray();
		for(int i=0;i<compNickList.size();i++)
		{
			String nick = (String)compNickList.get(i);
			disabledIpObj.add(nick);
		}
		rootJSON.put("disabledIpList",disabledIpObj);

		if (isSearchEnable)
		{
			agentList = getSearchData(agentList,searchStr,true);
			rootJSON.put("totalProperty",agentList.size());
		}

		csvData.add(_mapping.getTextDescription("admin.agents.Total number of agents")+","+agentList.size());
		csvData.add("");

		ArrayList dataForCsv = new ArrayList();
		dataForCsv.addAll(agentList);
		ArrayList csvList = getCSVData(allAgentsMap, allCompNicks, agentType, _mapping, nick_ip_map, debug_status,compNickList,autoIpNameCheck);
		if (csvList != null && csvList.size() > 0)
		{
			csvData.addAll(csvList);
		}

		JSONArray agentsDetails = new JSONArray();
		if(!allAgentsMap.isEmpty())
		{
			boolean proceed = false;
			boolean isAssignedHostShared = false;
			boolean setDisableOutputLogging = false;
			//To display Total Number of Agents in Agent Status Page.
			rootJSON.put("totalNoAgent",allAgentsMap.size());

			String agentIPNick = _mapping.getTextDescription("admin.agents.Agent IP/Nickname");
			String install = _mapping.getTextDescription("admin.agents.Installed");
			String status = _mapping.getTextDescription("admin.agents.Status");
			String outputEnabled = _mapping.getTextDescription("admin.agents.Output Logging Enabled");
			//csvData.add(agentIPNick+","+install+","+status+","+outputEnabled);
			rootJSON.put("enableSearch",true);
			rootJSON.put("managedHostsFoundForSearch",true);

			Iterator itr = allAgentsMap.keySet().iterator();
			while(itr.hasNext())
			{
				String agentIP = (String)itr.next();
				String agent_state = (String)allAgentsMap.get(agentIP);
				String installed = agent_state.substring(0,agent_state.indexOf("-"));
				String running = agent_state.substring(agent_state.indexOf("-")+1);
				JSONObject obj = new JSONObject();
				if(agentType.equalsIgnoreCase("ExternalAgents"))
				{
					String hosts = getAssignedHostsForExternalAgent(agentIP,allCompNicks);
					if(hosts.trim().equals(""))
					{
						hosts = "- No assigned hosts found -";
					}
					else
					{
						isAssignedHostShared = isAssignedHostShared(isNickShared,sharedAgents,hosts);
					}
					obj.put("AssignedHosts",hosts);
					//csvAssignHosts.add(agentIP+"#@#"+hosts);
				}
				else if (agentType.equalsIgnoreCase("RemoteAgents"))
				{
					String hosts = getAssignedHostsForRemoteAgent(agentIP,allCompNicks);
					if(hosts.trim().equals(""))
					{
						hosts = "- No assigned hosts found -";
					}
					else
					{
						isAssignedHostShared = isAssignedHostShared(isNickShared,sharedAgents,hosts);
					}
					obj.put("AssignedHosts",hosts);
					//csvAssignHosts.add(agentIP+"#@#"+hosts);
				}

				if(isNickShared && (sharedAgents.contains(agentIP) || isAssignedHostShared))
				{
					proceed = true;
				}
				else
				{
					proceed = false;
				}

				String restartFlg = "No";
				if(installed != null && (installed.equals("Not Installed") || running.equals("Not Running")))
				{
					restartFlg = "No";
				}
				else
				{
					if(proceed)
						restartFlg = "No";
					else
						restartFlg = "Yes";
				}
				//String onSelected="";
				//String offSelected="";
				boolean output = false;
				String agent_ip_address=null;
				String agent_ip_address_arr[]=null;
				String debugStatus=null;
				if(nick_ip_map.containsKey(agentIP))
				{
					agent_ip_address = (String)nick_ip_map.get(agentIP);
					if(agent_ip_address != null)
					{
						agent_ip_address_arr = StringUtils.getTokens(agent_ip_address,":");
					}
				}
				boolean statusNotFound=true;
				if(autoIpNameCheck)
				{
					if(agent_ip_address_arr != null)
					{
						int ipsCount=agent_ip_address_arr.length;
						for(int j=0;j<ipsCount;j++)
						{
							agent_ip_address=agent_ip_address_arr[j];
							if(debug_status.containsKey(agent_ip_address))
							{
								debugStatus = (String)debug_status.get(agent_ip_address);
								statusNotFound=false;
								break;
							}
							else if(debug_status.containsKey(agent_ip_address.toUpperCase()))
							{
								debugStatus = (String)debug_status.get(agent_ip_address.toUpperCase());
								statusNotFound=false;
								break;
							}
							else if(debug_status.containsKey(agent_ip_address.toLowerCase()))
							{
								debugStatus = (String)debug_status.get(agent_ip_address.toLowerCase());
								statusNotFound=false;
								break;
							}
							else if(compNickList != null && (compNickList.contains(agentIP) || compNickList.contains(agentIP.toLowerCase()) || compNickList.contains(agentIP.toUpperCase())))
							{
								debugStatus = "yes";
								statusNotFound=false;
								break;
							}
						}
					}
				}
				if(statusNotFound)
				{
					if(agentIP != null && debug_status.containsKey(agentIP))
					{
						debugStatus = (String)debug_status.get(agentIP);
					}
					else if(agentIP != null && debug_status.containsKey(agentIP.toUpperCase()))
					{
						debugStatus = (String)debug_status.get(agentIP.toUpperCase());
					}
					else if(compNickList != null && (compNickList.contains(agentIP) || compNickList.contains(agentIP.toLowerCase()) || compNickList.contains(agentIP.toUpperCase())))
					{
						debugStatus = "yes";
					}
				}
				if(debugStatus != null && debugStatus.equalsIgnoreCase("yes"))
				{
					//onSelected = "selected";
					//offSelected = "";
					output=true;
				}
				else
				{
					//onSelected = "";
					//offSelected = "selected";
					output=false;
				}//AgentIP/Nickname-Installed-Status-Output-Restart-Logs
				rootJSON.put(agentIP+"_IP",agent_ip_address);

				String tempInstalled = "Yes";
				if (installed.equalsIgnoreCase("Not Installed"))
				{
					tempInstalled = "No";
				}
				if (tempInstalled.equalsIgnoreCase("No") && running.equalsIgnoreCase("Not Running"))
				{
					setDisableOutputLogging = true;
				}
				else if(tempInstalled.equalsIgnoreCase("Yes") && running.equalsIgnoreCase("Running"))
				{
					if(proceed)
						setDisableOutputLogging = true;
					else
						setDisableOutputLogging = false;
				}
				obj.put("AgentIP",agentIP+'~'+tempInstalled);
				obj.put("Installed",tempInstalled);
				obj.put("Status",running);
				obj.put("Output",output);
				obj.put("Restart",restartFlg+"~"+agentIP);
				String csvOutput = "No";
				if (output)
					csvOutput = "Yes";
				String installMapping = _mapping.getTextDescription("admin.common."+tempInstalled);
				String runMapping = _mapping.getTextDescription("admin.agents."+running);
				String outputMapping = _mapping.getTextDescription("admin.common."+csvOutput);
				//csvData.add(agentIP+","+installMapping+","+runMapping+","+outputMapping);
				if(installed.equalsIgnoreCase("Not Installed") || running.equalsIgnoreCase("Not Running"))
				{
					obj.put("Logs","DoNotShow");
					obj.put("Xmx","DoNotShow");
				}
				else
				{
					if(proceed)
					{
						obj.put("Logs","DoNotShow");
						obj.put("Xmx","DoNotShow");
					}
					else
					{
						obj.put("Logs","Show");
						obj.put("Xmx","Show");
					}
				}
				obj.put("StopAgent",restartFlg+"~"+agentIP);
				obj.put("isAgentShared",proceed+"~"+setDisableOutputLogging);
				if (com.eg.EgMemInfo.remoteEnabled && _user.getLoginRCEnabled())
				{
					/*String s_mode = com.egurkha.monitor.remotecontrol.PreAgentInfo.getAgentMode(agentIP);
					if(s_mode.equalsIgnoreCase("CRITICAL_MODE"))
					{
						s_mode="Critical";
					}
					else if(s_mode.equalsIgnoreCase("WAITING_MODE"))
					{
						s_mode="Waiting";
					}
					else
					{
						s_mode="Normal";
					}*/
					//obj.put("RemoteControl",restartFlg+"~"+agentIP+"~"+s_mode);
					obj.put("RemoteControl",restartFlg+"~"+agentIP+"~Normal");
				}
				else
				{
					obj.put("RemoteControl","no~"+agentIP+"~no");
				}
				agentsDetails.add(obj);
			}
		}
		else
		{
			rootJSON.put("enableSearch",false);
			rootJSON.put("managedHostsFoundForSearch",false);
		}
		rootJSON.put("agentDetails",agentsDetails);
	}

	session.setAttribute("list",csvData);
	session.setAttribute("isAuditlogCSV","true");
	out.println(rootJSON);
%>
<%!
	public String getAssignedHostsForExternalAgent(String agentName,ArrayList allNicks)
	{
		IniFile extIni = new IniFile(EgInstallInfo.getInstallDir() + "/manager/config/eg_external.ini");
		String[] vars = extIni.getVariables("Test_Mapping_Section");
		String res="";
		if (vars == null)
			return res;
		List tmpList = new ArrayList();
		com.eg.EgDiscInfo discInfoObj = new com.eg.EgDiscInfo("manager");
		String rumServerList[] = discInfoObj.getAllServersOfType("Real_user_monitor");
		ArrayList varsList = new ArrayList(Arrays.asList(vars));
		boolean isRUMCompExists = false;
		try{
			if (rumServerList != null ) {
				for (int a=0;a<rumServerList.length;a++) {
					String serverName = (String)rumServerList[a];
					if (serverName != null && serverName.startsWith("Real_user_monitor")) {
						try{
							serverName = serverName.substring(serverName.indexOf(":")+1,serverName.lastIndexOf(":"));
							isRUMCompExists = true;
						} catch(Exception ex){
							serverName = serverName;
						}
						varsList.remove(serverName);
					}
				}
			}
		}
		catch(Exception ex){
			ex.printStackTrace();
		}
		if (isRUMCompExists){
			vars = (String[])varsList.toArray(new String[varsList.size()]);
		}
		for (int v=0; v<vars.length; v++)
		{
			String host = vars[v];
			if (allNicks != null && allNicks.contains(host))
			{
				String agents = extIni.getValue("Test_Mapping_Section",host);
				StringTokenizer stt = new StringTokenizer(agents,",");
				while (stt.hasMoreTokens())
				{
					if (agentName.equals(stt.nextToken()))
					{
						//res += host+", ";
						tmpList.add(host);
						break;
					}
				}
			}
		}
		Collections.sort(tmpList, String.CASE_INSENSITIVE_ORDER);
		for (int t=0; t < tmpList.size(); t++)
		{
			String tmp = tmpList.get(t).toString();
			res += tmp+",";
		}
		res = res.trim();
		if (res.endsWith(","))
			res = res.substring(0,res.length()-1);
		return res;
	}

	public String getAssignedHostsForRemoteAgent(String agentName,ArrayList allNicks)
	{
		IniFile extIni = new IniFile(EgInstallInfo.getInstallDir() + "/manager/config/eg_external.ini");
		String[] vars = extIni.getVariables("Remote_Agent_Mapping_Section");
		String res="";
		if (vars == null)
			return res;
		List tmpList = new ArrayList();
		for (int v=0; v<vars.length; v++)
		{
			String host = vars[v];
			if (allNicks != null && allNicks.contains(host))
			{
				String agent = extIni.getValue("Remote_Agent_Mapping_Section",host);
				if (agent.equals(agentName))
				{
					//res += host+", ";
					tmpList.add(host);
				}
			}
		}
		Collections.sort(tmpList, String.CASE_INSENSITIVE_ORDER);
		for (int t=0; t < tmpList.size(); t++)
		{
			String tmp = tmpList.get(t).toString();
			res += tmp+",";
		}
		res = res.trim();
		if (res.endsWith(","))
			res = res.substring(0,res.length()-1);
		return res;
	}

	/*
	 * This method is used to get shared agent(s) among users
	 *
	 * [SHARED AGENT - component monitoring by an agent which are assigned by more than one limited admin user]
	 *
	 * 1. get all managed variables from eg_discover.ini by passing nicks and
	 * 2. compare it with managed variables(for single user) at 'user_serv' table
	 * 3. if 'user_serv' contains all the eg_discover.ini variables then no shared agents found
	 * 4. otherwise shared agents found.
	 *
	 */
	public ArrayList getUsersSharedAgents(ArrayList agentList, EgRoleInfo egRoleInfo, boolean ExtAgent, boolean RemAgent)
	{
		ArrayList userWiseCompList = egRoleInfo.getAllServers(); //Userwise managed components list
		ArrayList allCompNicks = egRoleInfo.getAllServerNicks();
		ArrayList userCompList = new ArrayList();
		ArrayList sharedAgents = new ArrayList();

		if(ExtAgent || RemAgent)
		{
			ArrayList usersNicks = new ArrayList();
			for(int a=0; a<agentList.size(); a++)
			{
				String temp = "";
				if(ExtAgent)
					temp = getAssignedHostsForExternalAgent((String)agentList.get(a),allCompNicks);
				else if(RemAgent)
					temp = getAssignedHostsForRemoteAgent((String)agentList.get(a),allCompNicks);
				if(temp.trim().length() > 0)
				{
					StringTokenizer tmpStrTknzr = new StringTokenizer(temp,",");
					while(tmpStrTknzr.hasMoreTokens())
					{
						String st = (String)tmpStrTknzr.nextToken();
						if(!usersNicks.contains(st))
						{
							usersNicks.add(st); //External/Remote Agent's all assigned hosts of corresponding user
						}
					}
				}
			}
			userCompList = getAllManagedComponents(usersNicks);
		}
		else
		{
			userCompList = getAllManagedComponents(agentList);
		}
		if(userCompList != null && userCompList.size() > 0)
		{
			for (int m=0; m<userCompList.size(); m++)
			{
				String host = (String)userCompList.get(m);
				if(userWiseCompList.contains(host))
					continue;
				else
				{
					host = host.substring(host.indexOf(":")+1);
					host = host.substring(0,host.indexOf(":"));
					if(!sharedAgents.contains(host))
					{
						sharedAgents.add(host);
					}
				}
			}
		}
		return sharedAgents;
	}

	/*
	 * This method is used to get all managed components from eg_discover.ini (from all users)
	 */
	public ArrayList getAllManagedComponents(ArrayList usersNicks)
	{
		com.eg.EgDiscInfo discInfoObj = new com.eg.EgDiscInfo("manager");
		ArrayList usersAllCompList = new ArrayList();

		if(usersNicks != null && usersNicks.size() > 0)
		{
			for(int r=0; r<usersNicks.size(); r++)
			{
				String tempHost = (String)usersNicks.get(r);
				ArrayList userComps = discInfoObj.getServersForHost(tempHost, true);
				usersAllCompList.addAll(userComps);
			}
		}
		return usersAllCompList;
	}

	/*
	 * This method is used to check whether the assigned host for external/remote agents shared among users or not
	 */
	public boolean isAssignedHostShared(boolean isNickShared, ArrayList sharedAgents, String hosts)
	{
		boolean isAssignedHostShared = false;
		if(sharedAgents != null)
		{
			int sharedAgentsSize = sharedAgents.size();
			if(isNickShared && sharedAgentsSize > 0)
			{
				ArrayList hostList = new ArrayList();
				StringTokenizer hostTknzr = new StringTokenizer(hosts, ",");
				while (hostTknzr.hasMoreTokens())
				{
					hostList.add(hostTknzr.nextToken());
				}
				sharedAgents.removeAll(hostList);
				if(sharedAgentsSize != sharedAgents.size())
				{
					isAssignedHostShared = true;
				}
			}
		}
		return isAssignedHostShared;
	}

	private ArrayList getSearchData(ArrayList usersList,String searchStr, boolean isSubstring)
	{
		ArrayList resultList = new ArrayList();
		int size = usersList.size();
		if (com.egurkha.util.StringUtils.isNull(searchStr))
		{
			return usersList;
		}

		ArrayList searchList = new ArrayList();
		if (searchStr.indexOf(" ") != -1)
		{
			searchList = com.egurkha.util.StringUtils.egTokenizer(searchStr, " ");
		}
		else
		{
			searchList.add(searchStr);
		}

		if (searchList != null && !searchList.isEmpty())
		{
			ArrayList tmpSrchList = new ArrayList();
			int count = searchList.size();
			for (int c=0;c<count;c++)
			{
				String strSearch = (String) searchList.get(c);
				if (com.egurkha.util.StringUtils.isNull(strSearch))
				{
					continue;
				}
				tmpSrchList.add(strSearch);
			}
			searchList = new ArrayList();
			searchList.addAll(tmpSrchList);
		}

		for (int s=0;s<size;s++)
		{
			String strValue = usersList.get(s).toString();
			String tmpUser = strValue;
			if (searchList != null && searchList.size() > 0)
			{
				int searchCnt = searchList.size();
				if (searchCnt == 1)
				{
					if (isMatch(tmpUser,searchList.get(0).toString(),true))
					{
						resultList.add(strValue);
					}
				}
				else
				{
					for (int i=0;i<searchCnt;i++)
					{
						String strSearchVal = searchList.get(i).toString();
						if (isMatch(tmpUser,strSearchVal,true))
						{
							resultList.add(strValue);
						}
					}
				}
			}
			else
			{
				resultList.add(strValue);
			}
		}
		return resultList;
	}

	public static boolean isMatch(String o,String ss,boolean isNotCaseSensitive)
	{
		String valueString=o;
		String searchString=ss;
		if ((o == null) && (ss == null))
			return true;

		if(isNotCaseSensitive)
		{
			valueString = o.toLowerCase();
			searchString = ss.toLowerCase();
		}
		boolean flag = false;
		if (valueString.indexOf(searchString) != -1)
		{
			flag = true;
		}

		return(flag);
	}

	private ArrayList getCSVData(Map allAgentsMap, ArrayList allCompNicks, String agentType, EgMappingInfo _mapping, Hashtable nick_ip_map, Hashtable debug_status,Vector compNickList,boolean autoIpNameCheck)
	{
		List assignHostList = new ArrayList();
		ArrayList csvData = new ArrayList();
		if(!allAgentsMap.isEmpty())
		{
			String agentIPNick = _mapping.getTextDescription("admin.agents.Agent IP/Nickname");
			String install = _mapping.getTextDescription("admin.agents.Installed");
			String status = _mapping.getTextDescription("admin.agents.Status");
			String outputEnabled = _mapping.getTextDescription("admin.agents.Output Logging Enabled");

			csvData.add(agentIPNick+","+install+","+status+","+outputEnabled);
			Iterator itr = allAgentsMap.keySet().iterator();
			while(itr.hasNext())
			{
				String agentIP = (String)itr.next();
				String agent_state = (String)allAgentsMap.get(agentIP);
				String installed = agent_state.substring(0,agent_state.indexOf("-"));
				String running = agent_state.substring(agent_state.indexOf("-")+1);

				JSONObject obj = new JSONObject();
				if(agentType.equalsIgnoreCase("ExternalAgents"))
				{
					String hosts = getAssignedHostsForExternalAgent(agentIP,allCompNicks);
					if(hosts.trim().equals(""))
					{
						hosts = "- No assigned hosts found -";
					}
					assignHostList.add(agentIP+"#@#"+hosts);
				}
				else if (agentType.equalsIgnoreCase("RemoteAgents"))
				{
					String hosts = getAssignedHostsForRemoteAgent(agentIP,allCompNicks);
					if(hosts.trim().equals(""))
					{
						hosts = "- No assigned hosts found -";
					}
					assignHostList.add(agentIP+"#@#"+hosts);
				}
				boolean statusNotFound=true;
				boolean output = false;
				String agent_ip_address=null;
				String agent_ip_address_arr[]=null;
				String debugStatus=null;
				if(nick_ip_map.containsKey(agentIP))
				{
					agent_ip_address = (String)nick_ip_map.get(agentIP);
					if(agent_ip_address != null && agent_ip_address.indexOf(":")>0)
					{
						agent_ip_address_arr = StringUtils.getTokens(agent_ip_address,":");
						if(agent_ip_address != null)
						{
							agent_ip_address_arr = StringUtils.getTokens(agent_ip_address,":");
						}
					}
				}
				if(autoIpNameCheck)
				{
					if(agent_ip_address_arr != null)
					{
						int ipsCount=agent_ip_address_arr.length;
						for(int j=0;j<ipsCount;j++)
						{
							agent_ip_address=agent_ip_address_arr[j];
							if(debug_status.containsKey(agent_ip_address))
							{
								debugStatus = (String)debug_status.get(agent_ip_address);
								statusNotFound=false;
								break;
							}
							else if(debug_status.containsKey(agent_ip_address.toUpperCase()))
							{
								debugStatus = (String)debug_status.get(agent_ip_address.toUpperCase());
								statusNotFound=false;
								break;
							}
							else if(debug_status.containsKey(agent_ip_address.toLowerCase()))
							{
								debugStatus = (String)debug_status.get(agent_ip_address.toLowerCase());
								statusNotFound=false;
								break;
							}
							else if(compNickList != null && (compNickList.contains(agentIP) || compNickList.contains(agentIP.toLowerCase()) || compNickList.contains(agentIP.toUpperCase())))
							{
								debugStatus = "yes";
								statusNotFound=false;
								break;
							}
						}
					}
				}
				if(statusNotFound)
				{
					if(agentIP != null && debug_status.containsKey(agentIP))
					{
						debugStatus = (String)debug_status.get(agentIP);
					}
					else if(agentIP != null && debug_status.containsKey(agentIP.toUpperCase()))
					{
						debugStatus = (String)debug_status.get(agentIP.toUpperCase());
					}
					else if(agentIP != null && debug_status.containsKey(agentIP.toLowerCase()))
					{
						debugStatus = (String)debug_status.get(agentIP.toLowerCase());
					}
					else if(compNickList != null && (compNickList.contains(agentIP) || compNickList.contains(agentIP.toLowerCase()) || compNickList.contains(agentIP.toUpperCase())))
					{
						debugStatus = "yes";
					}
				}
				if(debugStatus != null && debugStatus.equalsIgnoreCase("yes"))
				{
					output=true;
				}
				else
				{
					output=false;
				}

				String tempInstalled = "Yes";
				if (installed.equalsIgnoreCase("Not Installed"))
				{
					tempInstalled = "No";
				}

				String csvOutput = "No";
				if (output)
					csvOutput = "Yes";

				String installMapping = _mapping.getTextDescription("admin.common."+tempInstalled);
				String runMapping = _mapping.getTextDescription("admin.agents."+running);
				String outputMapping = _mapping.getTextDescription("admin.common."+csvOutput);
				csvData.add(agentIP+","+installMapping+","+runMapping+","+outputMapping);
			}
		}
		
		if (!assignHostList.isEmpty())
		{
			String agentIPs = "";
			int big = 0;
			ArrayList allAssignHosts = new ArrayList();
			for (int c=0; c<assignHostList.size(); c++)
			{
				String hostStr = assignHostList.get(c).toString();
				String agent = hostStr.substring(0,hostStr.indexOf("#@#"));
				String assignHosts = hostStr.substring(hostStr.indexOf("#@#")+3);
				ArrayList assignHostsList = StringUtils.egTokenizer(assignHosts,",");
				int size = 0;
				if (!assignHosts.equals("- No assigned hosts found -"))
				{
					size = assignHostsList.size();
				}
				agentIPs += agent +" ("+size+")"+",";
				if(size > big)
					big = size;

				allAssignHosts.add(assignHostsList);
			}
			csvData.add("");
			csvData.add("");
			csvData.add("Assigned Hosts");
			csvData.add("");
			csvData.add(agentIPs);
			csvData.add("");

			for (int b=0; b<big; b++)
			{
				String row = "";
				for(int a=0; a<allAssignHosts.size(); a++)
				{
					ArrayList tmpList = (ArrayList)allAssignHosts.get(a);
					if(b < tmpList.size())
					{
						row += tmpList.get(b).toString()+",";
					}
					else
					{
						row += ""+",";
					}
				}
				csvData.add(row);
			}
		}
		return csvData;
	}

	Vector disableIPList()
	{
		Vector ipList = new Vector();
		ipList.addAll(getAgentDebug("AGENT_DEBUG_OPERATION_DISABLED").keySet());
		Vector disableIps = new Vector();
		if(ipList == null && ipList.size() == 0)
			return disableIps;
		EgDiscInfo discInfo = new EgDiscInfo("manager");
		Hashtable ipNickMap = discInfo.getIpNickMap();
		Hashtable nickIpMap = discInfo.getNickIpMap(true);
		for(int j=0;j<ipList.size();j++)
		{
			String ip = (String)ipList.get(j);
			String nick = (String)ipNickMap.get(ip);
			String nickIp = (String)nickIpMap.get(ip);
			if(!disableIps.contains(ip))
			{
				disableIps.add(ip);
			}
			if(nickIp != null && !disableIps.contains(nickIp))
			{
				disableIps.add(nickIp);
			}
			if(nick == null)
				continue;
			if(nick.indexOf(":") >-1)
			{
				String[] nicks = StringUtils.getTokens(nick,":");
				for(int k=0;k<nicks.length;k++)
				{
					String nick1 = nicks[k];
					nickIp = (String)nickIpMap.get(nick1);
					if(!disableIps.contains(nick1))
					{
						disableIps.add(nick1);
					}
					if(nickIp != null && !disableIps.contains(nickIp))
					{
						disableIps.add(nickIp);
					}
				}
			}
			else
			{
				nickIp = (String)nickIpMap.get(nick);
				if(!disableIps.contains(nick))
				{
					disableIps.add(nick);
				}
				if(nickIp != null && !disableIps.contains(nickIp))
				{
					disableIps.add(nickIp);
				}
			}
		}
		return disableIps;
	}

	public ArrayList getAgentsBasedOnStatus(ArrayList agentList, String agentState, EgServerList serverList)
	{
		ArrayList resultAgentsList = new ArrayList();
		ArrayList totalAgents = null;

		ArrayList aList = serverList.getAgentListFromDB();
		String currList[] = serverList.getTargetNames();
		totalAgents = serverList.getAgentList(agentList,aList,currList);
		int size = totalAgents.size();

		if (size > 0)
		{
			for(int j=0;j<size;j=j+4)
			{
				String agentIP = (String)totalAgents.get(j);
				String message = (String)totalAgents.get(j+1);
				if (agentState.equalsIgnoreCase("NotRunning"))
				{
					if (message.equals("Not Installed-Not Running") || message.equals("Installed-Not Running"))
					{
						resultAgentsList.add(agentIP);
					}
				}
				else if (agentState.equalsIgnoreCase("Running"))
				{
					if(message.equals("Installed-Running"))
					{
						resultAgentsList.add(agentIP);
					}
				}
			}
		}

		return resultAgentsList;
	}

	public Hashtable getAgentDebug(String subject)
	{
		IniFile agentStatus_ini =  new IniFile(EgInstallInfo.getInstallDir() + 
			"/manager/config/eg_agentoutputstatus.ini");
		Hashtable agentDebugMap = new Hashtable();
		String[] ipStrAry = agentStatus_ini.getVariables(subject);
		if(ipStrAry != null && ipStrAry.length>0)
		{
			for(int i=0;i<ipStrAry.length;i++)
			{
				String delimiter = ":";
				if(ipStrAry[i].indexOf(com.eg.EgInstallInfo.ipV6Sep)>=0)
				{
					delimiter = com.eg.EgInstallInfo.ipV6Sep;
				}
				String[] ips = StringUtils.getTokens(ipStrAry[i],delimiter);
				if(ips == null || ips.length == 0)
					continue;
				for(int j=0;j<ips.length;j++)
				{
					agentDebugMap.put(ips[j],agentStatus_ini.getValue(subject,ipStrAry[i]));
				}
			}
		}
		return agentDebugMap;
	}
%>




