<%@ include file="../../EgTrackerAJSON.jsp" %>
<%@ page import = "java.util.*" %>
<%@ page import="java.sql.*" %>
<%@ page import = "java.lang.*" %>
<%@ page import="com.eg.EgInstallInfo"%>
<%@ page import="com.eg.EgMappingInfo"%>
<%@ page import="com.eg.IniFile" %>
<%@ page import = "com.egurkha.ini.IniUI"%>
<%@ page import = "com.eg.EgConfigFilesSync"%>
<%@ page import = "com.egurkha.admin.AuditLogThread"%>
<%@ page import = "com.egurkha.util.StringUtils"%>
<%@ page import ="egurkha.EgDbAdapterUI"%>
<%@ page import ="com.eg.EgDbAdapterTypeUI"%>
<%@ page import="com.eg.UpdateAndTransmitTrendInfo" %>
<%@ page import="com.eg.EgTesterInfo" %>
<%@ page import="com.eg.EgDateInfo" %>
<%@ page import="com.eg.EgDbInfo" %>
<%@ page import="com.eg.EgThresholdInfo" %>
<%@ page import="com.eg.EgSpecsInfo" %>
<%@ page import="com.eg.EgConfigInfo" %>
<%@ page import="com.eg.EgDiscInfo" %>
<%@ page import="com.eg.EgDiscInfo2" %>
<%@ page import="com.eg.EgServerGroupBean" %>
<%@ page import="net.sf.json.*"%>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>

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

<%
	JSONObject rootJson = new JSONObject();
	IniUI iniUI = IniUI.getInstance();
	//user language
	String userLanguage = iniUI.getDefaultLanguage();
	EgDbAdapterUI egDb;
	EgDateInfo dat=new EgDateInfo();
	EgDbInfo dbInfo=new EgDbInfo("manager");
	EgThresholdInfo dbThresh =new EgThresholdInfo("manager");
	EgTesterInfo testerInfo =new EgTesterInfo("manager");
	EgSpecsInfo egSpecs = new EgSpecsInfo("manager");
	EgDiscInfo2 discInfo2 = new EgDiscInfo2("manager");
	EgConfigInfo configInfo = new EgConfigInfo("manager");
	EgServerGroupBean descGrpp = new EgServerGroupBean();


	ResultSet rs = null;
	String status ="";
	ArrayList compWithInfoList = new ArrayList();
	ArrayList managedCompList = new ArrayList();
	ArrayList descThreshList = new ArrayList();
	ArrayList userThreshList = new ArrayList();
	ArrayList specificInfos = new ArrayList();
	ArrayList htKeyValues = new ArrayList();

	Hashtable ht = new Hashtable();
	String subjectVal = "Newtarget_Update_EgThresholdManager";

	if (_user != null)
	{
		userLanguage = _user.getLanguage();
	}
	EgMappingInfo mappingInfo = new EgMappingInfo(userLanguage);
	String operation = request.getParameter("operation");
	String que="";
	String measUpdate="";
	String threshUpdate="";
	String minUpdate="";
	String maxUpdate="";
	String currentTime="";
	String threshTable="";
	String trgtHost="";
	String port="";
	String startTime="";
	Vector host = new Vector();
	Vector sid = new Vector();
	String user_thresh = "USER_THRESHOLDS";
	String descr_thresh = "DESCRIPTOR_THRESHOLDS"; // SIFY
	String policySubject = "THRESHOLDPOLICIES";
	StringTokenizer st1 = null;

	long tim = 0l;
	long current = 0l;
	String time="";
	String measur="";
	if (!StringUtils.isNull(operation) && operation.equals("alarmPolicyDesc"))
	{
		String alarmPolicy = request.getParameter("alarmPolicy");
		IniFile thresholdsIni = new IniFile(EgInstallInfo.getInstallDir()+"/manager/config/eg_thresholds.ini");
		String strDescription = thresholdsIni.getValue("ALARM_POLICY",alarmPolicy);
		int i_idx = strDescription.indexOf(",");
		String windowSize = strDescription.substring(0,i_idx);
		String numCrossings = strDescription.substring(i_idx+1);
		if (windowSize.equals("1") && numCrossings.equals("1"))
		{
			out.println(numCrossings + " threshold violation out of " + windowSize + " measurement");
		}
		else
		{
			out.println(numCrossings + " threshold violations out of " + windowSize + " measurements");
		}
	}
	else if (!StringUtils.isNull(operation) && operation.equals("newRuleName"))
	{
		String s_policyName = request.getParameter("policyName");
		if(!StringUtils.isNull(s_policyName))
		{
			s_policyName = StringUtils.decodeSecurityChar(s_policyName);
		}

		String testName = request.getParameter("testName");
		IniFile infoGroupIniWrite = EgConfigFilesSync.getInstance(EgInstallInfo.getInstallDir()+"/manager/config/eg_infogroup.ini");
		IniFile defaultIni = new IniFile(EgInstallInfo.getInstallDir()+"/manager/config/eg_thresholds.ini");
		String defaultThreshold = defaultIni.getValue("DEFAULT_THRESHOLDS",testName);
		String variable = testName+":"+s_policyName;
		session.setAttribute("grpPolicyName",s_policyName);

		/* code for auditlog starts */
		AuditLogThread auditLogThread = new AuditLogThread();	
		auditLogThread.setValue("Category","Admin");
		auditLogThread.setValue("User_id",_user.getLoginID());
		auditLogThread.setValue("Host_ip",_user.getUserIP(session.getId()));
		auditLogThread.setValue("Session_id",session.getId());
		auditLogThread.setValue("Module","Thresholds");
		auditLogThread.setValue("Activity","Threshold Rules");
		auditLogThread.setValue("Description","Threshold rule (" + s_policyName+") has been created");
		auditLogThread.sendItToDB();
		/* code for auditlog ends */

		infoGroupIniWrite.setValue(policySubject,variable,defaultThreshold);
		infoGroupIniWrite.saveFile();
		EgConfigFilesSync.releaseInstance(infoGroupIniWrite);
		rootJson.put("successUpdate",true);
	}
	else if(!StringUtils.isNull(operation) && operation.equals("updateThresholds"))
	{
		//String strComponentType = request.getParameter("componentType");
		String strPolicyName = request.getParameter("policyName");
		if(!StringUtils.isNull(strPolicyName))
		{
			strPolicyName = StringUtils.decodeSecurityChar(strPolicyName);
		}
		String testName = request.getParameter("testName");
		String threshold = request.getParameter("threshold");
		String variable = testName+":"+strPolicyName;
		String measure = threshold.substring(0,threshold.indexOf(":"));
		measure+=":";
		String newDefaultThreshold = "";
		StringBuffer strbuffer = new StringBuffer();
		IniFile infoGroupIni = new IniFile(EgInstallInfo.getInstallDir()+"/manager/config/eg_infogroup.ini");
		String prevThresholdValues = infoGroupIni.getValue(policySubject,variable);
		ArrayList previousValues = new ArrayList();
		StringTokenizer st = new StringTokenizer(prevThresholdValues,",");
		while (st.hasMoreTokens())
		{
			String strTok = st.nextToken();
			previousValues.add(strTok);
			if (strTok.startsWith(measure))
			{
				strbuffer.append(threshold).append(",");
			}
			else
			{
				strbuffer.append(strTok).append(",");
			}
		}
		/* code for auditlog starts */

		AuditLogThread auditLogThread = new AuditLogThread();	
		auditLogThread.setValue("Category","Admin");
		auditLogThread.setValue("User_id",_user.getLoginID());
		auditLogThread.setValue("Host_ip",_user.getUserIP(session.getId()));
		auditLogThread.setValue("Session_id",session.getId());
		auditLogThread.setValue("Module","Thresholds");

		for(int i=0;i<previousValues.size();i++)
		{
			String preData = (String) previousValues.get(i);
			if(preData.startsWith(measure))
			{
				ArrayList tempPrevious = StringUtils.egTokenizer(preData,":");
				ArrayList tempCurrent = StringUtils.egTokenizer(threshold,":");

				String auditMeasure = "$measure$:"+testName+":"+tempPrevious.get(0).toString().trim();;
				String previousMin = tempPrevious.get(2).toString().trim();
				String previousMax = tempPrevious.get(3).toString().trim();
				String alarmPolicyPrevious = tempPrevious.get(4).toString().trim();

				String currentMin = tempCurrent.get(2).toString().trim();
				String currentMax = tempCurrent.get(3).toString().trim();
				String alarmPolicyCurrent = tempCurrent.get(4).toString().trim();

				if(!previousMin.equals(currentMin))
				{
					if(previousMin.equals("-1"))
					{
						previousMin = "none";
					}
					if(currentMin.equals("-1"))
					{
						currentMin = "none";
					}
					auditLogThread.setPreviousValue(auditMeasure,"Minimum-Threshold " + previousMin);
					auditLogThread.setCurrentValue(auditMeasure,"Minimum-Threshold " + currentMin);
				}

				if(!previousMax.equals(currentMax))
				{
					if(previousMax.equals("-1"))
					{
						previousMax = "none";
					}
					if(currentMax.equals("-1"))
					{
						currentMax = "none";
					}
					auditLogThread.setPreviousValue(auditMeasure,"Maximum-Threshold " + previousMax);
					auditLogThread.setCurrentValue(auditMeasure,"Maximum-Threshold " + currentMax);
				}

				if(!alarmPolicyPrevious.equals(alarmPolicyCurrent))
				{
					auditLogThread.setPreviousValue(auditMeasure,"Alarms " + alarmPolicyPrevious);
					auditLogThread.setCurrentValue(auditMeasure,"Alarms " + alarmPolicyCurrent);
				}
			}
		}
		auditLogThread.setValue("Activity","Threshold Rules");
		if (!StringUtils.isNull(strPolicyName))
		{
			auditLogThread.setValue("Description","Threshold rule (" + strPolicyName + ") has been modified");
		}
		auditLogThread.sendItToDB();
		/* code for auditlog ends */
		
		/* code for new ini entries starts */
		Vector managedServers = descGrpp.getServerGroupForPolicy(strPolicyName);
		TreeSet managedServersInfos = descGrpp.getManagedInfosForPolicy(strPolicyName);
		String[] arrHostTests = egSpecs.getDefaultTestsForServer("Host_system");
		ArrayList hostLevelTests = null;
		if (arrHostTests != null)
		{
			hostLevelTests = new ArrayList(Arrays.asList(arrHostTests));
		}

		if(managedServers != null && managedServers.size() > 0)
		{

			for(int c=0;c<managedServers.size();c++)
			{
				String tmpComp = (String) managedServers.get(c);
				Vector vecComp = descGrpp.getComponentNamesWithType(tmpComp);
				for(int i=0;i<vecComp.size();i++)
				{
					String cmpData = (String) vecComp.get(i);
					String tmpCompData = "";
					if(hostLevelTests.contains(testName))
					{
						tmpCompData = cmpData.substring(cmpData.indexOf("#")+1);
						tmpCompData = tmpCompData.substring(0,tmpCompData.indexOf(":"));
						tmpCompData +=":NULL";
					}
					else
					{
						tmpCompData = cmpData.substring(cmpData.indexOf("#")+1);
					}
					managedCompList.add(tmpCompData);
				}
			}

			if(managedServersInfos != null && managedServersInfos.size() > 0)
			{
				Iterator itr1 = managedServersInfos.iterator();
				while(itr1.hasNext())
				{
					String itrData = (String) itr1.next();
					if(!specificInfos.contains(itrData))
					{
						specificInfos.add(itrData);
					}
				}

				//for(int si=0;si<specificInfos.size();si++)
				//{
				//	String descInfoData = (String) specificInfos.get(si);
					if(managedCompList != null && managedCompList.size() > 0)
					{
						for(int a=0;a<managedCompList.size();a++)
						{
							String compData = (String) managedCompList.get(a);
							String tmpComp = "";
							if(hostLevelTests.contains(testName))
							{
								tmpComp = compData.substring(0,compData.indexOf(":"));
								tmpComp +=":NULL";
							}
							else
							{
								tmpComp = compData;
							}

							if(!descGrpp.isServerAssociatedToTest(compData,testName) && descGrpp.isServerAssociatedToTestUI(compData,testName))
							{
								if(specificInfos != null && specificInfos.size() > 0)
								{
									for(int v=0;v<specificInfos.size();v++)
									{
										String vecInfo = (String) specificInfos.get(v);
										compWithInfoList.add(tmpComp+"#"+vecInfo);
									}
								}
							}
							//compWithInfoList.add(compData+"#"+descInfoData);
						}
					}
				//}
			}
			//else
			//{
				if(managedCompList != null && managedCompList.size() > 0)
				{
						for(int a=0;a<managedCompList.size();a++)
						{
							String compData = (String) managedCompList.get(a);
							String tmpComp = "";
							if(hostLevelTests.contains(testName))
							{
								tmpComp = compData.substring(0,compData.indexOf(":"));
								tmpComp +=":NULL";
							}
							else
							{
								tmpComp = compData;
							}

							if(descGrpp.isServerAssociatedToTest(compData,testName))
							{
								compWithInfoList.add(tmpComp);
								continue;
							}
						}

					//compWithInfoList.addAll(managedCompList);
				}
			//}
			egDb=EgDbAdapterTypeUI.getObject();
			try
			{
				boolean isConnected = false;
				status = egDb.setConnection();
				if(status.equals("CONNECTED"))
				{
					isConnected = true;
				}
				if(isConnected)
				{
					String query ="SELECT TRGT_HOST,PORT_NO,SITE_NAME,INFO,MSMT_HOST FROM MEASURE_LAST WHERE TEST_NAME='"+testName+"'" ;
					rs = egDb.SelectExec(query);
					while(rs.next())
					{
						String hostVal = rs.getString(1);
						String portVal = rs.getString(2);
						String siteVal = rs.getString(3);
						String infoVal = rs.getString(4);
						String msmthostVal = rs.getString(5);

						String updateDbData = hostVal+"#&#"+portVal+"#&#"+siteVal+"#&#"+StringUtils.encodeSecurityChar(infoVal)+"#&#"+msmthostVal+"#&#"+testName;
						int r = infoVal.indexOf(EgConfigInfo.infoFieldSeparator);

						String str_info = "";
						String sidVal = "";
						if(r != -1)
						{
							str_info = infoVal.substring(r+1).trim();
							sidVal = infoVal.substring(0,r);
						}
						if(StringUtils.isNull(sidVal))
						{
							ht.put(hostVal+":"+portVal+"#"+str_info+"#"+msmthostVal,updateDbData);
						}
						else
						{
							ht.put(hostVal+":"+portVal+":"+sidVal+"#"+infoVal+"#"+msmthostVal,updateDbData);

						}

						//ht.put(hostVal+":"+portVal+"#"+infoVal,updateDbData);

					}
				}
				rs.close();
				egDb.releaseConnection(false);
				EgDbAdapterTypeUI.releaseObject(egDb);
			}
			catch(Exception e)
			{
				if(rs != null)
				{
					rs.close();
				}
				egDb.releaseConnection(true);
				EgDbAdapterTypeUI.releaseObject(egDb);
			}
			if(ht != null && ht.size() > 0)
			{
				Iterator iterAll = ht.keySet().iterator();
				while(iterAll.hasNext())
				{
					String tempKeys = (String) iterAll.next();
					htKeyValues.add(tempKeys);
				}
			}
		}

		prgBean.createFile("eg_thresholds.ini");
		String[] userThreshVal = prgBean.getVariables(user_thresh);
		if(userThreshVal.length > 0)
		{
			for(int r=0; r<userThreshVal.length; r++)
			{
				if(userThreshVal[r].startsWith(testName))
				{
					userThreshList.add(userThreshVal[r]);
				}
			}
		}
		String []descThreshVal = prgBean.getVariables(descr_thresh);
		if(descThreshVal.length > 0)
		{
			for(int r=0; r<descThreshVal.length; r++)
			{
				if(descThreshVal[r].startsWith(testName))
				{
					descThreshList.add(descThreshVal[r]);
				}
			}
		}
		newDefaultThreshold = strbuffer.toString();
		int len = newDefaultThreshold.length()-1;
		newDefaultThreshold = newDefaultThreshold.substring(0,len);

		String strGroupThreshIni = EgInstallInfo.getInstallDir()+"/manager/config/eg_infogroup.ini";
		IniFile groupThreshIniWrite = EgConfigFilesSync.getInstance(strGroupThreshIni);
		groupThreshIniWrite.setValue(policySubject,variable,newDefaultThreshold);
		groupThreshIniWrite.saveFile();
		EgConfigFilesSync.releaseInstance(groupThreshIniWrite);

		if(managedServers != null && managedServers.size() > 0)
		{
			boolean isSaveIni = false;
			IniFile serIniWr = EgConfigFilesSync.getInstance(EgInstallInfo.getInstallDir()+"/manager/config/eg_threshupdate.ini");
			for(int ct = 0;ct<compWithInfoList.size();ct++)
			{
				String compWithInfo = (String)compWithInfoList.get(ct);
				String tempComp = "";
				String tmpTrgtHost = "";
				String tmpInfo = "";
				if(compWithInfo.indexOf("#") != -1)
				{
					tempComp = compWithInfo.substring(0,compWithInfo.indexOf("#"));
					tmpTrgtHost = tempComp.substring(0,tempComp.indexOf(":"));
					tmpInfo = compWithInfo.substring(compWithInfo.indexOf("#")+1);

				}
				else
				{
					tempComp = compWithInfo;
					tmpTrgtHost = tempComp.substring(0,tempComp.indexOf(":"));

				}

				if(ht != null && ht.size() > 0)
				{
					for(int h=0;h<htKeyValues.size();h++)
					{
						String htKey = (String) htKeyValues.get(h);
						String infoData = htKey.substring(htKey.indexOf("#")+1);
						infoData = infoData.substring(0,infoData.indexOf("#"));
						int r = infoData.indexOf(EgConfigInfo.infoFieldSeparator);
						String str_info="";
						String sidVal="";
						if(r != -1)
						{
							str_info = infoData.substring(r+1).trim();
							sidVal = infoData.substring(0,r);
						}

						if(htKey.startsWith(tmpTrgtHost))
						{

							if(hostLevelTests.contains(testName))
							{
								String strUserVal = testName+":"+tmpTrgtHost;
								String nickWithNullPort = tmpTrgtHost+":NULL";
								String strDescVal = testName+":"+nickWithNullPort+"#"+StringUtils.encodeSecurityChar(str_info);
								String strGrpDescVal = testName+":"+nickWithNullPort+"#"+str_info;
								if(userThreshList != null && userThreshList.contains(strUserVal))
								{
									break;
								}
								else if(descThreshList != null && (descThreshList.contains(strDescVal) || descThreshList.contains(strGrpDescVal)))
								{
									continue;
								}
								else
								{
									if(compWithInfo.indexOf("#") != -1)
									{
										if(!StringUtils.isNull(tmpInfo) && tmpInfo.equals(str_info))
										{
											String htValues = (String) ht.get(htKey);
											isSaveIni = true;
											serIniWr.setValue(subjectVal,htValues,testName);
										}
										else
										{
											continue;
										}
									}
									else
									{
										String htValues = (String) ht.get(htKey);
										isSaveIni = true;
										serIniWr.setValue(subjectVal,htValues,testName);
									}
								}
							}
							else
							{
								String strUserVal = testName+":"+tempComp;
								String strDescVal = testName+":"+tempComp+"#"+StringUtils.encodeSecurityChar(str_info);
								String strGrpDescVal = testName+":"+tempComp+"#"+str_info;
								if(userThreshList != null && userThreshList.contains(strUserVal))
								{
									break;
								}
								else if(descThreshList != null && (descThreshList.contains(strDescVal) || descThreshList.contains(strGrpDescVal)))
								{
									continue;
								}
								else
								{
									if(compWithInfo.indexOf("#") != -1)
									{
										if(htKey.startsWith(tempComp) && !StringUtils.isNull(tmpInfo) && tmpInfo.equals(str_info))
										{
											String htValues = (String) ht.get(htKey);
											isSaveIni = true;
											serIniWr.setValue(subjectVal,htValues,testName);
										}
										else
										{
											continue;
										}
									}
									else if(htKey.startsWith(tempComp))
									{
										String htValues = (String) ht.get(htKey);
										isSaveIni = true;
										serIniWr.setValue(subjectVal,htValues,testName);
									}
								}
							}
						}
					}
				}
			}
			if(isSaveIni)
			{
				serIniWr.saveFile();
			}
			EgConfigFilesSync.releaseInstance(serIniWr);
		}
		rootJson.put("successUpdate",true);
	}

	out.println(rootJson.toString());
%>

<%!

	public ArrayList getAllManagedComps()
	{
		ArrayList aListPorts = new ArrayList();
		EgDiscInfo2 discInfo2 = new EgDiscInfo2("manager");
		List allHosts = discInfo2.getAllManagedComponents();
		for (int i=0;i<allHosts.size();i++)
		{
			String strTemp = "";
			String allData = (String)allHosts.get(i);
			StringTokenizer st = new StringTokenizer(allData,",");
			String serType = st.nextToken();
			String ipVal = st.nextToken();
			String nick = "";
			String port = "";
			String sid = "";
			if(serType.equals("Oracle_server"))
			{
				nick = st.nextToken();
				port = st.nextToken();
				String isPassive = st.nextToken();
				if (!st.hasMoreTokens())
					continue;
				sid = st.nextToken();
				strTemp = nick+":"+port+":"+sid;
			}
			else
			{
				nick = st.nextToken();
				port = st.nextToken();
				strTemp = nick+":"+port;
			}
			aListPorts.add(strTemp);
		}
		return aListPorts;
	}
%>