<%
/**
 *	File name		: eGBTMSummary.jsp
 *	Purpose			: This page shows the call graph of a web request in HTML Table Tree view
 *	Version			: eG 6.0
 *	Creation Date	: 30-Apr-2014
 *	Author			: Mr.R and Mr.Balraj
 */
%>
<%@ include file= "EgMonitorTracker.jsp"%> 
<%@ page import="com.eg.*"%>
<%@ page import="com.eg.EgDiscInfo"%>
<%@ page import="com.egurkha.util.StringUtils" %>
<%@ page import = "com.egurkha.util.EgSorter"%>
<%@ page import = "com.egurkha.util.DateUtil"%>
<%@ page import="net.sf.json.*" %>
<%@ page import="java.util.*"%>
<%@ page import="java.lang.*"%>
<%@ page import="java.sql.*"%>
<%@ page import = "java.text.*" %>
<%@ page import="com.egurkha.*"%>
<%@ page import = "java.math.*"%>
<%@ page import = "com.egurkha.monitor.VMDesktopBean" %>
<%@ page import = "com.egurkha.monitor.alarms.AlarmPriorities" %>
<%@ page import = "com.eg.EgAgentInfo" %>
<%@ page language="java" contentType="application/json; charset=UTF-8" pageEncoding="UTF-8" %>

<%
	EgAPMInfo apm = new EgAPMInfo("manager");
	String testName = request.getParameter("testName");
	String apmType = apm.getAPMType(testName);
%>
 <%!
	// String Constants
	String asyncThreadStr = "asyncThread";
	String summaryTabStr = "Summary";
	String hotSpotTabStr = "HotSpot";
	String externalDetailsTabStr = "ExternalDetails";
	String errorDetailsTabStr = "ErrorDetails";
	String popupDetailsClickStr = "HttpWebJms";
	String userExperienceHealthyStr = "Healthy";
	String userExperienceSlowStr = "Slow";
	String userExperienceStalledStr = "Stalled";
	String userExperienceErrorStr = "Error";
	String seperatorHash = "#";
	//String seperatoratAtTheRate = "@";
	//String seperatorEquals = "=";
	String seperatorHyphen = "-";
	String seperatorTilt = "~";
	String sessionExternalData = "ExternalData";
	String sessionSummaryData = "SummaryData";
	private final String DEFAULT_SQL_EXEC_CUTOFF_TIME = "10";
	private final double DEFAULT_MAX_QUERY_VALUE = 25.0D;

	DecimalFormat df = new DecimalFormat(seperatorHash);
	DecimalFormat dft = new DecimalFormat("#.##");

	private boolean findDBComp(String dbServerType,String extHost , String extPort , String dbName)
	{
		EgDiscInfo discInfo = new EgDiscInfo("manager");
		boolean found = false ; 
		if(dbServerType!=null)
		{
			 ArrayList dbServerList = discInfo.getAllEntries(dbServerType);
			if(dbServerList != null || dbServerList.size() > 0)
			{
				String result = getDBManagedComp(dbServerType,extHost,extPort,dbName,dbServerList);
				if(result!=null)
				{
					found = true ; 
				}
			}
		}
		return found;

	}

	// Below method returns virtual_comptype+":"+vmHost ,when it is present. Otherwise NULL
	private String getVirtualServerComp(String dbtype,String sid,String port,Vector user_comps, String managedNickName, 
				Vector virtualServerComp, Hashtable vmht_virtualCompMap )
	{
		if(virtualServerComp != null && dbtype!=null && virtualServerComp.contains(dbtype))
		{
			String vmHost = managedNickName+":"+port;
			if(dbtype.indexOf("Oracle_server")>-1  && sid!=null && sid.trim().length()>0)
				vmHost=managedNickName+":"+port+":"+sid;
			String vmCompType = dbtype;
			String component=vmCompType+":"+vmHost;
			if(vmht_virtualCompMap!=null && vmht_virtualCompMap.size() > 0 && 
				vmht_virtualCompMap.containsValue(component) && user_comps!=null && user_comps.contains(component))
			{
				return component;
			}
		}
		else
		{
			if(vmht_virtualCompMap!=null && vmht_virtualCompMap.size() > 0 && dbtype!=null)
			{
				String vmcheck = dbtype+":"+managedNickName+":"+port;
				if(dbtype.indexOf("Oracle_server")>-1 && sid!=null && sid.trim().length()>0)
					vmcheck = dbtype+":"+managedNickName+":"+port+":"+sid;
				String vmvirtualComp=(String)vmht_virtualCompMap.get(vmcheck);
				if (vmvirtualComp != null)
				{
					StringTokenizer vmst=new StringTokenizer(vmvirtualComp,":");
					if (vmst.countTokens()>2)
					{
						String vmCompType=vmst.nextToken();
						String	vmHost=vmst.nextToken()+":"+vmst.nextToken();
						String component=vmCompType+":"+vmHost;
						if(user_comps!=null && user_comps.contains(component))
						{
							return component;
						}
					}
				}
			}
		}
		return null;
	}

	// Below method returns cloud_comptype+":"+vmHost ,when it is present. Otherwise NULL
	private String getCloudServerComp(String dbtype,String sid,String port,Vector user_comps, String managedNickName, 
				Vector cloudServerComp , Hashtable vmht_cloudCompMap)
	{
		String vmHost=managedNickName+":"+port;
		if (cloudServerComp !=null && dbtype!=null && cloudServerComp.contains(dbtype))
		{
			
			if(dbtype.indexOf("Oracle_server")>-1 && sid!=null && sid.trim().length()>0)
			vmHost=managedNickName+":"+port+":"+sid;
			String vmCompType = dbtype;
			String component=vmCompType+":"+vmHost;
			if(vmht_cloudCompMap!=null && vmht_cloudCompMap.size() > 0 && vmht_cloudCompMap.containsValue(component) && user_comps!=null && user_comps.contains(component))
			{
				return component;
			}
		}
		else
		{
			if(vmht_cloudCompMap!=null && vmht_cloudCompMap.size() > 0 && dbtype!=null)
			{
				String vmcheck = dbtype+":"+managedNickName+":"+port;
				if(dbtype.indexOf("Oracle_server")>-1 && sid!=null && sid.trim().length()>0)
					vmcheck=dbtype+":"+managedNickName+":"+port+":"+sid;
				String vmvirtualComp=(String)vmht_cloudCompMap.get(vmcheck);
				if (vmvirtualComp != null)
				{
					StringTokenizer vmst=new StringTokenizer(vmvirtualComp,":");
					if (vmst.countTokens()>2)
					{
						String vmCompType=vmst.nextToken();
						String svmHost=vmst.nextToken()+":"+vmst.nextToken();
						String component=vmCompType+":"+vmHost;
						if(user_comps!=null && user_comps.contains(component))
						{
							return component;
						}
					}
				}
			}
		}
		return null;
	}
	
	private String getVMComponents(String dbtype,String sid,String port,Vector user_comps ,String managedNickName,  Vector virtualServerComp , 
					Vector cloudServerComp, Hashtable vmht_virtualCompMap, Hashtable vmht_cloudCompMap)
	{
		String vmComponent = getVirtualServerComp(dbtype,sid, port,user_comps, managedNickName , virtualServerComp , vmht_virtualCompMap);
		if(vmComponent == null){
			vmComponent = getCloudServerComp(dbtype,sid, port,user_comps, managedNickName, cloudServerComp , vmht_cloudCompMap);
		}
		return vmComponent;
	}

	private String getDBString(String dbServerType, ArrayList racIpList , String dbName , String allColumns){
		boolean found = false;
		for(int i=0;i<racIpList.size();i++){
			String racIpString = (String) racIpList.get(i);
			int colon_index = racIpString.lastIndexOf(":");
			if(colon_index > 0){
				String racIp = racIpString.substring(0 , colon_index);
				String racPort = racIpString.substring(colon_index+1);
				found = findDBComp(dbServerType,racIp,racPort,dbName);
				if(found){
					return dbServerType+"*"+racIpString;
				}
			}
		}


		if(allColumns!=null && allColumns.length() > 0){
			ArrayList allColumnList = StringUtils.egTokenizer(allColumns,",");
			if(allColumnList!=null && allColumnList.size() > 0 )
			{
				for(int i = 0 ; i < allColumnList.size() ; i++)
				{
					String serverType = (String)allColumnList.get(i);
					for(int j=0;j<racIpList.size();j++){
						String racIpString = (String) racIpList.get(j);
						int colon_index = racIpString.lastIndexOf(":");
						if(colon_index > 0){
							String racIp = racIpString.substring(0 , colon_index);
							String racPort = racIpString.substring(colon_index+1);
							found = findDBComp(serverType,racIp,racPort,dbName);
							if(found)
							{
								dbServerType = serverType;
								return dbServerType+"*"+racIpString;
							}
						}
					}
				}
			}
		}
		
		
		return dbServerType;
	}
	
	private String getDBString(String dbServerType , String extHost , String extPort , String dbName , String allColumns)
	{
		boolean found = false ;
		if(allColumns!=null && allColumns.length() > 0 ){
			ArrayList allColumnList = StringUtils.egTokenizer(allColumns,",");
			if(allColumnList!=null && allColumnList.size() > 0 )
			{
				for(int i = 0 ; i < allColumnList.size() ; i++)
				{
					String serverType = (String)allColumnList.get(i);
					found = findDBComp(serverType,extHost,extPort,dbName);
					if(found)
					{
						dbServerType = serverType;
						return dbServerType;
					}
				}
			}
		}
		return dbServerType;
	}

	private String getDBLabel(String dbIP, String dbPort, String dbType, String dbName, boolean flag){
		StringBuffer detailsBuffer = new StringBuffer();
		detailsBuffer.append(dbIP);
		if(flag){
			detailsBuffer.append("^*");
		}
		if(dbIP.startsWith("jdbc:")){
			return detailsBuffer.toString();
		}

		if(!dbPort.equals("-")){
			detailsBuffer.append(" - ").append(dbPort);
		}
		if(!dbType.equals("UNKNOWN")){
			detailsBuffer.append(" - ").append(dbType);
		}
		if(!dbName.equals("-")){
			detailsBuffer.append(" - ").append(dbName);
		}
		return detailsBuffer.toString();
	}

	private String getDBManagedComp(String dbServerType , String extHost , String extPort , String dbName,ArrayList dbServerList)
	{
		String result = null ;
		for(int k=0;k<dbServerList.size();k++)
		{
			String line = (String) dbServerList.get(k);
			if(line.startsWith("#"))
				continue;
			String rhsPart = line.substring(line.indexOf("=")+1);
			StringTokenizer st = new StringTokenizer(rhsPart , ",");
			int count = st.countTokens();
			String compType = st.nextToken();
			String hostIp = st.nextToken();
			String nickName = st.nextToken();
			String portNo = st.nextToken();
			String isPassive = st.nextToken();
			String sid = null;
			if(count == 6){
				sid = st.nextToken();
			}
			boolean found = false;
			if(extHost.equalsIgnoreCase(hostIp) && extPort.equalsIgnoreCase(portNo))
			{
				if(sid!=null && sid.equalsIgnoreCase(dbName)){
					result = compType+"_M:"+nickName+":"+portNo+":"+dbName;
					found = true;
				}
				else{
					result = compType+"_M:"+nickName+":"+portNo;
					found = true;
				}
			}
			if(found) 
				break;
		}
		return result;
	}

	private Hashtable getLdapDetailsTable(ArrayList temp, ArrayList ldapDetails, Hashtable ldapDataTable, double totalResTime, DecimalFormat dft, int ldapMethodCount) {
		try {
			String methodDetails = (String)temp.get(6);
	
			if (ldapDataTable.containsKey(methodDetails)){
				ldapDetails = (ArrayList)ldapDataTable.get(methodDetails);
				if (ldapDetails != null && ldapDetails.size() > 0){
					String methodName = (String)ldapDetails.get(0);
					int methodTotCount = (Integer)ldapDetails.get(1);
					int methodTime = ((BigDecimal)ldapDetails.get(2)).intValue();
					methodTime = methodTime + ((BigDecimal)temp.get(7)).intValue();
					//double methodPercent = (Double)ldapDetails.get(3); 
					//Not going to do anything with else part percent. In if part itself, calculating percent.
					double timeInPercent = 0.0;
					try {
						timeInPercent = Double.parseDouble (dft.format((methodTime/totalResTime)*100));
					} catch(Exception ex){
						System.err.println("Exception While parsing String to Double for LDAP call type "+ex.getMessage());
					}

					ldapMethodCount = methodTotCount + 1;
					BigDecimal methodTimeInBigDecimal = new BigDecimal(methodTime);
					ldapDetails.clear();
					ldapDetails.add(methodName);
					ldapDetails.add(ldapMethodCount);
					ldapDetails.add(methodTimeInBigDecimal);
					ldapDetails.add(timeInPercent);
					ldapDataTable.put(methodDetails, ldapDetails);
				}
			} else{
				ldapMethodCount = 1;
				ldapDetails = new ArrayList();
				ldapDetails.add(methodDetails);
				ldapDetails.add(ldapMethodCount);
				ldapDetails.add(temp.get(7));//time
				double percent = 0.0;
				try {
					percent = Double.parseDouble (dft.format((Double.parseDouble(temp.get(7).toString())/totalResTime)*100));
				}
				catch (Exception ex){
					System.err.println("Exception While parsing String to Double for LDAP call type "+ex.getMessage());
					//ex.printStackTrace();
				}
				ldapDetails.add(percent);//percent
				ldapDataTable.put(methodDetails, ldapDetails);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ldapDataTable;
	}
	
	// Below method gives the Nick Name of component, if it is managed. Otherwise NULL.
	public String getManagedComponentNickName(String dbType,String ip,String port,String sid, EgDiscInfo discInfo)
	{
		if(dbType == null){
			return null;
		}
		boolean found = false;
		ArrayList dbServerList = discInfo.getAllEntries(dbType);
		System.out.println("dbServerList -> "+dbServerList);
		String result = null;
		if(dbServerList != null && dbServerList.size()>0)
		{
			try
			{
				for(int k=0;k<dbServerList.size();k++){
					String line = (String) dbServerList.get(k);
					if(line.startsWith("#"))
						continue;
					String rhsPart = line.substring(line.indexOf("=")+1);
					StringTokenizer st = new StringTokenizer(rhsPart , ",");
					int count = st.countTokens();
					String compType = st.nextToken();
					String hostIp = st.nextToken();
					String nickName = st.nextToken();
					String portNo = st.nextToken();
					String isPassive = st.nextToken();
					if(count == 6){
						String dbname = st.nextToken();;
						if(ip.equalsIgnoreCase(hostIp) && port.equalsIgnoreCase(portNo) && dbname.equalsIgnoreCase(sid)){
							result = nickName;
							found = true;
						}
					}
					else if (count == 5){
						if(ip.equalsIgnoreCase(hostIp) && port.equalsIgnoreCase(portNo)){
							result = nickName;
							found = true;
						}
					}
					if(found) 
						break;
				}

				if(!found){
					for(int k=0;k<dbServerList.size();k++){
						String line = (String) dbServerList.get(k);
						if(line.startsWith("#"))
							continue;
						String rhsPart = line.substring(line.indexOf("=")+1);
						StringTokenizer st = new StringTokenizer(rhsPart , ",");
						int count = st.countTokens();
						String compType = st.nextToken();
						String hostIp = st.nextToken();
						String nickName = st.nextToken();
						String portNo = st.nextToken();
						String isPassive = st.nextToken();
						if (count == 5){
							//if(ip.indexOf("\\") > 0 && ip.indexOf(hostIp) != -1){ //Block to get nickname if DB component is managed using instance i.e ip=hostname\instance name.
							if(ip.indexOf("\\") > 0 ){ //Block to get nickname if DB component is managed using instance i.e ip=hostname\instance name.

								StringTokenizer st1 = new StringTokenizer(ip,"\\");
								if(st1.hasMoreTokens()){
									String tmp_ip = st1.nextToken();
									String instance = st1.nextToken();
									if(tmp_ip.equalsIgnoreCase(hostIp)){
										String configuredPort = getPortByInstanceName(nickName,instance);
										if(configuredPort != null && configuredPort.length() > 0){
											result = nickName+":"+configuredPort;
											found = true;;
										}
									}
								}
							}
						}
						if(found) 
							break;
					}
				}
				if(!found){
					for(int k=0;k<dbServerList.size();k++){
						String line = (String) dbServerList.get(k);
						if(line.startsWith("#"))
							continue;
						String rhsPart = line.substring(line.indexOf("=")+1);
						StringTokenizer st = new StringTokenizer(rhsPart , ",");
						int count = st.countTokens();
						String compType = st.nextToken();
						String hostIp = st.nextToken();
						String nickName = st.nextToken();
						String portNo = st.nextToken();
						String isPassive = st.nextToken();
						if (count == 5){
							if(ip.indexOf(".") > 0 && ip.toLowerCase().indexOf(hostIp.toLowerCase()) != -1){
								String tmp_ip = ip.substring(0,ip.indexOf("."));
								if(tmp_ip.equalsIgnoreCase(hostIp)){
									result = nickName;
									found = true;
								}
							}
						}
						if(found) 
							break;
					}
				}
			}
			catch (Exception e)
			{
				System.err.println("Exception in eGBTMSummary.jsp : "+e.getMessage());
				//e.printStackTrace();
			}
		}
		return result;
	}

	public String getPortByInstanceName(String compNick, String instance){
		EgExternalInfo externalInfo = new EgExternalInfo("manager");
		EgDiscInfo discInfo = new EgDiscInfo("manager");
		String configuredInstance = null;
		String configuredPort = null;

		try{
			String port = discInfo.getPortForHost(compNick,"MS_sql_server");
			com.eg.IniFile agentIni = new com.eg.IniFile(EgInstallInfo.getInstallDir()+"/manager/config/eg_agents.ini");
			String agent = compNick;
			List agentNames = externalInfo.getAgentsFor("MsSqlNetTest", "MS_sql_server", compNick);
			if(agentNames != null && agentNames.size() > 0)
				agent = (String)agentNames.get(0);
			String val = agentIni.getValue(agent,"MsSqlNetTest::"+compNick+":"+port);
			if(val != null && val.trim().length() > 0){
				StringTokenizer st = new StringTokenizer(val," ");
				while(st.hasMoreTokens()){
					String token = st.nextToken();
					if(token.equalsIgnoreCase("-instance")){
						configuredInstance = st.nextToken();
					}
					if(configuredInstance != null)
						break;
				}

				if(configuredInstance != null && configuredInstance.equalsIgnoreCase(instance))
					configuredPort = port;
			}
		}
		catch(Exception ex){
			ex.printStackTrace();
		}
		return configuredPort;
	}

	/*public String escapeHTML (String string) {
		String escapedTxt = "";
		char tmp = ' ';
		for(int i = 0; i < string.length(); i++) {
			tmp = string.charAt(i);
			switch (tmp) {
				case '<':
					escapedTxt += "&lt;";
					break;
				case '>':
					escapedTxt += "&gt;";
					break;
				case '"':
					escapedTxt += "&quot;";
					break;
				case '\'':
					escapedTxt += "&#x27;";
					break;
				case '/':
					escapedTxt += "&#x2F;";
					break;
				default:
					escapedTxt += tmp;
			}
		}
		return escapedTxt;
	}*/

	public String escapeHTML(String value) {
		if (value == null) return null;

		int length = value.length();
		String encoded;

		for (int i = 0; i < length; i++) {
			char c = value.charAt(i);

			if (c <= 62 && (encoded = getHtmlEntity(c)) != null) {
				// We found a character to encode, so we need to start from here and buffer the encoded string.
				StringBuilder sb = new StringBuilder((int) (length * 1.25));
				sb.append(value.substring(0, i));
				sb.append(encoded);

				i++;

				for (; i < length; i++) {
					c = value.charAt(i);

					if (c <= 62 && (encoded = getHtmlEntity(c)) != null) {
						sb.append(encoded);
					} else {
						sb.append(c);
					}
				}

				value = sb.toString();
				break;
			}
		}
		value = BTMHelper.decodeUrlString(value);
		return value;
	}

	private static String getHtmlEntity(char c) {
		switch (c) {
			case '\'': return "&#x27;";
			case '"': return "&quot;";
			case '<': return "&lt;";
			case '>': return "&gt;";
			case '/': return "&#x2F;";
			case '+': return "&#43;";
			default: return null;
		}
	}
	public double getDoubleFromBigDecimalValue(Object value) 
	{
		double tempValueToBeReturned = 0.0;
		try{
				tempValueToBeReturned = ((BigDecimal)value).doubleValue();
		}catch(Exception e)
		{
			System.out.println("Exception while parsing the value "+e);
		}
		return tempValueToBeReturned ;
	}

	public double getDoubleValue(Object value)
	{
		double tempValueToBeReturned = 0.0;
		try{
				tempValueToBeReturned = Double.parseDouble(value.toString());
		}
		catch(Exception e)
		{
			System.out.println("Exception while parsing the value "+e);
		}
		return tempValueToBeReturned ;
	}

	private Hashtable createSummaryDataForCSV(String name, String url, String qryStr, String date, String prcTime, String totalSqlQuery, String totalSqlTime,String errorQry, String guid, String componentName,String userName) {
		String csvTitle = "Slow SQL Queries for a specific transaction snapshot";
		Vector headersLst = new Vector();   // for headers 
		List columnsLst = new LinkedList();  // for columns values 
		headersLst.add("Transaction Snapshot Summary:");
		headersLst.add("");
		columnsLst.add("Business Transaction Name");
		columnsLst.add(name);
		columnsLst.add("Request URL");
		columnsLst.add(url);
		columnsLst.add("Query String");
		columnsLst.add(qryStr);
		columnsLst.add("Request DateTime");
		columnsLst.add(date);
		columnsLst.add("Transaction Processing Time(ms)");
		columnsLst.add(prcTime);
		columnsLst.add("Number of SQL Queries");
		columnsLst.add(totalSqlQuery);
		columnsLst.add("Cumulative SQL Time(ms)");
		columnsLst.add(totalSqlTime);
		columnsLst.add("Error SQL Queries");
		columnsLst.add(errorQry);
		columnsLst.add("Transaction GUID");
		columnsLst.add(guid);
		columnsLst.add("Component Name");
		columnsLst.add(componentName);
		columnsLst.add("User Name");
		columnsLst.add(userName);
		Hashtable headerColumnMap = new Hashtable();
		headerColumnMap.put(headersLst,columnsLst);  											
		Hashtable entryMap=new Hashtable();
		entryMap.put(csvTitle,headerColumnMap);
		return entryMap;
	}

	private Hashtable createSlowSqlQueriesCsvData(String jsonString, String headerStr) {
		Vector headersLst = new Vector();
		List columnsLst = new LinkedList();
		Hashtable headerColumnMap = new Hashtable();
		Hashtable entryMap=new Hashtable();
		int count = 0;
		headersLst.add("Query Type");
		headersLst.add("Query Details");
		headersLst.add("Count");
		headersLst.add("Avg Execution Time(ms)");
		headersLst.add("Total Execution Time(ms)");
		headersLst.add("% Time");
		headersLst.add("Error");
		headersLst.add("Database");
		JSONObject csvJson = JSONObject.fromObject(jsonString);

		JSONArray gridData = csvJson.getJSONArray("gridData");
		for(Object js : gridData){
			JSONObject gridJson = (JSONObject) js;
			String queryType = (String) gridJson.get("Query_Type");
			String queryDetails = (String) gridJson.get("Query_Details");
			String queryCount = String.valueOf(gridJson.get("Count"));
			String avgExecutionTime = String.valueOf(gridJson.get("Avg_Execution_Time"));
			String totalExecutionTime = String.valueOf(gridJson.get("Total_Execution_Time"));
			String progress = String.valueOf(gridJson.get("Progress"));
			String error = (String) gridJson.get("Error");
			if(error != null && !error.equals("-")) {
				count = count + 1;
			}
			String dbDetails = (String) gridJson.get("Database_Details_For_Csv");
			if(dbDetails != null && dbDetails.indexOf("'>") > -1 && dbDetails.indexOf("</span") > -1){
				dbDetails = dbDetails.substring(dbDetails.indexOf("'>")+2,dbDetails.indexOf("</span"));
			}
			try{
				if(queryDetails!=null){
					queryDetails  = queryDetails.replaceAll("&acute;","\u2018");
				}
				if(error!=null){
					error  = error.replaceAll("&acute;","\u2018");
				}
				if(dbDetails!=null){
					dbDetails  = dbDetails.replaceAll("&acute;","\u2018");
				}
			} catch(Exception e) {
				System.out.println("Exception while replacing the value for queryDetails, error, dbDetails "+e);
			}
			columnsLst.add(queryType);
			columnsLst.add(queryDetails);
			columnsLst.add(queryCount);
			columnsLst.add(avgExecutionTime);
			columnsLst.add(totalExecutionTime);
			columnsLst.add(progress);
			columnsLst.add(error);
			columnsLst.add(dbDetails);
        }
		headerColumnMap.put(headersLst,columnsLst);
		entryMap.put(headerStr,headerColumnMap);
		entryMap.put("errorQryCount",count);
		return entryMap;
	}

	private String getSqlExecCutoffTime(String agentInfoStr) {
		if(agentInfoStr == null) {
			return null;
		}
		int sqlCutoffIndex = agentInfoStr.indexOf("-SQL_Exec_CutOff ");
		if (sqlCutoffIndex < 0)
			return null;
		String sqlCutoffTime = agentInfoStr.substring(sqlCutoffIndex+17);
		sqlCutoffTime = sqlCutoffTime.trim();
		sqlCutoffIndex = sqlCutoffTime.indexOf(' ');
		if (sqlCutoffIndex < 0)
			return (sqlCutoffTime.trim());
		return (sqlCutoffTime.substring(0,sqlCutoffIndex).trim());
	}

	private void getSqlGroupingQueryDetails(Hashtable sqlQueryTable, ArrayList singleRowData, double thisExecutionTime, double result, double responseTime){
		String query = escapeHTML(singleRowData.get(2).toString());
		String queryType = (String)singleRowData.get(0);
		double currentCount = 0;
		String slowQueryDescriptor = "Other Slow Queries On - ";
		String errorQueryDescriptor = "Other Error Queries On - ";
		if(query.matches("[0-9]+")){
			currentCount = Double.parseDouble(query);
			queryType="OTHER";
			String newQuery = "";
			if(((String)singleRowData.get(8)).contains("SLOWEXCCEDQUERY")){
				newQuery = slowQueryDescriptor + singleRowData.get(7).toString();
			}else if(((String)singleRowData.get(8)).contains("ERROREXCCEDQUERY")){
				newQuery = errorQueryDescriptor + singleRowData.get(7).toString();
			}
			if(sqlQueryTable.containsKey(query)) {
				sqlQueryTable.put(newQuery, sqlQueryTable.remove(query));
			}
			query=newQuery;
		}
		if(sqlQueryTable.containsKey(query)) {
			ArrayList queryList = (ArrayList) sqlQueryTable.get(query);
				double totalCount = (Double)queryList.get(0);
				totalCount += (query.startsWith(slowQueryDescriptor) || query.startsWith(errorQueryDescriptor)) ? currentCount : 1.0;
			double totalExecuteTime = (Double)queryList.get(1) + thisExecutionTime;
			double avgExecuteTime = totalExecuteTime/totalCount;
			double overallTime = (totalExecuteTime/responseTime)*100;
			queryList.set(0,totalCount);
			queryList.set(1,totalExecuteTime);
			queryList.set(2,Math.round(avgExecuteTime));
			String queryErrorInfo= (String)singleRowData.get(3);
			if(!queryErrorInfo.equals("-")) 
			{
				ArrayList err_list = (ArrayList)sqlQueryTable.get(query+"~#~error");
				if(!err_list.contains(queryErrorInfo))
				{
					String queryError = (String)queryList.get(4);
					queryError = queryError.equals("-")?"":queryError;
					String totalQueryError = (queryError.length()>1)? queryError+","+queryErrorInfo:queryErrorInfo;
					queryList.set(4,totalQueryError);
					err_list.add(queryErrorInfo);
				}
			}
			queryList.set(5,overallTime);
			sqlQueryTable.put(query,queryList);
		}
		else {
				double initCount = (query.startsWith(slowQueryDescriptor) || query.startsWith(errorQueryDescriptor)) ? currentCount : 1.0;
			ArrayList queryDetailsList = new ArrayList();
			queryDetailsList.add(initCount);                    // add - count
			queryDetailsList.add(thisExecutionTime);            // add - execution time
			queryDetailsList.add(Math.round(thisExecutionTime/initCount));  // add - average execution time
				queryDetailsList.add(queryType);         // add - query type
			queryDetailsList.add(singleRowData.get(3));         // add - error
			
			ArrayList  err_list = new ArrayList();
			err_list.add((String)singleRowData.get(3));//error List
			sqlQueryTable.put(query+"~#~error",err_list);

			queryDetailsList.add(result);                       // add - % time
			queryDetailsList.add(singleRowData.get(4));         // add - ip
			queryDetailsList.add(singleRowData.get(5));         // add - port
			queryDetailsList.add(singleRowData.get(6));         // add - dbType
			queryDetailsList.add(singleRowData.get(7));         // add - sid
			sqlQueryTable.put(query,queryDetailsList);
		}
	}
%>

<%
	EgDiscInfo discInfo = new EgDiscInfo("manager");
	//String businessTransTest = "BusinessTransTest";
	String trgt_Host = null ; 
	String portNo = null ;
	String url = null ; 

	String device = null ; 
	String os = null ; 
	String browser = null ; 
	String browserVersion = null ; 
	String country = null ; 
	String region = null ; 
	String city = null ; 

	String lbl_Healthy = mappingInfo.getTextDescription("monitor.apmtopology.Healthy");
	String lbl_Slow = mappingInfo.getTextDescription("monitor.apmtopology.Slow");
	String lbl_Stalled = mappingInfo.getTextDescription("monitor.apmtopology.Stalled");
	String lbl_Error = mappingInfo.getTextDescription("monitor.apmtopology.Error");

	String uiFile = "eg_ui.ini";
	String s_iniFile_dir = EgInstallInfo.getInstallDir()+ "/manager/config/";
	IniFile egUI = new IniFile(s_iniFile_dir + uiFile);
	String currentDateFormat = egUI.getValue("CURRENT_DATE_FORMAT","selectedDateFormat");

	/* Getting MaxQueryValue for SQL Grouping */
	double maxQueryValue;
	String maxQueryValueStr = apm.getValue("SQL_CALL_GROUPING","MaxLimit");
	if(maxQueryValueStr != null && maxQueryValueStr.trim().length() > 0) {
		try {
			maxQueryValue = Double.parseDouble(maxQueryValueStr);
		} catch(Exception e) {
			maxQueryValue = DEFAULT_MAX_QUERY_VALUE;
		} 
	} else {
		maxQueryValue = DEFAULT_MAX_QUERY_VALUE;
	}

	String buttonClicked = request.getParameter("buttonClicked");
	String guidString = request.getParameter("EG_GUID");
	String asyncGuid = request.getParameter("asyncGuid");
	String nodeOrder = request.getParameter("nodeOrder");
	nodeOrder = StringUtils.decodeSecurityChar(nodeOrder);
	String requestType = request.getParameter("requestType");
	String isAsyncThread = request.getParameter("isAsyncThread");
	String timeString = request.getParameter("timeString");
	timeString = StringUtils.decodeSecurityChar(timeString); 
	String allColumns = apm.getValue("SUMMARY_DATA_FOR_TEST","ALL_COLUMNS_LIST");
	ArrayList allColumnList = StringUtils.egTokenizer(allColumns,",");
	ArrayList summaryDataList = (ArrayList) session.getAttribute(sessionSummaryData);
	Hashtable summaryDataDetails = new Hashtable() ; 
	String keys = guidString+seperatorHash+nodeOrder;
	ArrayList summaryWholeData = null ; 
	if(summaryDataList != null && summaryDataList.size()>0)
	{
		summaryDataDetails = (Hashtable) summaryDataList.get(0);
		summaryWholeData = (ArrayList) summaryDataDetails.get(keys);
		if(summaryWholeData!=null)
		{
			trgt_Host = (String) summaryWholeData.get(allColumnList.indexOf("TRGT_HOST"));
			portNo = (String) summaryWholeData.get(allColumnList.indexOf("PORT_NO"));
			url = (String) summaryWholeData.get(allColumnList.indexOf("URL"));
			
		 
			device = (String) summaryWholeData.get(allColumnList.indexOf("DEVICE"));
			os = (String) summaryWholeData.get(allColumnList.indexOf("OS"));
			browser = (String) summaryWholeData.get(allColumnList.indexOf("BROWSER"));
			browserVersion = (String) summaryWholeData.get(allColumnList.indexOf("BROWSER_VERSION"));
			country = (String) summaryWholeData.get(allColumnList.indexOf("COUNTRY"));
			region = (String) summaryWholeData.get(allColumnList.indexOf("REGION"));
			city = (String) summaryWholeData.get(allColumnList.indexOf("CITY"));
		}
	}

	//*****Code Start****Getting sqlExecCutoffTime data from eg_agent.ini file****By prathap
	
	String sqlExecCutoffTime = DEFAULT_SQL_EXEC_CUTOFF_TIME;
	EgAgentInfo agentInfo = new EgAgentInfo("manager");
	String agentInfoKey = testName+"::"+trgt_Host+":"+portNo;
	String agentInfoValue = agentInfo.getValueForVar(agentInfoKey);
	if(agentInfoValue != null && agentInfoValue.trim().length()>0)
	{
		 sqlExecCutoffTime = getSqlExecCutoffTime(agentInfoValue);
		if (sqlExecCutoffTime == null) 
			sqlExecCutoffTime = DEFAULT_SQL_EXEC_CUTOFF_TIME;
	}
	//*****Code End****Getting sqlExecCutoffTime data from eg_agent.ini file****

	String jvmComp = trgt_Host+":"+portNo;
	String compType=discInfo.getServerTypesForComponentNamePort(jvmComp);
	String compName = mappingInfo.getComponentTypeDescription(compType);
	response.setContentType("application/json;charset=UTF-8");
	JSONObject rootJson = new JSONObject();
	BTMHelper btmHelperObj = new BTMHelper();
	try
	{
		if(buttonClicked != null)
		{
			// For Summary Tab Clicked
			if(buttonClicked.equalsIgnoreCase(summaryTabStr))
			{
				
				if(summaryDataList != null && summaryDataList.size()>0)
				{
					String overAllExperience = (String) summaryDataList.get(4);
					if(overAllExperience.equalsIgnoreCase(userExperienceErrorStr))
						overAllExperience = lbl_Error;
					else if(overAllExperience.equalsIgnoreCase(userExperienceStalledStr))
						overAllExperience = lbl_Stalled;
					else if(overAllExperience.equalsIgnoreCase(userExperienceSlowStr))
						overAllExperience = lbl_Slow;
					else if(overAllExperience.equalsIgnoreCase(userExperienceHealthyStr))
						overAllExperience = lbl_Healthy;
					String transName = "";
					
					if(summaryDataDetails != null)
					{
						if(summaryWholeData != null && summaryWholeData.size()>0)
						{
							int thisNodeSelfTime = 0;
							
							if(timeString != null && timeString.length()>0)
							{
								thisNodeSelfTime = Integer.parseInt(timeString);
								/*StringTokenizer slfTimeTokenizer = new StringTokenizer(timeString,seperatorTilt);
								while(slfTimeTokenizer.hasMoreTokens())
								{
									String nodeOrderWithValue = slfTimeTokenizer.nextToken();
									if(nodeOrderWithValue != null && nodeOrderWithValue.indexOf(seperatorHyphen)>-1)
									{
										String tknzrNode = nodeOrderWithValue.substring(0,nodeOrderWithValue.indexOf(seperatorHyphen));
										if(tknzrNode != null && tknzrNode.equals(nodeOrder))
										{
											String thisstrNodeSelfTime = nodeOrderWithValue.substring(nodeOrderWithValue.indexOf(seperatorHyphen)+1);
											thisNodeSelfTime = Integer.parseInt(thisstrNodeSelfTime);
											break;
										}
									}
								}*/
							}
							double resTime = 0.0;
							
							String apmIdentifier = (String) summaryWholeData.get(allColumnList.indexOf("TEST_NAME"));
							String apmColumns = apm.getValue("SUMMARY_DATA_FOR_TEST",apmIdentifier.toUpperCase());
							ArrayList apmColumnList = StringUtils.egTokenizer(apmColumns,",");
							String threadDetail = (String) summaryWholeData.get(allColumnList.indexOf("Thread ID"));
							String info = "-";
							String threadName = "-";
							String threadId = threadDetail;
							String title = "";
							boolean isJava = apmType.equalsIgnoreCase("Java");
							/*  This code written for specific logic common to Both the tests */
							 if(isJava)
							{
								threadName = threadDetail.substring(0, threadDetail.lastIndexOf("["));
								threadId = threadDetail.substring(threadDetail.lastIndexOf("["));
							}
							double slowUrlThreshold = getDoubleFromBigDecimalValue(summaryWholeData.get(allColumnList.indexOf("SLOW_URL_THRESHOLD")));
							double stalledUrlThreshold =getDoubleFromBigDecimalValue(summaryWholeData.get(allColumnList.indexOf("STALLED_URL_THRESHOLD")));
							boolean noneThreshold = false;
							boolean isStalledUnlimited = false;

							if(slowUrlThreshold < 0.0D && stalledUrlThreshold < 0.0D ){
								noneThreshold = true;
							}
							else if(stalledUrlThreshold < 0.0D){
								isStalledUnlimited = true;
							}
							//Summay Page Grid Table data preparation starts here
							String compTypeFromNickPort = discInfo.getServerTypesForComponentNamePort(trgt_Host+":"+portNo);
							JSONObject tmpObj = new JSONObject();
							JSONArray gridData = new JSONArray();


							for(int i = 0 ; i< apmColumnList.size(); i++)
							{
								String valueToBeAddedInJsonObject = "-";
								String dataTobeInserted  = (String)apmColumnList.get(i) ;
;								int indexToBeFetchedFromAllColums = allColumnList.indexOf(dataTobeInserted);
								String keyForJson = mappingInfo.getTextDescription("monitor.apmtopology."+dataTobeInserted ); 
								if(indexToBeFetchedFromAllColums > -1)
									valueToBeAddedInJsonObject = "<span class='font_bold11'>"+summaryWholeData.get(indexToBeFetchedFromAllColums)+"</span>" ;
								if(dataTobeInserted.equalsIgnoreCase("URL"))
								{
									if(isAsyncThread != null && isAsyncThread.equals(asyncThreadStr))
									{
										valueToBeAddedInJsonObject = "<span class='font_bold11'>Async Call from "+summaryWholeData.get(indexToBeFetchedFromAllColums)+"</span>";
									}
								}
								else if(dataTobeInserted.equalsIgnoreCase("Request Time"))
								{
									String managerTimeFormat = DateUtil.changeDateFormat(summaryWholeData.get(indexToBeFetchedFromAllColums).toString(),"yyyy-MM-dd HH:mm:ss",currentDateFormat+" HH:mm:ss");
									String timeZone = (String) summaryWholeData.get(allColumnList.indexOf("TIME_ZONE"));
									valueToBeAddedInJsonObject = "<span class='font_bold11'>"+managerTimeFormat+" "+timeZone+"</span>";
								}
								else if(dataTobeInserted.equalsIgnoreCase("Business Transaction"))
								{
									int infoIndex = allColumnList.indexOf(dataTobeInserted);
									info = (String) summaryWholeData.get(infoIndex);
									if(nodeOrder != "1")
									{
										summaryDataDetails = (Hashtable) summaryDataList.get(0);
										if(summaryDataDetails.containsKey(guidString+"#1"))
										{
											ArrayList startNode = (ArrayList) summaryDataDetails.get(guidString+"#1");
											if(startNode != null)
											{
												info = startNode.get(infoIndex).toString();
											}
										}
									}
									valueToBeAddedInJsonObject = "<span class='font_bold11'>"+info.substring(1)+"</span>" ;
								}
								else if(dataTobeInserted.equalsIgnoreCase("User Experience (Overall)"))
								{
									String userExpIconOverall = "BTM_transaction_state_"+overAllExperience;
									if(overAllExperience.equals(userExperienceHealthyStr))
										userExpIconOverall = "BTM_transaction_state_Normal";
									valueToBeAddedInJsonObject = "<div style='float:left;height:20px;padding-top:1px';class='btmDisplayFieldCompValueEllipsis' data-qclass='yellowTip para' data-qtip="+overAllExperience+"><img src='../images/Light/"+overAllExperience.toLowerCase()+".png'></div>";
									if(monitor_Skin.equals("Dark"))
									{
										valueToBeAddedInJsonObject = "<div style='float:left;height:20px;padding-top:1px';class='btmDisplayFieldCompValueEllipsis' data-qclass='yellowTip para' data-qtip="+overAllExperience+"><img src='../images/Dark/"+overAllExperience.toLowerCase()+".png'></div>";
									}
								}
								else if(dataTobeInserted.equalsIgnoreCase("APM_TYPE"))
								{
									transName = "";
									String thisNodeHealth = null;
									String tmp = mappingInfo.getTextDescription("monitor.apmtopology.Processing Status on ");
									String trghost = trgt_Host+":"+portNo;
									if(portNo != null && portNo.equals("NULL"))
									{
										 trghost = trgt_Host;
									}
									keyForJson = mappingInfo.getTextDescription("monitor.apmtopology."+apmType)+" "+tmp+" "+trghost;
									if (testName != null)
										thisNodeHealth = mappingInfo.getMeasureDescription(testName , summaryWholeData.get(allColumnList.indexOf("Business Transaction")).toString());
									if(thisNodeHealth != null && thisNodeHealth.equals("Error transactions"))
									{
										transName = lbl_Error;
									}
									else
									{
										if(noneThreshold){
											transName = lbl_Healthy;
										}
										else{
											if(isStalledUnlimited){
												transName = thisNodeSelfTime>slowUrlThreshold ? lbl_Slow:lbl_Healthy;
											}
											else{
												transName = (thisNodeSelfTime>slowUrlThreshold)?((thisNodeSelfTime>stalledUrlThreshold)?lbl_Stalled:lbl_Slow):lbl_Healthy;
											}
										}
									}
									valueToBeAddedInJsonObject =  "<div style='float:left;height:20px;padding-top:1px';class='btmDisplayFieldCompValueEllipsis' data-qclass='yellowTip para' data-qtip="+transName+"><img src='../images/Light/"+transName.toLowerCase()+".png'></div>";

									
									if(monitor_Skin.equals("Dark"))
									{
										valueToBeAddedInJsonObject = "<div style='float:left;height:20px;padding-top:1px';class='btmDisplayFieldCompValueEllipsis' data-qclass='yellowTip para' data-qtip="+transName+"><img src='../images/Dark/"+transName.toLowerCase()+".png'></div>";
									}
								}
								else if(dataTobeInserted.equalsIgnoreCase("Total Processing Time"))
								{
									resTime = getDoubleValue(summaryWholeData.get(indexToBeFetchedFromAllColums));
									if(noneThreshold){
										valueToBeAddedInJsonObject = "<span class='font_bold11'>"+df.format(resTime)+" ms </span>";
									}
									else{
										if(isStalledUnlimited){
											valueToBeAddedInJsonObject = (resTime>slowUrlThreshold)? "<span class='font_bold11'>"+df.format(resTime)+" ms (Transaction was slower than the slow threshold of "+df.format(summaryWholeData.get(allColumnList.indexOf("SLOW_URL_THRESHOLD")))+" ms)</span>" : "<span class='font_bold11'>"+df.format(resTime)+" ms (Transaction was executed within the slow/stalled threshold of "+df.format(summaryWholeData.get(allColumnList.indexOf("SLOW_URL_THRESHOLD")))+"/Unlimited ms respectively)</span>" ; 
										}
										else{
											valueToBeAddedInJsonObject = (resTime>stalledUrlThreshold)? "<span class='font_bold11'>"+df.format(resTime)+" ms (Transaction was slower than the stalled threshold of "+df.format(summaryWholeData.get(allColumnList.indexOf("STALLED_URL_THRESHOLD")))+" ms)</span>" : (resTime>slowUrlThreshold)? "<span class='font_bold11'>"+df.format(resTime)+" ms (Transaction was slower than the slow threshold of "+df.format(summaryWholeData.get(allColumnList.indexOf("SLOW_URL_THRESHOLD")))+" ms)</span>" : "<span class='font_bold11'>"+df.format(resTime)+" ms (Transaction was executed within the slow/stalled threshold of "+df.format(summaryWholeData.get(allColumnList.indexOf("SLOW_URL_THRESHOLD")))+"/"+df.format(summaryWholeData.get(allColumnList.indexOf("STALLED_URL_THRESHOLD")))+" ms respectively)</span>" ; 
										}
									}

								}else if(dataTobeInserted.equalsIgnoreCase("Session ID"))
								{
									String sessionId= (String)summaryWholeData.get(indexToBeFetchedFromAllColums);
									valueToBeAddedInJsonObject = "<span class='font_bold11' data-qclass='yellowTip para' data-qtip="+sessionId+" >"+sessionId+"</span>" ;
								}
								else if(dataTobeInserted.equalsIgnoreCase("Component"))
								{
									title = "Call Drill Down for "+url+ " on "+trgt_Host+":"+portNo;
									valueToBeAddedInJsonObject="<span class='font_bold11'>"+trgt_Host+":"+portNo+"</span>";
									rootJson.put("componentLookupData","<div style='float:left'>"+"Component"+" : </div><div style='float:left;width:80%'; class='btmDisplayFieldCompValueEllipsis' data-qclass='yellowTip para' data-qtip='"+trgt_Host+":"+portNo+" ("+mappingInfo.getComponentTypeDescription(compTypeFromNickPort)+")"+"'>"+trgt_Host+":"+portNo+" ("+mappingInfo.getComponentTypeDescription(compTypeFromNickPort)+")"+"</div>");
									
									if(portNo != null && portNo.equals("NULL"))
									{
										title = "Call Drill Down for "+url+ " on "+trgt_Host;
										valueToBeAddedInJsonObject="<span class='font_bold11'>"+trgt_Host+"</span>";
										rootJson.put("componentLookupData","<div style='float:left'>"+"Component"+" : </div><div style='float:left;width:80%'; class='btmDisplayFieldCompValueEllipsis'  data-qclass='yellowTip para' data-qtip='"+trgt_Host+" ("+mappingInfo.getComponentTypeDescription(compTypeFromNickPort)+")"+"'>"+trgt_Host+" ("+mappingInfo.getComponentTypeDescription(compTypeFromNickPort)+")"+"</div>");
									}
								}
								else if(dataTobeInserted.equalsIgnoreCase("Query String"))
								{
									String queryString = BTMHelper.decodeUrlString(summaryWholeData.get(indexToBeFetchedFromAllColums).toString()) ; 
									valueToBeAddedInJsonObject = "<span class='font_bold11' data-qclass='yellowTip para' data-qtip="+queryString+" >"+queryString+"</span>";
								}
								else if(dataTobeInserted.equalsIgnoreCase("Thread Name"))
								{
									valueToBeAddedInJsonObject = "<span class='font_bold11'>"+threadName+"</span>";
								}
								else if(dataTobeInserted.equalsIgnoreCase("Thread ID"))
								{
									valueToBeAddedInJsonObject = "<span class='font_bold11'>"+threadId+"</span>";
								}
								else if(dataTobeInserted.equalsIgnoreCase("Transaction Threshold"))
								{
									if(noneThreshold){
										valueToBeAddedInJsonObject =  "<span class='font_bold11'>"+mappingInfo.getTextDescription("monitor.apmtopology.None")+"</span>" ; 
									}
									else{
										valueToBeAddedInJsonObject =  "<span class='font_bold11' >"+df.format(summaryWholeData.get(allColumnList.indexOf("SLOW_URL_THRESHOLD")))+" ms</span>" ; 
									}
								}
								else if(dataTobeInserted.equalsIgnoreCase("Request GUID"))
								{
									valueToBeAddedInJsonObject = "<span class='font_bold11' >"+guidString+"</span>" ;
								}
								else if(dataTobeInserted.equalsIgnoreCase("CPU_TIME"))
								{
									String cpuTime = summaryWholeData.get(indexToBeFetchedFromAllColums).toString();
									if(cpuTime.startsWith("-5")){
										continue;
									}
									double  cpuPercentage = 0.0;
									try 
									{
										valueToBeAddedInJsonObject  = "<span class='font_bold11'>"+"-"+"</span>";
										double tmpTiming = Double.parseDouble(cpuTime);
										if(tmpTiming >=0 && resTime>0)
										{
											cpuPercentage = ((Double.parseDouble(summaryWholeData.get(indexToBeFetchedFromAllColums).toString()))/resTime)*100;
											valueToBeAddedInJsonObject  = "<span class='font_bold11'>"+df.format(tmpTiming)+" ms ("+dft.format(cpuPercentage)+" %)</span>";
										}
									}
									catch (Exception ex)
									{
										System.out.println("Exception occured while parsing the value ");
									}
								}else if(dataTobeInserted.equalsIgnoreCase("BLOCK_TIME") || dataTobeInserted.equalsIgnoreCase("WAIT_TIME"))
								{
									String blockWaitTime = summaryWholeData.get(indexToBeFetchedFromAllColums).toString();
									if(blockWaitTime.startsWith("-5")){
										continue;
									}
									try
									{
										valueToBeAddedInJsonObject  = "<span class='font_bold11'>"+"-"+"</span>";
										double tmpTiming = Double.parseDouble(blockWaitTime);
										if(tmpTiming>=0.0)
											valueToBeAddedInJsonObject = "<span class='font_bold11'>"+df.format(tmpTiming)+" ms</span>";
									}catch(Exception e)
									{
										System.out.println("Exception occured while parsing the value ");
										
									}
								}
								else if(dataTobeInserted.equalsIgnoreCase("Pre Processing Time"))
								{
									double preProcessingTime = getDoubleFromBigDecimalValue(summaryWholeData.get(indexToBeFetchedFromAllColums)); 
									valueToBeAddedInJsonObject = "<span class='font_bold11'>"+df.format(preProcessingTime)+" ms</span>" ;
								}else if(dataTobeInserted.equalsIgnoreCase("USERNAME") || dataTobeInserted.equalsIgnoreCase("BUSINESS_CONTEXT"))
								{
									String temp = summaryWholeData.get(indexToBeFetchedFromAllColums).toString();
									if(temp.equals("-")){
										continue;
									}
								}
								else if(dataTobeInserted.equalsIgnoreCase("Device"))
								{
									valueToBeAddedInJsonObject = "<span class='font_bold11' >"+device+"</span>" ;
								}else if(dataTobeInserted.equalsIgnoreCase("Operating System"))
								{
									valueToBeAddedInJsonObject = "<span class='font_bold11' >"+os+"</span>" ;
								}else if(dataTobeInserted.equalsIgnoreCase("Browser"))
								{
									valueToBeAddedInJsonObject = "<span class='font_bold11' >"+browser+"</span>" ;
								}else if(dataTobeInserted.equalsIgnoreCase("Browser version"))
								{
									valueToBeAddedInJsonObject = "<span class='font_bold11' >"+browserVersion+"</span>" ;
								}else if(dataTobeInserted.equalsIgnoreCase("Country"))
								{
									valueToBeAddedInJsonObject = "<span class='font_bold11' >"+country+"</span>" ;
								}else if(dataTobeInserted.equalsIgnoreCase("Region"))
								{
									valueToBeAddedInJsonObject = "<span class='font_bold11' >"+region+"</span>" ;
								}
								else if(dataTobeInserted.equalsIgnoreCase("City"))
								{
									valueToBeAddedInJsonObject = "<span class='font_bold11' >"+city+"</span>" ;
								}
							
								tmpObj.put("A",keyForJson);
								tmpObj.put("B",valueToBeAddedInJsonObject);
								gridData.add(tmpObj);
								tmpObj = new JSONObject();
							}
							String topologyWindowTitle = mappingInfo.getMeasureDescription(testName , summaryWholeData.get(2).toString()+":"+info.substring(1));
							rootJson.put("gridData",gridData);
							rootJson.put("title",title+"^%^"+topologyWindowTitle);
							rootJson.put("SummaryDataPresence", "yes");
							//Summay Page Grid Table data preparation ends here
							//Summary Page Top LHS panel data starts
							rootJson.put("totalProcessTimeLookupData","<div style='float:left'>"+"Total Processing time"+" : </div><div style='float:left'><span class='btmDisplayFieldValue' >"+df.format(resTime)+" ms</span></div>");

							rootJson.put("urlLookupData","<div style='float:left;'>"+"URL"+" : </div><div style='float:left;width:350px' class='btmDisplayFieldURLValueEllipsis' data-qclass='yellowTip para' data-qtip='"+url+"'>"+url+"</div>");

							String javaExecString = "<p style='white-space:nowrap;text-overflow:ellipsis;overflow: hidden;'>"+ mappingInfo.getTextDescription("monitor.apmtopology."+apmType) +" (this node) </p><p class='value1'>"+thisNodeSelfTime+"<span class='ms1'> ms </span></p>";
							rootJson.put("javaExecTimeData",javaExecString);

							String ExternalExecString = "<p style='white-space:nowrap;text-overflow:ellipsis;overflow: hidden;'>Remote Calls (database, others)</p><p class='value2'>"+((int)resTime-thisNodeSelfTime)+"  <span class='ms2'> ms </span></p>";
							rootJson.put("externalExecTimeData",ExternalExecString);
							//Summary Page Top LHS panel data ends


							// Pie Chart Json Formation Starts Here

							JSONObject pieDatarootJson = new JSONObject();

							JSONObject chartDataObj = new JSONObject();
							JSONObject chartDataObj2 = new JSONObject();
							JSONObject chartDataObj3 = new JSONObject();
							ArrayList arlistObj = new ArrayList();
							arlistObj.add(3);
							arlistObj.add(0);
							arlistObj.add(32);
							arlistObj.add(0);
							chartDataObj.put("type","pie");
							chartDataObj.put("plotBackgroundColor",null);
							chartDataObj.put("plotBorderWidth",null);
							chartDataObj.put("plotShadow",false);
							chartDataObj.put("backgroundColor","transparent");
							chartDataObj.put("margin",arlistObj);
							chartDataObj.put("reflow",true);
							pieDatarootJson.put("chart",chartDataObj);
							chartDataObj = new JSONObject();

							chartDataObj.put("text","");
							chartDataObj2.put("color", "#5e5e5e");
							chartDataObj2.put("fontWeight", "bold");
							chartDataObj2.put("font-size", "13px");
							chartDataObj2.put("font-family", "LucidaGrandeBold !important");
							chartDataObj.put("style",chartDataObj2);
							pieDatarootJson.put("title",chartDataObj);
							chartDataObj = new JSONObject();
							chartDataObj2 = new JSONObject();
							JSONObject labelStyle=new JSONObject();

							labelStyle.put("fontWeight","normal");
							labelStyle.put("fontFamily","Arial");
							chartDataObj.put("enabled",false);
							pieDatarootJson.put("credits",chartDataObj);
							chartDataObj = new JSONObject();

							chartDataObj.put("enabled",false);
							pieDatarootJson.put("exporting",chartDataObj);
							chartDataObj = new JSONObject();

							chartDataObj.put("allowPointSelect", true);
							chartDataObj.put("cursor", "pointer");
							chartDataObj2.put("enabled",true);
							chartDataObj2.put("distance",15);
							chartDataObj2.put("format","{point.percentage:.0f}%");
							chartDataObj2.put("style",labelStyle);


							if(monitor_Skin.equals("Dark"))
								chartDataObj2.put("color","#c6c6c6");
							chartDataObj.put("dataLabels", chartDataObj2);
							chartDataObj.put("showInLegend",true);
							chartDataObj2 = new JSONObject();

							//chartDataObj2.put("legendItemClick", "function(e){e.preventDefault();}");
							chartDataObj2.put("legendItemClick", "function(){this.select();chart.tooltip.refresh(this); return false;}");
							chartDataObj3.put("events",chartDataObj2);
							chartDataObj.put("point",chartDataObj3);
							chartDataObj3 = new JSONObject();

							chartDataObj.put("startAngle",90);
							if(monitor_Skin.equals("Dark"))
								chartDataObj.put("borderColor","#444444");
							chartDataObj3.put("pie",chartDataObj);
							pieDatarootJson.put("plotOptions",chartDataObj3);
							chartDataObj = new JSONObject();
							chartDataObj2 = new JSONObject();
							chartDataObj3 = new JSONObject();

							chartDataObj.put("enabled",true);
							chartDataObj.put("layout","horizontal");
							chartDataObj.put("x",0);
							chartDataObj.put("y",10);
							chartDataObj.put("symbolWidth",10);
							chartDataObj.put("symbolHeight",10);

							//chartDataObj2.put("font","normal 11px LucidaGrandeRegular !important");
							//chartDataObj2.put("font"," 11px Arial !important");
							chartDataObj2.put("fontFamily"," Arial !important");
							chartDataObj2.put("fontSize"," 11px !important");
							//color:#333333;font-size:12px;font-family:Arial;font-weight:500;fill:#333333;
							chartDataObj2.put("font-weight","Normal !important");
							if(monitor_Skin.equals("Dark"))
							{
								chartDataObj2.put("color","#c6c6c6");
								chartDataObj.put("itemHoverStyle",chartDataObj2);
							}
							chartDataObj.put("itemStyle",chartDataObj2);
							chartDataObj.put("labelFormatter","function() { return this.name.length>15?this.name.slice(0, 15)+'..':this.name}");
							pieDatarootJson.put("legend",chartDataObj);
							chartDataObj = new JSONObject();
							chartDataObj2 = new JSONObject();

							//chartDataObj.put("pointFormat", "<b style='font-family: Arial !important;font-weight:bold;'>{point.y} ms</b>({point.percentage:.2f}%)");
							//chartDataObj.put("pointFormat", "<b >{point.y} ms</b>({point.percentage:.2f}%)<br/>");
							chartDataObj.put("useHTML",true);
							chartDataObj.put("headerFormat", "<div style='margin-bottom:10px;font-family:Arial !important;font-weight:normal !important;font-size:11px !important'><b>{point.key}</b></div>");
							chartDataObj.put("pointFormat", "<div style='font-family:Arial !important;font-weight:bold !important;font-size:12px !important'>{point.y} ms <span style='font-size:11px !important;font-weight:normal !important;'>({point.percentage:.2f}%)</span></div>");
							pieDatarootJson.put("tooltip",chartDataObj);
							chartDataObj = new JSONObject();

							ArrayList seriesHolder = new ArrayList();
							ArrayList tempDataList = new ArrayList();
							if(portNo != null && portNo.equals("NULL"))
								chartDataObj2.put("name", summaryWholeData.get(0));
							else
								chartDataObj2.put("name", summaryWholeData.get(0)+":"+portNo);
							chartDataObj2.put("y", thisNodeSelfTime);
							chartDataObj2.put("color", "#115fa6");
							tempDataList.add(chartDataObj2);
							chartDataObj3.put("name", "Others");
							chartDataObj3.put("y", (int)resTime-thisNodeSelfTime);
							chartDataObj3.put("color", "#e9a645");
							tempDataList.add(chartDataObj3);
							chartDataObj.put("data",tempDataList);
							seriesHolder.add(chartDataObj);
							pieDatarootJson.put("series",seriesHolder);
							chartDataObj = new JSONObject();
							chartDataObj2 = new JSONObject();
							chartDataObj3 = new JSONObject();

							rootJson.put("pieDatarootJson",pieDatarootJson);
							//System.out.println("PIE Chart RootJson : "+pieDatarootJson);
							// Pie Chart Json Formation Ends Here

						}
						else
						{
							rootJson.put("SummaryDataPresence", "no");
						}
						out.println(rootJson.toString());
					}
				}
			}
			// HotSpot Tab data preparation starts here
			else if(buttonClicked.equals(hotSpotTabStr))
			{
				ArrayList hotSpotDetails = (ArrayList) session.getAttribute("HotSpotData"+seperatorHash+nodeOrder);
				ArrayList traceDetails = (ArrayList) session.getAttribute("TraceData"+seperatorHash+nodeOrder);
				boolean isPartialGraph = false;
				if(traceDetails != null && traceDetails.size()>0)
				{
					String rootNode = (String) traceDetails.get(0);
					if(rootNode.startsWith("0#="))
					{
						isPartialGraph = false;
					}
					else
					{
						isPartialGraph = true;
					}
				}
				double totalDuration = 0.00;
				double totalPercentage = 0.00;
				JSONArray gridData = new JSONArray();
				if(hotSpotDetails != null && hotSpotDetails.size()>0 && !isPartialGraph)
				{
					EgSorter egSort = new EgSorter(hotSpotDetails,4);
					hotSpotDetails = (ArrayList)egSort.sort(3,"Double","desc");

					for(int i=0; i<hotSpotDetails.size(); i++)
					{
						ArrayList temp  = (ArrayList) hotSpotDetails.get(i);
						JSONObject tmpObj = new JSONObject();
						String methodDetail = temp.get(0).toString();
						if(methodDetail.indexOf("[ASYNC]")>0)
							methodDetail = methodDetail.substring(0,methodDetail.indexOf("[ASYNC]"));
						
						tmpObj.put("MethodDetail",methodDetail);
						tmpObj.put("Count",(Integer)temp.get(1));
						tmpObj.put("Duration",Integer.valueOf(df.format(temp.get(2))));
						tmpObj.put("Percentage",Double.parseDouble(dft.format(temp.get(3))));
						gridData.add(tmpObj);
					}
					rootJson.put("gridData", gridData);
					rootJson.put("hotSpotPresence", "yes");
				}
				else
				{
					rootJson.put("nickName",trgt_Host+":"+portNo);
					rootJson.put("url",url);
					rootJson.put("compName",compName);
					rootJson.put("hotSpotPresence", "no");
				}
				out.println(rootJson.toString());
			}
			//HotSpot Data preparation ends here

			//Error Detail Data preparation starts
			else if(buttonClicked.equals(errorDetailsTabStr))
			{
				boolean expPresence = false;
				String nodeId = request.getParameter("index");
				if(nodeId == null)
					nodeId = "-1";

				Hashtable nodeIdTable = new Hashtable();
				String mainKey = guidString+seperatorHash+nodeOrder+seperatorHash+requestType;
				Hashtable errList = new Hashtable();
				errList = (Hashtable) session.getAttribute(sessionExternalData);

				if(errList != null && errList.size() >0)
				{
					nodeIdTable = (Hashtable) errList.get(mainKey);
				}
				
				int ErrorCount = 0;
				StringBuffer sbf = new StringBuffer();
				if(nodeIdTable != null && nodeIdTable.size()>0)
				{
					if(nodeId.equals("-1"))
					{
						Enumeration e = nodeIdTable.keys();
						
						sbf.append("<table style='width:100%;' class='btmErrorData'>");
						while (e.hasMoreElements()) 
						{
							String key = (String) e.nextElement();
							ArrayList keyValue = (ArrayList) nodeIdTable.get(key);
							if(keyValue != null && keyValue.size()>0)
							{
								String type = (String) keyValue.get(1);
								if(!type.equals("EXCEPTION"))
									continue;
								String wholeExceptionData = (String)keyValue.get(8);
								if(wholeExceptionData.length()>0 /*&& wholeExceptionData.indexOf("?^?")>0*/)
								{
									ErrorCount++;
									expPresence = true;
									StringTokenizer stk = new StringTokenizer(wholeExceptionData, "?^?");

									ArrayList tmp = StringUtils.egTokenizer(wholeExceptionData,"?^?");
									boolean flag = true;
									sbf.append("<tr class='alternateColor'><td class='btmErrorDataBorderTopBottom'><table style='width:100%;border:0px solid red !important' >");
									if(tmp!=null && tmp.size() > 0)//while(stk.hasMoreTokens()) 
									{
										for(int j=0;j<tmp.size();j++)
										{
											String expSingleLine = (String)tmp.get(j);
											if(expSingleLine.indexOf("Caused by:")>-1)
												flag = true;
											if(flag)
											{
												flag = false;
												sbf.append("<tr><td class='font_bold11'>"+escapeHTML(expSingleLine)+"</td></tr><tr><td valign='top' style='padding-left:30px'>");
											}
											else
											{
												sbf.append("" +escapeHTML(expSingleLine)+"</br>");
											}
										}
									}
									sbf.append("</td></tr></table></td></tr>");
								} 
							}
						}
						sbf.append("</table>");
					}
					else
					{
						ArrayList singleNodeIdData = (ArrayList) nodeIdTable.get(nodeId);
						if(singleNodeIdData != null && singleNodeIdData.size()>0)
						{
							String wholeExceptionData = (String) singleNodeIdData.get(8);
							if(wholeExceptionData.length()>0 /*&& wholeExceptionData.indexOf("?^?")>0*/)
							{
								expPresence = true;
								StringTokenizer stk = new StringTokenizer(wholeExceptionData, "?^?");
								boolean flag = true;
								sbf.append("<table class='btmErrorDataPopup' style='width:100%'>");
								while(stk.hasMoreTokens())
								{
									String expSingleLine = stk.nextToken();
									if(expSingleLine.indexOf("Caused by:")>-1)
										flag = true;

									if(flag)
									{
										flag = false;
										sbf.append("<tr><td >"+escapeHTML(expSingleLine)+"</td></tr><tr><td valign='top' style='padding-left:30px'>");
									}
									else
									{
										sbf.append("" +escapeHTML(expSingleLine)+"</br>");
									}
								}
								sbf.append("</td></tr></table>");
							}
						}
					}
				}
				
				if(expPresence)
				{
					rootJson.put("errorPresence","yes");
					rootJson.put("errorData",sbf.toString());
					rootJson.put("errorDataCount",new Integer(ErrorCount));					
					out.println(rootJson.toString());
				}
				else
				{
					rootJson.put("errorPresence","no");
					rootJson.put("nickName",trgt_Host+":"+portNo);
					rootJson.put("url",url);
					rootJson.put("compName",compName);
					out.println(rootJson.toString());
				}
			}
			// ErrorDetails data preparation ends

			// SQL tab data preparation starts 
			else if(buttonClicked.equals("SQLCalls"))
			{
				double responseTime = 0.0000;
				String businessTrnsName = null;
				String reqUrl = null;
				String reqDateTime = null;
				String trnsPrcTime = null;
				String qryStr = null;
				String index = request.getParameter("index");
				if(index == null)
					index = "-1";
				String userName = (String)session.getAttribute("userName");
				if(userName!=null && userName.equalsIgnoreCase("User")){
					userName = "-" ; 
				}
				ArrayList summaryData = (ArrayList) session.getAttribute(sessionSummaryData);
				if(summaryDataList != null && summaryDataList.size()>0)
				{
					if(summaryDataDetails != null)
					{
						String key = guidString+seperatorHash+nodeOrder;
						if(summaryWholeData != null && summaryWholeData.size()>0)
						{
							try {
								responseTime = Double.parseDouble(summaryWholeData.get(11).toString());
								trnsPrcTime = String.valueOf(responseTime);								
								businessTrnsName = (String) summaryWholeData.get(4);
								if(businessTrnsName.startsWith("+")) {
									businessTrnsName = businessTrnsName.substring(businessTrnsName.indexOf("+")+1);
								}
								reqUrl = (String) summaryWholeData.get(9);
								String mgrFormatTime = DateUtil.changeDateFormat(summaryWholeData.get(7).toString(),"yyyy-MM-dd HH:mm:ss",currentDateFormat+" HH:mm:ss");
								String timeZone = (String) summaryWholeData.get(8);
								reqDateTime = mgrFormatTime+" "+timeZone;
								qryStr = (String) summaryWholeData.get(12);
							}
							catch (Exception ex)
							{
								System.err.println("Exception While parsing in preparing sql data "+ex.getMessage());
								//ex.printStackTrace();
							}
						}
					}
				}
				JSONArray gridData = new JSONArray();
				Hashtable nodeIdTable = new Hashtable();
				String mainKey = guidString+seperatorHash+nodeOrder+seperatorHash+requestType;
				Hashtable sqlList = new Hashtable();
				sqlList = (Hashtable) session.getAttribute(sessionExternalData);
				if(sqlList != null && sqlList.size()>0)
				{
					nodeIdTable = (Hashtable) sqlList.get(mainKey);
				}

				Hashtable dbdetailsQueryMap = new Hashtable();

				boolean isFastQueryPresent = false;
				int fastQryExecTime = 0;
				int fastQueryCount = 0;
				int totalNonFastQueries = 0;
				int max_length = apm.getMaxLength();
				if(nodeIdTable != null && nodeIdTable.size()>0)
				{
					if(index.equals("-1"))
					{
						Enumeration en = nodeIdTable.keys();
						long count = 0L;
						while (en.hasMoreElements()) 
						{
							String key = (String) en.nextElement();
							ArrayList keyValue = (ArrayList) nodeIdTable.get(key);
							if(keyValue != null && keyValue.size()>0)
							{
								String type = (String)keyValue.get(1);
								if(type.equals("SQL") || type.equals("MONGODB"))
								{
									String currentQueryType = keyValue.get(9).toString();
									if(!key.startsWith("FASTQUERY")){
											totalNonFastQueries +=	(currentQueryType.matches(".*\\d.*")) ? Integer.parseInt(currentQueryType): 1 ;
									}
									int query_execution_time = ((BigDecimal)keyValue.get(7)).intValue();
									String queryCountString = (String) keyValue.get(8);
									if(key.startsWith("FASTQUERY"))
									{
										isFastQueryPresent = true;
										int tempFastQryExecTime = query_execution_time;
										fastQryExecTime = tempFastQryExecTime +fastQryExecTime;
										fastQueryCount = fastQueryCount + Integer.parseInt(queryCountString);
										continue;
									}

									String ip = (String)keyValue.get(2);
									String port = (String)keyValue.get(3);
									String dbtype = (String)keyValue.get(4);
									String dbName = (String)keyValue.get(5);
									String sid = dbName;

									if(ip!=null){
										String lowerCaseIPString = ip.toLowerCase();
										if(lowerCaseIPString.startsWith("jdbc:")){
											// No change in the dbtype
										}
										else{
											if(lowerCaseIPString.indexOf(",") > 0){
												// It is cluster DB
												String allColumnString = apm.getValue("CLUSTER_DB",dbtype);
												ArrayList RACIpPortList = StringUtils.egTokenizer(ip,",");
												String resultString = getDBString(dbtype , RACIpPortList, dbName , allColumnString);
												int star_index = resultString.indexOf("*");
												if(star_index > 0){
													dbtype = resultString.substring(0, star_index);
													String ipPortString = resultString.substring(star_index+1);
													int colon_index = ipPortString.lastIndexOf(":");
													if(colon_index > 0){
														ip = ipPortString.substring(0,colon_index);
														port = ipPortString.substring(colon_index + 1);
													}
												}
											}
											else{
												String allColumnString = apm.getValue("DB_MAPPINGS",dbtype);
												dbtype = getDBString(dbtype , ip , port , dbName , allColumnString);
											}
										}
									}

									String dbDetails = null;
									if(ip.indexOf("\\") != -1){
										dbDetails = BTMHelper.decodeUrlString(getDBLabel(ip, "-",  mappingInfo.getComponentTypeDescription(dbtype),sid, false));
									}
									else{
										dbDetails = BTMHelper.decodeUrlString(getDBLabel(ip, port, mappingInfo.getComponentTypeDescription(dbtype),sid, false));
									}


									String queryType = keyValue.get(9).toString();

									ArrayList query = new ArrayList();
									query.add(queryType);
									query.add(query_execution_time);
									query.add(queryCountString);
									query.add(keyValue.get(10));
									query.add(ip);
									query.add(port);
									query.add(dbtype);
									query.add(sid);
									query.add(key);
									if(dbdetailsQueryMap.containsKey(dbDetails))
									{
										ArrayList dataToShow = (ArrayList) dbdetailsQueryMap.get(dbDetails);
										dataToShow.add(query);
										dbdetailsQueryMap.put(dbDetails,dataToShow);
									}
									else
									{
										ArrayList dataToShow = new ArrayList();
										dataToShow.add(query);
										dbdetailsQueryMap.put(dbDetails,dataToShow);
									}
									count++;
								}
							}
						}
						if(dbdetailsQueryMap != null && dbdetailsQueryMap.size()>0)
						{
							JSONArray singleGridData = new JSONArray();
							Enumeration e = dbdetailsQueryMap.keys();
							double totalExecutionTime = 0.0;
							HashMap databaseUrlMappingTable = new HashMap();

							EgExternalInfo externalInfo = new EgExternalInfo("manager");
							EgVirtualComponentInfo virCompInfo =new EgVirtualComponentInfo("manager");

							Vector virtualServerComp = externalInfo.getVirtualServers();
							Vector cloudServerComp = externalInfo.getCloudServers();
							Hashtable vmht_virtualCompMap = virCompInfo.getVirtualComponentsMap();
							Hashtable vmht_cloudCompMap = virCompInfo.getCloudComponentsMap();
							Vector user_comps = new Vector();
							user_comps.addAll(u_ser.getServers(false));
							//Vector componentDetails = discInfo.getAllManagedComponents();
							String antiPatternLabel = "false" ;
							boolean errPresent = false;
							int antiPatternCount = 0;
							while (e.hasMoreElements())
							{
								String key = (String) e.nextElement();
								ArrayList type = (ArrayList) dbdetailsQueryMap.get(key);
								EgSorter egSort = new EgSorter(type,4);
								type = (ArrayList)egSort.sort(2,"Integer","desc");
								Hashtable sqlQueryTable = new Hashtable();
								for(int i=0; i<type.size(); i++)
								{
									ArrayList singleRowData = (ArrayList) type.get(i);
									if(singleRowData != null && singleRowData.size()>0)
									{
										double result = 0.0;
										double thisExecutionTime = 0.0;
										try 
										{
											thisExecutionTime = Double.parseDouble(singleRowData.get(1).toString());
											totalExecutionTime += thisExecutionTime;
											result = (thisExecutionTime/responseTime)*100;
										}
										catch (Exception ex)
										{
											System.err.println("Exception While parsing String to Double for ExternalDetails data "+ex.getMessage());
											//ex.printStackTrace();
										}

										/*SQL Grouping Code Starts Here*/
										getSqlGroupingQueryDetails(sqlQueryTable, singleRowData, thisExecutionTime, result, responseTime);
									}
								}
								Iterator sqlQueryTableIterator = (Iterator)sqlQueryTable.keys();
								while(sqlQueryTableIterator.hasNext()) {
									String keyAsQuery = (String)sqlQueryTableIterator.next();
									if(keyAsQuery!=null && keyAsQuery.indexOf("~#~error")>-1)
										continue;
									ArrayList queryList=(ArrayList)sqlQueryTable.get(keyAsQuery);
									JSONObject dataObj = new JSONObject();
									double queryCount = ((Double)queryList.get(0)).doubleValue();
									String queryType = (String)queryList.get(3);
									String errorMsg = (String)queryList.get(4);
									String errorMsg_Win=errorMsg;
									ArrayList errorMsgForWindow = new ArrayList();
									if(errorMsg != null && !errorMsg.equals("-"))
										errorMsgForWindow = StringUtils.egTokenizer(errorMsg,".,",false,true,true);//param 3-->includeEmpty,4-->unique,5-->trim
									if(errorMsgForWindow!=null && errorMsgForWindow.size()>0)
									{
										StringBuffer err_buf = new StringBuffer();
										for(int b=0;b<errorMsgForWindow.size();b++)
										{
											String errVal=(String)errorMsgForWindow.get(b);
											if(errVal != null && errVal.trim().length()>0 && !errVal.equals("-"))
												err_buf.append("</br>"+(b+1)+"."+errVal+"</br></br>");
										}
										errorMsg_Win=err_buf.toString();
									}
									if( (errorMsg != null && !errorMsg.equals("-")) || (queryCount >= maxQueryValue && queryType.equalsIgnoreCase("SELECT"))){
										dataObj.put("Warning","<img style='display:block;float:left;' src='data:image/gif;base64,R0lGODlhAQABAID/AMDAwAAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==' class='x-tree-icon x-tree-icon-leaf iconExclamationSmall'>");
										if(errorMsg != null)
										{
											if(errorMsg.equals("-") && !errPresent)
												antiPatternLabel = "N+1" ;
											if(!errorMsg.equals("-")){
												antiPatternLabel = "error" ;
												errPresent = true;
												antiPatternCount++;
											}
										
										}
										 
									} else {
										dataObj.put("Warning","");
									}
									dataObj.put("Query_Type",queryList.get(3));
									dataObj.put("Query_Details",keyAsQuery);
									dataObj.put("Total_Execution_Time",df.format(queryList.get(1)));
									dataObj.put("Count",queryList.get(0));
									dataObj.put("Avg_Execution_Time",dft.format(queryList.get(2)));
									dataObj.put("Progress",dft.format(queryList.get(5)));
									dataObj.put("Error",errorMsg);
									dataObj.put("ErrorWin",errorMsg_Win);
									
									/*SQL Grouping Code Ends Here*/

									/*dataObj.put("Query_Type",singleRowData.get(0));
									dataObj.put("Query_Details",escapeHTML(singleRowData.get(2).toString()));
									dataObj.put("Execution_Time",thisExecutionTime);
									dataObj.put("Progress",Double.parseDouble(dft.format(result)));
									dataObj.put("Error",singleRowData.get(3));
									
									String ip     =(String)singleRowData.get(4);
									String port   =(String)singleRowData.get(5);
									String dbtype =(String)singleRowData.get(6);
									String sid    =(String)singleRowData.get(7);*/

									String ip     =(String)queryList.get(6);
									String port   =(String)queryList.get(7);
									String dbtype =(String)queryList.get(8);
									String sid    =(String)queryList.get(9);
									String keyString = dbtype+"#"+ip+"#"+port+"#"+sid;

									//dataObj.put("Database_Details_For_Csv",key);
									if(databaseUrlMappingTable.containsKey(keyString))
									{
										String value = (String)databaseUrlMappingTable.get(keyString);
										dataObj.put("Database_Details",value);
										String value1 = (String)databaseUrlMappingTable.get(keyString+"_name");
										dataObj.put("Database_Details_For_Csv",value1);
										singleGridData.add(dataObj);
										continue;
									}

									String managedNickName = getManagedComponentNickName(dbtype,ip,port,sid,discInfo);
									if(managedNickName == null){
										String dbTypeMapping = mappingInfo.getComponentTypeDescription(dbtype);
										keyString = dbTypeMapping+"#"+ip+"#"+port+"#"+sid;
										String value = "<span data-qtip='"+key+"'>"+key+"</span>";
										databaseUrlMappingTable.put(keyString,value);
										databaseUrlMappingTable.put(keyString+"_name",key);
										dataObj.put("Database_Details",value);
										dataObj.put("Database_Details_For_Csv",key);
										singleGridData.add(dataObj);
										continue;
									}

									if(managedNickName.indexOf(":") > 0){
										port = managedNickName.substring(managedNickName.indexOf(":")+1);
										managedNickName = managedNickName.substring(0,managedNickName.indexOf(":"));
									}

									String vmComponent = getVMComponents(dbtype, sid, port, user_comps, managedNickName, virtualServerComp, cloudServerComp, vmht_virtualCompMap , vmht_cloudCompMap);

									VMDesktopBean vm_DesktopBean=null;
									String vmcomp_type = ""; 
									String vmhost ="";
									if (vmComponent!=null)
									{
										List vm_managedcomp = u_ser.getServers(false);
										vmcomp_type = vmComponent.substring(0, vmComponent.indexOf(":"));
										vmhost = vmComponent.substring(vmComponent.indexOf(":")+1);

										String vmstart = vmcomp_type+":";
										String vmend = ":"+vmhost;
										for (int j=0;j<vm_managedcomp.size();j++)
										{
											String vmcomp=(String)vm_managedcomp.get(j);
											if (vmcomp.startsWith(vmstart) &&  vmcomp.endsWith(vmend))
											{
												vm_DesktopBean = new VMDesktopBean(request);
												break;
											}
										}
									}

									String linkUrl = null;
									if(vm_DesktopBean!=null && (vmhost!=null && !vmhost.equals(" ")))
									{
										String vm_port="";
										String vmhostState=vm_DesktopBean.getVmhostState(vmcomp_type+":"+vmhost);

										int vmindex = vmhost.indexOf(":");
										if(vmindex>0)
										{
											vm_port =vmhost.substring(vmindex+1);
											if(vm_port!=null && vm_port.indexOf(":")>-1 && dbtype.indexOf("Oracle_server")>-1)
											{
												vm_port=vm_port.substring(0,vmindex);
											}
											vmhost = vmhost.substring(0,vmindex);
										}
										linkUrl="EgVmwareCompGraphApp.jsp?Vmhost="+EgURLEncoder.encode(vmhost,"UTF-8")+"&vmcomp_type="+vmcomp_type+"&state="+vmhostState+"&port="+vm_port+"&fromPage=LayerModel";
									}
									else
									{
										vmhost=managedNickName+":"+port;
										if(dbtype.indexOf("Oracle_server")>-1 && sid!=null && sid.trim().length()>0)
										{
											vmhost=managedNickName+":"+port+":"+sid;
										}
										if(user_comps!=null && user_comps.contains(dbtype+":"+vmhost)){
											linkUrl = "/final/servlet/com.eg.EgDashboardController?from=list&site=NULL&qctr=0&host="+EgURLEncoder.encode(vmhost,"UTF-8")+"&comptype="+dbtype+"&comeFrom=topology&tab=LayerModel&toDashBoardLayer=true";
										}
									}

									if(linkUrl!=null && linkUrl.trim().length()>0)
									{
										String comp_name = managedNickName+":"+port;
										if(dbtype.indexOf("Oracle_server")>-1 && sid!=null && sid.trim().length()>0)
										{
											comp_name=managedNickName+":"+port+":"+sid;
										}
										AlarmPriorities ap = AlarmPriorities.getInstance();
										String thisState = ap.getAlarmPriority(Server.getServerName(dbtype+":"+comp_name), dbtype);
										String value = "<span style='text-decoration:underline;' data-qtip='"+comp_name+"'><img style='display:block;float:left;' src='data:image/gif;base64,R0lGODlhAQABAID/AMDAwAAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==' class='x-tree-icon x-tree-icon-leaf state_"+thisState+"'><a href='javascript:void(0);' onclick=UrlFrame(\'"+linkUrl+"\')>"+comp_name+"</a></span>";
										dataObj.put("Database_Details",value);
										dataObj.put("Database_Details_For_Csv",comp_name);
										databaseUrlMappingTable.put(keyString,value);
										databaseUrlMappingTable.put(keyString+"_name",comp_name);
									}
									else{
										String value = "<span data-qtip='"+key+"'>"+key+"</span>";
										databaseUrlMappingTable.put(keyString,value);
										databaseUrlMappingTable.put(keyString+"_name",key);
										dataObj.put("Database_Details",value);
										dataObj.put("Database_Details_For_Csv",key);
									}
									
									singleGridData.add(dataObj);
								}
							//}
								rootJson.put("AntiPatternLabel", antiPatternLabel);
								rootJson.put("AntiPatternCount", antiPatternCount);
								rootJson.put("TotalSqlCalls", totalNonFastQueries);
								rootJson.put("SQlPresence", "yes");
								rootJson.put("charCount", max_length);
							}
							if(isFastQueryPresent)
							{
								double fastAndSlowExecutionTime = 0.0;
								fastAndSlowExecutionTime = totalExecutionTime + fastQryExecTime;
								rootJson.put("totalExecutionTime",fastAndSlowExecutionTime);
								rootJson.put("gridData", singleGridData);
								rootJson.put("FastSQLCount", fastQueryCount);
								rootJson.put("sqlExecCutoffTime", sqlExecCutoffTime);
							}
							else
							{
								rootJson.put("totalExecutionTime",totalExecutionTime);
								 
								rootJson.put("gridData", singleGridData);
							}
						}
						else if(isFastQueryPresent) //if FastSQL, then dbdetailsQueryMap will be null
						{
							rootJson.put("SQlPresence", "fast");
							rootJson.put("sqlExecCutoffTime", sqlExecCutoffTime);
							rootJson.put("FastSQLCount", fastQueryCount);
							rootJson.put("totalExecutionTime",fastQryExecTime);
							//rootJson.put("FastSQLTime", fastQryExecTime);
						}
						else
						{
							rootJson.put("SQlPresence", "no");
							rootJson.put("nickName",trgt_Host+":"+portNo);
							rootJson.put("dbdetail","None");
							rootJson.put("url",url);
							rootJson.put("compName",compName);
						}
					}
					else
					{
						ArrayList singleNodeIdData = (ArrayList) nodeIdTable.get(index);
						if(singleNodeIdData != null && singleNodeIdData.size()>0)
						{
							String dbIp = (String) singleNodeIdData.get(2);
							String dbPort = (String) singleNodeIdData.get(3);
							String dbType = (String) singleNodeIdData.get(4);
							String dbName = (String) singleNodeIdData.get(5);
							String errorMsg = (String)singleNodeIdData.get(10);
							dbType = mappingInfo.getComponentTypeDescription(dbType);
							String dbDetails = getDBLabel(dbIp, dbPort, mappingInfo.getComponentTypeDescription(dbType),dbName , true);
							dbDetails = BTMHelper.decodeUrlString(dbDetails);
							JSONObject tmpObj = new JSONObject();
							double result = ((Double.parseDouble(singleNodeIdData.get(7).toString()))/responseTime)*100;
							String queryType = (String) singleNodeIdData.get(9);
							tmpObj.put("Query_Type",queryType);
							tmpObj.put("Query_Details",escapeHTML(singleNodeIdData.get(8).toString()));
							tmpObj.put("Execution_Time",(Double.parseDouble(singleNodeIdData.get(7).toString())));
							tmpObj.put("Progress",dft.format(result));
							tmpObj.put("Error",errorMsg);

							gridData.add(tmpObj);

							rootJson.put("dbdetail", dbDetails);
							rootJson.put("gridData", gridData);
							rootJson.put("SQlPresence", "yes");
							rootJson.put("charCount", max_length);
						}
						else
						{
							rootJson.put("SQlPresence", "no");
							rootJson.put("nickName",trgt_Host+":"+portNo);
							rootJson.put("url",url);
							rootJson.put("compName",compName);
						}
					}
				}
				else
				{
					rootJson.put("nickName",trgt_Host+":"+portNo);
					rootJson.put("url",url);
					rootJson.put("dbdetail","None");
					rootJson.put("compName",compName);
					rootJson.put("SQlPresence", "no");
				}
				out.println(rootJson.toString());
				/* Generating Csv for Slow Sql queries start here */
				String jsonString = rootJson.toString();
				//EgAgentInfo agentInfo = new EgAgentInfo("manager");
				//String agentInfoKey = testName+"::"+trgt_Host+":"+portNo;
				//String agentInfoValue = agentInfo.getValueForVar(agentInfoKey);
				//String sqlExecCutoffTime = getSqlExecCutoffTime(agentInfoValue);
				//if (sqlExecCutoffTime == null) {
					//sqlExecCutoffTime = DEFAULT_SQL_EXEC_CUTOFF_TIME;
				//}
				JSONObject csvJson = JSONObject.fromObject(jsonString);
				String isSQlPresence = (csvJson.has("SQlPresence")) ? csvJson.getString("SQlPresence") : "no";
				String componentName = trgt_Host+":"+portNo+" ("+compName+")";
				if (isSQlPresence.equalsIgnoreCase("yes")) { // Slow SQL Calls
					String  noteStr = "Note: Queries that are executed within "+sqlExecCutoffTime+" ms are not shown here";
					int slowSqlCount = (csvJson.has("TotalSqlCalls")) ? Integer.parseInt(csvJson.getString("TotalSqlCalls")) : 0;
					int fastSqlCount = (csvJson.has("FastSQLCount")) ? Integer.parseInt(csvJson.getString("FastSQLCount")) : 0;
					String totalSqlCalls = String.valueOf(slowSqlCount+fastSqlCount);
//					System.out.println("from 1809 slowSqlCount = "+ slowSqlCount);
//					System.out.println("from 1809 fastSqlCount = "+ fastSqlCount);
//					System.out.println("from 1809 totalSqlCalls = "+ totalSqlCalls);
					String slowQueriesHeaderStr = "Slow SQL Queries("+slowSqlCount+" out of "+totalSqlCalls+" queries are slow):";
					String totalExecutionTime = (csvJson.has("totalExecutionTime")) ? csvJson.getString("totalExecutionTime") : "";
					Hashtable gridSlowData = createSlowSqlQueriesCsvData(jsonString,slowQueriesHeaderStr);
					String errorQry = String.valueOf(gridSlowData.get("errorQryCount"));
					gridSlowData.remove("errorQryCount");
					Hashtable summaryCsvDat = createSummaryDataForCSV(businessTrnsName,reqUrl,qryStr,reqDateTime,trnsPrcTime,totalSqlCalls,totalExecutionTime,errorQry,guidString,componentName,userName);
					List lst = new LinkedList();
					lst.add(summaryCsvDat);
					lst.add(noteStr);
					lst.add("");
					lst.add(gridSlowData);
					session.setAttribute("list",lst);
				} else if (isSQlPresence.equalsIgnoreCase("fast")) { // Fast SQL Calls
					String noteStr = "All queries are executed within the sql execution cutoff time "+sqlExecCutoffTime+" ms";
					String totalSqlCalls = (csvJson.has("FastSQLCount")) ? csvJson.getString("FastSQLCount") : "";
					String totalExecutionTime = (csvJson.has("totalExecutionTime")) ? csvJson.getString("totalExecutionTime") : "";
					String errorQry = "-";
					Hashtable summaryCsvDat = createSummaryDataForCSV(businessTrnsName,reqUrl,qryStr,reqDateTime,trnsPrcTime,totalSqlCalls,totalExecutionTime,errorQry,guidString,componentName,userName);
					List lst = new LinkedList();
					lst.add(summaryCsvDat);
					lst.add("");
					lst.add(noteStr);
					session.setAttribute("list",lst);
				}
				/* Generating Csv for Slow Sql queries end here */
			}
			// SQL tab data preparation ends here

			// DrillDown popup for HTTP/WS/JMS from Call Graph page starts
			else if(buttonClicked.equals(popupDetailsClickStr))
			{
				boolean isOtherPointCut = false;
				String drillDownPresent = "No";
				String nextData = null;
				String nodeId = request.getParameter("index");
				String type = request.getParameter("type");
				//String nodeCount = request.getParameter("nodeCount");
				//String nextNode = nodeOrder+"."+nodeCount;
				String connectedNodeOrder = null;
				Hashtable externalData = (Hashtable) session.getAttribute(sessionExternalData);
				Hashtable secondTable = (Hashtable)  summaryDataList.get(1);
				JSONObject jsonForJMSTopic = null;
				//ArrayList webOrderList = new ArrayList();
				//ArrayList threadOrderList = new ArrayList();

				//if(requestDataList!=null && requestDataList.size() == 6)
				//{
					//ArrayList orderList = BTMHelper.getOrderedList(requestDataList);
					//webOrderList = (ArrayList)orderList.get(0);
					//threadOrderList = (ArrayList)orderList.get(1);
				//}
				/*if(webOrderList != null && webOrderList.size()>0)
				{
					int webOrderListSize = webOrderList.size();
					int currentPosition = webOrderList.indexOf(nodeOrder);

					if(webOrderListSize > currentPosition+1)
						nextData = (String) webOrderList.get(currentPosition+1);

					if(nextData != null && nextData.length()>0)
					{
						//drillDownPresent = "Yes";
						Hashtable firstTable = (Hashtable) requestDataList.get(0);
						ArrayList nextNodeDetails = (ArrayList) firstTable.get(guidString+seperatorHash+nextData);
						state = (String) nextNodeDetails.get(2);
						if(state.equals("Slow_percentage"))
							state = "BTM_transaction_state_Slow";
						else if(state.equals("Error_percentage"))
							state = "BTM_transaction_state_Error";
						else if(state.equals("Healthy_percentage"))
							state = "BTM_transaction_state_Normal";
						else if(state.equals("Stalled_percentage"))
							state = "BTM_transaction_state_Stalled";
					}
					else
					{
						drillDownPresent = "No";
					}
				}*/
				Hashtable nodeIdTable = new Hashtable();
				String mainKey = guidString+seperatorHash+nodeOrder+seperatorHash+requestType;
				Hashtable dataList = new Hashtable();
				dataList = (Hashtable) session.getAttribute("Http_Jms_Web"+"$"+mainKey);
				if(dataList != null && dataList.size() == 2)
				{
					nodeIdTable = (Hashtable) dataList.get(mainKey);
				}
				else
				{
					//String query = "select REQUEST_DATE, EG_GUID, REQUEST_TYPE, NODE_ORDER, DETAILS from EXTERNAL_SERVICE_DETAILS where EG_GUID = '"+guidString+"'  ORDER BY NODE_ORDER asc";

					//dataList = btmHelperObj.getExternalDetails(query);
					ArrayList nodeOrdersList = (ArrayList) summaryDataList.get(2);
					ArrayList webOrderList = (ArrayList) nodeOrdersList.get(0);

					dataList =  (Hashtable) session.getAttribute(sessionExternalData);
					session.setAttribute("Http_Jms_Web"+"$"+mainKey, dataList);
					nodeIdTable = (Hashtable) dataList.get(mainKey);
				}
				ArrayList singleNodeIdData = new ArrayList();
				if(nodeIdTable != null && nodeIdTable.size()>0)
				{
					singleNodeIdData = (ArrayList) nodeIdTable.get(nodeId);
				}

				String result = "";
				if(singleNodeIdData != null && singleNodeIdData.size()>0)
				{
					isOtherPointCut = apm.isPointCutInIni(testName,type);

					if(type.equals("http") || type.equals("webservice") || type.equals("jms"))
					{
						if(type.equals("http") || type.equals("webservice"))
						{
							connectedNodeOrder = (String) singleNodeIdData.get(9);
							if(secondTable.containsKey(guidString+"#"+connectedNodeOrder))
							{
								ArrayList connectedNodeDetails = (ArrayList) secondTable.get(guidString+"#"+connectedNodeOrder);
								String nickName = (String) connectedNodeDetails.get(0);
								String port = (String) connectedNodeDetails.get(1);

								List userCompDetails = (List) u_ser.getServers(true);
								if(userCompDetails.contains(nickName+":"+port))
									drillDownPresent = "Yes";
							}

							if(type.equals("http"))
							{
								
								/*EgSpecsInfo specsInfo = new EgSpecsInfo("manager");
								EgDiscInfo discoverInfo = new EgDiscInfo("manager");
								ArrayList businessTransServerList = new ArrayList();
								ArrayList allDetails = new ArrayList();
								String[] allServerTypes = discoverInfo.getServerTypes();

								for(int k=0;k<allServerTypes.length;k++)
								{
									String singleServerType = allServerTypes[k];
									//if(specsInfo.isTestRelevantForServer(singleServerType, businessTransTest))
									if(specsInfo.isTestRelevantForServer(singleServerType, testName))
									{
										businessTransServerList.add(singleServerType);
									}
								}
								for(int j=0;j<businessTransServerList.size();j++)
								{
									String btmServerType = (String) businessTransServerList.get(j);
									ArrayList btmServerList = discoverInfo.getAllEntries(btmServerType);
									for(int i=0;i<btmServerList.size();i++)
									{
										String line = (String) btmServerList.get(i);
										if(line.startsWith("#Unmanage|"))
											continue;
										String rhsPart = line.substring(line.indexOf(seperatorEquals)+1);
										StringTokenizer st = new StringTokenizer(rhsPart , ",");
										int count = st.countTokens();

										String compType = st.nextToken();
										String hostIp = st.nextToken();
										String nickName = st.nextToken();
										String portNo = st.nextToken();
										
										List userCompDetails = (List) u_ser.getServers(true);
										if(singleNodeIdData.get(2).equals(hostIp) && singleNodeIdData.get(3).equals(portNo))
										{
											if(nextData != null && nextData.length()>0)
											{
												if(userCompDetails.contains(nickName+":"+portNo))
													drillDownPresent = "Yes";
											}
											break;
										}
									}
								}*/
								String ipandPort = (String) singleNodeIdData.get(4);
								if(ipandPort.lastIndexOf(":NULL")>-1)
									ipandPort = ipandPort.substring(0,ipandPort.lastIndexOf(":NULL"));

								String extInfoUrl =  ipandPort+""+singleNodeIdData.get(6);
								String extUrl = (String)singleNodeIdData.get(6);
								if(extUrl.equals("-"))
									extInfoUrl = ipandPort;

								if(extInfoUrl.indexOf("UNKNOWN_NODE_") > -1)
									result = "";
								else
									result = extInfoUrl + "*&*" + singleNodeIdData.get(5) + "*$*" + df.format(singleNodeIdData.get(7)) + " ms" + "*#*" + singleNodeIdData.get(10);
							}
							else if(type.equals("webservice"))
							{
								result = singleNodeIdData.get(4)+""+singleNodeIdData.get(6) + "*&*" + singleNodeIdData.get(5) + "*$*" + singleNodeIdData.get(10);//singleNodeIdData.get(4);
							}
						}else if(type.equals("jms"))
						{
							String queueName = (String)singleNodeIdData.get(5) ;
							connectedNodeOrder = (String) singleNodeIdData.get(9);
							Hashtable jmsNodeData = (Hashtable) session.getAttribute("jmsHelper");
							result = singleNodeIdData.get(4) + "*&*" + queueName + "*$*" + singleNodeIdData.get(8);
							// Fix - JMS (Entry) Div not showing drill down link 
							if(secondTable.containsKey(guidString+"#"+connectedNodeOrder) || jmsNodeData.containsKey(connectedNodeOrder))
							{
								//if(jmsNodeData.containsKey(connectedNodeOrder))
								{
									ArrayList al = (ArrayList)jmsNodeData.get(connectedNodeOrder);
									if(al!=null ){
										int size = al.size();
										connectedNodeOrder =(String) al.get(0);
										ArrayList connectedNodeDetails = (ArrayList) secondTable.get(guidString+"#"+connectedNodeOrder);
										String nickName = (String) connectedNodeDetails.get(0);
										String port = (String) connectedNodeDetails.get(1);
										List userCompDetails = (List) u_ser.getServers(true);
										if(userCompDetails.contains(nickName+":"+port)){
											drillDownPresent = "Yes";
										}

										if(size > 1){
											JSONArray jsonForJmsArr = new JSONArray();
											Hashtable infoTable = (Hashtable) summaryDataList.get(0);
											int jmsDivRowCount = 0;
											for(int h=0 ; h<size; h++)
											{
												String newConnectedNodeOrder =(String) al.get(h);
												ArrayList detailList = (ArrayList)infoTable.get(guidString+"#"+newConnectedNodeOrder);
												if(detailList == null)
													continue;

												// Drill down from JMSDiv Fix
												String qorTopic = (String)detailList.get(4); //+Async_Listener_topic://paymentTopic
												if(qorTopic!=null && qorTopic.length() > 0){
													// Match the value against queueName
													if(!qorTopic.endsWith(queueName)){
														continue;
													}
												}

												String target_host = (String)detailList.get(0);
												String port_no = (String)detailList.get(1);
												String userExperience = (String)detailList.get(2);

												String callType = (String)detailList.get(6);
												String startTime = detailList.get(7).toString();
												String time_zone = detailList.get(8).toString();
												String exe_time = detailList.get(11).toString();

												callType = callType.equalsIgnoreCase("web") ? "Synchronous" : "Asynchronous" ;
												userExperience = userExperience.substring(0,userExperience.lastIndexOf("_"));
												exe_time  = dft.format(Double.parseDouble(exe_time));

												JSONObject jmsRootJson = new JSONObject();
												jmsRootJson.put("userExperience",userExperience.toLowerCase());
												jmsRootJson.put("callType",callType);
												jmsRootJson.put("target",target_host+":"+port_no);
												jmsRootJson.put("startTime",DateUtil.changeDateFormat(startTime,"yyyy-MM-dd HH:mm:ss",currentDateFormat+" HH:mm:ss") +" "+time_zone); 
												jmsRootJson.put("executionTime",exe_time);
												newConnectedNodeOrder = StringUtils.encodeSecurityChar(newConnectedNodeOrder); 
												newConnectedNodeOrder = BTMHelper.getEncodedURI(newConnectedNodeOrder);
											
												jmsRootJson.put("connectedNodeOrder",newConnectedNodeOrder);
												jsonForJmsArr.add(jmsRootJson);
												jmsDivRowCount++;
											}

											if(jmsDivRowCount > 1){
												jsonForJMSTopic = new JSONObject();
												jsonForJMSTopic.put("jmsData",jsonForJmsArr);
											}
										}
									}
								}
							}
						}
					}
					else if(type.equals("redis"))
					{
						String command = (String)singleNodeIdData.get(6);
						String extHost = (String)singleNodeIdData.get(2);
						String extPort = (String)singleNodeIdData.get(3);
						String dbUrl = extHost + ":" + extPort;
						ArrayList valueTokens = StringUtils.egTokenizer(command,"[C]");
						JSONArray jsonForRedis = new JSONArray();
						if(valueTokens.size() > 2)
						{
							drillDownPresent = "Yes";
							for(int k = 0 ; k < valueTokens.size() ; k += 2)
							{
								JSONObject tmpJsonObj = new JSONObject();
								String  tmpdbName= (String)valueTokens.get(k);
								String tmpCommand = (String)valueTokens.get(k+1);
								tmpJsonObj.put("dataOne",tmpdbName);
								tmpJsonObj.put("dataTwo",tmpCommand);
								jsonForRedis.add(tmpJsonObj);
							}
							JSONObject redisJsonObj = new JSONObject();
							redisJsonObj.put("redisData",jsonForRedis);
							result = redisJsonObj.toString() + "*&*" + dbUrl + "*$*" + "-" +"*^*" +singleNodeIdData.get(7)+ " ms";
						}else
						{
							command = (String)valueTokens.get(1);
							String dbName = (String)valueTokens.get(0);
							result = command + "*&*" + dbUrl + "*$*" + dbName +"*^*" +singleNodeIdData.get(7)+ " ms";
						}	
					}
					else if(type.equals("sap jco"))
					{
						String idwithNo = (String)singleNodeIdData.get(3);
						String no = idwithNo.substring(0,idwithNo.indexOf(seperatorHash));
						String id = idwithNo.substring(idwithNo.indexOf(seperatorHash)+1);
						result = singleNodeIdData.get(6) + "*&*" + singleNodeIdData.get(2) + "*&*" + id+ "*&*" + no + "*&*" + singleNodeIdData.get(4)+"*&*" + singleNodeIdData.get(5);
					}
					else if(isOtherPointCut || type.equals("ejb")) //For RMI|JavaMail.
					{
						result = singleNodeIdData.get(6) + "*&*" + singleNodeIdData.get(8);
						if (type.equalsIgnoreCase("email") || type.equalsIgnoreCase("ldap") || type.equalsIgnoreCase("runtime")) {
							result = singleNodeIdData.get(6) + "*&*" + singleNodeIdData.get(7) + " ms";
						}
					}
				}

				connectedNodeOrder = StringUtils.encodeSecurityChar(connectedNodeOrder); 
				connectedNodeOrder = BTMHelper.getEncodedURI(connectedNodeOrder);
				if(jsonForJMSTopic == null ){
					out.println(result+"#$#"+drillDownPresent.trim()+"&^&"+connectedNodeOrder);
				}
				else{
					out.println(result+"#$#"+drillDownPresent.trim()+"&^&"+connectedNodeOrder+"***"+jsonForJMSTopic.toString());
				}
			}
			// DrillDown popup for HTTP/WS/JMS from Call Graph page ends

			// External Details tab data preparation starts
			else if(buttonClicked.equals(externalDetailsTabStr))
			{
				boolean isOtherPointCut = false;
				Hashtable dataList = new Hashtable();
				Hashtable result = new Hashtable();
				ArrayList temp = new ArrayList();
				ArrayList wholeArrayListData = new ArrayList();
				
				String tmpStr = null;
				double totalResTime= 0.00;
				Hashtable externalData = (Hashtable) session.getAttribute(sessionExternalData);
				ArrayList summaryData = (ArrayList) session.getAttribute(sessionSummaryData);
				if(summaryData != null && summaryData.size()>0)
				{
					/*if(isAsyncThread != null && isAsyncThread.equals(asyncThreadStr))
					{
						summaryDataDetails = (Hashtable) summaryData.get(2);
					}*/
					if(summaryDataDetails != null)
					{
						if(summaryWholeData != null && summaryWholeData.size()>0)
						{
							try 
							{
								totalResTime = (Double.parseDouble(summaryWholeData.get(11).toString()));
							}
							catch (Exception ex)
							{
								System.err.println("Exception While parsing String to Double for ExternalDetails data "+ex.getMessage());
								//ex.printStackTrace();
							}
						}
					}
				}
				String mainKey = guidString+seperatorHash+nodeOrder+seperatorHash+requestType;
				JSONArray jsonArr = new JSONArray();
				boolean allow = false;
				ArrayList sortingArray = new ArrayList();
				if(externalData != null && externalData.size()>0)
				{
					dataList = (Hashtable) externalData.get(mainKey);
					if(dataList != null && dataList.size() > 0)
					{
						Set keySet = dataList.keySet();
						Iterator it = keySet.iterator();
						int actualLdapCount = 0;
						while(it.hasNext())
						{
							ArrayList PCDetailsList = (ArrayList) dataList.get(it.next());
							if (PCDetailsList != null){
								String tempCallType = (String)PCDetailsList.get(1);
								if (tempCallType != null && tempCallType.equalsIgnoreCase("LDAP")){
									actualLdapCount++;
								}
							}
							sortingArray.add(PCDetailsList);
						}
						int tempLdapCount = 0;
						if(sortingArray != null && sortingArray.size()>0)
						{
							EgSorter egSort = new EgSorter(sortingArray,12);
							sortingArray = (ArrayList)egSort.sort(8,"Double","desc");
							Hashtable ldapDataTable = new Hashtable();
							int ldapMethodCount = 1;
							int unknownHttpCount = 0;
							ArrayList ldapDetails = null;
							int sortingArraySize = sortingArray.size();
							Hashtable redisMappingTable = new Hashtable();
							for(int i=0;i<sortingArraySize;i++)
							{
								JSONArray gridData = new JSONArray();
								JSONObject tmpObj = new JSONObject();
								temp = (ArrayList) sortingArray.get(i);
								String callType = (String) temp.get(1);
								String childPointcut = apm.changeChildPointcutTime(callType);
								if (childPointcut != null && childPointcut.length() > 0)
									callType = childPointcut;

								isOtherPointCut = apm.isPointCutInIni(testName,callType);
								if(callType.equals("HTTP") || callType.equals("WEBSERVICE") || callType.equals("JMS") || callType.equals("SAP JCO") || isOtherPointCut || callType.equals("EJB") || callType.equals("REDIS") || callType.equals("EHCACHE"))
								{
									allow = true;
									if(callType.equals("HTTP"))
									{
										tmpObj.put("Type",mappingInfo.getTextDescription("monitor.apmtopology."+temp.get(1)));
										tmpObj.put("Status_code",temp.get(10));
										String ipandPort = (String) temp.get(4);
										if(ipandPort.lastIndexOf(":NULL")>-1)
											ipandPort = ipandPort.substring(0,ipandPort.lastIndexOf(":NULL"));

										String extUrl = (String) temp.get(6);
										if(extUrl.equals("-"))
										{
											if(ipandPort.indexOf("UNKNOWN_NODE_")>-1)
											{
												//tmpObj.put("Details","-");
												unknownHttpCount++;
												continue;
											}
											else 
											{
												tmpObj.put("Details",ipandPort);
											}
										}
										else
										{
											tmpObj.put("Details",ipandPort+""+temp.get(6));
										}

										tmpObj.put("Time <br> (MS)",temp.get(7));
										double percent = 0.0;
										try {
											percent = Double.parseDouble (dft.format((Double.parseDouble(temp.get(7).toString())/totalResTime)*100));
										}
										catch (Exception ex)
										{
											System.err.println("Exception While parsing String to Double for Http call type "+ex.getMessage());
											//ex.printStackTrace();
										}
										tmpObj.put("% Time", "<div class='btmGraphBg' ><div class='btmGraph' align='center' height='14' style='position:absolute;top:0px;left:0px;text-align:center;width:"+percent+"%;height:14px;margin-left:0px;border:0px solid red;' ></div> <span style='position:absolute;top:0px;left:0px;text-align:center;margin:0 auto 0 0px;width:63px !important;' class='btmGraphValue' >"+percent+"&nbsp;%</span> </div>");

										tmpObj.put("Method",temp.get(5));
										tmpObj.put("PercentValue",percent);
									}else if(callType.equals("REDIS"))
									{
										BigDecimal responseString1 = (BigDecimal) temp.get(7);
										int respTime = responseString1.intValue();
										String command = null;
										String extHost = (String)temp.get(2);
										String extPort = (String)temp.get(3);
										String dbName =  null ; 
										String dbServerType = (String)temp.get(4);
										String dbUrl = extHost + ":" + extPort;
										String dataString = (String)temp.get(6);
										ArrayList valueTokens = StringUtils.egTokenizer(dataString,"[C]");
										int counter = 0 ; 
										if(valueTokens.size() > 2)
										{
											String finalStr = "" ; 
											for(int k = 0 ; k < valueTokens.size() ; k += 2)
											{
												String tmpdbName = (String)valueTokens.get(k);
												String tmpCommand = (String)valueTokens.get(k+1);
												ArrayList tmpTokens = StringUtils.egTokenizer(tmpCommand,",");
												counter= counter + tmpTokens.size();
												if(dbName!=null)
													dbName = dbName+","+tmpdbName;
												else
													dbName = tmpdbName;

												finalStr += "<span class='font_bold11'> DatabaseID : </span>"+tmpdbName+"<br>"+tmpCommand+"<br>";
											}
											
											tmpObj.put("Type","Redis");
											tmpObj.put("DB Name",dbName);
											tmpObj.put("Redis Command",finalStr);
											tmpObj.put("Redis Count",counter);
											tmpObj.put("Total <br> Execution <br> Time (MS)",responseString1);
											double avgTime = Double.parseDouble(responseString1.toString())/counter;
											tmpObj.put("Avg <br> Execution <br> Time (MS)",dft.format(avgTime));
											double percent = 0.0;
											try {
												percent = Double.parseDouble (dft.format((Double.parseDouble(responseString1.toString())/totalResTime)*100));
											}
											catch (Exception ex)
											{
												System.err.println("Exception While parsing String to Double for Http call type "+ex.getMessage());
												//ex.printStackTrace();
											}
											tmpObj.put("% Time", "<div class='btmGraphBg' ><div class='btmGraph' align='center' height='14' style='position:absolute;top:0px;left:0px;text-align:center;width:"+percent+"%;height:14px;margin-left:0px;border:0px solid red;' ></div> <span style='position:absolute;top:0px;left:0px;text-align:center;margin:0 auto 0 0px;width:63px !important;' class='btmGraphValue' >"+percent+"&nbsp;%</span> </div>");
											tmpObj.put("End Point",dbUrl);
											gridData.add(tmpObj);
											jsonArr.add(gridData);
											continue;
										}else
										{
											command = (String)valueTokens.get(1);
											ArrayList tmpTokens = StringUtils.egTokenizer(command,",");
											dbName = (String)valueTokens.get(0);
											counter = tmpTokens.size() ;
										}
										dbUrl = extHost + ":" + extPort + "/" +dbName;
										if(redisMappingTable.containsKey(dbUrl))
										{
											Hashtable innerTable = (Hashtable)redisMappingTable.get(dbUrl);
											if(innerTable.containsKey(command))
											{
												ArrayList redisList = (ArrayList)innerTable.get(command);
												int count =(Integer) redisList.get(0);
												int responseString = (Integer) redisList.get(1);
												count = count+counter;
												responseString = respTime+responseString;
												redisList.set(0,count);
												redisList.set(1,responseString);
											}else
											{
													ArrayList redisList = new ArrayList();
													redisList.add(counter);
													redisList.add(respTime);
													redisList.add(dbServerType);
													innerTable.put(command,redisList);
											}
										}else
										{
											Hashtable innerTable = new Hashtable();
											ArrayList redisList = new ArrayList();
											redisList.add(counter);
											redisList.add(respTime);
											redisList.add(dbServerType);
											innerTable.put(command,redisList);
											redisMappingTable.put(dbUrl,innerTable);
										}
										continue;
									}
									else if(callType.equals("WEBSERVICE"))
									{
										tmpObj.put("Type",mappingInfo.getTextDescription("monitor.apmtopology."+temp.get(1)));
										tmpObj.put("Status_code",temp.get(10));
										tmpObj.put("Details",temp.get(4)+""+temp.get(6));
										tmpObj.put("Time <br> (MS)",temp.get(7));
										double percent = 0.0;
										try {
											percent = Double.parseDouble (dft.format((Double.parseDouble(temp.get(7).toString())/totalResTime)*100));
										}
										catch (Exception ex)
										{
											System.err.println("Exception While parsing String to Double for Webservice call type "+ex.getMessage());
											//ex.printStackTrace();
										}
										tmpObj.put("% Time", "<div class='btmGraphBg' ><div class='btmGraph' align='center' height='14' style='position:absolute;top:0px;left:0px;text-align:center;width:"+percent+"%;height:14px;margin-left:0px;border:0px solid red;' ></div> <span style='position:absolute;top:0px;left:0px;text-align:center;margin:0 auto 0 0px;width:63px !important;' class='btmGraphValue' >"+percent+"&nbsp;%</span> </div>");
										tmpObj.put("Operation",temp.get(5));
										tmpObj.put("PercentValue",percent);
									}
									else if(callType.equals("JMS"))
									{
										String details = (String)temp.get(5);
										if(details!=null && details.equals("-")){
											continue;
										}
										tmpObj.put("Type",mappingInfo.getTextDescription("monitor.apmtopology."+temp.get(1)));
										tmpObj.put("Details",details);
										tmpObj.put("Time <br> (MS)",temp.get(7));
										double percent = 0.0;
										try {
											percent = Double.parseDouble (dft.format((Double.parseDouble(temp.get(7).toString())/totalResTime)*100));
										}
										catch (Exception ex)
										{
											System.err.println("Exception While parsing String to Double for JMS call type "+ex.getMessage());
											//ex.printStackTrace();
										}
										tmpObj.put("% Time", "<div class='btmGraphBg' ><div class='btmGraph' align='center' height='14' style='position:absolute;top:0px;left:0px;text-align:center;width:"+percent+"%;height:14px;margin-left:0px;border:0px solid red;' ></div> <span style='position:absolute;top:0px;left:0px;text-align:center;margin:0 auto 0 0px;width:63px !important;' class='btmGraphValue' >"+percent+"&nbsp;%</span> </div>");
										tmpObj.put("PercentValue",percent);
									}
									else if(callType.equals("SAP JCO"))
									{
										tmpObj.put("Type",mappingInfo.getTextDescription("monitor.apmtopology."+temp.get(1)));
										tmpObj.put("AS Host",temp.get(2));
										String noWithId = (String) temp.get(3);
										String no = noWithId.substring(0,noWithId.indexOf(seperatorHash));
										String id = noWithId.substring(noWithId.indexOf(seperatorHash)+1);
										tmpObj.put("System No",no);
										tmpObj.put("System Id",id);
										tmpObj.put("Client",temp.get(5));
										tmpObj.put("User",temp.get(4));
										tmpObj.put("Function",temp.get(6));
										tmpObj.put("Time <br> (MS)",temp.get(7));
									}
									else if(callType.equalsIgnoreCase("EJB"))
									{
										tmpObj.put("Type",mappingInfo.getTextDescription("monitor.apmtopology."+temp.get(1)));
										tmpObj.put("Details",temp.get(6));
										tmpObj.put("Target",temp.get(8));
										tmpObj.put("Time <br> (MS)",temp.get(7));
										double percent = 0.0;
										try {
											percent = Double.parseDouble (dft.format((Double.parseDouble(temp.get(7).toString())/totalResTime)*100));
										}
										catch (Exception ex)
										{
											System.err.println("Exception While parsing String to Double for RMI call type "+ex.getMessage());
											//ex.printStackTrace();
										}
										tmpObj.put("% Time", "<div class='btmGraphBg' ><div class='btmGraph' align='center' height='14' style='position:absolute;top:0px;left:0px;text-align:center;width:"+percent+"%;height:14px;margin-left:0px;border:0px solid red;' ></div> <span style='position:absolute;top:0px;left:0px;text-align:center;margin:0 auto 0 0px;width:63px !important;' class='btmGraphValue' >"+percent+"&nbsp;%</span> </div>");
										tmpObj.put("PercentValue",percent);
									}
									else if(callType.equalsIgnoreCase("RMI") || callType.equalsIgnoreCase("RUNTIME"))
									{
										tmpObj.put("Type",mappingInfo.getTextDescription("monitor.apmtopology."+temp.get(1)));
										tmpObj.put("Details",temp.get(6));
										tmpObj.put("Time <br> (MS)",temp.get(7));
										double percent = 0.0;
										try {
											percent = Double.parseDouble (dft.format((Double.parseDouble(temp.get(7).toString())/totalResTime)*100));
										}
										catch (Exception ex)
										{
											System.err.println("Exception While parsing String to Double for RMI call type "+ex.getMessage());
											//ex.printStackTrace();
										}
										tmpObj.put("% Time", "<div class='btmGraphBg' ><div class='btmGraph' align='center' height='14' style='position:absolute;top:0px;left:0px;text-align:center;width:"+percent+"%;height:14px;margin-left:0px;border:0px solid red;' ></div> <span style='position:absolute;top:0px;left:0px;text-align:center;margin:0 auto 0 0px;width:63px !important;' class='btmGraphValue' >"+percent+"&nbsp;%</span> </div>");
										tmpObj.put("PercentValue",percent);
									}
									else if (callType.equalsIgnoreCase("EMAIL")){
										tmpObj.put("Type",mappingInfo.getTextDescription("monitor.apmtopology."+callType));
										String mailMethodName = (String)temp.get(6);
										tmpObj.put("Details",mailMethodName);
										String mailEndPoint = "-";
										if(temp.size() >7 ){
											mailEndPoint = (String)temp.get(8);
										}
										tmpObj.put("End Point",mailEndPoint);

										tmpObj.put("Time <br> (MS)",temp.get(7));
										double percent = 0.0;
										try {
											percent = Double.parseDouble (dft.format((Double.parseDouble(temp.get(7).toString())/totalResTime)*100));
										}
										catch (Exception ex)
										{
											System.err.println("Exception While parsing String to Double for RMI call type "+ex.getMessage());
											//ex.printStackTrace();
										}
										tmpObj.put("% Time", "<div class='btmGraphBg' ><div class='btmGraph' align='center' height='14' style='position:absolute;top:0px;left:0px;text-align:center;width:"+percent+"%;height:14px;margin-left:0px;border:0px solid red;' ></div> <span style='position:absolute;top:0px;left:0px;text-align:center;margin:0 auto 0 0px;width:63px !important;' class='btmGraphValue' >"+percent+"&nbsp;%</span> </div>");
										tmpObj.put("PercentValue",percent);
									}else if(callType.equalsIgnoreCase("EHCache"))
									{
									
										tmpObj.put("Type",mappingInfo.getTextDescription("monitor.apmtopology."+temp.get(1)));
										tmpObj.put("Operation <br> Name",temp.get(6));
										tmpObj.put("Count",temp.get(8));
										tmpObj.put("Total <br> Time (MS)",temp.get(7));
										double percent = 0.0;
										try {
											percent = Double.parseDouble (dft.format((Double.parseDouble(temp.get(7).toString())/totalResTime)*100));
										}
										catch (Exception ex)
										{
											System.err.println("Exception While parsing String to Double for EHCache call type "+ex.getMessage());
											//ex.printStackTrace();
										}
										tmpObj.put("% Time", "<div class='btmGraphBg' ><div class='btmGraph' align='center' height='14' style='position:absolute;top:0px;left:0px;text-align:center;width:"+percent+"%;height:14px;margin-left:0px;border:0px solid red;' ></div> <span style='position:absolute;top:0px;left:0px;text-align:center;margin:0 auto 0 0px;width:63px !important;' class='btmGraphValue' >"+percent+"&nbsp;%</span> </div>");
										tmpObj.put("PercentValue",percent);
									}
									else if(callType.equalsIgnoreCase("LDAP"))
									{
										getLdapDetailsTable(temp, ldapDetails, ldapDataTable, totalResTime, dft, ldapMethodCount);
										tempLdapCount++;
										
										if (tempLdapCount == actualLdapCount){ // executing at the end of loop
											ArrayList sortedList = new ArrayList();
											Iterator tempItr = ldapDataTable.keySet().iterator();
											while (tempItr.hasNext()){
												String methodDetail = (String)tempItr.next();
												ArrayList tempDataList = (ArrayList)ldapDataTable.get(methodDetail);
												if (tempDataList != null){
													sortedList.add(tempDataList);
												}
											}
											if (sortedList != null && sortedList.size() > 0){
												egSort = new EgSorter(sortedList,12);
												sortedList = (ArrayList)egSort.sort(3,"Double","desc");
												for (int a=0 ; a<sortedList.size() ; a++){
													ArrayList ldapDataList = (ArrayList) sortedList.get(a);
													if (ldapDataList != null){
														JSONArray ldapGridData = new JSONArray();
														JSONObject ldapTmpObj = new JSONObject();
														ldapTmpObj.put("Type","LDAP");
														String methodName = (String)ldapDataList.get(0);
														ldapTmpObj.put("Details",methodName);
														int methodTotCount = (Integer)ldapDataList.get(1);
														BigDecimal methodTime = (BigDecimal)ldapDataList.get(2);
														ldapTmpObj.put("Time <br> (MS)",methodTime);
														ldapTmpObj.put("Count",methodTotCount);
														double methodPercent = (Double)ldapDataList.get(3);
														ldapTmpObj.put("% Time", "<div class='btmGraphBg' ><div class='btmGraph' align='center' height='14' style='position:absolute;top:0px;left:0px;text-align:center;width:"+methodPercent+"%;height:14px;margin-left:0px;border:0px solid red;' ></div> <span style='position:absolute;top:0px;left:0px;text-align:center;margin:0 auto 0 0px;width:63px !important;' class='btmGraphValue' >"+methodPercent+"&nbsp;%</span> </div>");
														ldapTmpObj.put("PercentValue",methodPercent);
														ldapGridData.add(ldapTmpObj);
														jsonArr.add(ldapGridData);
													}
												}
											}
										}
									}
									if (!callType.equalsIgnoreCase("LDAP") || !callType.equalsIgnoreCase("REDIS")) {
										gridData.add(tmpObj);
										jsonArr.add(gridData);
									}
								}
							}
							Set dbKeys = redisMappingTable.keySet();
							Iterator itr = dbKeys.iterator();
							 while (itr.hasNext()) 
							{
								
								String dbName = (String)itr.next();
								Hashtable cmdValueTable = (Hashtable)redisMappingTable.get(dbName);
								String extHost = dbName.substring(0,dbName.indexOf(":"));
								String extPort =  dbName.substring(dbName.indexOf(":")+1,dbName.indexOf("/"));
								String extInstance =  dbName.substring(dbName.indexOf("/")+1);
								dbName = dbName.substring(0,dbName.indexOf("/"));
								Set cmdKeys = cmdValueTable.keySet();
								Iterator redisItr = cmdKeys.iterator();
								while (redisItr.hasNext()) 
								{
									String commands = (String)redisItr.next();
									ArrayList redisList = (ArrayList)cmdValueTable.get(commands);
		
									JSONObject tmpObj = new JSONObject();
									JSONArray gridData = new JSONArray();
									String dbtype = (String)redisList.get(2);
									int counter = (Integer)redisList.get(0);
									tmpObj.put("Type",mappingInfo.getTextDescription("monitor.apmtopology.Redis"));
									tmpObj.put("DB Name",extInstance);
									tmpObj.put("Redis Command",commands);
									tmpObj.put("Redis Count",counter);
									tmpObj.put("Total <br> Execution <br> Time (MS)",redisList.get(1));
									double avgTime = Double.parseDouble(redisList.get(1).toString())/counter;
									tmpObj.put("Avg <br> Execution <br> Time (MS)",dft.format(avgTime));
									
									double percent = 0.0;
									try {
										percent = Double.parseDouble (dft.format((Double.parseDouble(redisList.get(1).toString())/totalResTime)*100));
									}
									catch (Exception ex)
									{
										System.err.println("Exception While parsing String to Double for Http call type "+ex.getMessage());
										//ex.printStackTrace();
									}
									tmpObj.put("% Time", "<div class='btmGraphBg' ><div class='btmGraph' align='center' height='14' style='position:absolute;top:0px;left:0px;text-align:center;width:"+percent+"%;height:14px;margin-left:0px;border:0px solid red;' ></div> <span style='position:absolute;top:0px;left:0px;text-align:center;margin:0 auto 0 0px;width:63px !important;' class='btmGraphValue' >"+percent+"&nbsp;%</span> </div>");
									tmpObj.put("End Point",dbName);
									gridData.add(tmpObj);
									
									jsonArr.add(gridData);
								}
							 }
							if(sortingArraySize == unknownHttpCount)
								allow = false;
						}
					}
				}
				if(allow)
				{
					rootJson.put("externalDetailsPresence", "yes");
					rootJson.put("gridData",jsonArr);
				}
				else
				{
					rootJson.put("nickName",trgt_Host+":"+portNo);
					rootJson.put("url",url);
					rootJson.put("compName",compName);
					rootJson.put("externalDetailsPresence", "no");
				}
				out.println(rootJson.toString());
			}
			//External Details tab data preparation ends here
		}
	}
	catch(Exception e)
	{
		//e.printStackTrace();
		System.err.println("Exception occured while handling the btm button request");
	}
%>

