
<%@ include file = "../../EgTrackerAJSON.jsp" %>
<%@ page import = "com.eg.EgSpecsInfo"%>
<%@ page import="com.egurkha.util.*" %>
<%@ page import = "com.eg.EgExternalInfo"%>
<%@ page import = "net.sf.json.*"%>
<%@ page import = "com.eg.IniFile" %>
<%@ page import = "com.egurkha.ini.IniUI"%>
<%@ page import = "egurkha.EgTestParamBean" %>
<%@ page language = "java" contentType = "text/html; charset=UTF-8" pageEncoding = "UTF-8" %>

<%
	response.setHeader("Pragma","no-cache");
	response.setDateHeader("Expires", -1);
	response.setContentType("application/json");

	JSONObject rootJson = new JSONObject();
	
	IniUI iniUI = IniUI.getInstance();
	String userLanguage = iniUI.getDefaultLanguage();
	_user.getUserPreferences();
	if (_user != null)
	{
		userLanguage = _user.getLanguage();
	}
	EgMappingInfo mapping = new EgMappingInfo(userLanguage);
	String user_id = _user.getLoginID();
	EgApmGuidInfo apmGuidInfoNew = null;
	EgUuidInfo uuidInfo = null;
	
	String printThis = new Date()+" EgDispBtmComponentsJson.jsp - BTM jar download :";
	String egTitleSearchStr = request.getParameter("egTitleSearchStr");
	boolean isSearchResult = (egTitleSearchStr!=null && egTitleSearchStr!="");
	ArrayList searchList = new ArrayList();
	if (isSearchResult)
	{
		StringTokenizer st = new StringTokenizer(egTitleSearchStr);
		while (st.hasMoreTokens())
		{
			String thisToken = st.nextToken().trim();
			if (thisToken.equals(""))
				continue;
			searchList.add(thisToken);
		}
	}
%>

<jsp:useBean id="prgBean" scope="page" class="egurkha.EgTestParamBean"/>

<%
	JSONArray gridRumCollectors = new JSONArray();
	JSONObject gridObject = new JSONObject();
	String colon = ":";
try {
		EgRoleInfo roleInfo = EgRoleInfo.getInstance(session.getId(), (String) session.getAttribute("sess_userid"));
		EgDiscInfo egDisc = new EgDiscInfo("manager");
		egSpecs.checkForUpdate();
		egExternalInfo.checkForUpdate();
		ArrayList<String> btmComponents = egSpecs.getAllComponentTypesForTest("BusinessTransTest");
		ArrayList appNameList = new ArrayList();
		for (int b = 0; b < btmComponents.size(); b++) {

			String strServer = btmComponents.get(b);
			if (strServer == null || strServer.equalsIgnoreCase("null"))
				strServer = "";
			String temp = "";
			String[] serversArray = roleInfo.getAllServersOfType(strServer);
			ArrayList servers = serversArray == null ? new ArrayList()
					: new ArrayList(Arrays.asList(serversArray));
			if (servers == null || servers.size() <= 0) {
				//System.out.println(printThis +" No servers found for >>>>"+strServer);
				continue;
			}

			boolean serversFound = false;
			List minusList = new ArrayList();
			for (int j = 0; j < servers.size(); j++) {
				String thisSrv = (String) servers.get(j);
				if (thisSrv.startsWith("Format:") || thisSrv.startsWith("#")) {
					minusList.add(thisSrv);
					continue;
				}
				int thisSrvIndex = thisSrv.indexOf(colon);
				if(thisSrvIndex > -1){
					temp = thisSrv.substring(thisSrvIndex + 1);
				}
				int tmpFirstIndex = temp.indexOf(colon);
				int tmpLastIndex = temp.lastIndexOf(colon);
				if ((tmpFirstIndex != tmpLastIndex) && tmpLastIndex >-1) {
					temp = temp.substring(0, tmpLastIndex);
				}

				//String ipWithoutPort = Server.getServerNameWithoutPort(temp, false);
				// if (isSearchResult && !doesExist(searchList, ipWithoutPort)) {
					// minusList.add(thisSrv);
					// continue;
				// }
				serversFound = true;
			}
			servers.removeAll(minusList);
			Collections.sort(servers, String.CASE_INSENSITIVE_ORDER);
			Vector vecStore = new Vector();
			String[] extTypes = egSpecs.getAllExternalServerTypes();
			List extCompTypes = new ArrayList();
			if (extTypes != null) {
				extCompTypes = new ArrayList(Arrays.asList(extTypes));
			}
			if (!strServer.equals("null") && servers.size() > 0) {
				IniFile apmIni = new IniFile(EgInstallInfo.getInstallDir() + "/manager/config/eg_apm.ini");
				try 
				{
					EgApmGuidInfo guidInfo = new EgApmGuidInfo("manager",false);
					Vector values = guidInfo.getValues("APM_GUID_MAPPING_WITH_NICK");
					String[] vars = guidInfo.getVariables("APM_GUID_MAPPING_WITH_NICK");
					List list = Arrays.asList(vars);
					for (int j = 0; j < servers.size(); j++) {
						String thisSrv = (String) servers.get(j);
						int thisSvcIndex = thisSrv.indexOf(colon);
						String serverType = thisSrv;
						if(thisSvcIndex > -1){
							serverType = (thisSrv.substring(0, thisSvcIndex)).trim();
							temp = thisSrv.substring(thisSvcIndex + 1);
						}
						String compIp = egDisc.getComponentIP(strServer, temp);
						int tmpFirstIndex = temp.indexOf(colon);
						int tmpLastIndex = temp.lastIndexOf(colon);
						String nickAlone = temp;
						if(tmpFirstIndex > -1){
							nickAlone = temp.substring(0, tmpFirstIndex);
						}
						if ((tmpFirstIndex != tmpLastIndex) && tmpLastIndex > -1) {
							temp = temp.substring(0, tmpLastIndex);
						}
						if (!vecStore.contains(temp)) {
							vecStore.addElement(temp);
							String ipWithoutPort = Server.getServerNameWithoutPort(temp, false);

							// if (isSearchResult && !doesExist(searchList, ipWithoutPort))
								// continue;
							serversFound = true;
							String agentType = "Agent-based";
							if (egExternalInfo.isRemoteBased(nickAlone)) {
								agentType = "Agentless";
							} else if (extCompTypes.contains(strServer)) {
								agentType = "External Agent";
							}

							JSONObject obj = new JSONObject();
							String compToShow = ipWithoutPort;
							String[] compNameArr = compToShow.split(colon);
							String componentName = "";
							String componentPort = "NULL";
							if(compNameArr.length == 2){
								 componentName = compNameArr[0];
								 componentPort = compNameArr[1];
							}else if(compNameArr.length == 1){ // Handling component with NO PORT :   MyJavaApp:NULL
								 componentName = compNameArr[0];
							}

							String componentType = strServer;
							String componentTypeDesc =  mapping.getComponentTypeDescription(componentType);
							
							gridObject.put("compType", componentTypeDesc);
							gridObject.put("CompNickName", componentName);
							gridObject.put("hostIP", compIp);
							gridObject.put("comPort", componentPort);
							//TODO: Get dynamically
							String tech =  "JAVA";
							gridObject.put("APMName",tech);
							gridObject.put("monitoring", agentType);
							
							String testName = "BusinessTransTest";
							//TODO: Read from ini and Add JVM tests also
							//String[] offloadTestNames = { "BusinessTransTest", "TransactionFlowTest", "KBusinessTransTest" };
							//List<String> offloadTestList = (List<String>) Arrays.asList(offloadTestNames);

							prgBean.createFile("eg_agents.ini");
							List listAgents = getAgents(compToShow);
							
							//System.out.println(printThis +" listAgents : "+ listAgents);
							if (testName != null && !testName.equals("")) {
								//fetch the exact agent
								String tempAgentName = getAgentNickName(componentType, testName, listAgents);
								tempAgentName = tempAgentName != null ? tempAgentName : "";
								String[] testVariables = prgBean.getVariables(tempAgentName);
								String agentIp = egExternalInfo.getIpForRemoteAgent(tempAgentName);
								if(agentIp == null){
									 agentIp = egExternalInfo.getIpForAgent(tempAgentName);
								}
								if(agentIp == null){
									agentIp ="localhost";
								}
								
								gridObject.put("agentIP", agentIp);
								
								String var = componentType+colon+componentName+colon+componentPort;
								String value = apmIni.getValue("BTM_PROFILER_APPNAME_MAPPING", var);
								String appName="";
								String tierName="";
								String[] arr = value.split(colon);
								if(arr.length==2){
									 appName = arr[0];
									 tierName = arr[1];
									if(appName.equalsIgnoreCase("none"))
									{
										appName = "";
									}
								
									if(tierName.equalsIgnoreCase("none"))
									{
										tierName = "";
									}
								
									gridObject.put("tierName", tierName);
									gridObject.put("appName", appName);
								}else 
								{
									appNameList.add(var+"=none:none");
									gridObject.put("tierName", "");
									gridObject.put("appName", "");
								}
								String guid="";
								StringBuilder guidVar = new StringBuilder();
								guidVar.append(componentType).append("^");
								guidVar.append(compIp).append("^");
								guidVar.append(componentName).append("^");
								guidVar.append(componentPort);
								int guidIndex = list.indexOf(guidVar.toString());
								// Getting existing GUIDs
								if(guidIndex > -1)
								{
									String guidStr = values.get(guidIndex).toString();
									if(guidStr!=null && guidStr.length() > 0)
									{
										guid = guidStr;
									}
								}else{
									Hashtable params = new Hashtable();
									params.put("componenttype",componentType);
									params.put("hostip",compIp);
									params.put("componentname",componentName);
									params.put("port",componentPort);
									params.put("uuiduser",user_id);

									uuidInfo = new EgUuidInfo();
									apmGuidInfoNew = new EgApmGuidInfo("manager", true);
									apmGuidInfoNew.generateApmGuid(false,params);
									guid = apmGuidInfoNew.getValue("APM_GUID_MAPPING_WITH_NICK", guidVar.toString());
								}
								
								gridObject.put("GUID", guid);
								if(isSearchResult)
								{
									StringBuilder builder = new StringBuilder();
									builder.append(componentTypeDesc).append(",");
									builder.append(componentName).append(",");
									builder.append(compIp).append(",");
									builder.append(componentPort).append(",");
									builder.append(tech).append(",");
									builder.append(agentType).append(",");
									builder.append(agentIp).append(",");
									builder.append(appName).append(",");
									builder.append(tierName).append(",");
									builder.append(guid);
									String fullData = builder.toString().toUpperCase();
									
									if(fullData.indexOf(egTitleSearchStr.toUpperCase())>-1){
										gridRumCollectors.add(gridObject);
									}
									
								}else{
									gridRumCollectors.add(gridObject);
								}
							}
						}
					}
				}
				catch (Exception e)
				{
					System.out.println(printThis +"  Unable to retrieve app and tier name details, "+ e);
				}
			}
		}
		if (appNameList.size() > 0) {
			storeAppNameDetails(appNameList);
		}
	}
	catch (Exception e)
	{
		System.out.println(printThis +"  Unable to retrieve components details, "+ e);
	}
%>

<%!
private boolean doesExist(List searchList, String thisGroup)
{
	Iterator i = searchList.iterator();
	while(i.hasNext())
	{
		String nextStr = (String) i.next();
		if (thisGroup.indexOf(nextStr)!=-1||(thisGroup.toUpperCase().indexOf(nextStr.toUpperCase()))!=-1)
			return true;
	}
	return false;
}
%>

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

	rootJson.put("gridRmtAgents",gridRumCollectors);
	out.println(rootJson.toString());
%>

<%!

	EgExternalInfo egExternalInfo = new EgExternalInfo("manager");
	EgSpecsInfo egSpecs = new EgSpecsInfo("manager");

	private List getAgents(String componentName)
	{
		List agentsList = new ArrayList();
		try {
			Hashtable internalAgentMap = egExternalInfo.getInternalAgentMap();
	
			int index = componentName.indexOf(":");
			String componentNickName = componentName;
			if(index>-1){ // Handling component with NO PORT :   MyJavaApp:NULL
				componentNickName = componentName.substring(0,index);
			}
			
			String agentNickName = "";
			boolean isRemote = false;
	
			//To fetch the exact agent for the selected component - start
			isRemote = egExternalInfo.isRemoteBased(componentNickName);
			if (isRemote)
			{
				//Agentless
				agentNickName = egExternalInfo.getRemoteAgentForHost(componentNickName);
			}
			else
			{
				//Auto or Manual
				String agentName = egExternalInfo.getAgentFor(componentNickName);
	
				if (agentName != null) //Manual
				{
					if (internalAgentMap != null && internalAgentMap.containsKey(agentName))
					{
						agentNickName = (String)internalAgentMap.get(agentName);
					}
					else
					{
						agentNickName = agentName;
					}
				}
				else //Auto
				{
					agentNickName = componentNickName;
				}
			}
	
			//adding an internal agent (or) a remote agent
			agentsList.add(agentNickName);
			//To fetch the exact agent for the selected component - end
	
			//To fetch the external agent for the selected component type - starts
			boolean hasExternalAgent = egExternalInfo.hasExternalAgent(componentNickName);
			if (hasExternalAgent)
			{
				String extAgents[] = egExternalInfo.getExternalAgentsForHost(componentNickName);
				//adding one or more external agent(s)
				agentsList.addAll(Arrays.asList(extAgents));
			}
			//To fetch the external agent for the selected component type - ends
	
		}
		catch(Exception e){
			System.out.println("EgDispBtmComponentsJson.jsp - BTM jar download :  Unable to retrieve components details, "+ e);
		}
			return agentsList;
	}

	//Will provide the right agent (subject) for a component and its test
	private String getAgentNickName(String componentType,String testName,List listAgents)
	{
		boolean isExternalTest = egSpecs.isExternalTest(testName,componentType);
		String agentName = null;
		if (isExternalTest)
		{
			//external agent for external test
			if (listAgents != null && listAgents.size() > 0 )
			{
				agentName = (String)listAgents.get(1);
			}
		}
		else
		{
			//internal agent or remote agent for host level test and application level test.
			if (listAgents != null && listAgents.size() > 0 )
			{
				agentName = (String)listAgents.get(0);
			}
		}

		return agentName;
	}
	
	private void storeAppNameDetails(ArrayList appList){
		IniFile apmIni = EgConfigFilesSync.getInstance(EgInstallInfo.getInstallDir() + "/manager/config/eg_apm.ini",true);
		try{
			for(int i=0;i<appList.size();i++){
				String appTierName = (String) appList.get(i);
				String[] array = appTierName.split("=");
				if(array.length == 2){
					String var = array[0];
					String value = array[1];
					apmIni.setValue("BTM_PROFILER_APPNAME_MAPPING", var, value);
				}
			}
			
		}catch (Exception e){
			System.out.println("EgDispBtmComponentsJson.jsp - BTM jar download :  Unable to retrieve app and tier name details, "+ e);
		}finally{
			apmIni.saveFile();
			EgConfigFilesSync.releaseInstance(apmIni);
		}
	}
	
%>


