<%
/**
 *	File name		: EgBTMQueryDetails.jsp
 *	Purpose			: This page shows the DB query details of APM - Java , .Net , NodeJS & PHP.
 *	Version			: eG 6.1
 *	Creation Date	: 2-Aug-2016
 */
%>

<%@ page import ="com.eg.*" %>
<%@ page import ="java.io.*" %>
<%@ page import="java.sql.*"%>
<%@ page import="java.util.*"%>
<%@ page import="egurkha.EgDBConnectUI"%>
<%@ page import="egurkha.EgDbAdapterUI"%>
<%@ page import ="com.egurkha.util.StringUtils"%>
<%@ page import ="com.eg.EgInstallInfo"%>
<%@ page import ="org.json.JSONObject"%>
<%@ page import ="java.text.SimpleDateFormat"%>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>

<%!

	String External_Service_Details = "External_Service_Details";
	String BTM_User_Experience = "BTM_User_Experience";

	String[] dddTableColumns = {"SITE_NAME","TRGT_HOST","PORT_NO","TEST_NAME","MEASURE","INFO","STATE","MSMT_HOST","MSMT_TIME","SEQ_NO","EG_GUID","NODE_ORDER","APPLICATION_NAME","CONTEXT_NAME","REQUEST_TIME","THREAD_GUID","URI","RESPONSE_TIME","TIME_ZONE","REMOTE_HOST","REQUEST_TYPE","TRANSACTION_TYPE","SLOW_URL_THRESHOLD","STALLED_URL_THRESHOLD","URL_PARAMS","SESSION_ID","THREAD_ID","DEVICE","OS","BROWSER","REFERER","COUNTRY","LOCATION","POSITION","TRACE_DETAILS","PRE_PROCESSOR_TIME","METHOD_TYPE","STATUS_CODE","COOKIES","HEADER","USERNAME","BUSINESS_CONTEXT","CPU_TIME","WAIT_TIME","BLOCK_TIME","USER_AGENT","BROWSER_VERSION","REGION","CITY","GATEWAY_IP","EXCEPTION_NAME","COMPONENT_ID","UTC_DATE"};
	
	String[] userExpTableColumns = {"MSMT_TIME","EG_GUID","BTM_EXPERIENCE","BUSINESSTRANSTEST","KBUSINESSTRANSTEST","DOTNETMONITORTEST","KDOTNETMONITORTEST","NODETRANSTEST","KNODETRANSTEST","PHPTRANSTEST","KPHPTRANSTEST"};
	
	String[] exServicDetialsTableColumns = {"MSMT_TIME","REQUEST_DATE","EG_GUID","REQUEST_TYPE","NODE_ORDER","DETAILS","SQL_CALLS","SQL_TIME","EXT_HASH","MSMT_TIME","EXT_HASH","CALL_TYPE","NODE_ORDER","RESP_TIME","EXN_HASH","STACK_HASH","MSMT_TIME","EXN_HASH","EXCEPTION_NAME","EXCEPTION_MSG","MSMT_TIME","STACK_HASH","STACKTRACE","MSMT_TIME","EXT_HASH","CALL_TYPE","HOST_IP","PORT_NO","DB_TYPE","DB_NAME","CALL_GRAPH_ID","TABLE_NAME","QUERY_TYPE","ERROR_DETAILS","EXE_TIME","QUERY_HASH","MSMT_TIME","QUERY_HASH","QUERY"};

	String[] EXN_DETAILS_COLUMNS = {"MSMT_TIME","EXT_HASH","CALL_TYPE","NODE_ORDER","RESP_TIME","EXN_HASH","STACK_HASH"};
	String[] EXN_STACKTRACE_COLUMNS = {"MSMT_TIME","STACK_HASH","STACKTRACE"};
	String[] EXN_MASTER_COLUMNS = {"MSMT_TIME","EXN_HASH","EXCEPTION_NAME","EXCEPTION_MSG"};

	String[] SQL_QUERIES_COLUMNS = {"MSMT_TIME","QUERY_HASH","QUERY"};
	String[] SQL_DETAILS_COLUMNS = {"MSMT_TIME","EXT_HASH","CALL_TYPE","HOST_IP","PORT_NO","DB_TYPE","DB_NAME","CALL_GRAPH_ID","TABLE_NAME","QUERY_TYPE","ERROR_DETAILS","EXE_TIME","QUERY_HASH"};


	public void getExitPointCutTableInfo(HashMap exitPointCutTableMapper, String key, String[] values)
	{
		if(exitPointCutTableMapper != null && key.length() > 0)
		{
			try
			{
				if (values != null && values.length > 0)
				{
					ArrayList tempList = new ArrayList();
					for(int x=0 ; x<values.length ; x++)
					{
						String tableHeaderStr = values[x];
						tempList.add(tableHeaderStr);
					}
					exitPointCutTableMapper.put(key, tempList);
				}
			}
			catch(Exception ee)
			{
				ee.printStackTrace();
			}
		}
	}


	public void updateOtherTables(String tableName, HashMap dataMap, HashMap sourceMap , HashMap columnNameMap, String[] columnHeaders){
		Set dataKeys = dataMap.keySet();
		Iterator exnItr = dataKeys.iterator();
		ArrayList btmExnList = new ArrayList();
		while(exnItr.hasNext()){
			String keyString = (String)exnItr.next();
			ArrayList rowList = (ArrayList)dataMap.get(keyString);
			btmExnList.add(rowList);
		}

		if(btmExnList.size() > 0){
			sourceMap.put(tableName, btmExnList);
			columnNameMap.put(tableName, new ArrayList(Arrays.asList(columnHeaders)));
		}
	}

	public boolean checkForNewDbSchema(Set tableNames, Connection conn)
	{
		Iterator tableNams = tableNames.iterator();
		//EgDbAdapterUI egDb = EgDbAdapterTypeUI.getObject();
		boolean isNewSchema = false;
		try
		{
			//String s_status = egDb.setConnection();
			//if(s_status.equals("CONNECTED"))
			{
				while(tableNams.hasNext())
				{
					String tblName = (String)tableNams.next();
					StringBuffer buffer = new StringBuffer();
					buffer.append("select count(");
					if(tblName.equalsIgnoreCase("EXTERNAL_SERVICE_DETAILS" )){
						buffer.append("EXT_HASH) from ").append(tblName);
					}
					else if (tblName.toUpperCase().endsWith("_DDD")){
						buffer.append("UTC_DATE) from ").append(tblName);
					}
					else{
						continue;
					}

					Statement stat = null;
					ResultSet rs = null;
					try{
						stat = conn.createStatement();
						rs = stat.executeQuery(buffer.toString());
						isNewSchema = true;
					}
					catch(Exception e){
						e.printStackTrace();
					}
					finally{
						if (rs != null){
							try {
								rs.close();
							} catch (Exception grr){}
						}

						if (stat != null){
							try {
								stat.close();
							} catch (Exception grr){}
						}
					}

					if(isNewSchema){
						break;  // while loop break;
					}

					/*if(tblName.equalsIgnoreCase("BUSINESSTRANSTEST_DDD") || tblName.equalsIgnoreCase("KBUSINESSTRANSTEST_DDD") || tblName.equalsIgnoreCase("EXTERNAL_SERVICE_DETAILS" ))
					{
						ResultSet rs = null;
						try
						{
							rs = egDb.dbselect(buffer.toString());
							isNewSchema = true;
							//ResultSetMetaData rsmd = rs.getMetaData();
							//int noOfColumns = rsmd.getColumnCount();
							//String lastColumn = rsmd.getColumnName(noOfColumns);
							//if(lastColumn.equalsIgnoreCase("UTC_DATE") || lastColumn.equalsIgnoreCase("EXT_HASH"))
							//	return true;
						}
						catch(Exception ex){
							ex.printStackTrace();
						}
						finally{
							if (rs != null){
								try {
									rs.close();
								} catch (Exception grr){}
							}
						}
					}*/
				}
			}
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		finally{
			//egDb.releaseConnection(false);
			//EgDbAdapterTypeUI.releaseObject(egDb);
		}
		return isNewSchema;
	}

	public void createDbEntry(HashMap mainKVP, HashMap columnNames, Connection conn) throws Exception
	{
		boolean isDbNew=checkForNewDbSchema(mainKVP.keySet(), conn);
		boolean dtaBlongs2NuTbl = false;
		Iterator tableNames = mainKVP.keySet().iterator(); 
		while(tableNames.hasNext())
		{
			String tableName = (String)tableNames.next();
			if(tableName.equalsIgnoreCase("BUSINESSTRANSTEST_DDD") || tableName.equalsIgnoreCase("KBUSINESSTRANSTEST_DDD"))
			{
				dtaBlongs2NuTbl=((ArrayList)columnNames.get(tableName)).contains("UTC_DATE");
			}
			if(isDbNew)
			{
				if(tableName.equalsIgnoreCase("BUSINESSTRANSTEST_DDD") || tableName.equalsIgnoreCase("KBUSINESSTRANSTEST_DDD")) 
				{
					ArrayList transTestColumns = ((ArrayList)columnNames.get(tableName));
					if(!dtaBlongs2NuTbl)
					{
						if(!transTestColumns.contains("UTC_DATE")){
							transTestColumns.add("UTC_DATE");
						}
					}
				}else if(tableName.equalsIgnoreCase(External_Service_Details)) 
				{
					ArrayList extServiceDetailColumns = ((ArrayList)columnNames.get(tableName));
					if(!dtaBlongs2NuTbl)
					{
						if(!extServiceDetailColumns.contains("EXT_HASH")){
							extServiceDetailColumns.add("EXT_HASH");
						}
					}
				}
			}
			//System.out.println("tableName :"+tableName);
			ArrayList rowsDataMapList = (ArrayList)mainKVP.get(tableName);
			//System.out.println("rowsDataMapList :"+rowsDataMapList);
			ArrayList columnNamesList = (ArrayList)(columnNames.get(tableName));
			//System.out.println("columnNamesList :"+columnNamesList);

			StringBuffer queryBuffer = new StringBuffer();
			queryBuffer.append("INSERT INTO ").append(tableName).append(" ( ");
			int len = columnNamesList.size();
			boolean isExtSrvTable = false;
			if(tableName.equalsIgnoreCase(External_Service_Details)){
				len = 9;
				isExtSrvTable = true;
			}
			for(int r=0; r<len; r++){
				String columnName = (String)columnNamesList.get(r);
				queryBuffer.append(columnName);
				if(r == (len -1)){
					queryBuffer.append(" )");
				}
				else{
					queryBuffer.append(",");
				}
			}

			queryBuffer.append(" VALUES ( ");
			for(int v=0; v<len; v++){
				queryBuffer.append('?');
				if(v == (len-1)){
					queryBuffer.append(" )");
				}
				else{
					queryBuffer.append(",");
				}
			}

			String query = queryBuffer.toString();
			System.out.println("[BTMQueryDetails] -  Table Name :"+tableName +" & Query is : "+query);

			PreparedStatement psmt = null;
			try{
				psmt = conn.prepareStatement(query);
				for(int a=0;a<rowsDataMapList.size();a++){
					ArrayList rowList = (ArrayList)rowsDataMapList.get(a);
					int colCount = 0;
					int limit = rowList.size();
					if(isExtSrvTable){
						limit = 9;
					}
					for(int b=0;b<limit;b++){
						Object rowDta = rowList.get(b);
						if(rowDta == null){
							rowDta = new String("-5.0");
						}
						colCount++;

						String dataClassName = rowDta.getClass().getName();
						//System.out.println(" colCount :"+colCount+"   "+rowDta+"  dataClassName "+dataClassName);
						if(dataClassName.contains("java.lang.Integer")){
							psmt.setInt(colCount,(Integer)rowDta);
						}
						else if(dataClassName.contains("java.lang.Double")){
							psmt.setDouble(colCount,(Double)rowDta);
						}
						else if (dataClassName.contains("java.sql.Timestamp")){
							psmt.setTimestamp(colCount,((java.sql.Timestamp)rowDta));
						}
						else if (dataClassName.contains("[B")){
							psmt.setBytes(colCount,(byte[])rowDta);
						}
						else {
							try{
								double dddd  = Double.parseDouble(rowDta.toString());
								psmt.setDouble(colCount,dddd);
							}
							catch(Exception e){
								psmt.setString(colCount,(String)rowDta);
							}
						}
					}

					// Insert Data on the table
					try{
						int updateRecords = psmt.executeUpdate();
						System.out.println("[BTMQueryDetails] - Inserting into  "+tableName+" ("+ updateRecords+") Rows Affected.");
					}
					catch(Exception ee){
						String expString = ee.toString().toLowerCase();
						boolean showException = false;
						if (expString.indexOf("unique constraint") > 0){
							showException = true;
						} 
						else if (expString.indexOf("duplicate key") < 0) {
							showException = true;
						}
						if(showException){
							System.out.println("[BTMQueryDetails] - Exception while Executing the Query "+query);
							ee.printStackTrace();
						}
					}
				}
			}
			catch(Exception e){
				e.printStackTrace();
			}
			finally{
				try{
					if(psmt!=null){
						psmt.close();
					}
				}
				catch(Exception e){}
			}

			/*for(int rowMapIndx = 0; rowMapIndx<rowsDataMapList.size();rowMapIndx++)
			{
				HashMap row = (HashMap)rowsDataMapList.get(rowMapIndx);
				if(tableName.equalsIgnoreCase("EXTERNAL_SERVICE_DETAILS") && columnNamesList.size() > 9)
				{
					HashMap masterMap = new HashMap();
					masterMap.put("EXTERNAL_SERVICE_DETAILS",new ArrayList());
					masterMap.put("BTM_EXN_DETAILS",new ArrayList());
					masterMap.put("BTM_EXN_MASTER",new ArrayList());
					masterMap.put("BTM_EXN_STACKTRACE",new ArrayList());
					masterMap.put("BTM_SQL_DETAILS",new ArrayList());
					masterMap.put("BTM_SQL_QUERIES",new ArrayList());
					for(int i=0;i<columnNamesList.size();i++)
					{
						if(i<=8) 				((ArrayList)masterMap.get("EXTERNAL_SERVICE_DETAILS")).add(columnNamesList.get(i));
						else if(i>8 && i<=15)	((ArrayList)masterMap.get("BTM_EXN_DETAILS")).add(columnNamesList.get(i));
						else if(i>15 && i<=19)	((ArrayList)masterMap.get("BTM_EXN_MASTER")).add(columnNamesList.get(i));
						else if(i>19 && i <= 22)((ArrayList)masterMap.get("BTM_EXN_STACKTRACE")).add(columnNamesList.get(i));
						else if(i>22 && i<= 35)	((ArrayList)masterMap.get("BTM_SQL_DETAILS")).add(columnNamesList.get(i));
						else if(i>35 && i<=38)	((ArrayList)masterMap.get("BTM_SQL_QUERIES")).add(columnNamesList.get(i));
					}
					for(Object tblName: masterMap.keySet())
					{
						String tbl = (String)tblName;
						ArrayList masterColumnNames = ((ArrayList)masterMap.get(tblName));
						if(masterColumnNames.size() == 0){
							System.out.println("masterColumnNames is empty for the table "+tblName);
							continue;
						}
						String query = "INSERT INTO " + tbl + " ( " ;
						boolean runQuery = true;

						for(int i=0;i<masterColumnNames.size();i++)
						{
							String colNam = (String)((ArrayList)masterMap.get(tblName)).get(i);
							if((tbl.equalsIgnoreCase("BTM_SQL_QUERIES") && colNam.startsWith("QUERY_HASH")) || (tbl.equalsIgnoreCase("BTM_SQL_DETAILS")&& colNam.startsWith("EXT_HASH")) || (tbl.equalsIgnoreCase("BTM_EXN_STACKTRACE")&& colNam.startsWith("STACK_HASH")) || (tbl.equalsIgnoreCase("BTM_EXN_MASTER")&& colNam.startsWith("EXN_HASH")) || (tbl.equalsIgnoreCase("BTM_EXN_Details")&& colNam.startsWith("EXT_HASH")))
							{
								if(row.get(colNam)==null)
								{
									runQuery=false;
								}
							}
							colNam = colNam.split("->")[0];
							query+=colNam+",";
						}
						query = (query.substring(0,query.length()-1))+") Values ( ";
						for(int count=0;count<((List)masterMap.get(tblName)).size();count++)
						{
							query+="?,";
						}
						query=(query.substring(0,query.length()-1))+")";
						System.out.println("[EgBTMQueryDetails.jsp] - Query is :"+query);
						PreparedStatement psmt = getPreparedStatement(conn, query, masterColumnNames,row);
						if(runQuery)
						{
							try{
								int updateRecords = psmt.executeUpdate();
								System.out.println("Inserting into  "+tblName+"\n"+ updateRecords+" Rows Affected.");
							}
							catch(Exception ee){
								System.out.println("Exception while Executing the Query "+query);
								ee.printStackTrace();
							}
							finally{
								try{
									if(psmt!=null){
										psmt.close();
									}
								}
								catch(Exception e){}
							}
						}
					}
				}
				else
				{
					ArrayList tblColumnNames = (ArrayList)columnNames.get(tableName);
					String query = "INSERT INTO " + tableName + " (" + tblColumnNames.toString().replace("[","").replace("]","")+") Values (";
					for(int count=0;count<tblColumnNames.size();count++)
					{
						query+="?,";
//						System.out.println("i = "+(count+1)+" column Name = "+tblColumnNames.get(count)+"--------------"+row.get(count));
					}
					query=(query.substring(0,query.length()-1))+")";
//					System.out.println("query = "+query);
					PreparedStatement psmt = getPreparedStatement(conn, query, tblColumnNames, row );
					if(isDbNew && (tableName.equalsIgnoreCase("BUSINESSTRANSTEST_DDD") || tableName.equalsIgnoreCase("KBUSINESSTRANSTEST_DDD"))) 
					{
						int indexOfUTC_DATE = (tblColumnNames.indexOf("UTC_DATE"))+1;
						SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
						format.setTimeZone(TimeZone.getTimeZone("UTC"));
						psmt.setTimestamp(indexOfUTC_DATE,java.sql.Timestamp.valueOf(format.format(new java.util.Date(((java.sql.Timestamp)row.get("REQUEST_TIME")).getTime()))));
					}
					if( isDbNew && !dtaBlongs2NuTbl && tableName.equalsIgnoreCase("EXTERNAL_SERVICE_DETAILS"))
						psmt.setString(((tblColumnNames.indexOf("EXT_HASH"))+1),"-");
					try
					{
						System.out.println("Inserting into  "+tableName+"\n"+psmt.executeUpdate()+" Rows Affected.");
					}catch(Exception e)
					{
						e.printStackTrace();
					}
					finally{
						try{
							if(psmt!=null){
								psmt.close();
							}
						}
						catch(Exception e){}
					}
				}
			}*/
		}
	}

	public PreparedStatement getPreparedStatement(Connection conn, String qry,ArrayList tblColumnNames,HashMap row )throws SQLException
	{
		PreparedStatement psmt = conn.prepareStatement(qry);
		for(int columnNameIndx =0; columnNameIndx<tblColumnNames.size();columnNameIndx++)
		{
			String columnName = (String) tblColumnNames.get(columnNameIndx);
			int colCount = (tblColumnNames.indexOf(columnName))+1;
			Object rowDta = row.get(columnName);
			
			if(rowDta!=null && rowDta.getClass().getName().contains("java.lang.Integer"))
			{
				psmt.setInt(colCount++,(Integer)rowDta);
			}else if(rowDta!=null && rowDta.getClass().getName().contains("java.lang.Double"))
			{
				psmt.setDouble(colCount++,(Double)rowDta);
			}else if (rowDta!=null && rowDta.getClass().getName().contains("java.sql.Timestamp"))
			{
				psmt.setTimestamp(colCount++,((java.sql.Timestamp)rowDta));
			}else if (rowDta!=null && rowDta.getClass().getName().contains("[B"))
			{
				psmt.setBytes(colCount++,(byte[])rowDta);
			}else if(rowDta!=null)
			{
				psmt.setString(colCount++,(String)rowDta);
			}
		}
		return psmt;
	}

	public boolean deleteDbEntry(String guid,ArrayList tableNames, Connection conn)
	{
		boolean deleted = false;
		//Connection conn = dbconnect.getConnection();
		int rowsAffected = 0;
		PreparedStatement psmt = null;
		if(conn == null){
			return deleted = false;
		}

		try{
			psmt = conn.prepareStatement("DELETE FROM ? WHERE EG_GUID =?");
			for(int tableNameIndx =0;tableNameIndx<tableNames.size();tableNameIndx++)
			{
				Object tableName = tableNames.get(tableNameIndx);
				try{
					psmt.setString(1, tableName.toString());
					psmt.setString(2, guid);
					rowsAffected = psmt.executeUpdate();
				}
				catch(Exception e){
					e.printStackTrace();
					//dbconnect.changeConn();
				}
				if(rowsAffected>0){
					deleted = true;
				}
			}
		}
		catch(Exception e){
			e.printStackTrace();
		}
		finally{
			if(psmt != null){
				try{
					psmt.close();
				}catch(Exception cc){}
			}
			//dbconnect.releaseConnection();
		}
		return deleted;
	}

	public boolean guidPresentInDb (String guid, ArrayList tableNames, EgDBConnectUI dbconnect) throws Exception
	{
		boolean alreadyPresent = false;
		Statement statement = null;
		try{
			Connection conn = dbconnect.getConnection();
			statement = conn.createStatement();
			for(int tableNameIndx =0;tableNameIndx<tableNames.size();tableNameIndx++)
			{
				Object tableName = tableNames.get(tableNameIndx);
				ResultSet rs = null;
				try{
					rs = statement.executeQuery("SELECT COUNT(*) FROM "+(String)tableName+" WHERE EG_GUID='"+guid+"'");
					while(rs.next())
					{
						if (rs.getInt(1)>0)
						{
							alreadyPresent = true;
						}
					}
				}
				catch(Exception aa){
					aa.printStackTrace();
				}
				finally{
					if (rs != null){
						try {
							rs.close();
						} catch (Exception grr){}
					}
				}
			}
		}
		catch(Exception e){
			e.printStackTrace();
		}
		finally{
			if(statement!=null){
				try{
					statement.close();
				}
				catch(Exception rr){}
			}
			dbconnect.releaseConnection();
		}
		return alreadyPresent;
	}

	/*public static HashMap getJsonMap(HashMap columnNames, HashMap columnData)
	{
		HashMap mainKVP = new HashMap();
		Iterator tableNames = columnNames.keySet().iterator(); 
		while(tableNames.hasNext())
		{
			Object tableName = tableNames.next();
			int colNamesCount = ((List)columnNames.get(tableName)).size();
			ArrayList tblDta = new ArrayList();
			List colDtaRows = (List)columnData.get(tableName);
			if(colDtaRows!=null)
			{
				for(int AllRowsColDataIndx =0; AllRowsColDataIndx<colDtaRows.size();AllRowsColDataIndx++)
				{
					Object row = colDtaRows.get(AllRowsColDataIndx);
					HashMap thisRowData = new HashMap();
					for(int elemIndx =0; elemIndx<colNamesCount;elemIndx++)
					{
						String colName = (String)((ArrayList)columnNames.get(tableName)).get(elemIndx);
						Object cellData = ((ArrayList)row).get(elemIndx);
						thisRowData.put(colName, cellData);
					}
					tblDta.add(thisRowData);
				}
			}
			mainKVP.put(tableName, tblDta);
		}
		return mainKVP;
	}*/

	public ArrayList getRowData(ResultSet rs, ResultSetMetaData rsmd,int totalColumns) throws SQLException
	{
		ArrayList row = new ArrayList();
		for(int d=1;d<=totalColumns;d++)
		{
			int columnType = rsmd.getColumnType(d);
			if(columnType == 12)  row.add(rs.getString(d));
			else if(columnType == 93)  row.add(rs.getTimestamp(d));
			else if(columnType == 2)  row.add(rs.getDouble(d));
			else if(columnType == 2004)  row.add((byte[])rs.getBytes(d));
			else row.add(rs.getString(d));
		}
		return row;
	}
%>

<%
	String guid = request.getParameter("guid");
	String testType = request.getParameter("testType");
	String whoami = request.getParameter("whoami");
	String pwd = request.getParameter("pwd");
	String enableSaveGuidBtn = "";
	if(whoami == null || pwd == null || whoami.equals("null") || pwd.equals("null") || !whoami.equals("egurkha")  || !pwd.equals("admin"))
	{
		%><jsp:forward page="../admin/EgErrorUrl.jsp"/><%
	}
	String[] testTypeArray = null;
	String iniFileName = "eg_apm.ini";
	com.eg.IniFile apmIni = new com.eg.IniFile(EgInstallInfo.getInstallDir()+"/manager/config/"+iniFileName);
	HashMap exitPointCutTableMapper = new HashMap();
	
	if(testType == null)
	{
		testType = "All";
	}

	Vector testTypeFromIni = apmIni.getAllValues("APM_TEST_TYPE");
	Set testTypeSet = new HashSet(testTypeFromIni);
	if (testTypeSet != null)
	{
		testTypeArray = new String[testTypeSet.size()+1];
		testTypeArray[0] = "All";
		Iterator testTypeItr = testTypeSet.iterator();
		int temp = 1;
		while(testTypeItr.hasNext())
		{
			String testTypeNameStr = (String)testTypeItr.next();
			testTypeArray[temp] = testTypeNameStr;
			temp++;
		}
	}
	String[] pointCutNames = apmIni.getVariables("POINTCUT_HEADER_DETAILS");
	if (pointCutNames != null && pointCutNames.length > 0)
	{
		for (int k=0 ; k<pointCutNames.length ; k++)
		{
			String tblHeaderDetails = apmIni.getValue("POINTCUT_HEADER_DETAILS", pointCutNames[k]);
			if (tblHeaderDetails != null && tblHeaderDetails.length() > 0)
			{
				String[] headerInfos = (String[])tblHeaderDetails.split(",");
				getExitPointCutTableInfo(exitPointCutTableMapper, pointCutNames[k], headerInfos);
			}
		}
	}
	
	boolean uploadSuccess = false;
	String fileName = null;
	String fileUpload = request.getParameter("fileUpload");
	String contentType = request.getContentType();

	if(fileUpload!=null && fileUpload.equals("true"))
	{
		if(contentType!=null && contentType.indexOf("multipart/form-data;") > -1)
		{
			InputStream inputStream = null;
			OutputStream outputStream = null;
			String destinationDir = EgInstallInfo.getInstallDir()+"/manager/tomcat/temp/";
			try
			{
				Part filePart = request.getPart("btmdatafile");
				if(filePart!=null)
				{
					String header = filePart.getHeader("content-disposition");
					if(header!=null && header.length() > 0)
					{
						String fileNameKey = "filename=\"";
						fileName = header.substring(header.indexOf(fileNameKey) + fileNameKey.length(), header.lastIndexOf("\""));
					}
				}
				if(fileName!=null)
				{
					inputStream = filePart.getInputStream();
					outputStream = new FileOutputStream(new File(destinationDir + File.separator + fileName));
					int read = 0;
					byte[] bytes = new byte[1024];
					try
					{
						while ((read = inputStream.read(bytes)) != -1) 
						{
							outputStream.write(bytes, 0, read);
						}
						uploadSuccess = true;
						System.out.println("Successfully uploaded the file "+fileName+" on the folder "+destinationDir);
					}
					catch(Exception e)
					{
						System.out.println("Exception occured while uploading the file "+fileName);
						e.printStackTrace();
					}
					finally
					{
						try
						{
							if (outputStream != null) 
							{
								outputStream.close();
							}
						}
						catch(Exception e)
						{
							e.printStackTrace();
						}
						try
						{
							if (inputStream != null) 
							{
								inputStream.close();
							}
						}
						catch(Exception e)
						{
							e.printStackTrace();
						}
					}
				}
			}
			catch(Exception e)
			{
				System.out.println("Exception occured while uploading BTM data file. "+e.getMessage());
				e.printStackTrace();
			}
		}
	}
	//out.println("uploadSuccess :"+uploadSuccess);
	boolean deSerializationDone = false;
	HashMap sourceMap = null;
	HashMap columnNames = null;
	
	HashMap exnDetailsMap = null;
	HashMap exnMasterMap = null;
	HashMap exnStackTraceMap = null;
	HashMap sqlDetailsMap = null;
	HashMap sqlQueriesMap = null;
	
	String uploadSuccessFromReq = request.getParameter("uploadSuccess");
	String fileNameFromReq = request.getParameter("fileName");
	if(uploadSuccessFromReq != null && fileNameFromReq != null)
	{
		uploadSuccess = (uploadSuccessFromReq.equalsIgnoreCase("true")) ? true : false;	
		fileName = request.getParameter("fileName");
	}
	
	if(uploadSuccess)
	{
		String filePath = EgInstallInfo.getInstallDir()+"/manager/tomcat/temp/"+fileName;
		FileInputStream fis  = null;
		ObjectInputStream ois = null;
		try 
		{
			fis = new FileInputStream(filePath);
			ois = new ObjectInputStream(fis);
			// read object from file
			Object sourceObject = ois.readObject();
			if(sourceObject!=null && sourceObject instanceof HashMap)
			{
				sourceMap = (HashMap)sourceObject;
			}
			Object columnNameObject = ois.readObject();
			if(columnNameObject!=null && columnNameObject instanceof HashMap)
			{
				columnNames = (HashMap)columnNameObject;
			}
			deSerializationDone = true;
			int len = fileName.length();
			int lastIndex = fileName.lastIndexOf("_");
			if(len > 40 && lastIndex > 0)
			{
				guid = fileName.substring(fileName.lastIndexOf("_")+1 , len-4);
			}
			else
			{
				guid = fileName;
			}
			testType = "All";
			System.out.println("BTM Data is de-serialized from the file "+fileName);
		} catch (IOException e) 
		{
			e.printStackTrace();
		}
		finally
		{
			// closing resources
			try
			{
				ois.close();
			}catch(Exception e)
			{
				e.printStackTrace();
			}
			try
			{
				fis.close();
			}catch(Exception e)
			{
				e.printStackTrace();
			}
		}
	}
	String fileDownload = request.getParameter("fileDownload");
	boolean export = false;
	if(fileDownload != null && fileDownload.length() > 0 && fileDownload.equalsIgnoreCase("true"))
	{
		//Download the details of this GUID as a serializable object.
		export = true;
	}

	ArrayList queryTables = null;
//	deSerializationDone =true if u upload file the next line checks if u didnot upload serialized file.
	if(!deSerializationDone)
	{
		sourceMap = new HashMap();
		columnNames = new HashMap();
		EgDbaseInfo egDbaseInfo = new EgDbaseInfo("manager");

		String[] queries = null;
		String errorMsg = "";
		Connection conn = null;
		Statement stmt = null;
		ResultSet rs = null;
		ResultSetMetaData rsmd = null;
		int colCount = 0;
		ArrayList userExpColumnNames = new ArrayList();
		ArrayList userExpColumnValues = new ArrayList();
		String[] apmTestTables = apmIni.getVariables("APM_TEST_TYPE");
		if (apmTestTables != null && guid!=null)
		{
			queryTables = new ArrayList();
			EgDBConnectUI dbconnect = new EgDBConnectUI();
			conn = dbconnect.getConnection();
			ArrayList enabledTests = new ArrayList();
			try
			{
				stmt = conn.createStatement();
				rs = stmt.executeQuery("Select * from "+BTM_User_Experience+" where EG_GUID='"+guid.trim()+"'");
				if (rs != null)
				{
					rsmd = rs.getMetaData();
				}
				int maxColCount = rsmd.getColumnCount();
				for(int i=1;i<=maxColCount;i++)
				{
					userExpColumnNames.add(rsmd.getColumnName(i));
				}
				while(rs.next())
				{
					userExpColumnValues.add(getRowData(rs,rsmd,maxColCount));
					for(int i=1;i<=maxColCount;i++)
					{
						if(i>3 && rs.getInt(i)>0)
						{
							enabledTests.add(rsmd.getColumnName(i)+"_DDD");
						}
					}
				}
			}
			catch(Exception ex){
				ex.printStackTrace();
			}
			finally{
				if (rs != null){
					try {
						rs.close();
					} catch (Exception grr){}
				}
				if (stmt != null){
					try {
						stmt.close();
					} catch (Exception gr){}
				}
				rs = null;
				stmt = null;
				rsmd = null;
			}

			if(conn!=null){
				try
				{
					stmt = conn.createStatement();
					for (int x=0 ; x<apmTestTables.length ; x++)
					{
						String apmTestType = apmIni.getValue("APM_TEST_TYPE", apmTestTables[x]);
						String testTable = apmTestTables[x]+"_DDD";
						if (apmTestType.equalsIgnoreCase(testType) || testType.equalsIgnoreCase("All"))
						{
							boolean isTableExistsInDB = egDbaseInfo.isTableExistInDB(testTable);
							if(enabledTests.toString().toLowerCase().contains(testTable.toLowerCase()))
							{
								if(isTableExistsInDB)
								{
									queryTables.add(testTable);
								}
								else{
									try{
	//									System.out.println("Executing query = "+"select * from "+testTable);
										rs = stmt.executeQuery("select count(EG_GUID) from "+testTable);
										//rsmd = rs.getMetaData();
										int count = 1;
										long records = -1L;
										while(rs.next())// && count < rsmd.getColumnCount())
										{
											//rs.getString(rsmd.getColumnName(count++));
											records = rs.getLong(count);
											if(records > 0){
												queryTables.add(testTable);
												break;
											}
										}
									}
									catch(SQLException e) {
										e.printStackTrace();
										//System.out.println("Table -> "+testTable+" Is Not Present In DataBase! ");
									}
									finally {
										if (rs != null) {
											try {
												rs.close();
											} catch (Exception gr){}
										}
										rs = null;
									}
								}
							}
						}
					}
				}
				catch(Exception ab){
					ab.printStackTrace();
				}
				finally{
					if (stmt != null) {
						try {
							stmt.close();
						} catch (Exception gr){}
					}
				}
			}
			
			dbconnect.releaseConnection();
			queryTables.add(External_Service_Details);
			queryTables.add(BTM_User_Experience);
		}
		if (queryTables != null && guid != null && guid.length() > 0)
		{
			guid = guid.trim();
			if (queryTables.size() > 0)
			{
				queries = new String[queryTables.size()];
				String orderByStr = "";
				for (int q=0 ; q<queryTables.size() ; q++) 
				{
					String testTableName = (String)queryTables.get(q);
					testTableName = testTableName.trim();
					if (testTableName.endsWith("_DDD") || testTableName.endsWith("_Details"))
					{
						orderByStr = " order by node_order";
					}else
					{
						orderByStr = "";
					}
					if(testTableName.equalsIgnoreCase("External_Service_Details"))
					{
						String query1 = "SELECT * FROM External_Service_Details A  "+
										"LEFT JOIN BTM_EXN_Details B ON A.EXT_HASH = B.EXT_HASH "+
										"LEFT JOIN BTM_EXN_MASTER C ON B.EXN_HASH = C.EXN_HASH "+
										"LEFT JOIN BTM_EXN_STACKTRACE D ON B.STACK_HASH = D.STACK_HASH "+
										"LEFT JOIN BTM_SQL_DETAILS E ON A.EXT_HASH = E.EXT_HASH "+
										"LEFT JOIN BTM_SQL_QUERIES F ON E.QUERY_HASH = F.QUERY_HASH  "+
										"WHERE A.EG_GUID = '"+guid+"' ORDER BY A.node_order";
						queries[q] = query1;
					}else
					{
						queries[q] = "select * from "+testTableName+" where eg_guid='"+guid+"'"+orderByStr;	
					}
				}
			}
		}
		ArrayList externalColumnTypes = new ArrayList();
		ArrayList userExpColumnTypes = new ArrayList();
		//System.out.println("queries = "+Arrays.asList(queries));
		if(queries != null && queries.length > 0)
		{
			EgDBConnectUI dbconnect = new EgDBConnectUI();
			ArrayList joinDetailsList = new ArrayList();
			try
			{
				//String displayName = "";
				conn = dbconnect.getConnection();
				stmt = conn.createStatement();
				for (int a=0 ; a<queries.length ; a++)
				{
					//ArrayList dddColumnTypes = new ArrayList();
					String query = queries[a];
					String testTableName = (String)queryTables.get(a);
					boolean dddTable = false;
					//displayName = "Data Details for "+testTableName;
					if(testTableName != null && testTableName.contains("_DDD")) 
					{
						//displayName = "DDD Data Details for "+testTableName;
						dddTable = true;
					}
					//System.out.println("Executing Query :"+query);
					try
					{
						rs = stmt.executeQuery(query); // executing all BTM related tables one by one
						if (rs != null)
						{
							rsmd = rs.getMetaData();
						}
					}
					catch(Exception ex)
					{
						if(rs !=null){
							try{
								rs.close();
							}
							catch(Exception ee){}
						}
						rs = null;
						rsmd = null;
						System.out.println("Problem while executing Query :"+query);
						ex.printStackTrace();
						continue;
					}

					/* VARCHAR - 12 , NUMERIC - 2 , TIMESTAMP - 93 , BLOB - 2004 */
					int totalColumns = rsmd.getColumnCount();

					boolean dddBlobColumn = false;
					
					if(!testTableName.equalsIgnoreCase(External_Service_Details))
					{
						ArrayList resultList = new ArrayList();
						while(rs.next())
						{
							ArrayList row = getRowData(rs,rsmd,totalColumns);
//							for(int i=1;i<totalColumns;i++) System.out.println("i = "+i+" ColName = "+rsmd.getColumnName(i)+" ---------- "+row.get(i));
							resultList.add(row);
							boolean isUserExpTable = testTableName.equalsIgnoreCase(BTM_User_Experience);
							ArrayList userExpData = ((!isUserExpTable && resultList.size() > 0) ? resultList : userExpColumnValues);
							sourceMap.put(testTableName , userExpData);
						}
					}
					else
					{
						while(rs.next())
						{
							ArrayList row = getRowData(rs,rsmd,totalColumns);
							joinDetailsList.add(row);
						}
					}

					if (rs != null)
					{
						try {
							rs.close();
						} catch (Exception gr){}
					}
					rs = null;
					rsmd = null;

					if(dddTable)
					{
						/*ArrayList dddColumnNames = new ArrayList();
						if(dddColumnTypes.size() == 0)
						{
							for(int d = 1; d <=totalColumns; d++)
							{
								int columnType = rsmd.getColumnType(d);
								dddColumnTypes.add(columnType);
								String columnName = rsmd.getColumnName(d);
								dddColumnNames.add(columnName);
							}
							columnNames.put(testTableName , dddColumnNames);
						}*/
						columnNames.put(testTableName , new ArrayList(Arrays.asList(dddTableColumns)));
					}
					else if (testTableName.equals(External_Service_Details))
					{
						/*ArrayList externalColumnNames = new ArrayList();
						HashMap counterMap = new HashMap();
						if(externalColumnTypes.size() == 0)
						{
							for(int d = 1; d <=totalColumns; d++)
							{
								int columnType = rsmd.getColumnType(d);
								externalColumnTypes.add(columnType);
								String columnName = rsmd.getColumnName(d);
								counterMap.put(columnName, (counterMap.containsKey(columnName)) ? ((int)counterMap.get(columnName))+1 : 1);
								externalColumnNames.add((externalColumnNames.contains(columnName) ? columnName+"->"+counterMap.get(columnName) : columnName));
							}
							columnNames.put(testTableName , externalColumnNames);
						}*/
						columnNames.put(External_Service_Details , new ArrayList(Arrays.asList(exServicDetialsTableColumns)));
					}
					else if(testTableName.equals(BTM_User_Experience))
					{
						//columnNames.put(testTableName , userExpColumnNames);
						columnNames.put(testTableName , new ArrayList(Arrays.asList(userExpTableColumns)));
					} 
				}
			}
			catch(Exception e)
			{
				e.printStackTrace();
				dbconnect.changeConn();
				errorMsg = "Problem while executing query... "+e.toString();
			}
			finally
			{
				try
				{
					if(rs != null)
					{
						try {
							rs.close();
						} catch (Exception aa){}
					}
					if(stmt != null)
					{
						try {
							stmt.close();
						} catch (Exception aa) {}
					}
					dbconnect.releaseConnection();
				}
				catch(Exception e1)
				{
					e1.printStackTrace();
				}
				rs=null;
				stmt=null;
				rsmd=null;
			}

			//Parse JoinQuery Results
			if(joinDetailsList!=null){
				HashMap externalDetailsData = new HashMap();

				HashMap exnDetailsData = new HashMap();
				HashMap exnMasterData = new HashMap();
				HashMap exnStackTraceData = new HashMap();

				HashMap sqlDetailsData = new HashMap();
				HashMap sqlQueriesData = new HashMap();
				
				for(int j=0;j<joinDetailsList.size();j++){
					ArrayList rowList = (ArrayList)joinDetailsList.get(j);

					String extHash = null;
					boolean oldSchma = false;
					try{
						extHash = (String)rowList.get(8);
					}
					catch(Exception e){
						//old schema
						extHash = "-";
						oldSchma = true;
					}

					if(extHash!=null && extHash.length() >0){
						if(!externalDetailsData.containsKey(extHash)){
							ArrayList extRowList = new ArrayList();
							for(int a=0;a<=8;a++){
								extRowList.add(rowList.get(a));
							}
							externalDetailsData.put(extHash , extRowList);
						}
					}
					//System.out.println("externalDetailsData :"+externalDetailsData);

					if(oldSchma){
						continue;
					}

					// Data for BTM_EXN_DETAILS
					String callGraphId = (String)rowList.get(12);
					if(callGraphId!=null && callGraphId.length() > 0){
						String keyString = extHash+"~~~|~~~"+callGraphId;
						if(!exnDetailsData.containsKey(keyString)){
							ArrayList exnRowList = new ArrayList();
							for(int a=9;a<=15;a++){
								exnRowList.add(rowList.get(a));
							}
							exnDetailsData.put(keyString, exnRowList);
						}
					}

					//Data for BTM_EXN_MASTER
					String exnHash = (String)rowList.get(17);
					if(exnHash!=null && exnHash.length() > 0){
						if(!exnMasterData.containsKey(exnHash)){
							ArrayList exnDetailsList = new ArrayList();
							for(int a=16;a<=19;a++){
								exnDetailsList.add(rowList.get(a));
							}
							exnMasterData.put(exnHash,exnDetailsList);
						}
					}

					//Data for BTM_EXN_STACKTRACE
					String stackHash = (String)rowList.get(21);
					if(stackHash!=null && stackHash.length() > 0){
						if(!exnStackTraceData.containsKey(stackHash)){
							ArrayList stackList = new ArrayList();
							for(int a=20;a<=22;a++){
								stackList.add(rowList.get(a));
							}
							exnStackTraceData.put(stackHash,stackList);
						}
					}

					//Data for BTM_SQL_DETAILS
					String sqlCallgraphID = (String)rowList.get(30);
					if(sqlCallgraphID!=null && sqlCallgraphID.length() > 0){
						String keyString = extHash+"~~~|~~~"+sqlCallgraphID;
						if(!sqlDetailsData.containsKey(keyString)){
							ArrayList sqlDetailsList = new ArrayList();
							for(int a=23;a<=35;a++){
								sqlDetailsList.add(rowList.get(a));
							}
							sqlDetailsData.put(keyString, sqlDetailsList);
						}
					}

					//Data for BTM_SQL_QUERIES
					String queryHash = (String)rowList.get(37);
					if(queryHash!=null && queryHash.length() > 0){
						if(!sqlQueriesData.containsKey(queryHash)){
							ArrayList sqlQueryList = new ArrayList();
							for(int a=36;a<=38;a++){
								sqlQueryList.add(rowList.get(a));
							}
							sqlQueriesData.put(queryHash, sqlQueryList);
						}
					}
				}

				//Rows for EXTERNAL_SERVICE_DETAILS
				Set keys = externalDetailsData.keySet();
				Iterator itr = keys.iterator();
				ArrayList externalDataList = new ArrayList();
				while(itr.hasNext()){
					String extHashString = (String) itr.next();
					ArrayList extList = (ArrayList)externalDetailsData.get(extHashString);
					externalDataList.add(extList);
				}
				sourceMap.put(External_Service_Details, externalDataList);

				//Rows for BTM_EXN_DETAILS
				updateOtherTables("BTM_EXN_DETAILS",exnDetailsData,sourceMap,columnNames,EXN_DETAILS_COLUMNS);

				//Rows for BTM_EXN_MASTER
				updateOtherTables("BTM_EXN_MASTER",exnMasterData,sourceMap,columnNames,EXN_MASTER_COLUMNS);

				//Rows for EXN_STACKTRACE_COLUMNS
				updateOtherTables("BTM_EXN_STACKTRACE",exnStackTraceData,sourceMap,columnNames,EXN_STACKTRACE_COLUMNS);

				//Rows for BTM_SQL_DETAILS
				updateOtherTables("BTM_SQL_DETAILS",sqlDetailsData,sourceMap,columnNames,SQL_DETAILS_COLUMNS);

				//Rows for EXN_STACKTRACE_COLUMNS
				updateOtherTables("BTM_SQL_QUERIES",sqlQueriesData,sourceMap,columnNames,SQL_QUERIES_COLUMNS);
			}
			else{
				// No External data  
				sourceMap.put(External_Service_Details, new ArrayList());
			}
		}
	}

	boolean present=false;
	if(guid!=null && guid.trim().length() > 0)
	{
		Set columnKeys = columnNames.keySet();
		Iterator columnItr = columnKeys.iterator();
		ArrayList columnList = new ArrayList();
		while(columnItr.hasNext()){
			String keyString =  (String) columnItr.next();
			if(keyString.endsWith("_DDD") || keyString.equalsIgnoreCase(External_Service_Details) || 
				keyString.equalsIgnoreCase(BTM_User_Experience)){
				columnList.add(keyString);
			}
		}
		present= guidPresentInDb(guid,  columnList, new EgDBConnectUI());
		enableSaveGuidBtn = (present) ? "disabled" : "";
	}
	String operation = request.getParameter("operation");
	if(export)
	{
		//C:\egurkha\manager\tomcat\temp
		String fileName4ser = "eg_btm_log_"+guid+".ser";
		String filePath = EgInstallInfo.getInstallDir()+"/manager/tomcat/temp/"+fileName4ser;
		FileOutputStream fos  = null;
		ObjectOutputStream oos = null;
		boolean serializationDone = false;
		try 
		{
			fos = new FileOutputStream(filePath);
			oos = new ObjectOutputStream(fos);
			// write object to file
			oos.writeObject(sourceMap);
			oos.writeObject(columnNames);
			serializationDone = true;
			System.out.println("BTM Data is serialized for the guid "+guid);
		} catch (IOException e) 
		{
			e.printStackTrace();
		}
		finally
		{
			// closing resources
			try
			{
				oos.close();
			}catch(Exception e)
			{
				e.printStackTrace();
			}
			try
			{
				fos.close();
			}catch(Exception e)
			{
				e.printStackTrace();
			}
		}
		// .ser File Download (Begin)
		if(serializationDone)
		{
			BufferedInputStream buf=null;
			ServletOutputStream myOut=null;
			try
			{
				myOut = response.getOutputStream();
				File myfile = new File(filePath);
				//set response headers
				response.setContentType("application/octet-stream");
				response.setHeader("Content-Disposition","attachment; filename="+fileName4ser);
				response.setContentLength((int) myfile.length());
				FileInputStream input = new FileInputStream(myfile);
				buf = new BufferedInputStream(input);
				int readBytes = 0;

				//read from the file; write to the ServletOutputStream
				while((readBytes = buf.read( )) != -1)
				{
					myOut.write(readBytes);
				}
			}
			catch (Exception ex)
			{
				ex.printStackTrace();
			}
			finally
			{
				//close the input/output streams
				if (myOut != null)
				{
					myOut.close();
				}
				if (buf != null)
				{
					buf.close();
				}
			}
		}
		//.ser File Download (End)
		return;
	}
	else {
		if(operation!=null){
			EgDBConnectUI dbconnect = new EgDBConnectUI();
			Connection connection = dbconnect.getConnection();
			try{
				if(operation.equalsIgnoreCase("create")){
					if(!present)
					{
						createDbEntry(sourceMap,columnNames, connection);
					}else{
						response.setStatus(409);
						return;
					}
				}
				else if(operation.equalsIgnoreCase("delete")){
					boolean deleted = deleteDbEntry(guid, new ArrayList(columnNames.keySet()), connection);
					if (!deleted) 
						response.setStatus(409);
				}
			}
			catch(Exception e) {
				dbconnect.changeConn();
				System.out.print("Object Exception Occured!"+e);
				response.setStatus(409);
				e.printStackTrace();
			}
			finally
			{
				try 
				{
					dbconnect.releaseConnection(); 
				}catch(Exception e1)
				{
					e1.printStackTrace();
				}
			}
		}
	}
%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>eG Java/.Net Query Helper Page</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.8.24/themes/base/jquery-ui.css">

<link rel="stylesheet" type="text/css" href="/final/resources/css/ext-eg.css">

<!--
<link rel = "StyleSheet" href = "/final/admin/eg_styles/adminstyle_gray.css"/>
-->

<style>

.newTable {
    border: 0px solid #b5b5b5;
    overflow: auto;
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
}
.newTable table {
    border: 1px solid #cdcdcd;
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
}
.newTable table tbody tr:nth-child(even) {
    background-color: #f9f9f9
}
.newTable table tbody tr:nth-child(odd) {
    background-color: #ffffff
}
.newTable table thead tr th {
    border: 1px solid #cdcdcd;
    padding: 4px 10px 1px 10px;
    font-size: 12px;
    background-color: #e6e6e6;
    text-transform: uppercase;
    line-height: 1.8em;
}
.newTable table thead tr th.subHeader {
    background-color: #f4f5f5;
    text-align: center
}
.newTable table tbody tr td {
    border-bottom: 1px solid #cdcdcd;
    padding: 4px 10px 1px 10px;
    font-size: 12px;
    line-height: 1.8em;
}
.newTable table tbody tr td.iconColumn{
	padding: 2px 10px 1px 10px;
    line-height: 1.6em;
}
.newTable table tbody tr td.rowspanRightBorder {
    border-right: 1px solid #cdcdcd;
}
.newTable table tbody tr td .ellipsisText {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}
/*   New components  --> class:newTable  -  styles end here   */

.popupDiv{
	background:#ffffff;
	padding:10px;
	border:1px solid #cccccc;
	border-radius:5px;
	-webkit-box-shadow: 0px 0px 10px 5px rgba(100, 100, 100, 0.35); 
    -moz-box-shadow: 0px 0px 10px 5px rgba(100, 100, 100, 0.35);
    box-shadow: 0px 0px 10px 5px rgba(100, 100, 100, 0.35);
}

.ui-icon-closethick {
    background-image: url(/final/images/Light/newPopupWindowClose.png) !important;
    background-position: left !important;
    margin: 0 5px 0 0 !important;
}

.ui-dialog .ui-dialog-titlebar-close, .ui-icon-closethick {
    width: 16px !important;
    height: 16px !important;
}

.ui-dialog .ui-dialog-titlebar-close {
    background: none !important;
	border: 0px solid red !important;
}

.ui-dialog .ui-dialog-titlebar-close, .ui-dialog .ui-dialog-titlebar-close:hover {
    padding: 0 !important;
}

.ui-button-icon-only .ui-icon {
    left: 0px;
	margin-left:0px;
	top:0px;
}

</style>

<script src="/final/jquery/jquery.js"></script>
<script src="/final/jquery/jquery-ui.js"></script>
<script type="text/javascript" src="/final/monitor/eg_scripts/eg_aggregate.js"></script>
<script language="javascript" src="/final/admin/eg_scripts/timeout.js"></script>

<script>
	$(document).ready( function(){
//		Uncomment This to enable DeleteFromDatabase Button after every 5 clicks on the guid cell
		var clickCount=0;
		$("#guid").click(function() {
			clickCount=clickCount+1;
			if(clickCount % 5 == 0)	$("#deleteGuid").attr("disabled", false);
			else $("#deleteGuid").attr("disabled", true);
		})
		$(".tableTotalValue").each(function() {
			var value = $(this).attr("value");
			var $spanId = $(this).attr("data-id");
			$("#"+$spanId).html(value);
		});
	});

	function showTopologyPage($this, url){
		var height = 680; 
		var width = 1300;
		var left = (screen.width/2)-(width/2);
		var top = (screen.height/2)-(height/2);
		var myWindow = window.open(url, "myWindow", "width="+width+", height="+height+", top="+top+", left="+left);
	}
	function getTraceDetails($this,title)
	{
		$($this).closest("td").append('<div class="dialog" title="Trace Details" style="display:none;"> </div>');
		var $table=$($this).closest("td").find('div.tableContainer');
		var $dialog=$($this).closest("td").find('div.dialog');
		$dialog.html($table.html());
		//$dialog.show();
		$dialog.dialog();
		$dialog.dialog("option","width",800);
		$dialog.dialog("option","height",500);
		$dialog.dialog("option","position",'center');
		$dialog.dialog("option","title",title+" Trace Details");
		$dialog.dialog("option", "closeText" ,"");

		$(".tabs").tabs();
		$(".tabs").each(function() {
			$(this).css("display", "inline-block");
		});
	}
	function popupStackTraceDetails(hash){
		popupTable(hash,JSON.parse($("#exnStackTraceMapJson").text()),20,22,'BTM_EXN_STACKTRACE');
	}
	function popupExceptionDetails(hash){
		popupTable(hash,JSON.parse($("#exnMasterMapJson").text()),16,19,'BTM_EXN_MASTER');
	}
	function popupQueryDetails(hash){
		popupTable(hash,JSON.parse($("#sqlQueriesMapJson").text()),36,38,'BTM_SQL_QUERIES');
	}
	function popupTable(hash, tableData, startindx,endindx,title){
		var columnNames = JSON.parse($("#columnNamesJson").text())["External_Service_Details"];
		tblstr =	'<div style="overflow: auto;">'+
						'<table style="width:100%; position: relative; top: 0; bottom: 0; left: 0; right: 0;">'+
							'<tr style="border-bottom:1px solid #e0e0e0;">';
								for(var i in columnNames){
									if(i>=startindx && i<=endindx) tblstr+='<td style="padding:10px; margin:5px;">'+columnNames[i]+'</td>';
								}
							tblstr += '</tr>'
							tblstr += '<tr>'
							for(var j in tableData[hash]){
								tblstr+='<td style="padding:10px; margin:5px;">'+tableData[hash][j]+'</td>';
							}tblstr += '</tr>'
							
						tblstr += '</table>'+
					'</div>'+
					 $(tblstr).dialog({
					autoOpen:true,
					dialogClass: "no-close",
					show: {effect:"fade",duration:200},
					hide: {effect:"scale",duration:200},
					resizable: true,
					modal: false,
					closeOnEscape: true,
					height: $(window).height()-200,
					width: $(window).width()-200,
					title: title,
					open: function(event, ui) {
						$(".ui-dialog-titlebar-close", ui.dialog | ui).text("X");
					}
				}); 			
	}
	function getExternalTraceDetails()	{
			var columnNames = JSON.parse($("#columnNamesJson").text())["External_Service_Details"];
			var exnDetailsMapData = JSON.parse($("#exnDetailsMapJson").text());			
			var sqlDetailsMapData = JSON.parse($("#sqlDetailsMapJson").text());
			tblstr = '<div>'+
						'<table style="width:100%; position: relative; top: 0; bottom: 0; left: 0; right: 0;">'+
							'<tr>'+
								'<td>';
									tblstr +='<div style="overflow: auto;"><h1><br>Exception Details<br> </h1>'+
										'<table style="width:100%; position: relative; top: 0; bottom: 0; left: 0; right: 0;">'+
											'<tr style="border-bottom:1px solid #e0e0e0;"><td>#</td>'
												for(var i in columnNames){
													if(i>=11 && i<=15) tblstr+='<td style="padding:10px; margin:5px;">'+columnNames[i].split('->')[0]+'</td>';
												}
												tblstr += '</tr>'
												rowcount=0;
												for(var i in exnDetailsMapData){
													rowcount+=1;
													tblstr += '<tr><td>'+rowcount+'</td>'
													for(var j in exnDetailsMapData[i]){
														if(j>1){
															if(j<exnDetailsMapData[i].length-2){
																tblstr+='<td style="padding:10px; margin:5px; border-left:1px solid #e0e0e0;">'+exnDetailsMapData[i][j]+'</td>';
															}else{
																
																if(j==exnDetailsMapData[i].length-2){
																	tblstr+='<td style="padding:10px; margin:5px; border-left:1px solid #e0e0e0;"><input type="submit" value="'+exnDetailsMapData[i][j]+'" onclick="popupExceptionDetails(\''+exnDetailsMapData[i][j]+'\')"></td>';
																}
																else{
																	tblstr+='<td style="padding:10px; margin:5px; border-left:1px solid #e0e0e0;"><input type="submit" value="'+exnDetailsMapData[i][j]+'" onclick="popupStackTraceDetails(\''+exnDetailsMapData[i][j]+'\')"></td>';
																}
															}
														}
													}
													
													tblstr += '</tr>'
												}
												if(rowcount == 0){tblstr+='<tr><td colspan="11" style="text-align:center;"><br>No Rows In Table</td></tr>'};
										tblstr += '</table>'+
									'</div>'+
								'</td>'+
							'</tr>'+
							'<tr>'+
								'<td><br><br>';
									tblstr +='<div style="overflow: auto;"><h1><br>SQL Details<br> </h1>'+
											'<table style="width:100%; position: relative; top: 0; bottom: 0; left: 0; right: 0;">'+
												'<tr style="border-bottom:1px solid #e0e0e0;"><td>#</td>'
													for(var i in columnNames){
														if(i>=25 && i<=35) tblstr+='<td style="padding:10px; margin:5px;">'+columnNames[i].split('->')[0]+'</td>';
													}
													tblstr += '</tr>'
													rowcount=0;
													for(var i in sqlDetailsMapData){
														rowcount+=1;
														tblstr += '<tr><td>'+rowcount+'</td>'
														for(var j in sqlDetailsMapData[i]){
															if(j>1){
																if(j<sqlDetailsMapData[i].length-1){
																	tblstr+='<td style="padding:10px; margin:5px; border-left:1px solid #e0e0e0;">'+sqlDetailsMapData[i][j]+'</td>';
																}else{
																	tblstr+='<td style="padding:10px; margin:5px; border-left:1px solid #e0e0e0;"><input type="submit" value="'+sqlDetailsMapData[i][j]+'" onclick="popupQueryDetails(\''+sqlDetailsMapData[i][j]+'\')"></td>';
																}
															}
														}
														tblstr += '</tr>'
													}
													if(rowcount == 0){tblstr+='<tr><td colspan="11" style="text-align:center;"><br>No Rows In Table</td></tr>'};
											tblstr += '</table>'+
									'</div>'+
								'</td>'+
							'</tr>'+
						'</table>'+
					'</div>'

			  $(tblstr).dialog({
					autoOpen:true,
					dialogClass: "no-close",
					show: {effect:"fade",duration:200},
					hide: {effect:"scale",duration:200},
					resizable: true,
					modal: false,
					closeOnEscape: true,
					height: $(window).height()-50,
					width: $(window).width()-50,
					title: "External_Service_Details",
					open: function(event, ui) {
						$(".ui-dialog-titlebar-close", ui.dialog | ui).text("X");
					}
				}); 			
     
	}

	function validateForm() {
		var x = document.forms["BTMQueryForm"]["guid"].value;
		if (x == null || x == "") {
			alert("BTM Request GUID must be filled out");
			return false;
		}
	}

	function save()
	{
		window.location.href = "/final/misc/EgBTMQueryDetails.jsp?sessionInUse=true&fileDownload=true";
	}

	function openUploadWin() {
		showDivs('linkDiv');
	}

	function hideDivs(divId)
	{
		var show_div = document.getElementById(divId);
		if(show_div!=null)
		{
			show_div.style.display="none";
		}
	}

	function showDivs(divId)
	{
		var show_div = document.getElementById(divId);
		if(show_div!=null)
		{
			show_div.style.display = 'block';
			show_div.style.position = 'absolute';
			bringToFront(show_div);
		}
	}

	function bringToFront(obj)
	{
		if (!document.getElementsByTagName)
			return;
		var divs = getAbsoluteDivs();  
		var max_index = 0;  
		var cur_index;  
		for (i = 0; i < divs.length; i++)
		{
			var item = divs[i];
			if (item == obj || item.style.zIndex == '')
				continue;
			cur_index = parseInt(item.style.zIndex);
			if (max_index < cur_index)
			{
				max_index = cur_index;
			}
		}
			obj.style.zIndex = max_index + 1;
	}

	function getAbsoluteDivs()  
	{
		var arr = new Array();
		var all_divs = document.body.getElementsByTagName("DIV");
		var j = 0;
		for (i = 0; i < all_divs.length; i++)
			if (all_divs.item(i).style.position=='absolute')
			{
				arr[j] = all_divs.item(i);
				j++;
		}
		return arr;
	}
	function saveToDb(url,guid){	
		$.ajax({
			type: "GET",
			url: url,
			success: function(data){ alert("DataSaved To DataBase!"); },
			error : function(er){ if(er.status == 409) alert("Insert Failed ! Please delete the last guid entry manually");  }
		});
	}
	function deleteFromDb(url){
		$.ajax({
			type: "GET",
			url: url,
			success: function(data){ alert("Data Deleted From DataBase"); },
			error : function(er){ if(er.status == 409) alert("Delete Failed Data Might Not Be Present!");  }
		});
	}
</script>
</head>
<body>
	<div id="linkDiv" class="popupDiv" name="linkDiv" style="display:none;left:500px;top:100px;width:400px;height:70px; position:absolute;">
		<table  border="0" cellspacing="0" cellpadding="0" width="100%">
			<tr>
				<td class="eg_whitebg">
					<table cellspacing="0" cellpadding="3" border="0" width="100%">
						<tr>
							<td >
								<div style="display:block;text-align:right"><a id="closeLink" class="mouse" onclick="hideDivs('linkDiv');"><img src="/final/images/Light/newPopupWindowClose.png" border="0" class="mouse" title="close"></a>
								</div>
							</td>
						</tr>
					</table>
				</td>
			<tr>
				<td>
					<div  id='linkInnerDiv' name='linkInnerDiv' style="height:50px;"> 
						<form name="uploadForm" id="uploadForm"  method = "post" enctype = "multipart/form-data" action="/final/misc/EgBTMQueryDetails.jsp?whoami=egurkha&pwd=admin&fileUpload=true">
						<table>
							<tr>
								<td style="width:80%;padding:10px;"> <input type="file" id="btmdatafile" name="btmdatafile" style="border:1px solid #cccccc;padding:4px;width:100%"/></td>
								<td style="width:100px;text-align:center;padding:10px"> <input type="submit" value="Upload" style="padding:4px 10px"/> </td>
							</tr>
						</table>
						</form>
					</div>
				</td>
			</tr>
		</table>
	</div>

<%
		if (guid == null || testType == null )
		{
			guid = "";
			testType = "All";
%>
			<form name="BTMQueryForm" action="EgBTMQueryDetails.jsp" onsubmit="return validateForm();">
				<INPUT TYPE="hidden" NAME="whoami" value="<%=whoami%>">
				<INPUT TYPE="hidden" NAME="pwd" value="<%=pwd%>">
				<br/>
				<table align="center" width="75%" border="0">
					<th align="left" style="font-size:24px;"><b>eG BTM Debug Helper</b></th>
					<th align="right" style="font-size:16px;text-align:right"><b><%=new java.util.Date()%></b></th>
				</table>
				<br/>
				<div class="newTable">
				<table border="0" width="75%" align="center">
					<tr>
						<td width="50%" ><b>BTM Request GUID </td>
						<td width="50%"><INPUT TYPE="text" NAME="guid" value="<%=guid%>" size="60"></b></td>
					</tr>
					<tr>
						<td width="50%"><b>APM Type</b></td>
						<td width="65%">
							<select name="testType">
	<%		for (int i=0;i<testTypeArray.length;i++)
			{
				String selected = "";
				if (testType.equalsIgnoreCase(testTypeArray[i])) 
				{
					selected = "selected";
				}
	%>							<option value="<%=testTypeArray[i]%>" <%=selected%>><%=testTypeArray[i]%></option><%
			}
	%>						</select>
						</td>
					</tr>
					<tr>
						<td align="center"  colspan="2" style="padding:4px" ><input type="button" value="Export" title="Export the transaction details" disabled style="padding:2px 10px"> <input type="button" value="Import" title="Import the transaction details" onClick="javascript:openUploadWin()" style="padding:2px 10px;margin-left:30px" ></td>
					</tr>
					</table>
					</div>
						<p style="text-align:center;margin:10px">
							<INPUT TYPE="submit" style="padding:2px 10px">
						</p>
					<br>

			</form>
	<%
		}
		else
		{
			int size = sourceMap.size();
			String exportDisabled = "";
			if(size == 0) 
			{
				exportDisabled = "disabled";
			}
%>
			<br/>
				<table align="center" width="75%" border="0">
					<th align="left" style="font-size:24px;"><b>eG BTM Debug Helper</b></th>
					<th align="right" style="font-size:16px;text-align:right"><b><%=new java.util.Date()%></b></th>
				</table>
			<div class="newTable">
			<table border="1" width="75%" align="center">
				<br>
				<tr>
					<td width="45%"><b>DDD Data Details for GUID</td>
					<td id ="guid" width="45%"><%=guid%></b></td>
				</tr>
				<tr>
					<td width="45%"><b>APM TestType</td>
					<td width="45%"><%=testType%></b></td>
				</tr>
				<tr>
					<td align="center" colspan="2" style="padding:4px"><a href="EgBTMQueryDetails.jsp?whoami=<%=whoami%>&pwd=<%=pwd%>&guid=<%=guid%>&testType=<%=testType%>&fileDownload=true"><input style="padding:2px 10px;margin-left:30px" type="button" value="Export" title="Export the transaction details" <%=exportDisabled%>></a> <%if(uploadSuccess){%><input style="padding:2px 10px;margin-left:30px" type="button" value="Save To DataBase" title="Save table Values to DataBase" onClick="javascript:saveToDb('EgBTMQueryDetails.jsp?whoami=<%=whoami%>&pwd=<%=pwd%>&guid=<%=guid%>&testType=<%=testType%>&uploadSuccess=true&fileName=<%=fileName%>&operation=create','<%=guid%>')" <%=enableSaveGuidBtn%>><input style="padding:2px 10px;margin-left:30px" type="button" value="Delete From DataBase" title="Delete table Values From DataBase" id="deleteGuid" onClick="javascript:deleteFromDb('EgBTMQueryDetails.jsp?whoami=<%=whoami%>&pwd=<%=pwd%>&guid=<%=guid%>&testType=<%=testType%>&&operation=delete')" disabled><%}%><input style="padding:2px 10px;margin-left:30px" type="button" value="Import" title="Import the transaction details" onClick="javascript:openUploadWin()"><input style="padding:2px 10px;margin-left:30px" type="button" value="Show Topology From DataBase" title="Shows The Topology Diagram For This GUID" onClick="javascript:showTopologyPage(this,'/final/monitor/eGBTMd3Topology.jsp?&testName=BusinessTransTest&EG_GUID=<%=guid%>')"> </td>
				</tr>
			</table>
			</div>
				<p style="text-align:center;margin:10px">
					<a href="EgBTMQueryDetails.jsp?whoami=<%=whoami%>&pwd=<%=pwd%>"><input style="padding:2px 10px" type="button" value="Back To HomePage"></a>
				</p>
			<br>
<%
			if(deSerializationDone)
			{
%>
				<h4 align="center">Below BTM data's are retrieved from the file : &nbsp;<%=fileName%></h4>
<%
			}
			HashMap userExperienceStateMap = new HashMap();
			userExperienceStateMap.put(5, "Error");
			userExperienceStateMap.put(10, "Stalled");
			userExperienceStateMap.put(15, "Slow");
			userExperienceStateMap.put(20, "Healthy");
			try
			{
				if(sourceMap.size() > 0) 
				{
					Set keys = sourceMap.keySet();
					Iterator itr = keys.iterator();
					while(itr.hasNext())
					{
						String tableName = (String) itr.next();
						ArrayList ddDataList = (ArrayList) sourceMap.get(tableName);
						ArrayList columnHeaderNames = (ArrayList) columnNames.get(tableName);
						if(columnHeaderNames==null || columnHeaderNames.size() == 0) 
						{
							continue;
						}
						if(tableName.equalsIgnoreCase("External_Service_Details"))
						{
							ArrayList newList = new ArrayList();
							for(int i=0;i<columnHeaderNames.size();i++)
							{
								if(i<9)
								{
									newList.add(columnHeaderNames.get(i));
								}
							}
							columnHeaderNames = newList;
						}
						int rows = ddDataList.size();
						String displayName = "DDD Data Details for "+tableName;
						boolean dddBlobColumn = false;
						boolean extBlobColumn = false;
						boolean blobColumn = false;
						int blobIndex = -1;
						boolean isUserExpTable = false;
						if(tableName.equals(BTM_User_Experience))
						{
							isUserExpTable = true;
						}
%>
					<div id='resultDiv' style='margin:10px;border:1px solid #cccccc'>
					<div id='headerDiv'></div>
					<h4  style="margin:10px;"><%=displayName%> ( Number of rows found : <span id="<%=rows%>Span"> <%=rows%> </span> )</h4>
					<div class="newTable" style="margin:0px 10px 10px 10px;overflow:auto">
					<table border="1" id="wholetable">
						<tr>
<%
						for(int i=0; i<columnHeaderNames.size();i++)
						{
							String headerName = (String) columnHeaderNames.get(i);
							if(headerName.equalsIgnoreCase("trace_details"))
							{
								dddBlobColumn = true;
								blobIndex = i;
							}else if(headerName.equalsIgnoreCase("details"))
							{
								extBlobColumn = true;
								blobIndex = i;
							}
							else if(headerName.equalsIgnoreCase("query") || headerName.equalsIgnoreCase("stacktrace")){
								blobColumn = true;
								blobIndex = i;
							}
%>
							<td nowrap> <b><%=headerName%> </b> </td>
<%
						}
%>
						</tr>
<%
						for(int i=0;i<rows;i++)
						{
							ArrayList rowList = (ArrayList) ddDataList.get(i);
%>
						<tr>
<%
							for(int j=0;j<rowList.size();j++)
							{
								Object data = rowList.get(j);
								if(data==null)
								{
									data = "-"; 
								}
								if(extBlobColumn && j>8)
								{
									continue;
								}
								if(isUserExpTable && j == 2)
								{
									// User EXP.
									String codeString = data.toString();
									try
									{
										Integer expCode = (codeString.contains(".")) ? ((int)Double.parseDouble(codeString)) : Integer.parseInt(codeString);
										Object value = userExperienceStateMap.get(expCode);
										if(value!=null)
										{
											data = value;
										}
									}
									catch(Exception e)
									{
										Double expCode = Double.parseDouble(codeString);
										int code = expCode.intValue();
										Object value = userExperienceStateMap.get(code);
										if(value!=null)
										{
											data = value;
										}
									}
								}
								if(dddBlobColumn && j == blobIndex)
								{
									// DDD BLOB Column
									byte[] allBytesInBlob = (byte[])data;
									ByteArrayInputStream bos = new ByteArrayInputStream(allBytesInBlob);
									ObjectInputStream objectInputStream = new ObjectInputStream(bos);
									String dataString = (String)objectInputStream.readObject();
									ArrayList valueTokens = StringUtils.egTokenizer(dataString,"%*%");
									if(valueTokens != null)
									{
										int valueTokensSize = valueTokens.size();
%>
									<td>
										<div class="tableContainer" style="display:none;">
											<div class="tabs">
												<ul>
													<li><a href="#tabs-1">View TabularData</a></li>
													<li><a href="#tabs-2">View RawData</a></li>
												</ul>
												<div id="tabs-1" class="newTable">
													<table border="1" style="font-size:12px">
													<thead>
														<tr>
															<th>Call Type</th>
															<th>Node Order</th>
															<th>Total Execution Time(ms)</th>
															<th>Self Execution Time(ms)</th>
															<th>Trace Details</th>
														</tr>
													</thead>
													<tbody>
<%
											StringBuilder traceDetailsBuf = new StringBuilder();
											for(int k=0 ; k<valueTokensSize ; k++)
											{
												String valueString = (String) valueTokens.get(k);
												traceDetailsBuf.append(valueString);
												if(valueString != null)
												{
													ArrayList exitPcStackTraceSpliter = StringUtils.egTokenizer(valueString, "#=#");
													if (exitPcStackTraceSpliter != null && exitPcStackTraceSpliter.size() > 0)
													{
														try
														{
															String nodeOrder = (String)exitPcStackTraceSpliter.get(0);
															String execTime = (String)exitPcStackTraceSpliter.get(1);
															String selfExecTime = (String)exitPcStackTraceSpliter.get(2);
															String method = (String)exitPcStackTraceSpliter.get(3);
															String callType = (String)exitPcStackTraceSpliter.get(4);
%>
														<tr>
															<td><%=callType%></td>
															<td><%=nodeOrder%></td>
															<td><%=execTime%></td>
															<td><%=selfExecTime%></td>
															<td><%=method%></td>
														</tr>
<%
														}
														catch(Exception ex) 
														{
															System.err.println("[EgBTMQueryDetails] - StackTraceLine :"+valueString+" StackTrace Spliter :"+exitPcStackTraceSpliter);
															ex.printStackTrace();
														}
													}
												}
												traceDetailsBuf.append("<br/>");
											}
%>
													</tbody>
													</table>
												</div>
												<div id="tabs-2">
													<p style="font-size:12px"><%=traceDetailsBuf.toString()%></p>
												</div>
											</div>
										</div>
										<input class="traceDetailsClass" type="submit" name="TRACE DETAILS" value="TRACE DETAILS" onclick="getTraceDetails(this,'<%=tableName%>')">
									</td>
<%
									}
								}else if(blobColumn && j == blobIndex){
									byte[] allBytesInBlob = (byte[])data;
									ByteArrayInputStream bos = new ByteArrayInputStream(allBytesInBlob);
									ObjectInputStream objectInputStream = new ObjectInputStream(bos);
									String dataString = (String)objectInputStream.readObject();
%>
									<td nowrap> <%=dataString%> </td>
<%
								}else if(extBlobColumn && j == blobIndex)
								{
									// Ext. BLOB Column
									Hashtable ht = new Hashtable();
									byte[] allBytesInBlob = (byte[])data;
									ByteArrayInputStream bos = new ByteArrayInputStream(allBytesInBlob);
									ObjectInputStream objectInputStream = new ObjectInputStream(bos);
									Hashtable wholeDataFromDb = (Hashtable)objectInputStream.readObject();
									if (wholeDataFromDb != null)
									{
										Iterator dbItr = wholeDataFromDb.keySet().iterator();
										while(dbItr.hasNext())
										{
											String keyData = (String) dbItr.next();
											String type = keyData;
											if(keyData.indexOf("[") > -1)
											{
												type = keyData.substring(0,keyData.indexOf("["));
											}
											Hashtable modifiedDataTable = new Hashtable();
											ArrayList values = (ArrayList)wholeDataFromDb.get(keyData);
											if(values != null)
											{
												modifiedDataTable.put(keyData,values);
											}
											ArrayList temp;
											if(ht != null && ht.containsKey(type))
											{
												temp = (ArrayList) ht.get(type);
												temp.add(modifiedDataTable);
											}
											else
											{
												temp = new ArrayList();
												temp.add(modifiedDataTable);
												ht.put(type, temp);
											}
										}
									}
%>
									<td>
<%
									if (ht != null)
									{
										StringBuilder extDetailsBuf = new StringBuilder();
										Iterator htItr = ht.keySet().iterator();
%>
										<div class="tableContainer" style="display:none;">
											<div class="tabs">
												<ul>
													<li><a href="#tabs-1">View TabularData</a></li>
													<li><a href="#tabs-2">View RawData</a></li>
												</ul>
												<div id="tabs-1" class="newTable">
<%
										while(htItr.hasNext()) 
										{
											String key = (String) htItr.next();
											if(key != null)
											{
%>
													<p><%=key%></p>
													<table border="1" style="font-size:12px">
													<thead>
<%
												if (exitPointCutTableMapper != null && exitPointCutTableMapper.size() > 0)
												{
													Iterator pcItr = exitPointCutTableMapper.keySet().iterator();
													while(pcItr.hasNext())
													{
														String callTypeStr = (String)pcItr.next();
														if (callTypeStr.equalsIgnoreCase(key))
														{
															ArrayList tableColList = (ArrayList)exitPointCutTableMapper.get(callTypeStr);
															if(tableColList != null && tableColList.size() > 0) 
															{
																for (int v=0 ; v<tableColList.size() ; v++) 
																{
																	String tableHeaders = (String)tableColList.get(v);
%>
														<th><%=tableHeaders%></th>
<%
																}
															}
														}
													}
												}
												%>
												</thead>
												<tbody>
												<%
												ArrayList outList = (ArrayList)ht.get(key);
												if(outList != null)
												{
													for (int b=0 ; b<outList.size() ; b++)
													{
														Hashtable combinedDataTable = (Hashtable)outList.get(b);
														if (combinedDataTable != null && combinedDataTable.size() > 0)
														{
															Iterator combinedDataTableItr = combinedDataTable.keySet().iterator();
															while(combinedDataTableItr.hasNext())
															{
																String headerStr = (String)combinedDataTableItr.next();
																if(headerStr!= null && headerStr.length() > 0) 
																{
																	ArrayList valueList = (ArrayList)combinedDataTable.get(headerStr);
																	if (valueList != null) 
																	{
																		for (int jj=0 ; jj<valueList.size() ; jj++) 
																		{
																		String details = (String)valueList.get(jj);
																		String rawData = headerStr+"="+details;
%>
														<tr>
<%
																		if(key.equalsIgnoreCase("SQL") || key.equalsIgnoreCase("HTTP") || key.equalsIgnoreCase("WebService")) 
																		{
																			try
																			{
																				if (headerStr.indexOf("[H]") > -1)
																				{
																					String tblCallType = headerStr.substring(0,headerStr.indexOf("[H]"));
																					String tblDbIpAddr = headerStr.substring(headerStr.indexOf("[H]")+3, headerStr.indexOf("[P]"));
																					String tblDbPort = headerStr.substring(headerStr.indexOf("[P]")+3, headerStr.indexOf("[T]"));
																					String tblDbHostName = headerStr.substring(headerStr.indexOf("[T]")+3, headerStr.indexOf("[I]"));
																					String tblDbSid = headerStr.substring(headerStr.indexOf("[I]")+3);
%>
															<td><%=tblCallType%></td>
															<td><%=tblDbIpAddr%></td>
															<td><%=tblDbPort%></td>
															<td><%=tblDbHostName%></td>
															<td><%=tblDbSid%></td>
<%
																				}
																			}
																			catch(Exception ex1) 
																			{
																				System.err.println("[EgBTMQueryDetails] - Key :"+key+" Header String  :"+headerStr);
																				ex1.printStackTrace();
																			}
																		}
																		else if(key.equalsIgnoreCase("RMI") || key.equalsIgnoreCase("EMAIL") ||
																				key.equalsIgnoreCase("EJB") || key.equalsIgnoreCase("EXCEPTION") ||
																				key.indexOf("Custom")>-1) 
																				{
																					String tblCallType = key;
																							
%>
																<td><%=tblCallType%></td>
<%
																		}
																		else if(key.equalsIgnoreCase("JMS")) 
																		{
																			try
																			{
																				if (headerStr.indexOf("[T]") > -1) 
																				{
																					String tblCallType = headerStr.substring(0,headerStr.indexOf("[T]"));
																					String tblJmsProvider = headerStr.substring(headerStr.indexOf("[T]")+3, headerStr.indexOf("[I]"));
																					String tblQueueOrTopic = headerStr.substring(headerStr.indexOf("[I]")+3);
%>
																<td><%=tblCallType%></td>
																<td><%=tblJmsProvider%></td>
																<td><%=tblQueueOrTopic%></td>
<%
																				}
																			}
																			catch(Exception ex1) 
																			{
																				System.err.println("[EgBTMQueryDetails] - Key :"+key+" Header String  :"+headerStr);
																				ex1.printStackTrace();
																			}
																		}

																		if(details != null)
																		{
																			ArrayList extServiceTraceSpliter = StringUtils.egTokenizer(details, "[V]");
																			for (int z=0 ; z<extServiceTraceSpliter.size() ; z++)
																			{
																				String element = (String)extServiceTraceSpliter.get(z);
%>
																<td><%=element%></td>
<%
																			}
																		}
																		extDetailsBuf.append(rawData+"<br/>");
%>
															</tr>
<%
																		}
																	}
																}
															}
														}
													}
												}
												extDetailsBuf.append("<br/>");
											}
%>
														</tbody></table><br/>
<%
										}
%>
													</div>
												<div id="tabs-2">
													<p style="font-size:12px"><%=extDetailsBuf.toString()%></p>
												</div>
											</div>
										</div>
										<input class="traceDetailsClass" type="submit" name="DETAILS" value="DETAILS" onclick="getTraceDetails(this,'<%=tableName%>')">
<%
									}
%>
									</td>
<%
								}
								else
								{
%>
									<td nowrap> <%=data.toString()%> </td>
<%
								}
							}
%>
						</tr>
<%
						}
%>
					</table>
					</div>
					</div>
<%
					}
				}
				else
				{
					// No Data Found !!!
					//out.println("No Data Found !!!");
%>
					<table height="100%" width="100%" border="0" class="white_bg" style="table-layout:auto;">
					<tr>
						<td align="center" valign="middle" id="eg_errorsmall" style="font-size:10.5pt"> 
							<img src="/final/images/Light/info_mgs_icon.png" align="center" border="0"/><br>
							No detailed data found for this Guid <%=guid%>
						</td>
					</tr>
				</table>
<%
				}
			}
			catch(Exception e)
			{
				e.printStackTrace();
			}
		}
%>
		</div>
</body>
</html>