<%
/*******************************************************************************
*	File name		: jvmThreads.jsp
*	Purpose			: To show the Threads Details along with Stack Trace for JvmThreadTest
*	Version			: eG 4.3.
*	Creation Date	: 20/12/2008
*	Authtor			: S.Ramesh
******************************************************************************/
%>
<%@ include file = "EgMonitorTracker.jsp" %>
<%@ page import="com.egurkha.util.StringUtils"%>
<%@ page import="com.egurkha.util.DateUtil"%>
<%@ page import="java.sql.*"%>
<%@ page import="com.eg.EgDbInfo"%>
<%@ page import="egurkha.EgDbAdapterUI"%>
<%@ page import="com.eg.EgDbAdapterTypeUI"%>
<%@ page language="java" contentType="text/html;charset=UTF-8" pageEncoding="UTF-8" %>
<jsp:useBean id="trans" scope="page" class="egurkha.TransactionBean" />
<%@ page import ="net.sf.json.*" %>

<%
	response.setContentType("application/json");
	
	String data = request.getParameter("details");
	String measureTime = request.getParameter("time"); 
	String onlyData = request.getParameter("onlyData"); 
	String isTable="";
	
	JSONObject json = new JSONObject();
	StringBuffer sbData = new StringBuffer();
	
	if(data == null || data.equalsIgnoreCase("null") || data.equals("Nil") || data.trim().equals(""))
	{
		String noMeasure = mappingInfo.getTextDescription("monitor.dashboard.No detailed StackTrace for this measure");
		sbData.append("<div class='centerDiv'><table> <tr> <td align=\"center\" valign=\"middle\" style=\"margin-top:100px;text-align:center;font-size:9pt;width:100%\"><center><div class='iconInformation'></div><br/><div>"+noMeasure+"!!</div></center></td> </tr> </table></div>");
		json.put("tableData",sbData.toString());
	}
	else
	{
		data = com.egurkha.util.StringUtils.decodeSecurityChar(data);
		Hashtable threadSession = (Hashtable)session.getAttribute("threadSession");
		if(data.startsWith(","))
			data = data.substring(1);
		if(data.indexOf("#~#") == -1)
		{
			if(threadSession == null || !threadSession.containsKey(data))
			{
				String noMeasure = mappingInfo.getTextDescription("monitor.dashboard.No detailed StackTrace for this measure");
				sbData.append("<div class='centerDiv'><table> <tr> <td align=\"center\" valign=\"middle\" style=\"margin-top:100px;text-align:center;font-size:9pt;width:100%\"><center><div class='iconInformation'></div><br/><div>"+noMeasure+"!!</div></center></td> </tr> </table></div>");
				json.put("tableData",sbData.toString());
			}
			else
				data = (String)threadSession.get(data);
		}

		if(data!=null && data.startsWith("[") && data.endsWith("]"))
			data = data.substring(1,data.length()-1);
		else if(data!=null && data.startsWith(",,[") && data.endsWith("]"))
			data = data.substring(3,data.length()-1);
		
		ArrayList displayList = new ArrayList();
		if(data!=null && data.indexOf("#~#,")==-1 && data.indexOf("#~#")>-1)
		{
			data = data.replace("#~#","");
			displayList = StringUtils.egTokenizer(data,", ");
		}
		else
		{
			displayList = StringUtils.egTokenizer(data,"#~#, ");
		}
		int dataSize = displayList.size();
		int dataCount = 0;

		String threadName= ( dataCount < dataSize )?(String)displayList.get(dataCount):"";
		dataCount = dataCount+1;

		//if(threadName.startsWith("[["))
		//	threadName = threadName.substring(2);

		//threadName = com.egurkha.util.StringUtils.decodeSecurityChar(threadName);

		String tId = ( dataCount < dataSize )?(String)displayList.get(dataCount):"";
		dataCount = dataCount+1;

		String tState = ( dataCount < dataSize )?(String) displayList.get(dataCount):"";
		dataCount = dataCount+1;

		String threadCpuTime = ( dataCount < dataSize )?(String) displayList.get(dataCount):"";
		dataCount = dataCount+1;

		String percentCpuTime = ( dataCount < dataSize )?(String) displayList.get(dataCount):"";
		dataCount = dataCount+1;

		String totBlocked = ( dataCount < dataSize )?(String)displayList.get(dataCount):"";
		dataCount = dataCount+1;

		String blockedTime = ( dataCount < dataSize )?(String)displayList.get(dataCount):"";
		dataCount = dataCount+1;

		String percentBlockTime = ( dataCount < dataSize )?(String)displayList.get(dataCount):"";
		dataCount = dataCount+1;

		String totWaited = ( dataCount < dataSize )?(String) displayList.get(dataCount):"";
		dataCount = dataCount+1;

		String waitedTime = ( dataCount < dataSize )?(String) displayList.get(dataCount):"";
		dataCount = dataCount+1;

		String percentWaitTime = ( dataCount < dataSize )?(String) displayList.get(dataCount):"";
		dataCount = dataCount+1;
		
		

		String sTrace = "Not Available;";
		ArrayList traceToken = new ArrayList();
		if(displayList.size() >=12)
		{
			sTrace = ( dataCount < dataSize )?(String) displayList.get(dataCount):"";
			dataCount = dataCount+1;
			traceToken = StringUtils.egTokenizer(sTrace,";");
		}

		trans.createFile("eg_format.ini");
		String strValue=trans. getStrValue("DDD_TESTS", "JvmThreadTest");
		if(strValue!=null && strValue.length()>0)
		{
			strValue=strValue.replace("_"," ");
		}
		ArrayList header = StringUtils.egTokenizer(strValue,",");

		boolean isLink = false;
		String linkLine = null;
		if(tState.indexOf("owned by:") > 0)
		{
			linkLine = tState.substring(tState.indexOf("owned by:")+10);
			tState = tState.substring(0,tState.indexOf("owned by:")+10);
			isLink =true;
		}

		StringBuffer resultBuffer = new StringBuffer();

		if(isLink)
		{
			IniFile UIni =  new IniFile(EgInstallInfo.getInstallDir() + "/manager/config/eg_ui.ini", false);
			String currentDateFormat = UIni.getValue("CURRENT_DATE_FORMAT","selectedDateFormat");
			String date = measureTime.substring(0,measureTime.indexOf(" "));
			date = DateUtil.changeDateFormat(date,currentDateFormat,"MM/dd/yyyy");
			String time = measureTime.substring(measureTime.indexOf(" ")+1);
			if(time!=null && time.endsWith(".0"))
				time = time.substring(0,time.lastIndexOf("."));
			String dbMeasureTime = date+" "+time;

			StringBuffer sb = new StringBuffer();
			String thisName = linkLine.substring(0,linkLine.lastIndexOf("("));
			String thisID = linkLine.substring(linkLine.lastIndexOf("(")+1,linkLine.lastIndexOf(")"));

			Hashtable ht=null;
			if(EgInstallInfo.isSuperManager)
			{
				ht = new Hashtable();
				StringBuffer orasb = new StringBuffer();
				StringBuffer sqlsb = new StringBuffer();

				orasb.append("select SEQ_NO,MSMT_TIME,MEASURE,Thread_name,ThreadID,Thread_state, Thread_cpu_time, Pct_thread_cpu_time, Blocked_count,Blocked_time,Pct_blocked_time, Waited,Waited_time, Pct_waited_time, Stacktrace from JvmThreadTest_DDD ");

				sqlsb.append("select SEQ_NO,MSMT_TIME,MEASURE,Thread_name,ThreadID,Thread_state, Thread_cpu_time, Pct_thread_cpu_time, Blocked_count,Blocked_time,Pct_blocked_time, Waited,Waited_time, Pct_waited_time, Stacktrace from JvmThreadTest_DDD ");

				sqlsb.append(" where MSMT_TIME = CONVERT (datetime, '");
				sqlsb.append(dbMeasureTime);
				sqlsb.append("', 103)"); 

				orasb.append(" where MSMT_TIME = TO_DATE('");
				orasb.append(dbMeasureTime);
				orasb.append("','MM/DD/YYYY HH24:MI:SS')");

				orasb.append(" and Thread_name='"+thisName+"'");
				orasb.append(" and ThreadID='"+thisID+"'");
				//orasb.append(" and MEASURE != 'Deadlock_threads'");
				orasb.append(" ORDER BY SEQ_NO ASC");

				sqlsb.append(" and Thread_name='"+thisName+"'");
				sqlsb.append(" and ThreadID='"+thisID+"'");
				//sqlsb.append(" and MEASURE != 'Deadlock_threads'");
				sqlsb.append(" ORDER BY SEQ_NO ASC");

				ht.put("OracleQuery",orasb.toString());
				ht.put("OracleQuery",sqlsb.toString());
				ht.put("sourceDateFormat","MM/dd/yyyy HH:mm:ss");
				ht.put("startDate",dbMeasureTime);
			}
			else
			{
				sb.append("select SEQ_NO,MSMT_TIME,MEASURE,Thread_name,ThreadID,Thread_state, Thread_cpu_time, Pct_thread_cpu_time, Blocked_count,Blocked_time,Pct_blocked_time, Waited,Waited_time, Pct_waited_time, Stacktrace from JvmThreadTest_DDD ");

				if(EgDbInfo.checkDBType().equals("EgMsSqlAdapter"))
				{
					sb.append(" where MSMT_TIME = CONVERT (datetime, '");
					sb.append(dbMeasureTime);
					sb.append("', 103)"); 
				}
				else
				{
					sb.append(" where MSMT_TIME = TO_DATE('");
					sb.append(dbMeasureTime);
					sb.append("','MM/DD/YYYY HH24:MI:SS')");
				}
				sb.append(" and Thread_name='"+thisName+"'");
				sb.append(" and ThreadID='"+thisID+"'");
				//sb.append(" and MEASURE != 'Deadlock_threads'");
				sb.append(" ORDER BY SEQ_NO ASC");
			}
			String query = sb.toString();
			EgDbAdapterUI egDb = EgDbAdapterTypeUI.getObject();
			try
			{
				String s_status = egDb.setConnection();
				if(s_status.equals("CONNECTED"))
				{
					ResultSet rs = null;
					if(EgInstallInfo.isSuperManager)
					{
						rs = new EgSMDBHelper().getResultSet(ht);
					}
					else
					{
						rs = egDb.dbselect(query);
					}
					if(rs!=null)
					{
						ResultSetMetaData md = rs.getMetaData();
						int columns = md.getColumnCount();

						int segNo = -1;
						String measureName = null;
						boolean isEnd = false;
						while(rs.next())
						{
							int row = rs.getRow();
							if(row == 1)
							{
								for(int i=1;i<=columns;i++)
								{
									String colName = md.getColumnName(i);
									if(colName.equalsIgnoreCase("SEQ_NO"))
									{
										segNo= rs.getInt(colName);
									}
									else if(colName.equalsIgnoreCase("Measure"))
									{
										measureName = (String)rs.getObject(colName);
									}
									else if(colName.equalsIgnoreCase("Stacktrace"))
									{
										String strace = (String)rs.getObject(colName);
										if(strace!=null && strace.endsWith("~#~"))
										{
											strace = strace.substring(0,strace.lastIndexOf("~#~"));
											resultBuffer.append(strace);
										}
										else
										{
											resultBuffer.append(strace);
											isEnd = true;
										}
									}
									else if(i>3)
									{
										String resultData = (String)rs.getObject(colName);
										resultBuffer.append(resultData);
										resultBuffer.append("#~#, ");
									}
								}
							}
							else
							{
								int nextSegNo = rs.getInt("SEQ_NO");
								String nextMeasure  = (String)rs.getObject("Measure");
								if(nextSegNo == (segNo+1) && nextMeasure.equals(measureName))
								{
									String strace = (String)rs.getObject("Stacktrace");
									if(strace!=null && strace.endsWith("~#~"))
									{
										strace = strace.substring(0,strace.lastIndexOf("~#~"));
										resultBuffer.append(strace);
										segNo = nextSegNo;
									}
									else
									{
										resultBuffer.append(strace);
										isEnd = true;
									}
								}
								else
								{
									isEnd = true;
								}
							}
							if(isEnd)
								break;
						}
					}
				}
			}
			catch(Exception e)
			{
				System.out.println("Exception Occured.......in JvmThreads.jsp");
				resultBuffer = new StringBuffer();
				e.printStackTrace();
			}
			finally
			{
				egDb.releaseConnection(false);
				EgDbAdapterTypeUI.releaseObject(egDb);
			}
		}
		String threadNameLbl = mappingInfo.getTextDescription("monitor.dashboard.Thread Name");
		String threadIDLbl = mappingInfo.getTextDescription("monitor.dashboard.Thread Id");
		String threadstateLbl = mappingInfo.getTextDescription("monitor.dashboard.Thread State");
		String stackTraceLbl = mappingInfo.getTextDescription("monitor.dashboard.Stack Trace");
		sbData.append("<table cellspacing=\"5\">");
		sbData.append("<tr><td valign=\"top\" style=\"width:110px;\" class=\"font_bold11\" >"+threadNameLbl+"</td><td style=\"width:10px;\" >:</td><td valign=\"top\" class=\"font_normal11\" >"+threadName+"</td></tr>");
		//sbData.append("<br/>");
		sbData.append("<tr> <td valign=\"top\" style=\"width:110px;\" class=\"font_bold11\">"+threadIDLbl+"</td><td style=\"width:10px;\" >:</td><td valign=\"top\" class=\"font_normal11\">"+tId+"</td></tr>");
		//sbData.append("<br/>");
		sbData.append("<tr> <td valign=\"top\" style=\"width:110px;\" class=\"font_bold11\">"+threadstateLbl+"</td><td style=\"width:10px;\" >:</td><td valign=\"top\" class=\"font_normal11\" >"+tState);

		if(isLink && resultBuffer.length() > 0)
		{
			sbData.append("<a href=\"javascript:void(0);\" class=\"qin_link\" style=\"text-decoration:underline\" onclick=\"javascript:threadLinkWindow(\'"+com.egurkha.util.StringUtils.encodeSecurityChar(resultBuffer.toString())+"\',\'"+measureTime+"\');\">"+linkLine+" </a>");
		}
		else if(isLink)
		{
			sbData.append(linkLine);
		}
		sbData.append("</td> </tr></table>");
		sbData.append("<br/>"); //gap between header and start of table
		sbData.append("<div class=\"x-table  border-theme\"><table class=\"x-grid-table\" style=\"font-size:12px;\"><thead><tr class=\"x-grid-row\" > <td class=\"x-grid-cell\" align=\"center\" style=\"table-layout:auto;width:75px;padding:10px\" wrap><b>");
		sbData.append(mappingInfo.getTextDescription("monitor.dashboard."+(String)header.get(3))+"</b></td>");
		sbData.append("<td class=\"x-grid-cell\" align=\"center\" style=\"width:80px;padding:10px\"><b>"+mappingInfo.getTextDescription("monitor.dashboard."+(String)header.get(4))+"</b></td>");
		sbData.append("<td class=\"x-grid-cell\" align=\"center\" style=\"width:80px;padding:10px\"><b>"+mappingInfo.getTextDescription("monitor.dashboard."+(String)header.get(5))+"</b></td>");
		sbData.append("<td class=\"x-grid-cell\" align=\"center\" style=\"width:80px;padding:10px\"><b>"+mappingInfo.getTextDescription("monitor.dashboard."+(String)header.get(6))+"</b></td>");
		sbData.append("<td class=\"x-grid-cell\" align=\"center\" style=\"width:80px;padding:10px\"><b>"+mappingInfo.getTextDescription("monitor.dashboard."+(String)header.get(7))+"</b></td>");
		sbData.append("<td class=\"x-grid-cell\" align=\"center\" style=\"width:80px;padding:10px\"><b>"+mappingInfo.getTextDescription("monitor.dashboard."+(String)header.get(8))+"</b></td>");
		sbData.append("<td class=\"x-grid-cell\" align=\"center\" style=\"width:80px;padding:10px\"><b>"+mappingInfo.getTextDescription("monitor.dashboard."+(String)header.get(9))+"</b></td>");
		sbData.append("<td class=\"x-grid-cell\" align=\"center\" style=\"width:80px;padding:10px\"><b>"+mappingInfo.getTextDescription("monitor.dashboard."+(String)header.get(10))+"</b></td>");
		sbData.append("</tr></thead> <tbody><tr  class=\"x-grid-row\">");
		sbData.append("<td class=\"x-grid-cell\" style=\"width:75px\"><div class=\"x-grid-cell-inner\">"+threadCpuTime+"</div></td>");
		sbData.append("<td class=\"x-grid-cell\" style=\"width:75px\"><div class=\"x-grid-cell-inner\">"+percentCpuTime+"</div></td>");
		sbData.append("<td class=\"x-grid-cell\" style=\"width:75px\"><div class=\"x-grid-cell-inner\">"+totBlocked+"</div></td>");
		sbData.append("<td class=\"x-grid-cell\" style=\"width:75px\"><div class=\"x-grid-cell-inner\">"+blockedTime+"</div></td>");
		sbData.append("<td class=\"x-grid-cell\" style=\"width:75px\"><div class=\"x-grid-cell-inner\">"+percentBlockTime+"</div></td>");
		sbData.append("<td class=\"x-grid-cell\" style=\"width:75px\"><div class=\"x-grid-cell-inner\">"+totWaited+"</div></td>");
		sbData.append("<td class=\"x-grid-cell\" style=\"width:75px\"><div class=\"x-grid-cell-inner\">"+waitedTime+"</div></td>");
		sbData.append("<td class=\"x-grid-cell\" style=\"width:75px\"><div class=\"x-grid-cell-inner\">"+percentWaitTime+"</div></td>");
		sbData.append("</tr></tbody></table></div><br/><table><tr> <td  class=\"font_bold11\" style=\"padding-bottom:3px\">"+stackTraceLbl+"</td></tr>");

		if(traceToken.size()>0 && traceToken != null)
		{
			for(int i=0;i<traceToken.size();i++)
			{
				String tmpTok = (String)traceToken.get(i);
				if(tmpTok.indexOf(".") > 1)
				{
					sbData.append("<tr> <td  style=\"font-size:11px;padding-top:6px\">"+tmpTok+"</td> </tr>");
				}
			}
		}
		sbData.append("</table>");
		if(onlyData==null || onlyData.trim().length()==0)
			json.put("tableData",sbData.toString());
	}
	//new link code created by murugan
	if(onlyData==null || onlyData.trim().length()==0)
		response.getWriter().write(json.toString());
	else
		response.getWriter().write(sbData.toString());
%>

