<%@ include file="../../EgTrackerAJSON.jsp" %>
<%@ page import = "net.sf.json.*"%>
<%@ page import="com.eg.*"%>
<%@ page import="com.egurkha.util.StringUtils"%>
<%@ page import="com.egurkha.admin.AuditLogThread"%>
<%@ page import="egurkha.TestBean"%>
<%@ page import="egurkha.EgTestParamBean"%>
<%@ page import="egurkha.EgUIUtils"%>
<%@ page import="java.io.File"%>
<%@ page import="java.util.*"%>
<%@ page language="java" contentType="application/json; charset=UTF-8" pageEncoding="UTF-8" %>

<%
	response.setContentType("application/json;charset=UTF-8");
	JSONObject rootJson = new JSONObject();
	JSONObject operationStatus = new JSONObject();
	boolean errorOccured = false;

	String test = request.getParameter("test");
	String aggTest = request.getParameter("aggTest");
	String operation = request.getParameter("operation");
	String measuresFunctions = request.getParameter("measureNames");
	if(measuresFunctions != null)
	{
		measuresFunctions = EgUIUtils.decodeSecurityChar(measuresFunctions);
	}
	String test_description = EgUIUtils.decodeSecurityChar(request.getParameter("add_modify_test_description"));
	String selectedCompType = request.getParameter("component_types");
	String pct_unit_measures = request.getParameter("pctdetails");
	
	if(selectedCompType == null || selectedCompType.trim().equalsIgnoreCase("null") || selectedCompType.trim().length()==0)
		selectedCompType = "";

	EgAggregateInfo aggregateInfo = new EgAggregateInfo("manager");
	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","Add/Modify Aggregate Test");

	if(operation != null && !StringUtils.isNull(aggTest))
	{
		Vector existingAggTests=aggregateInfo.getAggregateTests();
		if(existingAggTests != null && existingAggTests.size()>0)
		{
			if(operation.equalsIgnoreCase("addMeasures"))
			{
				boolean testFound = false;
				for(int i=0;i<existingAggTests.size();i++)
				{
					String tmp = (String)existingAggTests.get(i);
					if(tmp.equalsIgnoreCase(aggTest))
					{
						testFound = true;
						break;
					}
				}
				if(testFound)
				{
					auditLogThread.setValue("Activity","Add Aggregate Test");
					auditLogThread.setValue("Description","$test$:"+aggTest + " can not be added as it already exists");
					auditLogThread.sendItToDB();
					//aggregateInfo.saveFile();
					operationStatus.put("errormessage",_mapping.getTextDescription("admin.error.You are trying to add a test which is already existing")+".");
					rootJson.put("operationStatus",operationStatus);
					errorOccured = true;
				}
				else
				{
					IniFile agglang = new IniFile(EgInstallInfo.getInstallDir()+"/manager/config/eg_aggregate_lang_en_US.ini");
					Vector testNameMapping = agglang.getAllValues("TEST_NAME_MAPPING");
					if(testNameMapping != null && testNameMapping.size()>0)
					{
						for(int i=0;i<testNameMapping.size();i++)
						{
							if(testNameMapping.get(i).toString().trim().toLowerCase().equals(test_description.trim().toLowerCase()))
							{
								auditLogThread.setValue("Activity","Add Aggregate Test");
								auditLogThread.setValue("Description","$test$:"+aggTest + " can not be added as its display name already exists");
								auditLogThread.sendItToDB();
								operationStatus.put("errormessage",_mapping.getTextDescription("admin.error.You are trying to add a test display name which is already existing")+".");
								rootJson.put("operationStatus",operationStatus);
								errorOccured = true;
								break;
							}
						}
					}
				}
			}
			else
			{
				IniFile agglang = new IniFile(EgInstallInfo.getInstallDir()+"/manager/config/eg_aggregate_lang_en_US.ini");
				Vector testNames = agglang.getVariables("TEST_NAME_MAPPING",true);
				Vector testNameMapping = agglang.getAllValues("TEST_NAME_MAPPING");
				if(testNameMapping != null && testNameMapping.size()>0)
				{
					for(int i=0;i<testNameMapping.size();i++)
					{
						String thisAggTest = (String)testNames.get(i);
						String thisAggTestDescName = (String)testNameMapping.get(i);
						if(thisAggTestDescName.toString().trim().toLowerCase().equals(test_description.trim().toLowerCase()) && !aggTest.equals(thisAggTest))
						{
							auditLogThread.setValue("Activity","Add Aggregate Test");
							auditLogThread.setValue("Description","$test$:"+aggTest + " can not be modified as test display name is already assigned to " + thisAggTestDescName);
							auditLogThread.sendItToDB();
							operationStatus.put("errormessage",_mapping.getTextDescription("admin.error.Test display name has already been assigned to")+" "+thisAggTestDescName+"." + _mapping.getTextDescription("admin.error.Please choose a new name")+".");
							rootJson.put("operationStatus",operationStatus);
							errorOccured = true;
							break;
						}
					}
				}
			}
		}
	}
	if(!errorOccured && !StringUtils.isNull(test) && !StringUtils.isNull(aggTest) && !StringUtils.isNull(measuresFunctions))
	{
		Hashtable fnMapping = new Hashtable();
		fnMapping.put("avg",_mapping.getTextDescription("admin.common.avg"));
		fnMapping.put("avg_sum",_mapping.getTextDescription("admin.common.avg_sum"));
		fnMapping.put("min",_mapping.getTextDescription("admin.common.min"));
		fnMapping.put("max", _mapping.getTextDescription("admin.common.max"));
		fnMapping.put("sum",_mapping.getTextDescription("admin.common.sum"));
		fnMapping.put("condition",_mapping.getTextDescription("admin.common.condition"));
		fnMapping.put("multi-condition",_mapping.getTextDescription("admin.common.multi-condition"));
		fnMapping.put("multi_condition",_mapping.getTextDescription("admin.common.multi-condition"));

		String dbColumnSize = "Number(20,4)";
		TestBean testBean = new TestBean(true);
		EgThresholdInfo threshConfig = new EgThresholdInfo("manager");
		ArrayList existingMeasures = new ArrayList();
		ArrayList existingAggMeasures = new ArrayList();
		String temp_measures[] = threshConfig.getMeasurementsForTest(test);
		String temp_agg_measures[] = threshConfig.getMeasurementsForTest(aggTest);
		if(temp_measures != null && temp_measures.length>0)
		{
			existingMeasures = new ArrayList(Arrays.asList(temp_measures));
		}
		if(temp_agg_measures != null && temp_agg_measures.length>0)
		{
			existingAggMeasures = new ArrayList(Arrays.asList(temp_agg_measures));
		}
		Hashtable pctHt = null;
		if(pct_unit_measures != null && pct_unit_measures.trim().length()>0 && !pct_unit_measures.trim().equalsIgnoreCase("null"))
		{
			pctHt = new Hashtable();
			String array[]=StringUtils.getTokens(pct_unit_measures,",");
			for(int i=0;i<array.length;i++)
			{
				String s = array[i];
				int idx = s.indexOf(":");
				String pct_measure = s.substring(0,idx);
				String related_measures = s.substring(idx+1);
				pctHt.put(pct_measure,related_measures);
			}
		}
		boolean portBased =new EgSpecsInfo("manager").isPortRelevantForTest(test);
		String measureFunction[] = StringUtils.getTokens(measuresFunctions,"$");
		String descriptorAggregation = request.getParameter("descriptorAggregation_New");
		if(descriptorAggregation == null || (descriptorAggregation=descriptorAggregation.trim()).length()==0 || descriptorAggregation.equalsIgnoreCase("null"))
		{
			descriptorAggregation="false";
		}
		//descriptorAggregation value should be either true or false
		if(descriptorAggregation.toLowerCase().equals("true") || descriptorAggregation.toLowerCase().equals("yes"))
		{
			descriptorAggregation="true";
		}
		else
		{
			descriptorAggregation="false";
		}
		if(operation != null && (operation.equalsIgnoreCase("addMeasures") || operation.equalsIgnoreCase("appendMeasures")) && existingMeasures.size()>0)
		{
			EgDbaseInfo dbaseInfo = new EgDbaseInfo("manager");
			if(dbaseInfo.isTableExistInDB(aggTest))
			{
				String sep = System.getProperty("file.separator");
				String dbServType = new EgDbInfo("manager").checkDBType();
				if(dbServType != null && dbServType.equals("EgMsSqlAdapter"))
				{
					String queryDir = EgInstallInfo.getInstallDir()+sep+"bin"+sep+"database"+sep+"mssql"+sep+"Aggregate_Test_Query";
					File dir = new File(queryDir);
					if(dir.isDirectory())
					{
						File queryFile = new File(queryDir+sep+aggTest+".txt");
						if(queryFile.exists())
						{
							queryFile.delete();
						}
					}
				}
				else
				{
					String queryDir = EgInstallInfo.getInstallDir()+sep+"bin"+sep+"database"+sep+"Aggregate_Test_Query";
					File dir = new File(queryDir);
					if(dir.isDirectory())
					{
						File queryFile = new File(queryDir+sep+aggTest+".txt");
						if(queryFile.exists())
						{
							queryFile.delete();
						}
					}
				}
				/* deleting existing entries from [DYN_TABLES] of eg_dbase.ini */
				dbaseInfo.removeDynamicTable(aggTest);

				/* deleting existing entries from [MEASUREMENT_DB_MAPPING] of eg_db.ini */
				IniFile dbFilePtrWr = EgConfigFilesSync.getInstance(EgInstallInfo.getInstallDir()+"/manager/config/eg_db.ini");
				for(int i=0;i<existingAggMeasures.size();i++)
				{
					String e_measure = (String)existingAggMeasures.get(i);
					dbFilePtrWr.deleteValue("MEASUREMENT_DB_MAPPING", aggTest +":"+ e_measure);
					dbFilePtrWr.deleteValue("MEASUREMENT_DB_MAPPING", aggTest +":"+ e_measure + ":state");
				}
				dbFilePtrWr.saveFile();
				EgConfigFilesSync.releaseInstance(dbFilePtrWr);
			}
			Vector addAggMeasures = new Vector();
			String normalMeasure = null;
			for(int i=0;i<measureFunction.length;i++)
			{
				normalMeasure = measureFunction[i].substring(0,measureFunction[i].indexOf(":"));
				if(existingAggMeasures != null && !existingAggMeasures.contains(normalMeasure))
				{
					addAggMeasures.add(measureFunction[i]);
				}
			}
			if(addAggMeasures != null && addAggMeasures.size()>0)
			{
				auditLogThread.setCurrentValue("01~~Aggregate test display name",test_description);
				if(descriptorAggregation.equalsIgnoreCase("true")) {
					auditLogThread.setCurrentValue("02~~Report by descriptors","No");
				}
				else {
					auditLogThread.setCurrentValue("02~~Report by descriptors","Yes");
				}

				Hashtable tempHt = new Hashtable();
				Vector tempList1 = (Vector) addAggMeasures.clone();//new individual measures to be aggregated
				for(int i=0;i<tempList1.size();i++)
				{
					String s = (String)tempList1.get(i);
					tempHt.put(s.substring(0,s.indexOf(":")),s);
				}
				addAggMeasures.clear();
				for(int i=0;i<existingMeasures.size();i++)
				{
					String s1 = (String)existingMeasures.get(i);
					if(tempHt.containsKey(s1))
					{
						addAggMeasures.add(tempHt.get(s1));//synchronizing order of aggregte measures with invididual measures
					}
				}
				Hashtable testMsrMapHt = new Hashtable();
				if(operation.equalsIgnoreCase("appendMeasures"))
				{
					String testMsrMapStr = aggregateInfo.getValue("MEASURES",aggTest);
					if(testMsrMapStr != null && testMsrMapStr.indexOf(":")>0)
					{
						String array[] = StringUtils.getTokens(testMsrMapStr,"#");
						for(int i=0;i<array.length;i++)
						{
							String s = array[i];
							String m = s.substring(0,s.indexOf(":"));
							testMsrMapHt.put(m,s.substring(0,s.lastIndexOf(":")+1));
						}
					}
				}
				String mfd1 = null;
				String measureName1 = null;
				String unit1 = null;
				EgTablesInfo tablesInfo = new EgTablesInfo("manager");
				for(int i=0;i<addAggMeasures.size();i++)
				{
					mfd1 = addAggMeasures.get(i).toString();
					String array[] = StringUtils.getTokens(mfd1,":");
					measureName1 = array[0];
					if(array.length==8 && (array[1].equalsIgnoreCase("condition") || array[1].equalsIgnoreCase("multi-condition")))
					{
						unit1 = array[7];
					}
					else if(array[1].equalsIgnoreCase("pct"))
					{
						unit1 = "%";
					}
					else
					{
						unit1 = tablesInfo.getUnitForMeasure(test,measureName1);
					}
					if(unit1 != null && (unit1=unit1.trim()).equalsIgnoreCase("boolean"))
					{
						unit1="Value";// When the individual_test:measuer unit name is Boolean, we set its corresponding aggregate_test:measure unit name as Value.
					}
					//aggregateInfo.addMeasureForTest(aggTest, measureName1,dbColumnSize, unit1);//changed now
					if(!testMsrMapHt.containsKey(measureName1))
					{
						testMsrMapHt.put(measureName1,(measureName1 + ":" + dbColumnSize + ":" + unit1 + "::"));
					}
				}
				String measuresInOrder = "";
				for(int i=0;i<existingMeasures.size();i++)//individual test measures in order
				{
					String s1 = (String)existingMeasures.get(i);
					if(testMsrMapHt.containsKey(s1))
					{
						if(measuresInOrder.length()==0)
						{
							measuresInOrder = (String)testMsrMapHt.get(s1)+((i+1));
						}
						else
						{
							measuresInOrder += "#" + (String)testMsrMapHt.get(s1)+((i+1));
						}
					}
				}
				IniFile aggregateInfoSync = EgConfigFilesSync.getInstance(EgInstallInfo.getInstallDir()+"/manager/config/eg_aggregate.ini",true);
				aggregateInfoSync.setValue("MEASURES",aggTest,measuresInOrder);
				//aggregateInfo.saveFile();

				Vector AGG_FUN_VARS = null;
				Vector AGG_FUN_VALS = null;
				if(operation.equalsIgnoreCase("appendMeasures"))
				{
					AGG_FUN_VARS = (Vector)aggregateInfoSync.getVariables("AGGREGATE_FUNCTION",true).clone();
					AGG_FUN_VALS = (Vector)aggregateInfoSync.getAllValues("AGGREGATE_FUNCTION").clone();
					for(int i=AGG_FUN_VARS.size()-1;i>=0;i--)
					{
						String var = (String)AGG_FUN_VARS.get(i);
						if(var.startsWith(aggTest+":"))
						{
							aggregateInfoSync.deleteValue("AGGREGATE_FUNCTION",var);
							AGG_FUN_VARS.set(i,var.substring(var.indexOf(":")+1).toUpperCase());
							continue;
						}
						AGG_FUN_VARS.remove(i);
						AGG_FUN_VALS.remove(i);
					}
					Vector COLUMN_NAME_VARS = (Vector)aggregateInfoSync.getVariables("COLUMN_NAME_MAPPING",true).clone();
					for(int i=0;i<COLUMN_NAME_VARS.size();i++)
					{
						String CNM = (String)COLUMN_NAME_VARS.get(i);
						if(CNM.startsWith(aggTest+":"))
						{
							aggregateInfoSync.deleteValue("COLUMN_NAME_MAPPING",CNM);
						}
					}
					COLUMN_NAME_VARS.clear();
					//aggregateInfo.saveFile();
				}
				if(operation.equalsIgnoreCase("addMeasures"))
				{
					deleteTestFromUserThresholds(aggTest); // //added by sasi 22Nov2013
					aggregateInfoSync.setValue("AGGREGATE_TEST", aggTest,test);
					ArrayList siteOrientedTests = new ArrayList();
					siteOrientedTests.add("WebSiteTest");
					siteOrientedTests.add("WebSiteTransactionTest");
					if(siteOrientedTests.contains(test))
					{
						aggregateInfoSync.setValue("SITE_AGGREGATE_TEST",aggTest,"yes");
					}
					EgTestParamBean testParamIni = new EgTestParamBean();
					testParamIni.createSyncFile("eg_testparam.ini","save");
					testParamIni.setValues("RADIO",aggTest,"aggregateDescriptor");
					testParamIni.saveFile();
					testParamIni.releaseInstance();
				}
				IniFile agglang = EgConfigFilesSync.getInstance(EgInstallInfo.getInstallDir()+"/manager/config/eg_aggregate_lang_en_US.ini");
				if(operation.equalsIgnoreCase("addMeasures"))
				{
					agglang.setValue("TEST_NAME_MAPPING",aggTest,test_description);
					agglang.setValue("AGG_TEXT_NAME_MAPPING","admin.aggregate."+aggTest,test_description);
				}
				//testBean.addAggTest(aggTest,test,portBased,addAggMeasures.size(),descriptorAggregation);
				String mfd = null;
				String measureName = null;
				String function = null;
				String measuresDescription = null;
				//String unit = null;
				int idx = 0;
				String factor="1",factor1="1",process="UNALTERED",conversionFactor="1";
				IniFile uiIni = EgConfigFilesSync.getInstance(EgInstallInfo.getInstallDir()+"/manager/config/eg_ui.ini");
				String label = addAggMeasures.size()==1?"Measure name":"Measure names";
				for(int i=0;i<addAggMeasures.size();i++)
				{
					mfd = addAggMeasures.get(i).toString();
					String array[] = StringUtils.getTokens(mfd,":");
					if(array.length==8)
					{
						measureName = array[0];
						function = array[1];
						measuresDescription = array[2];
						String trgtOperation = array[3];
						String trgtValue = array[4];
						String trgtComps = array[5];
						String violation = array[6];
						String dispValueIn = array[7];
						StringBuffer sbuffer = new StringBuffer();
						sbuffer.append(trgtOperation);
						sbuffer.append("|");
						sbuffer.append(trgtValue);
						sbuffer.append("|");
						if(trgtComps.equalsIgnoreCase("Not Applicable"))
						{
							sbuffer.append("NA");
						}
						else
						{
							sbuffer.append(trgtComps);
						}
						sbuffer.append("|");
						if(violation.equalsIgnoreCase("Not Applicable"))
						{
							sbuffer.append("NA");
						}
						else
						{
							sbuffer.append(violation);
						}
						sbuffer.append("|");
						sbuffer.append(dispValueIn);
						aggregateInfoSync.setValue("COMPARISON", aggTest+":"+measureName,sbuffer.toString());
						if(trgtOperation.equals("GT"))
						{
							trgtOperation=">";
						}
						else if(trgtOperation.equals("LT"))
						{
							trgtOperation="<";
						}
						else if(trgtOperation.equals("GE"))
						{
							trgtOperation=">=";
						}
						else if(trgtOperation.equals("LE"))
						{
							trgtOperation="<=";
						}
						else if(trgtOperation.equals("EQ"))
						{
							trgtOperation="=";
						}
						if(descriptorAggregation.equalsIgnoreCase("true"))
						{
							if(function.equalsIgnoreCase("condition") || function.equalsIgnoreCase("multi-condition") || function.equalsIgnoreCase("multi_condition"))
							{
								auditLogThread.setCurrentValue(label,measuresDescription + " (" +(String)fnMapping.get(function)+"|" + trgtOperation+"|"+trgtValue+"|"+trgtComps+"|"+violation+"|"+dispValueIn+")");
							}
							else
							{
								auditLogThread.setCurrentValue(label,measuresDescription + " (" +(String)fnMapping.get(function));
							}
						}
						else
						{
							if(function.equalsIgnoreCase("condition") || function.equalsIgnoreCase("multi-condition") || function.equalsIgnoreCase("multi_condition"))
							{
								auditLogThread.setCurrentValue(label,measuresDescription + " (" +(String)fnMapping.get(function)+"|" + trgtOperation+"|"+trgtValue+"|"+trgtComps+"|"+dispValueIn+")");
							}
							else
							{
								auditLogThread.setCurrentValue(label,measuresDescription + " (" +(String)fnMapping.get(function));
							}
						}
					}
					else
					{
						measureName = array[0];
						function = array[1];
						measuresDescription = array[2];
						auditLogThread.setCurrentValue(label,measuresDescription + " (" +(String)fnMapping.get(function)+")");
					}
					agglang.setValue("MEASURE_NAME_MAPPING",aggTest+":"+measureName,measuresDescription);
					idx = existingMeasures.indexOf(measureName);
					//unit = tablesInfo.getUnitForMeasure(test,measureName);
					/*if(unit.equalsIgnoreCase("boolean"))
					{
						uiIni.setValue("Measure_value_display",aggTest+":"+measureName + ":0","No");
						uiIni.setValue("Measure_value_display",aggTest+":"+measureName + ":1","Yes");
					}*/
					if(pctHt != null && pctHt.containsKey(measureName))
					{
						String ndmeasures = (String)pctHt.get(measureName);
						String and[] = StringUtils.getTokens(ndmeasures,":");
						String andKey = aggTest+":"+idx;
						int nidx = existingMeasures.indexOf(and[0]);
						int didx = existingMeasures.indexOf(and[1]);
						if(nidx>-1 && didx>-1)
						{
							aggregateInfoSync.setValue("SPECIAL_FUNCTION",aggTest+":"+idx,nidx+":avg_sum:1#1,"+didx+":avg_sum:1#1");
						}
					}
					if(function.equalsIgnoreCase("percent"))
					{
						function="pct";
					}
					if(operation.equalsIgnoreCase("appendMeasures"))
					{
						AGG_FUN_VARS.add(measureName.toUpperCase());
						if(function.equals("multi-condition"))
						{
							AGG_FUN_VALS.add(idx+":multi_condition:"+factor+"#"+factor1);
						}
						else
						{
							AGG_FUN_VALS.add(idx+":"+function+":"+factor+"#"+factor1);
						}
					}
					else
					{
						if(function.equals("multi-condition"))
						{
							aggregateInfoSync.setValue("AGGREGATE_FUNCTION", aggTest+":"+measureName.toUpperCase(), idx+":multi_condition:"+factor+"#"+factor1);
						}
						else
						{
							aggregateInfoSync.setValue("AGGREGATE_FUNCTION", aggTest+":"+measureName.toUpperCase(), idx+":"+function+":"+factor+"#"+factor1);
						}
						aggregateInfoSync.setValue("COLUMN_NAME_MAPPING", aggTest+":"+measureName, test+":"+measureName);
					}
				}
				if(operation.equalsIgnoreCase("appendMeasures"))
				{
					for(int i=0;i<existingMeasures.size();i++)
					{
						String measurement = (String)existingMeasures.get(i);
						String MEASUREMENT = measurement.toUpperCase();
						int ix = AGG_FUN_VARS.indexOf(MEASUREMENT);
						if(ix > -1)
						{
							aggregateInfoSync.setValue("AGGREGATE_FUNCTION",aggTest+":"+MEASUREMENT, (String)AGG_FUN_VALS.get(ix));
							aggregateInfoSync.setValue("COLUMN_NAME_MAPPING",aggTest+":"+measurement, test+":"+measurement);
						}
					}
				}
				if(operation.equalsIgnoreCase("addMeasures"))
				{
					auditLogThread.setValue("Activity","Add Aggregate Test");
					auditLogThread.setValue("Description","$test$:"+aggTest + " has been added");
				}
				else
				{
					auditLogThread.setValue("Activity","Modify Aggregate Test");
					if(addAggMeasures.size()==1)
					{
						auditLogThread.setValue("Description","Measure has been included to $test$:"+aggTest);
					}
					else
					{
						auditLogThread.setValue("Description","Measures have been included to $test$:"+aggTest);
					}
				}
				auditLogThread.sendItToDB();
				//aggregateInfo.saveFile();
				aggregateInfoSync.saveFile();
				EgConfigFilesSync.releaseInstance(aggregateInfoSync);
				if(operation.equalsIgnoreCase("addMeasures"))
				{
					boolean firstLevel=false;
					boolean secondLevel=false;
					String uivals = uiIni.getValue("TEST_PANEL_SUBTREE","SubTreeTestList");
					if(uivals != null && uivals.length()>0)
					{
						String searchKey = ","+uivals+",";
						if(searchKey.indexOf(","+test+",")>=0)
						{
							String searchKey2 = ","+uivals+",";
							if(searchKey2.indexOf(","+aggTest+",")==-1)
							{
								firstLevel=true;
								uiIni.setValue("TEST_PANEL_SUBTREE","SubTreeTestList",(uivals+","+aggTest));
							}
						}
					}
					uivals = uiIni.getValue("TEST_PANEL_SUBTREE","SecondLevelSubTreeList");
					if(uivals != null && uivals.length()>0)
					{
						String searchKey = ","+uivals+",";
						if(searchKey.indexOf(","+test+",")>=0)
						{
							String searchKey2 = ","+uivals+",";
							if(searchKey2.indexOf(","+aggTest+",")==-1)
							{
								secondLevel=true;
								uiIni.setValue("TEST_PANEL_SUBTREE","SecondLevelSubTreeList",(uivals+","+aggTest));
							}
						}
					}
					if(firstLevel)
					{
						String uival = uiIni.getValue("TEST_PANEL_SUBTREE",test);
						if(uival != null && (uival=uival.trim()).length()>0)
						{
							uiIni.setValue("TEST_PANEL_SUBTREE",aggTest,uival);
						}
					}
					if(secondLevel)
					{
						String uival = uiIni.getValue("TEST_PANEL_SUBTREE","SecondLevelSubTreeList:"+test);
						if(uival != null && (uival=uival.trim()).length()>0)
						{
							uiIni.setValue("TEST_PANEL_SUBTREE","SecondLevelSubTreeList:"+aggTest,uival);
						}
					}
				}
				uiIni.saveFile();
				EgConfigFilesSync.releaseInstance(uiIni);
				agglang.saveFile();
				EgConfigFilesSync.releaseInstance(agglang);

				EgTesterInfo testerInfo = new EgTesterInfo("manager");
				boolean externalAgentRunsAllAggTests = testerInfo.externalAgentRunsAllAggTests();
				//keep this line at last
				testBean.addAggTest(aggTest,test,portBased,addAggMeasures.size(),descriptorAggregation,externalAgentRunsAllAggTests);
			}
			else
			{
				//aggregateInfo.saveFile();
				auditLogThread.setValue("Activity","Modify Aggregate Test");
				auditLogThread.setValue("Description","No more measures to add to $test$:"+aggTest);
				auditLogThread.sendItToDB();
				operationStatus.put("errormessage",_mapping.getTextDescription("admin.user.Selected Measures are already configured for this test")+" " + _mapping.getTestDescription(aggTest));
				rootJson.put("operationStatus",operationStatus);
				errorOccured = true;
			}
		}
		else if(operation != null && operation.equalsIgnoreCase("modifyMeasures"))
		{
			Vector percentageMeasureKeys = new Vector();
			try
			{
				String pctVars[]=aggregateInfo.getVariables("SPECIAL_FUNCTION");
				for(int i=0;i<pctVars.length;i++)
				{
					String key = pctVars[i];
					if(key.startsWith((aggTest+":")))
					{
						String measure_index = pctVars[i].substring(pctVars[i].indexOf(":")+1).toUpperCase();
						String tp = temp_measures[Integer.parseInt(measure_index)].toUpperCase();
						percentageMeasureKeys.add(aggTest+":"+tp);
					}
				}
			}
			catch(Exception e)
			{
				e.printStackTrace();
			}
			Hashtable ht = new Hashtable();
			boolean changed = false;
			ArrayList mlist = (ArrayList)session.getAttribute("emt");
			if(mlist != null && mlist.size()>0)
			{
				for(int i=0;i<mlist.size();i++)
				{
					String temp = (String)mlist.get(i);
					String arr[] = StringUtils.getTokens(temp,":");
					if(arr.length==3)
					{
						ht.put(arr[0],(arr[1]+":"+arr[2]));
					}
					else
					{
						ht.put(arr[0],(arr[1]+":"+arr[2]+":"+arr[3]+":"+arr[4]+":"+arr[5]+":"+arr[6]+":"+arr[7]));
					}
				}
			}
			else
			{
				mlist = new ArrayList();
			}
			EgTablesInfo tablesInfo = new EgTablesInfo("manager");
			ArrayList measureList = new ArrayList();
			ArrayList measureUnitList = new ArrayList();
			Hashtable measureNewUnit = new Hashtable();
			Vector modifyMeasures = new Vector();
			for(int i=0;i<measureFunction.length;i++)
			{
				String measure = measureFunction[i].substring(0,measureFunction[i].indexOf(":"));
				modifyMeasures.add(measureFunction[i]);
				if(!mlist.contains(measureFunction[i]))
				{
					changed = true;
				}
				String newUnit = tablesInfo.getUnitForMeasure(test,measure);
				String array[] = StringUtils.getTokens(measureFunction[i],":");
				if(array[1].equalsIgnoreCase("condition") || array[1].equalsIgnoreCase("multi-condition"))
				{
					newUnit=array[7];
				}
				else if(array[1].equalsIgnoreCase("pct"))
				{
					newUnit="%";
				}
				measureList.add(measure);
				measureUnitList.add(newUnit);
			}

			String test_description_pre = (String)session.getAttribute("test_description_pre");
			String descriptorAggregation_pre = (String)session.getAttribute("descriptorAggregation_pre");
			if(!changed) {
				if(!test_description.equalsIgnoreCase(test_description_pre)) {
					changed = true;
				}
				if(!descriptorAggregation.equalsIgnoreCase(descriptorAggregation_pre)) {
					changed =true;
				}
			}

			if(!changed)
			{
				//aggregateInfo.saveFile();
				operationStatus.put("errormessage",_mapping.getTextDescription("admin.user.No changes have been done for this test")+" " + _mapping.getTestDescription(aggTest));
				rootJson.put("operationStatus",operationStatus);
				errorOccured = true;
			}
			else if(modifyMeasures != null && modifyMeasures.size()>0)
			{
				IniFile aggregateInfoSync = EgConfigFilesSync.getInstance(EgInstallInfo.getInstallDir()+"/manager/config/eg_aggregate.ini",true);
				if(!test_description.equalsIgnoreCase(test_description_pre)) {
					auditLogThread.setPreviousValue("01~~Aggregate test display name",test_description_pre);
					auditLogThread.setCurrentValue("01~~Aggregate test display name",test_description);
				}
				if(!descriptorAggregation.equalsIgnoreCase(descriptorAggregation_pre))
				{
					if(descriptorAggregation_pre.equalsIgnoreCase("true")) {
						auditLogThread.setPreviousValue("02~~Report by descriptors","No");
					}
					else {
						auditLogThread.setPreviousValue("02~~Report by descriptors","Yes");
					}
					if(descriptorAggregation.equalsIgnoreCase("true")) {
						auditLogThread.setCurrentValue("02~~Report by descriptors","No");
					}
					else {
						auditLogThread.setCurrentValue("02~~Report by descriptors","Yes");
					}
					//testBean.addAggTest(aggTest,test,portBased,existingAggMeasures.size(),descriptorAggregation);//changed now
				}
				auditLogThread.setValue("Activity","Modify Aggregate Test");
				String measuresDesc[] = StringUtils.getTokens(request.getParameter("measureNamesDesc"),"$");
				String factor="1",factor1="1",process="UNALTERED",conversionFactor="1";

				String mfd = null;
				String measureName = null;
				String function = null;
				String measuresDescription = null;
				String trgtOperation = null;
				String trgtValue = null;
				String trgtComps = null;
				String dispValueIn = null;
				String violation = null;
				int idx = 0;
				//String unit = null;
				IniFile agglang = EgConfigFilesSync.getInstance(EgInstallInfo.getInstallDir()+"/manager/config/eg_aggregate_lang_en_US.ini");
				for(int i=0;i<modifyMeasures.size();i++)
				{
					mfd = modifyMeasures.get(i).toString();
					String mfd_now[] = StringUtils.getTokens(mfd,":");
					measureName = mfd_now[0];
					function = mfd_now[1];
					measuresDescription = mfd_now[2];
					if(mfd_now.length==8)
					{
						trgtOperation = mfd_now[3];
						trgtValue = mfd_now[4];
						trgtComps = mfd_now[5];
						violation = mfd_now[6];
						dispValueIn = mfd_now[7];
						if(trgtOperation.equals("GT"))
						{
							trgtOperation=">";
						}
						else if(trgtOperation.equals("LT"))
						{
							trgtOperation="<";
						}
						else if(trgtOperation.equals("GE"))
						{
							trgtOperation=">=";
						}
						else if(trgtOperation.equals("LE"))
						{
							trgtOperation="<=";
						}
						else if(trgtOperation.equals("EQ"))
						{
							trgtOperation="=";
						}
					}
					String previous = (String) ht.get(measureName);
					String array[] = StringUtils.getTokens(previous,":");
					String pre_func = array[0];
					String pre_desc = array[1];
					String pre_trgt_op = null;
					String pre_target_value = null;
					String pre_target_comps = null;
					String pre_disp_value_in = null;
					String pre_violation = null;
					if(array.length==7)
					{
						pre_trgt_op = array[2];
						pre_target_value = array[3];
						pre_target_comps = array[4];
						pre_violation = array[5];
						pre_disp_value_in = array[6];
					}
					if(function.equalsIgnoreCase("condition") || function.equalsIgnoreCase("multi-condition"))
					{
						StringBuffer sbuffer = new StringBuffer();
						sbuffer.append(mfd_now[3]);
						sbuffer.append("|");
						sbuffer.append(trgtValue);
						sbuffer.append("|");
						if(trgtComps.equalsIgnoreCase("Not Applicable"))
						{
							sbuffer.append("NA");
						}
						else
						{
							sbuffer.append(trgtComps);
						}
						sbuffer.append("|");
						if(violation.equalsIgnoreCase("Not Applicable"))
						{
							sbuffer.append("NA");
						}
						else
						{
							sbuffer.append(violation);
						}
						sbuffer.append("|");
						sbuffer.append(dispValueIn);
						aggregateInfoSync.setValue("COMPARISON", aggTest+":"+measureName,sbuffer.toString());
					}
					else
					{
						aggregateInfoSync.deleteValue("COMPARISON", aggTest+":"+measureName);
					}
					if(!pre_desc.equalsIgnoreCase(measuresDescription) || !pre_func.equalsIgnoreCase(function) || 
					!pre_trgt_op.equalsIgnoreCase(trgtOperation) || !pre_target_value.equalsIgnoreCase(trgtValue) || !pre_target_comps.equalsIgnoreCase(trgtComps) || !pre_disp_value_in.equalsIgnoreCase(dispValueIn) || !pre_violation.equalsIgnoreCase(violation))
					{
						if(array.length==7)
						{
							if(descriptorAggregation.equalsIgnoreCase("true"))
							{
								if(pre_func.equalsIgnoreCase("condition") || pre_func.equalsIgnoreCase("multi-condition") || pre_func.equalsIgnoreCase("multi_condition"))
								{
									auditLogThread.setPreviousValue("Measure name(s)",pre_desc + " (" +(String)fnMapping.get(pre_func)+"|" + pre_trgt_op +"|"+pre_target_value+"|"+pre_target_comps+"|"+pre_violation+"|"+pre_disp_value_in+")");
								}
								else
								{
									auditLogThread.setPreviousValue("Measure name(s)",pre_desc + " (" +(String)fnMapping.get(pre_func)+")");
								}
							}
							else
							{
								if(pre_func.equalsIgnoreCase("condition") || pre_func.equalsIgnoreCase("multi-condition") || pre_func.equalsIgnoreCase("multi_condition"))
								{
									auditLogThread.setPreviousValue("Measure name(s)",pre_desc + " (" +(String)fnMapping.get(pre_func)+"|" + pre_trgt_op +"|"+pre_target_value+"|"+pre_target_comps+"|"+pre_disp_value_in+")");
								}
								else
								{
									auditLogThread.setPreviousValue("Measure name(s)",pre_desc + " (" +(String)fnMapping.get(pre_func)+")");
								}
							}
						}
						else
						{
							auditLogThread.setPreviousValue("Measure name(s)",pre_desc + " (" +(String)fnMapping.get(pre_func)+")");
						}
						if(mfd_now.length==8)
						{
							if(descriptorAggregation.equalsIgnoreCase("true"))
							{
								if(function.equalsIgnoreCase("condition") || function.equalsIgnoreCase("multi-condition") || function.equalsIgnoreCase("multi_condition"))
								{
									auditLogThread.setCurrentValue("Measure name(s)",measuresDescription + " (" +(String)fnMapping.get(function)+"|" + trgtOperation +"|"+trgtValue+"|"+trgtComps+"|"+violation+"|"+dispValueIn+")");
								}
								else
								{
									auditLogThread.setCurrentValue("Measure name(s)",measuresDescription + " (" +(String)fnMapping.get(function));
								}
							}
							else
							{
								if(function.equalsIgnoreCase("condition") || function.equalsIgnoreCase("multi-condition") || function.equalsIgnoreCase("multi_condition"))
								{
									auditLogThread.setCurrentValue("Measure name(s)",measuresDescription + " (" +(String)fnMapping.get(function)+"|" + trgtOperation +"|"+trgtValue+"|"+trgtComps+"|"+dispValueIn+")");
								}
								else
								{
									auditLogThread.setCurrentValue("Measure name(s)",measuresDescription + " (" +(String)fnMapping.get(function));
								}
							}
						}
						else
						{
							auditLogThread.setCurrentValue("Measure name(s)",measuresDescription + " (" +(String)fnMapping.get(function)+")");
						}
					}
					agglang.setValue("MEASURE_NAME_MAPPING",aggTest+":"+measureName,measuresDescription);
					idx = existingMeasures.indexOf(measureName);
					//unit = tablesInfo.getUnitForMeasure(test,measureName);
					if(pctHt != null && pctHt.containsKey(measureName))
					{
						String ndmeasures = (String)pctHt.get(measureName);
						String and[] = StringUtils.getTokens(ndmeasures,":");
						String andKey = aggTest+":"+idx;
						int nidx = existingMeasures.indexOf(and[0]);
						int didx = existingMeasures.indexOf(and[1]);
						if(nidx>-1 && didx>-1)
						{
							aggregateInfoSync.setValue("SPECIAL_FUNCTION",aggTest+":"+idx,nidx+":avg_sum:1#1,"+didx+":avg_sum:1#1");
						}
					}
					String af_key = aggTest+":"+measureName.toUpperCase();
					if(function.equals("multi-condition"))
					{
						aggregateInfoSync.setValue("AGGREGATE_FUNCTION", af_key, idx+":multi_condition:"+factor+"#"+factor1);
					}
					else
					{
						aggregateInfoSync.setValue("AGGREGATE_FUNCTION", af_key, idx+":"+function+":"+factor+"#"+factor1);
					}
					if(percentageMeasureKeys.contains(af_key) && !function.equalsIgnoreCase("pct"))
					{
						aggregateInfoSync.deleteValue("SPECIAL_FUNCTION",aggTest+":"+idx);
					}
				}
				auditLogThread.setValue("Description","$test$:"+aggTest + " has been modified");
				auditLogThread.sendItToDB();
				//aggregateInfoSync.modifyUnitForMeasure(aggTest,measureList,measureUnitList);//support this


				String val = aggregateInfoSync.getValue("MEASURES", aggTest);
				if (val == null || val.length() == 0)
					val = "";
				if(val.length() > 1)
				{
					StringTokenizer tokens = new StringTokenizer(val,"#");
					Vector v = new Vector();
					while(tokens.hasMoreTokens())
					{
						String token = tokens.nextToken();
						String gtoken = token;

						int mic = token.indexOf(":");
						String measure = token.substring(0,mic);
						int midx = measureList.indexOf(measure);
						if(midx>-1)
						{
							token = token.substring(mic+1);
							mic = token.indexOf(":");
							String dbcolumnsize = token.substring(0,mic);
							token = token.substring(mic+1);

							mic = token.indexOf(":");
							String unitExist = token.substring(0,mic);
							token = token.substring(mic+1);

							String finalStr = measure+":"+dbcolumnsize+":"+(String)measureUnitList.get(midx)+":"+token;
							v.add(finalStr);
						}
						else
						{
							v.add(gtoken);
						}
					}
					String finalOrderedMeasures = "";
					for(int i=0;i<v.size();i++)
					{
						finalOrderedMeasures += v.get(i).toString()+"#";
					}
					if(finalOrderedMeasures.endsWith("#"))
						finalOrderedMeasures = finalOrderedMeasures.substring(0,finalOrderedMeasures.length()-1);
					aggregateInfoSync.setValue("MEASURES", aggTest,finalOrderedMeasures);
				}

				aggregateInfoSync.saveFile();
				EgConfigFilesSync.releaseInstance(aggregateInfoSync);
				agglang.setValue("TEST_NAME_MAPPING",aggTest,test_description);
				agglang.setValue("AGG_TEXT_NAME_MAPPING","admin.aggregate."+aggTest,test_description);
				agglang.saveFile();
				EgConfigFilesSync.releaseInstance(agglang);
				String url = "aggShowComponentTypes.jsp?agg_test_name="+aggTest;
				operationStatus.put("message",_mapping.getTextDescription("admin.user.Test measures have been modified for this test")+" " + _mapping.getTestDescription(aggTest));
				rootJson.put("operationStatus",operationStatus);

				IniFile tableFilePtr = EgConfigFilesSync.getInstance(EgInstallInfo.getInstallDir()+"/manager/config/eg_tables.ini");
				if (measureList!=null)
				{
					for (int i=0;i<measureList.size() ;i++ )
					{
						tableFilePtr.setValue("MEASUREMENT_UNITS_TABLE", (aggTest + ":" + (String)measureList.get(i)),(String)measureUnitList.get(i));
					}
				}
				tableFilePtr.saveFile();
				EgConfigFilesSync.releaseInstance(tableFilePtr);

				//keep this block at last
				if(!descriptorAggregation.equalsIgnoreCase(descriptorAggregation_pre))
				{
					EgTesterInfo testerInfo = new EgTesterInfo("manager");
					boolean externalAgentRunsAllAggTests = testerInfo.externalAgentRunsAllAggTests();
					testBean.addAggTest(aggTest,test,portBased,existingAggMeasures.size(),descriptorAggregation,externalAgentRunsAllAggTests);
				}
			}
			else
			{
				//aggregateInfo.saveFile();
				auditLogThread.setValue("Description","$test$:"+aggTest + " has not been modified");
				auditLogThread.sendItToDB();
				operationStatus.put("errormessage",_mapping.getTextDescription("admin.user.Selected Measures have not been modified for this test")+" " + _mapping.getTestDescription(aggTest));
				rootJson.put("operationStatus",operationStatus);
				errorOccured = true;
			}
		}
		else if(operation != null && operation.equalsIgnoreCase("deleteMeasures"))
		{
			Vector deleteMeasures = new Vector();
			for(int i=0;i<measureFunction.length;i++)
			{
				String measure = measureFunction[i].substring(0,measureFunction[i].indexOf(":"));
				if(existingAggMeasures.contains(measure))
				{
					deleteMeasures.add(measure);
				}
			}
			if(deleteMeasures != null && deleteMeasures.size()>0)
			{
				EgDbaseInfo dbaseInfo = new EgDbaseInfo("manager");
				if(dbaseInfo.isTableExistInDB(aggTest))
				{
					String sep = System.getProperty("file.separator");
					String dbServType = new EgDbInfo("manager").checkDBType();
					if(dbServType != null && dbServType.equals("EgMsSqlAdapter"))
					{
						String queryDir = EgInstallInfo.getInstallDir()+sep+"bin"+sep+"database"+sep+"mssql"+sep+"Aggregate_Test_Query";
						File dir = new File(queryDir);
						if(dir.isDirectory())
						{
							File queryFile = new File(queryDir+sep+aggTest+".txt");
							if(queryFile.exists())
							{
								queryFile.delete();
							}
						}
					}
					else
					{
						String queryDir = EgInstallInfo.getInstallDir()+sep+"bin"+sep+"database"+sep+"Aggregate_Test_Query";
						File dir = new File(queryDir);
						if(dir.isDirectory())
						{
							File queryFile = new File(queryDir+sep+aggTest+".txt");
							if(queryFile.exists())
							{
								queryFile.delete();
							}
						}
					}
					/* deleting existing entries from [DYN_TABLES] of eg_dbase.ini */
					dbaseInfo.removeDynamicTable(aggTest);

					/* deleting existing entries from [MEASUREMENT_DB_MAPPING] of eg_db.ini */
					IniFile dbFilePtrWr = EgConfigFilesSync.getInstance(new com.eg.EgUDConfigInfo("manager").getDbFile());
					for(int i=0;i<existingAggMeasures.size();i++)
					{
						String e_measure = (String)existingAggMeasures.get(i);
						dbFilePtrWr.deleteValue("MEASUREMENT_DB_MAPPING", aggTest +":"+ e_measure);
						dbFilePtrWr.deleteValue("MEASUREMENT_DB_MAPPING", aggTest +":"+ e_measure + ":state");
					}
					dbFilePtrWr.saveFile();
					EgConfigFilesSync.releaseInstance(dbFilePtrWr);
				}
				IniFile aggregateInfoSync = EgConfigFilesSync.getInstance(EgInstallInfo.getInstallDir()+"/manager/config/eg_aggregate.ini",true);
				Hashtable testMsrMapHt = new Hashtable();
				String testMsrMapStr = aggregateInfoSync.getValue("MEASURES",aggTest);
				if(testMsrMapStr != null && testMsrMapStr.indexOf(":")>0)
				{
					String array[] = StringUtils.getTokens(testMsrMapStr,"#");
					for(int i=0;i<array.length;i++)
					{
						String s = array[i];
						String m = s.substring(0,s.indexOf(":"));
						testMsrMapHt.put(m,s.substring(0,s.lastIndexOf(":")+1));
					}
				}
				String deleteMeasure  = null;
				for(int i=0;i<deleteMeasures.size();i++)
				{
					deleteMeasure = (String)deleteMeasures.get(i);
					if(testMsrMapHt.containsKey(deleteMeasure))
					{
						testMsrMapHt.remove(deleteMeasure);
					}
				}
				String measuresInOrder = "";
				for(int i=0;i<existingMeasures.size();i++)//individual test measures in order
				{
					String s1 = (String)existingMeasures.get(i);
					if(testMsrMapHt.containsKey(s1))
					{
						if(measuresInOrder.length()==0)
						{
							measuresInOrder = (String)testMsrMapHt.get(s1)+((i+1));
						}
						else
						{
							measuresInOrder += "#" + (String)testMsrMapHt.get(s1)+((i+1));
						}
					}
				}
				aggregateInfoSync.setValue("MEASURES",aggTest,measuresInOrder);
				//aggregateInfo.saveFile();

				auditLogThread.setValue("Activity","Modify Aggregate Test");
				String label = deleteMeasures.size()==1?"Excluded measure name":"Excluded measure names";
				deleteTestFromUserThresholds(aggTest); //added by sasi 22Nov2013
				//testBean.addAggTest(aggTest,test,portBased,(existingAggMeasures.size()-deleteMeasures.size()),descriptorAggregation);

				String test_description_pre = (String)session.getAttribute("test_description_pre");
				String descriptorAggregation_pre = (String)session.getAttribute("descriptorAggregation_pre");
				if(!test_description.equalsIgnoreCase(test_description_pre)) {
					auditLogThread.setPreviousValue("01~~Aggregate test display name",test_description_pre);
					auditLogThread.setCurrentValue("01~~Aggregate test display name",test_description);
				}
				if(!descriptorAggregation.equalsIgnoreCase(descriptorAggregation_pre)) {
					if(descriptorAggregation_pre.equalsIgnoreCase("true")) {
						auditLogThread.setPreviousValue("02~~Report by descriptors","No");
					}
					else {
						auditLogThread.setPreviousValue("02~~Report by descriptors","Yes");
					}
					if(descriptorAggregation.equalsIgnoreCase("true")) {
						auditLogThread.setCurrentValue("02~~Report by descriptors","No");
					}
					else {
						auditLogThread.setCurrentValue("02~~Report by descriptors","Yes");
					}
				}
				String val = aggregateInfoSync.getValue("MEASURES", aggTest);
				String fval = "";
				if (val == null || val.length() == 0)
					val = "";
				deleteMeasure = null;
				IniFile agglang = EgConfigFilesSync.getInstance(EgInstallInfo.getInstallDir()+"/manager/config/eg_aggregate_lang_en_US.ini");
				for(int i=0;i<deleteMeasures.size();i++)
				{
					deleteMeasure = (String)deleteMeasures.get(i);
					String desc = agglang.getValue("MEASURE_NAME_MAPPING",aggTest+":"+deleteMeasure);
					agglang.deleteValue("MEASURE_NAME_MAPPING",aggTest+":"+deleteMeasure);
					if(StringUtils.isNull(desc))
					{
						desc = deleteMeasure;
					}
					auditLogThread.setCurrentValue(label,desc);
					//aggregateInfoSync.removeMeasureFromTest(aggTest, deleteMeasure);//suppor this

					if(val.length() > 1)
					{
						StringTokenizer tokens = new StringTokenizer(val,"#");
						Vector v = new Vector();
						while(tokens.hasMoreTokens())
						{
							String token = tokens.nextToken();
							if(token.startsWith(deleteMeasure+":"))
							{
								continue;
							}
							else
							{
								v.add(token.substring(0,token.lastIndexOf(":")+1));
							}
						}
						val = "";
						for(int mic=0;mic<v.size();mic++)
						{
							String temp = v.get(mic).toString();
							val += temp+(mic+1)+"#";
						}
						if(val.endsWith("#"))
							val = val.substring(0,val.length()-1);
					}
					int d_idx = existingMeasures.indexOf(deleteMeasure);
					if(d_idx>-1)
					{
						aggregateInfoSync.deleteValue("SPECIAL_FUNCTION", aggTest+":"+String.valueOf(d_idx));
					}
					aggregateInfoSync.deleteValue("AGGREGATE_FUNCTION", aggTest+":"+deleteMeasure.toUpperCase());
					aggregateInfoSync.deleteValue("COLUMN_NAME_MAPPING", aggTest+":"+deleteMeasure);
					aggregateInfoSync.deleteValue("COMPARISON", aggTest+":"+deleteMeasure);
				}
				
				aggregateInfoSync.setValue("MEASURES", aggTest,val);
				if(deleteMeasures.size()==1)
				{
					auditLogThread.setValue("Description","Measure has been excluded from $test$:"+aggTest);
				}
				else
				{
					auditLogThread.setValue("Description","Measures have been excluded from $test$:"+aggTest);
				}
				auditLogThread.sendItToDB();
				aggregateInfoSync.saveFile();
				EgConfigFilesSync.releaseInstance(aggregateInfoSync);
				agglang.setValue("TEST_NAME_MAPPING",aggTest,test_description);
				agglang.setValue("AGG_TEXT_NAME_MAPPING","admin.aggregate."+aggTest,test_description);
				agglang.saveFile();
				EgConfigFilesSync.releaseInstance(agglang);
				operationStatus.put("message",_mapping.getTextDescription("admin.user.Test measures have been excluded from this test")+" " + _mapping.getTestDescription(aggTest));
				rootJson.put("operationStatus",operationStatus);

				EgTesterInfo testerInfo = new EgTesterInfo("manager");
				boolean externalAgentRunsAllAggTests = testerInfo.externalAgentRunsAllAggTests();
				//keep this line at last
				testBean.addAggTest(aggTest,test,portBased,(existingAggMeasures.size()-deleteMeasures.size()),descriptorAggregation,externalAgentRunsAllAggTests);
			}
			else
			{
				//aggregateInfo.saveFile();
				auditLogThread.setValue("Description","No measures found to exclude from $test$:"+aggTest);
				auditLogThread.sendItToDB();
				operationStatus.put("errormessage",_mapping.getTextDescription("admin.user.Selected measures are not yet configured for this test")+" " + _mapping.getTestDescription(aggTest));
				rootJson.put("operationStatus",operationStatus);
				errorOccured = true;
			}
		}
		if(!errorOccured)
		{
			/*
			Below code is to inform the AGENT to download recent eg_thresholds.ini file from MANAGER as we add/modify this aggregate test.
			*/
			IniFile testsIni = EgConfigFilesSync.getInstance(EgInstallInfo.getInstallDir()+"/manager/config/eg_tests.ini");
			Vector trend_vars = testsIni.getVariables("TREND_TESTS",true);
			Vector globe_vars = testsIni.getVariables("GLOBAL_THRESHOLDS",true);
			if(trend_vars != null && trend_vars.indexOf(test)>-1)
			{
				String tmp = testsIni.getValue("TREND_TESTS",test);
				if(tmp == null || tmp.trim().length()==0 || tmp.trim().equalsIgnoreCase("null"))
					tmp = "No";
				testsIni.setValue("TREND_TESTS",aggTest,tmp);
			}
			if(globe_vars != null && globe_vars.indexOf(test)>-1)
			{
				String tmp = testsIni.getValue("GLOBAL_THRESHOLDS",test);
				if(tmp == null || tmp.trim().length()==0 || tmp.trim().equalsIgnoreCase("null"))
					tmp = "No";
				testsIni.setValue("GLOBAL_THRESHOLDS",aggTest,tmp);
			}
			testsIni.setValue("AGGREGATE_TEST","updated_time",""+System.currentTimeMillis());
			testsIni.saveFile();
			EgConfigFilesSync.releaseInstance(testsIni);
			testsIni = null;
			//ends
			testBean.setThresholdsForAggTest(aggTest);
			EgTablesInfo tablesInfo = new EgTablesInfo("manager");
			String layer = tablesInfo.getLayerForTest(test);
			UpdateAndTransmitICInfo updateICInfo = new  UpdateAndTransmitICInfo();
			//updateICInfo.setTestsForLayer(layer, aggTest);
			if(operation != null && (operation.equalsIgnoreCase("deleteMeasures") || operation.equalsIgnoreCase("appendMeasures")))
			{
				//removing aggTest entries from [MEASUREMENT_DB_MAPPING] of eg_db.ini and [DYN_TABLES] of eg_dbase.ini 
				//from secondary managers
				updateICInfo.removeAggTestEntries(aggTest);
			}
			Hashtable testMappingHt = new Hashtable();
			Hashtable defaultTestMappingHt = new Hashtable();
			Hashtable testSpecification = new Hashtable();
			Hashtable aggregateTestsHt = new Hashtable();
			IniFile specsIni = new IniFile(EgInstallInfo.getInstallDir()+"/manager/config/eg_specs.ini");
			String test_spec_var[] = specsIni.getVariables("TEST_SPECIFICATION");

			if(operation != null && !operation.equalsIgnoreCase("deleteMeasures"))
			{
				String host_layer_tests = specsIni.getValue("TEST_MAPPING","Host_system");
				String tempStr = ","+host_layer_tests+",";
				if(tempStr.indexOf(","+test+",")>-1 && tempStr.indexOf(","+aggTest+",")<0)
				{
					testMappingHt.put("Host_system",(host_layer_tests + "," + aggTest));
				}
				String aggTests[] = specsIni.getVariables("AGGREGATE_TESTS");
				if(aggTests == null || aggTests.length==0 || !Arrays.asList(aggTests).contains(aggTest))
				{
					aggregateTestsHt.put(aggTest,"yes");
				}
			}
			ArrayList agg_measures = new ArrayList();
			ArrayList agg_test_measure = new ArrayList();
			ArrayList normal_test_measure = new ArrayList();
			aggregateInfo = new EgAggregateInfo("manager");
			String variables[] = aggregateInfo.getVariables("COLUMN_NAME_MAPPING");
			if(variables != null && variables.length>0)
			{
				for(int i=0;i<variables.length;i++)
				{
					if(variables[i].startsWith((aggTest+":")))
					{
						agg_test_measure.add(variables[i]);
						normal_test_measure.add(aggregateInfo.getValue("COLUMN_NAME_MAPPING",variables[i]));
					}
				}
				String agg_test_msr = null;
				for(int i=0;i<agg_test_measure.size();i++)
				{
					agg_test_msr = (String)agg_test_measure.get(i);
					agg_measures.add(agg_test_msr.substring(agg_test_msr.indexOf(":")+1));
				}
			}

			Vector TEST_SPECIFICATION_VARS = (Vector)specsIni.getVariables("TEST_SPECIFICATION",true).clone();
			Vector TEST_SPECIFICATION_VALS = (Vector)specsIni.getAllValues("TEST_SPECIFICATION").clone();

			Vector TEST_MAPPING_VARS = (Vector)specsIni.getVariables("TEST_MAPPING",true).clone();
			Vector TEST_MAPPING_VALS = (Vector)specsIni.getAllValues("TEST_MAPPING").clone();

			Vector DEFAULT_TEST_MAPPING_VARS = (Vector)specsIni.getVariables("DEFAULT_TEST_MAPPING",true).clone();
			Vector DEFAULT_TEST_MAPPING_VALS = (Vector)specsIni.getAllValues("DEFAULT_TEST_MAPPING").clone();

			String layer_array[] = null;
			if(!StringUtils.isNull(layer))
			{
				EgTesterInfo testerInfo = new EgTesterInfo("manager");
				boolean externalAgentRunsAllAggTests = testerInfo.externalAgentRunsAllAggTests();
				String server = null;
				String ex_tests = null;
				String INDIVIDUAL_SREVER_TYPE = null;
				String test_spec = null;
				String agg_test_spec =  null;
				String dummy123 = null;
				String spec_val = null;
				String m_count="";
				String normal_tests = null;
				boolean addthis = false;
				layer_array = StringUtils.getTokens(layer,",");
				for(int m=0;m<layer_array.length;m++)
				{
					layer = layer_array[m];
					ArrayList servers = tablesInfo.getServersForLayer(layer, true);
					if(servers != null && servers.size()>0)
					{
						for(int n=0;n<servers.size();n++)
						{
							server = (String) servers.get(n);
							if(server.startsWith("Agg_"))
							{
								INDIVIDUAL_SREVER_TYPE = server.substring(server.indexOf("_")+1);
								int index1 = TEST_MAPPING_VARS.indexOf(INDIVIDUAL_SREVER_TYPE);
								if(index1==-1)
								{
									//ic_component_type was created. after that, ic_aggregate_component_type was created. then ic_aggregate_test is created from this ic_component_type. after that, ic_component _type was deleted. Now you are trying to modify the ic_aggregate _test which was created from ic_component_type to this ic_aggregate_component type. You will nont find any entry in eg_specs.ini for this ic_component_type.
									continue;
								}
								//normal_tests = ","+specsIni.getValue("TEST_MAPPING",server.substring(4))+",";
								if(index1==-1)
								{
									normal_tests = null;
								}
								else
								{
									normal_tests = ","+removeSpaces(TEST_MAPPING_VALS.get(index1).toString())+",";
								}
								addthis = normal_tests.indexOf((","+test+","))>=0;
								if(operation != null && !operation.equalsIgnoreCase("deleteMeasures"))
								{
									int index2 = DEFAULT_TEST_MAPPING_VARS.indexOf(server);
									//ex_tests = specsIni.getValue("DEFAULT_TEST_MAPPING",server);
									if(index2==-1)
									{
										ex_tests = null;
									}
									else
									{
										ex_tests = removeSpaces(DEFAULT_TEST_MAPPING_VALS.get(index2).toString());
									}

									String normal_tests_dtm = "";
									int index3 = DEFAULT_TEST_MAPPING_VARS.indexOf(INDIVIDUAL_SREVER_TYPE);
									if(index3==-1)
									{
										normal_tests_dtm = "";
									}
									else
									{
										normal_tests_dtm = ","+removeSpaces(DEFAULT_TEST_MAPPING_VALS.get(index3).toString())+",";
									}
									boolean addthis_dtm = normal_tests_dtm.indexOf((","+test+","))>=0;
									if(addthis_dtm)
									{
										if(!StringUtils.isNull(ex_tests))
										{
											ex_tests = ex_tests+",";
											if(ex_tests.indexOf(aggTest+",")==-1)
											{
												defaultTestMappingHt.put(server,ex_tests+aggTest);
											}
										}
										else
										{
											defaultTestMappingHt.put(server,aggTest);
										}
									}
									int index4 = TEST_MAPPING_VARS.indexOf(server);
									//ex_tests = specsIni.getValue("TEST_MAPPING",server);
									if(index4==-1)
									{
										ex_tests = null;
									}
									else
									{
										ex_tests = removeSpaces(TEST_MAPPING_VALS.get(index4).toString());
									}
									if(addthis && selectedCompType.equals(INDIVIDUAL_SREVER_TYPE))
									{
										if(!StringUtils.isNull(ex_tests))
										{
											ex_tests = ex_tests+",";
											if(ex_tests.indexOf(aggTest+",")==-1)
											{
												testMappingHt.put(server,ex_tests+aggTest);
											}
										}
										else if(addthis)
										{
											testMappingHt.put(server,aggTest);
										}
									}
								}
								test_spec = findTest(test,INDIVIDUAL_SREVER_TYPE,test_spec_var);
								agg_test_spec = test_spec;
								dummy123 = ":"+INDIVIDUAL_SREVER_TYPE+":";
								if(test_spec != null)// && test_spec.indexOf(dummy123)>0)
								{
									/*
										get the default test period of individual test and
										assign it to default test period of this aggregate test.
									*/
									int index5 = TEST_SPECIFICATION_VARS.indexOf(test_spec);
									String defaultTestPeriod = null;
									if(index5>-1)
									{
										defaultTestPeriod = (String)TEST_SPECIFICATION_VALS.get(index5);
										defaultTestPeriod = defaultTestPeriod.substring(defaultTestPeriod.lastIndexOf(",")+1).trim();
									}
									if(defaultTestPeriod == null || defaultTestPeriod.length()==0)
									{
										defaultTestPeriod = "300";//5 minutes
									}
									agg_test_spec = aggTest + agg_test_spec.substring(agg_test_spec.indexOf(":"));
									agg_test_spec = StringUtils.replace(agg_test_spec,INDIVIDUAL_SREVER_TYPE,server);
									m_count = ""+agg_measures.size();
									if(portBased)
									{
										if(externalAgentRunsAllAggTests)
										{
											spec_val = "$EG_SERVER,-auto, -host $hostIp -port $portNo -action_on_descriptors include -include_descriptors all -excludeDescriptor none -aggregateDescriptor "+descriptorAggregation+" -agentless y -rptName $hostName -mCount "+m_count+", "+defaultTestPeriod;
										}
										else
										{
											spec_val = "$hostName,-auto, -host $hostIp -port $portNo -action_on_descriptors include -include_descriptors all -excludeDescriptor none -aggregateDescriptor "+descriptorAggregation+" -agentless y -rptName $hostName -mCount "+m_count+", "+defaultTestPeriod;
										}
									}
									else
									{
										if(externalAgentRunsAllAggTests)
										{
											spec_val = "$EG_SERVER,-auto, -host $hostIp -action_on_descriptors include -include_descriptors all -excludeDescriptor none -aggregateDescriptor "+descriptorAggregation+" -agentless y -rptName $hostName -mCount "+m_count+", "+defaultTestPeriod;
										}
										else
										{
											spec_val = "$hostName,-auto, -host $hostIp -action_on_descriptors include -include_descriptors all -excludeDescriptor none -aggregateDescriptor "+descriptorAggregation+" -agentless y -rptName $hostName -mCount "+m_count+", "+defaultTestPeriod;
										}
									}
									if(agg_test_spec.endsWith(":$sid"))
									{
										agg_test_spec = agg_test_spec.substring(0,agg_test_spec.lastIndexOf(":$sid"));
									}
									testSpecification.put(agg_test_spec,spec_val);
									spec_val = "";
								}
							}
						}
					}
				}
			}
			Vector specVec = new Vector();
			specVec.add(testMappingHt);
			specVec.add(defaultTestMappingHt);
			specVec.add(testSpecification);
			specVec.add(aggregateTestsHt);
			updateICInfo.updateSpecsForServer(specVec);
		}
		//EgDefault.jsp?server=null&qctr=0&page=true&t_name="+aggTest+"&normalTestName="+test
	}
	rootJson.put("success","true");
	out.println(rootJson.toString());
%>
<%!
	/*****************************************************************
	* below method is copied from EgSpecsInfo.java
	* public String findTest ()
	* 	find a the right test in the test mapping section
	*	e.g., ProcessTest:: or ProcessTest:Web_server:...
	******************************************************************/
	public String findTest(String test, String server,String vars[])
	{
		int c = vars.length;
		StringBuffer sb = new StringBuffer(128);
		synchronized (sb)
		{
			sb.append(test);
			sb.append(":");
			sb.append(server);
			sb.append(":");
		}
		String s = sb.toString();
		for (int i = 0; i < c; i++)
		{
			if (vars[i].startsWith(s))
				return (vars[i]);
		}
		StringBuffer sb2 = new StringBuffer(128);
		synchronized (sb2)
		{
			sb2.append(test);
			sb2.append("::");
		}
		s = sb2.toString();
		for (int i = 0; i < c; i++)
		{
			if (vars[i].startsWith(s))
				return (vars[i]);
		}
		return (null);
	}

	private void deleteTestFromUserThresholds(String test)
	{
		IniFile threshFilePtr = EgConfigFilesSync.getInstance(EgInstallInfo.getInstallDir()+"/manager/config/eg_thresholds.ini");
		String[] variables=threshFilePtr.getVariables("USER_THRESHOLDS");
		boolean flag = false;
		if (variables!=null)
		{
			for (int i=0;i<variables.length ;i++ )
			{
				if (variables[i].startsWith(test+":"))
				{
					flag = true;
					threshFilePtr.deleteValue("USER_THRESHOLDS", variables[i]);
				}
			}
		}

		if(flag)
		{
			threshFilePtr.saveFile();
		}
		EgConfigFilesSync.releaseInstance(threshFilePtr);
	}
	String removeSpaces(String tests)
	{
		if(tests != null && tests.trim().length()>0)
		{
			StringBuffer sb = new StringBuffer(128);
			StringTokenizer tokens = new StringTokenizer(tests,",");
			while(tokens.hasMoreTokens())
			{
				sb.append(tokens.nextToken().trim());
				sb.append(",");
			}
			tests = sb.toString();
			tests = tests.substring(0,tests.length()-1);
		}
		return tests;
	}
%>