<%@ include file= "../../EgTrackerAJSON.jsp"%>
<%@ page language="java" contentType="application/json; charset=UTF-8" pageEncoding="UTF-8" %>
<%@ page import = "com.egurkha.ini.IniUI"%>
<%@ page import = "com.eg.EgName"%>
<%@ page import = "com.eg.EgDiscInfo"%>
<%@ page import = "com.eg.IniFile"%>
<%@ page import = "com.eg.EgInstallInfo"%>
<%@ page import = "com.eg.AgentConfig"%>
<%@ page import = "com.eg.EgAgentInfo"%>
<%@ page import = "com.eg.EgExternalInfo"%>
<%@ page import = "com.eg.EgSpecsInfo"%>
<%@ page import = "com.eg.EgLicenseInfo"%>
<%@ page import = "com.eg.EgAggregateInfo"%>
<%@ page import = "com.eg.MappingNameSorter"%>
<%@ page import = "com.eg.EgAggregateInfo"%>
<%@ page import = "com.egurkha.*" %>
<%@ page import = "com.egurkha.util.DateUtil"%>
<%@ page import = "com.egurkha.util.StringUtils"%>
<%@ page import = "com.egurkha.admin.AgentsUpgradeVO"%>
<%@ page import = "com.egurkha.admin.AuditLogThread"%>
<%@ page import="java.util.ArrayList"%>
<%@ page import="java.util.Vector"%>
<%@ page import="java.util.Hashtable"%>
<%@ page import="java.util.List"%>
<%@ page import="java.util.TreeSet"%>
<%@ page import="java.util.Collections"%>
<%@ page import="java.util.Arrays"%>
<%@ page import="java.util.StringTokenizer"%>
<%@ page import = "java.text.Format"%>
<%@ page import = "java.text.SimpleDateFormat"%>
<%@ page import="net.sf.json.*" %>
<%@ page import = "com.eg.EgDiscInfo"%>
<%@ page import = "com.eg.EgGroupInfo"%>

<%
	response.setContentType("application/json;charset=UTF-8");
	Vector aggregateTypes = new Vector();
	ArrayList totalResult=new ArrayList();
	if(EgInstallInfo.isAggregationSupported())
	aggregateTypes = new EgAggregateInfo("manager").getAggregateTypes();
	JSONObject rootJson = new JSONObject();
	JSONObject GRIDVALUES = new JSONObject();
	JSONArray GRID_ARRAY = new JSONArray();
	JSONObject Cmpt_Values = new JSONObject();
	JSONArray cmpt_type = new JSONArray();
	JSONObject total=new JSONObject();
	JSONArray Count = new JSONArray();
	JSONObject statusObj = new JSONObject();
	JSONArray statusArr = new JSONArray();
	JSONObject screenLabels =new JSONObject();
	JSONArray versionArr = new JSONArray();
	JSONArray osArr = new JSONArray();
	JSONObject groupObj = new JSONObject();
	JSONArray groupListArr = new JSONArray();
	session.removeAttribute("list");
	session.removeAttribute("isAuditlogCSV");

	Hashtable osMap = new Hashtable();
	osMap.put("NONE","None");
	osMap.put("AIX","AIX");
	osMap.put("HPUX","HP-UX");
	osMap.put("LINUX","Linux");
	osMap.put("SOLARIS","Solaris");
	osMap.put("TRU64","Tru64");
	osMap.put("WINDOWSNT","Windows XP");
	osMap.put("WINDOWS2000","Windows 2000");
	osMap.put("WINDOWS2003","Windows 2003");
	osMap.put("WINDOWS2008","Windows 2008");
	osMap.put("WINDOWS2012","Windows 2012");
	osMap.put("WINDOWS2016","Windows 2016");
	osMap.put("WINDOWS2019","Windows 2019");

	List csvList = new LinkedList();
	csvList.add("AGENT UPGRADE - ADVANCED SEARCH");
	csvList.add("");
	csvList.add("User name," + _user.getLoginID());
	String currentTime = new com.eg.EgDateInfo().egetDate();
	int idx = currentTime.indexOf(" ");
	String dateOnly = currentTime.substring(0,idx);
	String timeOnly = currentTime.substring(idx+1);
	String dispDate = com.egurkha.util.DateUtil.changeDateFormat(dateOnly,"dd/MM/yyyy",_user.getUserDateFormat());
	csvList.add("Date," + "\""+dispDate+" "+timeOnly+"\"");

	String selectedChoice = request.getParameter("choice");
	if(selectedChoice != null && selectedChoice.equalsIgnoreCase("Range"))
	{
		csvList.add("Search criteria,IP Address");
		String selectedTo = request.getParameter("to");
		String selectedFrom = request.getParameter("from");
		if(selectedFrom != null && selectedFrom.trim().length()>0)
		{
			csvList.add("From IP Address," + selectedFrom);
		}
		if(selectedTo != null && selectedTo.trim().length()>0)
		{
			csvList.add("To IP Address," + selectedTo);
		}
	}
	else
	{
		csvList.add("Search criteria,Component/Agent Type");
		String selectedNickName = request.getParameter("nickname");
		if(selectedNickName != null && selectedNickName.trim().length()>0)
		{
			selectedNickName = egurkha.EgUIUtils.decodeSecurityChar(selectedNickName);
			csvList.add("Component/Agent name," + selectedNickName);
		}
		String selectedServerType =request.getParameter("servertype");
		if(selectedServerType != null && selectedServerType.trim().length()>0)
		{
			csvList.add("Component/Agent type," + (selectedServerType.equalsIgnoreCase("all")?"All":selectedServerType.equalsIgnoreCase("Component_Groups")?"Component Group":selectedServerType));
		}
		String groupName = request.getParameter("groupName");
		if(groupName != null && groupName.trim().length()>0)
		{
			csvList.add("Component Group," + groupName);
		}
		String selectedStatus = request.getParameter("status");
		if(selectedStatus != null && selectedStatus.trim().length()>0)
		{
			csvList.add("Status," + selectedStatus);
		}
		String selectedAgentVersion = request.getParameter("s_agent_version");
		if(selectedAgentVersion != null && selectedAgentVersion.trim().length()>0)
		{
			csvList.add("Agent Version," + selectedAgentVersion);
		}
		String selectedAgentOs = request.getParameter("s_agent_os");
		if(selectedAgentOs != null && selectedAgentOs.trim().length()>0)
		{
			String upperCaseKey = selectedAgentOs.toUpperCase();
			if(osMap.containsKey(upperCaseKey))
			{
				String displayOsname=(String)osMap.get(upperCaseKey);
				csvList.add("Operating System," + displayOsname);
			}
			else
			{
				csvList.add("Operating System," + selectedAgentOs);
			}
		}
	}
	csvList.add("");
	String cp_Type=request.getParameter("servertype"); 
	IniUI ui = (IniUI)com.egurkha.ini.IniUI.getInstance();
	String refreshTime =ui.getRefreshTime("AutoUpgrade");
	try
	{
		refreshTime = (refreshTime != null && !refreshTime.equalsIgnoreCase("null") && refreshTime.length()>0)?refreshTime:"180";
		long temp = (new Long(refreshTime).longValue()) * 1000L;
		refreshTime = new Long(temp).toString();
	}
	catch(Exception e)
	{
		refreshTime = "180000";//default 3 minutes
	}

	String sessId = request.getParameter("sessionId");
	if (sessId == null)
		sessId = session.getId();
		
	User user = UserRegistry.getInstance().getUser(sessId,true);

	EgDiscInfo discInfo = new EgDiscInfo("manager");
	Vector v_allComps = discInfo.getAllManagedComponents();
	Vector Comp_Name=new Vector();
	for(int i=0;i < v_allComps.size(); i++)
	{
		String component=(String)v_allComps.elementAt(i);
		String serverName=component.substring(0,component.indexOf(","));
		if(!Comp_Name.contains(serverName))
			Comp_Name.add(serverName);
	}
	EgGroupInfo groupInfo = new EgGroupInfo();
	String[] groupList = groupInfo.getGroupNames();
	boolean groupCreated = groupList != null && groupList.length > 0;

	String allComponents[] = (String[])Comp_Name.toArray(new String[0]);
	String userLanguage = user.getLanguage();
	MappingNameSorter sorter = new MappingNameSorter(userLanguage);
	ArrayList serverList = sorter.getSortedCompTypeList(allComponents);
	Cmpt_Values.put("displayField",_mapping.getTextDescription("admin.upgrade.All"));
	Cmpt_Values.put("valueField","all");
	cmpt_type.add(Cmpt_Values);
	Cmpt_Values.put("displayField",_mapping.getTextDescription("admin.upgrade.External Agent"));
	Cmpt_Values.put("valueField","External Agent");
	cmpt_type.add(Cmpt_Values);
	Cmpt_Values.put("displayField",_mapping.getTextDescription("admin.upgrade.Remote Agent"));
	Cmpt_Values.put("valueField","Remote Agent");
	cmpt_type.add(Cmpt_Values);
	if(groupCreated)
	{
		Cmpt_Values.put("displayField",_mapping.getTextDescription("admin.upgrade.Component Group"));
		Cmpt_Values.put("valueField","Component_Groups");
		cmpt_type.add(Cmpt_Values);
	}
	for(int i=0;i<serverList.size();i++)
	{
		EgName nameObj = (EgName)serverList .get(i);
		String tmpVal = nameObj.getActualName();
		if(tmpVal.startsWith("Agg_"))
		{
			continue;
		}
		String tmpDis = nameObj.getLocalName();
		Cmpt_Values.put("displayField",tmpDis);
		Cmpt_Values.put("valueField",tmpVal);
		cmpt_type.add(Cmpt_Values);
		
	}
	if(groupCreated)
	{
		int gcount = groupList.length;
		for(int i=0;i<gcount;i++)
		{
			String groupName = groupList[i];
			groupObj.put("displayField",groupName);
			groupObj.put("valueField",groupName);
			groupListArr.add(groupObj);
		}
	}
	IniFile iniUiObj = new IniFile(EgInstallInfo.getInstallDir()+ "/manager/config/eg_ui.ini");
	String name_column = iniUiObj.getValue("DISPLAY_CHARACTERS_COUNT","Component_name");
	String type_column = iniUiObj.getValue("DISPLAY_CHARACTERS_COUNT","Component_type");
	String agent_name_column = iniUiObj.getValue("DISPLAY_CHARACTERS_COUNT","Agent_name");
	
	int componentName_columnWidth = getCharactersCountToDisplay(name_column);
	int componentType_columnWidth = getCharactersCountToDisplay(type_column);
	int agentName_columnWidth = getCharactersCountToDisplay(agent_name_column);

	/* code for auditlog starts */
	AuditLogThread auditLogThread = new AuditLogThread();
	auditLogThread.setValue("Category","Admin");
	auditLogThread.setValue("User_id",user.getLoginID());
	auditLogThread.setValue("Host_ip",user.getUserIP(sessId));
	auditLogThread.setValue("Session_id",sessId);
	auditLogThread.setValue("Module","Agents Upgrade");
	/* code for auditlog ends */

	AgentConfig agentConfig = AgentConfig.getAgentConfig();
	String sai = request.getParameter("sai");//sai - selected agent ids
	String currentOption = request.getParameter("option");
	String ugne = request.getParameter("default_upgrade_now_enabled");
	ugne = (ugne==null || ugne.equalsIgnoreCase("null")|| ugne.length()==0)?"No":ugne;//ugne - upgrade now enabled
	String displayOnly = request.getParameter("displayOnly");
	displayOnly = (displayOnly==null || displayOnly.equalsIgnoreCase("null") || displayOnly.length()==0)?"Yes":displayOnly;
	if(currentOption!=null && !currentOption.equalsIgnoreCase("null") && currentOption.length()>0 && displayOnly.equalsIgnoreCase("no"))
	{
		Vector upgradeDelVal = new Vector();
		ArrayList aListUpgradeEnableAgentIds = new ArrayList();
		//Changed By Inbaraj
		String fileName = "";
		IniFile servicesIniRead = new IniFile(EgInstallInfo.getInstallDir() + "/manager/config/eg_services.ini");
		String autoUpgradeInfo = servicesIniRead.getValue("MISC_ARGS","AutoUpgradeInfo");
		if(autoUpgradeInfo !=null && !autoUpgradeInfo.equals("") && autoUpgradeInfo.equalsIgnoreCase("eg_autoupgrade"))
		{
			fileName = "eg_autoupgrade.ini";
		}
		else
		{
			fileName = "eg_tests.ini";
		}
		if(currentOption.equalsIgnoreCase("setAutoUpgrade"))
		{
			//IniFile ini_write1 = new IniFile(EgInstallInfo.getInstallDir() + "/manager/config/" + fileName, true);
			IniFile ini_write1 = EgConfigFilesSync.getInstance(EgInstallInfo.getInstallDir() + "/manager/config/" + fileName);
			StringTokenizer stoken = new StringTokenizer(sai,"$");
			boolean success = false;
			while(stoken.hasMoreTokens())
			{
				String aid = (String) stoken.nextToken();
				aListUpgradeEnableAgentIds.add(aid);
				//agentConfig.enableDisableAutoUpgrade(aid,"true");
				StringTokenizer stoken1 = new StringTokenizer(aid,":");
				upgradeDelVal = new Vector();
				while(stoken1.hasMoreTokens())
				{
					String temp1 = (String) stoken1.nextToken();
					upgradeDelVal.add(temp1.trim());
					//ini_write1.deleteValue("UPGRADE_NOW",temp1.trim());
					success = true;
				}
				ini_write1.deleteValues("UPGRADE_NOW",upgradeDelVal);
				auditLogThread.setCurrentValue("Agent ID",aid);
			}
			if(success)
			{
				auditLogThread.setValue("Activity","Auto upgrade");
				auditLogThread.setValue("Description","Auto upgrade is enabled for agents");
				auditLogThread.sendItToDB();
			}
			if(aListUpgradeEnableAgentIds!=null && aListUpgradeEnableAgentIds.size()>0)
			{
				agentConfig.enableDisableAutoUpgrade(aListUpgradeEnableAgentIds,"true");
			}
			ini_write1.saveFile();
			EgConfigFilesSync.releaseInstance(ini_write1);
		}
		else if(currentOption.equalsIgnoreCase("resetAutoUpgrade"))
		{
			ArrayList aListUpgradeDisableAgentIds = new ArrayList();
			//IniFile ini_write1 = new IniFile(EgInstallInfo.getInstallDir() + "/manager/config/eg_tests.ini", true);
			IniFile ini_write1 = EgConfigFilesSync.getInstance(EgInstallInfo.getInstallDir() + "/manager/config/"+fileName);
			StringTokenizer stoken = new StringTokenizer(sai,"$");
			boolean success = false;
			while(stoken.hasMoreTokens())
			{
				String aid = (String) stoken.nextToken();
				aListUpgradeDisableAgentIds.add(aid);
				//agentConfig.enableDisableAutoUpgrade(aid,"false");
				StringTokenizer stoken1 = new StringTokenizer(aid,":");
				upgradeDelVal = new Vector();
				while(stoken1.hasMoreTokens())
				{
					String temp1 = (String) stoken1.nextToken();
					upgradeDelVal.add(temp1.trim());
					//ini_write1.deleteValue("UPGRADE_NOW",temp1.trim());
					success = true;
				}
				ini_write1.deleteValues("UPGRADE_NOW",upgradeDelVal);
				auditLogThread.setCurrentValue("Agent ID",aid);
			}
			if(success)
			{
				auditLogThread.setValue("Activity","Auto upgrade");
				auditLogThread.setValue("Description","Auto upgrade is disabled for agents");
				auditLogThread.sendItToDB();
			}
			if(aListUpgradeDisableAgentIds!=null && aListUpgradeDisableAgentIds.size()>0)
			{
				agentConfig.enableDisableAutoUpgrade(aListUpgradeDisableAgentIds,"false");
			}
			ini_write1.saveFile();
			EgConfigFilesSync.releaseInstance(ini_write1);
		}
		else if(currentOption.equalsIgnoreCase("upgradeNow"))
		{
			aListUpgradeEnableAgentIds = new ArrayList();
			//IniFile ini_write1 = new IniFile(EgInstallInfo.getInstallDir() + "/manager/config/eg_tests.ini", true);
			IniFile ini_write1 = EgConfigFilesSync.getInstance(EgInstallInfo.getInstallDir() + "/manager/config/"+fileName);
			boolean success = false;
			if(ugne.equalsIgnoreCase("yes"))
			{
				StringTokenizer stoken = new StringTokenizer(sai,"$");
				int i=0;

				String allIds[] = new String[stoken.countTokens()];
				while(stoken.hasMoreTokens())
				{
					allIds[i++] = (String) stoken.nextToken();
				}
				for( i=0;i<allIds.length;i++)
				{
					//agentConfig.enableDisableAutoUpgrade(allIds[i],"true");
					aListUpgradeEnableAgentIds.add(allIds[i]);
					StringTokenizer stoken1 = new StringTokenizer(allIds[i],":");
					while(stoken1.hasMoreTokens())
					{
						String temp1 = (String) stoken1.nextToken();
						ini_write1.setValue("UPGRADE_NOW",temp1,temp1.trim());
						success = true;
					}
					auditLogThread.setCurrentValue("Agent ID",allIds[i]);
				}
				if(aListUpgradeEnableAgentIds!=null && aListUpgradeEnableAgentIds.size()>0)
				{
					agentConfig.enableDisableAutoUpgrade(aListUpgradeEnableAgentIds,"true");
				}
			}
			else
			{
					StringTokenizer stoken = new StringTokenizer(sai,"$");
					while(stoken.hasMoreTokens())
					{
						String aid = (String) stoken.nextToken();
						if(!agentConfig.isAutoUpgradeEnabled(aid.trim()))
						continue;
						StringTokenizer stoken1 = new StringTokenizer(aid,":");
						while(stoken1.hasMoreTokens())
						{
							String temp1 = (String) stoken1.nextToken();
							ini_write1.setValue("UPGRADE_NOW",temp1,temp1.trim());
							success = true;
						}
						auditLogThread.setCurrentValue("Agent ID",aid);
					}
			}
			if(success)
			{
				auditLogThread.setValue("Activity","Upgrade Now");
				auditLogThread.setValue("Description","Upgrade now is enabled for agents");
				auditLogThread.sendItToDB();
			}
			ini_write1.saveFile();
			EgConfigFilesSync.releaseInstance(ini_write1);
		}
		else
		{
			//IniFile ini_write1 = new IniFile(EgInstallInfo.getInstallDir() + "/manager/config/eg_tests.ini", true);
			IniFile ini_write1 = EgConfigFilesSync.getInstance(EgInstallInfo.getInstallDir() + "/manager/config/"+fileName);
			StringTokenizer stoken = new StringTokenizer(sai,"$");
			boolean success = false;
			while(stoken.hasMoreTokens())
			{
				String aid = (String) stoken.nextToken();
				StringTokenizer stoken1 = new StringTokenizer(aid,":");
				upgradeDelVal = new Vector();
				while(stoken1.hasMoreTokens())
				{
					String temp1 = (String) stoken1.nextToken();
					upgradeDelVal.add(temp1.trim());
					//ini_write1.deleteValue("UPGRADE_NOW",temp1.trim());
					success = true;
				}
				ini_write1.deleteValues("UPGRADE_NOW",upgradeDelVal);
				auditLogThread.setCurrentValue("Agent ID",aid);
			}
			if(success)
			{
				auditLogThread.setValue("Activity","Upgrade Now");
				auditLogThread.setValue("Description","Upgrade now is disabled for agents");
				auditLogThread.sendItToDB();
			}
			ini_write1.saveFile();
			EgConfigFilesSync.releaseInstance(ini_write1);
		}
	}

	EgAgentInfo ai = new EgAgentInfo("manager");
	EgSpecsInfo egSpecsInfo = new EgSpecsInfo("manager");
	EgExternalInfo egExternalInfo = new EgExternalInfo("manager");
	Hashtable ipHashtable = new Hashtable();
	String[] est = egSpecsInfo.getAllExternalServerTypes();
	String[] allextagents = egExternalInfo.getAllExternalAgents();
	Hashtable hostAgentMap = new Hashtable();

	String pageNoStr = request.getParameter("pageNo");
	if(pageNoStr == null || pageNoStr.equals("null") || pageNoStr.length() == 0)
	{
		session.removeAttribute("dispTable");
		pageNoStr = "1";
	}
	for(int d=0;d<est.length;d++)
	{
		
		String[] servers = discInfo.getAllServersOfType (est[d]);
		for(int e=0;e<servers.length;e++)
		{	
			String host = servers[e].substring(servers[e].indexOf(":")+1);
			host = host.substring(0,host.indexOf(":"));
			String[] extAgents = egExternalInfo.getExternalAgentsForHost(host);
			if(extAgents !=null && extAgents.length>0)
			{
				hostAgentMap.put(host,java.util.Arrays.asList(extAgents));
				for(int f=0;f<extAgents.length;f++)
				{
					if(!ipHashtable.containsKey(extAgents[f]))
					{
						ArrayList al = new ArrayList();
						al.add(host);
						ipHashtable.put(extAgents[f],al);
					}
					else
					{
						ArrayList al = (ArrayList) ipHashtable.get(extAgents[f]);
						al.add(host);
						ipHashtable.put(extAgents[f],al);
					}
				}
			}
		}
	}	
	String[] remComps = egExternalInfo.getRemoteComponents();
	
	if(remComps != null && remComps.length > 0)
	{
		for(int m=0;m<remComps.length;m++)
		{
			String tmp = remComps[m];
			String tmp1 = egExternalInfo.getRemoteAgentForHost(tmp);
			String tmpIPAddress = egExternalInfo.getIpForRemoteAgent(tmp1);

			if(tmpIPAddress == null)
				continue;
			if(!ipHashtable.containsKey(tmpIPAddress))
			{
				ArrayList al = new ArrayList();
				al.add(tmp);
				ipHashtable.put(tmpIPAddress,al);
			}
			else
			{
				ArrayList al = (ArrayList) ipHashtable.get(tmpIPAddress);
				al.add(tmp);
				ipHashtable.put(tmpIPAddress,al);
			}
		}
	}
	String status = "";
	String agentName = "";
	IniFile ini_services = new IniFile(EgInstallInfo.getInstallDir() + "/manager/config/eg_services.ini");
	String defaultUpgradeValue=ini_services.getValue("MISC_ARGS","DefaultAutoUpgrade");
	String allowQualifiedHostNames = ini_services.getValue("MISC_ARGS","AllowQualifiedHostNames");
	allowQualifiedHostNames = StringUtils.isNull(allowQualifiedHostNames)?"yes":allowQualifiedHostNames.trim();
	Hashtable statusHash = new Hashtable();
	Hashtable agentList = new Hashtable(25);
	Vector agentListWithStatus = agentConfig.getUpgradeStatusForAllAgents();
	ArrayList ipList = new ArrayList();
	for(int i=0;i<agentListWithStatus.size();i++)
	{
		StringTokenizer str1 = new StringTokenizer((String)agentListWithStatus.elementAt(i), ",");
		agentName = str1.nextToken();
		status = str1.nextToken();
		StringTokenizer str2 = new StringTokenizer(agentName, ":");
		String ipStr = "";
		while(str2.hasMoreTokens())
		{
			ipStr = str2.nextToken();
			statusHash.put(ipStr, status);
			ipList.add(ipStr);
		}
	}
	ArrayList validAgents = ai.getValidAgentsFromList (ipList);
	for (int i=0; i<validAgents.size(); i++)
	{
		String me = (String) validAgents.get(i);
		String st = (String) statusHash.get(me);
		if (st != null)
		{
			agentList.put(me,st);
		}
	}

	String csvTableHeading = "";
	csvTableHeading += _mapping.getTextDescription("admin.common.Component/Agent name")+",";
	csvTableHeading += _mapping.getTextDescription("admin.common.Component/Agent type")+",";
	csvTableHeading += _mapping.getTextDescription("admin.upgrade.Agent Name")+",";
	csvTableHeading += _mapping.getTextDescription("admin.upgrade.Auto Upgrade")+",";
	csvTableHeading += _mapping.getTextDescription("admin.upgrade.Upgrade Now")+",";
	csvTableHeading += _mapping.getTextDescription("admin.upgrade.Version")+",";
	csvTableHeading += _mapping.getTextDescription("admin.upgrade.Agent Operating System")+",";
	csvTableHeading += _mapping.getTextDescription("admin.upgrade.Last Upgrade Package")+",";
	csvTableHeading += _mapping.getTextDescription("admin.upgrade.Last Upgrade Time");
	csvList.add(csvTableHeading);

	ArrayList dispTable = getAgentDetailsToDisplay(request, agentConfig, remComps, egExternalInfo, agentList, hostAgentMap, ipHashtable, allowQualifiedHostNames);	
	ArrayList managedNicks = discInfo.getAllManagedNames();
	int jCount = managedNicks.size();
	Hashtable managedNicksHt = new Hashtable();
	for(int j=0;j<jCount;j++)
	{
		String s = (String)managedNicks.get(j);
		managedNicksHt.put(s.toUpperCase(),s);
	}
	for(int j=0; j < dispTable.size(); j++)
	{
		String csvString="";
		AgentsUpgradeVO vo = (AgentsUpgradeVO) dispTable.get(j);
		String id=vo.getId();
		GRIDVALUES.put("id",id+"_"+j);
		// Component Name		
		String currentInfo = vo.getComponentName();	
		String temp = currentInfo;
	
	
		if(currentInfo.length()>componentName_columnWidth)
		{
			currentInfo = currentInfo.substring(0,componentName_columnWidth)+"...";
		}		
		GRIDVALUES.put("componentName",temp);
		csvString=temp;
		//Component type
		String compTypesTmp = vo.getComponentType();
		String totalStr = "";
		String tarray[] = StringUtils.getTokens(compTypesTmp,",");
		if(tarray != null && tarray.length>0)
		{
			for(int f=0;f<tarray.length;f++)
			{
				totalStr += "," + _mapping.getComponentTypeDescription(tarray[f]);
			}
			totalStr = totalStr.substring(1);
		}
		GRIDVALUES.put("componentType",totalStr);
		csvString +=  "," + "\""+totalStr+"\"";

		//Agent name
		currentInfo=vo.getAgentName();
		String agentArray[] = StringUtils.getTokens(currentInfo,":");
		int count = agentArray.length;
		String currentInfoForCSV="";
		currentInfo="";
		ArrayList alist = new ArrayList();
		for(int i=0;i<count;i++)
		{
			String str = agentArray[i];
			String s = str.toUpperCase();
			if(!alist.contains(s))
			{
				alist.add(s);
				if(managedNicksHt.containsKey(s))
				{
					str = (String)managedNicksHt.get(s);
				}
				currentInfo += ", " + str;
				currentInfoForCSV += ":" + str;
			}
		}
		if(currentInfo.length()>0)
		{
			currentInfo=currentInfo.substring(2);
			csvString +=  "," + currentInfoForCSV.substring(1);
		}
		alist.clear();
		alist=null;
		String strEncodeAgentNick = vo.getAgentIP();
		try
		{
			if(strEncodeAgentNick!=null && strEncodeAgentNick.length()>0)
				strEncodeAgentNick = com.eg.EgURLEncoder.encode(strEncodeAgentNick,"UTF-8");
		}
		catch(Exception e)
		{

		}
		String HrefValues=currentInfo+"@"+strEncodeAgentNick;
		GRIDVALUES.put("agentName",HrefValues);
		//Auto Upgrade
		String auto_Upgrade=vo.getAutoUpgrade();
		GRIDVALUES.put("autoUpgrade",auto_Upgrade);
		csvString +=  "," + auto_Upgrade;

		//Upgrade Now
		String upgrade_Now=vo.getUpgradeNowFlag();
		GRIDVALUES.put("upgradeNow",upgrade_Now);
		csvString +=  "," + upgrade_Now;

		//version
		String version =vo.getAgentVersion();
		GRIDVALUES.put("version",version);
		csvString +=  "," + version;
		
		//operating System
		currentInfo = vo.getAgentOS();
		String upperCaseKey = currentInfo.toUpperCase();
		if(osMap.containsKey(upperCaseKey))
		{
			currentInfo=(String)osMap.get(upperCaseKey);
		}
		GRIDVALUES.put("operatingSystem",currentInfo);
		csvString +=  "," + currentInfo;
		
		//LastUpgraded pack
		currentInfo = vo.getLastUpgradePack();
		GRIDVALUES.put("lastUpgradepack",currentInfo);
		csvString +=  "," + currentInfo;
		
		//LastUpgrade time
		GRIDVALUES.put("lastupgradeTime",vo.getLastUpgradedTime());
		GRID_ARRAY.add(GRIDVALUES);
		csvString +=  "," + vo.getLastUpgradedTime().replace(","," ");
		csvList.add(csvString);
		
	}
	session.setAttribute("list",csvList);
	session.setAttribute("isAuditlogCSV","true");
	int totalResultCount=totalResult.size();
	total.put("count",totalResultCount);		
%>
<%!
//method starts

	int getCharactersCountToDisplay(String countStr)
	{
		int val = 20;
		try
		{
			val = Math.abs(Integer.parseInt(countStr));
		}
		catch(Exception e)
		{
			val = 20;
		}
		finally
		{
			return val;
		}
	}

	boolean checkIPRange(String fromIP, String toIP, String currentIP)
	{
		StringTokenizer st1 = new StringTokenizer(fromIP,".");
		StringTokenizer st2 = new StringTokenizer(toIP,".");
		StringTokenizer st3 = new StringTokenizer(currentIP,".");
		long ip1 = 0;
		long ip2 = 0;
		long ip3 = 0;
		String str1,str2,str3; 
		
		while(st1.hasMoreTokens())
		{
			str1 = (String) st1.nextToken();
			str2 = (String) st2.nextToken();
			str3 = (String) st3.nextToken();
				
			try
			{
				ip1 = (new Long(str1)).longValue();
				ip2 = (new Long(str2)).longValue();
				ip3 = (new Long(str3)).longValue();
			}
			catch(NumberFormatException e)
			{
				return false;
			}
			if (( ip3 >= ip1 ) && ( ip3 < ip2 ))
			{
				return true;
			}
			else if(( ip3 < ip1 ) || ( ip3 > ip2 ))
			{
				return false;
			}
		}
		return true;
	}

	String checkForRemoteComponent(String[] remComps, EgExternalInfo egExternalInfo, String remoteComponent)
	{
		List list = Arrays.asList(remComps);
		if(list.contains(remoteComponent))
			return egExternalInfo.getRemoteAgentForHost(remoteComponent);
		else
			return "-1";
	}

	String checkForExternalAgent(Hashtable agentIpHashtable, Hashtable hostAgentMap, String host, String ipAddress)
	{
		List list = (List) hostAgentMap.get(host);
		if(list !=null && list.size()>0)
		{
			return (String)agentIpHashtable.get(ipAddress);
		}
		else
			return "-1";
	}

	boolean isValidIPAddress(String ipAddress)
	{
		String a[] = StringUtils.getTokens(ipAddress,".");
		if(a==null || a.length!=4)
			return false;
		for(int i=0;i<a.length;i++)
		{
			try
			{
				if(Integer.parseInt(a[i]) > 255 || Integer.parseInt(a[i]) < 0 )
					return false;
			}
			catch(Exception e)
			{
				return false;
			}
		}
		return true;
	}

	public ArrayList getAgentDetailsToDisplay(HttpServletRequest request, AgentConfig agentConfig, String[] remComps, EgExternalInfo egExternalInfo, Hashtable agentList, Hashtable hostAgentMap, Hashtable ipHashtable, String allowQualifiedHostNames)
	{
		String defaultAgent =new EgSpecsInfo("manager").getEGServer();
		ArrayList pureExtAgents = new ArrayList();
		String[] allextagents = egExternalInfo.getAllExternalAgents();
		if(allextagents != null && allextagents.length>0)
		{
			pureExtAgents.addAll(Arrays.asList(allextagents));
		}
		ArrayList pureRemAgents = new ArrayList();
		String[] allremagents = egExternalInfo.getAllRemoteAgents();
		if(allremagents != null && allremagents.length>0)
		{
			pureRemAgents.addAll(Arrays.asList(allremagents));
		}
		IniFile iniui = new IniFile(EgInstallInfo.getInstallDir()+ "/manager/config/eg_ui.ini");
		String currentDateFormat = iniui.getValue("CURRENT_DATE_FORMAT","selectedDateFormat");
		EgLicenseInfo licenseInfo = new EgLicenseInfo();
		ArrayList listOfExternalAgents = licenseInfo.getExternalAgents();
		ArrayList listOfRemoteAgents = licenseInfo.getRemoteAgents();
		Hashtable agentIpHashtable = new Hashtable();
		Hashtable results = agentConfig.getAllAgentDetails();
		EgDiscInfo discObj = new EgDiscInfo("manager");
		Hashtable htt = discObj.getIpNickMap();
		Hashtable ht = discObj.getNickIpMap();
		String ids[] = 	agentConfig.getArrayOfAgentIDs();
		boolean vladimir = true;
		boolean rowCount = true;
		Format formatter = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
		ArrayList finalResult = new ArrayList();
		//Changed By Inbaraj
		IniFile servicesIniRead = new IniFile(EgInstallInfo.getInstallDir() + "/manager/config/eg_services.ini");
		String fileName = "";
		String autoUpgradeInfo = servicesIniRead.getValue("MISC_ARGS","AutoUpgradeInfo");
		if(autoUpgradeInfo != null && !autoUpgradeInfo.equals("") && autoUpgradeInfo.equalsIgnoreCase("eg_autoupgrade"))
		{		
			fileName = "eg_autoupgrade.ini";
		}
		else
		{
			fileName = "eg_tests.ini";
		}
		IniFile ini_read = new IniFile(EgInstallInfo.getInstallDir() + "/manager/config/" + fileName);
		String upgradeNowAgents[] = ini_read.getVariables("UPGRADE_NOW");
		Vector aggregateTypes = new Vector();
		if(EgInstallInfo.isAggregationSupported())
			aggregateTypes = new EgAggregateInfo("manager").getAggregateTypes();

		String option = "all";
		String selectedNickName = request.getParameter("nickname");
		String selectedTo = request.getParameter("to");
		String selectedFrom = request.getParameter("from");
		String selectedChoice = request.getParameter("choice");
		String selectedServerType =request.getParameter("servertype");
		String selectedStatus = request.getParameter("status");
		String selectedAgentVersion = request.getParameter("s_agent_version");
		String selectedAgentOs = request.getParameter("s_agent_os");
		if(selectedNickName==null)selectedNickName="";
		if(selectedTo==null)selectedTo="";
		if(selectedFrom==null)selectedFrom="";
		if(selectedChoice==null)selectedChoice="";
		if(selectedStatus==null)selectedStatus="";
		//if(selectedServerType==null)selectedServerType="All";
		EgGroupInfoAdmin groupInfoAdmin = new EgGroupInfoAdmin();
		Vector comp_types_under_group = null;
		ArrayList components_under_group = null;

		String selectedGroupName = null;
		if(selectedServerType !=null && selectedServerType.equalsIgnoreCase("Component_Groups"))
		{
			selectedGroupName = request.getParameter("groupName");
		}
		Enumeration enu = request.getParameterNames();
		while(enu.hasMoreElements())
		{
			String stt = (String)enu.nextElement();
		}
		if(selectedFrom !=null && selectedFrom.length()>0)
		{
			option = "onlyIPBased";
		}
		else if(selectedNickName !=null && selectedNickName.length() > 0 && selectedServerType !=null && selectedServerType.equalsIgnoreCase("all") && (selectedFrom ==null || selectedFrom.length()==0))
		{
			option = "onlyNickBased";
		}
		else if((selectedNickName ==null || selectedNickName.length() == 0) && selectedServerType !=null && selectedServerType.equalsIgnoreCase("all") && (selectedFrom ==null || selectedFrom.length()==0))
		{
			option = "onlyAllServerBased";
		}
		else if((selectedNickName !=null && selectedNickName.length() > 0) && selectedServerType !=null && selectedServerType.equalsIgnoreCase("all") && (selectedFrom ==null || selectedFrom.length()==0))
		{
			option = "nickAllServerBased";
		}
		else if((selectedNickName ==null || selectedNickName.length() == 0) && selectedServerType !=null && selectedServerType.equalsIgnoreCase("Component_Groups") && (selectedFrom ==null || selectedFrom.length()==0))
		{
			comp_types_under_group = groupInfoAdmin.getComponentTypes("Group",selectedGroupName);
			components_under_group=groupInfoAdmin.getAllComponentsUnderGroup("Group:"+selectedGroupName+":NULL");
			option="specificServersBasedForGroup";

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

			if(components_under_group == null)
				components_under_group = new ArrayList();
		}
		else if((selectedNickName !=null && selectedNickName.length() > 0) && selectedServerType !=null && selectedServerType.equalsIgnoreCase("Component_Groups") && (selectedFrom ==null || selectedFrom.length()==0))
		{
			comp_types_under_group = groupInfoAdmin.getComponentTypes("Group",selectedGroupName);
			components_under_group=groupInfoAdmin.getAllComponentsUnderGroup("Group:"+selectedGroupName+":NULL");
			option = "nickSpecifiServersBasedForGroup";

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

			if(components_under_group == null)
				components_under_group = new ArrayList();
		}
		else if((selectedNickName ==null || selectedNickName.length() == 0) && selectedServerType !=null && !selectedServerType.equalsIgnoreCase("all") && (selectedFrom ==null || selectedFrom.length()==0))
		{
			option = "specificServerBased";
		}
		else if((selectedNickName !=null && selectedNickName.length() > 0) && selectedServerType !=null && !selectedServerType.equalsIgnoreCase("all") && (selectedFrom ==null || selectedFrom.length()==0))
		{
			option = "nickSpecifiServerBased";
		}

		ArrayList managedNicks = discObj.getAllManagedNames();
		Hashtable hh = null;
		boolean chkIPRange = false;
		for(int i=0;i<ids.length;i++)
		{
			String agentsAllInfosString = (String) results.get(ids[i]);
			String agentsAllInfosStringArray[] = StringUtils.getTokens(agentsAllInfosString,",");
			String agentOs = agentsAllInfosStringArray[4];
			if(selectedAgentOs != null && (!selectedAgentOs.equalsIgnoreCase("all") && !selectedAgentOs.equals(agentOs)))
			{
				continue;
			}
			String agentVersion = agentsAllInfosStringArray[5];
			if(agentVersion ==null || agentVersion.equalsIgnoreCase("null"))
				continue;
			if(selectedAgentVersion != null && (!selectedAgentVersion.equalsIgnoreCase("all") && !selectedAgentVersion.equals(agentVersion)))
			{
				continue;
			}
			Vector nicks = new Vector();
			String allAgents[] = StringUtils.getTokens(ids[i],":");
			String global = allAgents[0];
			String ipAddress = (String) ht.get(global);
			for(int s=0;s<allAgents.length;s++)
			{
				String compNick = allAgents[s];
				if(!managedNicks.isEmpty() && managedNicks.contains(compNick))
				{
					global = compNick;
					break;
				}
			}
			if(ht.containsKey(global))
			{
				ipAddress = (String) ht.get(global);
			}
			else 
			{
				Iterator itr = ht.keySet().iterator();
				while(itr.hasNext())
				{
					String s = (String)itr.next();
					if(s.equalsIgnoreCase(global))
					{
						ipAddress = (String) ht.get(s);
						break;
					}
				}
			}
			if (ipAddress == null)
			{
				continue;
			}
			if(allowQualifiedHostNames.equalsIgnoreCase("no"))
			{
				if(ipAddress ==null || ipAddress.equalsIgnoreCase("null") || !isValidIPAddress(ipAddress))
				{
					continue;
				}
			}
			String sbb = ids[i];
			for(int j=0;j<allAgents.length;j++)
			{
				String newS = allAgents[j];
				String thisIpAddress = (String)ht.get(newS);
				if(ht.containsKey(newS))
				{
					thisIpAddress = (String) ht.get(newS);
				}
				else 
				{
					Iterator itr = ht.keySet().iterator();
					while(itr.hasNext())
					{
						String s = (String)itr.next();
						if(s.equalsIgnoreCase(newS))
						{
							thisIpAddress = (String) ht.get(s);
							break;
						}
					}
				}
				ArrayList multipleIPAddresses = new ArrayList();
				boolean multipleIpsFound=false;
				boolean allContinue=true;
				if(thisIpAddress != null && !thisIpAddress.trim().equalsIgnoreCase("null") && thisIpAddress.indexOf(":")>0)
				{
					multipleIpsFound=true;
					String arr[] = StringUtils.getTokens(thisIpAddress,":");
					for(int z=0;z<arr.length;z++)
					{
						String thisIpAddress_z = arr[z];
						if(allowQualifiedHostNames.equalsIgnoreCase("no"))
						{
							if(!isValidIPAddress(thisIpAddress_z))
							{
								continue;
							}
							else
							{
								if(!multipleIPAddresses.contains(thisIpAddress_z))
								{
									multipleIPAddresses.add(thisIpAddress_z);
								}
								allContinue=false;
							}
						}
						if(htt == null || !htt.containsKey(thisIpAddress_z))
						{
							continue;
						}
						else
						{
							if(!multipleIPAddresses.contains(thisIpAddress_z))
							{
								multipleIPAddresses.add(thisIpAddress_z);
							}
							allContinue=false;
						}
					}
					if(allContinue)
					{
						continue;
					}
				}
				else
				{
					if(allowQualifiedHostNames.equalsIgnoreCase("no"))
					{
						if(thisIpAddress ==null || thisIpAddress.equalsIgnoreCase("null") || !isValidIPAddress(thisIpAddress))
						{
							continue;
						}
					}
					if(htt == null || thisIpAddress == null || thisIpAddress.equalsIgnoreCase("null") || !htt.containsKey(thisIpAddress))
					{
						continue;
					}
				}
				String vNick = null;
				if(!multipleIPAddresses.isEmpty())
				{
					for(int z=0;z<multipleIPAddresses.size();z++)
					{
						String thisIpAddress_z = (String)multipleIPAddresses.get(z);
						if(htt.containsKey(thisIpAddress_z))
						{
							if(vNick==null)
							{
								vNick="";
							}
							vNick += ":" + (String)htt.get(thisIpAddress_z);
						}
					}
					if(vNick != null)
					{
						vNick = vNick.substring(1);
					}
				}
				else
				{
					vNick = (String)htt.get(thisIpAddress);
				}
				if(vNick ==null || vNick.equalsIgnoreCase("null"))
				{
					continue;
				}
				StringTokenizer tokens = new StringTokenizer(vNick,":");
				while(tokens.hasMoreTokens())
				{
					String cToken = (String) tokens.nextToken();
					boolean isAdded = false;
					if(listOfExternalAgents.contains(cToken))
					{
						if(multipleIPAddresses.isEmpty())
						{
							if(egExternalInfo.getIpForAgent(cToken).equals(thisIpAddress))
							{
								if(!agentIpHashtable.containsKey(thisIpAddress))
									agentIpHashtable.put(thisIpAddress,cToken);
								ArrayList al = (ArrayList)ipHashtable.get(cToken);
								if(al !=null && al.size()>0)
								{
									for(int h=0;h<al.size();h++)
									{
										String zstr = (String)al.get(h);
										if(!nicks.contains(zstr))
										{
											nicks.add(zstr);
										}
									}
								}
							}
						}
						else
						{
							for(int z=0;z<multipleIPAddresses.size();z++)
							{
								String thisIpAddress_z = (String)multipleIPAddresses.get(z);
								if(egExternalInfo.getIpForAgent(cToken).equals(thisIpAddress_z))
								{
									if(!agentIpHashtable.containsKey(thisIpAddress_z))
										agentIpHashtable.put(thisIpAddress_z,cToken);
									ArrayList al = (ArrayList)ipHashtable.get(cToken);
									if(al !=null && al.size()>0)
									{
										for(int h=0;h<al.size();h++)
										{
											nicks.add(al.get(h));
										}
									}
								}
							}
						}
					}
					if(listOfRemoteAgents.contains(cToken))
					{
						String tmpIPAddress = egExternalInfo.getIpForRemoteAgent(cToken);
						ArrayList al = null;
						if(ipHashtable.containsKey(tmpIPAddress))
						al = (ArrayList)ipHashtable.get(tmpIPAddress);

						if(al !=null && al.size()>0)
						{
							for(int h=0;h<al.size();h++)
							{
								nicks.add(al.get(h));
							}
						}
					}
					if (!nicks.contains(cToken))
					{
						nicks.add(cToken);
					}
				}
			}
			TreeSet tt = new TreeSet(nicks);
			nicks.clear();
			nicks.addAll(tt);
			allAgents = new String[0];
			allAgents = (String[])nicks.toArray(new String[0]);
			if(selectedChoice != null && selectedChoice.equalsIgnoreCase("Range"))
			{
				chkIPRange = checkIPRange(selectedFrom,selectedTo,ipAddress);
			}
			for(int k=0;k<allAgents.length;k++)
			{
				AgentsUpgradeVO vo = new AgentsUpgradeVO();
				if(option.equals("onlyNickBased") || option.equals("nickAllServerBased")||  option.equals("nickSpecifiServerBased"))
				{
					Vector v = new Vector();
					StringTokenizer st = null;
					if(selectedNickName.indexOf(",")!=-1)
					st = new StringTokenizer(selectedNickName,",");
					else
					st = new StringTokenizer(selectedNickName);
					while(st.hasMoreTokens())
					{
						String temp = (String) st.nextToken();
						if(temp.length()>0)
						{
							v.add(temp.trim());
						}
					}
					String temps[] = (String[])v.toArray(new String[0]);
					boolean t = false;
					for(int m=0;m<temps.length;m++)
					{
						if(allAgents[k].toLowerCase().indexOf(temps[m].toLowerCase())!=-1)
						{
							t = true;
						}
					}
					if(!t)
					{
						continue;
					}
				}
				else if(option.equals("specificServersBasedForGroup") || option.equals("nickSpecifiServersBasedForGroup"))
				{
					Vector v = new Vector();
					if(selectedNickName != null && !selectedNickName.equals(""))
					{
						StringTokenizer st = null;
						if(selectedNickName.indexOf(",")!=-1)
						st = new StringTokenizer(selectedNickName,",");
						else
						st = new StringTokenizer(selectedNickName);
						while(st.hasMoreTokens())
						{
							String temp = (String) st.nextToken();
							if(temp.length()>0)
							{
								v.add(temp.trim());
							}
						}
					}
					else if(components_under_group != null)
					{
						int ccount=components_under_group.size();
						for(int ab=0;ab<ccount;ab++)
						{
							String comp = (String)components_under_group.get(ab);
							comp=comp.substring(comp.indexOf(":")+1);
							comp=comp.substring(0,comp.indexOf(":"));
							if(!v.contains(comp))
							{
								v.add(comp);
							}
						}
					}
					String temps[] = (String[])v.toArray(new String[0]);
					boolean t = false;
					for(int m=0;m<temps.length;m++)
					{
						if(allAgents[k].toLowerCase().indexOf(temps[m].toLowerCase())!=-1)
						{
							t = true;
						}
					}
					if(!t)
					{
						continue;
					}
				}
				if(ht.containsKey(allAgents[k]))
				{
					if(option.equals("onlyIPBased"))
					{
						if(selectedChoice.equalsIgnoreCase("Range"))
						{
							if(!chkIPRange)
							continue;
						}
						else
						{
							if(!ipAddress.equalsIgnoreCase(selectedFrom))
							continue;
						}
					}
					if (hh == null)
							hh = discObj.getServerTypesForAllNicks();
					if(hh == null || (!ht.containsKey(allAgents[k])))
					{
						continue;
					}
					List componentTypes1 = (List)hh.get(allAgents[k]);
					if(option.equals("onlyNickBased"))
					{
						if(listOfExternalAgents.contains(allAgents[k]))
						{
							if(componentTypes1 == null)
							{
								componentTypes1 = new ArrayList();
								componentTypes1.add("External Agent");
							}
							else
							{
								componentTypes1.add(0,"External Agent");
							}
						}
						if(listOfRemoteAgents.contains(allAgents[k]))
						{
							if(componentTypes1 == null)
							{
								componentTypes1 = new ArrayList();
								componentTypes1.add("Remote Agent");
							}
							else
							{
								if(componentTypes1.contains("External Agent"))
								{
									componentTypes1.add(1,"Remote Agent");
								}
								else
								{
									componentTypes1.add(0,"Remote Agent");
								}
							}
						}
					}
					else if(selectedServerType != null)
					{
						if(selectedServerType.equalsIgnoreCase("External Agent"))
						{
							if(listOfExternalAgents.contains(allAgents[k]))
							{
								if(componentTypes1 == null)
								{
									componentTypes1 = new ArrayList();
								}
								else
								{
									componentTypes1.clear();
								}
								componentTypes1.add("External Agent");
							}
						}
						if(selectedServerType.equalsIgnoreCase("Remote Agent"))
						{
							if(listOfRemoteAgents.contains(allAgents[k]))
							{
								if(componentTypes1 == null)
								{
									componentTypes1 = new ArrayList();
								}
								else
								{
									componentTypes1.clear();
								}
								componentTypes1.add("Remote Agent");
							}
						}
					}
					List componentTypes = new ArrayList();
					if(componentTypes1 != null && !componentTypes1.isEmpty())
					{
						componentTypes.addAll(componentTypes1);
					}
					if(componentTypes!= null && componentTypes.size()>0 && aggregateTypes != null && aggregateTypes.size()>0)
					{
						componentTypes.removeAll(aggregateTypes);
					}
					if(componentTypes==null || componentTypes.size()==0)
					{
						continue;
					}
					if(option.equals("specificServersBasedForGroup") || option.equals("nickSpecifiServersBasedForGroup"))
					{
						for(int j=componentTypes.size()-1;j>=0;j--)
						{
							if(!comp_types_under_group.contains(componentTypes.get(j).toString()))
							{
								componentTypes.remove(j);
							}
						}
						if(componentTypes.size()==0)
						{
							continue;
						}
					}
					if(option.equals("specificServerBased") || option.equals("nickSpecifiServerBased"))
					{
						for(int j=componentTypes.size()-1;j>=0;j--)
						{
							if(!componentTypes.get(j).toString().equalsIgnoreCase(selectedServerType))
							componentTypes.remove(j);
						}
						if(componentTypes.size()==0)
						{
							continue;
						}
					}
					String upgraded = "Yes";
					String lastUpgradedPack = agentsAllInfosStringArray[1];
					if(lastUpgradedPack == null || lastUpgradedPack.equalsIgnoreCase("null") || lastUpgradedPack.length()==0)
						upgraded = "No";
					if(!selectedStatus.equalsIgnoreCase("all") && !option.equals("onlyIPBased"))
					{
						if(selectedStatus.equalsIgnoreCase("Upgraded") && !upgraded.equals("Yes"))
						{
							continue;
						}
						if(selectedStatus.equalsIgnoreCase("Not Upgraded") && !upgraded.equals("No"))
						{
							continue;
						}
					}
					String agentStatus = (String) agentList.get(global);
					//agentList.remove(global);
					if(agentStatus == null || agentStatus.equalsIgnoreCase("null") || agentStatus.trim().length()==0)
						continue;

					if(agentStatus.equalsIgnoreCase("true"))
						agentStatus = "Enabled";
					else
						agentStatus = "Disabled";

					if(!selectedStatus.equalsIgnoreCase("all") && !option.equals("onlyIPBased"))
					{
						if(selectedStatus.equalsIgnoreCase("Auto Upgrade Enabled") && !agentStatus.equals("Enabled"))
						{
							continue;
						}
						if(selectedStatus.equalsIgnoreCase("Auto Upgrade Disabled") && !agentStatus.equals("Disabled"))
						{
							continue;
						}
					}
					List list = null;
					if(upgradeNowAgents !=null && upgradeNowAgents.length >0 )
					{
						list = Arrays.asList(upgradeNowAgents);
					}
					if(!selectedStatus.equalsIgnoreCase("all") && !option.equals("onlyIPBased"))
					{
						if(selectedStatus.equalsIgnoreCase("Upgrade Now Enabled"))
						{
							if(list !=null && list.contains(global))
							{
								//do nothing
							}
							else
								continue;
						}
						if(selectedStatus.equalsIgnoreCase("Upgrade Now Disabled"))
						{
							if(list !=null && list.contains(global))
							{
								continue;
							}
						}
					}
					if(vladimir)
					{
						vladimir = false;
					}
					else
					{
						vladimir = true;
					}
					vo.setId(ids[i]);//value to be set in checkbox.
					vo.setComponentName(allAgents[k]);
					TreeSet ts = new TreeSet(componentTypes);
					componentTypes.clear();
					
					componentTypes.addAll(ts);
					
					Collections.sort(componentTypes,String.CASE_INSENSITIVE_ORDER);
					String compTypes = null;
					for(int j=0;j<ts.size();j++)
					{
						String tmpCompType = (String)componentTypes.get(j);
						if(compTypes == null)
							compTypes = tmpCompType;
						else
							compTypes = compTypes+","+tmpCompType;
					}
					vo.setComponentType(compTypes);

					String ttmp ="";
					String external = "-1";
					if(agentIpHashtable !=null && agentIpHashtable.size()>0)
						external = checkForExternalAgent(agentIpHashtable, hostAgentMap, allAgents[k], ipAddress);
					String remote = "-1";
					if(remComps !=null && remComps.length>0)
						remote = checkForRemoteComponent(remComps, egExternalInfo, allAgents[k]);
					if(external !=null && !external.equalsIgnoreCase("null") && !external.equals("-1"))
					{
						ttmp = external;
					}
					else if(remote !=null && !remote.equalsIgnoreCase("null") && !remote.equals("-1"))
					{
						ttmp = remote;
					}
					else
					{
						ttmp = allAgents[k];
					}
					vo.setAgentName(sbb);
					vo.setAgentIP(ttmp);
					vo.setAutoUpgrade(agentStatus);
					if(list !=null && list.contains(global) && agentsAllInfosStringArray[0].equalsIgnoreCase("true"))
					{
						vo.setUpgradeNowFlag("Enabled");
					}
					else
					{
						vo.setUpgradeNowFlag("Disabled");
					}
					vo.setAgentVersion(agentsAllInfosStringArray[5]);
					vo.setAgentOS(agentsAllInfosStringArray[4]);
					vo.setLastUpgradePack(agentsAllInfosStringArray[1]);
					String showDate = agentsAllInfosStringArray[2];
					try
					{
						if(!showDate.equalsIgnoreCase("None") && showDate.trim().length()>0)
						{
							showDate = formatter.format(new java.util.Date(Long.parseLong(agentsAllInfosStringArray[2])));
							String firstPart = showDate.substring(0,showDate.indexOf(" "));
							String secondPart = showDate.substring(showDate.indexOf(" "));
							showDate = DateUtil.changeDateFormat(firstPart,"MM/dd/yyyy",currentDateFormat);
							showDate += secondPart;
						}
					}
					catch(Exception e)
					{
						
						showDate = agentsAllInfosStringArray[2];
						e.printStackTrace();
					}
					vo.setLastUpgradedTime(showDate);
					rowCount = !rowCount;
					finalResult.add(vo);
				}
			}
			results.remove(ids[i]);
		} // ids
		return finalResult;
	}
//end methods
%>

<%
	if (request.getQueryString()!= null)
	{
		session.setAttribute("adminLastAccessedURL","/final/admin/AdvanceSearch.jsp?"+request.getQueryString());
	}
	else
	{
		session.setAttribute("adminLastAccessedURL","/final/admin/AdvanceSearch.jsp");
	}

	screenLabels.put("Set Refresh On",_mapping.getTextDescription("admin.upgrade.Set Refresh On"));
	screenLabels.put("Set Refresh Off",_mapping.getTextDescription("admin.upgrade.Set Refresh Off"));
	screenLabels.put("Search",_mapping.getTextDescription("admin.upgrade.Search"));
	screenLabels.put("Clear",_mapping.getTextDescription("admin.upgrade.Clear"));
	screenLabels.put("refreshTime",refreshTime);
	screenLabels.put("sessionID",sessId);
	screenLabels.put("selectedServerType",cp_Type);


	statusObj.put("displayField",_mapping.getTextDescription("admin.agents.All"));
	statusObj.put("valueField","All");
	statusArr.add(statusObj);

	statusObj.put("displayField",_mapping.getTextDescription("admin.upgrade.Auto Upgrade Enabled"));
	statusObj.put("valueField","Auto Upgrade Enabled");
	statusArr.add(statusObj);

	statusObj.put("displayField",_mapping.getTextDescription("admin.upgrade.Auto Upgrade Disabled"));
	statusObj.put("valueField","Auto Upgrade Disabled");
	statusArr.add(statusObj);

	statusObj.put("displayField",_mapping.getTextDescription("admin.upgrade.Upgrade Now Enabled"));
	statusObj.put("valueField","Upgrade Now Enabled");
	statusArr.add(statusObj);

	statusObj.put("displayField",_mapping.getTextDescription("admin.upgrade.Upgrade Now Disabled"));
	statusObj.put("valueField","Upgrade Now Disabled");
	statusArr.add(statusObj);

	JSONObject versionObj = new JSONObject();
	versionObj.put("displayField",_mapping.getTextDescription("admin.agents.All"));
	versionObj.put("valueField","All");
	versionArr.add(versionObj);

	JSONObject osObj = new JSONObject();
	osObj.put("displayField",_mapping.getTextDescription("admin.agents.All"));
	osObj.put("valueField","All");
	osArr.add(osObj);

	UpgradeStatusHelper ush = new UpgradeStatusHelper();
	List agents = ush.getAllDetails();
	if(agents != null && !agents.isEmpty())
	{
		String separator = ush.getSeparator();
		ArrayList version = new ArrayList();
		ArrayList osSet = new ArrayList();
		for (Iterator iterator=agents.iterator(); iterator.hasNext(); )
		{
			String line = (String)iterator.next();
			String[] tokens = StringUtils.getTokens(line, separator);
			if (version.indexOf(tokens[1]) == -1)
			{
				version.add(tokens[1]);
			}
			if (osSet.indexOf(tokens[3]) == -1)
			{
				osSet.add(tokens[3]);
			}
		}
		if(!version.isEmpty())
		{
			Collections.sort(version,String.CASE_INSENSITIVE_ORDER);
			for(int i=0;i<version.size();i++)
			{
				String ver = (String)version.get(i);
				versionObj.put("displayField",ver);
				versionObj.put("valueField",ver);
				versionArr.add(versionObj);
			}
			version.clear();

			ArrayList osList = new ArrayList();
			osList.addAll(osSet);
			Collections.sort(osList,String.CASE_INSENSITIVE_ORDER);
			for(int i=0;i<osList.size();i++)
			{
				String os = (String)osList.get(i);
				String key = os.toUpperCase();
				if(osMap.containsKey(key))
				{
					String osdispname = (String)osMap.get(key);
					osObj.put("displayField",osdispname);
				}
				else
				{
					osObj.put("displayField",os);
				}
				osObj.put("valueField",os);
				osArr.add(osObj);
			}

		}
	}
	rootJson.put("statusVal",statusArr);
	rootJson.put("total_Result",dispTable.size());
	rootJson.put("gridValues",GRID_ARRAY);
	rootJson.put("cmpt_type",cmpt_type);
	rootJson.put("versionArr",versionArr);
	rootJson.put("osArr",osArr);
	rootJson.put("totalcount",total);
	rootJson.put("screenLabels",screenLabels);
	rootJson.put("groupListArr",groupListArr);

	out.println(rootJson.toString());
%>