<%
/*******************************************************************************
*	Name			:	EgReplicateUserJSON.jsp
*	Purpose			:	This jsp is used for replicating users.
*	Version			:
*	CreationDate	:	12/03/2012
*	LastModified	:
*	Author			:	Abdul Khader
*	Design Changes	:
*******************************************************************************/
%>

<%@ include file = "../../EgTrackerAJSON.jsp"%>
<%@ page import = "egurkha.EgDbAdapterUI"%>
<%@ page import = "com.eg.EgDbAdapterTypeUI"%>
<%@ page import = "com.egurkha.ini.IniErrors"%>
<%@ page import = "java.sql.*"%>
<%@ page import = "java.util.*"%>
<%@ page import = "com.egurkha.EgUserRole"%>
<%@ page import = "com.egurkha.User"%>
<%@ page import = "com.eg.EgInstallInfo"%>
<%@ page import = "com.eg.IniFile"%>
<%@ page import = "com.eg.EgCloneUser"%>
<%@ page import = "com.egurkha.util.TimeZoneUtil"%>
<%@ page import = "com.egurkha.util.DateUtil"%>
<%@ page import = "java.util.TimeZone"%>
<%@ page import = "com.egurkha.User"%>
<%@ page import = "com.eg.KerberosAuthentication"%>
<%@ page import = "com.eg.AuthConf"%>
<%@ page import = "com.eg.EgUserVerification"%>
<%@ page import = "com.eg.EgDbInfo"%>
<%@ page import = "com.eg.EgCrypt"%>
<%@ page import = "com.eg.EgLdapUserVerification"%>
<%@ page import = "com.eg.Memberof"%>
<%@ page import = "com.eg.ADDomainPwdAuth"%>
<%@ page import = "com.eg.EgMemCheck"%>
<%@ page import = "com.eg.BuildTree"%>
<%@ page import = "com.eg.GroupSerialization"%>
<%@ page import = "java.io.*"%>
<%@ page import = "com.egurkha.util.StringUtils"%>
<%@ page import = "net.sf.json.*" %>

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>

<%
	JSONObject rootJson = new JSONObject();

	JSONArray actionArrayJson = new JSONArray();
	JSONArray domainArrayJson = new JSONArray();
	JSONArray ssoList = new JSONArray();
	JSONArray timeZoneArrayJson = new JSONArray();
	JSONArray countryArrayJson = new JSONArray();
	JSONArray categoryArrayJson = new JSONArray();

	JSONObject authenticationTypeJson = new JSONObject();
	JSONObject operationTypeJson = new JSONObject();
	JSONObject isValidatedJson = new JSONObject();
	JSONObject userLanguageJson = new JSONObject();

	JSONObject currentDateJson = new JSONObject();
	JSONObject currentDayJson = new JSONObject();
	JSONObject currentMonthJson = new JSONObject();
	JSONObject currentYearJson = new JSONObject();
	JSONObject currentHourJson = new JSONObject();
	JSONObject currentMinJson = new JSONObject();

	JSONObject isDoubleJson = new JSONObject();
	JSONObject usersExistJson = new JSONObject();
	JSONObject currentDateFormatJson = new JSONObject();
	JSONObject adDomainpwdJson = new JSONObject();
	JSONObject validatedUserJson = new JSONObject();
	JSONObject selectedTimeZoneJson = new JSONObject();
	JSONObject defaultTimeZoneJson = new JSONObject();
	JSONObject selectedDateFormatJson = new JSONObject();

	String isValidUserForJSON = "true";
	String uiFile = "eg_ui.ini";
	String s_iniFile_dir = EgInstallInfo.getInstallDir() + "/manager/config/";
	IniFile egUI = new IniFile(s_iniFile_dir + uiFile);

	String countryCode = "";
	Hashtable countryLang;
	String countryName = "";
	ArrayList keyList;
	String strSelect2 = "";
	String domainPwd = null;
	Vector sess_vec = new Vector();

	String currentDateFormat = egUI.getValue("CURRENT_DATE_FORMAT","selectedDateFormat");

	String pwdLength = egUI.getValue("MISC_ARGS","PwdMinLen");
	rootJson.put("pwdLength",pwdLength);

	/*
	 * password complexity check - STARTS
	 * by Meena.V
	 */
	String pwdComplexity = egUI.getValue("MISC_ARGS","PwdComplexity");
	if(pwdComplexity == null || pwdComplexity.length()==0)
	{
		pwdComplexity = "LC";
	}
	StringTokenizer pwdComplexStrTknzr = new StringTokenizer(pwdComplexity,",");
	rootJson.put("pwdComplexity",pwdComplexity);
	rootJson.put("pwdComplexityCount",pwdComplexStrTknzr.countTokens());
	/*
	 * password complexity check - ENDS
	 */

	//if(currentDateFormat.indexOf("MMM") >= 0)
	//{
		//for(int i=0; i < currentDateFormat.length();i++)
		//{
			//if(String.valueOf(currentDateFormat.charAt(i)).equals("M"))
			//{
				//currentDateFormat = currentDateFormat.replace('M','N');
				//currentDateFormatJson.put("currentDateFormat",currentDateFormat);
			//}
		//}
	//}

	ResultSet rs = null;
	ResultSet rs_uname = null;
	boolean b_state = false;
	Vector users = new Vector();
	String usersexist = "";
	Vector all_Users = new Vector();
	String actDomain=request.getParameter("domain");
	String actSso=request.getParameter("SAML");

	boolean isDouble=EgDbInfo.doubleByteEnabled;

	isDoubleJson.put("isDouble",isDouble);

	String servicesDir = EgInstallInfo.getInstallDir()+"/manager/config/";
	IniFile ServicesIni = new IniFile(servicesDir+"eg_services.ini");

	String eGMgrModel = ServicesIni.getValue("MISC_ARGS","eGMgrModel");

	EgUuidInfo egUuidInfo = new EgUuidInfo();

	IniFile eguuid = new IniFile(EgInstallInfo.getInstallDir() + "/manager/config/eg_uuid.ini");
	String orgs [] = eguuid.getVariables("ORG_EXPIRY_DATE");
	ArrayList orgList = orgs==null?new ArrayList():new ArrayList(Arrays.asList(orgs));

	EgUserRole usrRole = _user.getUserRole();
	boolean hasAllComponentAccess = usrRole.hasAllComponentAccess();
	String userId = _user.getLoginID();

	EgDbAdapterUI egDb = EgDbAdapterTypeUI.getObject();
	String str_conn = egDb.setConnection();
	if (str_conn.equals("CONNECTED"))
	{
		try
		{
			String str_query = "SELECT user_id,user_type FROM user_info ORDER BY user_id";
			rs_uname = egDb.SelectExec(str_query);
			Hashtable roles = new Hashtable();
			Hashtable allComps = new Hashtable();
			String tmpUser = "";
			while(rs_uname.next())
			{
				String str_uname=rs_uname.getString("user_id");
				String str_uid_uname = str_uname;
				String str_utype=rs_uname.getString("user_type");
				tmpUser = str_uname;
				String temp_Usr = egUI.getValue("DBUSER_USER_MAP",str_uname);
				if (temp_Usr != null && temp_Usr.length() > 0)
				{
					tmpUser = temp_Usr;
				}
				usersexist = usersexist + tmpUser + "|hash|";

				boolean isdefuser = User.isDefaultUser(str_uname);

				String sess_userid = (String)session.getAttribute("sess_userid");

				if (str_uname.equalsIgnoreCase(sess_userid))
				{
					continue;
				}

				if (!isdefuser && !orgList.contains(str_uname))
				{
					String userOrg = eguuid.getValue("ORGANIZATION_MAPPING",str_uname);
					if (egUuidInfo.isUserExpired(userOrg))
					{
						continue;
					}
					
					if(!hasAllComponentAccess)
					{
						String orgName = "";
						boolean isSuperOrg = egUuidInfo.isSuperOrg(userId);
						boolean isOrg = egUuidInfo.isOrg(userId);
						if (isSuperOrg)
						{
							orgName = userId;
						}
						else if (isOrg)
						{
							orgName = userId;
						}
						else
						{
							orgName = egUuidInfo.getDirectDependentOU(userId);
						}
						TreeSet userSet = egUuidInfo.getAllUsersUnderOrg(orgName);
						if (userSet.contains(str_uname))
						{
							all_Users.add(str_uname);
						}
					}
					else
					{
						if (eGMgrModel != null && eGMgrModel.equalsIgnoreCase("enterprise"))
						{
							TreeSet userSet = egUuidInfo.getAllUsersUnderOrg("egenterprise");
							if (userSet.contains(str_uname))
							{
								all_Users.add(str_uname);
							}
						}
						else
						{
							all_Users.add(str_uname);
						}
					}
				}
				EgUserRole userRole=(EgUserRole)roles.get(str_utype);
				Boolean allComp = (Boolean) allComps.get(str_utype);
				boolean allCompAccess = false;
				if (userRole == null || allComp == null)
				{
					userRole = EgUserRole.getRoleObject(str_utype);
					if (userRole == null)
						continue;
					roles.put(str_utype,userRole);
					allCompAccess = userRole.hasAllComponentAccess();
					allComps.put(str_utype,new Boolean(allCompAccess));
				}
				else
				{
					allCompAccess = allComp.booleanValue();
				}
				if (!allCompAccess)
				{
					users.add(str_uname);
				}
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			try
			{
				egDb.releaseConnection(false);
				EgDbAdapterTypeUI.releaseObject(egDb);
			}
			catch(Exception e)
			{
				egDb.releaseConnection(true);
				EgDbAdapterTypeUI.releaseObject(egDb);
			}
		}
	}

	rootJson.put("isUsersCreated",new Boolean(true));
	if (all_Users.size() == 0)
	{
		rootJson.put("isUsersCreated",new Boolean(false));
		out.println(rootJson);
		return;
	}

	rootJson.put("displayNameOfDefaultOrg",_mapping.getTextDescription("admin.user.egenterprise"));

	if (usersexist != null && usersexist.endsWith("|hash|"))
	{
		usersexist = usersexist.substring(0,usersexist.length()-6);
		usersexist = usersexist.trim();
	}

	usersExistJson.put("usersexist",usersexist);

	// To fetch the timezone of the selected user
	String timeZone = "";
	String str_query = "";
	egDb = EgDbAdapterTypeUI.getObject();
	str_conn = egDb.setConnection();
	if (str_conn.equals("CONNECTED"))
	{
		try
		{
			//str_query = "SELECT user_id FROM user_info";
			String userName = request.getParameter("username");
			userName = com.egurkha.util.StringUtils.decodeSecurityChar(userName);
			if (userName != null && !userName.equalsIgnoreCase("null") && !userName.equals("-1"))
			{
				//if (eGMgrModel != null && eGMgrModel.equalsIgnoreCase("msp"))
				{
					String organizationName = eguuid.getValue("ORGANIZATION_MAPPING",userName);
					String uvalidtill = eguuid.getValue("ORG_EXPIRY_DATE",organizationName);
					rootJson.put("orgName",organizationName);
					rootJson.put("superOrgName",egUuidInfo.getSuperOU(userName));
					rootJson.put("uvalidtill",uvalidtill);
				}

				if (userName.indexOf("(Group)") != -1)
				{
					int idx = userName.indexOf("/");
					int nextIdx = userName.indexOf("(Group)");
					String strtempuname = userName.substring(0,idx);
					strtempuname = strtempuname + "/Grp/";
					String strtempuname_A = userName.substring(idx + 1 ,nextIdx);
					userName = strtempuname + strtempuname_A;
					userName = userName.trim();
				}
				str_query = "SELECT timezone FROM user_pref where user_id='" + userName + "'";
				ResultSet rSet = egDb.dbselect(str_query);
				if (rSet.next())
				{
					timeZone = rSet.getString("timezone");
				}
			}

			/* Added by Prakash.K starts */
			String dateFormat = currentDateFormat;
			if(timeZone != null && timeZone.length() > 0 && timeZone.indexOf("$@$") > -1)
			{
				ArrayList aListTokens = StringUtils.egTokenizer(timeZone,"$@$");

				if(aListTokens!=null)
				{
					timeZone=(String)aListTokens.get(0);
					dateFormat=(String)aListTokens.get(1);
					selectedDateFormatJson.put("selectedDateFormat",dateFormat);
				}
			}
			else
			{
				selectedDateFormatJson.put("selectedDateFormat",dateFormat);
			}
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			try
			{
				egDb.releaseConnection(false);
				EgDbAdapterTypeUI.releaseObject(egDb);
			}
			catch(Exception e)
			{
				egDb.releaseConnection(true);
				EgDbAdapterTypeUI.releaseObject(egDb);
			}
		}
	}

	String categoryArray[] = {"User Information & Preferences","Infrastructure Elements","Exclude Mail Alerts","Live Graph","Quick Insights","Favorite Measures","Custom Dashboards","Favorites","Schedules","Configuration Settings","Quick Links","User Experience Dashboard","Business Dashboard","User Reports","Maintenance Policies","Booklets","Background Reports","Citrix Dashboards"};

	EgCloneUser EgCloneUserObj = new EgCloneUser();
	ArrayList categoryList = EgCloneUserObj.getCategories();

	User user = registry.getUser(session.getId());
	String userLanguage = user.getLanguage();
	String authenticationType = (String)request.getParameter("authentication");
	if (authenticationType==null)
	{
		authenticationType="Eg";
	}
	String operationType = (String)request.getParameter("operation");
	String ldapPass = request.getParameter("ldapPass");
	String userName = request.getParameter("uname");
	userName = com.egurkha.util.StringUtils.decodeSecurityChar(userName);
	String grpName = request.getParameter("grpname");
	String isRefresh = request.getParameter("isRefresh");
	String cloningUser = request.getParameter("cloningUser");
	String isValidated = request.getParameter("isValidated");
	
	if(isRefresh == null || isRefresh.equals("null"))
	{
		isRefresh = "";
	}
	if (userName==null || userName.equals("null"))
	{
		userName = "";
	}
	if (operationType==null)
	{
		operationType = "User";
	}
	if (grpName==null || grpName.equals("null"))
	{
		grpName = "  ----Click on the icon to select a group----  ";
	}
	if (isValidated == null || isValidated.equals("null"))
	{
		isValidated = "false";
	}
	String adDomainPwd = request.getParameter("ldapPass");
	if (adDomainPwd == null)
	{
		adDomainPwd = "";
	}

	IniFile ssoIniObj = new IniFile(EgInstallInfo.getInstallDir()+"/manager/config/eg_samlsso.ini");
	boolean hasSsoLoginEnabled = false;
	String enableSSOLogin = ssoIniObj.getValue("SAML_SSO","SSO_ENABLED");
	if(enableSSOLogin!=null && (enableSSOLogin.equalsIgnoreCase("yes") || enableSSOLogin.equalsIgnoreCase("true")))
	{
		hasSsoLoginEnabled = true;
	}
	rootJson.put("isSAMLLoginEnabled",hasSsoLoginEnabled);


	IniFile iniFile=new IniFile(EgInstallInfo.getInstallDir() +"/manager/config/eg_authenticate.ini");
	String[] domains=iniFile.getSubjects();
	boolean multipledomains=false;
	int count=0;
	for (int i=0;i<domains.length;i++)
	{
		if (!StringUtils.isNull(domains[i]) && domains[i].equals("Domain_Alias"))
		{
			continue;
		}
		String parent=iniFile.getValue(domains[i],"parent_domain_name");
		if (parent.equalsIgnoreCase("none"))
		{
			count++;
		}
	}

	if (count > 1)
	{
		multipledomains=true;
	}

	int validuser=-1;
	boolean validuser1=false;

	String searchBase="";
	ArrayList alistGroup = new ArrayList();
	if (authenticationType.equalsIgnoreCase("Domain") && actDomain!=null)
	{
		ArrayList statusList = null;
		if (operationType.equalsIgnoreCase("User") && userName != null && !userName.equals("null") && userName.length() > 0)
		{
			String parentDoamin=iniFile.getValue(actDomain,"parent_domain_name");
			String domainName=iniFile.getValue(actDomain,"domain_name");
			String domainUser=iniFile.getValue(actDomain,"user");
			String SavePassword = iniFile.getValue(actDomain,"SavePassword");
			if (SavePassword == null || SavePassword.equalsIgnoreCase("") || SavePassword.length() == 0)
			{
				SavePassword = "Yes";
			}
			String authenMode = iniFile.getValue(actDomain,"AuthenticationMode");
			if (SavePassword.equalsIgnoreCase("true") || SavePassword.equalsIgnoreCase("yes"))
			{
				domainPwd=iniFile.getValue(actDomain,"password");
				if (domainPwd == null || domainPwd.equalsIgnoreCase(""))
				{
					domainPwd = EgCrypt.encrypt(request.getParameter("ldapPass"));
				}
			}
			else
			{
				domainPwd = EgCrypt.encrypt(request.getParameter("ldapPass"));
			}
			String domainIp=iniFile.getValue(actDomain,"domain_ip");
			String discover=iniFile.getValue(actDomain,"AutoDiscover");
			domainName=domainName.trim();
			String filename=domainName;
			if (parentDoamin!=null && !parentDoamin.equalsIgnoreCase("none"))
			{
				while (true)
				{
					filename=iniFile.getValue(parentDoamin,"domain_name");
					parentDoamin=iniFile.getValue(parentDoamin,"parent_domain_name");
					if (parentDoamin!=null && parentDoamin.equalsIgnoreCase("none"))
					{
						break;
					}
				}
			}

			if (authenMode == null || authenMode.equalsIgnoreCase("") || authenMode.length() == 0)
			{
				authenMode = "Kerberos";
			}

			if (authenMode != null && authenMode.equalsIgnoreCase("Kerberos"))
			{
				String fdel=new String(EgInstallInfo.getInstallDir() +"/manager/config/egAD_"+filename+".ini");
				File f=new File(fdel);
				if(!f.exists())
				{
					authenMode = "ldap";
				}
			}
			if (authenMode != null && authenMode.equalsIgnoreCase("Kerberos"))
			{
				KerberosAuthentication ka=new KerberosAuthentication(EgInstallInfo.getInstallDir() +"/manager/config/egAD_"+filename+".ini",filename);
				StringTokenizer st=new StringTokenizer(domainName,".");
				int counttokens=st.countTokens();
				for (int i=0;i<counttokens; i++)
				{
					String s_token=st.nextToken();
					if (i==0 || searchBase.equals(""))
						searchBase="DC="+s_token;
					else
						searchBase+=",DC="+s_token;
				}

				if (multipledomains)
				{
					EgUserVerification userVerification=new EgUserVerification();
					validuser =userVerification.userValidate(filename,filename,domainUser,EgCrypt.decrypt(domainPwd),userName,searchBase);
					statusList = new ArrayList(userVerification.errorList);
				}
				else
				{
					validuser=ka.CheckUserAvailable(domainName,domainUser,EgCrypt.decrypt(domainPwd),userName,searchBase);
					statusList = new ArrayList(ka.errorList);
				}

				if (validuser==0)
				{
					validuser1=true;
				}
			}
			else
			{
				parentDoamin = iniFile.getValue(actDomain,"parent_domain_name");
				domainName = iniFile.getValue(actDomain,"domain_name");
				domainUser = iniFile.getValue(actDomain,"user");
				SavePassword = iniFile.getValue(actDomain,"SavePassword");
				if (SavePassword == null || SavePassword.equalsIgnoreCase("") || SavePassword.length() == 0)
				{
					SavePassword = "Yes";
				}
				if (SavePassword.equalsIgnoreCase("true") || SavePassword.equalsIgnoreCase("yes"))
				{
					domainPwd = iniFile.getValue(actDomain,"password");
					if (domainPwd == null || domainPwd.equalsIgnoreCase(""))
					{
						domainPwd = EgCrypt.encrypt(request.getParameter("ldapPass"));
					}
				}
				else
				{
					domainPwd = EgCrypt.encrypt(request.getParameter("ldapPass"));
				}
				domainName = domainName.trim();

				String domAliasName = iniFile.getValue("Domain_Alias",domainName);
				String strPortNo = iniFile.getValue(actDomain,"port_no");
				String strssl = iniFile.getValue(actDomain,"isSSL");
				discover = iniFile.getValue(actDomain,"AutoDiscover");
				String domain_name = domainName;
				if (discover != null && discover.equalsIgnoreCase("Yes")) 
				{
					if (parentDoamin!=null && !parentDoamin.equalsIgnoreCase("none"))
					{
						while (true)
						{
							domainName = iniFile.getValue(parentDoamin,"domain_name");
							domainUser = iniFile.getValue(parentDoamin,"user");
							SavePassword = iniFile.getValue(parentDoamin,"SavePassword");
							if (SavePassword == null || SavePassword.equalsIgnoreCase("") || SavePassword.length() == 0)
							{
								SavePassword = "Yes";
							}
							if (SavePassword.equalsIgnoreCase("true") || SavePassword.equalsIgnoreCase("yes"))
							{
								domainPwd=iniFile.getValue(parentDoamin,"password");
								if (domainPwd == null || domainPwd.equalsIgnoreCase(""))
								{
									domainPwd = EgCrypt.encrypt(request.getParameter("ldapPass"));
								}
							}
							else
							{
								domainPwd = EgCrypt.encrypt(request.getParameter("ldapPass"));
							}
							strPortNo = iniFile.getValue(parentDoamin,"port_no");
							strssl = iniFile.getValue(parentDoamin,"isSSL");
							parentDoamin = iniFile.getValue(parentDoamin,"parent_domain_name");
							if (parentDoamin!=null && (parentDoamin.equalsIgnoreCase("none") || parentDoamin.length() == 0))
							{
								break;
							}
						}
					}
				}

				boolean ssl = (strssl.equalsIgnoreCase("true"));
				if (strPortNo != null && strPortNo.length() == 0)
				{
					if (ssl)
					{
						strPortNo = "636";
					}
					else
					{
						strPortNo = "389";
					}
				}
				
				String connectUser = domainUser + "@" + domainName;
				Memberof mbrof = new Memberof();
				if (!StringUtils.isNull(domAliasName))
				{
					connectUser = mbrof.findUserDN(connectUser,domainPwd,domainName,strPortNo,ssl,domainUser,domAliasName);
				}
				else
				{
					connectUser = mbrof.findUserDN(connectUser,domainPwd,domainName,strPortNo,ssl,domainUser);
				}
				//connectUser = mbrof.findUserDN(connectUser,domainPwd,domainName,strPortNo,ssl,domainUser);
				if (connectUser != null)
				{
					connectUser = connectUser + "," + mbrof.getSearchBase(domainName);
					//EgLdapUserVerification userVerification =  new EgLdapUserVerification(connectUser,domain_name,userName,strPortNo,domainPwd,ssl);
					EgLdapUserVerification userVerification =  null;

					if (!StringUtils.isNull(domAliasName))
					{
						userVerification =  new EgLdapUserVerification(connectUser,domain_name,userName,strPortNo,domainPwd,ssl,domAliasName);
					}
					else
					{
						userVerification =  new EgLdapUserVerification(connectUser,domain_name,userName,strPortNo,domainPwd,ssl);
					}
					validuser1 = userVerification.isUserAvailable();
					statusList = new ArrayList(userVerification.errorList);
				}
				else
				{
					statusList = new ArrayList(mbrof.errorResult);
				}
			}

			if (!validuser1)
			{
				isValidUserForJSON = "false";
				sess_vec.removeAllElements();
				sess_vec.addElement(_mapping.getTextDescription("admin.user.Clone user page"));
				sess_vec.addElement("EgReplicateUser.jsp?qctr=0");
				sess_vec.addElement(_mapping.getTextDescription("admin.auth.Clone user page"));
				sess_vec.addElement("AUTH_ADD_DOMAIN_USER_ERROR");
				String errCode = getADErrorMessage(statusList);
				session.setAttribute("domainError",statusList);
				session.setAttribute("d_name",actDomain);
				session.setAttribute("realm_name",domainName);
				sess_vec.addElement("LDAP_ERROR_CODE#"+errCode);
				session.putValue("vec_Results",sess_vec);
			}
		}
		else if (operationType != null && operationType.equalsIgnoreCase("Group"))
		{
			String parentDomain=iniFile.getValue(actDomain,"parent_domain_name");
			String domainName = iniFile.getValue(actDomain,"domain_name");
			String domainUser = iniFile.getValue(actDomain,"user");
			String SavePassword = iniFile.getValue(actDomain,"SavePassword");
			if (SavePassword == null || SavePassword.equalsIgnoreCase("") || SavePassword.length() == 0)
			{
				SavePassword = "Yes";
			}
			if (SavePassword.equalsIgnoreCase("true") || SavePassword.equalsIgnoreCase("yes"))
			{
				domainPwd = iniFile.getValue(actDomain,"password");
				if (domainPwd == null || domainPwd.equalsIgnoreCase(""))
				{
					domainPwd = EgCrypt.encrypt(request.getParameter("ldapPass"));
				}
			}
			else
			{
				domainPwd = EgCrypt.encrypt(request.getParameter("ldapPass"));
			}
			String discover = iniFile.getValue(actDomain,"AutoDiscover");
			String strPortNo = iniFile.getValue(actDomain,"port_no");
			String strssl = iniFile.getValue(actDomain,"isSSL");
			boolean ssl = (strssl.equalsIgnoreCase("true"));
			String tempdomainName = domainName;

			if (strPortNo != null && strPortNo.length() == 0)
			{
				if (ssl)
				{
					strPortNo = "636";
				}
				else
				{
					strPortNo = "389";
				}
			}

			if (parentDomain != null && !parentDomain.equalsIgnoreCase("none") && discover.equalsIgnoreCase("yes"))
			{
				while (true)
				{
					domainUser = iniFile.getValue(parentDomain,"user");
					domainName = iniFile.getValue(parentDomain,"domain_name");
					SavePassword = iniFile.getValue(parentDomain,"SavePassword");
					if (SavePassword == null || SavePassword.equalsIgnoreCase("") || SavePassword.length() == 0)
					{
						SavePassword = "Yes";
					}
					if (SavePassword.equalsIgnoreCase("true") || SavePassword.equalsIgnoreCase("yes"))
					{
						domainPwd = iniFile.getValue(parentDomain,"password");
						if (domainPwd == null || domainPwd.equalsIgnoreCase(""))
						{
							domainPwd = EgCrypt.encrypt(request.getParameter("ldapPass"));
						}
					}
					else
					{
						domainPwd = EgCrypt.encrypt(request.getParameter("ldapPass"));
					}
					discover = iniFile.getValue(parentDomain,"AutoDiscover");
					String parentDomain_A  = iniFile.getValue(parentDomain,"parent_domain_name");
					if (parentDomain_A != null && (parentDomain_A.equalsIgnoreCase("none") || parentDomain_A.length() == 0))
					{
						break;
					}
				}
			}

			String domAliasName = iniFile.getValue("Domain_Alias",domainName);
			String iniFile_dir = EgInstallInfo.getInstallDir()+"/manager/tomcat/temp/";
			try
			{
				File grpFile = new File(iniFile_dir+"eGADGroups_"+actDomain+".txt");
				BuildTree tree = new BuildTree();
				GroupSerialization grpSez = new GroupSerialization();
				Memberof mbrof = new Memberof();
				ArrayList errorList = null;
				if (!grpFile.exists())
				{
					session.removeAttribute("rootTreeMap");
					ArrayList grpSeg = new ArrayList();
					String connectUser = domainUser + "@" + domainName;
					//ArrayList alistGroupCD = mbrof.getCategorizedADGroups(connectUser,domainPwd,domainName,strPortNo,ssl,tempdomainName);
					ArrayList alistGroupCD = new ArrayList();
					if (!StringUtils.isNull(domAliasName))
					{
						alistGroupCD = mbrof.getCategorizedADGroups(connectUser,domainPwd,domAliasName,strPortNo,ssl,tempdomainName);
					}
					else
					{
						alistGroupCD = mbrof.getCategorizedADGroups(connectUser,domainPwd,domainName,strPortNo,ssl,tempdomainName);
					}
					errorList = (ArrayList)mbrof.errorResult;
					ArrayList list1 = (ArrayList)mbrof.getCDGroups(alistGroupCD);
					ArrayList mainGroup = (ArrayList)mbrof.grpTree;
					alistGroup = (ArrayList)mbrof.alistGroup;

					StringBuffer sb = new StringBuffer();
					tree.createParentNodes(list1,mainGroup,tempdomainName);
					sb	= tree.genTree();
					int lastTraversedNode = tree.lastNodeId;
					Hashtable cachedGroups = tree.cachedGroups;
					String lastNodeId = String.valueOf(lastTraversedNode);

					session.setAttribute("listGroups",alistGroup);
					session.setAttribute("selectedDomain",actDomain);
					session.setAttribute("domainName",tempdomainName);
					session.setAttribute("treeBean",sb.toString());
					session.setAttribute("treeData",sb.toString());
					session.setAttribute("rootGrpList",list1);
					session.setAttribute("mainGroup",mainGroup);
					session.setAttribute("nodeID",lastNodeId);
					session.setAttribute("cachedGroups",cachedGroups);

					if (errorList != null && errorList.size() == 0)
					{
						grpSeg.add(list1);
						grpSeg.add(mainGroup);
						grpSeg.add(alistGroup);
						grpSeg.add(sb);
						grpSeg.add(lastNodeId);
						grpSeg.add(cachedGroups);
						grpSez.setADGroups(grpSeg,actDomain);
					}
					session.setAttribute("errorList",errorList);
				}
				else
				{
					String currentDate = grpSez.getCurrentDate();
					ArrayList grp_Seg = grpSez.getADGroups(actDomain);
					String lastModifiedDate = grpSez.getLastModifiedDate();

					if (grp_Seg == null)
					{
						grp_Seg = new ArrayList();
					}

					if (currentDate != null && currentDate.equals(lastModifiedDate) && grp_Seg.size() > 0)
					{
						ArrayList list1 = (ArrayList)grp_Seg.get(0);
						ArrayList mainGroup = (ArrayList)grp_Seg.get(1);
						ArrayList alist_Group = (ArrayList)grp_Seg.get(2);
						StringBuffer sb = new StringBuffer();
						String nodeID = "";
						Hashtable domainCaching = new Hashtable();
						if (grp_Seg.size() == 3)
						{
							tree.createParentNodes(list1,mainGroup,tempdomainName);
							int lastTraversedNode = tree.lastNodeId;
							Hashtable cachedGroups = tree.cachedGroups;
							String lastNodeId = String.valueOf(lastTraversedNode);
							sb	= tree.genTree();
							nodeID = lastNodeId;
							ArrayList grpSeg = new ArrayList();
							grpSeg.add(list1);
							grpSeg.add(mainGroup);
							grpSeg.add(alist_Group);
							grpSeg.add(sb);
							grpSeg.add(lastNodeId);
							grpSeg.add(cachedGroups);
							grpSez.setADGroups(grpSeg,actDomain);
						}
						else
						{
							sb = (StringBuffer)grp_Seg.get(3);
							nodeID = (String)grp_Seg.get(4);
							domainCaching = (Hashtable)grp_Seg.get(5);
						}
						session.setAttribute("listGroups",alist_Group);
						session.setAttribute("treeBean",sb.toString());
						session.setAttribute("treeData",sb.toString());
						session.setAttribute("selectedDomain",actDomain);
						session.setAttribute("domainName",tempdomainName);
						session.setAttribute("rootGrpList",list1);
						session.setAttribute("mainGroup",mainGroup);
						session.setAttribute("nodeID",nodeID);
						session.setAttribute("cachedGroups",domainCaching);

					}
					else
					{
						session.removeAttribute("rootTreeMap");
						ArrayList grpSeg = new ArrayList();
						String connectUser = domainUser + "@" + domainName;
						//ArrayList alistGroupCD = mbrof.getCategorizedADGroups(connectUser,domainPwd,domainName,strPortNo,ssl,tempdomainName);
						ArrayList alistGroupCD = new ArrayList();
						if (!StringUtils.isNull(domAliasName))
						{
							alistGroupCD = mbrof.getCategorizedADGroups(connectUser,domainPwd,domAliasName,strPortNo,ssl,tempdomainName);
						}
						else
						{
							alistGroupCD = mbrof.getCategorizedADGroups(connectUser,domainPwd,domainName,strPortNo,ssl,tempdomainName);
						}

						errorList = (ArrayList)mbrof.errorResult;
						ArrayList list1 = (ArrayList)mbrof.getCDGroups(alistGroupCD);
						ArrayList mainGroup = (ArrayList)mbrof.grpTree;
						alistGroup = (ArrayList)mbrof.alistGroup;

						StringBuffer sb = new StringBuffer();
						tree.createParentNodes(list1,mainGroup,tempdomainName);
						sb	= tree.genTree();
						int lastTraversedNode = tree.lastNodeId;
						Hashtable cachedGroups = tree.cachedGroups;
						String lastNodeId = String.valueOf(lastTraversedNode);

						session.setAttribute("listGroups",alistGroup);
						session.setAttribute("selectedDomain",actDomain);
						session.setAttribute("domainName",tempdomainName);
						session.setAttribute("treeBean",sb.toString());
						session.setAttribute("treeData",sb.toString());
						session.setAttribute("rootGrpList",list1);
						session.setAttribute("mainGroup",mainGroup);
						session.setAttribute("nodeID",lastNodeId);
						session.setAttribute("cachedGroups",cachedGroups);

						if (errorList != null && errorList.size() == 0)
						{
							grpSeg.add(list1);
							grpSeg.add(mainGroup);
							grpSeg.add(alistGroup);
							grpSeg.add(sb);
							grpSeg.add(lastNodeId);
							grpSeg.add(cachedGroups);
							grpSez.setADGroups(grpSeg,actDomain);
						}
						session.setAttribute("errorList",errorList);
					}
				}
			}
			catch(Exception e)
			{
				//error
			}
			rootJson.put("source","EgReplicate");
			rootJson.put("domainNameForGrp",domainName);
			session.setAttribute("source","EgReplicate");
			session.setAttribute("domainNameForGrp",domainName);
		}
	}
	boolean isValidCloningUser = true;
	//boolean isValidCloningUser = (cloningUser != null) && (!cloningUser.equals("none"));

	String str_currentdate = "";
	String str_currentday = "";
	String str_currentmonth = "";
	String str_currentyear = "";
	String str_currenthr = "";
	String str_currentmin = "";

	EgDateInfo Datehandler = new EgDateInfo();
	String str_currenttime=Datehandler.egetDate();
	str_currenttime=str_currenttime.replace(' ','*');
	str_currentdate=str_currenttime.substring(0,str_currenttime.indexOf("*"));
	str_currentday=str_currentdate.substring(0,str_currentdate.indexOf("/"));
	str_currentmonth=str_currentdate.substring(str_currentdate.indexOf("/") + 1,str_currentdate.lastIndexOf("/"));
	str_currentyear=str_currentdate.substring(str_currentdate.lastIndexOf("/") + 1,str_currentdate.length());
	str_currenthr=str_currenttime.substring(str_currenttime.indexOf("*") + 1,str_currenttime.indexOf(":"));
	str_currentmin=str_currenttime.substring(str_currenttime.indexOf(":") + 1,str_currenttime.lastIndexOf(":"));
	str_currentdate = str_currentmonth + "/" + str_currentday + "/" + str_currentyear;

	currentDateJson.put("str_currentdate",str_currentdate);
	currentDayJson.put("str_currentday",str_currentday);
	currentMonthJson.put("str_currentmonth",str_currentmonth);
	currentYearJson.put("str_currentyear",str_currentyear);
	currentHourJson.put("str_currenthr",str_currenthr);
	currentMinJson.put("str_currentmin",str_currentmin);

	// availableUsersTree - start
	IniFile inifile = new IniFile(EgInstallInfo.getInstallDir()+"/manager/config/eg_services.ini");
	String managerModel = inifile.getValue("MISC_ARGS","eGMgrModel");
	String session_userid = (String)session.getAttribute("sess_userid");
	if (hasAllComponentAccess)
	{
		if(managerModel != null && managerModel.equalsIgnoreCase("msp"))
		{
			IniFile inifile1 = new IniFile(EgConfigInfo.egMgrConfigDir + "eg_uuid.ini");
			String topLevelOrgs[] = inifile1.getVariables("ORG_UUID");

			ArrayList superOrgs = new ArrayList();
			if(topLevelOrgs != null && topLevelOrgs.length>0)
			{
				superOrgs.addAll(Arrays.asList(topLevelOrgs));
			}
			JSONArray exportDataArr = new JSONArray();
			for(int i=0;i<superOrgs.size();i++)
			{
				JSONObject exportDataObj = new JSONObject();
				String optVar = "";
				String optVal = "";

				String strDbChild = "";

				String orgname = (String)superOrgs.get(i);

				optVar = (String)superOrgs.get(i);
				optVal = (String)superOrgs.get(i);

				JSONArray rootUserObjectArray = egUuidInfo.buildTreeJsonForAllUsers(orgname,session_userid,false,"all");
				if (orgname.equalsIgnoreCase("egenterprise"))
				{
					if (!rootUserObjectArray.isEmpty())
					{
						exportDataObj.put("text",_mapping.getTextDescription("admin.user.egenterprise"));
						exportDataObj.put("id",optVar);
						exportDataObj.put("iconCls","iconDomain");
						exportDataObj.put("expanded",true);
						exportDataObj.put("children",rootUserObjectArray);
						exportDataArr.add(exportDataObj);
					}
				}
				else
				{
					exportDataObj.put("text",optVal);
					exportDataObj.put("id",optVar);
					exportDataObj.put("iconCls","iconDomain");
					exportDataObj.put("expanded",true);
					exportDataObj.put("children",rootUserObjectArray);
					exportDataArr.add(exportDataObj);
				}
			}
			rootJson.put("exportDataArr",exportDataArr);
			rootJson.put("RootNodeText","Choose an user");

			if (exportDataArr.isEmpty())
			{
				rootJson.put("isUsersCreated",new Boolean(false));
				out.println(rootJson);
				return;
			}
		}
		else
		{
			JSONArray exportDataArr = new JSONArray();
			JSONObject exportDataObj = new JSONObject();

			exportDataObj.put("text",_mapping.getTextDescription("admin.user.egenterprise"));
			exportDataObj.put("id","egenterprise");
			exportDataObj.put("iconCls","iconDomain");
			exportDataObj.put("expanded",true);

			JSONArray rootUserObjectArray = egUuidInfo.buildTreeJsonForAllUsers("egenterprise",session_userid,false,"all");
			exportDataObj.put("children",rootUserObjectArray);
			exportDataArr.add(exportDataObj);

			if (rootUserObjectArray.isEmpty())
			{
				rootJson.put("isUsersCreated",new Boolean(false));
				out.println(rootJson);
				return;
			}
			else
			{
				rootJson.put("exportDataArr",exportDataArr);
				rootJson.put("RootNodeText","Choose an user");
			}
		}
	}
	else
	{
		String orgname = "";
		boolean isSuperOrg = egUuidInfo.isSuperOrg(session_userid);
		boolean isOrg = egUuidInfo.isOrg(session_userid);
		if (isSuperOrg)
		{
			orgname = session_userid;
		}
		else if (isOrg)
		{
			orgname = session_userid;
		}
		else
		{
			orgname = egUuidInfo.getDirectDependentOU(session_userid);
		}
		
		JSONArray rootUserObjectArray = egUuidInfo.buildTreeJsonForAllUsers(orgname,session_userid,false,"all");
		rootJson.put("exportDataArr",rootUserObjectArray);
		rootJson.put("RootNodeText","Choose an user");

		if (rootUserObjectArray.isEmpty())
		{
			rootJson.put("isUsersCreated",new Boolean(false));
			out.println(rootJson);
			return;
		}
	}

	// availableUsersTree - end

	String strdomain="";
	String streg="";
	if (authenticationType.equalsIgnoreCase("Eg"))
	{
		streg = "checked";
	}
	else if (authenticationType.equalsIgnoreCase("Domain"))
	{
		strdomain = "checked";
	}
	authenticationTypeJson.put("authenticationType",authenticationType);
	String userNameWidth = "256";
	if (isValidCloningUser)
	{
		//if (authenticationType.equalsIgnoreCase("Domain"))
		{
			userNameWidth = "155";

			ArrayList allDomains=new ArrayList();
			if(domains!=null)
			{
				for(int i=0;i<domains.length;i++)
				{
					String domain = domains[i];
					if (!StringUtils.isNull(domain) && domain.equals("Domain_Alias"))
					{
						continue;
					}
					allDomains.add(domain);
					
				}
			}
			Collections.sort(allDomains,String.CASE_INSENSITIVE_ORDER);
			JSONObject chooseDomain = new JSONObject();
			chooseDomain.put("displayField","Choose a domain");
			chooseDomain.put("valueField","Choose a domain");
			domainArrayJson.add(chooseDomain);
			if(allDomains!=null && allDomains.size() > 0)
			{
				for(int i=0;i<allDomains.size();i++)
				{
					JSONObject domainObj = new JSONObject();
					String domain = (String) allDomains.get(i);
					domainObj.put("displayField",domain);
					domainObj.put("valueField",domain);
					domainArrayJson.add(domainObj);
					if(domain.equalsIgnoreCase(actDomain))
					{
						strSelect2 = "selected";
					}
					
					strSelect2 = "";
				}
			}

			String struser = "";
			String strgroup = "";
			if (operationType.equalsIgnoreCase("User"))
			struser="checked";
			else if (operationType.equalsIgnoreCase("Group"))
			strgroup="checked";
			operationTypeJson.put("operationType",operationType);
		}

		if (authenticationType.equalsIgnoreCase("Eg") || operationType.equalsIgnoreCase("Group") || "true".equals(isValidated))
		{
			TimeZoneUtil tzu = new TimeZoneUtil();
			String defaultText = _mapping.getTextDescription("admin.user.Default");

			ArrayList timeZoneList = tzu.getAllTimeZones();
			if (timeZoneList!=null && timeZoneList.size()>0)
			{
				JSONObject defaultTimeZoneObj = new JSONObject();
				String defaultTimeZone = tzu.getID();
				defaultTimeZoneJson.put("defaultTimeZone",defaultTimeZone);

				for (int i=0;i<timeZoneList.size();i++)
				{
					String timeZoneValue = (String)timeZoneList.get(i);
					StringTokenizer st = new StringTokenizer(timeZoneValue,"@");
					String offset = st.nextToken();
					String timeZoneId = st.nextToken();
					if(!timeZoneId.equals("Singapore"))
					{
						JSONObject timeZoneObj = new JSONObject();
						if (timeZoneId.equalsIgnoreCase(defaultTimeZone))
						{
							timeZoneId = timeZoneId + "(" + defaultText + ")";
							timeZoneObj.put("displayField",offset+" "+timeZoneId.replace('_',' '));
							timeZoneObj.put("valueField","default");
							timeZoneArrayJson.add(timeZoneObj);
						}
						else
						{
							timeZoneObj.put("displayField",offset+" "+timeZoneId.replace('_',' '));
							timeZoneObj.put("valueField",timeZoneId);
							timeZoneArrayJson.add(timeZoneObj);
						}
					}
				}
			}
			Object langCodes[] = egUI.getVariables("COUNTRY_AND_LANGUAGE_CODE");
			countryLang=new Hashtable();
			for (int i=0;i<langCodes.length;i++)
			{
				countryName=egUI.getValue("COUNTRY_AND_LANGUAGE_CODE",(String)langCodes[i]);
				countryLang.put(langCodes[i],countryName);
			}
			Enumeration keys=countryLang.keys();
			keyList=new ArrayList();
			while (keys.hasMoreElements())
			{
				keyList.add(keys.nextElement());
			}
			Collections.sort(keyList);
			userLanguageJson.put("userLanguage",userLanguage);
			for (int idx=0;idx<keyList.size();idx++)
			{
				JSONObject countryObj = new JSONObject();
				countryName=(String)keyList.get(idx);
				countryCode=(String)countryLang.get(countryName);
				countryObj.put("valueField",countryCode);
				countryObj.put("displayField",countryName);
				countryArrayJson.add(countryObj);
			}
		}

		for (int i=0;i<categoryArray.length;i++)
		{
			categoryArrayJson.add(categoryArray[i]);
		}
	}

	String[] idps=ssoIniObj.getSubjects();
	if(idps!=null)
	{
		JSONObject tmpObj = new JSONObject();
		tmpObj.put("displayField","Choose identiy provider");
		tmpObj.put("valueField","none");
		ssoList.add(tmpObj);

		for(int i=0;i<idps.length;i++)
		{
			String idp = idps[i];
			if (!com.egurkha.util.StringUtils.isNull(idps[i]) && (idps[i].equals("SAML_SSO") || idps[i].startsWith("SECONDARY_")))
			{
				continue;
			}

			tmpObj = new JSONObject();
			if(idp.equalsIgnoreCase(actSso))
			{
				rootJson.put("selectedSso",actSso);
			}
			tmpObj.put("displayField",idp);
			tmpObj.put("valueField",idp);
			ssoList.add(tmpObj);
		}
	}

	adDomainpwdJson.put("adDomainpwd",adDomainPwd);
	validatedUserJson.put("isValidUserForJSON",isValidUserForJSON);

	rootJson.put("ssoList",ssoList);
	rootJson.put("actionArrayJson",actionArrayJson);
	rootJson.put("domainArrayJson",domainArrayJson);
	rootJson.put("timeZoneArrayJson",timeZoneArrayJson);
	rootJson.put("countryArrayJson",countryArrayJson);
	rootJson.put("categoryArrayJson",categoryArrayJson);

	rootJson.put("authenticationTypeJson",authenticationTypeJson);
	rootJson.put("operationTypeJson",operationTypeJson);
	rootJson.put("userLanguageJson",userLanguageJson);

	rootJson.put("currentDateJson",currentDateJson);
	rootJson.put("currentDayJson",currentDayJson);
	rootJson.put("currentMonthJson",currentMonthJson);
	rootJson.put("currentYearJson",currentYearJson);
	rootJson.put("currentHourJson",currentHourJson);
	rootJson.put("currentMinJson",currentMinJson);

	rootJson.put("usersExistJson",usersExistJson);
	rootJson.put("isDoubleJson",isDoubleJson);
	rootJson.put("currentDateFormatJson",currentDateFormatJson);
	rootJson.put("adDomainpwdJson",adDomainpwdJson);
	rootJson.put("validatedUserJson",validatedUserJson);

	rootJson.put("defaultTimeZoneJson", defaultTimeZoneJson);
	rootJson.put("selectedDateFormatJson", selectedDateFormatJson);


	/* code for 2fa starts here */
	IniFile egMFAIniFile = new IniFile(EgInstallInfo.getInstallDir() + "/manager/config/eg_mfa.ini");

	String isAdminEnabled2FA = egMFAIniFile.getValue("2FA_SETTINGS","Is2FAEnabled");

	if (isAdminEnabled2FA.trim().length() == 0)
	{
		isAdminEnabled2FA = "false";
	}
	rootJson.put("isAdminEnabled2FA",isAdminEnabled2FA);

	if (isAdminEnabled2FA != null && (isAdminEnabled2FA.equalsIgnoreCase("yes") || isAdminEnabled2FA.equalsIgnoreCase("true")))
	{
		String twoFAOptionFlag = egMFAIniFile.getValue("2FA_SETTINGS","TwoFAOptionFlag");

		if (twoFAOptionFlag != null && twoFAOptionFlag.equalsIgnoreCase("c"))
		{
			rootJson.put("is2FACFlagEnabled","yes");
		}
		else
		{
			rootJson.put("is2FACFlagEnabled","no");
		}
	}

	/* code for 2fa ends here */

	out.println(rootJson);
%>

<%!
	public String getADErrorMessage(ArrayList stausList)
	{
		String errCode = "E999";
		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);
					}
				}
			}
			else if (errorStr.startsWith("javax.naming.NoPermissionException"))
			{
				errCode = "50";
			}
			else if (errorStr.startsWith("javax.naming.CommunicationException"))
			{
				if (errorStr.indexOf("SSLHandshakeException") > -1 || errorStr.indexOf("ValidatorException") > -1 || errorStr.indexOf("SunCertPathBuilderException") > -1)
				{
					errCode = "E010";
				}
				else
				{
					errCode = "2";
				}
			}
			else if (errorStr.startsWith("javax.naming.ServiceUnavailableException"))
			{
				errCode = "51";
			}
			else if(errorStr.startsWith("java.net.UnknownHostException"))
			{
				errCode = "E001";
			}
			else if (errorStr.startsWith("javax.naming.NamingException"))
			{
				errCode = "E999";
			}
			else
			{
				errCode = "E999";
			}
		}
		else if (stausList.contains("KERBEROS"))
		{
			int idx = stausList.indexOf("KERBEROS");
			String  errorStr =(String )stausList.get(idx+1);
			if (errorStr.startsWith("javax.naming.AuthenticationException"))
			{
				StringTokenizer strTokens = new StringTokenizer(errorStr,",");
				while(strTokens.hasMoreTokens())
				{
					String tok = strTokens.nextToken();
					if (tok.startsWith(" data "))
					{
						errCode = tok.substring(tok.indexOf(" ",1)+1);
					}
				}
			}
			else if (errorStr.startsWith("javax.net.ssl.SSLHandshakeException"))
			{
				errCode = "E010";
			}
			else if (errorStr.startsWith("Receive timed out"))
			{
				errCode = "E011";
			}
			else if (errorStr.startsWith("Clients credentials have been revoked"))
			{
				errCode = "E012";
			}
			else if (errorStr.startsWith("Server not found in Kerberos database"))
			{
				errCode = "E013";
			}
			else if (errorStr.startsWith("KDC has no support for encryption type"))
			{
				errCode = "E014";
			}
			else if (errorStr.startsWith("PRE_EXCEPTION"))
			{
				int idxy = stausList.indexOf("PRE_EXCEPTION");
				Exception e =(Exception)stausList.get(idxy+1);
				errorStr = e.toString();
				if (errorStr.startsWith("javax.naming.AuthenticationException"))
				{
					StringTokenizer strTokens = new StringTokenizer(errorStr,",");
					while(strTokens.hasMoreTokens())
					{
						String tok = strTokens.nextToken();
						if (tok.startsWith(" data "))
						{
							errCode = tok.substring(tok.indexOf(" ",1)+1);
						}
					}
				}
				else if (errorStr.startsWith("javax.naming.NoPermissionException"))
				{
					errCode = "50";
				}
				else if (errorStr.startsWith("javax.naming.CommunicationException"))
				{
					if (errorStr.indexOf("SSLHandshakeException") > -1 || errorStr.indexOf("ValidatorException") > -1 || errorStr.indexOf("SunCertPathBuilderException") > -1)
					{
						errCode = "E010";
					}
					else
					{
						errCode = "2";
					}
				}
				else if (errorStr.startsWith("javax.naming.ServiceUnavailableException"))
				{
					errCode = "51";
				}
				else if(errorStr.startsWith("java.net.UnknownHostException"))
				{
					errCode = "E001";
				}
				else if (errorStr.startsWith("javax.naming.NamingException"))
				{
					errCode = "E999";
				}
				else
				{
					errCode = "E999";
				}
			}
			else if (errorStr.startsWith("Clock skew too great"))
			{
				errCode = "E004";
			}
			else if (errorStr.startsWith("Identifier"))
			{
				errCode = "E006";
			}
			else if (errorStr.startsWith("Client not found in Kerberos database"))
			{
				errCode = "E007";
			}
			else if (errorStr.startsWith("Pre-authentication"))
			{
				errCode = "E005";
			}
			else if (stausList.contains("USER_EXCEPTION"))
			{
				errCode = "525";
			}
			else if (errorStr.startsWith("Invalid User"))
			{
				errCode = "E008";
			}
			else if (errorStr.startsWith("javax.naming.NoPermissionException"))
			{
				errCode = "50";
			}
			else if (errorStr.startsWith("javax.naming.CommunicationException"))
			{
				if (errorStr.indexOf("SSLHandshakeException") > -1 || errorStr.indexOf("ValidatorException") > -1 || errorStr.indexOf("SunCertPathBuilderException") > -1)
				{
					errCode = "E010";
				}
				else
				{
					errCode = "2";
				}
			}
			else if (errorStr.startsWith("javax.naming.ServiceUnavailableException"))
			{
				errCode = "51";
			}
			else if(errorStr.startsWith("java.net.UnknownHostException"))
			{
				errCode = "E001";
			}
			else if (errorStr.startsWith("javax.naming.NamingException"))
			{
				errCode = "E999";
			}
			else
			{
				errCode = "E999";
			}
		}
		else if (stausList.contains("USER_EXCEPTION"))
		{
			errCode = "525";
		}
		else if (stausList.contains("Others"))
		{
			int idx = stausList.indexOf("Others");
			String  errorStr =(String )stausList.get(idx+1);
			
			if (errorStr.startsWith("Invalid User"))
			{
				errCode = "E008";
			}
		}
		else if (stausList.contains("SocketException"))
		{
			errCode = "E001";
		}
		return errCode;
	}
%>



