<%
/*******************************************************************************
*	Name            :       EgConfigDescGroupsp.jsp
*	Purpose         :     
*******************************************************************************/
%>

<%@ page import="java.util.*" %>
<%@ include file="../../EgTrackerAJSON.jsp" %>
<%@ page import="com.egurkha.util.*" %>
<%@ page import="com.eg.EgServerGroupBean" %>
<%@ page import = "com.egurkha.admin.AuditLogThread"%>
<%@ page import = "com.eg.EgInstallInfo"%>
<%@ page import = "com.eg.IniFile"%>
<%@ page import = "com.eg.EgConfigFilesSync"%>
<%@ page import = "com.egurkha.util.StringUtils" %>
<%@ page import ="egurkha.EgDbAdapterUI"%>
<%@ page import ="com.eg.EgDbAdapterTypeUI"%>
<%@ page import="java.sql.*" %>
<%@ page import="com.eg.EgConfigInfo" %>
<%@ page import="com.eg.EgSpecsInfo"%>
<%@ 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" />

<%
	response.setHeader("Cache-Control","no-store");
	response.setHeader("Pragma","no-cache");
	response.setDateHeader("Expires", -1);
	response.setContentType("application/json");

%>

<%
	JSONObject rootJson = new JSONObject();
	EgServerGroupBean descGrp = new EgServerGroupBean();
	String ServerType = "";
	String url = "EgShowServerGroups.jsp";
	String group = request.getParameter("group");
	String prevGroup = request.getParameter("prevGroup");
	String mServers=request.getParameter("fmanage");
	String previouslyManaged = request.getParameter("pfmanage");
	String unManaged = request.getParameter("funmanage");
	//new ini entries starts here
	EgDbAdapterUI egDb;
	EgConfigInfo configInfo = new EgConfigInfo("manager");
	EgSpecsInfo specsInfo = new EgSpecsInfo("manager");
	ResultSet rs = null;
	String status ="";
	TreeSet allComps = new TreeSet();
	Hashtable ht = new Hashtable();
	ArrayList compWithInfoList = new ArrayList();
	ArrayList managedCompList = new ArrayList();
	ArrayList descThreshList = new ArrayList();
	ArrayList userThreshList = new ArrayList();
	ArrayList specificInfos = new ArrayList();
	ArrayList htKeyValues = new ArrayList();
	Vector preDataList = new Vector();
	Vector newDataList = new Vector();
	String subject = "THRESH_POLICY_MAPPING";
	String user_thresh = "USER_THRESHOLDS";
	String descr_thresh = "DESCRIPTOR_THRESHOLDS";
	String subjectVal = "Newtarget_Update_EgThresholdManager";
	prgBean.createFile("eg_thresholds.ini");
	String[] arrHostTests = specsInfo.getDefaultTestsForServer("Host_system");
	ArrayList hostLevelTests = null;
	if (arrHostTests != null)
	{
		hostLevelTests = new ArrayList(Arrays.asList(arrHostTests));
	}

	boolean isInfoBased = false;
	boolean isGroupAssociated = false;

	if(!StringUtils.isNull(group))
	{
		if (!StringUtils.isNull(prevGroup)  && !group.equals(prevGroup))
		{
			isGroupAssociated = descGrp.isServerGroupAndPolicyMapped(prevGroup);
			//preDataList = descGrp.getComponentNamesWithType(prevGroup);
		}
		else
		{
			isGroupAssociated = descGrp.isServerGroupAndPolicyMapped(group);
			preDataList = descGrp.getComponentNamesWithType(group);
		}
	}
	// get all group from INI;
	String[] subjects = descGrp.getServerGroups();
	Vector vec_group = new Vector();
	if(subjects != null && subjects.length > 0)
	{
		for(int i=0;i<subjects.length;i++)
		{
			vec_group.add(subjects[i]);
		}
	}

	/* 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 Component Groups");
	/* code for auditlog ends */

	if(vec_group != null && vec_group.size() > 0 && vec_group.contains(group))
	{
		Vector sess_vec = new Vector();
		sess_vec.add(_mapping.getTextDescription("admin.threshold.Add / Modify threshold component groups"));
		sess_vec.add(url);
		sess_vec.add(_mapping.getTextDescription("admin.threshold.Add / Modify threshold component groups"));
		sess_vec.add(_mapping.getTextDescription("admin.threshold.Your changes have been updated successfully")+".");
		session.putValue("vec_Results",sess_vec);

		ServerType = descGrp.getServerType(group);
		Vector v_group = descGrp.getComponentNames(group);
		if(v_group != null && v_group.size() > 0)
		{
			IniFile iniFileWr = EgConfigFilesSync.getInstance(EgInstallInfo.getInstallDir()+"/manager/config/eg_infogroup.ini");
			iniFileWr.deleteSubject(group);
			StringTokenizer stok = new StringTokenizer(mServers,",");
			while(stok.hasMoreTokens())
			{
				String s_compName = stok.nextToken();
				iniFileWr.setValue(group,ServerType+"#"+s_compName,s_compName);
			}
			iniFileWr.saveFile();
			EgConfigFilesSync.releaseInstance(iniFileWr);
			//descGrp.deleteGroupSection(group);
			//descGrp.setValueForGroupSection(ServerType,mServers,group);
			//descGrp.saveFile();
		}

		/* code for auditlog starts */
		ArrayList currentComponentList = new ArrayList();
		ArrayList currentComponents = new ArrayList();
		StringTokenizer st = new StringTokenizer(mServers,",");
		if(st.countTokens()>0)
		{
			while(st.hasMoreTokens())
			{
				String componentName = (String) st.nextToken();
				currentComponentList.add(componentName);
				if (componentName.endsWith(":NULL"))
					componentName = componentName.substring(0, componentName.indexOf(":"));
				currentComponents.add(componentName);
			}
		}
		ArrayList previousComponentList = new ArrayList();
		st = new StringTokenizer(previouslyManaged,",");
		if(st.countTokens()>0)
		{
			while(st.hasMoreTokens())
			{
				String componentName = (String) st.nextToken();
				previousComponentList.add(componentName);
				if (componentName.endsWith(":NULL"))
					componentName = componentName.substring(0, componentName.indexOf(":"));
				if(!currentComponents.contains(componentName))
					auditLogThread.setCurrentValue("Disassociated components",componentName);
				else
					currentComponents.remove(componentName);
			}
		}
		auditLogThread.setCurrentValue("01~~Component type","$ctype$:" + ServerType);
		for(int i=0;i<currentComponents.size();i++)
			auditLogThread.setCurrentValue("Associated components",(String) currentComponents.get(i));

		auditLogThread.setValue("Description","Threshold component group " + group +" has been modified");
		Collections.sort(currentComponentList);
		Collections.sort(previousComponentList);		
		boolean allowAuditLog = !currentComponentList.containsAll(previousComponentList);
		if(allowAuditLog)
			auditLogThread.sendItToDB();
		/* code for auditlog ends */
		newDataList = descGrp.getComponentNamesWithType(group);
	}
	else
	{
		Vector sess_vec = new Vector();
		sess_vec.add(_mapping.getTextDescription("admin.threshold.Add / Modify threshold component groups"));
		sess_vec.add(url);
		sess_vec.add(_mapping.getTextDescription("admin.threshold.Add / Modify threshold component groups"));
		sess_vec.add(_mapping.getTextDescription("admin.threshold.Your changes have been updated successfully")+".");
		session.putValue("vec_Results",sess_vec);
		ServerType = request.getParameter("server");
		if(StringUtils.isNull(ServerType))
			ServerType = (String) session.getAttribute("Server_Type");
		IniFile iniFileWr = EgConfigFilesSync.getInstance(EgInstallInfo.getInstallDir()+"/manager/config/eg_infogroup.ini");
		StringTokenizer stok = new StringTokenizer(mServers,",");
		while(stok.hasMoreTokens())
		{
			String s_compName = stok.nextToken();
			iniFileWr.setValue(group,ServerType+"#"+s_compName,s_compName);
		}

		if (!StringUtils.isNull(prevGroup))
		{
			//iniFileWr = EgConfigFilesSync.getInstance(EgInstallInfo.getInstallDir()+"/manager/config/eg_infogroup.ini");
			boolean isGroupAssociatedWithPolicy = descGrp.isServerGroupAndPolicyMapped(prevGroup);
			if (!isGroupAssociatedWithPolicy)
			{
				//descGrp.deleteGroupSection(prevGroup);
				iniFileWr.deleteSubject(prevGroup);
			}
			else
			{
				ArrayList associateList = descGrp.getAssociatedPolicyForServerGroup(prevGroup);
				if (associateList != null && associateList.size() > 0)
				{
					Vector deltmpVariable = new Vector();
					for (int i=0;i<associateList.size();i++)
					{
						String strAssociateLine = (String) associateList.get(i);
						String tmpVariable = strAssociateLine.substring(0,strAssociateLine.indexOf("="));
						String strVariable = group+"#"+tmpVariable.substring(tmpVariable.indexOf("#")+1);
						String tmpValue = strAssociateLine.substring(strAssociateLine.indexOf("=")+1);
						iniFileWr.setValue(subject,strVariable,tmpValue);
						deltmpVariable.add(tmpVariable);
						//iniFileWr.deleteValue(subject,tmpVariable);
					}
					iniFileWr.deleteValues(subject,deltmpVariable);
				}
	
				//descGrp.deleteGroupSection(prevGroup);
				iniFileWr.deleteSubject(prevGroup);
				descGrp.deleteServerGroup(subject,prevGroup);
			}
		}
		iniFileWr.saveFile();
		EgConfigFilesSync.releaseInstance(iniFileWr);
		
		newDataList = descGrp.getComponentNamesWithType(group);
		//descGrp.setValueForGroupSection(ServerType,mServers,group);
		//descGrp.saveFile();

		/* code for auditlog starts */
		auditLogThread.setCurrentValue("01~~Component type","$ctype$:" + ServerType);
		StringTokenizer st = new StringTokenizer(mServers,",");
		if(st.countTokens()>0)
		{
			while(st.hasMoreTokens())
			{
				String componentName = (String) st.nextToken();
				if (componentName.endsWith(":NULL"))
					componentName = componentName.substring(0, componentName.indexOf(":"));
				auditLogThread.setCurrentValue("Associated components",componentName);
			}
		}
		auditLogThread.setValue("Description","Threshold component group " + group + " has been created");
		auditLogThread.sendItToDB();
		/* code for auditlog ends */
	}

	if(isGroupAssociated)
	{
		Vector allPolicy = descGrp.getAllPolicy(subject);
		ArrayList managedPolicy = new ArrayList();
		ArrayList managedServers = new ArrayList();
		ArrayList ruleTests = new ArrayList();
		String query ="SELECT TEST_NAME,TRGT_HOST,PORT_NO,SITE_NAME,INFO,MSMT_HOST FROM MEASURE_LAST WHERE ";

		for(int i=0;i<allPolicy.size();i++)
		{
			String polData = (String) allPolicy.get(i);
			Vector managedGroups = descGrp.getServerGroupForPolicy(polData);
			if(managedGroups.contains(group))
			{
				managedPolicy.add(polData);
				ruleTests.add(descGrp.getTestNameForPolicy(polData));
			}
		}

		for(int pre=0;pre<preDataList.size();pre++)
		{
			String previousData = (String) preDataList.get(pre);
			if(!newDataList.contains(previousData))
			{
				managedServers.add(previousData);
			}
		}
		for(int n=0;n<newDataList.size();n++)
		{
			String recentData = (String) newDataList.get(n);
			if(!preDataList.contains(recentData))
			{
				managedServers.add(recentData);
			}
		}

		String[] userThreshVal = prgBean.getVariables(user_thresh);
		if(userThreshVal.length > 0)
		{
			for(int t=0; t<ruleTests.size(); t++)
			{
				String testNameVal = (String) ruleTests.get(t);
				for(int r=0; r<userThreshVal.length; r++)
				{
					if(userThreshVal[r].startsWith(testNameVal))
					{
						userThreshList.add(userThreshVal[r]);
					}
				}
			}
		}

		String []descThreshVal = prgBean.getVariables(descr_thresh);
		if(descThreshVal.length > 0)
		{
			for(int t=0; t<ruleTests.size(); t++)
			{
				String testNameVal = (String) ruleTests.get(t);
				for(int r=0; r<descThreshVal.length; r++)
				{
					if(descThreshVal[r].startsWith(testNameVal))
					{
						descThreshList.add(descThreshVal[r]);
					}
				}
			}
		}
		if(managedServers != null && managedServers.size() > 0)
		{
			IniFile serIniWr = EgConfigFilesSync.getInstance(EgInstallInfo.getInstallDir()+"/manager/config/eg_threshupdate.ini");
			boolean isSaveIni = false;

			if(ruleTests != null && ruleTests.size() == 1)
			{
				query +="TEST_NAME='"+(String)ruleTests.get(0)+"'" ;
			}
			else
			{
				for(int r=0;r<ruleTests.size();r++)
				{
					query +="TEST_NAME='"+(String)ruleTests.get(r)+"'";
					if (r != ruleTests.size()-1)
					{
						query += " OR ";
					}
				}
			}
			egDb=EgDbAdapterTypeUI.getObject();
			try
			{
				boolean isConnected = false;
				status = egDb.setConnection();
				if(status.equals("CONNECTED"))
				{
					isConnected = true;
				}
				if(isConnected)
				{
					rs = egDb.SelectExec(query);
					while(rs.next())
					{
						String testVal = rs.getString(1);
						String hostVal = rs.getString(2);
						String portVal = rs.getString(3);
						String siteVal = rs.getString(4);
						String infoVal = rs.getString(5);
						String msmthostVal = rs.getString(6);
						String updateDbData = hostVal+"#&#"+portVal+"#&#"+siteVal+"#&#"+StringUtils.encodeSecurityChar(infoVal)+"#&#"+msmthostVal+"#&#"+testVal;
						int r = infoVal.indexOf(EgConfigInfo.infoFieldSeparator);
						ht.put(hostVal+":"+portVal+"#"+infoVal+"#"+testVal+"#"+msmthostVal,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);
				}
			}

			for(int ct = 0;ct<managedServers.size();ct++)
			{
				String compWithInfo = (String)managedServers.get(ct);
				String tempComp = compWithInfo.substring(compWithInfo.indexOf("#")+1);
				String 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);
						}
						String htVal = (String) ht.get(htKey);
						String testName = htVal.substring(htVal.lastIndexOf("#&#")+3);
						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)) || (descThreshList != null && (descThreshList.contains(strDescVal) || descThreshList.contains(strGrpDescVal))))
								{
									continue;
								}
								//else if(descThreshList != null && descThreshList.contains(strDescVal))
								//{
								//	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)) || (descThreshList != null && (descThreshList.contains(strDescVal) || descThreshList.contains(strGrpDescVal))))
								{
									continue;
								}
								//else if(descThreshList != null && descThreshList.contains(strDescVal))
								//{
								//	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());
%>
