<%@ include file="../../EgTrackerAJSON.jsp" %>
<%@ page language="java" contentType="application/json; charset=UTF-8" pageEncoding="UTF-8" %>
<%@ page import = "net.sf.json.*"%>
<%@ page import="com.eg.EgRoleInfo"%>
<%@ page import="com.eg.EgDiscInfo"%>
<%@ page import="com.eg.EgGroupInfo"%>
<%@ page import="com.eg.EgSpecsInfo"%>
<%@ page import="com.eg.EgURLEncoder"%>
<%@ page import="com.eg.EgTablesInfo"%>
<%@ page import="com.eg.EgAggregateInfo"%>
<%@ page import="com.eg.EgConfigFilesSync"%>
<%@ page import="com.egurkha.admin.ComponentAdd"%>
<%@ page import="com.egurkha.util.StringUtils"%>
<%@ page import="com.eg.UpdateAndTransmitICInfo"%>
<%@ page import="com.egurkha.admin.AuditLogThread"%>
<%@ page import="com.egurkha.admin.UserAssociateComponent"%>
<%@ page import="egurkha.LayerBean"%>
<%@ page import="egurkha.ServerBean"%>
<%@ page import="java.util.*"%>
<%@ page import="com.eg.EgTopoInfo"%>
<%@ page import="com.eg.EgTesterInfo"%>
<%@ page import = "com.egurkha.EgUserRole"%>
<%@ page import = "egurkha.EgDbAdapterUI"%>
<%@ page import = "com.eg.EgDbAdapterTypeUI"%>
<%@ page import = "java.sql.*" %>
<%!
	/*****************************************************************
	* 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);
	}
%>
<%
	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();
	String session_userId = (String)session.getAttribute("sess_userid");
	EgTesterInfo testerInfo = new EgTesterInfo("manager");
	boolean externalAgentRunsAllAggTests = testerInfo.externalAgentRunsAllAggTests();

	String elementType = (String)session.getAttribute("elementType");
	String elementName = (String)session.getAttribute("elementName");
	String serverType = (String)session.getAttribute("selected_server_types");
	String hostnames = (String)session.getAttribute("hostname");
	String remoteAgents = null;
	String externalAgents = null;
	if(externalAgentRunsAllAggTests)
	{
		externalAgents = (String)session.getAttribute("externalAgent");
	}
	else
	{
		remoteAgents = (String)session.getAttribute("remoteAgent");
	}
	session.removeAttribute("elementType");
	session.removeAttribute("elementName");
	session.removeAttribute("selected_server_types");
	session.removeAttribute("hostname");
	session.removeAttribute("remoteAgent");

	if(!StringUtils.isNull(elementType) && !StringUtils.isNull(elementName) && !StringUtils.isNull(serverType))
	{
		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 Servers");
		auditLogThread.setValue("Activity","Add Component");
		if(elementType.equals("zone"))
		{
			auditLogThread.setCurrentValue("01~~Zone name",elementName);
		}
		else if(elementType.equals("service"))
		{
			auditLogThread.setCurrentValue("01~~Service name",elementName);
		}
		else if(elementType.equals("segment"))
		{
			auditLogThread.setCurrentValue("01~~Segment name",elementName);
		}
		else if(elementType.equals("group"))
		{
			auditLogThread.setCurrentValue("01~~Group name",elementName);
		}

		String hostnamesArray[] = null;
		String remoteAgentsArray[] = null;
		String externalAgentsArray[] = null;
		if(!externalAgentRunsAllAggTests && !StringUtils.isNull(hostnames) && !StringUtils.isNull(remoteAgents))
		{
			hostnamesArray = StringUtils.getTokens(hostnames,",");
			remoteAgentsArray = StringUtils.getTokens(remoteAgents,",");
		}
		else if(!StringUtils.isNull(hostnames) && !StringUtils.isNull(externalAgents))
		{
			hostnamesArray = StringUtils.getTokens(hostnames,",");
			externalAgentsArray = StringUtils.getTokens(externalAgents,",");
		}
		ArrayList manCompArrList = new ArrayList();
		ArrayList notYetCreatedAggCompType = new ArrayList();
		ArrayList normalTypes = new ArrayList();
		EgDiscInfo temporary = new EgDiscInfo("manager");
		ArrayList siteServerTypes = temporary.getSiteServers();
		String componentType[] = StringUtils.getTokens(serverType,",");
		Object obj[] = new Object[componentType.length];
		String nickName[] = new String[componentType.length];
		for(int i=0;i<componentType.length;i++)
		{
			String hostName = hostnamesArray[i];
			Hashtable params = new Hashtable();
			params.put("componenttype",componentType[i]);
			params.put("hostip","0.0.0.0");
			params.put("componentname",hostName);
			manCompArrList.add(componentType[i]+":"+hostName+":NULL");
			if(externalAgentRunsAllAggTests)
			{
				params.put("agentless","no");
				params.put("externalagents",externalAgentsArray[i]);
				
			}
			else
			{
				params.put("agentless","yes");
				params.put("mode","Aggregate");
				params.put("remoteagent",remoteAgentsArray[i]);
			}
			obj[i] = params;
			nickName[i] = hostName;
			if(!temporary.isServerTypeAvailable(componentType[i]))
			{
				notYetCreatedAggCompType.add(componentType[i]);
				normalTypes.add(componentType[i].substring(4));
			}
		}
		temporary=null;
		EgAggregateInfo aggregateInfo = new EgAggregateInfo("manager");
		int count = notYetCreatedAggCompType.size();
		if(count>0)
		{
			// Block is common for this and Egnewserverp.jsp pages - starts
			String aggServerTypes[] = (String[])notYetCreatedAggCompType.toArray(new String[count]);
			ArrayList templates = aggregateInfo.getAllTestTemplates();
			Hashtable testMeasureCount = new Hashtable();
			for(int m=0;m<templates.size();m++)
			{
				String test_template_name = templates.get(m).toString();
				String ntm[] = aggregateInfo.getVariables(test_template_name);//ntm - normal test measures
				if(ntm != null && ntm.length>0)
				{
					String atm=aggregateInfo.getValue(test_template_name,ntm[0]);//atm - aggregate test measures
					if(atm != null && atm.indexOf(":")>0)
					{
						testMeasureCount.put(atm.substring(0,atm.indexOf(":")),(ntm.length+""));
					}
				}
			}
			IniFile specsIniFile = new IniFile(EgInstallInfo.getInstallDir() + "/manager/config/eg_specs.ini");
			String test_spec_var[] = null;
			Vector TEST_SPECIFICATION_VAR = specsIniFile.getVariables("TEST_SPECIFICATION",true);
			Vector TEST_SPECIFICATION_VAL = specsIniFile.getAllValues("TEST_SPECIFICATION");

			Vector vars = specsIniFile.getVariables("TEST_MAPPING",true);
			Vector vals = specsIniFile.getAllValues("TEST_MAPPING");
			if(vars != null && vars.size()>0 && vals != null && vals.size()>0 && vals.size()==vals.size())
			{
				for(int a=vars.size()-1;a>=0;a--)
				{
					String comp_type = (String)vars.get(a);
					if(comp_type.startsWith("Agg_"))
					{
						continue;
					}
					comp_type = "Agg_"+ comp_type;
					if(!notYetCreatedAggCompType.contains(comp_type))
					{
						vars.remove(a);
						vals.remove(a);
					}
				}
			}

			ArrayList defaultEnabledTemplates = aggregateInfo.getDefaultEnbaledTemplates();
			Hashtable testMappingHt = new Hashtable();
			Hashtable defaultTestMappingHt = new Hashtable();
			Hashtable testSpecification = new Hashtable();
			Hashtable mytable = new Hashtable();
			String testPeriod = null;
			Hashtable testPeriodMapping = new Hashtable();
			for(int i=0;i<TEST_SPECIFICATION_VAR.size();i++)
			{
				String tmp = (String)TEST_SPECIFICATION_VAR.get(i);
				if(tmp.indexOf("::")>-1)
				{
					continue;
				}
				for(int j=0;j<normalTypes.size();j++)
				{
					String n_type = normalTypes.get(j).toString();
					if(tmp.indexOf(":"+n_type+":")>0)
					{
						testPeriod = (String)TEST_SPECIFICATION_VAL.get(i);
						testPeriod = testPeriod.substring(testPeriod.lastIndexOf(",")+1).trim();
						if(testPeriod.length()==0)
						{
							testPeriod = "300";
						}
						String normalTestName = tmp.substring(0,tmp.indexOf(":"));
						testPeriodMapping.put(normalTestName,testPeriod);
						if(mytable.containsKey(n_type))
						{
							ArrayList filter = (ArrayList) mytable.get(n_type);
							filter.add(tmp);
						}
						else
						{
							ArrayList filter = new ArrayList();
							filter.add(tmp);
							mytable.put(n_type,filter);
						}
						break;
					}
				}
			}
			String displayName[] = new String[count];
			String imageType[] = new String[count];
//			String layers[] = new String[count];
			Arrays.fill(imageType,"aggregate");
			boolean error = false;
			int errorIndex = 0;
			EgTablesInfo tablesInfo = new EgTablesInfo("manager");
			EgSpecsInfo specsInfo = new EgSpecsInfo("manager");
			String aggServerType = null;
			String normalServerType = null;
//			String layerLeves[] = null;
//			String layer = null;
//			String levelStr = null;
//			ArrayList layersForServer = null;
			String aggTestsStr = null;
			String defAggTestsStr = null;
			Hashtable antest = null;
			String a_test = null;
			String n_test = null;

			String test_spec = "";
			String agg_test_spec = "";
			String dummy123 = "";

			String m_count = "";
			String spec_val = null;
			boolean testsAssociated = true;
			Hashtable nickHt = aggregateInfo.getDisplayNames(normalTypes);
			for(int i=0;i<aggServerTypes.length;i++)
			{
				aggServerType = aggServerTypes[i];
				normalServerType = aggServerType.substring(aggServerType.indexOf("_")+1);

				List enabledTestList= new ArrayList();
				int comp_type_idx = -1;
				if(vars != null && (comp_type_idx=vars.indexOf(normalServerType))>-1)
				{
					String enabledNormalTests = (String) vals.get(comp_type_idx);
					String enabledTests[] = StringUtils.getTokens(enabledNormalTests,",");
					for(int b=0;b<enabledTests.length;b++)
					{
						String test_perf = enabledTests[b].trim();
						if(!test_perf.endsWith("_cf"))
						{
							enabledTestList.add(test_perf);
						}
					}
				}

				if(nickHt.containsKey(normalServerType))
				{
					displayName[i] = (String) nickHt.get(normalServerType);
				}
				else
				{
					String display = normalServerType;
					if(display.indexOf("_")>-1)
					{
						String tmp[] = StringUtils.getTokens(display,"_");
						display = "";
						for(int j=0;j<tmp.length;j++)
						{
							display+=tmp[j];
						}
					}
					if(display.length()<=6)
					{
						displayName[i] = display.toUpperCase();
					}
					else
					{
						displayName[i] = display.substring(0,6).toUpperCase();
					}
				}
//				String layersStr = "";
				String rat = null;
				String normalTestName = null;
//				layersForServer = tablesInfo.getLayersForComponent(normalServerType);
//				if(layersForServer == null || layersForServer.isEmpty())
//				{
//					//component type is created from integration console, but no layers are associated with it.
//					//for example, component type "james_ex" is there without layers.
//					//but user has created components for this component type james_ex.
//				}
//				else
//				{
//					int layersCount = layersForServer.size();
//					//layerLeves = new String[layersCount];
//					//int arrayIndex=-1;
//					Hashtable layerLevel = new Hashtable();
//					for(int j=0;j<layersForServer.size();j++)
//					{
//						layer = (String)layersForServer.get(j);
//						levelStr = tablesInfo.getLevelForLayer(normalServerType, layer);
//						try
//						{
//							int level = Integer.parseInt(levelStr.trim());
//							layerLevel.put(layer,levelStr.trim());
//							/*if(layersCount==1)
//							{
//								if(level == -1)
//								{
//									layerLeves[0] = layer;
//								}
//								else
//								{
//									layerLeves[level] = layer;
//								}
//							}
//							else
//							{
//								layerLeves[++arrayIndex] = layer;
//							}*/
//						}
//						catch(Exception e)
//						{
//							//System.out.println(layer + " level is " + levelStr);
//							error=true;
//							errorIndex=i;
//							e.printStackTrace();
//							break;
//						}
//					}
//					if(error)
//						break;
//					//layersForServer.clear();
//					//layersForServer = new ArrayList(Arrays.asList(layerLeves));
//					Collections.reverse(layersForServer);
//					for(int s=0;s<layersForServer.size();s++)
//					{
//						String lay = (String)layersForServer.get(s);
//						layersStr += lay+":"+(String)layerLevel.get(lay)+",";
//					}
//					layersStr = layersStr.substring(0,layersStr.length()-1);
//				}
				//layers[i] = layersStr;
				aggTestsStr = null;
				defAggTestsStr = null;
				antest = new Hashtable();

				ArrayList validAggTests = aggregateInfo.getValidAggTests(aggServerType);
				ArrayList validTemplateTests = aggregateInfo.getValidTemplateTests(aggServerType);
				for(int k=0;k<validTemplateTests.size();k++)
				{
					normalTestName = (String)validTemplateTests.get(k);
					rat = aggregateInfo.getRelatedAggregateTest(normalTestName);
					if(!StringUtils.isNull(rat))
					{
						validAggTests.remove(rat);
						antest.put(rat,normalTestName);
						if(aggTestsStr==null)
						{
							aggTestsStr = rat;
						}
						else
						{
							aggTestsStr += ","+rat;
						}
						if(defaultEnabledTemplates.contains(normalTestName+"_Template"))
						{
							if(defAggTestsStr==null)
							{
								if(enabledTestList != null && !enabledTestList.isEmpty() && enabledTestList.contains(normalTestName))
								{
									defAggTestsStr = rat;
								}
							}
							else if(enabledTestList != null && !enabledTestList.isEmpty() && enabledTestList.contains(normalTestName))
							{
								defAggTestsStr += ","+rat;
							}
						}
					}
				}
				if(defAggTestsStr==null)
				{
					defAggTestsStr="";
				}
				for(int k=0;k<validAggTests.size();k++)//remaining aggregate tests to be assigned to this component type
				{
					rat = (String) validAggTests.get(k);
					normalTestName = aggregateInfo.getTestName(rat);
					antest.put(rat,normalTestName);
					testMeasureCount.put(rat,(aggregateInfo.getMeasuresForTest(rat).size()+""));
					if(StringUtils.isNull(aggTestsStr))
					{
						aggTestsStr = rat;
					}
					else
					{
						aggTestsStr += ","+rat;
					}
				}
				Iterator itr_2 = antest.keySet().iterator();
				while(itr_2.hasNext())
				{
					try
					{
						a_test = (String) itr_2.next();
						n_test = (String)antest.get(a_test);
						if(!mytable.containsKey(normalServerType))
						{
							break;
						}
						ArrayList alist = (ArrayList)mytable.get(normalServerType);
						if(alist == null || alist.size()==0)
						{
							error=true;
							errorIndex=i;
							break;
						}
						test_spec_var = (String[])alist.toArray(new String[alist.size()]);
						test_spec = findTest(n_test,normalServerType,test_spec_var);
						boolean portBased = false;
						int sindex = TEST_SPECIFICATION_VAR.indexOf(test_spec);
						if(sindex>-1)
						{
							String dummyStr = (String)TEST_SPECIFICATION_VAL.get(sindex);
							if(dummyStr.indexOf(" -port ")>-1)
							{
								portBased = true;
							}
						}
						agg_test_spec = test_spec;
						dummy123 = ":"+normalServerType+":";
						if(test_spec != null && test_spec.indexOf(dummy123)>0)
						{
							String mykey = a_test+"::";
							String descriptorAggregation = "true";
							for(int z=0;z<TEST_SPECIFICATION_VAR.size();z++)
							{
								String tmp = (String)TEST_SPECIFICATION_VAR.get(z);
								if(tmp.startsWith(mykey))
								{
									descriptorAggregation = (String)TEST_SPECIFICATION_VAL.get(z);
									descriptorAggregation = descriptorAggregation.substring(descriptorAggregation.indexOf("-aggregateDescriptor")+20);
									descriptorAggregation = descriptorAggregation.trim();
									descriptorAggregation = descriptorAggregation.substring(0,descriptorAggregation.indexOf(" "));
									break;
								}
							}
							agg_test_spec = a_test + agg_test_spec.substring(agg_test_spec.indexOf(":"));
							agg_test_spec = StringUtils.replace(agg_test_spec,normalServerType,aggServerType);
							m_count = (String)testMeasureCount.get(a_test);
							if(portBased)
							{
								if(externalAgentRunsAllAggTests)
								{
									spec_val = "$EG_SERVER,-auto, -host $hostIp -port $portNo -excludeDescriptor none -aggregateDescriptor "+descriptorAggregation+" -agentless y -rptName $hostName -mCount "+m_count+", "+(String)testPeriodMapping.get(n_test);
								}
								else
								{
									spec_val = "$hostName,-auto, -host $hostIp -port $portNo -excludeDescriptor none -aggregateDescriptor "+descriptorAggregation+" -agentless y -rptName $hostName -mCount "+m_count+", "+(String)testPeriodMapping.get(n_test);
								}
							}
							else
							{
								if(externalAgentRunsAllAggTests)
								{
									spec_val = "$EG_SERVER,-auto, -host $hostIp -excludeDescriptor none -aggregateDescriptor "+descriptorAggregation+" -agentless y -rptName $hostName -mCount "+m_count+", "+(String)testPeriodMapping.get(n_test);
								}
								else
								{
									spec_val = "$hostName,-auto, -host $hostIp -excludeDescriptor none -aggregateDescriptor "+descriptorAggregation+" -agentless y -rptName $hostName -mCount "+m_count+", "+(String)testPeriodMapping.get(n_test);
								}
							}
							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 = "";
						}
					}
					catch(Exception e)
					{
						e.printStackTrace();
						error=true;
						errorIndex=i;
						break;
					}
				}
				mytable.clear();
				if(error)
					break;

				if(StringUtils.isNull(aggTestsStr))
				{
					aggTestsStr="";
				}
				if(StringUtils.isNull(defAggTestsStr))
				{
					defAggTestsStr="";
				}

//				if(!StringUtils.isNull(aggTestsStr))
//				{
					defaultTestMappingHt.put(aggServerType,aggTestsStr);
					if(defAggTestsStr.length()==0)
						testMappingHt.put(aggServerType,aggTestsStr);
					else
						testMappingHt.put(aggServerType,defAggTestsStr);
//				}
//				else
//				{
//					testsAssociated=false;
//					break;
//				}
				enabledTestList.clear();
			}
			/*
				work to write everything into ini files starts
			*/
			boolean discoverUpdated = false;
			boolean tablesUpdated = false;
			boolean specsUpdated = false;
			UpdateAndTransmitICInfo updateICInfo = new UpdateAndTransmitICInfo();
			if(!error)// && testsAssociated)
			{
				Vector specVec = new Vector();
				specVec.add(testMappingHt);
				specVec.add(defaultTestMappingHt);
				specVec.add(testSpecification);
				if(updateICInfo.createAggregateImages(aggServerTypes,displayName,imageType))
				{
					discoverUpdated=true;
					//if(updateICInfo.updateLayersForAggregateServer(aggServerTypes,layers))
					{
						tablesUpdated = true;
						if(updateICInfo.updateSpecsForServer(specVec))
						{
							specsUpdated = true;
						}
					}
				}
			}
			if(!specsUpdated)
			{
				JSONObject errorReported = new JSONObject();
				for(int i=0;i<aggServerTypes.length;i++)
				{
					updateICInfo.removeServer(aggServerTypes[i]);
				}
				if(!testsAssociated)
				{
					errorReported.put("errorMessage",_mapping.getTextDescription("admin.error.No aggregate tests found for creating aggregate component type")+" <b>"+_mapping.getComponentTypeDescription(aggServerTypes[errorIndex])+"</b>.");
				}
				else if(error)
				{
					errorReported.put("errorMessage",_mapping.getTextDescription("admin.error.Error while assigning layers to aggregate component type")+" "+_mapping.getComponentTypeDescription(aggServerTypes[errorIndex])+".");
				}
				else if(!discoverUpdated)
				{
					errorReported.put("errorMessage",_mapping.getTextDescription("admin.error.Unable to create new image for aggregate component type")+".");
				}
				else if(!tablesUpdated)
				{
					errorReported.put("errorMessage",_mapping.getTextDescription("admin.error.Unable to add entries into configuration file eg_tables")+".");
				}
				else if(!specsUpdated)
				{
					errorReported.put("errorMessage",_mapping.getTextDescription("admin.error.Unable to add entries into configuration file eg_specs")+".");
				}
				rootJson.put("errorReported",errorReported);
				rootJson.put("success","true");
				out.println(rootJson.toString());
				return;
			}
			else
			{
				IniFile aggregateInfoSync = EgConfigFilesSync.getInstance(EgInstallInfo.getInstallDir()+"/manager/config/eg_aggregate.ini",true);
				for(int k=0;k<aggServerTypes.length;k++)
				{
					String server = aggServerTypes[k];
					aggregateInfoSync.setValue("AGGREGATE_TYPES",server,"yes");
					aggregateInfoSync.setValue("COMPONENT_TYPE_MAPPING",server,server.substring(server.indexOf("_")+1));
				}
				aggregateInfoSync.saveFile();
				EgConfigFilesSync.releaseInstance(aggregateInfoSync);
			}
			// Block is common for this and Egnewserverp.jsp pages - ends
		}
%>
<jsp:useBean id="servicer" scope="request" class="egurkha.ServiceBean"/>
<jsp:useBean id="EgConfigTopo" scope="page" class="egurkha.ConfigTopology"/>
<%
		EgConfigTopo.createFile("eg_services.ini");
		int compSize = Integer.parseInt(EgConfigTopo.getValues("MISC_ARGS","MaxManagedComponentsForDisc"));
		EgRoleInfo egRoleInfo = EgRoleInfo.getInstance(session.getId(),(String)session.getAttribute("sess_userid"));
		String[] sTypes = egRoleInfo.getServerTypes();
		boolean hasLimitExceeded=false;
		int cnt=0;
		if(sTypes != null && sTypes.length > 0)
		{
			for (int st=0;st<sTypes.length;st++)
			{
				String[] strComps = egRoleInfo.getAllServersOfType(sTypes[st]);
				if (strComps.length > 0)
				{
					cnt = cnt + strComps.length;
					if (cnt > compSize)
					{
						hasLimitExceeded = true;
						break;
					}
				}
			}
		}
		//The following line is to ensure that the stopDiscovery & startDiscovery runs inside a sync block
		IniFile infraIni = EgConfigFilesSync.getInstance(EgInstallInfo.getInstallDir() + "/manager/config/eg_infrastructure.ini");
		servicer.stopDiscovery();
		String addedComponentsStr = "";
		String notAddedComponentsStr = "";
		ArrayList elementTypeAssociatedCompTypes = new ArrayList();
		ArrayList addedComponents = new ArrayList();

		/* for user-comp mapping - START*/
		int usrLicStatus = 0;
		String user_id = _user.getLoginID();
		EgCertUsage egCertUsage = new EgCertUsage();
		//ArrayList usersList = egCertUsage.getAllLimitedCompAccessUsers(true);
		//boolean isLimitedAdmin = (usersList.contains(user_id));//!egRoleInfo.hasAllComponentAccess();
		UserAssociateComponent uacObj = new UserAssociateComponent(_user.getLoginID(),_user.getUserIP(session.getId()),session.getId());
		EgUuidInfo uuidInfo = new EgUuidInfo();
		/* for user-comp mapping - END*/

		IniFile egTests_tmp = new IniFile(EgInstallInfo.getInstallDir() + "/manager/config/eg_tests.ini");
		String aggAgent_tmp = egTests_tmp.getValue("AGENTS_FOR_AGGREGATE_COMPONENTS","ExternalAgentRunsAllAggTests");
		if (aggAgent_tmp != null &&(aggAgent_tmp.equalsIgnoreCase("yes") || aggAgent_tmp.equalsIgnoreCase("true") || aggAgent_tmp.equalsIgnoreCase("y") || aggAgent_tmp.equalsIgnoreCase("t")))
		{
			usrLicStatus=1;
		}
		//if (isLimitedAdmin && usrLicStatus != 1)
		if (usrLicStatus != 1)
		{
			if (!manCompArrList.isEmpty())
			{
				List orgList = uuidInfo.getOrgNames(user_id);
				int orgListLen = (orgList != null) ? orgList.size() : 0;
				//String mamCompsStr = manCompArrList.toString();
				//mamCompsStr = mamCompsStr.substring(0,mamCompsStr.length()-1);
				for (int y=0; y<orgListLen; y++)
				{
					String org_id = orgList.get(y).toString().trim();
					GroupCertValidator grpCert = new GroupCertValidator(org_id);
					usrLicStatus = grpCert.checkBulkMonitors (componentType[0],org_id,manCompArrList);
					if (usrLicStatus != 1)
					{
						String compsForLog = manCompArrList.toString();
						compsForLog = compsForLog.substring(1,compsForLog.length()-1);
						grpCert.errorLogWrite(org_id,compsForLog,"managing");
						break;
					}
				}
			}
		}
		if(usrLicStatus != 1)
		{
			JSONArray notAddedComponentsJSONArray = new JSONArray();
			for(int i=0;i<componentType.length;i++)
			{
				JSONObject tempJson = new JSONObject();
				tempJson.put("component",_mapping.getComponentTypeDescription(componentType[i])+":"+hostnamesArray[i]);
				tempJson.put("Error",_mapping.getTextDescription("admin.common.License limit has exceeded"));
				notAddedComponentsJSONArray.add(tempJson);
			}
			if(notAddedComponentsJSONArray.size()>0)
			{
				rootJson.put("notAddedComponents",notAddedComponentsJSONArray);
			}
		}
		else
		{
			ArrayList componentStatus = new ComponentAdd().addAggComponents(obj);
			if(hasLimitExceeded)
			{
				servicer.startDiscovery("1");
			}
			else
			{
				servicer.startDiscovery("1",true);
			}
			EgConfigFilesSync.releaseInstance(infraIni);
			while(true)
			{
				if(!EgUpdateRegistry.isRunning)
				{
					//synchronized(EgUpdateRegistry.syncString)
					{
						EgUpdateRegistry.lastCheckTime=0;
						registry.updateAllUserMaps();
					}
					break;
				}
			}
			Vector v1_components=new Vector();
			Vector v2_components=new Vector();
			Vector v1_associations=new Vector();
			Vector v2_associations=new Vector();
			Vector v1_site=new Vector();
			Vector v2_site=new Vector();
			IniFile userCompMapSync = EgConfigFilesSync.getInstance(EgInstallInfo.getInstallDir()+"/manager/config/eg_usercompmapping.ini",true);
			IniFile aggregateInfoSync = EgConfigFilesSync.getInstance(EgInstallInfo.getInstallDir()+"/manager/config/eg_aggregate.ini",true);
			if(componentStatus != null && !componentStatus.isEmpty())
			{
				JSONArray addedComponentsJSONArray = new JSONArray();
				JSONArray notAddedComponentsJSONArray = new JSONArray();
				ArrayList siteAggregateComps = new ArrayList();
				EgTopoInfo topoInfo = null;
				for(int i=0;i<componentStatus.size();i++)
				{
					String aggComponentStatus = (String)componentStatus.get(i);
					if(aggComponentStatus.indexOf("~#~")>0)
					{
						String status = aggComponentStatus.substring(aggComponentStatus.lastIndexOf("~#~")+3);
						String aggComponent = aggComponentStatus.substring(0,aggComponentStatus.lastIndexOf("~#~"));
						if(!status.equals("eG_CLI_0030"))
						{
							notAddedComponentsStr+=aggComponentStatus+",";
							if(aggComponent.endsWith(":NULL"))
							{
								auditLogThread.setCurrentValue("Not Added Aggregate Components","$ctype$:"+aggComponent.substring(0,aggComponent.lastIndexOf(":")));
							}
							else
							{
								auditLogThread.setCurrentValue("Not Added Aggregate Components","$ctype$:"+aggComponent);
							}
							JSONObject tempJson = new JSONObject();
							tempJson.put("component",_mapping.getComponentTypeDescription(aggComponent.substring(0,aggComponent.indexOf(":")))+":"+(aggComponent.substring(aggComponent.indexOf(":")+1,aggComponent.lastIndexOf(":"))));
							tempJson.put("Error",_mapping.getErrorCodeValue(status));
							notAddedComponentsJSONArray.add(tempJson);
							continue;
						}
						else
						{
							elementTypeAssociatedCompTypes.add(aggComponent.substring(0,aggComponent.indexOf(":")));
							addedComponents.add(aggComponent);
							if(aggComponent.endsWith(":NULL"))
							{
								auditLogThread.setCurrentValue("Added Aggregate Components","$ctype$:"+aggComponent.substring(0,aggComponent.lastIndexOf(":")));
							}
							else
							{
								auditLogThread.setCurrentValue("Added Aggregate Components","$ctype$:"+aggComponent);
							}
							addedComponentsStr+=aggComponentStatus+",";

							int index = aggComponent.indexOf(":");
							String atype = _mapping.getComponentTypeDescription(aggComponent.substring(0,index));
							String acomp = aggComponent.substring(index+1,aggComponent.lastIndexOf(":"));
							JSONObject tempJson = new JSONObject();
							tempJson.put("componentType",atype);
							tempJson.put("nickname",acomp);
							addedComponentsJSONArray.add(tempJson);
							if(!_user.getUserRole().hasAllComponentAccess())
							{
								StringBuffer sb = new StringBuffer();
								sb.append(atype);
								sb.append(",0.0.0.0,");
								sb.append(acomp);
								sb.append(",NULL,");
								sb.append("false");
								userCompMapSync.setValue(session_userId,aggComponent,sb.toString());
								sb.setLength(0);
							}
						}
						String aggComponentType = aggComponent.substring(0,aggComponent.indexOf(":"));
						Vector components = new EgGroupInfo().getComponents(elementType,elementName,aggComponentType.substring(4));
						for(int j=0;j<components.size();j++)
						{
							v1_components.add(aggComponent+"#"+components.get(j));
							v2_components.add("associated");
						}
						if(siteServerTypes != null && siteServerTypes.contains(aggComponentType.substring(4)))
						{
							ArrayList memberList = new ArrayList();
							memberList.addAll(components);
							if(topoInfo==null)
							{
								topoInfo=new EgTopoInfo("manager");
							}
							ArrayList sites=topoInfo.getSitesForComponents(memberList);
							v1_site.add(aggComponent);
							v2_site.add(((sites == null || sites.isEmpty())?"no":"yes"));
						}
						v1_associations.add(aggComponent+"#"+elementType+"#"+elementName);
						v2_associations.add(elementType+"#"+elementName);
					}
				}
				String[] aggreagetComponents1 = aggregateInfoSync.getVariables("AGGREGATE_COMPONENTS");
				if(aggreagetComponents1 !=null)
				{
					Vector v1_unmanged=new Vector();
					Set alreadyUnmanagedAggComp=new TreeSet();
					boolean alreadyUnmanagedCompIsBeingAdded=false;
					int addedComponentsCount=addedComponents.size();
					for(int i=0;i<addedComponentsCount;i++)
					{
						String addedComponent=(String)addedComponents.get(i);
						String unmanagedCompKey ="#Unmanage|"+addedComponent+"#";
						for(int j=0;j<aggreagetComponents1.length;j++)
						{
							String tempVar=aggreagetComponents1[j];
							if(tempVar.startsWith(unmanagedCompKey))
							{
								alreadyUnmanagedCompIsBeingAdded=true;
								v1_unmanged.add(tempVar);
								alreadyUnmanagedAggComp.add(addedComponent);
							}
						}
					}
					if(!v1_unmanged.isEmpty())
					{
						aggregateInfoSync.deleteValues("AGGREGATE_COMPONENTS", v1_unmanged);
						v1_unmanged.clear();
					}
					if(alreadyUnmanagedCompIsBeingAdded)
					{
						int alreadyUnmanagedCompsCount=alreadyUnmanagedAggComp.size();
						String unmanComps[] = (String[])alreadyUnmanagedAggComp.toArray(new String[alreadyUnmanagedAggComp.size()]);
						String[] aggregateTestInfosExclude = aggregateInfoSync.getVariables("AGGREGATE_TEST_INFOS_EXCLUDED");
						if(aggregateTestInfosExclude != null)
						{
							int icount=aggregateTestInfosExclude.length;
							for(int i=0;i<alreadyUnmanagedCompsCount;i++)
							{
								String acomp=unmanComps[i];
								String unmanagedCompKey=":"+acomp+"#";
								for(int j=0;j<icount;j++)
								{
									String tempVar = aggregateTestInfosExclude[j];
									if(tempVar.indexOf(unmanagedCompKey)>0)
									{
										v1_unmanged.add(tempVar);
									}
								}
							}
						}
						if(!v1_unmanged.isEmpty())
						{
							aggregateInfoSync.deleteValues("AGGREGATE_TEST_INFOS_EXCLUDED", v1_unmanged);
							v1_unmanged.clear();
						}
						String[] uiComponentAssociations = aggregateInfoSync.getVariables("UI_COMPONENT_ASSOCIATION");
						if(uiComponentAssociations != null)
						{
							int icount=uiComponentAssociations.length;
							for(int i=0;i<alreadyUnmanagedCompsCount;i++)
							{
								String acomp=unmanComps[i];
								String unmanagedCompKey=acomp+"#";
								for(int j=0;j<icount;j++)
								{
									String tempVar = uiComponentAssociations[j];
									if(tempVar.startsWith(unmanagedCompKey))
									{
										v1_unmanged.add(tempVar);
									}
								}
							}
						}
						if(!v1_unmanged.isEmpty())
						{
							aggregateInfoSync.deleteValues("UI_COMPONENT_ASSOCIATION", v1_unmanged);
							v1_unmanged.clear();
						}
						String[] component_association = aggregateInfoSync.getVariables("COMPONENT_ASSOCIATION");
						if(component_association != null)
						{
							int icount=component_association.length;
							for(int i=0;i<alreadyUnmanagedCompsCount;i++)
							{
								String acomp=unmanComps[i];
								String unmanagedCompKey=acomp+"#";
								for(int j=0;j<icount;j++)
								{
									String tempVar = component_association[j];
									if(tempVar.startsWith(unmanagedCompKey))
									{
										v1_unmanged.add(tempVar);
									}
								}
							}
						}
						if(!v1_unmanged.isEmpty())
						{
							aggregateInfoSync.deleteValues("COMPONENT_ASSOCIATION", v1_unmanged);
							v1_unmanged.clear();
						}
						String[] anchor_component = aggregateInfoSync.getVariables("ANCHOR_COMPONENT");
						if(anchor_component != null)
						{
							int icount=anchor_component.length;
							for(int i=0;i<alreadyUnmanagedCompsCount;i++)
							{
								String acomp=unmanComps[i];
								String unmanagedCompKey=acomp+"#";
								for(int j=0;j<icount;j++)
								{
									String tempVar = anchor_component[j];
									if(tempVar.startsWith(unmanagedCompKey))
									{
										v1_unmanged.add(tempVar);
									}
								}
							}
						}
						if(!v1_unmanged.isEmpty())
						{
							aggregateInfoSync.deleteValues("ANCHOR_COMPONENT", v1_unmanged);
							v1_unmanged.clear();
						}
					}
				}
				if(!v1_components.isEmpty())
				{
					aggregateInfoSync.setValues("AGGREGATE_COMPONENTS", v1_components,v2_components,false);
					v1_components.clear();
					v2_components.clear();
				}
				if(!v1_site.isEmpty())
				{
					aggregateInfoSync.setValues("SITE_SUPPORT", v1_site,v2_site,false);
					v1_site.clear();
					v2_site.clear();
				}
				if(!v1_associations.isEmpty())
				{
					aggregateInfoSync.setValues("COMPONENT_ASSOCIATION", v1_associations,v2_associations,false);
					v1_associations.clear();
					v2_associations.clear();
				}
				if(addedComponentsJSONArray.size()>0)
				{
					rootJson.put("addedComponents",addedComponentsJSONArray);
				}
				if(notAddedComponentsJSONArray.size()>0)
				{
					rootJson.put("notAddedComponents",notAddedComponentsJSONArray);
				}
				auditLogThread.setValue("Description","Aggregate components have been created from " + elementType);
				auditLogThread.sendItToDB();
			}
			/* deleting anchor component from this elementName if components are added */
			String vars[] = aggregateInfoSync.getVariables("ANCHOR_COMPONENT");
			if(vars != null && vars.length>0 && addedComponents != null && !addedComponents.isEmpty())
			{
				Vector snchorCompDel = new Vector();
				for(int i=0;i<vars.length;i++)
				{
					String str = vars[i];
					String comp_type = str.substring(0,str.indexOf(":"));
					if(elementTypeAssociatedCompTypes.contains(comp_type) && str.startsWith(comp_type+":") && str.endsWith(("#"+elementType+"#"+elementName)))
					{
						snchorCompDel.add(str);
						//aggregateInfoSync.deleteValue("ANCHOR_COMPONENT", str);
					}
				}
				aggregateInfoSync.deleteValues("ANCHOR_COMPONENT", snchorCompDel);
			}
			/* setting anchor component to this elementName from added components */
			if(addedComponents != null && !addedComponents.isEmpty())
			{
				Vector v1_anchor=new Vector();
				Vector v2_anchor=new Vector();
				for(int i=0;i<addedComponents.size();i++)
				{
					v1_anchor.add((String)addedComponents.get(i)+"#"+elementType+"#"+elementName);
					v2_anchor.add(elementType+"#"+elementName);
				}
				aggregateInfoSync.setValues("ANCHOR_COMPONENT", v1_anchor,v2_anchor,false);
			}
			aggregateInfoSync.saveFile();
			EgConfigFilesSync.releaseInstance(aggregateInfoSync);
			userCompMapSync.saveFile();
			EgConfigFilesSync.releaseInstance(userCompMapSync);
			/* ends */

			//automatic component association to element if element type is zone and automatic_zone_association is true
			String memberComponent = null;//request.getParameter("automatic_zone_association");
			if(session.getAttribute("automatic_zone_association") != null)
			{
				memberComponent = (String)session.getAttribute("automatic_zone_association");
			}
			if(elementType.equalsIgnoreCase("zone") && memberComponent != null && (memberComponent=memberComponent.trim()).length()>0 && !memberComponent.equalsIgnoreCase("null") && !memberComponent.equalsIgnoreCase("-1"))
			{
				//EgGroupInfo groupInfo = new EgGroupInfo();
				IniFile grIni = EgConfigFilesSync.getInstance(EgInstallInfo.getInstallDir() + "/manager/config/eg_group.ini");
				for(int i=0;i<addedComponents.size();i++)
				{
					String key = (String)addedComponents.get(i)+"#"+elementName;
					if(memberComponent.equalsIgnoreCase("true"))
					{
						grIni.setValue("ZONE_DETAILS",key,elementName);
					}
				}
				grIni.saveFile();
				EgConfigFilesSync.releaseInstance(grIni);
			}
			//String user_id = _user.getLoginID();
			if (new EgCertUsage().getAllLimitedCompAccessUsers(true).contains(user_id))
			{
				boolean autoCreateZoneForUser = uuidInfo.autoCreateZone();
				for(int i=0;i<addedComponents.size();i++)
				{
					String key = (String)addedComponents.get(i);
					int colIndex = key.indexOf(":");
					String stype = key.substring(0,colIndex);
					String compName = key.substring(colIndex+1);

					Hashtable resultMap = new Hashtable();
					Hashtable argsMap = new Hashtable();
					argsMap.put("userid",user_id);
					argsMap.put("componenttype",stype);
					argsMap.put("components",compName);
					argsMap.put("autoassociatetype","no");
					String resultStr = uacObj.AssociateComponent(argsMap);
					if(autoCreateZoneForUser && resultStr != null && resultStr.equalsIgnoreCase("eG_CLI_Res_0286"))
					{
						argsMap = new Hashtable();
						argsMap.put("userid",user_id);
						argsMap.put("stype",stype);
						argsMap.put("compname",compName);
						resultMap = uacObj.AutoAssociateComponentToZone(argsMap);
					}
					if(autoCreateZoneForUser && resultStr != null && resultStr.equalsIgnoreCase("eG_CLI_Res_0286") && 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 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","Zones");
						auditlogThread.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";
							}
						}
						auditlogThread.setValue("Description", descMsg);
						auditlogThread.sendItToDB();
					}
				}
			}
			if(!_user.getUserRole().hasAllComponentAccess())
			{
				while(true)
				{
					if(!EgUpdateRegistry.isRunning)
					{
						//synchronized(EgUpdateRegistry.syncString)
						{
							EgUpdateRegistry.lastCheckTime=0;
							registry.updateAllUserMaps();
						}
						break;
					}
				}
			}
		}
	}

	rootJson.put("success","true");
	out.println(rootJson.toString());
%>