<%
/*
 *		Name			:		EgmodifymeasurespJson.jsp
 *		Purpose			:		Process page for IC Test - Measures modify page 
*/
%>

<%@ include file = "../../EgTrackerAJSON.jsp"%>
<%@ page language = "java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@ page import = "com.egurkha.admin.AuditLogThread"%>
<%@ page import = "egurkha.*" %>
<%@ page import = "com.egurkha.util.StringUtils" %>
<%@ page import = "net.sf.json.JSONObject"%>

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


<%
	JSONObject rootJSON = new JSONObject();
	rootJSON.put("success","true");
	ServiceBean serviceBean = new ServiceBean();
	//IniFile iniFile=new IniFile(EgInstallInfo.getInstallDir()+"/manager/config/eg_udtests.ini",true);
	/* 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","Integration Console");
	auditLogThread.setValue("Activity","Configure Test");
	Hashtable factorsMapping = new Hashtable();
	//factorsMapping = (Hashtable) session.getAttribute("factorsMapping");
	//session.removeAttribute("factorsMapping");
	IniFile iniUI = new IniFile(EgInstallInfo.getInstallDir() + "/manager/config/eg_ui.ini");
	String factors [] = iniUI.getVariables("CONVERSION_FACTORS");
	if(factors != null && factors.length > 0)
	{
		for (int i=0;i<factors.length;i++)
		{
			String var = (String) factors[i];
			String val = iniUI.getValue("CONVERSION_FACTORS", var);
			factorsMapping.put(val, var);
		}		
	}
	Enumeration en = request.getParameterNames();
	while(en.hasMoreElements())
	{
		String name = ((String) en.nextElement()).toString().trim();
		if(name != null && !name.equalsIgnoreCase("null") && name.length()>0 && name.startsWith("$_"))
		{
			if(name.equals("$_mfactor") || name.equals("$_factor1"))
				continue;
			String value = request.getParameter(name);
			if(value != null && !value.equalsIgnoreCase("null") && value.length()>0 && value.indexOf("$") !=-1)
			{
				String label = null;
				String labelValue = null;
				StringTokenizer stokens = new StringTokenizer(value,"$");
				if(stokens.countTokens()==2)
				{
					label = stokens.nextToken().toString();
					labelValue = stokens.nextToken();
				}
				else
				{
					label = stokens.nextToken();
					labelValue = "";
				}
				if(label != null && labelValue != null && !labelValue.equalsIgnoreCase("null") && labelValue.trim().length()>0)
				{
					labelValue = labelValue.startsWith("_")?labelValue.substring(1):labelValue;
					if(name.equals("$_fnt"))
						labelValue = labelValue +" * "+ request.getParameter("$_mfactor")+" *" + request.getParameter("$_factor1");
					if(name.substring(2).equals("s_factor"))
					{
						String str = request.getParameter("$_cFactor");
						str=EgUIUtils.decodeSecurityChar(str);
						str = str.substring(str.indexOf("$")+1);
						labelValue = (String)factorsMapping.get(str);
					}
					auditLogThread.setPreviousValue(label, labelValue.trim());
				}
				String currentValue = request.getParameter(name.substring(2));
				if(currentValue == null || currentValue.equalsIgnoreCase("null") && currentValue.trim().length()==0)
					continue;
				currentValue = currentValue.trim();
				if(currentValue.length()>0)
				{
					if(name.substring(2).equals("mname"))
						currentValue = currentValue.substring(0,currentValue.indexOf(","));
					if(name.substring(2).equals("fnt"))
						currentValue = currentValue +" * "+ request.getParameter("mfactor") +" *" + request.getParameter("factor1");
					if(name.substring(2).equals("s_factor"))
						currentValue = (String)factorsMapping.get(request.getParameter("s_factor"));
					auditLogThread.setCurrentValue(label, currentValue.trim());
				}
			}
		}
	}	
	/* code for auditlog ends */
	String test = request.getParameter("test");
	String testType = request.getParameter("testtype");
	String org_measure = request.getParameter("org_measure");
	org_measure = EgUIUtils.decodeSecurityChar(org_measure);
	String org_process = request.getParameter("org_process");
	String org_factor = request.getParameter("org_factor");
	String org_counter = request.getParameter("org_counter");
	String org_oid = request.getParameter("org_oid");
	String fileName=request.getParameter("fileName");
	String measure = request.getParameter("s_measure");
	measure = EgUIUtils.decodeSecurityChar(measure);
	String mbean = request.getParameter("mbean");
	String mbeanDisplayVal = request.getParameter("mbeanDispVal");
	
	if (org_counter != null)
	{
		org_counter = EgUIUtils.decodeSecurityChar(org_counter);
	}

	IniFile iniFile=EgConfigFilesSync.getInstance(EgInstallInfo.getInstallDir()+"/manager/config/eg_udtests.ini",true);
	if(fileName!=null && !fileName.equals(""))
	{
		String key="";
			if(org_measure.equals(measure))
			{
				key=test+"#"+org_measure+":"+"ObjectOID";
			}
			else
			{
				if(org_measure.indexOf(":")>0)
				{
					String oldmeasurename=org_measure.substring(0,org_measure.indexOf(":"));
					iniFile.deleteValue("TEST_MIBFILE_MAPPING",test+"#"+oldmeasurename+":"+"ObjectOID");
				}
				key=test+"#"+measure+":"+"ObjectOID";
			}
			iniFile.setValue("TEST_MIBFILE_MAPPING",key,fileName);
			iniFile.saveFile();
	}
	EgConfigFilesSync.releaseInstance(iniFile);
	boolean isConfigTest=EgInstallInfo.isConfigTest(test);

	String process = request.getParameter("s_process");
	if(process == null || process.length() == 0)
		process = "";

	String factor = request.getParameter("s_factor");
	if(factor == null || factor.length() == 0)
		factor = "none";

	String counter = request.getParameter("s_counter");
	if(counter == null || counter.length() == 0)
		counter = "";
	counter = EgUIUtils.decodeSecurityChar(counter);
	String oid = request.getParameter("s_oid");
	if(oid == null || oid.length() == 0)
		oid = "";

	String dbSize = request.getParameter("s_dbsize");
	dbSize = EgUIUtils.decodeSecurityChar(dbSize);
	String unitA = request.getParameter("s_otherunit");
	String unitB = request.getParameter("s_un");
	unitB = EgUIUtils.decodeSecurityChar(unitB);
	String index = request.getParameter("index");
	String callPage = request.getParameter("callPage");
	callPage = EgUIUtils.decodeSecurityChar(callPage);
	String exceptionMsg = request.getParameter("s_alarmdescription");
	String oldRESTDataColumn = request.getParameter("oldRESTDataColumn");
	String restdatafld = request.getParameter("restdatafld");
	String restParentNode = request.getParameter("restParentNode");
	String mbeanAttr = request.getParameter("s_mBeanArributes");
	String domainName = request.getParameter("domain");
	if(!testType.equalsIgnoreCase("Jmx"))
	{
		exceptionMsg = request.getParameter("alarmdescription");
	}

	if(domainName != null && domainName.length() > 0 && !domainName.equals(""))
		session.setAttribute("domainName", domainName);
	String unit = null;
	String org_measure_name = null;
	

	//skm
	EgAggregateInfo aggregateInfo = null;
	String new_fname = null;
	String new_measurename = null;
	String new_factor = null;
	String new_factor1 = null;
	EgDbInfo dbInfo = null;
	
	if (testType.equalsIgnoreCase("Aggregate"))
	{
		unit = request.getParameter("unit");
		
		org_measure_name = org_measure.substring(0,org_measure.indexOf(":"));
		
		String mname = request.getParameter("mname");
		new_measurename = mname.substring(0,mname.indexOf(","));
		new_fname = request.getParameter("fnt");

		aggregateInfo = new EgAggregateInfo("manager");
		
		dbInfo = new EgDbInfo("manager"); 
		String wrappedTest = aggregateInfo.getWrappedTest(test);
		String temp_new_measurename = dbInfo.getColumnForMeasure(wrappedTest,new_measurename);
		if(!temp_new_measurename.equals(""))
		{
			new_measurename = temp_new_measurename;
		}

		new_factor = request.getParameter("mfactor");
		new_factor1 = request.getParameter("factor1");
		if (new_factor.equalsIgnoreCase("none"))
			new_factor = "1";
		if(!new_factor1.equals("1"))
		{
			try
			{
				double d = Double.parseDouble(new_factor1);
				new_factor1 = ""+d;
			}
			catch(NumberFormatException nfe)
			{
				new_factor1 = "1";
			}
		}
	} //skm
	else
	{
		if(unitA == null || unitA.length() == 0)
			unit = unitB;
		else
			unit = unitA;
		
		if((isConfigTest) && unit==null)
			unit="NONE";

	}

	if(mbeanAttr == null || mbeanAttr.length() == 0)
	{
		mbeanAttr = "";
	}
	else
	{
		counter = mbeanAttr;
	}
	
	TestBean testBean = new TestBean(true);
	if(testType != null)
	{
		String tmpOrgMeas = org_measure;
		if(org_measure.indexOf(":")>0)
		{
			tmpOrgMeas = org_measure.substring(0,org_measure.indexOf(":"));
		}
		if(!tmpOrgMeas.equals(measure) && testBean.doesMeasureExistFor(measure, test))
		{
			rootJSON.put("AlertType","Error");
			rootJSON.put("AlertTitle",_mapping.getTextDescription("admin.error.Modify test measures"));
			String msg = _mapping.getTextDescription("admin.ic.You are trying to modify a measure name which is already existing for this test")+". ";
			msg += _mapping.getTextDescription("admin.ic.Please enter a new measure name");
			rootJSON.put("AlertMsg",msg);
			
			/* code for auditlog starts */
			auditLogThread.setValue("Description","You are trying to modify a measure name " + measure + " which is already existing for the test " + test);
			auditLogThread.sendItToDB();
			/* code for auditlog ends */
		}
		else
		{
			boolean status = false;
			restdatafld=restParentNode+"|^|"+restdatafld;
			if(exceptionMsg!= null)
			{
				status = testBean.modifyMeasureForTest(test, measure,dbSize, unit, index, process, factor, counter, mbeanDisplayVal, oid,org_measure, org_process, org_factor, org_counter, org_oid,oldRESTDataColumn,restdatafld,exceptionMsg);
			}
			else
			{
				status = testBean.modifyMeasureForTest(test, measure,dbSize, unit, index, process, factor, counter, mbeanDisplayVal, oid,org_measure, org_process, org_factor, org_counter,org_oid,oldRESTDataColumn, restdatafld);
			}
			testBean.addMbeanForMeasure(test,measure,mbeanDisplayVal);
			if(status)
			{
				if (testType.equalsIgnoreCase("Aggregate")) //skm
				{
					// commented by Thirumal  Friday, July 14, 2006
					aggregateInfo.deleteValue("AGGREGATE_FUNCTION",test + ":" + org_measure_name.toUpperCase());
					aggregateInfo.setValue("AGGREGATE_FUNCTION", test+":"+measure.toUpperCase(), new_measurename+":"+new_fname+":"+new_factor+"#"+new_factor1);
					String oldMeasureName = request.getParameter("org_measure");
					oldMeasureName = oldMeasureName.substring(0,oldMeasureName.indexOf(":"));
					String measureNameNow = request.getParameter("s_measure");
					
					String newMeasureName = request.getParameter("mname");
					newMeasureName = newMeasureName.substring(0,newMeasureName.indexOf(","));
					
					String normalTestMeasure = aggregateInfo.getValue("AGGREGATE_TEST",test);
					normalTestMeasure += ":" + newMeasureName;
					aggregateInfo.deleteValue("COLUMN_NAME_MAPPING", test+":"+oldMeasureName);
					aggregateInfo.setValue("COLUMN_NAME_MAPPING", test+":"+measure,normalTestMeasure);
					aggregateInfo.saveFile();
				}
				else if (testType.equalsIgnoreCase("REST")) 
				{
					UpdateAndTransmitICInfo updateICInfo = new UpdateAndTransmitICInfo();
					testBean.deleteExistingTest(test);//added by James Thomas to remove records from measure_last and metatest tables for the given test if rows to the test exists.
					if(!testBean.checkIndices(test))
					{
						/* code for auditlog starts */
						auditLogThread.setCurrentValue("Test Name",test);
						auditLogThread.setCurrentValue("Measure Name",measure);
						auditLogThread.setCurrentValue("Measure Index",index);
						auditLogThread.setValue("Description","Inconsistent measure indices for the test" +" "+ test);
						auditLogThread.sendItToDB();
						/* code for auditlog ends */
						rootJSON.put("AlertType","Error");
						rootJSON.put("AlertTitle",_mapping.getTextDescription("admin.ic.Generate a Test"));
						String msg = _mapping.getTextDescription("admin.ic.Inconsistent Measure Indices")+". ";
						msg += _mapping.getTextDescription("admin.ic.Please update the measure indices correctly");
						rootJSON.put("AlertMsg",msg);
					}
					else if(updateICInfo.getConnection())
					{
						/*if(elementOid != null && !elementOid.equals("") && rediscPeriod != null && !rediscPeriod.equals(""))
						{
							if(validOid == null || validOid.equals(""))
								validOid = "none";
							if(validValue == null || validValue.equals(""))
								validValue = "none";
							testBean.setSnmpOID(test, elementOid, validOid, validValue, rediscPeriod);
							testBean.setMultipleValue(test,"true");
						}
						else
						{
							testBean.setMultipleValue(test,"false");
						}*/
						String descriptorbasedtest=request.getParameter("descriptorbasedtest");
						String selDescRestFldVal=request.getParameter("selDescRestFldVal");
					
						if(!StringUtils.isNull(descriptorbasedtest))
						{
							if(!StringUtils.isNull(selDescRestFldVal) && !StringUtils.isNull(restParentNode))
							{
								testBean.setRESTDataFieldForDescriptor(test,selDescRestFldVal,restParentNode);
							}
						}
						testBean.setThresholds(test);
						EgThresholdInfo.setUpdated();
						String error = updateICInfo.setMeasures("REST",test);
						if(error != null && error.length() > 0)
						{
							/* code for auditlog starts */
							auditLogThread.setCurrentValue("Result","eG manager failed to create the required tables and indices for the new test");
							auditLogThread.setCurrentValue("Reason(s)","One or more database keywords are being used as test or measure names");
							auditLogThread.setCurrentValue("Reason(s)","The tablespace allocated to eG manager has no more space left to create tables");
							auditLogThread.setValue("Description","Error while generating test measures for the test" +" "+ test);
							auditLogThread.sendItToDB();
							/* code for auditlog ends */

							rootJSON.put("AlertType","Error");
							rootJSON.put("AlertTitle",_mapping.getTextDescription("admin.ic.Generate a Test"));
							String msg = _mapping.getTextDescription("admin.ic.eG manager failed to create the required tables and indices for the new test")+". <br>";
							msg += _mapping.getTextDescription("admin.ic.Possible Reasons")+" :<br>";
							msg += "1) "+_mapping.getTextDescription("admin.ic.One or more database keywords are being used as test or measure names")+".<br>";
							msg += _mapping.getTextDescription("admin.ic.For Eg* \"varchar\", \"number\", \"offline\" e*t*c are database keywords")+". ";
							msg += _mapping.getTextDescription("admin.ic.One workaround is to use prefixes to existing test name/measure names")+". ";
							msg += _mapping.getTextDescription("admin.ic.Please change these  appropriately and try again")+". <br>";
							msg += "2) "+_mapping.getTextDescription("admin.ic.The tablespace allocated to eG manager has no more space left to create tables")+". ";
							msg += _mapping.getTextDescription("admin.ic.Please increase the tablespace size and try again")+". "+_mapping.getTextDescription("admin.ic.For more information you can check /manager/logs/error_log in the installation directory")+".";
							rootJSON.put("AlertMsg",msg);
						}
						else
						{
							String ur = "EgDefault.jsp?" + "t_name=" + test + "&server=null&qctr=0&page=true";
							if(!EgInstallInfo.isConfigTest(test))
							{
								//ur = "EgDefault.jsp?" + "t_name=" + test + "&server=null&qctr=0&page=true";
								ur = "EgDefaultJson.jsp?" + "t_name=" + test + "&server=null&qctr=0&page=true";
								rootJSON.put("forwardPage",true);
								rootJSON.put("forwardURL",ur);
							}
							else
							{
								rootJSON.put("AlertType","Result");
								rootJSON.put("AlertTitle",_mapping.getTextDescription("admin.ic.Add new tests"));
								rootJSON.put("AlertMsg",_mapping.getTextDescription("admin.ic.The test has been generated successfully")+".");
								//rootJSON.put("AlertMsg",_mapping.getTextDescription("admin.ic.Measures for")+" "+test+_mapping.getTextDescription("admin.ic.Your changes have been updated successfully"));
							}
							/* code for auditlog starts */
							auditLogThread.setValue("Description","Changes have been updated for the test" +" "+ test);
							auditLogThread.sendItToDB();
							/* code for auditlog ends */
						}
					}
				}

				rootJSON.put("AlertType","Result");
				rootJSON.put("AlertTitle",_mapping.getTextDescription("admin.error.Modify test measures"));
				if (testType.equalsIgnoreCase("REST")) 
				{
					rootJSON.put("AlertMsg",_mapping.getTextDescription("admin.ic.Measure has been modified and generated successfully"));
				}
				else
				{
					rootJSON.put("AlertMsg",_mapping.getTextDescription("admin.ic.Measure has been modified successfully")+". "+_mapping.getTextDescription("admin.ic.For the changes to take effect, click GENERATE button")+".");
				}

				/* code for auditlog starts */
				if(test.endsWith("_ex"))
					auditLogThread.setValue("Description","Measure "+measure+" has been modified for the test " +test);
				else
					auditLogThread.setValue("Description","Measure "+measure+" has been modified for the test " + "$test$:"+test);
				auditLogThread.sendItToDB();
				/* code for auditlog ends */
			}
			else
			{
				rootJSON.put("AlertType","Error");
				rootJSON.put("AlertTitle",_mapping.getTextDescription("admin.error.Modify test measures"));
				rootJSON.put("AlertMsg",_mapping.getTextDescription("admin.error.Error while modifying test measures")+".");
				
				/* code for auditlog starts */
				auditLogThread.setValue("Description","Error while modifying "+testType +" "+"test measures");
				auditLogThread.sendItToDB();
				/* code for auditlog ends */
			}
		}
	}
	else
	{
			rootJSON.put("AlertType","Error");
			rootJSON.put("AlertTitle",_mapping.getTextDescription("admin.error.Modify test measures"));
			rootJSON.put("AlertMsg",_mapping.getTextDescription("admin.error.Error while modifying test measures")+". "+_mapping.getTextDescription("admin.ic.Due to insufficient data")+".");
	}
	out.println(rootJSON);
%>




