<%@ include file="../../EgTrackerAJSON.jsp" %>
<%@ page import="com.eg.IniFile" %>
<%@ page import="com.eg.EgInstallInfo"%>
<%@ page import="com.eg.EgServicesInfo"%>
<%@ page import = "com.eg.AuthConf"%>
<%@ page import = "com.eg.Lookup"%>
<%@ page import = "com.eg.EgCrypt"%>
<%@ page import = "com.eg.EgConfigFilesSync"%>
<%@ page import = "java.io.*"%>
<%@ page import ="com.eg.ADDomainPwdAuth" %>
<%@ page import = "com.egurkha.admin.AuditLogThread"%>
<%@ page import = "com.eg.LdapAuthentication"%>
<%@ page import = "com.eg.FetchUsersDetailsFromAD"%>
<%@ page import = "net.sf.json.*"%>
<%@ page language="java" contentType="application/json; charset=UTF-8" pageEncoding="UTF-8" %>

<%
	JSONObject rootObj = new JSONObject();
	JSONObject errorObj = new JSONObject();
	response.setHeader("Cache-Control","no-store");
	response.setHeader("Pragma","no-cache");
	response.setDateHeader("Expires", -1);
	response.setContentType("application/json");

	ADDomainPwdAuth ldapPassword = new ADDomainPwdAuth();
	EgServicesInfo servicesInfo = new EgServicesInfo("manager");
	boolean isAutoDiscoverChild = servicesInfo.isAutoDiscoverChild();
	Vector sess_vec = new Vector();
	String  domain_nameadd="";
	String domain_name = request.getParameter( "domnam" );
	String domain_user = request.getParameter( "duser" );
	domain_user = com.egurkha.util.StringUtils.decodeSecurityChar(domain_user);

	String domain_ip = request.getParameter( "dmnip" );
	String parentDomn= request.getParameter("parentDomn");
	String chostype=request.getParameter("ctype");
	String domain = request.getParameter( "subjectypes" );
	String portn = request.getParameter( "prtno" );
	String discover=request.getParameter("dnsdiscover");
	String ssl = request.getParameter("ssl");
	String authenMode = request.getParameter("authenMode");
	String saveDomainPwdAuth = request.getParameter("saveDomainPwdAuth");
	String defaultDomain = request.getParameter("defaultdomain");
	String domAlias = request.getParameter("domAlias");
	String domAliasName = request.getParameter("domAliasName");
	String showuserdetail = request.getParameter("showuserdetails");
	IniFile servIni = EgConfigFilesSync.getInstance(EgInstallInfo.getInstallDir() + "/manager/config/eg_services.ini",true);
	if (defaultDomain!= null && !chostype.equalsIgnoreCase("delete") && !chostype.equalsIgnoreCase("deleteAll") && defaultDomain.equalsIgnoreCase("yes"))
	{
		servIni.setValue("MISC_ARGS","defaultDomainForLogin",domain);
	}
	else
	{
		servIni.setValue("MISC_ARGS","defaultDomainForLogin","eG Enterprise");
	}
	servIni.saveFile();
	EgConfigFilesSync.releaseInstance(servIni);

	boolean autoDiscover=false;
	boolean result=false;
	String unresolvedDomains = "";

	/* code for audit log starts */
	String curPwd = request.getParameter("newpwd");
	curPwd = com.egurkha.util.StringUtils.decodeSecurityChar(curPwd);

	String preSSL = request.getParameter("$_ssl");
	ArrayList previous = new ArrayList();
	ArrayList current = new ArrayList();

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

	if (parentDomn == null)
	{
		//if (!isAutoDiscoverChild)
		//{
			parentDomn = "none";
		//}
	}
	IniFile ini_write = EgConfigFilesSync.getInstance(EgInstallInfo.getInstallDir() + "/manager/config/eg_authenticate.ini",true);
	//String fr=new String(EgInstallInfo.getInstallDir() + "/manager/config/eg_authenticate.ini");
	//String fw=new String(EgInstallInfo.getInstallDir() + "/manager/config/eg_authenticate.ini");
	BufferedWriter bw = null;
	String data="";

	AuthConf ac=new AuthConf();
	Lookup lookup=new Lookup();
	LdapAuthentication ldap_authen = new LdapAuthentication();
	String prevParentDomain="";
	if(domain!=null)
		prevParentDomain = ini_write.getValue(domain,"parent_domain_name");

	if(domain !=null && !domain.equals(""))
		domain_nameadd = domain;

	String curParDom = "";
	if(parentDomn!=null)
		curParDom = parentDomn;

	if (domain_ip==null)
		domain_ip="";

	if (portn==null)
		portn="";

	if(curParDom==null)
		curParDom="none";

	if(curParDom.equalsIgnoreCase("none"))
	{
		curParDom = curParDom.substring(0,curParDom.indexOf("o"));
		curParDom = curParDom.toUpperCase();
		curParDom = curParDom+"one";
	}

	if(prevParentDomain.equalsIgnoreCase("none"))
	{
		prevParentDomain = prevParentDomain.substring(0,prevParentDomain.indexOf("o"));
		prevParentDomain = prevParentDomain.toUpperCase();
		prevParentDomain = prevParentDomain+"one";
	}

	String curSSL="";
	if(ssl!=null)
		curSSL = ssl.equalsIgnoreCase("true")?"Yes":"No";

	if(discover!=null && discover.equalsIgnoreCase("Yes"))
		autoDiscover=true;
	
	String curPwdFlag = ""; //for AuditLog 
	if (saveDomainPwdAuth != null)
	{
		curPwdFlag = saveDomainPwdAuth.equalsIgnoreCase("true")?"Yes":"No";
	}//ends

	if (saveDomainPwdAuth != null)
	{
		saveDomainPwdAuth = saveDomainPwdAuth.equalsIgnoreCase("true")?"Yes":"No";
	}

	String curUserFlag = "";
	boolean showusrdetail = false;
	if (showuserdetail != null && showuserdetail.trim().length() > 0)
	{
		showusrdetail = (showuserdetail.equalsIgnoreCase("true") || showuserdetail.equalsIgnoreCase("Yes"))?true:false;
		curUserFlag = showuserdetail;
	}
	//To Modify a Domain
	if(chostype !=null && chostype.equalsIgnoreCase("Modify"))
	{
		//checking for any duplicates of domains
		String $domain = request.getParameter("subjectypes");
		String $domainname = request.getParameter("domnam");
		ArrayList domainNames = new ArrayList();
		ArrayList displayNames = new ArrayList();
		String iniDomains[] = ini_write.getSubjects();
		for(int i=0;i<iniDomains.length;i++)
		{
			if (!com.egurkha.util.StringUtils.isNull(iniDomains[i]) && iniDomains[i].equals("Domain_Alias"))
			{
				continue;
			}
			String domainName = ini_write.getValue(iniDomains[i],"domain_name");
			displayNames.add(iniDomains[i]);
			domainNames.add(domainName);
		}
		String inidomainName = ini_write.getValue($domain,"domain_name");
		if(!inidomainName.equalsIgnoreCase($domainname))
		{
			if(displayNames.contains($domainname) || domainNames.contains($domainname))
			{
				EgConfigFilesSync.releaseInstance(ini_write);
				rootObj.put("success","true");
				rootObj.put("requestStatus","failed");
				errorObj.put("title",_mapping.getTextDescription("admin.auth.Configure Domain(s)"));
				errorObj.put("message1",_mapping.getTextDescription("admin.auth.Domain Already Exists"));
				rootObj.put("errors",errorObj);
				out.println(rootObj.toString());
				return;
			}
		}
		auditLogThread.setValue("Activity","Modify Domain");
		ArrayList stausList = null;
		String domain_pwd = EgCrypt.encrypt(com.egurkha.util.StringUtils.decodeSecurityChar(request.getParameter("newpwd")));
		if(domain_user != null && domain_pwd != null )
		{

			String previousDnsMode = request.getParameter("previousDnsMode");
			String currentDnsMode = request.getParameter("dnsdiscover");
			currentDnsMode = currentDnsMode.equals("Yes")?"Auto":"Manual";

			boolean isAllowToRemoveChilds = false;
			if (!com.egurkha.util.StringUtils.isNull(currentDnsMode) && !com.egurkha.util.StringUtils.isNull(previousDnsMode))
			{
				if (!previousDnsMode.equalsIgnoreCase(currentDnsMode))
				{
					isAllowToRemoveChilds = true;
				}
			}
			
			if (isAllowToRemoveChilds)
			{
				deleteChildDomains(domain);
			}

			String prevDomain = ini_write.getValue(domain,"domain_name");
			if (authenMode != null && authenMode.equalsIgnoreCase("Kerberos"))
			{
				ldapPassword.setDomDisplayName(domain);
				ldapPassword.setDomainName(domain_name);
				ldapPassword.setParentDomain(parentDomn);
				ldapPassword.setDnsDiscover(discover);
				ldapPassword.setDomainUser(domain_user);
				ldapPassword.setDomainPwd(domain_pwd);
				ldapPassword.setDomainIP(domain_ip);
				ldapPassword.setDomainPort(portn);
				ldapPassword.setAuthenticationMode(authenMode);
				ldapPassword.setSavePassword(saveDomainPwdAuth);
				ldapPassword.setSsl(ssl);
				ldapPassword.setPassword(domain_pwd);
				if (!com.egurkha.util.StringUtils.isNull(domAlias) && domAlias.equalsIgnoreCase("yes"))
				{
					ldapPassword.setDomainAliasName(domAliasName);
				}

				ac=new AuthConf(domain_name,ldapPassword);
				try
				{
					if (parentDomn!=null && parentDomn.equalsIgnoreCase("none"))
					{
						File f=new File(EgInstallInfo.getInstallDir()+ "/manager/config/egAD_"+domain_name+".ini");

						if (!autoDiscover && f.exists())
						{
							f.delete();
						}

						if (!f.exists())
						{
							result=ac.writeKrbFile(domain_name,domain_ip,autoDiscover);
						}
						else
						{
							try
							{
								if (discover!=null && discover.equalsIgnoreCase("yes"))
								{
									result=ac.modifyDomain(domain_name);
								}
								else
								{
									result=ac.modifyDomain(domain_name,domain_name,domain_ip);
								}
								
							}
							catch(Exception e)
							{
								e.printStackTrace();
							}
						}
					}
					else
					{
						String fileToModify = domain_name;
						if (parentDomn!=null && !parentDomn.equalsIgnoreCase("None"))
						{
							fileToModify = ini_write.getValue(parentDomn,"domain_name");
							while (true)
							{
								fileToModify = ini_write.getValue(parentDomn,"domain_name");
								
								parentDomn=ini_write.getValue(parentDomn,"parent_domain_name");
								if (parentDomn!=null && ( parentDomn.equalsIgnoreCase("none") || parentDomn.length() == 0))
								{
									break;
								}
							}
						}

						if (discover!=null && discover.equalsIgnoreCase("yes"))
						{
							result=ac.modifyDomain(fileToModify);
						}
						else
						{
							result=ac.modifyDomain(fileToModify,domain_name,domain_ip);
						}
					}
				}
				catch(Exception e)
				{
					e.printStackTrace();
				}
				stausList = new ArrayList(ac.status);
			}
			else
			{
				if (autoDiscover)
				{

					if (!com.egurkha.util.StringUtils.isNull(domAlias) && domAlias.equalsIgnoreCase("yes"))
					{
						ldap_authen = new LdapAuthentication(domain_nameadd,parentDomn,domain_user,ssl,domain_pwd,authenMode,saveDomainPwdAuth,true,domAliasName,showusrdetail);
					}
					else
					{
						ldap_authen = new LdapAuthentication(domain_nameadd,parentDomn,domain_user,ssl,domain_pwd,authenMode,saveDomainPwdAuth,showusrdetail);
					}
				//ldap_authen = new LdapAuthentication(domain_nameadd,parentDomn,domain_user,ssl,domain_pwd,authenMode,saveDomainPwdAuth);
				}
				else
				{
					if (!com.egurkha.util.StringUtils.isNull(domAlias) && domAlias.equalsIgnoreCase("yes"))
					{
						ldap_authen = new LdapAuthentication(domain_nameadd,parentDomn,domain_user,ssl,domain_pwd,portn,authenMode,saveDomainPwdAuth,true,domAliasName,showusrdetail);
					}
					else
					{
						ldap_authen = new LdapAuthentication(domain_nameadd,parentDomn,domain_user,ssl,domain_pwd,portn,authenMode,saveDomainPwdAuth,showusrdetail);
					}
					//	ldap_authen = new LdapAuthentication(domain_nameadd,parentDomn,domain_user,ssl,domain_pwd,portn,authenMode,saveDomainPwdAuth);
				}
				result = ldap_authen.modifyDomain(domain_name,domain_ip,autoDiscover);
				stausList = new ArrayList(ldap_authen.result);
			}
			
			sess_vec.addElement(_mapping.getTextDescription("admin.auth.Configure Domain(s)"));
			sess_vec.addElement("EgAuthentications.jsp?ctype=Add");
			sess_vec.addElement(_mapping.getTextDescription("admin.auth.Domain Details"));

			/* code for auditlog starts */
			//String previousDnsMode = request.getParameter("previousDnsMode");
			String previousDomainName = request.getParameter("$domainname");
			String previousDomainUser = request.getParameter("$domainuser");
			String previousDomainPassword = request.getParameter("$domainpassword");
			previousDomainPassword = com.egurkha.util.StringUtils.decodeSecurityChar(previousDomainPassword);

			String previousDomainIP = request.getParameter("$domainip");
			String previousPortNo = request.getParameter("$portnumber");
			//String currentDnsMode = request.getParameter("dnsdiscover");
			String previousAuthenMode = request.getParameter("$_authenMode");
			String currentAuthenMode = request.getParameter("authenMode");
			String previousSavePawword = request.getParameter("$_saveDomainPwdAuth");
			String previousShowUserDetail = request.getParameter("$_showuserdetails");
			//currentDnsMode = currentDnsMode.equals("Yes")?"Auto":"Manual";
			if (previousDnsMode != null && (previousDnsMode.equalsIgnoreCase("Auto") || previousDnsMode.equalsIgnoreCase("yes")))
			{
				if (currentDnsMode != null && (currentDnsMode.equalsIgnoreCase("Manual")||currentDnsMode.equalsIgnoreCase("No")))
				{
					String parentDomainName = ini_write.getValue(domain,"parent_domain_name");
					String dom_name = ini_write.getValue(domain,"domain_name");
					String[] allSubs = ini_write.getSubjects();
					if (allSubs != null && allSubs.length > 0)
					{
						boolean saveFile = false;
						String domainNameLowerCase = dom_name.toLowerCase();
						for (int i=0;i<allSubs.length;i++)
						{
							String eachDomain = allSubs[i].trim();
							//if (eachDomain.equalsIgnoreCase(domain) || eachDomain.equalsIgnoreCase(parentDomainName)) 
							if (eachDomain.equalsIgnoreCase(domain))
							{
								continue;
							}

							String domainName = ini_write.getValue(eachDomain,"domain_name");
							domainName = domainName.toLowerCase();
							if(domainName.endsWith("."+domainNameLowerCase))
							{
								ini_write.deleteSubject(eachDomain);
								saveFile = true;
							}
						}
						if (saveFile)
						{
							ini_write.saveFile();
						}
					}
				}
			}
			auditLogThread.setPreviousValue("00~~Parent Domain",prevParentDomain);
			auditLogThread.setCurrentValue("00~~Parent Domain",curParDom);
			previous.add(prevParentDomain);
			current.add(curParDom);

			auditLogThread.setPreviousValue("01~~Discover DNS",previousDnsMode);
			auditLogThread.setCurrentValue("01~~Discover DNS",currentDnsMode);
			previous.add(previousDnsMode);
			current.add(currentDnsMode);
			
			auditLogThread.setPreviousValue("02~~SSL Enabled",preSSL);
			auditLogThread.setCurrentValue("02~~SSL Enabled",curSSL);
			previous.add(preSSL);
			current.add(curSSL);

			auditLogThread.setPreviousValue("03~~Domain Name",previousDomainName);
			auditLogThread.setCurrentValue("03~~Domain Name",domain_name);
			previous.add(previousDomainName);
			current.add(domain_name);

			auditLogThread.setPreviousValue("04~~Connect User",previousDomainUser);
			auditLogThread.setCurrentValue("04~~Connect User",domain_user);
			previous.add(previousDomainUser);
			current.add(domain_user);

			auditLogThread.setPreviousValue("05~~Authentication Mode",previousAuthenMode);
			auditLogThread.setCurrentValue("05~~Authentication Mode",currentAuthenMode);
			previous.add(previousAuthenMode);
			current.add(currentAuthenMode);

			auditLogThread.setPreviousValue("06~~Save Connect Password",previousSavePawword);
			auditLogThread.setCurrentValue("06~~Save Connect Password",curPwdFlag);
			previous.add(previousSavePawword);
			current.add(curPwdFlag);

			auditLogThread.setPreviousValue("06~~Show User Detail",previousShowUserDetail);
			auditLogThread.setCurrentValue("06~~Show User Detail",curUserFlag);
			previous.add(previousShowUserDetail);
			current.add(curUserFlag);

			if (!autoDiscover)
			{
				if(previousDomainIP == null || previousDomainIP.trim().length()==0)
					previousDomainIP = "-";

				if(previousPortNo == null || previousPortNo.trim().length()==0)
					previousPortNo = "-";

				auditLogThread.setPreviousValue("07~~Domain IP",previousDomainIP);
				auditLogThread.setCurrentValue("07~~Domain IP",domain_ip);
				previous.add(previousDomainIP);
				current.add(domain_ip);

				auditLogThread.setPreviousValue("08~~Port No",previousPortNo);
				auditLogThread.setCurrentValue("08~~Port No",portn);
				previous.add(previousPortNo);
				current.add(portn);
			}

			if (previousSavePawword.equalsIgnoreCase("true") || previousSavePawword.equalsIgnoreCase("yes"))
			{
				if(!EgCrypt.encrypt(previousDomainPassword).equals(domain_pwd))
				{
					auditLogThread.setPreviousValue("09~~Connect Password","*****");
					auditLogThread.setCurrentValue("09~~Connect Password","******");
				}
				previous.add(previousDomainPassword);
				current.add(curPwd);
			}

			if (!result)
			{
				sess_vec.addElement("AUTH_MODIFY_DOMAIN_ERROR_ADMIN");
				String errCode = "";
				session.setAttribute("domainError",stausList);
				session.setAttribute("d_name",domain);
				session.setAttribute("realm_name",domain_name);
				if(stausList.contains("EXCEPTION"))
				{
					int idx = stausList.indexOf("EXCEPTION");
					Exception e =(Exception)stausList.get(idx+1);
					String errorStr = e.toString();
					if (errorStr.startsWith("javax.naming.AuthenticationException"))
					{
						String errMessage = e.getMessage();
						StringTokenizer strTokens = new StringTokenizer(errMessage,",");
						while(strTokens.hasMoreTokens())
						{
							String tok = strTokens.nextToken();
							if (tok.startsWith(" data "))
							{
								errCode = tok.substring(tok.indexOf(" ",1)+1);
							}
						}
						sess_vec.addElement("LDAP_ERROR_CODE#"+errCode);
					}
					else if (errorStr.startsWith("javax.naming.NoPermissionException"))
					{
						errCode = "50";
						sess_vec.addElement("LDAP_ERROR_CODE#"+errCode);
					}
					else if (errorStr.startsWith("javax.naming.CommunicationException"))
					{
						errCode = "2";
						if (errorStr.indexOf("SSLHandshakeException") > -1 || errorStr.indexOf("ValidatorException") > -1 || errorStr.indexOf("SunCertPathBuilderException") > -1)
						{
							errCode = "E010";
						}
						sess_vec.addElement("LDAP_ERROR_CODE#"+errCode);
					}
					else if (errorStr.startsWith("javax.naming.ServiceUnavailableException"))
					{
						errCode = "51";
						sess_vec.addElement("LDAP_ERROR_CODE#"+errCode);
					}
					else if(errorStr.startsWith("java.net.UnknownHostException"))
					{
						errCode="E001";
						sess_vec.addElement("LDAP_ERROR_CODE#"+errCode);
					}
					else
					{
						sess_vec.addElement("EXCEPTION");
					}
				}
				else if(stausList.contains("UNRESOLVED_DOMAIN"))
				{
					errCode="E999";
					//String unResDomains = "";
					//for (int c=1;c<stausList.size();c++)
					//{
					//	unResDomains = unResDomains + stausList.get(c) + ",";
					//}
					//unresolvedDomains = unResDomains;
					//if(unResDomains.length() > 0)
					//	unResDomains = unResDomains.substring(0,unResDomains.length()-1);
					//sess_vec.addElement("UNRESOLVED_DOMAIN"+"#"+unResDomains);
				}
				else if(stausList.contains("IOException"))
				{
					int index = stausList.indexOf("IOException");
					Exception e = (Exception)stausList.get(index+1);
					String errStr = e.toString();
					if (errStr.startsWith("java.io.FileNotFoundException"))
					{
						errCode="E002";
						sess_vec.addElement("LDAP_ERROR_CODE#"+errCode);
					}
					else
					{
						errCode="E002";
						sess_vec.addElement("LDAP_ERROR_CODE#"+errCode);
					}
				}
				else if(stausList.contains("SocketException"))
				{
					errCode="E001";
					sess_vec.addElement("LDAP_ERROR_CODE#"+errCode);
				}
				else if (stausList.contains("FILE_NOT_FOUND"))
				{
					errCode="E002";
					sess_vec.addElement("LDAP_ERROR_CODE#"+errCode);
				}
				else if (stausList.contains("SITE_NOT_FOUND"))
				{
					errCode="E016";
					sess_vec.addElement("LDAP_ERROR_CODE#"+errCode);
				}
				else
				{
					errCode="E999";
					sess_vec.addElement("LDAP_ERROR_CODE#"+errCode);
				}

				if (stausList.contains("UNRESOLVED_DOMAIN"))
				{
					StringTokenizer tok = new StringTokenizer(unresolvedDomains,",");
					int countTok = tok.countTokens();
					if (countTok > 1)
					{
						auditLogThread.setValue("Description","Domain has been modified");
					}
					else
					{
						auditLogThread.setValue("Description","Domain has not been modified");
					}
				}
				else
				{
					auditLogThread.setValue("Description","Domain has not been modified");
				}

				ArrayList tmpList = getErrorMessage(errCode);
				rootObj.put("success","true");
				rootObj.put("requestStatus","failed");
				errorObj.put("title",_mapping.getTextDescription("admin.auth.Configure Domain(s)"));
				errorObj.put("type","domainError");
				errorObj.put("ERROR",tmpList.get(0));
				errorObj.put("DESCRIPTION",tmpList.get(1));
				errorObj.put("RESOLUTION",tmpList.get(2));
				rootObj.put("errors",errorObj);
			}
			else
			{
				if (!com.egurkha.util.StringUtils.isNull(currentAuthenMode) && !com.egurkha.util.StringUtils.isNull(previousAuthenMode))
				{
					if (currentAuthenMode.equalsIgnoreCase("Ldap") && previousAuthenMode.equalsIgnoreCase("Kerberos"))
					{
						try
						{
							File f=new File(EgInstallInfo.getInstallDir()+ "/manager/config/egAD_"+domain_name+".ini");
							if (f.exists())
							{
								f.delete();
							}
						}
						catch(Exception e)
						{
							e.printStackTrace();
						}

						String[] allSubs = ini_write.getSubjects();
						if (allSubs != null && allSubs.length > 0)
						{
							boolean saveFile = false;
							for (int i=0;i<allSubs.length;i++)
							{
								String eachDomain = allSubs[i].trim();
								if (eachDomain.equalsIgnoreCase(domain))
								{
									continue;
								}

								String parent = getParentForDomain(ini_write, eachDomain);//.getValue(eachDomain,"parent_domain_name"));

								if (!com.egurkha.util.StringUtils.isNull(parent) && parent.equalsIgnoreCase(domain))
								{
									String authMode = ini_write.getValue(eachDomain,"AuthenticationMode");
									if (authMode != null && !authMode.equalsIgnoreCase(currentAuthenMode))
									{
										ini_write.setValue(eachDomain,"AuthenticationMode",currentAuthenMode);
										saveFile = true;
									}
								}
							}

							if (saveFile)
							{
								ini_write.saveFile();
							}
						}
					}
				}

				rootObj.put("success","true");
				rootObj.put("requestStatus","success");
				JSONObject resultMsg = new JSONObject();
				resultMsg.put("title",_mapping.getTextDescription("admin.auth.Configure Domain(s)"));
				resultMsg.put("message1",_mapping.getTextDescription("admin.auth.Domain has been modified successfully"));
				if (authenMode != null && authenMode.equalsIgnoreCase("Kerberos"))
				{
					resultMsg.put("message2",_mapping.getTextDescription("admin.auth.You must restart the eG manager for these changes to be effective"));
				}
				rootObj.put("result",resultMsg);
				auditLogThread.setValue("Description","Domain "+domain+" has been modified successfully");
			}

			if(!previous.containsAll(current))
			{
				auditLogThread.sendItToDB();
			}
			/* code for auditlog ends */
			EgConfigFilesSync.releaseInstance(ini_write);
			out.println(rootObj.toString());
			return;
		}
	}
	//To Add a New Domain
	else if(chostype !=null && (chostype.equalsIgnoreCase("Add") || chostype.equalsIgnoreCase("addChild")))
	{
		auditLogThread.setValue("Activity","Add Domain");
		//checking for any duplicates of domains
		String iniSubjects[]= ini_write.getSubjects();
		ArrayList displayNames = new ArrayList();
		ArrayList domainNames  = new ArrayList();
		for(int i=0; i<iniSubjects.length; i++)
		{
			if (!com.egurkha.util.StringUtils.isNull(iniSubjects[i]) && iniSubjects[i].equals("Domain_Alias"))
			{
				continue;
			}
			String domainName = ini_write.getValue(iniSubjects[i],"domain_name");
			domainNames.add(domainName);
			displayNames.add(iniSubjects[i]);
		}
		String $domain = request.getParameter("subjectypes");
		String $domainname = request.getParameter("domnam");
		String domain_pwd = EgCrypt.encrypt(com.egurkha.util.StringUtils.decodeSecurityChar(request.getParameter("newpwd")));
		if(displayNames.contains($domain) || displayNames.contains($domainname) || domainNames.contains($domain) ||  domainNames.contains($domainname))
		{
			auditLogThread.setValue("Description","Display Name or Domain Already Exists");
			auditLogThread.sendItToDB();
			EgConfigFilesSync.releaseInstance(ini_write);

			rootObj.put("success","true");
			rootObj.put("requestStatus","failed");
			errorObj.put("title",_mapping.getTextDescription("admin.auth.Configure Domain(s)"));
			errorObj.put("message1",_mapping.getTextDescription("admin.auth.Display Name or Domain Already Exists"));
			rootObj.put("errors",errorObj);
			out.println(rootObj.toString());
			return;
		}
		if (authenMode != null && authenMode.equalsIgnoreCase("Kerberos"))
		{
			ldapPassword.setDomDisplayName(domain_nameadd);
			ldapPassword.setDomainName(domain_name);
			ldapPassword.setParentDomain(parentDomn);
			ldapPassword.setDnsDiscover(discover);
			ldapPassword.setDomainUser(domain_user);
			ldapPassword.setDomainPwd(domain_pwd);
			ldapPassword.setDomainIP(domain_ip);
			ldapPassword.setDomainPort(portn);
			ldapPassword.setAuthenticationMode(authenMode);
			ldapPassword.setSavePassword(saveDomainPwdAuth);
			ldapPassword.setSsl(ssl);
			ldapPassword.setPassword(domain_pwd);
			if (!com.egurkha.util.StringUtils.isNull(domAlias) && domAlias.equalsIgnoreCase("yes"))
			{
				ldapPassword.setDomainAliasName(domAliasName);
			}

			ac=new AuthConf(domain_name,ldapPassword);
			String fileToModify=domain_name;
			if (parentDomn!=null && !parentDomn.equalsIgnoreCase("None"))
			{
				fileToModify=ini_write.getValue(parentDomn,"domain_name");
				while (true)
				{
					fileToModify=ini_write.getValue(parentDomn,"domain_name");
					parentDomn=ini_write.getValue(parentDomn,"parent_domain_name");
					if (parentDomn!=null && (parentDomn.equalsIgnoreCase("none") || parentDomn.length() == 0))
					{
						break;
					}
				}

				try
				{
					result=ac.AddChildDomain(fileToModify,domain_name,domain_ip);
					
				}
				catch(Exception e)
				{
					e.printStackTrace();
				}
			}
			else
			{
				result=ac.writeKrbFile(domain_name,domain_ip,autoDiscover);
			}

			if (!result)
			{
				String errCode = "";
				sess_vec.addElement(_mapping.getTextDescription("admin.auth.Configure Domain(s)"));
				sess_vec.addElement("EgAuthentications.jsp?ctype=Add&subjectypes="+domain_nameadd+"&domnam="+domain_name+"&parentDomn="+parentDomn+"&duser="+domain_user+"&dnsdiscover="+discover+"&ssl="+ssl+"&AuthenticationMode="+authenMode+"&SavePassword="+saveDomainPwdAuth+"&dmnip="+domain_ip+"&prtno="+portn);
				sess_vec.addElement(_mapping.getTextDescription("admin.auth.Domain Details"));
				ArrayList stausList = new ArrayList(ac.status);
				sess_vec.addElement("AUTH_ADD_DOMAIN_ERROR_ADMIN");
				session.setAttribute("domainError",stausList);
				session.setAttribute("d_name",domain);
				session.setAttribute("realm_name",domain_name);
				if(stausList.contains("EXCEPTION"))
				{
					int idx = stausList.indexOf("EXCEPTION");
					Exception e =(Exception)stausList.get(idx+1);
					String errorStr = e.toString();
					if (errorStr.startsWith("javax.naming.AuthenticationException"))
					{
						String errMessage = e.getMessage();
						StringTokenizer strTokens = new StringTokenizer(errMessage,",");
						while(strTokens.hasMoreTokens())
						{
							String tok = strTokens.nextToken();
							if (tok.startsWith(" data "))
							{
								errCode = tok.substring(tok.indexOf(" ",1)+1);
							}
						}
						sess_vec.addElement("LDAP_ERROR_CODE#"+errCode);
					}
					else if (errorStr.startsWith("javax.naming.NoPermissionException"))
					{
						errCode = "50";
						sess_vec.addElement("LDAP_ERROR_CODE#"+errCode);
					}
					else if (errorStr.startsWith("javax.naming.CommunicationException"))
					{
						errCode = "2";
						if (errorStr.indexOf("SSLHandshakeException") > -1 || errorStr.indexOf("ValidatorException") > -1 || errorStr.indexOf("SunCertPathBuilderException") > -1)
						{
							errCode = "E010";
						}
						sess_vec.addElement("LDAP_ERROR_CODE#"+errCode);
					}
					else if (errorStr.startsWith("javax.naming.ServiceUnavailableException"))
					{
						errCode = "51";
						sess_vec.addElement("LDAP_ERROR_CODE#"+errCode);
					}
					else if(errorStr.startsWith("java.net.UnknownHostException"))
					{
						errCode="E001";
						sess_vec.addElement("LDAP_ERROR_CODE#"+errCode);
					}
					else
					{
						sess_vec.addElement("EXCEPTION");
					}
				}
				else if(stausList.contains("UNRESOLVED_DOMAIN"))
				{
					errCode = "E999";
					//String unResDomains = "";
					//for (int c=1;c<stausList.size();c++)
					//{
					//	unResDomains = unResDomains + stausList.get(c) + ",";
					//}
					//unresolvedDomains = unResDomains;
					//if(unResDomains.length() > 0)
					//	unResDomains = unResDomains.substring(0,unResDomains.length()-1);
					//sess_vec.addElement("UNRESOLVED_DOMAIN"+"#"+unResDomains);
				}
				else if(stausList.contains("SocketException"))
				{
					errCode = "E001";
					sess_vec.addElement("LDAP_ERROR_CODE#"+errCode);
				}
				else if(stausList.contains("IOException"))
				{
					int index = stausList.indexOf("IOException");
					Exception e = (Exception)stausList.get(index+1);
					String errStr = e.toString();
					if (errStr.startsWith("java.io.FileNotFoundException"))
					{
						errCode="E002";
						sess_vec.addElement("LDAP_ERROR_CODE#"+errCode);
					}
					else
					{
						errCode="E002";
						sess_vec.addElement("LDAP_ERROR_CODE#"+errCode);
					}
				}
				else if (stausList.contains("FILE_NOT_FOUND"))
				{
					errCode="E002";
					sess_vec.addElement("LDAP_ERROR_CODE#"+errCode);
				}
				else if (stausList.contains("SITE_NOT_FOUND"))
				{
					errCode="E016";
					sess_vec.addElement("LDAP_ERROR_CODE#"+errCode);
				}
				else
				{
					errCode="E999";
					sess_vec.addElement("LDAP_ERROR_CODE#"+errCode);
				}

				if (stausList.contains("UNRESOLVED_DOMAIN"))
				{
					StringTokenizer tok = new StringTokenizer(unresolvedDomains,",");
					int countTok = tok.countTokens();
					if (countTok > 1)
					{
						auditLogThread.setValue("Description","Domain has been added");
					}
					else
					{
						auditLogThread.setValue("Description","Domain has not been added");
					}
				}
				else
				{
					auditLogThread.setValue("Description","Domain has not been added");
				}

				ArrayList tmpList = getErrorMessage(errCode);
				rootObj.put("success","true");
				rootObj.put("requestStatus","failed");
				errorObj.put("title",_mapping.getTextDescription("admin.auth.Configure Domain(s)"));
				errorObj.put("type","domainError");
				errorObj.put("ERROR",tmpList.get(0));
				errorObj.put("DESCRIPTION",tmpList.get(1));
				errorObj.put("RESOLUTION",tmpList.get(2));
				rootObj.put("errors",errorObj);
			}
			else
			{
				rootObj.put("success","true");
				rootObj.put("requestStatus","success");
				JSONObject resultMsg = new JSONObject();
				resultMsg.put("title",_mapping.getTextDescription("admin.auth.Configure Domain(s)"));
				resultMsg.put("message1",_mapping.getTextDescription("admin.auth.Domain has been added successfully"));
				resultMsg.put("message2",_mapping.getTextDescription("admin.auth.You must restart the eG manager for these changes to be effective"));

				rootObj.put("result",resultMsg);
				auditLogThread.setValue("Description","Domain has been added");
			}
		}
		else
		{
			if (autoDiscover)
			{
				if (!com.egurkha.util.StringUtils.isNull(domAlias) && domAlias.equalsIgnoreCase("yes"))
				{
					ldap_authen = new LdapAuthentication(domain_nameadd,parentDomn,domain_user,ssl,domain_pwd,authenMode,saveDomainPwdAuth,true,domAliasName,showusrdetail);
				}
				else
				{
					ldap_authen = new LdapAuthentication(domain_nameadd,parentDomn,domain_user,ssl,domain_pwd,authenMode,saveDomainPwdAuth,showusrdetail);
				}
			}
			else
			{
				if (!com.egurkha.util.StringUtils.isNull(domAlias) && domAlias.equalsIgnoreCase("yes"))
				{
					ldap_authen = new LdapAuthentication(domain_nameadd,parentDomn,domain_user,ssl,domain_pwd,portn,authenMode,saveDomainPwdAuth,true,domAliasName,showusrdetail);
				}
				else
				{
					ldap_authen = new LdapAuthentication(domain_nameadd,parentDomn,domain_user,ssl,domain_pwd,portn,authenMode,saveDomainPwdAuth,showusrdetail);
				}
			}
			result = ldap_authen.writeAuthenticateIniFile(domain_name,domain_ip,autoDiscover);
			if (!result)
			{
				String errCode = "";
				sess_vec.addElement(_mapping.getTextDescription("admin.auth.Configure Domain(s)"));
				sess_vec.addElement("EgAuthentications.jsp?ctype=Add&subjectypes="+domain_nameadd+"&domnam="+domain_name+"&parentDomn="+parentDomn+"&duser="+domain_user+"&dnsdiscover="+discover+"&ssl="+ssl+"&AuthenticationMode="+authenMode+"&SavePassword="+saveDomainPwdAuth+"&dmnip="+domain_ip+"&prtno="+portn);
				sess_vec.addElement(_mapping.getTextDescription("admin.auth.Domain Details"));
				ArrayList stausList = new ArrayList(ldap_authen.result);
				sess_vec.addElement("AUTH_ADD_DOMAIN_ERROR_ADMIN");
				session.setAttribute("domainError",stausList);
				session.setAttribute("d_name",domain);
				session.setAttribute("realm_name",domain_name);
				if(stausList.contains("EXCEPTION"))
				{
					int idx = stausList.indexOf("EXCEPTION");
					Exception e =(Exception)stausList.get(idx+1);
					String errorStr = e.toString();
					if (errorStr.startsWith("javax.naming.AuthenticationException"))
					{
						String errMessage = e.getMessage();
						StringTokenizer strTokens = new StringTokenizer(errMessage,",");
						while(strTokens.hasMoreTokens())
						{
							String tok = strTokens.nextToken();
							if (tok.startsWith(" data "))
							{
								errCode = tok.substring(tok.indexOf(" ",1)+1);
							}
						}
						sess_vec.addElement("LDAP_ERROR_CODE#"+errCode);
					}
					else if (errorStr.startsWith("javax.naming.NoPermissionException"))
					{
						errCode = "50";
						sess_vec.addElement("LDAP_ERROR_CODE#"+errCode);
					}
					else if (errorStr.startsWith("javax.naming.CommunicationException"))
					{
						errCode = "2";
						if (errorStr.indexOf("SSLHandshakeException") > -1 || errorStr.indexOf("ValidatorException") > -1 || errorStr.indexOf("SunCertPathBuilderException") > -1)
						{
							errCode = "E010";
						}
						sess_vec.addElement("LDAP_ERROR_CODE#"+errCode);
					}
					else if (errorStr.startsWith("javax.naming.ServiceUnavailableException"))
					{
						errCode = "51";
						sess_vec.addElement("LDAP_ERROR_CODE#"+errCode);
					}
					else if(errorStr.startsWith("java.net.UnknownHostException"))
					{
						errCode="E001";
						sess_vec.addElement("LDAP_ERROR_CODE#"+errCode);
					}
					else
					{
						sess_vec.addElement("EXCEPTION");
					}
				}
				else if(stausList.contains("IOException"))
				{
					int index = stausList.indexOf("IOException");
					Exception e = (Exception)stausList.get(index+1);
					String errStr = e.toString();
					if (errStr.startsWith("java.io.FileNotFoundException"))
					{
						errCode="E002";
						sess_vec.addElement("LDAP_ERROR_CODE#"+errCode);
					}
					else
					{
						errCode="E002";
						sess_vec.addElement("LDAP_ERROR_CODE#"+errCode);
					}
				}
				else if(stausList.contains("SocketException"))
				{
					errCode = "E003";
					sess_vec.addElement("LDAP_ERROR_CODE#"+errCode);
				}
				else if (stausList.contains("FILE_NOT_FOUND"))
				{
					errCode="E002";
					sess_vec.addElement("LDAP_ERROR_CODE#"+errCode);
				}
				else if (stausList.contains("SITE_NOT_FOUND"))
				{
					errCode="E016";
					sess_vec.addElement("LDAP_ERROR_CODE#"+errCode);
				}
				else
				{
					errCode="E999";
					sess_vec.addElement("LDAP_ERROR_CODE#"+errCode);
				}

				if (stausList.contains("UNRESOLVED_DOMAIN"))
				{
					StringTokenizer tok = new StringTokenizer(unresolvedDomains,",");
					int countTok = tok.countTokens();
					if (countTok > 1)
					{
						auditLogThread.setValue("Description","Domain has been added");
					}
					else
					{
						auditLogThread.setValue("Description","Domain has not been added");
					}
				}
				else
				{
					auditLogThread.setValue("Description","Domain has not been added");
				}
				ArrayList tmpList = getErrorMessage(errCode);
				rootObj.put("success","true");
				rootObj.put("requestStatus","failed");
				errorObj.put("title",_mapping.getTextDescription("admin.auth.Configure Domain(s)"));
				errorObj.put("type","domainError");
				errorObj.put("ERROR",tmpList.get(0));
				errorObj.put("DESCRIPTION",tmpList.get(1));
				errorObj.put("RESOLUTION",tmpList.get(2));
				rootObj.put("errors",errorObj);
			}
			else
			{
				rootObj.put("success","true");
				rootObj.put("requestStatus","success");
				JSONObject resultMsg = new JSONObject();
				resultMsg.put("title",_mapping.getTextDescription("admin.auth.Configure Domain(s)"));
				resultMsg.put("message1",_mapping.getTextDescription("admin.auth.Domain has been added successfully"));
				rootObj.put("result",resultMsg);
				auditLogThread.setValue("Description","Domain has been added");
			}
		}
		/* code for auditlog starts */
		auditLogThread.setCurrentValue("00~~Display Name",domain);
		auditLogThread.setCurrentValue("01~~Parent Domain",curParDom);
		auditLogThread.setCurrentValue("02~~Discover DNS",autoDiscover?"Auto":"Manual");
		auditLogThread.setCurrentValue("03~~SSL Enabled",curSSL);
		auditLogThread.setCurrentValue("04~~Domain Name",domain_name);
		auditLogThread.setCurrentValue("05~~Connect User",domain_user);

		if(!autoDiscover)
		{
			auditLogThread.setCurrentValue("06~~Domain IP",domain_ip);
			auditLogThread.setCurrentValue("07~~Port No",portn);
		}
		auditLogThread.setCurrentValue("08~~Authentication Mode",authenMode);
		auditLogThread.setCurrentValue("09~~Save Connect Password",saveDomainPwdAuth);
		auditLogThread.sendItToDB();
		/* code for auditlog ends */
		EgConfigFilesSync.releaseInstance(ini_write);
		out.println(rootObj.toString());
		return;
	}
	//To Delete a Domain
	else if(chostype !=null && chostype.equalsIgnoreCase("Delete"))
	{
		auditLogThread.setValue("Activity","Delete Domain");
		String domaintemp1 = request.getParameter("subjectypes");
		ArrayList domainList = new ArrayList();
		if(domaintemp1!=null)
		{
			StringTokenizer domains  = new StringTokenizer(domaintemp1,"~!~");
			while(domains.hasMoreTokens())
			{
				domainList.add(domains.nextToken());
			}
		}
		if(domainList != null)
		{
			Iterator it = domainList.iterator();
			while(it.hasNext())
			{
				String	domain1 = it.next().toString();
				String domainName=ini_write.getValue(domain1,"domain_name");
				String fdel=new String(EgInstallInfo.getInstallDir() +"/manager/config/egAD_"+domainName+".ini");
				String[] allDomains=ini_write.getSubjects();
				ArrayList domainstoDelete=new ArrayList();
				domainstoDelete.add(domain1);
				/*code for audit log starts */
				String parentDom = "";
				String treeDomain = "";
				String aliasName =  ini_write.getValue("Domain_Alias",domainName);

				if(domainstoDelete!=null)
				{
					for(int j=0;j<domainstoDelete.size();j++)
					{
						parentDom = (String) domainstoDelete.get(j);
						treeDomain = ini_write.getValue(parentDom,"parent_domain_name");
					}
				}
				/*code for audit log ends  */

				for (int i=0;i<allDomains.length;i++)
				{
					if (!com.egurkha.util.StringUtils.isNull(allDomains[i]) && allDomains[i].equals("Domain_Alias"))
					{
						continue;
					}

					String parentDomain=ini_write.getValue(allDomains[i],"parent_domain_name");
					if (domainstoDelete.contains(parentDomain))
					{
						domainstoDelete.add(allDomains[i]);
						ini_write.deleteSubject(allDomains[i]);
					}
				}
				ini_write.deleteSubject(domain1);
				if (!com.egurkha.util.StringUtils.isNull(aliasName))
				{
					ini_write.deleteValue("Domain_Alias",domainName);
				}
				ini_write.saveFile();
				if (parentDomn!=null && parentDomn.equalsIgnoreCase("none"))
				{
					File f=new File(fdel);
					if(f.exists())
					{
						f.delete();
					}
				}
				else
				{
					String fileToModify=ini_write.getValue(parentDomn,"domain_name");
					while (true)
					{
						fileToModify=ini_write.getValue(parentDomn,"domain_name");
						parentDomn=ini_write.getValue(parentDomn,"parent_domain_name");
						if (parentDomn != null && (parentDomn.equalsIgnoreCase("none") || parentDomn.length() == 0))
						{
							break;
						}
					}
					try
					{
						result=ac.DeleteChildDomain(fileToModify,domain_name);
					}
					catch(Exception e)
					{
						e.printStackTrace();
					}
				}
				Lookup.removeCache(domainName);
				
				rootObj.put("success","true");
				rootObj.put("requestStatus","success");
				JSONObject resultMsg = new JSONObject();
				resultMsg.put("title",_mapping.getTextDescription("admin.auth.Configure Domain(s)"));
				resultMsg.put("message1",_mapping.getTextDescription("admin.auth.Domain has been deleted successfully"));

				if (authenMode != null && authenMode.equalsIgnoreCase("Kerberos"))
				{
					resultMsg.put("message2",_mapping.getTextDescription("admin.auth.In future, if you add a new domain, you must restart the eG manager for the changes to be effective"));
				}
				rootObj.put("result",resultMsg);

				/* code for auditlog starts */
				auditLogThread.setValue("Description","Domain has been deleted");
				if(!treeDomain.equalsIgnoreCase("none") && treeDomain!=null)
					auditLogThread.setCurrentValue("00~~Parent Name",treeDomain);

				auditLogThread.setCurrentValue("01~~Display Name",domain1);
				auditLogThread.setCurrentValue("02~~Domain Name",domainName);
				auditLogThread.sendItToDB();
				/* code for auditlog ends */
			}
			EgConfigFilesSync.releaseInstance(ini_write);
			out.println(rootObj.toString());
			return;
		}
	}
	else if(chostype !=null && chostype.equalsIgnoreCase("Delsubdoms"))
	{
		//String subject = request.getParameter("subjectypes");
		String subject = request.getParameter("seleted_domain");
		String iniDomains[] = ini_write.getSubjects();
		String parentDomain=subject;
		String fileToModify=ini_write.getValue(parentDomain,"domain_name");
		while (true)
		{
			fileToModify=ini_write.getValue(parentDomain,"domain_name");
			parentDomain=ini_write.getValue(parentDomain,"parent_domain_name");
			if (parentDomain!=null && (parentDomain.equalsIgnoreCase("none") || parentDomain.length() == 0))
			{
				break;
			}
		}

		ArrayList domainsToDelete=new ArrayList();
		Hashtable deletedDomains = new Hashtable();		//for audit log
		for(int i=0; i < iniDomains.length ; i++)
		{
			if (!com.egurkha.util.StringUtils.isNull(iniDomains[i]) && iniDomains[i].equals("Domain_Alias"))
			{
				continue;
			}
			String parentDomainName = ini_write.getValue(iniDomains[i],"parent_domain_name");
			String tempDomain=ini_write.getValue(iniDomains[i],"domain_name");
			if(parentDomainName.equals(subject))
			{
				ini_write.deleteSubject(iniDomains[i]);
				domainsToDelete.add(tempDomain);
				ArrayList al = new ArrayList();		//for audit log
				al.add(tempDomain);
				al.add(parentDomainName);
				deletedDomains.put(iniDomains[i],al);
				for(int j=0; j < iniDomains.length ; j++)
				{
					String tempVal = ini_write.getValue(iniDomains[j],"parent_domain_name");
					tempDomain=ini_write.getValue(iniDomains[j],"domain_name");
					if(iniDomains[i].equals(tempVal))
					{
						ini_write.deleteSubject(iniDomains[j]);
						domainsToDelete.add(tempDomain);
						ArrayList aList = new ArrayList();		//for audit log
						aList.add(tempDomain);
						aList.add(tempVal);
						deletedDomains.put(iniDomains[j],aList);
					}
				}
			}
		}

		/* code for audit log starts */
		Set keySet = deletedDomains.keySet();
		Iterator itr = keySet.iterator();
		while(itr.hasNext())
		{
			String display = (String) itr.next();
			if(deletedDomains!=null)
			{
				ArrayList valPair = (ArrayList) deletedDomains.get(display);
				String strPair = valPair.toString();
				strPair = strPair.substring(0,strPair.indexOf("]"));
				strPair = strPair.substring(1);
				String domainName = strPair.substring(0,strPair.indexOf(","));
				String toParent = strPair.substring(strPair.indexOf(",")+1);
				toParent = toParent.trim();
				AuditLogThread auditLog = new AuditLogThread();
				auditLog.setValue("Category","Admin");
				auditLog.setValue("User_id",_user.getLoginID());
				auditLog.setValue("Host_ip",_user.getUserIP(session.getId()));
				auditLog.setValue("Session_id",session.getId());
				auditLog.setValue("Module","Authentication");
				auditLog.setValue("Activity","DeleteSubDomain");
				auditLog.setCurrentValue("00~~Display Name",display);
				auditLog.setCurrentValue("01~~Domain Name",domainName);
				auditLog.setCurrentValue("02~~Parent Domain",toParent);
				auditLog.setValue("Description","Domain has been deleted successfully");
				auditLog.sendItToDB();
			}
		}
		/* code for audit log ends */

		for (int i=0 ; i < domainsToDelete.size() ; i++)
		{
			String tempDomain=(String)domainsToDelete.get(i);
			try
			{
				result=ac.DeleteChildDomain(fileToModify,tempDomain);
				
			}
			catch(Exception e)
			{
				e.printStackTrace();
			}
		}
		ini_write.saveFile();

		rootObj.put("requestStatus","success");
		JSONObject resultMsg = new JSONObject();
		resultMsg.put("title",_mapping.getTextDescription("admin.auth.Configure Domain(s)"));
		resultMsg.put("message1",_mapping.getTextDescription("admin.auth.Subdomains has been deleted successfully"));
		rootObj.put("result",resultMsg);
		EgConfigFilesSync.releaseInstance(ini_write);
		return;
	}
	else if(chostype !=null && chostype.equalsIgnoreCase("deleteAll"))
	{
		Vector userExits = new Vector();
		Vector domainUsers = (Vector)session.getAttribute("dom_Users");
		String alldomains[] = ini_write.getSubjects();
		ArrayList deleteAll = new ArrayList();
		String pDomain = "";
		if(domainUsers != null && domainUsers.size() > 0)
		{
			for(int i=0; i< alldomains.length; i++)
			{
				if (!com.egurkha.util.StringUtils.isNull(alldomains[i]) && alldomains[i].equals("Domain_Alias"))
				{
					continue;
				}
				if (domainUsers.contains(alldomains[i]))
				{
					pDomain = ini_write.getValue(alldomains[i],"parent_domain_name");
					if (pDomain != null && !pDomain.equalsIgnoreCase("none"))
					{
						String disName = getParentDomainName(ini_write,pDomain);
						if (!userExits.contains(disName))
						{
							userExits.add(disName);
						}

						if (!userExits.contains(alldomains[i]))
						{
							userExits.add(alldomains[i]);
						}
					}
					else
					{
						if (!userExits.contains(alldomains[i]))
						{
							userExits.add(alldomains[i]);
						}
					}
				}
			}
		}
		if(alldomains!=null)
		{
			for(int i=0; i< alldomains.length; i++)
			{
				if (!com.egurkha.util.StringUtils.isNull(alldomains[i]) && alldomains[i].equals("Domain_Alias"))
				{
					continue;
				}
				if (!userExits.contains(alldomains[i]))
				{
					AuditLogThread auditLog = new AuditLogThread();
					auditLog.setValue("Category","Admin");
					auditLog.setValue("User_id",_user.getLoginID());
					auditLog.setValue("Host_ip",_user.getUserIP(session.getId()));
					auditLog.setValue("Session_id",session.getId());
					auditLog.setValue("Module","Authentication");
					auditLog.setValue("Activity","Delete All Domains");
					deleteAll.add(alldomains[i]);
					if(deleteAll!=null)
					{
						String displayName = (String) alldomains[i];
						String domainName = ini_write.getValue(displayName,"domain_name");
						String parentDomain = ini_write.getValue(displayName,"parent_domain_name");
						auditLog.setCurrentValue("00~~Display Name",displayName);
						auditLog.setCurrentValue("01~~Domain Name",domainName);
						if(!parentDomain.equals("none"))
							auditLog.setCurrentValue("02~~Parent Domain",parentDomain);
						auditLog.setValue("Description","Domain "+displayName+" has been deleted successfully");
						auditLog.sendItToDB();
						String fdel = new String(EgInstallInfo.getInstallDir() +"/manager/config/egAD_"+domainName+".ini");
						File f=new File(fdel);
						if(f.exists())
						{
							f.delete();
						}
						String aliasName =  ini_write.getValue("Domain_Alias",domainName);
						if (!com.egurkha.util.StringUtils.isNull(aliasName))
						{
							ini_write.deleteValue("Domain_Alias",domainName);
						}
					}
					ini_write.deleteSubject(alldomains[i]);
				}
			}
		}
		ini_write.saveFile();
		EgConfigFilesSync.releaseInstance(ini_write);
		if (userExits.size() > 0)
		{
			rootObj.put("success","true");
			rootObj.put("requestStatus","success");
			JSONObject resultMsg = new JSONObject();
			resultMsg.put("title",_mapping.getTextDescription("admin.auth.Configure Domain(s)"));
			resultMsg.put("message1",_mapping.getTextDescription("admin.auth.Domains/subdomains containing users have not been deleted"));
			rootObj.put("result",resultMsg);
		}
		else
		{
			rootObj.put("success","true");
			rootObj.put("requestStatus","success");
			JSONObject resultMsg = new JSONObject();
			resultMsg.put("title",_mapping.getTextDescription("admin.auth.Configure Domain(s)"));
			resultMsg.put("message1",_mapping.getTextDescription("admin.auth.Domains have been deleted successfully"));
			rootObj.put("result",resultMsg);
		}
		out.println(rootObj.toString());
		return;
	}
	else if(chostype !=null && chostype.equalsIgnoreCase("updateADUserDetails"))
	{
		auditLogThread.setValue("Activity","Update AD User Details");

		FetchUsersDetailsFromAD c = new FetchUsersDetailsFromAD();
		c.processUserData();
		
		rootObj.put("success","true");
		rootObj.put("requestStatus","success");
		JSONObject resultMsg = new JSONObject();
		resultMsg.put("title",_mapping.getTextDescription("admin.auth.Configure Domain(s)"));
		resultMsg.put("message1",_mapping.getTextDescription("admin.auth.AD User Details have been updated successfully"));
		rootObj.put("result",resultMsg);

		/* code for auditlog starts */
		auditLogThread.setValue("Description","AD User Details has been updated");
		auditLogThread.sendItToDB();
		/* code for auditlog ends */
		EgConfigFilesSync.releaseInstance(ini_write);
		out.println(rootObj.toString());
		return;
	}
	else
	{
		if (ini_write != null)
		{
			EgConfigFilesSync.releaseInstance(ini_write);
		}
	}
%>

<%!
	public ArrayList getErrorMessage(String errorCode)
	{
		ArrayList errors = new ArrayList();
		IniFile egErrorsIni = new IniFile(EgInstallInfo.getInstallDir()+"/manager/config/eg_errors.ini");
		String errorDescription = egErrorsIni.getValue("AD_ERRORS","ERR_"+errorCode);
		String reasons = egErrorsIni.getValue("LDAP_ERROR_DESCRIPTIONS","ERR_"+errorCode);
		String solution = egErrorsIni.getValue("LDAP_RESOLUTION","ERR_"+errorCode);
		errors.add(errorDescription);
		errors.add(reasons);
		errors.add(solution);
		return errors;
	}

	public String getParentDomainName(IniFile Ini_write,String parentdomName)
	{
		String domainNmae = "";
		if (parentdomName!=null && !parentdomName.equalsIgnoreCase("none"))
		{
			while (true)
			{
				domainNmae = Ini_write.getValue(parentdomName,"domain_name");
				parentdomName = Ini_write.getValue(parentdomName,"parent_domain_name");
				if (parentdomName!=null && parentdomName.equalsIgnoreCase("none"))
				{
					break;
				}
			}
		}
		String sub = getSubject(Ini_write,domainNmae);
		return sub;
	}

	public String getSubject(IniFile Ini_write,String domainName)
	{
		String domain = "";
		String subjs[] = Ini_write.getSubjects();
		if (subjs!=null && subjs.length>0)
		{
			for (int i=0;i<subjs.length ; i++)
			{
				String tmpDomain=Ini_write.getValue(subjs[i],"domain_name");
				if (tmpDomain!=null && domainName.equalsIgnoreCase(tmpDomain))
				{
					 domain = subjs[i];
					 break;
				}
			}
		}
		return domain;
	}

	public void deleteChildDomains(String domain)
	{
		IniFile ini_write = EgConfigFilesSync.getInstance(EgInstallInfo.getInstallDir() + "/manager/config/eg_authenticate.ini",true);

		String parentDomainName = ini_write.getValue(domain,"parent_domain_name");
		String dom_name = ini_write.getValue(domain,"domain_name");
		String[] allSubs = ini_write.getSubjects();
		if (allSubs != null && allSubs.length > 0)
		{
			boolean saveFile = false;
			String domainNameLowerCase = dom_name.toLowerCase();
			for (int i=0;i<allSubs.length;i++)
			{
				String eachDomain = allSubs[i].trim();
				//if (eachDomain.equalsIgnoreCase(domain) || eachDomain.equalsIgnoreCase(parentDomainName)) 
				if (eachDomain.equalsIgnoreCase(domain))
				{
					continue;
				}

				String domainName = ini_write.getValue(eachDomain,"domain_name");
				domainName = domainName.toLowerCase();
				if(domainName.endsWith("."+domainNameLowerCase))
				{
					ini_write.deleteSubject(eachDomain);
					saveFile = true;
				}
			}

			if (saveFile)
			{
				ini_write.saveFile();
			}
		}

		EgConfigFilesSync.releaseInstance(ini_write);

		//return true;
	}

	public String getParentForDomain(IniFile iniObj, String domainName)
	{
		String checkingDomain = domainName;
		while (true)
		{
			String strParent = iniObj.getValue(checkingDomain,"parent_domain_name");
			//if (isParentDomainSubject(strParent))
			{
				//checkingDomain = strParent;
				if (strParent != null && (strParent.equalsIgnoreCase("none") || strParent.length() == 0))
				{
					break;
				}
				checkingDomain = strParent; 
			}
		}
		return checkingDomain;
	}
%>




