<%@ include file="../../EgTrackerAJSON.jsp" %>
<%@ page import="java.io.*" %>
<%@ page import="java.util.*" %>
<%@ page import = "com.egurkha.admin.ComponentAdd"%>
<%@ page import = "com.egurkha.admin.UserAssociateComponent"%>
<%@ page import = "com.egurkha.admin.AuditLogThread"%>

<%@ page import = "com.egurkha.util.StringUtils"%>
<%@ page import= "egurkha.EgUIUtils"%>
<%@ page import = "net.sf.json.*"%>
<%@ page language="java" contentType="text/html;charset=UTF-8" pageEncoding="UTF-8" %>

<%!
	String[] splCompArr = new String[]{"MS_Office_365","Microsoft_Sharepoint_Online","MSExchangeOnline","MS_Skype_Online","Microsoft_Teams","MS_OneDrive_Business"};

	private List getAgents(String componentName)
	{
		List agentsList = new ArrayList();

		EgExternalInfo egExternalInfo = new EgExternalInfo("manager");
		Hashtable internalAgentMap = egExternalInfo.getInternalAgentMap();
		String componentNickName = componentName.substring(0,componentName.indexOf(":"));
		String agentNickName = "";
		boolean isRemote = false;

		//To fetch the exact agent for the selected component - start
		isRemote = egExternalInfo.isRemoteBased(componentNickName);
		if (isRemote)
		{
			//Agentless
			agentNickName = egExternalInfo.getRemoteAgentForHost(componentNickName);
		}
		else
		{
			//Auto or Manual
			String agentName = egExternalInfo.getAgentFor(componentNickName);
			if (agentName != null) //Manual
			{
				if (internalAgentMap != null && internalAgentMap.containsKey(agentName))
				{
					agentNickName = (String)internalAgentMap.get(agentName);
				}
				else
				{
					agentNickName = agentName;
				}
			}
			else //Auto
			{
				agentNickName = componentNickName;
			}
		}

		//adding an internal agent (or) a remote agent
		agentsList.add(agentNickName);
		//To fetch the exact agent for the selected component - end

		//To fetch the external agent for the selected component type - starts
		boolean hasExternalAgent = egExternalInfo.hasExternalAgent(componentNickName);
		if (hasExternalAgent)
		{
			String extAgents[] = egExternalInfo.getExternalAgentsForHost(componentNickName);
			//adding one or more external agent(s)
			agentsList.addAll(Arrays.asList(extAgents));
		}
		//To fetch the external agent for the selected component type - ends
		return agentsList;
	}
%>

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

	JSONObject rootJSON = new JSONObject();
	rootJSON.put("success","true");
	ComponentAdd compAdd;

	EgExternalInfo externalInfo = new EgExternalInfo("manager");
	EgSpecsInfo egSpecs = new EgSpecsInfo("manager");

	Hashtable compDetails = new Hashtable();
	Hashtable statusMap = new Hashtable();
	String checkBoxValues = request.getParameter("checkBoxValues");
	String checkBoxValuesModify = request.getParameter("checkBoxValuesModify");
	String hostname = request.getParameter("hostname");
	String hostip = request.getParameter("hostip");
	String stype = "MS_Office_365";
	String enableRmtAgent = "true";
	String remoteType = "true";
	String remotemode = "Other";
	String remotealos = "Other";
	String remoteAgent = "";

	String strRemAgent = request.getParameter("remoteAgent");
	if (strRemAgent != null && strRemAgent.trim().length() > 0)
	{
		remoteAgent = strRemAgent;
	}

	String remoteUser = request.getParameter("aluser");
	String remotepwd = request.getParameter("alpwd");
	String sshPort = "";
	String remoteEncrypt = "";
	String remoteKeyFile = "";
	String currAgent = "";
	String extAgentStr = "";
	boolean modifying = false;
	String prevRemAgent = externalInfo.getRemoteAgentForHost(hostname);
	
	String user_id = _user.getLoginID();
	EgMappingInfo mappingInfo = new EgMappingInfo(_user.getLanguage());
	EgRoleInfo egRoleInfo = EgRoleInfo.getInstance(session.getId(),(String)session.getAttribute("sess_userid"));
	UserAssociateComponent uacObj = new UserAssociateComponent(user_id,_user.getUserIP(session.getId()),session.getId());
	EgUuidInfo uuidInfo = new EgUuidInfo();
	boolean isLimitedAdmin = !egRoleInfo.hasAllComponentAccess();
	boolean isMspModel = EgUuidInfo.isMspModel();
	boolean autoCreateZoneForUser = EgUuidInfo.autoCreateZone();

	IniFile externalIni = new IniFile(EgConfigInfo.egMgrConfigDir + "eg_external.ini");
	String[] nickAloneTypes = externalIni.getVariables("NickName_Alone_Servers");
	List nickAloneTypesList = (nickAloneTypes != null) ? Arrays.asList(nickAloneTypes) : new ArrayList();
	boolean hideHostIPField = (nickAloneTypesList.contains(stype));
	if (hideHostIPField)
	{
		hostip = hostname;
	}

	ArrayList extIniEntries = new ArrayList();
	Hashtable operatingSystems = new Hashtable();
	IniFile extIniObj = new IniFile(EgConfigInfo.egMgrConfigDir + "eg_external.ini");
	String variables[] = extIniObj.getVariables("Default_Operating_Systems");
	Vector values = extIniObj.getAllValues("Default_Operating_Systems");
	if(variables != null && variables.length>0)
	{
		for(int ind=0;ind<variables.length;ind++)
		{
			operatingSystems.put(variables[ind],values.get(ind));
		}
	}

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

	//Expected error codes returned from ComponentAdd and ComponentModify class files
	String[] errCodes = new String[]{"eG_CLI_0032","eG_CLI_0033","eG_CLI_0034","eG_CLI_0035","eG_CLI_0036","eG_CLI_0037","eG_CLI_0038","eG_CLI_Err_0336","eG_CLI_Err_0337","eG_CLI_Err_0338","eG_CLI_Err_0339","eG_CLI_Err_0344","eG_CLI_Err_0345","eG_CLI_Err_0346","eG_CLI_Err_0347"};
	ArrayList errCodeList = new ArrayList(Arrays.asList(errCodes));

	egurkha.ConfigTopology EgConfigTopo = new egurkha.ConfigTopology();
	EgConfigTopo.createFile("eg_services.ini");
	EgDiscInfo egDiscInfo = new EgDiscInfo("manager");
	EgServicesInfo servicesInfo = new EgServicesInfo("manager");
	boolean isAllowHostName = servicesInfo.isAllowHostNames();
	int compSize = Integer.parseInt(EgConfigTopo.getValues("MISC_ARGS","MaxManagedComponentsForDisc"));
	boolean hasLimitExceeded=false;
	Vector managedAllComps = egDiscInfo.getAllManagedComponents();
	if (managedAllComps != null && (managedAllComps.size() > compSize))
	{
		hasLimitExceeded = true;
	}


	String[] testConfigParams = {"O365_User_Name","O365_Password","Domain_User_Name","Domain_Password","Domain_Name","Proxy_Host","Proxy_Port","Proxy_User_Name","Proxy_Password"};
	ArrayList testConfigParamsList = new ArrayList(Arrays.asList(testConfigParams));
	String testConfigParamsEntry = "";
	JSONObject hiddenParams = new JSONObject();
	Enumeration ep = request.getParameterNames();

	JSONArray encodeParamList = new JSONArray();
	if(session.getAttribute("encodeParamJsonList") != null)
	{
		encodeParamList = (JSONArray)session.getAttribute("encodeParamJsonList");
	}

	while(ep.hasMoreElements())
	{
		String name = (String) ep.nextElement();
		String value = request.getParameter(name);

		if(encodeParamList != null && encodeParamList.contains(name))
		{
			value = EgUIUtils.decodeSecurityChar(value);
		}

		if (name.equalsIgnoreCase("O365_Password") || name.equalsIgnoreCase("Domain_Password") || name.equalsIgnoreCase("Proxy_Password"))
		{
			value = EgCrypt.decrypt(value);
			value = EgCrypt.encrypt(value);
		}
		else
		{
			if (value.indexOf(" -") > -1)
			{
				if (!value.startsWith("\"") && !value.endsWith("\""))
				{
					value = "\"" + value + "\"";
				}
			}
		}

		if (testConfigParamsList.contains(name))
		{
			testConfigParamsEntry +=" -"+name+" "+value;
		}
		hiddenParams.put(name,value);
	}

	rootJSON.put("hiddenParams",hiddenParams);

	String extAgent = "";
	EgUserElementsInfo userElmentsObj = new EgUserElementsInfo();
	ArrayList extagentsList = null;

	if (isLimitedAdmin)
	{
		extagentsList = userElmentsObj.getExternalAgentsForUser(user_id);
	}

	if (extagentsList == null || extagentsList.isEmpty())
	{
		extagentsList = new ArrayList();
		EgSpecsInfo specs = new EgSpecsInfo("manager");
		String defaultExtAgent = specs.getEGServer();
		extagentsList.add(defaultExtAgent);
	}

	if (extagentsList != null && extagentsList.size() > 0)
	{
		if (extagentsList.contains(remoteAgent))
		{
			extAgent = remoteAgent;
		}
		else
		{
			extAgent = (String)extagentsList.get(0);
		}
	}
	else
	{
		rootJSON.put("errorMsg","The component(s) could not be created. External agent is not available for external monitoring.");
		rootJSON.put("success","false");

		session.setAttribute("adminLastAccessedURL","/final/admin/EgAdminOperations.jsp?"+request.getQueryString());
		out.println(rootJSON.toString());
		return;
	}

	boolean hasMoreComponents = false;

	String[] componentsArr = StringUtils.getTokens(checkBoxValues, ",");
	String[] componentsArrModify = StringUtils.getTokens(checkBoxValuesModify, ",");
	if (componentsArr != null || componentsArrModify != null)
	{
		egurkha.ServiceBean servicer = new egurkha.ServiceBean();
		servicer.stopDiscovery();
		
		if (componentsArr != null)
		{
			int compArrLen = componentsArr.length;
			String hostnameOrigin = hostname;
			for (int m=0; m<compArrLen; m++)
			{
				String tempHostName = hostname;
				//int pos = tempHostName.lastIndexOf("_");
				//hostname = (pos > -1) ? tempHostName.substring(0,pos) : tempHostName;
				compAdd = new ComponentAdd(_user.getLoginID(),_user.getUserIP(session.getId()),session.getId());
				if (componentsArr[m].equalsIgnoreCase("365"))
				{
					stype = "MS_Office_365";
					tempHostName += "_365";
					hostip = (hideHostIPField) ? tempHostName : hostip;
					hostnameOrigin = tempHostName;
				}
				else if (componentsArr[m].equalsIgnoreCase("spo"))
				{
					stype = "Microsoft_Sharepoint_Online";
					tempHostName += "_spo";
					hostip = (hideHostIPField) ? tempHostName : hostip;
					hostnameOrigin = tempHostName;
				}
				else if (componentsArr[m].equalsIgnoreCase("exo"))
				{
					stype = "MSExchangeOnline";
					tempHostName += "_exo";
					hostip = (hideHostIPField) ? tempHostName : hostip;
					hostnameOrigin = tempHostName;
				}
				else if (componentsArr[m].equalsIgnoreCase("sbo"))
				{
					stype = "MS_Skype_Online";
					tempHostName += "_sbo";
					hostip = (hideHostIPField) ? tempHostName : hostip;
					hostnameOrigin = tempHostName;
				}
				else if (componentsArr[m].equalsIgnoreCase("mtm"))
				{
					stype = "Microsoft_Teams";
					tempHostName += "_mtm";
					hostip = (hideHostIPField) ? tempHostName : hostip;
					hostnameOrigin = tempHostName;
				}
				else if (componentsArr[m].equalsIgnoreCase("odb"))
				{
					stype = "MS_OneDrive_Business";
					tempHostName += "_odb";
					hostip = (hideHostIPField) ? tempHostName : hostip;
					hostnameOrigin = tempHostName;
				}

				compDetails = new Hashtable();
				compDetails.put("componenttype",stype);
				compDetails.put("hostip",hostip);
				compDetails.put("componentname",tempHostName);
				compDetails.put("port","NULL");
				prevRemAgent = externalInfo.getRemoteAgentForHost(tempHostName);

				if (remoteType != null && (remoteType.equalsIgnoreCase("true") || remoteType.equalsIgnoreCase("yes")))
				{
					compDetails.put("agentless","yes");
					compDetails.put("mode",remotemode);
					if (remotealos != null && remotealos.length()>0)
					{
						String remoteOS = remotealos;
						if (operatingSystems.containsKey(remotealos))
						{
							remoteOS = operatingSystems.get(remotealos).toString();
						}
						compDetails.put("os",remoteOS);
					}
					compDetails.put("remoteagent",remoteAgent);
					if (remoteUser != null && remoteUser.length()>0)
					{
						compDetails.put("remoteuser",remoteUser);
					}
					if (remotepwd != null && remotepwd.length()>0)
					{
						compDetails.put("remotepwd",remotepwd);
					}
					if (sshPort != null && sshPort.length()>0)
					{
						compDetails.put("remoteport",sshPort);
					}
					if (remoteEncrypt != null && remoteEncrypt.length()>0)
					{
						compDetails.put("encrypttype",remoteEncrypt);
					}
					if (remoteKeyFile != null && remoteKeyFile.length()>0)
					{
						compDetails.put("keyfilename",remoteKeyFile);
					}
				}

				compDetails.put("externalagent",extAgent);
				if (isLimitedAdmin && user_id != null && user_id.length() > 0)
				{
					compDetails.put("CompUserMapping","yes");
					compDetails.put("uuiduser",user_id);
				}
				String statusStr = compAdd.add(compDetails);
				String tempElemStr = stype+"#"+tempHostName;
				if (statusMap.containsKey(statusStr))
				{
					String tempPrevElemStr = statusMap.get(statusStr).toString().trim();
					tempElemStr = tempPrevElemStr + "|$|" + tempElemStr;
				}
				statusMap.put(statusStr,tempElemStr);
				/* code for user comp association starts */
				if (isLimitedAdmin && !modifying && statusStr.equalsIgnoreCase("eG_CLI_0030"))
				{
					Hashtable argsMap = new Hashtable();
					String resultStr = "";
					String compName = tempHostName + ":" + "NULL";
					argsMap.put("userid",user_id);
					argsMap.put("componenttype",stype);
					argsMap.put("components",compName);
					argsMap.put("autoassociatetype","no");
					resultStr = uacObj.AssociateComponent(argsMap);

					//If autoCreateZoneForUser is set to true, then assign the component(s) to the user's zone.
					if (autoCreateZoneForUser && resultStr.length()>0 && resultStr.equalsIgnoreCase("eG_CLI_Res_0286"))
					{
						argsMap = new Hashtable();
						argsMap.put("userid",user_id);
						argsMap.put("stype",stype);
						argsMap.put("compname",compName);
						Hashtable resultMap = uacObj.AutoAssociateComponentToZone(argsMap);

						//associate zones to user and for zone audit log
						if (resultMap != null && !resultMap.isEmpty())
						{
							IniFile mgrMiscIni = new IniFile(EgInstallInfo.getInstallDir() + "/manager/config/eg_mgrmisc.ini");
							String associatedUsers = "";
							String associaedZones = "", disAssociatedZones = "";
							Enumeration enMapKeys = resultMap.keys();
							while (enMapKeys.hasMoreElements())
							{
								String userName = (String)enMapKeys.nextElement();
								String zoneName = mgrMiscIni.getValue("Auto_Created_Zone_User_Map",userName);
								if (zoneName == null || zoneName.trim().length() == 0)
								{
									zoneName = userName;
								}
								String resultStr2 = (String)resultMap.get(userName);
								if (!resultStr2.startsWith("eG_CLI_Err"))
								{
									associaedZones += zoneName + ",";
									associatedUsers += userName + ",";
								}
								else
								{
									disAssociatedZones += zoneName + ",";
								}
							}
							String descMsg = "";
							AuditLogThread auditLogThread2 = new AuditLogThread();
							auditLogThread2.setValue("Category","Admin");
							auditLogThread2.setValue("User_id",_user.getLoginID());
							auditLogThread2.setValue("Host_ip",_user.getUserIP(session.getId()));
							auditLogThread2.setValue("Session_id",session.getId());
							auditLogThread2.setValue("Module","Zones");
							auditLogThread2.setValue("Activity","Auto Zone Configuration");
							if (associaedZones != null && associaedZones.length()>0)
							{
								associaedZones = associaedZones.substring(0,associaedZones.length()-1);
								associatedUsers = associatedUsers.substring(0,associatedUsers.length()-1);
								if (associaedZones.indexOf(",") > -1)
								{
									descMsg = "Zones "+ associaedZones +" have been added/modified and associated to the users "+associatedUsers+" successfully";
								}
								else
								{
									descMsg = "Zone "+ associaedZones +" has been added/modified and associated to the user "+associatedUsers+" successfully";
								}
							}
							if (disAssociatedZones != null && disAssociatedZones.length()>0)
							{
								disAssociatedZones = disAssociatedZones.substring(0,disAssociatedZones.length()-1);
								if (disAssociatedZones.indexOf(",") > -1)
								{
									descMsg += "Zones "+ disAssociatedZones +" have not been added/modified";
								}
								else
								{
									descMsg += "Zone "+ disAssociatedZones +" has not been added/modified";
								}
							}
							auditLogThread2.setValue("Description", descMsg);
							auditLogThread2.sendItToDB();
						}
					}
				}
				/* code for user comp association ends */

				IniFile discoverParamObj = EgConfigFilesSync.getInstance(EgConfigInfo.egMgrConfigDir + "eg_discoveryParams.ini");
				String subject = "MS_Office_365";
				String key = stype+":"+tempHostName + ":NULL";
				discoverParamObj.setValue(stype,key,testConfigParamsEntry);
				discoverParamObj.saveFile();
				EgConfigFilesSync.releaseInstance(discoverParamObj);
			}
		}

		if (componentsArrModify != null)
		{
			IniFile agentIniObj = EgConfigFilesSync.getInstance(EgConfigInfo.egMgrConfigDir + "eg_agents.ini");
			int compArrModLen = componentsArrModify.length;
			ArrayList statusList = new ArrayList();
			Hashtable delTable = new Hashtable();
			for (int n=0; n<compArrModLen; n++)
			{
				String tempHostName = hostname;
				if (componentsArrModify[n].equalsIgnoreCase("365Modify"))
				{
					stype = "MS_Office_365";
					tempHostName += "_365";
				}
				else if (componentsArrModify[n].equalsIgnoreCase("spoModify"))
				{
					stype = "Microsoft_Sharepoint_Online";
					tempHostName += "_spo";
				}
				else if (componentsArrModify[n].equalsIgnoreCase("exoModify"))
				{
					stype = "MSExchangeOnline";
					tempHostName += "_exo";
				}
				else if (componentsArrModify[n].equalsIgnoreCase("sboModify"))
				{
					stype = "MS_Skype_Online";
					tempHostName += "_sbo";
				}
				else if (componentsArrModify[n].equalsIgnoreCase("mtmModify"))
				{
					stype = "Microsoft_Teams";
					tempHostName += "_mtm";
				}
				else if (componentsArrModify[n].equalsIgnoreCase("odbModify"))
				{
					stype = "MS_OneDrive_Business";
					tempHostName += "_odb";
				}

				ArrayList aListTestsForExclusion = new ArrayList();
				ArrayList aListPerfTestsForExclusion = egSpecs.getEnabledTests(stype,false);
				ArrayList aListConfTestsForExclusion = egSpecs.getEnabledTests(stype,true);
				aListTestsForExclusion.addAll(aListPerfTestsForExclusion);
				aListTestsForExclusion.addAll(aListConfTestsForExclusion);

				tempHostName = tempHostName+":NULL";

				List aListAgents = getAgents(tempHostName);

				for (int m=0;m<aListTestsForExclusion.size();m++)
				{
					String strTest = (String)aListTestsForExclusion.get(m);
					List aListTempAgents = null;
					boolean isExternalTest = egSpecs.isExternalTest(strTest,stype);
					if (isExternalTest)
					{
						aListTempAgents = aListAgents.subList(1,aListAgents.size());
					}
					else
					{
						aListTempAgents = aListAgents.subList(0,1);
					}
					String specificPattern_A = strTest + ":" + stype + ":" + tempHostName;
					String specificPattern_B = strTest + ":" + stype + ":" + tempHostName.substring(0,tempHostName.indexOf(":"));
					String defaultPattern_A = strTest + "::" + tempHostName;
					String defaultPattern_B = strTest + "::" + tempHostName.substring(0,tempHostName.indexOf(":"));

					for (int i=0; i<aListTempAgents.size(); i++)
					{
						String tempAgentNickName = (String)aListTempAgents.get(i);
						String iniVariables[] = agentIniObj.getVariables(tempAgentNickName);
						String tempResultantPattern = "";

						List listTestVariables = Arrays.asList(iniVariables);
						if (listTestVariables.contains(specificPattern_A))
						{
							tempResultantPattern = specificPattern_A;
						}
						else if (listTestVariables.contains(specificPattern_B))
						{
							tempResultantPattern = specificPattern_B;
						}
						else if (listTestVariables.contains(defaultPattern_A))
						{
							tempResultantPattern = defaultPattern_A;
						}
						else if (listTestVariables.contains(defaultPattern_B))
						{
							tempResultantPattern = defaultPattern_B;
						}

						if (tempResultantPattern.equals("")) continue;

						Vector varVect = (Vector)delTable.get(tempAgentNickName);
						if (varVect != null)
						{
							varVect.add(tempResultantPattern);
						}
						else
						{
							varVect = new Vector();
							varVect.add(tempResultantPattern);
						}
						delTable.put(tempAgentNickName,varVect);
					}
				}

				IniFile discoverParamObj = EgConfigFilesSync.getInstance(EgConfigInfo.egMgrConfigDir + "eg_discoveryParams.ini");
				String key = stype+":"+tempHostName;
				discoverParamObj.setValue(stype,key,testConfigParamsEntry);
				discoverParamObj.saveFile();
				EgConfigFilesSync.releaseInstance(discoverParamObj);

				statusList.add(key);
			}
			if (delTable != null)
			{
				Iterator it = delTable.keySet().iterator();
				while (it.hasNext())
				{
					String sub = (String)it.next();  
					Vector varVect = (Vector)delTable.get(sub);
					agentIniObj.deleteValues(sub,varVect);
				}
			}
			agentIniObj.saveFile();
			EgConfigFilesSync.releaseInstance(agentIniObj);

			int ModResLen = statusList.size();
			String modsucessMsg = "";
			for (int k=0; k<ModResLen; k++)
			{
				String statusKey = (String)statusList.get(k);
				String statusType = statusKey.substring(0,statusKey.indexOf(":"));
				String statusHostname = statusKey.substring(statusKey.indexOf(":")+1,statusKey.indexOf(":NULL"));
				statusType = mappingInfo.getComponentTypeDescription(statusType);

				if (ModResLen == 1)
				{
					modsucessMsg = "The "+statusType+" component ("+statusHostname+") has been modified successfully. <br/><br/>";
				}
				else if(ModResLen > 1)
				{
					if (k == ModResLen-1)
					{
						modsucessMsg = (modsucessMsg.lastIndexOf(", ") == modsucessMsg.length()-2) ? modsucessMsg.substring(0,modsucessMsg.length()-2) : modsucessMsg;
						modsucessMsg += " and " +statusType+" ("+statusHostname+") components have been modified successfully. <br/><br/>";
					}
					else
					{
						String tempStartStr = (modsucessMsg.length() == 0) ? "The " : "";
						modsucessMsg += tempStartStr+" "+statusType+" ("+statusHostname+"), ";
					}
				}
			}
			rootJSON.put("Modified_Result_info",modsucessMsg);
		}

		if (hasLimitExceeded)
		{
			servicer.startDiscovery("1");
		}
		else
		{
			servicer.startDiscovery("1",true);
		}
	}

		//To generate success or error alert messages
	if (statusMap != null)
	{
		int i=1;
		Enumeration e = statusMap.keys();
		String sucessMsg = "", tempErrMsg = "";
		String actionPerformed = modifying ? "modified" : "added";
		String msg = " "+_mapping.getTextDescription("admin.error.To upgrade your license")+", ";
		msg += _mapping.getTextDescription("admin.error.please contact")+" <b>license@eginnovations.com</b>";
		int statusMapSize = statusMap.size();
		rootJSON.put("resp_type_size",statusMapSize);
		while (e.hasMoreElements())
		{
			String statusStr = e.nextElement().toString().trim();//statusType
			String tempStr = statusMap.get(statusStr).toString().trim();//statusType
			String[] statusRes = StringUtils.getTokens(tempStr,"|$|");
			int statusResLen = statusRes.length;
			for (int k=0; k<statusResLen; k++)
			{
				String tempResStr = statusRes[k];
				String statusType = tempResStr.substring(0,tempResStr.indexOf("#"));
				String statusHostname = tempResStr.substring(tempResStr.indexOf("#")+1,tempResStr.length());
				statusType = mappingInfo.getComponentTypeDescription(statusType);

				//For error alert and its audit logs
				if (!statusStr.equalsIgnoreCase("eG_CLI_0030") && !statusStr.equalsIgnoreCase("eG_CLI_0047"))
				{
					/* code for auditlog starts */
					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","Discover/Monitor");
					
					auditLogThread.setValue("Description","Component "+statusHostname + " of type " +"$ctype$:"+statusType + " could not be created properly");
					auditLogThread.setValue("Activity","Add Component");
					auditLogThread.sendItToDB();
					/* code for auditlog ends */
					Vector err_msg = new Vector();
					JSONObject obj = new JSONObject();
					String title = _mapping.getTextDescription("admin.error.Add new component");
					obj.put("Error_Title",title);
					//if(!StringUtils.isNull(treeViewSrc))
					//{
						//obj.put("Error_URL","EgDispServer.jsp?qctr=1&server="+stype+"&treeViewSrc="+treeViewSrc+"&selectedServerGroup="+selectedServerGroup);
					//}
					//else
					//{
						//obj.put("Error_URL","EgDispServer.jsp?qctr=1&server="+stype+"&selectedServerGroup="+selectedServerGroup);
					//}

					String satusErr = mappingInfo.getErrorCodeValue(statusStr);
					if (satusErr.startsWith("Error :") || satusErr.startsWith("Error:"))
					{
						satusErr = satusErr.replace("Error",_mapping.getTextDescription("admin.auditlog.Reason"));
					}
					if (statusResLen == 1)
					{
						tempErrMsg = "The "+statusType+" ("+statusHostname+") component could not be "+actionPerformed+".";//+"<br/>";
					}
					else if (statusResLen > 1)
					{
						if (k == statusResLen-1)
						{
							tempErrMsg = (tempErrMsg.lastIndexOf(", ") == tempErrMsg.length()-2) ? tempErrMsg.substring(0,tempErrMsg.length()-2) : tempErrMsg;
							tempErrMsg += " and "+statusType+" ("+statusHostname+") components could not be "+actionPerformed+".";//+"<br/>";
						}
						else
						{
							String tempStartStr = (tempErrMsg.length() == 0) ? "The " : "";
							tempErrMsg += tempStartStr+statusType+" ("+statusHostname+"), ";
						}
					}
					obj.put("Error_Msg_A_"+(i),tempErrMsg+"<br/><br/>"+satusErr);
					if (errCodeList != null && errCodeList.contains(statusStr))
					{
						obj.put("Error_Msg_B_"+(i),"<br/>"+msg);
					}
					rootJSON.put("Error_Info_"+(i),obj);
				}
				else //For success alert and its audit logs
				{
					if (statusResLen == 1)
					{
						sucessMsg = "The "+statusType+" component ("+statusHostname+") has been "+actionPerformed+" successfully. <br/><br/>";
					}
					else if(statusResLen > 1)
					{
						if (k == statusResLen-1)
						{
							sucessMsg = (sucessMsg.lastIndexOf(", ") == sucessMsg.length()-2) ? sucessMsg.substring(0,sucessMsg.length()-2) : sucessMsg;
							sucessMsg += " and " +statusType+" ("+statusHostname+") components have been "+actionPerformed+" successfully. <br/><br/>";
						}
						else
						{
							String tempStartStr = (sucessMsg.length() == 0) ? "The " : "";
							sucessMsg += tempStartStr+" "+statusType+" ("+statusHostname+"), ";
						}
					}

					rootJSON.put("Result_info",sucessMsg);
					/* code for auditlog starts */
					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","Discover/Monitor");
					
					auditLogThread.setValue("Description","Component "+statusHostname + " of type " +"$ctype$:"+statusType + " has been created");
					auditLogThread.setValue("Activity","Add Component");
					//1. AUDITLOG - COMPONENT TYPE AND NICK NAME
					if(session.getAttribute("type").toString().equals("new"))
					{
						auditLogThread.setCurrentValue("01~~Component Type","$ctype$:"+statusType);
						auditLogThread.setCurrentValue("02~~Nick Name",statusHostname);
					}
					else
					{
						auditLogThread.setCurrentValue("02~~Nick Name",statusHostname);
					}

					//2. AUDITLOG - EXTERNAL AGENT
					if (extAgent != null && extAgent.length() > 0)
					{
						auditLogThread.setCurrentValue("External Agents",extAgent);
					}

					if (enableRmtAgent != null && enableRmtAgent.equals("true"))
					{
						auditLogThread.setCurrentValue("Agentless","Yes");
					}
					else
					{
						auditLogThread.setCurrentValue("Agentless","No");
					}
					if (remotealos != null && remotealos.length()>0)
					{
						String remoteOS = remotealos;
						if (operatingSystems.containsKey(remotealos))
						{
							remoteOS = operatingSystems.get(remotealos).toString();
						}
						auditLogThread.setCurrentValue("OS",remoteOS);
					}
					if (remotemode != null && remotemode.length()>0)
					{
						auditLogThread.setCurrentValue("Mode",remotemode);
					}
					if (remoteAgent != null && remoteAgent.length()>0)
					{
						auditLogThread.setCurrentValue("Remote Agent",remoteAgent);
					}

					//4. AUDITLOG - AGENTLESS USER DETAILS
					if(remotemode != null && !remotemode.equalsIgnoreCase("SNMP") && !remotemode.equalsIgnoreCase("Perfmon") && !remotemode.equalsIgnoreCase("other"))
					{
						if(!remoteUser.equals("NotApplicable"))
						{
							auditLogThread.setCurrentValue("User",remoteUser);
						}
					}
					auditLogThread.sendItToDB();
					/* code for auditlog ends */
				}
			}
			i++;
		}

		if(stype != null && stype != "")
		{
			rootJSON.put("hostIp",hostip);
		}
	}

	ArrayList splCompList = new ArrayList(Arrays.asList(splCompArr));
	ArrayList allCompsUnderSplTypes = egDiscInfo.getAllHostsOfTypes(Arrays.asList(splCompArr));
	if (allCompsUnderSplTypes != null && allCompsUnderSplTypes.size() > 0)
	{
//		allCompsUnderSplTypes : [demo_sbo, kimu_365, kimu_spo]

		for (int m=0;m<allCompsUnderSplTypes.size();m++)
		{
			String compName = allCompsUnderSplTypes.get(m).toString();
			String nickName = compName.substring(0,compName.indexOf("_"));
			int count = 0;
			for (int n = 0; n < allCompsUnderSplTypes.size(); n++)
			{
				String anotherCompName = allCompsUnderSplTypes.get(n).toString();
				if (!StringUtils.isNull(anotherCompName) && anotherCompName.startsWith(nickName+"_"))
				{
					count++;
				}
			}

			if (count != splCompArr.length)
			{
				hasMoreComponents = true;
				break;
			}
		}
	}
			
	rootJSON.put("hasMoreComponents",hasMoreComponents);

	session.setAttribute("adminLastAccessedURL","/final/admin/EgAdminOperations.jsp?"+request.getQueryString());

	out.println(rootJSON.toString());

%>




