<%
/*
 *		Name		:		EgconfigperfmonmeasurepJson.jsp
 *		Purpose		:		IC Test - Perfmon Type - Configure process 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 = "net.sf.json.JSONObject"%>
<%@ page import = "com.egurkha.util.*"%>
<%!
	private int getDbSize(int s)
	{
		int size=-1;
		switch(s)
		{
			case 1:size=32;break;
			case 2:size=64;break;
			case 3:size=128;break;
			case 4:size=256;break;
			case 5:size=512;break;
			case 6:size=1024;break;
		}
		return size;
	}
%>

<%
	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");

	Hashtable factorsMapping = new Hashtable();
	//factorsMapping = (Hashtable) session.getAttribute("factorsMapping");
	//session.removeAttribute("factorsMapping");
	IniFile iniUI = new IniFile(EgInstallInfo.getInstallDir() + "/manager/config/eg_ui.ini");
	IniFile iniOS = new IniFile(EgInstallInfo.getInstallDir() + "/manager/config/eg_services.ini");
	String factors [] = iniUI.getVariables("CONVERSION_FACTORS");
	String managerOS = iniOS.getValue("MISC_ARGS","ManagerOS");
	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);
		}		
	}

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

	String add = request.getParameter("add");
	String test = request.getParameter("test");
	String measure = request.getParameter("measure");
	String dbSize = request.getParameter("dbsize");
	String unitA = request.getParameter("otherunit");
	String unitB = EgUIUtils.decodeSecurityChar(request.getParameter("un"));
	String index = request.getParameter("index");
	String process = request.getParameter("process");
	String counter = request.getParameter("counter");
	String exceptionMsg = request.getParameter("alarmdescription");

	String factor = request.getParameter("factor");

	if (factor == null)
		factor="none";
	if (counter != null)
	{
		counter = EgUIUtils.decodeSecurityChar(counter);
	}

	String object = request.getParameter("object");
	String instances = request.getParameter("instances");
	String instances_neg = request.getParameter("instances_neg");
	UpdateAndTransmitICInfo updateICInfo = new UpdateAndTransmitICInfo();

	TestBean testBean = new TestBean(true);
	boolean isConfigTest = EgInstallInfo.isConfigTest(test);
	boolean isDescriptorBasedFlag = false;
	if(isConfigTest)
	{
		String isDecriptorBasedReq = request.getParameter("descVal");
		if(isDecriptorBasedReq != null)
		{
			isDecriptorBasedReq = isDecriptorBasedReq.trim();
			if(isDecriptorBasedReq.equalsIgnoreCase("true"))
			{
				 isDescriptorBasedFlag= true;
			}
		}
	}


	if(add.equals("add"))
	{
		if(testBean.doesMeasureExistFor(measure, test))
		{
			rootJSON.put("AlertType","Error");
			rootJSON.put("AlertTitle",_mapping.getTextDescription("admin.ic.Add Measure To Test"));
			String msg = _mapping.getTextDescription("admin.ic.You are trying to add a measure/db column name which is already existing for this test")+". ";
			msg += _mapping.getTextDescription("admin.ic.Please enter a new measure/db column name pair")+".";
			rootJSON.put("AlertMsg",msg);

			/* code for auditlog starts */
			auditLogThread.setCurrentValue("Test Name",test);
			auditLogThread.setCurrentValue("Measure Name",measure);
			auditLogThread.setValue("Description","You are trying to add a measure/db column name which is already existing for this test");
			auditLogThread.sendItToDB();
			/* code for auditlog ends */
		}
		else if(testBean.doesIndexExist(test, index))
		{
			rootJSON.put("AlertType","Error");
			rootJSON.put("AlertTitle",_mapping.getTextDescription("admin.ic.Add Measure To Test"));
			String msg = _mapping.getTextDescription("admin.ic.You are trying to add an index which is already existing")+". ";
			msg += _mapping.getTextDescription("admin.ic.Please select a new index value")+".";
			rootJSON.put("AlertMsg",msg);

			/* code for auditlog starts */
			auditLogThread.setCurrentValue("Test Name",test);
			auditLogThread.setCurrentValue("Measure Index",index);
			auditLogThread.setValue("Description","You are trying to add an index which is already existing");
			auditLogThread.sendItToDB();
			/* code for auditlog ends */
		}
		else
		{
			String unit = null;
			if(unitA == null || unitA.length() == 0)
				unit = unitB;
			else
				unit = unitA;
			if(exceptionMsg != null && exceptionMsg.trim().length()>0)
				testBean.addMeasureForTestWithAlarm(test, measure, dbSize, unit, process, factor, index, counter, exceptionMsg);
			else
				testBean.addMeasureForTest(test, measure, dbSize, unit, process, factor, index, counter);
			/* code for auditlog starts */
			String myDbSize = "";
			if(dbSize != null && dbSize.equals("1"))
				myDbSize = "Number(7,4)";
			else if(dbSize != null && dbSize.equals("2"))
				myDbSize = "Number(20,4)";
			else if(dbSize != null && dbSize.equals("3"))
				myDbSize = "Number(16)";
			auditLogThread.setCurrentValue("01~~Test Name",test);
			auditLogThread.setCurrentValue("02~~Measure index",index);
			auditLogThread.setCurrentValue("03~~Measure name",measure);
			auditLogThread.setCurrentValue("04~~Database column size",myDbSize);
			auditLogThread.setCurrentValue("05~~Unit",unit);
			auditLogThread.setCurrentValue("06~~Process method",process);
			if(factor != null && factor.trim().length()>0 && !factor.equalsIgnoreCase("null") && !factor.equalsIgnoreCase("none"))
				auditLogThread.setCurrentValue("07~~Conversion factor",(String)factorsMapping.get(factor));
			if(exceptionMsg != null && exceptionMsg.trim().length()>0)
				auditLogThread.setCurrentValue("08~~Alarm display string",exceptionMsg);
			auditLogThread.setCurrentValue("09~~Counter name",counter);
			auditLogThread.setValue("Description","Measure " + measure + " has been added to the test " +test);
			auditLogThread.sendItToDB();
			/* code for auditlog ends */
			String ur = "EgConfigPerfmonMeasureJson.jsp?" +"test=" + test + "&unit=" + "";

			rootJSON.put("AlertType","Result");
			rootJSON.put("AlertTitle",_mapping.getTextDescription("admin.ic.Add Measure To Test"));
			rootJSON.put("AlertMsg",_mapping.getTextDescription("admin.ic.Measure has been added successfully")+".");
			rootJSON.put("forwardPage",true);
			rootJSON.put("forwardURL",ur);
		}
	}
	else if(add.equals("del"))
	{
		testBean.deleteMeasure(test, measure);
		//new code for checking measure index using reviseMeasureIndex method written in TestBean
		testBean.reviseMeasureIndex(test);
		//response.sendRedirect("EgConfigPerfmonMeasure.jsp?" +"test=" + test);
		/* code for auditlog starts */
		auditLogThread.setValue("Description","Measure "+measure+" has been deleted from the test " + test);
		auditLogThread.sendItToDB();
		/* code for auditlog ends */
		String ur = "EgConfigPerfmonMeasureJson.jsp?" +"test=" + test + "&measure=" + "";

		rootJSON.put("AlertType","Result");
		rootJSON.put("AlertTitle",_mapping.getTextDescription("admin.ic.Add Measure To Test"));
		rootJSON.put("AlertMsg",_mapping.getTextDescription("admin.ic.Measure has been deleted successfully")+".");
		rootJSON.put("forwardURL",ur);
	}
	else if(add.equals("gen"))
	{
		//serviceBean.stopDiscovery(); //clustering
		//DbBean dbBean = new DbBean(true); //clustering
		if(!testBean.checkIndices(test))
		{
			/* code for auditlog starts */
			auditLogThread.setCurrentValue("Test Name",test);
			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())   //(dbBean.getConnection())
		{
			testBean.setObject(test, object);//ini
			testBean.setInstances(test, instances, instances_neg);//ini
			testBean.saveTestFile();
			String [] instances1 = null;
			if(EgInstallInfo.isConfigTest(test) && managerOS.equalsIgnoreCase("WINDOWS"))
			{
				testBean.setConfigTestFieldSize(test,getDbSize(Integer.parseInt(dbSize)));
				testBean.checkConfigMeasuresFor(test,isDescriptorBasedFlag);
				instances1 = EgJNIUtil.discoverInstances(object);

				if(isDescriptorBasedFlag)
				{
					if(instances1 == null)
					{
						rootJSON.put("objectError",true);
					}
					else
					{
						rootJSON.put("objectError",false);
					}
				}
				else
				{
					if(instances1 == null)
					{
						rootJSON.put("NonDescriptorObjError",false);
					}
					else
					{
						rootJSON.put("NonDescriptorObjError",true);
					}
				}
			}
			testBean.setThresholds(test);//ini
			EgThresholdInfo.setUpdated();
			String error = updateICInfo.setMeasures("perfmon",test);  // dbBean.setMeasuresFor(test);
			if(error != null && error.length() > 0)
			{
				//dbBean.releaseConnection(); //handled in helper class
				/* 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.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
			{
				//serviceBean.startDiscovery("1"); //moved to helper class clustering
				//dbBean.releaseConnection();      //moved to helper class clustering
				//response.sendRedirect("EgDefault.jsp?" +
				//"t_name=" + test +
				//"&server=null&qctr=0&page=true");
				String ur ="";
				if(!EgInstallInfo.isConfigTest(test))
				{
					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 */
				if(!StringUtils.isNull(object))
					auditLogThread.setCurrentValue("01~~Object name",object);
				if(!StringUtils.isNull(instances))
					auditLogThread.setCurrentValue("02~~Instances to be included",instances);
				if(!StringUtils.isNull(instances_neg))
					auditLogThread.setCurrentValue("03~~Instances to be excluded",instances_neg);
				auditLogThread.setValue("Description","Changes have been updated for the test" +" "+ test);
				auditLogThread.sendItToDB();
				/* code for auditlog ends */
			}
		}
		else
		{
			/* code for auditlog starts */
			auditLogThread.setCurrentValue("Test Name",test);
			auditLogThread.setCurrentValue("Measure Name",measure);
			auditLogThread.setValue("Description","Database connection failed"+". "+"Error while dealing with 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"));
			rootJSON.put("AlertMsg",_mapping.getTextDescription("admin.ic.Database connection failed")+". "+_mapping.getTextDescription("admin.ic.Please check if the database is up and try again")+".");
		}
	}
	out.println(rootJSON);
%>






