<%
/*****************************************************************************************************
*	Name		:	EgAgentLogView.jsp
*	Purpose		:	To view the Log Files from the selected Agent.
******************************************************************************************************/
%>
<%@ page import="java.io.*" %>
<%@ page import="java.util.*" %>
<%@ page import ="java.text.SimpleDateFormat"%>
<%@ page import = "com.eg.RemoteControlTaskHelper"%>
<%@ page import = "com.egurkha.util.StringUtils"%>
<%@ page import="com.eg.EgLicenseInfo" %>
<%@ page import="com.eg.EgRoleInfo"%>
<%@ page import="com.eg.EgUsersInfo"%>
<%@ page import="com.eg.EgDiscInfo" %>
<%@ page import="com.eg.EgServerList" %>
<%@ page import="com.eg.EgConMonHelper" %>
<%@ page import="com.eg.IniFile" %>
<%@ page import="com.eg.EgInstallInfo" %>
<%@ page import="com.egurkha.util.*" %>
<%@ page import="egurkha.UserBean" %>
<%@ taglib prefix="egui" uri="../WEB-INF/eg-taglib.tld"%>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%
	String sessionInUse = request.getParameter("sessionInUse");
	String pwd = request.getParameter("pwd");
	String authenticated = (String)session.getAttribute("authenticated");

	if (authenticated == null)
	{
		// Direct access from the browser address bar or from inside the toolkit via the tool
		if (pwd == null)
		{
			if (sessionInUse == null)
			{
				response.sendRedirect(request.getContextPath()+"/toolkitlogin?comeFrom=AgentLogs");
			}
			else
			{
%>
				<script>
					window.parent.location.href ="/final/toolkitlogin";
				</script>
<%
			}
		}
		else
		{
			// Direct access from the browser address bar
			if (!pwd.equals(EgConMonHelper.executePwd))
			{
				response.sendRedirect(request.getContextPath()+"/toolkitlogin?comeFrom=AgentLogs");
			}
			else
			{
				session.setAttribute("reqFromForTk","AgentLogs");
				String redirectURL = request.getContextPath()+"/toolkit";
				response.sendRedirect(redirectURL);
			}
		}
	}
	else
	{
		// Direct access from the browser address bar and session in use
		if (sessionInUse == null)
		{
			response.sendRedirect(request.getContextPath()+"/toolkit");
		}
	}
	session.setAttribute("reqFromForTk","AgentLogs");

	String comeFrom = request.getParameter("comeFrom");
	if (!StringUtils.isNull(comeFrom) && comeFrom.equals("AgentLogs"))
	{
		session.setAttribute("treeViewSrc","AgentLogs");
	}

	EgUsersInfo usersInfo = new EgUsersInfo();
	EgLicenseInfo licInfo = new EgLicenseInfo();
	UserBean userBean = new UserBean();
	EgServerList serverList = new EgServerList();

	ArrayList filterList = new ArrayList();
	String searchStr = request.getParameter("searchStr");
	boolean isFilterEnabled = (searchStr != null && searchStr.trim().length() > 0) ? true : false;
	if(isFilterEnabled)
	{
		StringTokenizer st_token = new StringTokenizer(searchStr);
		while (st_token.hasMoreTokens())
		{
			String thisToken = st_token.nextToken().trim();
			if (thisToken.equals(""))
				continue;
			filterList.add(thisToken);
		}
	}

	boolean isUserBasedCert = false;
	String USER_COMP_AGENTS = "Agents for user licensed types";
	String[] agentTypes = {"Basic Agents","Premium Agents", "External Agents", "Remote Agents",};
	ArrayList agentTypesList = new ArrayList(Arrays.asList(agentTypes));
	if (usersInfo.getUserAllowedCount() > 0)
	{
		agentTypesList.add(USER_COMP_AGENTS);
		isUserBasedCert = true;
	}

	Hashtable nick_ip_map = new com.eg.EgDiscInfo("manager").getNickIpMap();
	if(nick_ip_map == null){
		nick_ip_map = new Hashtable();
	}

	String selectFrom = request.getParameter("selectFrom");
	if(selectFrom != null && (selectFrom.equalsIgnoreCase("agentIP") || selectFrom.equalsIgnoreCase("agentType")))
	{
		session.removeAttribute("logFileList");
	}
	ArrayList resultData = new ArrayList();
	LinkedHashMap logsDirMap = new LinkedHashMap();
	logsDirMap.put("Select a log directory","-1");
	ArrayList logFileList = new ArrayList();
	logFileList.add("Select a log file");
	if(selectFrom == null && session.getAttribute("logFileList") != null)
	{
		logFileList = (ArrayList)session.getAttribute("logFileList");
	}
	String agentType = request.getParameter("agentType");
	if(agentType == null || agentType.trim().length() == 0)
	{
		agentType = "Premium Agents";
	}

	String agentIP = request.getParameter("agentIP");
	String logFileDir = request.getParameter("logFileDir");
	String logFileName = request.getParameter("logFileName");
	String downloadFlag = request.getParameter("downloadFlag");
	boolean downloadAction = (downloadFlag != null && downloadFlag.equalsIgnoreCase("true")) ? true : false;

	RemoteControlTaskHelper rcHelper = new RemoteControlTaskHelper();
	boolean showAlert = false;
	boolean timedout = false;
	String alertMessage = "-";
	String lastModified = "";

	ArrayList agentList = new ArrayList();
	if(agentType.equalsIgnoreCase("External Agents"))
		agentList = licInfo.getExternalAgents();
	else if(agentType.equalsIgnoreCase("Basic Agents"))
		agentList = licInfo.getBasicAgents();
	else if(agentType.equalsIgnoreCase("Premium Agents"))
		agentList = userBean.getPremiumAgents();
	else if(agentType.equalsIgnoreCase("Remote Agents"))
		agentList = licInfo.getRemoteAgents();
	else if (agentType.equalsIgnoreCase(USER_COMP_AGENTS))
		agentList = userBean.getPremiumAgents(true);

	ArrayList aList = serverList.getAgentListFromDB();
	String currList[] = serverList.getTargetNames();
	agentList = serverList.getAgentList(agentList,aList,currList);
	ArrayList agentIPList = new ArrayList();
	if(!agentList.isEmpty())
	{
		for(int i=0;i<agentList.size();i=i+4)
		{
			String agent_ip = (String)agentList.get(i);
			String msg = (String)agentList.get(i+1);
			String isRunning = msg.substring(msg.indexOf("-")+1);
			if(isRunning.equals("Running"))
			{
				if(!isFilterEnabled)
					agentIPList.add(agent_ip);
				else if(doesExist(filterList,agent_ip))
					agentIPList.add(agent_ip);
			}
		}
		if(!agentIPList.isEmpty())
		{
			Collections.sort(agentIPList,String.CASE_INSENSITIVE_ORDER);
			agentIPList.add(0,"Select an agent IP/Nickname");
		}
	}
	if(agentIPList.isEmpty())
	{
		agentIPList.add("No Agent IP/Nickname found");
	}

	if(agentIP != null && !agentIP.equals("-1"))
	{
		boolean foldersAdded = false;
		IniFile inifile = new IniFile(EgInstallInfo.getInstallDir()+"/manager/config/eg_ui.ini");
		if(inifile != null)
		{
			Vector displayNames = inifile.getVariables("AGENT_LOG_FOLDERS",true);
			Vector actualNames = inifile.getAllValues("AGENT_LOG_FOLDERS");
			if(displayNames != null && actualNames != null)
			{
				int count = displayNames.size();
				for(int i=0;i<count;i++)
				{
					logsDirMap.put((String)displayNames.get(i),(String)actualNames.get(i));
					foldersAdded = true;
				}
			}
		}
		if(!foldersAdded)
		{
			logsDirMap.put("Agent","agent/logs");
			logsDirMap.put(".NET","agent/logs/.NetProfLogs");
		}
	}
	if(logFileDir != null && !logFileDir.equals("-1") && selectFrom != null && selectFrom.equals("directory"))
	{
		session.removeAttribute("logFileList");
		if(agentIP != null && agentIP.length()>0 && agentIP.indexOf(":")>0)
		{
			agentIP = agentIP.substring(0,agentIP.indexOf(":"));
		}
		if(rcHelper.setAgentIntoControlMode(agentIP))
		{
			rcHelper.executeTask("ListLogFiles", session.getId(), logFileDir + "@#@Y");
			if(rcHelper.isOutputAvailable())
			{
				logFileList = rcHelper.getOutput();
				String message=null;
				int filesCount=logFileList.size();
				if(filesCount==1)
				{
					message=((String)logFileList.get(0)).trim();
				}
				if(message !=null && message.equalsIgnoreCase("Directory does not exist"))
				{
					showAlert=true;
					alertMessage="Selected directory does not exist";
				}
				else if(message !=null && message.equalsIgnoreCase("Directory is empty"))
				{
					logFileList.set(0,"Not Applicable");
				}
				else
				{
					logFileList.add(0,"Select a log file");
				}
				session.setAttribute("logFileList",logFileList);
			}
		}
		else
		{
			showAlert = true;
			alertMessage = "Please try again.";
		}
	}
	if(logFileName != null && !logFileName.equals("-1"))
	{
		if(rcHelper.setAgentIntoControlMode(agentIP))
		{
			rcHelper.executeTask("ReadFile", session.getId(), logFileName + "@#@Y");
			if(rcHelper.isOutputAvailable())
			{
				resultData = rcHelper.getOutput();
				session.setAttribute("logFileContent",resultData);
				long time = Long.parseLong(String.valueOf(resultData.get(0)));
				SimpleDateFormat sdf = new SimpleDateFormat("MMM dd, yyyy hh:mm:ss a");
				lastModified = (String)sdf.format(new Date(time));
				if(resultData == null || resultData.isEmpty() || resultData.size() ==1)
				{
					showAlert = true;
					alertMessage =  "Selected file " +logFileName+ " is empty.";
				}
			}
			else
			{
				timedout = true;
			}
		}
		else
		{
			showAlert = true;
			alertMessage = "Please try again.";
		}
	}
	if(downloadAction)
	{
		PrintWriter pw = null;
		try
		{
			pw = response.getWriter();
			response.setContentType("application/text");
			response.setHeader("Content-Disposition","attachment; filename="+logFileName);
			response.setContentLength(2048);
			if(resultData != null && !resultData.isEmpty())
			{
				for(int i=1;i<resultData.size();i++)
				{
					pw.write(resultData.get(i).toString()+"\n");
				}
			}
		}
		catch(Exception ioe)
		{
			throw new ServletException(ioe.getMessage());
		}
		finally
		{
			if(pw != null)
				pw.close();
		}
	}
	if(timedout)
	{
		showAlert = true;
		alertMessage = "Agent Timed out.";
	}
%>
<html>
<head>
<title>eG Agent Logs </title>
<link REL = "StyleSheet" href = "/final/admin/eg_styles/adminstyle_blue.css"/>
<style>
	.iconDownload
	{
		background : url('/final/images/Light/eG_Icons.png') no-repeat top left;
		background-position: -80px -260px; width: 16px; height: 16px;
		cursor:pointer;
		outline:none;
	}
	.iconRefresh
	{
		background : url('/final/images/Light/eG_Icons.png') no-repeat top left;
		background-position: -40px -280px; width: 16px; height: 16px;
		cursor:pointer;
		outline:none;
	}

</style>
<script language="JavaScript1.2" src="/final/jquery/jquery.js"></script>
<script language="javascript" src="/final/admin/eg_scripts/timeout.js"></script>
<script>
document.onscroll = function()
{
	clearTimeout(time);
	time = setTimeout(logout,timeoutTime);
}
</script>
<script language="javascript">
var loading = false;
var selectedType = "";
var selectedIp = "";
var selectedDir = "";
var selectedFile = "";
var searchStr = "";
var isEleDisabled = false;
function selectBoxDisable(value)
{
	var selectObjOne = document.getElementById("agentTypes");
	var selectObjTwo = document.getElementById("agentIp");
	var selectObjThree = document.getElementById("logdir");
	var selectObjFour = document.getElementById("logname");
	if(selectObjOne!=null && selectObjTwo!=null && selectObjThree != null)
	{
		if(value == 'true')
		{
			selectObjOne.disabled = true;
			selectObjTwo.disabled = true;
			selectObjThree.disabled = true;
			selectObjFour.disabled = true;
			loading = true;
		}
		else
		{
			selectObjOne.disabled = false;
			selectObjTwo.disabled = false;
			selectObjThree.disabled = false;
			selectObjFour.disabled = false;
			loading = false;
		}
	}
}

function showLoadImage(action)
{
	selectBoxDisable("true");
	var loading_image = document.getElementById("loading_image");
	if (loading_image != null)
	{
		loading_image.style.display = "block";
		loading_image.style.position = 'absolute';
		var message = "Please wait the file content is being loaded...";
		if(action == 'changeLogDir')
			message = "Please wait the log file(s) is being listed...";
		document.getElementById('loadMsg').innerHTML = message;
		bringToFront(loading_image);
	}
}

function getObj()
{
	var selType = document.getElementById("agentTypes");
	var selIp = document.getElementById("agentIp");
	var selDir = document.getElementById("logdir");
	var selFile = document.getElementById("logname");
	selectedType = selType[selType.selectedIndex].value;
	selectedIp = selIp[selIp.selectedIndex].value;
	selectedDir = selDir[selDir.selectedIndex].value;
	selectedFile = selFile[selFile.selectedIndex].value;
	searchStr = $j('#searchBox').val();
}

function chagenType(value)
{
	window.location.href="/final/misc/EgAgentLogView.jsp?sessionInUse=true&agentType="+value+"&selectFrom=agentType";
}

function changeIp(value)
{
	getObj();
	var queryStr = "sessionInUse=true&agentType="+selectedType+"&agentIP="+value+"&selectFrom=agentIP";
	if(searchStr != null && searchStr != '')
	{
		queryStr += "&searchStr="+searchStr;
	}
	window.location.href="/final/misc/EgAgentLogView.jsp?"+queryStr;
}

function changeLogDir()
{
	getObj();
	var queryString ="selectFrom=directory&sessionInUse=true&agentType="+selectedType;
	if(selectedDir != '-1')
	{
		queryString += "&agentIP="+selectedIp+"&logFileDir="+selectedDir;
		disableElements('changeLogDir');
	}
	if(searchStr != null && searchStr != '')
	{
		queryString += "&searchStr="+searchStr;
	}
	window.location.href="/final/misc/EgAgentLogView.jsp?"+queryString;
}

function changeLogFile()
{
	getObj();
	var queryString = "sessionInUse=true&agentType="+selectedType+"&agentIP="+selectedIp+"&logFileDir="+selectedDir+"&logFileName="+selectedFile;
	if(searchStr != null && searchStr != '')
	{
		queryString += "&searchStr="+searchStr;
	}
	window.location.href="/final/misc/EgAgentLogView.jsp?"+queryString;
	disableElements('changeLogFile');
}

function loadFile(action)
{
	if(isEleDisabled)
	 return;
	getObj();
	var queryString = "";
	if(action == 'refresh')
	{
		disableElements(action);
	}
	else if (action == 'download')
	{
		queryString = "downloadFlag=true&";
	}
	queryString += "sessionInUse=true&agentType="+selectedType+"&agentIP="+selectedIp+"&logFileDir="+selectedDir+"&logFileName="+selectedFile;
	if(searchStr != null && searchStr != '')
	{
		queryString += "&searchStr="+searchStr;
	}
	window.location.href="/final/misc/EgAgentLogView.jsp?"+queryString;
}

function bringToFront(obj)
{
	if (!document.getElementsByTagName)
		return;
	var divs = getAbsoluteDivs();
	var max_index = 0;
	var cur_index;
	for (var 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 (var 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 disableElements(action)
{
	showLoadImage(action);
	document.getElementById('logFrame').src = "";
	if(document.getElementById('lst_modified') != null)
	{
		document.getElementById('refresh').style.opacity = "0.5";
		document.getElementById('refresh').style.cursor = "auto";
		document.getElementById('lst_modified').style.opacity = "0.5";
		document.getElementById('download').style.opacity = "0.5";
		document.getElementById('download').style.cursor = "auto";
		isEleDisabled = true;
	}
}


function showElements(element)
{
	if(element == 'search')
	{
		$j('#searchBoxDiv').css('display','block');
		$j('#searchBox').focus();
		$j('#agentIpDiv').css('display','none');
	}
	else
	{
		$j('#searchBoxDiv').css('display','none');
		$j('#agentIpDiv').css('display','block');
	}
}

var $j = jQuery.noConflict();
jQuery.fn.egResize = function() {
	var winWidth = window.innerWidth;
	var winHeight = window.innerHeight;

	$j(".logFrame").width(winWidth-20);
	$j(".tableWidth").width(winWidth-20);
<%
	if(logFileName != null && !logFileName.equals("-1") && resultData.size() > 1)
	{
%>
	$j(".logFrame").height(winHeight-129);
	$j(".tableWidth").height(winHeight-129);
<%
	}
	else
	{
%>
	$j(".tableWidth").height(winHeight-103);
	$j(".tableWidth").height(winHeight-103);
<%
	}
%>
};

$j(document).ready(function(){
	$j(document).egResize();
});

$j(window).resize(function(){
	$j(document).egResize();
});
</script>
</head>
<body class="eg_cellbglits">
<table cellspacing="0" cellpadding="0" border="0" width="100%">
	<tr>
		<td class="eg_cellbglits">
			<table cellspacing="0" cellpadding="4" style="border:0px solid red" align="center">
				<tr>
					<td nowrap="" height="23" valign="right"></td>
					<td nowrap="" height="23" align="center"><b>eG Agent Logs</b></td>
				</tr>
				<tr>
					<td nowrap="" height="20" align="center">
						<img src="/final/admin/eg_images/info2.gif">
					</td>
					<td nowrap="" height="15" align="center">This page enables the administrator to view the log files of the agent.</td>
				</tr>
				<tr>
					<td nowrap="" height="11"></td>
				</tr>
			</table>
		</td>
	</tr>
	<tr>
		<td width="100%" valign="top" align="center" class="eg_cellbglits">
			<table cellspacing="0" width="98.7%" cellpadding="3" style="border:0px solid cyan">
				<tr class="eg_cellbglits">
					<td style="width:25%;text-align:left;"><egui:intnl text='admin.agents.Agent type'/></td>
					<td style="width:25%;text-align:left;"><egui:intnl text='admin.agents.Agent IP/Nickname'/></td>
					<td style="width:25%;text-align:left;"><egui:intnl text='admin.agents.Log file directory'/></td>
					<td style="width:25%;text-align:left;"><egui:intnl text='admin.agents.Log file name'/></td>
				</tr>
				<tr class="eg_cellbglits">
					<td style="width:25%;">
						<select id="agentTypes" name="agentTypes" style="width:100%" onchange='JavaScript:chagenType(this.value)'>
<%
	for (int i=0; i<agentTypesList.size(); i++)
	{
		String dispField = (String)agentTypesList.get(i);
		String valueField = dispField;
		String selected = "";
		if(dispField.equalsIgnoreCase(agentType))
			selected="selected";
%>
								<option value="<%=valueField%>"<%=selected%>><b><%=dispField%></b></option>
<%
	}
%>
							</select>
					</td>
					<td style="width:25%;">
						<div id="searchBoxDiv" style="display:none">
							<input type="text" id="searchBox" name="searchBox" style="width:100%" placeholder="Search agents" title="Press enter key for results">
						</div>
						<div id="agentIpDiv"><select id="agentIp" name="agentIp" style="width:100%" ondblclick="javaScript:showElements('search')" onchange='JavaScript:changeIp(this.value)' title="Double click to enable search">
<%
	for (int i=0; i<agentIPList.size(); i++)
	{
		String dispField = (String)agentIPList.get(i);
		String valueField = dispField;
		String selected = "";
		if(dispField.equalsIgnoreCase("Select an agent IP/Nickname"))
			valueField = "-1";
		if(valueField.equals(agentIP))
			selected="selected";
%>
							<option value="<%=valueField%>"<%=selected%>><b><%=dispField%></b></option>
<%
	}
%>
						<div></select>
					</td>
					<td style="width:25%" align="center">
						<select id="logdir" name="logdir" style="width:100%" onchange='JavaScript:changeLogDir();'>
<%
	Iterator dirListIter = logsDirMap.keySet().iterator();
	while(dirListIter.hasNext())
	{
		String dispField = (String)dirListIter.next();
		String valueField = (String)logsDirMap.get(dispField);
		String selected = "";
		if(valueField.equals(logFileDir))
			selected="selected";
%>

							<option value="<%=valueField%>"<%=selected%>><b><%=dispField%></b></option>
<%
	}
%>
						</select>
					</td>
					<td style="width:25%" align="right">
						<select id="logname" name="logname" onchange="javascript:changeLogFile();" style="width:100%">
<%
	for(int i=0;i<logFileList.size();i++)
	{
		String dispField = (String)logFileList.get(i);
		String valueField = dispField;
		String selected = "";
		if(dispField.equalsIgnoreCase("Select a log file"))
			valueField = "-1";
		if(valueField.equals(logFileName))
			selected="selected";
%>
									<option value="<%=valueField%>"<%=selected%> ><b><%=dispField%></b> </option>
<%
	}
%>
						</select>
					</td>
				</tr>
			</table>
			<table cellspacing="0" cellpadding="0" width="98%" style="border:0px solid green">
<%
	if(logFileName != null && !logFileName.equals("-1") && resultData.size()>1)
	{
%>
				<tr nowrap height="26">
					<td id="lst_modified" style="width:50%;text-align:left;font-weight:bold;font-size: 10px">
						<egui:intnl text='admin.manager.Last modified time'/> &nbsp;:&nbsp;<%=lastModified%>
					</td>
					<td style="width:50%" align="right">
						<button  id="refresh" style="border:0px" onclick="javascript:loadFile('refresh');" title="Refresh" class="iconRefresh"/>
						<button  id="download" style="border:0px;margin-left:10px" onclick="javascript:loadFile('download');" title="Download" class="iconDownload"/>
					</td>
				<tr>
<%
	}
%>
			</table>
			<table cellspacing="0" cellpadding="0" width="98.4%">
				<div id="loading_image" name="loading_image" class="eg_cellbgmedium linesquare" style="display:none;position:absolute;left:35%; top:50%;width:325px;height:80px">
					<img src='/final/admin/eg_images/loading-bar.gif' style="margin-top:10px" width='143' height='30' border='0'/>
					<center style="margin-top:5px"><label id="loadMsg"></label></center>
				</div>
				<div class="tableWidth linesquare">
					<iframe  id="logFrame" name="logFrame" src="/final/misc/EgAgentDebugMode.jsp?showAlert=<%=showAlert%>&alertMessage=<%=alertMessage%>" class="logFrame"  border="0" scrolling="hidden" scroll="no" marginwidth="0px" marginheight="0px" frameborder="0" color="blue" style="background-color:white;width:100%;height:100%;border-width:0px; border-style:solid;overflow:auto; border-color:grey"></iframe>
				<div>
			</table>
		</td>
	</tr>
</table>

</body>
</html>

<script language="javascript">
if('<%=isFilterEnabled%>' == 'true')
{
	$j('#searchBox').val('<%=searchStr%>');
}

$j('#searchBox').mouseout(function(){
	showElements('combo');
});

$j('#searchBox').keydown(function(event){
	if(event.key == 'Enter')
	{
		showElements('combo');
		getObj();
		var queryString = "sessionInUse=true&agentType="+selectedType;
		var searchStr = $j('#searchBox').val();
		if(searchStr != null && searchStr != '')
		{
			queryString += "&searchStr="+searchStr;
		}
		window.location.href="/final/misc/EgAgentLogView.jsp?"+queryString;
	}
});
</script>

<%!
	private boolean doesExist(List filterList, String agentIp)
	{
		Iterator searchItr = filterList.iterator();
		while(searchItr.hasNext())
		{
			String searchStr = (String)searchItr.next();
			if(agentIp.indexOf(searchStr)!=-1 || (agentIp.toLowerCase().indexOf(searchStr.toLowerCase()))!=-1)
				return true;
		}
		return false;
	}
%>


