
<%@ include file="../../EgTrackerAJSON.jsp"%>
<%@ page import="com.egurkha.EgUserRole" %>
<%@ page import = "com.egurkha.*"%>
<%@ page import = "java.util.*" %>
<%@ page import = "com.egurkha.util.*"%>
<%@ page import = "com.egurkha.util.StringUtils"%>
<%@ page import ="com.eg.EgDbAdapterTypeUI"%>
<%@ page import ="egurkha.EgDbAdapterUI"%>
<%@ page import="com.egurkha.EgConstants"%>
<%@ page import = "com.eg.EgMappingInfo"%>
<%@ page import = "com.eg.IniFile"%>
<%@ page import = "com.egurkha.util.DateUtil"%>
<%@ page import = "com.eg.EgInstallInfo" %>
<%@ page import = "com.eg.EgURLEncoder" %>
<%@ page import= "java.sql.*"%>
<%@ page import= "com.eg.EgGroupInfo"%>
<%@ page import= "com.eg.EgTopoInfo"%>
<%@ page import = "com.eg.EgName"%>
<%@ page import = "com.eg.MappingNameSorter"%>
<%@ page import = "com.egurkha.admin.AuditLogDAO"%>
<%@ page import = "com.egurkha.admin.AdminDAOFactory"%>
<%@ page import = "net.sf.json.*"%>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>

<%!
	private boolean doesExist(List searchList, String thisServer)
	{
		Iterator i = searchList.iterator();
		while(i.hasNext())
		{
			String nextStr = (String) i.next();
			if (thisServer.indexOf(nextStr)!=-1||(thisServer.toUpperCase().indexOf(nextStr.toUpperCase()))!=-1)
			{
				return true;
			}
		}
		return false;
	}

	public boolean isValidUser(String l_user)
	{
		l_user = StringUtils.replace(l_user,"\\","/");
		IniFile iniFile=new IniFile(EgInstallInfo.getInstallDir()+"/manager/config/eg_authenticate.ini");
		if (iniFile != null && l_user != null && l_user.indexOf("/") != -1)
		{
			l_user = l_user.substring(0,l_user.indexOf("/")).trim();
			String subjs[]=iniFile.getSubjects();
			if (subjs!=null && subjs.length>0)
			{
				for (int i=0;i<subjs.length ; i++)
				{
					String domainDisName = subjs[i];
					if (domainDisName != null && domainDisName.equalsIgnoreCase(l_user))
					{
						return true;
					}
				}
			}
		}
		return false;
	}

	public boolean isValidDomainUser(String l_user)
	{
		String tmpUsr1 = l_user;
		l_user = StringUtils.replace(l_user,"\\","/");
		IniFile iniFile=new IniFile(EgInstallInfo.getInstallDir()+"/manager/config/eg_authenticate.ini");
		if (iniFile != null && l_user != null && l_user.indexOf("/") != -1)
		{
			l_user = l_user.substring(0,l_user.indexOf("/")).trim();
			String subjs[]=iniFile.getSubjects();
			if (subjs!=null && subjs.length>0)
			{
				for (int i=0;i<subjs.length ; i++)
				{
					String domainDisName = subjs[i];
					if (domainDisName != null && domainDisName.equalsIgnoreCase(l_user) && tmpUsr1.indexOf("/Grp/") == -1)
					{
						return true;
					}
				}
			}
		}
		return false;
	}

	public boolean isValidDomainGroup(String l_user)
	{
		String tmpUsr = l_user;
		l_user = StringUtils.replace(l_user,"\\","/");
		IniFile iniFile=new IniFile(EgInstallInfo.getInstallDir()+"/manager/config/eg_authenticate.ini");
		if (iniFile != null && l_user != null && l_user.indexOf("/") != -1)
		{
			l_user = l_user.substring(0,l_user.indexOf("/")).trim();
			String subjs[]=iniFile.getSubjects();
			if (subjs!=null && subjs.length>0)
			{
				for (int i=0;i<subjs.length ; i++)
				{
					String domainDisName = subjs[i];
					if (domainDisName != null && domainDisName.equalsIgnoreCase(l_user) && tmpUsr.indexOf("/Grp/") != -1)
					{
						return true;
					}
				}
			}
		}
		return false;
	}
%>

<%
try
{
	JSONObject rootObj = new JSONObject();
	JSONObject intnlLabels = new JSONObject();
	JSONArray userDetailsGrid = new JSONArray();

	intnlLabels.put("admin.common.Time Zone",_mapping.getTextDescription("admin.common.Time Zone"));
	intnlLabels.put("admin.common.Format",_mapping.getTextDescription("admin.common.Format"));
	intnlLabels.put("admin.user.Change Profile",_mapping.getTextDescription("admin.user.Change Profile"));
	intnlLabels.put("admin.common.Zones",_mapping.getTextDescription("admin.common.Zones"));
	intnlLabels.put("admin.common.Service Groups",_mapping.getTextDescription("admin.common.Service Groups"));
	intnlLabels.put("admin.common.Services",_mapping.getTextDescription("admin.common.Services"));
	intnlLabels.put("admin.common.Segments",_mapping.getTextDescription("admin.common.Segments"));
	intnlLabels.put("admin.common.Components",_mapping.getTextDescription("admin.common.Components"));
	intnlLabels.put("admin.user.No associated elements",_mapping.getTextDescription("admin.user.No associated elements"));
	intnlLabels.put("admin.user.No User found for your current search",_mapping.getTextDescription("admin.user.No User found for your current search"));


	User user=registry.getUser(session.getId());
	registry.updateAllUserMaps();
	com.egurkha.ini.IniUI ui = (com.egurkha.ini.IniUI)com.egurkha.ini.IniUI.getInstance();
	String thisLanguage = ui.getDefaultLanguage();
	if (user!=null)
	{
		String userLang = user.getLanguage();
		if (userLang!=null && !userLang.equalsIgnoreCase("NULL"))
		{
			thisLanguage=userLang;
		}
	}

	EgUserRole userRole = _user.getUserRole();
	Vector getAllRoles = EgUserRole.getAllRoles();
	boolean hasAllComponentAccess = userRole.hasAllComponentAccess();

	String uname = user.getLoginID();
	
	EgMappingInfo mappingInfo = new EgMappingInfo(thisLanguage);
	MappingNameSorter sorter = new MappingNameSorter(thisLanguage);
	response.setHeader("Cache-Control","no-store");
	response.setHeader("Pragma","no-cache");
	response.setDateHeader("Expires", -1);
	
	EgDbAdapterUI egDb;
	ResultSet rs = null;
	String str_query = "";
	String str_conn = "";
	boolean b_state = false;
	Vector all_Users = null;
	ArrayList e_users = new ArrayList();
	final Hashtable e_users_reg = new Hashtable();
	Hashtable e_users_tz = new Hashtable();
	Hashtable e_users_vm = new Hashtable();
	
	TreeSet services = new TreeSet();
	TreeSet segments = new TreeSet();
	TreeSet userservers = new TreeSet();
	ArrayList userzones = new ArrayList();
	ArrayList userVMs = new ArrayList();
	ArrayList serviceGroups =new ArrayList();
	EgUserRole object = null;
	boolean hasallcompaccess = false;
	String timezone_query=null;
	String timezone="";
	String service_name="";
	String segment_name="";
	String server_name="";
	String zone_name="";
	String vm_name="";
	String showVMType = "";
	String servicegroup_name="";
	String expiry = "";
	String valid = "";
	String comment = "";
	String exp_str= "";
	String userComptypes="";
	String reqFrom=request.getParameter("reqfrom");
	reqFrom=(reqFrom != null && reqFrom.length()>0)?reqFrom:"";
	String egTitleSearchStr = request.getParameter("egTitleSearchStr");
	boolean isSearchResult =(egTitleSearchStr!=null);
	ArrayList searchList = new ArrayList();
	Vector sess_vec=new Vector();
	int vm_size =0;
	if (isSearchResult)
	{
		StringTokenizer st = new StringTokenizer(egTitleSearchStr);
		while (st.hasMoreTokens())
		{
			String thisToken = st.nextToken().trim();
			if (thisToken.equals(""))
				continue;
			searchList.add(thisToken);
		}
	}

	String uiFile = "eg_ui.ini";
	String s_iniFile_dir = EgInstallInfo.getInstallDir()+ "/manager/config/";
	IniFile egUI = new IniFile(s_iniFile_dir + uiFile);
	String currentDateFormat = egUI.getValue("CURRENT_DATE_FORMAT","selectedDateFormat");

	all_Users = new Vector();

	expiry = request.getParameter("expiry");
	if (expiry == null)
	{
		expiry = "all";
	}

	IniFile ServicesIni = new IniFile(EgInstallInfo.getInstallDir()+"/manager/config/eg_services.ini");
	String eGMgrModel = ServicesIni.getValue("MISC_ARGS","eGMgrModel");

	JSONArray optionsArr = new JSONArray();
	JSONObject optionsList = new JSONObject();
	optionsList.put("valueField","all");
	optionsList.put("displayField",_mapping.getTextDescription("admim.user.All Users"));
	optionsArr.add(optionsList);

	optionsList = new JSONObject();
	optionsList.put("valueField","nearing");
	optionsList.put("displayField",_mapping.getTextDescription("admim.user.Nearing Expiry Users"));
	optionsArr.add(optionsList);

	optionsList = new JSONObject();
	optionsList.put("valueField","noexpire");
	optionsList.put("displayField",_mapping.getTextDescription("admim.user.No Expiry Users"));
	optionsArr.add(optionsList);

	optionsList = new JSONObject();
	optionsList.put("valueField","expired");
	optionsList.put("displayField",_mapping.getTextDescription("admim.user.Expired Users"));
	optionsArr.add(optionsList);

	optionsList = new JSONObject();
	optionsList.put("valueField","activelocalusers");
	optionsList.put("displayField",_mapping.getTextDescription("admim.user.Active Local Users"));
	optionsArr.add(optionsList);
	
	if (eGMgrModel != null && !eGMgrModel.equalsIgnoreCase("msp"))
	{
		optionsList = new JSONObject();
		optionsList.put("valueField","activedomainusers");
		optionsList.put("displayField",_mapping.getTextDescription("admim.user.Active Domain Users"));
		optionsArr.add(optionsList);

		optionsList = new JSONObject();
		optionsList.put("valueField","activedomaingroups");
		optionsList.put("displayField",_mapping.getTextDescription("admim.user.Active Domain Groups"));
		optionsArr.add(optionsList);

		optionsList = new JSONObject();
		optionsList.put("valueField","activesamlusers");
		optionsList.put("displayField",_mapping.getTextDescription("admim.user.Active SAML Users"));
		optionsArr.add(optionsList);
	}
	
	IniFile lsIni = new IniFile(EgInstallInfo.getInstallDir() + "/manager/config/eg_ls_portal.ini");
	IniFile mgrIni = new IniFile(EgInstallInfo.getInstallDir() + "/manager/config/eg_mgrmisc.ini");
	String defaultPortal = lsIni.getValue("LS_TRIAL_SETTINGS","defaultPortal");
	String cloudModel = lsIni.getValue("LS_TRIAL_SETTINGS","cloudModel");

	String [] email = null;
	String [] regemail = null;

	if (defaultPortal != null && defaultPortal.equalsIgnoreCase("clstrial"))
	{
		email = lsIni.getVariables("LS_TRIAL_USER_DETAILS");
		regemail = lsIni.getVariables("NOT_REGISTERED_USERS_CLS");
	}
	else if (defaultPortal != null && defaultPortal.equalsIgnoreCase("cloud"))
	{
		email = lsIni.getVariables("CLOUD_USER_DETAILS");
		regemail = lsIni.getVariables("NOT_REGISTERED_USERS_CLOUD");
	}

	ArrayList userList = new ArrayList();
	if (email != null && email.length > 0)
	{
		userList = new ArrayList(Arrays.asList(email));
	}

	ArrayList reguserList = new ArrayList();
	if (regemail != null && regemail.length > 0)
	{
		reguserList = new ArrayList(Arrays.asList(regemail));
	}

	String [] blockedemail = lsIni.getVariables("Blocked_Users");
	ArrayList blockeduserList = new ArrayList();
	if (blockedemail != null && blockedemail.length > 0)
	{
		blockeduserList = new ArrayList(Arrays.asList(blockedemail));
	}

	String [] changePassword = mgrIni.getVariables("CHANGE_PASSWORD");
	ArrayList restrictChangePasswordList = new ArrayList();
	if (changePassword != null && changePassword.length > 0)
	{
		for (int i=0;i<changePassword.length;i++)
		{
			String userName = changePassword[i];
			String changePwd = mgrIni.getValue("CHANGE_PASSWORD",userName);
			if (changePwd != null && changePwd.equalsIgnoreCase("false"))
			{
				restrictChangePasswordList.add(userName);
			}
		}
	}

	String enableLS = lsIni.getValue("LS_TRIAL_SETTINGS","enableLS");
	if (enableLS != null && (enableLS.equalsIgnoreCase("true") || enableLS.equalsIgnoreCase("yes")))
	{
		if (defaultPortal != null && defaultPortal.equalsIgnoreCase("clstrial"))
		{
			optionsList = new JSONObject();
			optionsList.put("valueField","logonsimulatorusers");
			optionsList.put("displayField",_mapping.getTextDescription("admim.user.Logon Simulator Users"));
			optionsArr.add(optionsList);

			optionsList = new JSONObject();
			optionsList.put("valueField","nonactiveusers");
			optionsList.put("displayField",_mapping.getTextDescription("admim.user.Logon Simulator Users - Non Active"));
			optionsArr.add(optionsList);

			optionsList = new JSONObject();
			optionsList.put("valueField","logonsimulatoregusers");
			optionsList.put("displayField",_mapping.getTextDescription("admim.user.Logon Simulator Users - eG Innovations"));
			optionsArr.add(optionsList);

			optionsList = new JSONObject();
			optionsList.put("valueField","logonsimulatorregusers");
			optionsList.put("displayField",_mapping.getTextDescription("admim.user.Logon Simulator Users - Not Registered"));
			optionsArr.add(optionsList);
		}
		else if (defaultPortal != null && defaultPortal.equalsIgnoreCase("cloud"))
		{
			optionsList = new JSONObject();
			optionsList.put("valueField","cloudusers");
			optionsList.put("displayField",_mapping.getTextDescription("admim.user.eG Enterprise Cloud Users"));
			optionsArr.add(optionsList);

			optionsList = new JSONObject();
			optionsList.put("valueField","cloudregusers");
			optionsList.put("displayField",_mapping.getTextDescription("admim.user.eG Enterprise Cloud Users - Not Registered"));
			optionsArr.add(optionsList);
		}
	}

	rootObj.put("optionsArr",optionsArr);

	if (expiry.equalsIgnoreCase("logonsimulatorregusers") || expiry.equalsIgnoreCase("cloudregusers"))
	{
		JSONArray gridColums = new JSONArray();
		gridColums.add(_mapping.getTextDescription("admin.user.User Name"));
		gridColums.add(_mapping.getTextDescription("admin.user.First Name"));
		gridColums.add(_mapping.getTextDescription("admin.user.Last Name"));
		gridColums.add(_mapping.getTextDescription("admin.user.Phone Number"));
		gridColums.add(_mapping.getTextDescription("admin.user.Company"));
		gridColums.add(_mapping.getTextDescription("admin.user.Time Zone"));
		rootObj.put("gridColums",gridColums);

		List csvData = new ArrayList();
		String csvRow = "";
		String colHeads =  "User Name,First Name,Last Name,Phone Number,Company,Time Zone";
		csvData.add("");
		csvData.add(colHeads);

		JSONArray searchArr = new JSONArray();
		JSONObject searchObj = new JSONObject();
		StringTokenizer colHeadsST = new StringTokenizer(colHeads,",");
		while (colHeadsST.hasMoreTokens())
		{
			String tokens = colHeadsST.nextToken();
			searchObj.put("displayField",tokens);
			searchObj.put("valueField",tokens);
			searchArr.add(searchObj);
		}
		rootObj.put("searchArr",searchArr);

		for (int reg=0;reg<reguserList.size();reg++)
		{
			JSONObject tmpObj = new JSONObject();
			String regusername = (String)reguserList.get(reg);
			String reguserDetails = "";
			if (defaultPortal != null && defaultPortal.equalsIgnoreCase("clstrial"))
			{
				reguserDetails = lsIni.getValue("NOT_REGISTERED_USERS_CLS",regusername);
			}
			else if (defaultPortal != null && defaultPortal.equalsIgnoreCase("cloud"))
			{
				reguserDetails = lsIni.getValue("NOT_REGISTERED_USERS_CLOUD",regusername);
			}
			
			ArrayList regDetails = new ArrayList(StringUtils.egTokenizer(reguserDetails,"#@#"));
			tmpObj.put("UserName",regusername);
			tmpObj.put("FirstName",(String)regDetails.get(0));
			tmpObj.put("LastName",(String)regDetails.get(1));
			tmpObj.put("Company",(String)regDetails.get(2));
			tmpObj.put("PhoneNumber",(String)regDetails.get(3));
			String timeZone = (String)regDetails.get(5);
			TimeZone tz =TimeZone.getDefault();
			TimeZoneUtil tzu = new TimeZoneUtil();
			if(timeZone.equalsIgnoreCase("default"))
			{
				String[] timeZoneIDs = tz.getAvailableIDs();
				for(int z=0;z<timeZoneIDs.length;z++)
				{
					if(timeZoneIDs[z].equals(tzu.getID()))
					{
						timeZone = timeZoneIDs[z];
						break;
					}
				}
			}
			String timeZoneStr = tzu.getTimeZoneOffset(TimeZone.getTimeZone(timeZone))+" "+timeZone.replace('_',' ');
			tmpObj.put("TimeZone",timeZoneStr);

			csvRow = regusername+","+(String)regDetails.get(0)+","+(String)regDetails.get(1)+","+(String)regDetails.get(3)+","+(String)regDetails.get(2)+","+StringUtils.replace(timeZoneStr,","," ");
			csvData.add(csvRow);
			userDetailsGrid.add(tmpObj);
		}
		session.setAttribute("list",csvData);
		session.setAttribute("isAuditlogCSV","true");
		rootObj.put("UserInfo",userDetailsGrid);
		out.println(rootObj.toString());
		return;
	}
	egDb=EgDbAdapterTypeUI.getObject();
	try
	{
		//{
			try
			{
				str_conn = egDb.setConnection();
				//str_query = "SELECT user_id FROM user_info";
				str_query = "select user_id, user_reg_date from user_info";
				rs = egDb.dbselect(str_query);
				while(rs.next())
				{
					all_Users.add((String)rs.getString("user_id"));

					String user_id_forReg = rs.getString("user_id");
					String reg_date = rs.getString("user_reg_date");
					if (reg_date != null)
					{
						e_users_reg.put(user_id_forReg,reg_date);
					}
					else
					{
						e_users_reg.put(user_id_forReg,"Not Available");
					}
				}

				if (rs != null)
					rs.close();
			}
			catch(Exception e)
			{
				egDb.releaseConnection(true);
				e.printStackTrace();
			}

			try
			{
				str_query = "SELECT user_id, timezone FROM user_pref";
				rs = egDb.dbselect(str_query);

				while (rs.next())
				{
					String str_user_id = rs.getString("user_id");
					String str_time_zone = rs.getString("timezone");
					if (str_time_zone != null)
					{
						e_users_tz.put(str_user_id,str_time_zone);
					}
				}

				if (rs != null)
				{
					rs.close();
				}
			}
			catch(Exception e)
			{
				egDb.releaseConnection(true);
				e.printStackTrace();
			}

			try
			{
				str_query = "SELECT user_id, vm_name FROM user_vm";
				rs = egDb.dbselect(str_query);

				while (rs.next())
				{
					String str_user_id = rs.getString("user_id");
					String str_vm_name = rs.getString("vm_name");

					ArrayList aListVMs = (ArrayList) e_users_vm.get(str_user_id);
					if (aListVMs == null)
					{
						aListVMs = new ArrayList();
					}
					aListVMs.add(str_vm_name);
					e_users_vm.put(str_user_id,aListVMs);
				}

				if (rs != null)
				{
					rs.close();
				}
			}
			catch(Exception e)
			{
				egDb.releaseConnection(true);
				e.printStackTrace();
			}

			EgUuidInfo egUuidInfo = new EgUuidInfo();

			Vector orgSpecificUserList = new Vector();
			if(!hasAllComponentAccess)
			{
				String sess_userid = (String)session.getAttribute("sess_userid");
				String orgname = "";
				boolean isSuperOrg = egUuidInfo.isSuperOrg(sess_userid);
				boolean isOrg = egUuidInfo.isOrg(sess_userid);
				if (isSuperOrg)
				{
					orgname = sess_userid;
				}
				else if (isOrg)
				{
					orgname = sess_userid;
				}
				else
				{
					orgname = egUuidInfo.getDirectDependentOU(sess_userid);
				}
				orgSpecificUserList.addAll(egUuidInfo.getAllUsersUnderOrg(orgname));
				all_Users.retainAll(orgSpecificUserList);
				all_Users.remove((String)session.getAttribute("sess_userid"));
			}
			else
			{
				if (eGMgrModel != null && eGMgrModel.equalsIgnoreCase("enterprise"))
				{
					orgSpecificUserList.addAll(egUuidInfo.getAllUsersUnderOrg("egenterprise"));
					orgSpecificUserList.add("egenterprise");
					all_Users.retainAll(orgSpecificUserList);
					all_Users.remove((String)session.getAttribute("sess_userid"));
				}
			}

			if(all_Users.size() == 0)
			{
				rootObj.put("success","true");
				rootObj.put("requestStatus","failed");
				JSONObject errorObj = new JSONObject();
				errorObj.put("title",_mapping.getTextDescription("admim.user.User Information"));
				errorObj.put("message1",_mapping.getTextDescription("admin.user.User is not created in eG Enterprise")+"...");
				rootObj.put("errors",errorObj);
				//out.println(rootObj.toString());
			}
			else
			{
				//String reg_date = "";
				//String user_id_forReg = "";
				//rs = egDb.dbselect("select user_id, user_reg_date from user_info");
				//while(rs.next())
				//{
					//user_id_forReg = rs.getString("user_id");
					//reg_date = rs.getString("user_reg_date");
					//if (reg_date != null)
					//{
					//	e_users_reg.put(user_id_forReg,reg_date);
					//}
				//}
				//rs.close();

				List userIds = null;
				String startDate = null;
				String endDate = null;
				Hashtable metaTestData = new Hashtable();
				Hashtable auditData = new Hashtable();
				if (expiry != null && expiry.equalsIgnoreCase("nonactiveusers"))
				{
					startDate = request.getParameter("startDate");
					endDate = request.getParameter("endDate");

					AuditLogDAO dao = AdminDAOFactory.getAuditLogDAO();
					dao.setStartDate(startDate);
					dao.setEndDate(endDate);
					userIds = dao.getAllUserIDS();

					IniFile dbIni = new IniFile(EgInstallInfo.getInstallDir()+"/manager/config/eg_db.ini");
					String dbType = dbIni.getValue("DB_PROPERTIES","DB_Server_Type");
					String metaTestQuery = "";
					String auditQuery = "";

					if (dbType != null && dbType.equalsIgnoreCase("EgMsSqlAdapter"))
					{
						metaTestQuery = "select * from (select comp_name,msmt_time, row_number() over(partition by comp_name order by msmt_time desc) as t from metatest) as a where t <2 order by comp_name";
						auditQuery = "select * from (select user_id,login_time, row_number() over(partition by user_id order by login_time desc) as t from auditlog) as a where t <2 order by user_id";
					}
					else if (dbType != null && dbType.equalsIgnoreCase("EgOracleAdapter"))
					{
						metaTestQuery = "select * from (select comp_name,msmt_time, row_number() over(partition by comp_name order by msmt_time desc) as t from metatest) where t <2 order by comp_name";
						auditQuery = "select * from (select user_id,login_time, row_number() over(partition by user_id order by login_time desc) as t from auditlog) where t <2 order by user_id ";
					}

					rs = egDb.dbselect(metaTestQuery);
					while(rs.next())
					{
						String comp_name = rs.getString("comp_name");
						String msmt_time = rs.getString("msmt_time");
						StringTokenizer stk1 =  new StringTokenizer(msmt_time," ");
						String date = stk1.nextToken();
						String s_msmt_date = date;
						s_msmt_date = s_msmt_date.substring(s_msmt_date.indexOf('-') + 1,s_msmt_date.length()) + "-" + s_msmt_date.substring(0,s_msmt_date.indexOf('-'));
						
						s_msmt_date = StringUtils.replace(s_msmt_date,"-","/");
						metaTestData.put(comp_name,s_msmt_date);
					}
					rs.close();

					rs = egDb.dbselect(auditQuery);
					while(rs.next())
					{
						String user_id = rs.getString("user_id");
						String login_time = rs.getString("login_time");
						auditData.put(user_id,login_time);
					}
					rs.close();
				}

				//if user configuration is built
				rs = egDb.selectValidityPeriod(); // gives the user expiry details
				while(rs.next())
				{
					String user_id = rs.getString("user_id");

					if (user_id.equalsIgnoreCase("egsm") || user_id.equalsIgnoreCase("egenterprise"))
					{
						continue;
					}

					boolean isdefuser = User.isDefaultUser((String)rs.getString("user_id"));

					if(!hasAllComponentAccess)
					{
						if (!orgSpecificUserList.contains(user_id))
						{
							continue;
						}
						if (((String)session.getAttribute("sess_userid")).equalsIgnoreCase(user_id))
						{
							continue;
						}
					}
					else
					{
						if (eGMgrModel != null && eGMgrModel.equalsIgnoreCase("enterprise") && !orgSpecificUserList.contains(user_id))
						{
							continue;
						}
						if (!isdefuser && ((String)session.getAttribute("sess_userid")).equalsIgnoreCase(user_id))
						{
							continue;
						}
					}
					//if (user_id.indexOf("/Grp/") != -1)
					//{
					//	String grpDelimiter = "/Grp/";
					//	int idx = user_id.indexOf(grpDelimiter);
					//	String str_uname_A = user_id.substring(0,idx);
					//	int nextIdx = idx + grpDelimiter.length();
					//	String str_uname_B = user_id.substring(nextIdx);
					//	user_id = str_uname_A + "/" + str_uname_B + " (Group)";
					//}
					String user_type = rs.getString("user_type");
					String  user_valid_till = rs.getString("user_valid_till");
					long days = rs.getLong("days");
					String user_mailid = rs.getString("user_mailid");

					if (user_mailid == null || user_mailid.trim().length() == 0)
					{
						user_mailid = "Not Available";
					}

					if(!isdefuser)
					{
						if(days < 0 &&( expiry.equals("expired") || expiry.equals("all") ) )
						{
							valid="'eg_images/expiredlicense.gif'";
							comment="'Subscription expired'";
							exp_str = "Expired on ";
							e_users.add(user_id+"|hash|"+user_type+"#"+valid+"#"+comment+"#"+exp_str+"#"+user_valid_till+"#"+user_mailid);
						}
						else if(days >= 0 && days <= 7 && (expiry.equals("nearing")|| expiry.equals("all") ))
						{
							if(days==0)
								comment = "'Subscription expires today'";
							else if(days==1)
								comment = "'Subscription will expire in 1 day'";
							else
								comment=" ' "+ days + " days for the subscription to expire'";
							valid="'eg_images/7days.gif'";
							exp_str ="Expiry on ";
							e_users.add(user_id+"|hash|"+user_type+"#"+valid+"#"+comment+"#"+exp_str+"#"+user_valid_till+"#"+user_mailid);
						}
						else if(days > 7 && expiry.equals("all"))
						{
							if(user_valid_till.equals("12/12/9999"))
								exp_str =  mappingInfo.getTextDescription("admin.user.No expiry");
							else
								exp_str = mappingInfo.getTextDescription("admin.user.Expiry on ");
							
							valid="'eg_images/validlicense.gif'";
							comment="'Valid subscription'";
							
							e_users.add(user_id+"|hash|"+user_type+"#"+valid+"#"+comment+"#"+exp_str+"#"+user_valid_till+"#"+user_mailid);
						}
						else if(days > 7 && expiry.equals("noexpire") && user_valid_till.equals("12/12/9999"))
						{
							if(user_valid_till.equals("12/12/9999"))
								exp_str =  mappingInfo.getTextDescription("admin.user.No expiry");
							else
								exp_str = mappingInfo.getTextDescription("admin.user.Expiry on ");
							
							valid="'eg_images/validlicense.gif'";
							comment="'Valid subscription'";
							
							e_users.add(user_id+"|hash|"+user_type+"#"+valid+"#"+comment+"#"+exp_str+"#"+user_valid_till+"#"+user_mailid);
						}
						else if (days > 7 && expiry.equals("activelocalusers") && !isValidUser(user_id) && !user_id.startsWith("samlsso/"))
						{
							if(user_valid_till.equals("12/12/9999"))
								exp_str =  mappingInfo.getTextDescription("admin.user.No expiry");
							else
								exp_str = mappingInfo.getTextDescription("admin.user.Expiry on ");
							
							valid="'eg_images/validlicense.gif'";
							comment="'Valid subscription'";
							e_users.add(user_id+"|hash|"+user_type+"#"+valid+"#"+comment+"#"+exp_str+"#"+user_valid_till+"#"+user_mailid);
						}
						else if (days > 7 && expiry.equals("activedomainusers") && isValidDomainUser(user_id))
						{
							if(user_valid_till.equals("12/12/9999"))
								exp_str =  mappingInfo.getTextDescription("admin.user.No expiry");
							else
								exp_str = mappingInfo.getTextDescription("admin.user.Expiry on ");
							
							valid="'eg_images/validlicense.gif'";
							comment="'Valid subscription'";
							e_users.add(user_id+"|hash|"+user_type+"#"+valid+"#"+comment+"#"+exp_str+"#"+user_valid_till+"#"+user_mailid);
						}
						else if (days > 7 && expiry.equals("activedomaingroups") && isValidDomainGroup(user_id))
						{
							if(user_valid_till.equals("12/12/9999"))
								exp_str =  mappingInfo.getTextDescription("admin.user.No expiry");
							else
								exp_str = mappingInfo.getTextDescription("admin.user.Expiry on ");
							
							valid="'eg_images/validlicense.gif'";
							comment="'Valid subscription'";
							e_users.add(user_id+"|hash|"+user_type+"#"+valid+"#"+comment+"#"+exp_str+"#"+user_valid_till+"#"+user_mailid);
						}
						else if (days > 7 && expiry.equals("activesamlusers") && user_id.startsWith("samlsso/"))
						{
							if(user_valid_till.equals("12/12/9999"))
								exp_str =  mappingInfo.getTextDescription("admin.user.No expiry");
							else
								exp_str = mappingInfo.getTextDescription("admin.user.Expiry on ");
							
							valid="'eg_images/validlicense.gif'";
							comment="'Valid subscription'";
							e_users.add(user_id+"|hash|"+user_type+"#"+valid+"#"+comment+"#"+exp_str+"#"+user_valid_till+"#"+user_mailid);
						}
						else if (expiry.equals("logonsimulatorusers"))
						{
							if(user_valid_till.equals("12/12/9999"))
								exp_str =  mappingInfo.getTextDescription("admin.user.No expiry");
							else
								exp_str = mappingInfo.getTextDescription("admin.user.Expiry on ");
							valid="'eg_images/validlicense.gif'";
							comment="'Valid subscription'";
							if (user_id.indexOf("@eginnovations.com") == -1)
							{
								if (userList.contains(user_id))
								{
									e_users.add(user_id+"|hash|"+user_type+"#"+valid+"#"+comment+"#"+exp_str+"#"+user_valid_till+"#"+user_mailid);
								}
							}
						}
						else if (expiry.equals("logonsimulatoregusers"))
						{
							if(user_valid_till.equals("12/12/9999"))
								exp_str =  mappingInfo.getTextDescription("admin.user.No expiry");
							else
								exp_str = mappingInfo.getTextDescription("admin.user.Expiry on ");
							valid="'eg_images/validlicense.gif'";
							comment="'Valid subscription'";
							if (user_id.indexOf("@eginnovations.com") != -1)
							{
								if (userList.contains(user_id))
								{
									e_users.add(user_id+"|hash|"+user_type+"#"+valid+"#"+comment+"#"+exp_str+"#"+user_valid_till+"#"+user_mailid);
								}
							}
						}
						else if (expiry.equals("cloudusers"))
						{
							if(user_valid_till.equals("12/12/9999"))
								exp_str =  mappingInfo.getTextDescription("admin.user.No expiry");
							else
								exp_str = mappingInfo.getTextDescription("admin.user.Expiry on ");
							valid="'eg_images/validlicense.gif'";
							comment="'Valid subscription'";
							//if (user_id.indexOf("@eginnovations.com") == -1)
							{
								if (userList.contains(user_id))
								{
									e_users.add(user_id+"|hash|"+user_type+"#"+valid+"#"+comment+"#"+exp_str+"#"+user_valid_till+"#"+user_mailid);
								}
							}
						}
						else if (expiry.equals("nonactiveusers"))
						{
							if(user_valid_till.equals("12/12/9999"))
								exp_str =  mappingInfo.getTextDescription("admin.user.No expiry");
							else
								exp_str = mappingInfo.getTextDescription("admin.user.Expiry on ");
							valid="'eg_images/validlicense.gif'";
							comment="'Valid subscription'";
							if (user_id.indexOf("@eginnovations.com") == -1)
							{
								if (userList.contains(user_id))
								{
									String userRegDate = (String)e_users_reg.get(user_id);
									StringTokenizer stk1 =  new StringTokenizer(userRegDate," ");
									String date = stk1.nextToken();
									String s_regdate = date;
									s_regdate = s_regdate.substring(s_regdate.indexOf('-') + 1,s_regdate.length()) + "-" + s_regdate.substring(0,s_regdate.indexOf('-'));
									
									s_regdate = StringUtils.replace(s_regdate,"-","/");
									
									if (s_regdate.compareTo(startDate) <= 0) 
									{
										if (!userIds.contains(user_id))
										{
											String user_comp = lsIni.getValue("USER_RN_MAP",user_id);
											if (user_comp != null && user_comp.length() > 0)
											{
												String usrComp = "LogonSimulator_"+user_comp+":NULL";
												String compReportDate = (String)metaTestData.get(usrComp);
												if (compReportDate != null)
												{
													if (compReportDate.compareTo(startDate) <= 0) 
													{
														e_users.add(user_id+"|hash|"+user_type+"#"+valid+"#"+comment+"#"+exp_str+"#"+user_valid_till+"#"+user_mailid);
													}
												}
												else
												{
													e_users.add(user_id+"|hash|"+user_type+"#"+valid+"#"+comment+"#"+exp_str+"#"+user_valid_till+"#"+user_mailid);
												}
											}
										}
									}
								}
							}
						}
					}
					else
					{
						if (expiry.equals("all"))
						{
							e_users.add(user_id+"|hash|"+user_type+"#"+"'eg_images/validlicense.gif'"+"#"+"'Valid subscription'"+"#"+mappingInfo.getTextDescription("admin.user.No expiry")+"#"+"12/12/9999"+"#"+user_mailid);
						}
					}
				}
				rs.close();

				ArrayList servicesList = egDb.selectAllUserServices();//get all services associated to users
				ArrayList segmentsList = egDb.selectAllUserSegments();//get all segments assocaited to users
				ArrayList userserv = egDb.selectAllUserServers();//get all components associated to users
				userzones = egDb.selectAllUserZones();//get all components associated to users
				
				if (servicesList != null && servicesList.size() > 0)
				{
					services.addAll(servicesList);
				}
				if (segmentsList != null && segmentsList.size() > 0)
				{
					segments.addAll(segmentsList);
				}
				if (userserv != null && userserv.size() > 0)
				{
					userservers.addAll(userserv);
				}

				//EgGroupInfo groupinfo = new EgGroupInfo();
				//EgTopoInfo topoinfo = groupinfo.getTopoInfoObject();

				//if(userzones.size()!=0)
				//{
					//for(int m=0;m<userzones.size();m++)
					//{
						//String all_servers = (String)userzones.get(m);
						//int strIndex = all_servers.indexOf("|hash|");
						//String uid = all_servers.substring(0,strIndex);
						
						//String thisZoneName = all_servers.substring(strIndex+6,all_servers.length());
						//ArrayList zoneServices = groupinfo.getServicesUnderZone(thisZoneName, false);
						//Iterator serI = zoneServices.iterator();
						//while (serI.hasNext())
						//{
							//String thisSer = (String) serI.next();
							//String addString = uid+"|hash|"+thisSer;
							//services.add(addString);
						//}

						//ArrayList zoneSegments = groupinfo.getSegmentsUnderZone(thisZoneName, false);
						//Iterator segI = zoneSegments.iterator();
						//while (segI.hasNext())
						//{
							//String thisSeg = (String) segI.next();
							//String addString = uid+"|hash|"+thisSeg;
							//segments.add(addString);
						//}


						//ArrayList zoneComps = groupinfo.getIndependentElementsUnderZone(true, thisZoneName);
						//Iterator zoneI = zoneComps.iterator();
						//while (zoneI.hasNext())
						//{
							//String thisCmp = (String) zoneI.next();
							//String thisType = thisCmp.substring(0, thisCmp.indexOf(":"));
							//String thisName = thisCmp.substring(thisCmp.indexOf(":")+1);
							////kk#test:NULL#Generic_server
							//String addString = uid+"|hash|"+thisName+"#"+thisType;
							//userservers.add(addString);
						//}
					//}
				//}

				//if(services.size()!=0)
				//{
					//Iterator serI = services.iterator();
					//while (serI.hasNext())
					//{
						//String all_services = (String) serI.next();
						//int strIndex = all_services.indexOf("|hash|");
						//String uid = all_services.substring(0,strIndex);
						//String serviceName = all_services.substring(strIndex+6,all_services.length());
						//if(serviceName != null && serviceName.length()>0)
						//{
///*******************/ // Added by Maruthu
							//if(serviceName!=null && serviceName.length() > 0)
							//{
								//Vector componentsForService = topoinfo.getComponentsForSite(serviceName);
								//for(int p=0;p<componentsForService.size();p++)
								//{
									//String compName = (String)componentsForService.get(p);
									//int lastIndex = compName.lastIndexOf(":");
									//String thisName = compName.substring(0,lastIndex);
									//String thisType = compName.substring(lastIndex+1);
									//String addString = uid+"|hash|"+thisName+"#"+thisType;
									//userservers.add(addString);
								//}
							//}
///*******************/ // End
						//}
					//}
				//}

				//if(segments.size()!=0)
				//{
					//Iterator segI = segments.iterator();
					//while (segI.hasNext())
					//{
						//String all_segments = (String) segI.next();
						//int strIndex = all_segments.indexOf("|hash|");
						//String uid = all_segments.substring(0,strIndex);
						//String segmentName = all_segments.substring(strIndex+6,all_segments.length());
						//if(segmentName != null && segmentName.length()>0)
						//{
///*******************/// Added by Maruthu
							//if(segmentName!=null && segmentName.length() > 0)
							//{
								//Vector componentsForSegment = topoinfo.getComponentsForSegment(segmentName);
								//if (componentsForSegment != null)
								//{
									//for(int p=0;p<componentsForSegment.size();p++)
									//{
										//String compName = (String)componentsForSegment.get(p);
										//int lastIndex = compName.lastIndexOf(":");
										//String thisName = compName.substring(0,lastIndex);
										//String thisType = compName.substring(lastIndex+1);
										//String addString = uid+"|hash|"+thisName+"#"+thisType;
										//userservers.add(addString);
									//}
								//}
							//}
///*******************/ // End
						//}
					//}
				//}

				rs = egDb.dbselect("SELECT USER_ID,SERVICEGROUP_NAME FROM USER_SERVICEGROUP");
				while(rs.next())
				{
					String userId = rs.getString("user_id");
					String servGroup_Name = rs.getString("SERVICEGROUP_NAME");
					serviceGroups.add(userId+"|hash|"+servGroup_Name);
				}
				rs.close();
				

				//if(serviceGroups!=null && serviceGroups.size()>0)
				//{
					//for(int j=0;j<serviceGroups.size();j++)
					//{
						//String all_serviceGroups = (String)serviceGroups.get(j);
						//int strIndex = all_serviceGroups.indexOf("|hash|");
						//String uid = all_serviceGroups.substring(0,strIndex);
						//String serviceGroupsName = all_serviceGroups.substring(strIndex+6,all_serviceGroups.length());
						//if(serviceGroupsName!=null && serviceGroupsName.length() > 0)
						//{
							//ArrayList sergroupServices = groupinfo.getAllServicesFromServiceGroup(serviceGroupsName);
							//Iterator serI = sergroupServices.iterator();
							//while (serI.hasNext())
							//{
								//String thisSer = (String) serI.next();
								//String addString = uid+"|hash|"+thisSer;
								//services.add(addString);
							//}
						//}
					//}
				//}

				
				boolean searchItemFound = false;
				//Collections.sort(e_users,String.CASE_INSENSITIVE_ORDER);
				Collections.sort(e_users, new Comparator() {
					  public int compare(Object o1, Object o2){
							String line1 = o1.toString();
							String line2 = o2.toString();

							int strUserIndex = line1.indexOf("|hash|");
							String user_name = line1.substring(0,strUserIndex);

							String user_reg_date = (String)e_users_reg.get(user_name);
							String regdate = user_reg_date;

							int strUserIndex1 = line2.indexOf("|hash|");
							String user_name1 = line2.substring(0,strUserIndex1);

							String user_reg_date1 = (String)e_users_reg.get(user_name1);
							String regdate1 = user_reg_date1;

							if (regdate.equalsIgnoreCase("Not Available"))
							{
								regdate = "1111-01-01 00:00:59.0";
							}
							if (regdate1.equalsIgnoreCase("Not Available"))
							{
								regdate1 = "1111-01-01 00:00:59.0";
							}

							java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" );
							java.util.Date d1 = new java.util.Date();
							java.util.Date d2 = new java.util.Date();
							try {
								d1 = sdf.parse( regdate );
								d2 = sdf.parse( regdate1 );
							}
							catch (Exception e) {}
							long lvalue = d1.getTime() - d2.getTime();
							int result = 0;
							if (lvalue > 0)
							{
								result = 1;
							}
							else if (lvalue < 0)
							{
								result = -1;
							}
							return result;
					  }
				 });

				JSONArray gridColums = new JSONArray();
				gridColums.add(_mapping.getTextDescription("admin.user.User Name"));
				gridColums.add(_mapping.getTextDescription("admin.user.First Name"));
				gridColums.add(_mapping.getTextDescription("admin.user.Last Name"));
				gridColums.add(_mapping.getTextDescription("admin.user.Phone Number"));
				gridColums.add(_mapping.getTextDescription("admin.user.Company"));
				gridColums.add(_mapping.getTextDescription("admin.user.Role"));
				gridColums.add(_mapping.getTextDescription("admin.user.Registration Date"));
				gridColums.add(_mapping.getTextDescription("admin.user.Expiry Date"));
				gridColums.add(_mapping.getTextDescription("admin.user.Time Zone"));
				gridColums.add(_mapping.getTextDescription("admin.user.Date Format"));
				gridColums.add(_mapping.getTextDescription("admin.user.Email"));
				gridColums.add(_mapping.getTextDescription("admin.user.To"));
				gridColums.add(_mapping.getTextDescription("admin.user.Cc"));
				gridColums.add(_mapping.getTextDescription("admin.user.Bcc"));
				rootObj.put("gridColums",gridColums);

				List csvData = new ArrayList();
				String csvRow = "";
				String colHeads = "";
				String colSubHd = "";

				if (expiry.equalsIgnoreCase("logonsimulatorusers") || expiry.equalsIgnoreCase("logonsimulatoregusers") ||
					expiry.equalsIgnoreCase("nonactiveusers") || expiry.equalsIgnoreCase("cloudusers"))
				{
					colHeads =  "User Name,First Name,Last Name,Phone Number,Company,Registration Date,Expiry Date,Time Zone";
					if (expiry.equalsIgnoreCase("cloudusers"))
					{
						if (cloudModel != null && cloudModel.equalsIgnoreCase("phoenix"))
						{
							colHeads += ",CSI Downloaded?,Agent Installed";
						}
						else
						{
							colHeads += ",Agent Downloaded?";
						}
					}
				}
				else
				{
					colHeads =  "User Name,Role,Registration Date,Expiry Date,Time Zone,Date Format,,Email,,";
					colSubHd = ",,,,,,To,Cc,Bcc,";
				}

				csvData.add("");
				csvData.add(colHeads);

				if (colSubHd != null && colSubHd.trim().length() > 0)
				{
					csvData.add(colSubHd);
				}

				JSONArray searchArr = new JSONArray();
				JSONObject searchObj = new JSONObject();
				StringTokenizer colHeadsST = new StringTokenizer(colHeads,",");
				while (colHeadsST.hasMoreTokens())
				{
					String tokens = colHeadsST.nextToken();
					if (tokens.endsWith("?"))
					{
						tokens = tokens.substring(0,tokens.length()-1);
					}
					searchObj.put("displayField",tokens);
					searchObj.put("valueField",tokens);
					searchArr.add(searchObj);
				}

				searchObj.put("displayField","User Elements");
				searchObj.put("valueField","User Elements");
				searchArr.add(searchObj);

				rootObj.put("searchArr",searchArr);

				for(int i=0;i<e_users.size();i++)
				{
					JSONObject tmpObj = new JSONObject();
					// e-users might be any one or all
					String user_date = "";
					String user_reg_date = "";
					String user_mailid = "";
					String line= (String)e_users.get(i);
					int strUserIndex = line.indexOf("|hash|");
					String user_name = line.substring(0,strUserIndex);
					String str_username = user_name;
					if (str_username.indexOf("/Grp/") != -1)
					{
						String grpDelimiter = "/Grp/";
						int idx = str_username.indexOf(grpDelimiter);
						String str_uname_A = str_username.substring(0,idx);
						int nextIdx = idx + grpDelimiter.length();
						String str_uname_B = str_username.substring(nextIdx);
						str_username = str_uname_A + "/" + str_uname_B + " (Group)";
					}
					else if (str_username.indexOf("samlsso/") != -1)
					{
						String str_uname_A = str_username;
						int idx = str_uname_A.indexOf("/");
						String str_uname_B = str_uname_A.substring(idx+1);
						str_username = str_uname_B + " (SAML)";
					}

					String otherInfo = line.substring(strUserIndex+6,line.length());
					StringTokenizer stk =  new StringTokenizer(otherInfo,"#");
					if (isSearchResult && !doesExist(searchList,str_username))
					{
						continue;
					}

					//users.add(str_username);
					searchItemFound = true;
					String user_role = stk.nextToken();
					valid = stk.nextToken();
					comment = stk.nextToken();
					exp_str = stk.nextToken();
					user_date = stk.nextToken();
					user_mailid = stk.nextToken();
					user_reg_date = (String)e_users_reg.get(user_name);
					String regdate = user_reg_date;
					if (user_reg_date != null && !user_reg_date.equalsIgnoreCase("not available"))
					{
						StringTokenizer stk1 =  new StringTokenizer(user_reg_date," ");
						String date = stk1.nextToken();
						String time = stk1.nextToken();
						String s_regdate = date;
						s_regdate = s_regdate.substring(s_regdate.indexOf('-') + 1,s_regdate.length()) + "-" + s_regdate.substring(0,s_regdate.indexOf('-'));
						String dispDate = DateUtil.changeDateFormat(s_regdate + " " +time ,"MM-dd-yyyy HH:mm:ss",currentDateFormat + " HH:mm:ss");
						com.egurkha.EgTimeZoneConverter egt1 = new com.egurkha.EgTimeZoneConverter(dispDate, _user);
						regdate = (String)egt1.getDateTime();
					}
					
					//if(user_date.equals("12/12/9999"))
					//{
						//tmpObj.put("ExpiryDate",mappingInfo.getTextDescription("admin.user.No expiry"));
						//user_date = "";
					//}

					String mailToken = null, comma = ",", tomailStr = "", ccmailStr = "", bccmailStr = "";

					if (!user_mailid.equalsIgnoreCase("not available"))
					{
						String to = "To:", cc = "cc:", bcc = "bcc:", esc = "Esc", scrpt = "cmd:";
						StringBuffer tomail = new StringBuffer();
						StringBuffer ccmail = new StringBuffer();
						StringBuffer bccmail = new StringBuffer();
						StringBuffer escmail = new StringBuffer();
						StringBuffer scrptBuff = new StringBuffer();

						int tolen = to.length();
						String escMail = "";

						StringTokenizer stoken = new StringTokenizer(user_mailid, ",");
						int count = stoken.countTokens();
						for (int c = 0; c < count; c++)
						{
							mailToken = stoken.nextToken();
							if (mailToken.startsWith(to))
							{
								tomail.append(mailToken.substring(tolen));
								tomail.append(comma);
							}
							else if (mailToken.startsWith(cc))
							{
								ccmail.append(mailToken.substring(cc.length()));
								ccmail.append(comma);
							}
							else if (mailToken.startsWith(bcc))
							{
								bccmail.append(mailToken.substring(bcc.length()));
								bccmail.append(comma);
							}
							else if (mailToken.startsWith(esc))
							{
								escmail.append(mailToken.substring(esc.length()));
								escmail.append(comma);
							}
							else if (mailToken.startsWith(scrpt))
							{
								scrptBuff.append(mailToken.substring(scrpt.length()));
								scrptBuff.append(comma);
							}
							else
							{
								tomail.append(mailToken);
								tomail.append(comma);
							}
						}
						if (count > 0)
						{
							tomailStr = tomail.toString();
							if (tomailStr.length() > 0)
							{
								tomailStr = tomailStr.substring(0, tomailStr.length() - 1);
							}
							else
							{
								tomailStr = "-";
							}
							ccmailStr = ccmail.toString();
							if (ccmailStr.length() > 0)
							{
								ccmailStr = ccmailStr.substring(0, ccmailStr.length() - 1);
							}
							else
							{
								ccmailStr = "-";
							}
							bccmailStr = bccmail.toString();
							if (bccmailStr.length() > 0)
							{
								bccmailStr = bccmailStr.substring(0, bccmailStr.length() - 1);
							}
							else
							{
								bccmailStr = "-";
							}
						}

						tmpObj.put("To",tomailStr);
						tmpObj.put("Cc",ccmailStr);
						tmpObj.put("Bcc",bccmailStr);
					}
					else
					{
						tmpObj.put("To","-");
						tmpObj.put("Cc","-");
						tmpObj.put("Bcc","-");
					}
					//tmpObj.put("Email",user_mailid);

					object = EgUserRole.getRoleObject(user_role,getAllRoles); // check if user has all access to components defined in role
					hasallcompaccess=object.hasAllComponentAccess();
					
					String tmpUser2 = user_name;
					if (str_username.equalsIgnoreCase("egenterprise"))
					{
						tmpObj.put("UserName",_mapping.getTextDescription("admin.user.egenterprise"));
					}
					else
					{
						tmpObj.put("UserName",str_username);
					}
					tmpObj.put("Action",user_name);
					tmpObj.put("Role",user_role);
					tmpObj.put("hasallcompaccess",new Boolean(hasallcompaccess));
					
					String lastlogintime = (String)auditData.get(user_name);
					if (lastlogintime != null && lastlogintime.length() > 0)
					{
						StringTokenizer stk2 =  new StringTokenizer(lastlogintime," ");
						String date1 = stk2.nextToken();
						String time1 = stk2.nextToken();
						String s_lastlogindate = date1;
						s_lastlogindate = s_lastlogindate.substring(s_lastlogindate.indexOf('-') + 1,s_lastlogindate.length()) + "-" + s_lastlogindate.substring(0,s_lastlogindate.indexOf('-'));
						String dispLoginDate = DateUtil.changeDateFormat(s_lastlogindate + " " +time1 ,"MM-dd-yyyy HH:mm:ss",currentDateFormat + " HH:mm:ss");
						com.egurkha.EgTimeZoneConverter egt2 = new com.egurkha.EgTimeZoneConverter(dispLoginDate, _user);
						
						String lastLoginDate = (String)egt2.getDateTime();
						tmpObj.put("LastLoginTime",lastLoginDate);
					}
					else
					{
						tmpObj.put("LastLoginTime","Not Available");
					}
					String agentDownload = "No";
					String agentInstalled = "No";
					String FirstName = "";
					String LastName = "";
					String PhoneNumber = "";
					String Company = "";
					if (userList.contains(str_username))
					{
						ArrayList otherDetail = new ArrayList();
						if (defaultPortal != null && defaultPortal.equalsIgnoreCase("clstrial"))
						{
							String userDetails = lsIni.getValue("LS_TRIAL_USER_DETAILS",str_username);
							ArrayList userDetail = new ArrayList(StringUtils.egTokenizer(userDetails,"$@$"));
							String otherDetails = (String)userDetail.get(1);
							otherDetail = new ArrayList(StringUtils.egTokenizer(otherDetails,"#@#"));

							tmpObj.put("AgentDownloaded","-"); 
						}
						else if (defaultPortal != null && defaultPortal.equalsIgnoreCase("cloud"))
						{
							String userDetails = lsIni.getValue("CLOUD_USER_DETAILS",str_username);
							otherDetail = new ArrayList(StringUtils.egTokenizer(userDetails,"#@#"));

							IniFile uuidIni = new IniFile(EgInstallInfo.getInstallDir() + "/manager/config/eg_uuid.ini");
							String agentDownloadStr = uuidIni.getValue("AGENT_DOWNLOAD_STATUS",str_username);
							
							if (agentDownloadStr != null && (agentDownloadStr.equalsIgnoreCase("true") || agentDownloadStr.equalsIgnoreCase("yes")))
							{
								agentDownload = "Yes";
							}
							tmpObj.put("AgentDownloaded",agentDownload); 
						}

						FirstName = (String)otherDetail.get(0);
						LastName = (String)otherDetail.get(1);
						PhoneNumber = (String)otherDetail.get(3);
						Company = (String)otherDetail.get(2);
						
						tmpObj.put("FirstName",FirstName);
						tmpObj.put("LastName",LastName);
						tmpObj.put("PhoneNumber",PhoneNumber);
						tmpObj.put("Company",Company);
					}
					else
					{
						tmpObj.put("FirstName","-");
						tmpObj.put("LastName","-");
						tmpObj.put("PhoneNumber","-");
						tmpObj.put("Company","-"); 
						tmpObj.put("AgentDownloaded","-"); 
					}
					if (blockeduserList.contains(user_name))
					{
						tmpObj.put("BlockedUser","true");
					}
					else
					{
						tmpObj.put("BlockedUser","false");
					}

					boolean isDomainUser = false;
					
					if (user_name.indexOf("/") > 0 || user_name.indexOf("\\") > 0 || User.isDefaultUser(user_name))
					{
						tmpObj.put("LocalUser","false");
					}
					else
					{
						tmpObj.put("LocalUser","true");
					}

					if (restrictChangePasswordList.contains(user_name))
					{
						tmpObj.put("ChangePassword","false");
					}
					else
					{
						tmpObj.put("ChangePassword","true");
					}
					//out.print(hasallcompaccess);
					if(hasallcompaccess)
					{
						// user can access all
						service_name="";
						segment_name="";
						server_name="";
						service_name = "all services";
						segment_name = "all segments";
						server_name ="all components";
						zone_name ="all zones";
						servicegroup_name ="all service Groups";
						vm_name="no vms";

						tmpObj.put("Zones","all zones");
						tmpObj.put("Services","all services");
						tmpObj.put("Segments","all segments");
						tmpObj.put("Components","all components");
						tmpObj.put("ComponentName","all components");
						tmpObj.put("ServiceGroups","all service Groups");
						tmpObj.put("UserVms","no vms");
					}
					else
					{
						//user access restricted
						service_name="";
						segment_name="";
						server_name="";
						zone_name="";
						vm_name="";
						servicegroup_name="";
						showVMType ="";
						vm_size	 =0;
						if(userzones.size()!=0)
						{
							for(int m=0;m<userzones.size();m++)
							{
								String all_servers = (String)userzones.get(m);
								int strIndex = all_servers.indexOf("|hash|");
								String uid = all_servers.substring(0,strIndex);
								if(uid.equals(user_name))
								{
									String thisZoneName = all_servers.substring(strIndex+6,all_servers.length());
									zone_name+=thisZoneName +",";
								}
							}
							if(!zone_name.equals(""))
							{
								zone_name = zone_name.substring(0,zone_name.lastIndexOf(","));
							}
							else
							{
								tmpObj.put("Zones","no zones");
								zone_name ="no zones";
							}
						}
						else
						{
							tmpObj.put("Zones","no zones");
							zone_name ="no zones";
						}
						//service groups
						
						if(serviceGroups!=null && serviceGroups.size()>0)
						{
							for(int j=0;j<serviceGroups.size();j++)
							{
								String all_serviceGroups =(String)serviceGroups.get(j);
								int strIndex = all_serviceGroups.indexOf("|hash|");
								String uid = all_serviceGroups.substring(0,strIndex);
								String serviceGroupsName = all_serviceGroups.substring(strIndex+6,all_serviceGroups.length());
								if(uid.equals(user_name))
								{
									servicegroup_name += serviceGroupsName +",";
								}
							}
						}
						if(!servicegroup_name.equals(""))
						{
							servicegroup_name = servicegroup_name.substring(0,servicegroup_name.lastIndexOf(","));
						}
						else
						{
							tmpObj.put("ServiceGroups","no service groups");
							servicegroup_name = "no service groups";
						}
						
						//add services, segments, ind servers from zones - ends
						if(services.size()!=0)
						{//get services if present
							Iterator serI = services.iterator();
							while (serI.hasNext())
							{
								String all_services = (String) serI.next();
								int strIndex = all_services.indexOf("|hash|");
								String uid = all_services.substring(0,strIndex);
								String serviceName = all_services.substring(strIndex+6,all_services.length());
								if(uid.equals(user_name) && serviceName != null && serviceName.length()>0)
								{
									service_name += serviceName +",";
								}
							}
							if(!service_name.equals(""))
							{
								service_name = service_name.substring(0,service_name.lastIndexOf(","));
							}
							else
							{
								tmpObj.put("Services","no services");
								service_name = "no services";
							}
						}
						else
						{
							tmpObj.put("Services","no services");
							service_name = "no services";
						}

						if(segments.size()!=0)
						{//get segments if present
							Iterator segI = segments.iterator();
							while (segI.hasNext())
							{
								String all_segments = (String) segI.next();
								int strIndex = all_segments.indexOf("|hash|");
								String uid = all_segments.substring(0,strIndex);
								String segmentName = all_segments.substring(strIndex+6,all_segments.length());
								if(uid.equals(user_name) && segmentName != null && segmentName.length()>0)
								{
									segment_name += segmentName +",";
								}
							}
							if(!segment_name.equals(""))
							{
								segment_name = segment_name.substring(0,segment_name.lastIndexOf(","));
							}
							else
							{
								tmpObj.put("Segments","no segments");
								segment_name = "no segments";
							}
						}
						else
						{
							tmpObj.put("Segments","no segments");
							segment_name = "no segments";
						}


						if(userservers.size()!=0)
						{//get components if present
							Iterator userserI = userservers.iterator();
							while (userserI.hasNext())
							{
								String all_servers = (String) userserI.next();
								int strServerIndex = all_servers.indexOf("|hash|");
								String uid = all_servers.substring(0,strServerIndex);
								String serverName = all_servers.substring(strServerIndex+6,all_servers.length());
								StringTokenizer stk3 = new StringTokenizer(serverName,"#");
								if(uid.equals(user_name) && stk3.hasMoreTokens())
								{
									server_name+=stk3.nextToken() + "("+ stk3.nextToken()+")"+",";
								}
							}
							if(!server_name.equals(""))
							{
								server_name = server_name.substring(0,server_name.lastIndexOf(","));
							}
							else
							{
								tmpObj.put("Components","no components");
								tmpObj.put("ComponentName","no components");
								server_name = "no components";
							}
						}
						else
						{
							tmpObj.put("Components","no components");
							tmpObj.put("ComponentName","no components");
							server_name = "no components";
						}
					}

					String tmpUserDate = user_date;

					if(DateUtil.isDate(user_date,"MM/dd/yyyy"))
					{
						user_date = DateUtil.changeDateFormat(user_date,"MM/dd/yyyy",currentDateFormat);
					}

					if (user_name != null && !user_name.equalsIgnoreCase("null") && !user_name.equals("-1"))
					{
						
						//timezone_query ="SELECT timezone FROM user_pref where user_id='" + user_name + "'";
						//ResultSet resSet = egDb.dbselect(timezone_query);
						//if (resSet.next())
						//{
						//	timezone = resSet.getString("timezone");
						//}
						timezone = (String) e_users_tz.get(user_name);
					}

					if (timezone == null)
					{
						timezone = "-";
					}

					/* Added by Prakash.K starts */

					String dateFormat = "MMM dd, yyyy";
					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);
						}
					}

					String usrDateCt = "";

					if(!tmpUserDate.equals("") && tmpUserDate.length() > 0 && dateFormat.length() > 0)
					{
						usrDateCt = DateUtil.changeDateFormat(tmpUserDate,"MM/dd/yyyy", dateFormat);
						tmpObj.put("ExpiryDate",usrDateCt);
					}

					tmpObj.put("RegistrationDate",regdate);
					
					TimeZone tz =TimeZone.getDefault();
					TimeZoneUtil tzu = new TimeZoneUtil();
					if(timezone.equalsIgnoreCase("default"))
					{
						String[] timeZoneIDs = tz.getAvailableIDs();
						for(int z=0;z<timeZoneIDs.length;z++)
						{
							if(timeZoneIDs[z].equals(tzu.getID()))
							{
								timezone = timeZoneIDs[z];
								break;
							}
						}
					}

					String timeZoneStr = "";
					if (timezone.equals("-"))
					{
						timeZoneStr = timezone;
					}
					else
					{
						timeZoneStr = tzu.getTimeZoneOffset(TimeZone.getTimeZone(timezone))+" "+timezone.replace('_',' ');
					}

					tmpObj.put("DateFormat",dateFormat);
					tmpObj.put("TimeZone",timeZoneStr);

					String userExpiry = usrDateCt;
					if (userExpiry != null && userExpiry.equalsIgnoreCase("Dec 12, 9999"))
					{
						userExpiry = "No expiry";
					}
					String toMailId = tomailStr;
					String ccMailId = ccmailStr;
					String bccMailId = bccmailStr;
					if (toMailId == null || toMailId.trim().length() == 0)
					{
						toMailId = "-";
					}
					if (ccMailId == null || ccMailId.trim().length() == 0)
					{
						ccMailId = "-";
					}
					if (bccMailId == null || bccMailId.trim().length() == 0)
					{
						bccMailId = "-";
					}

					if(!zone_name.equalsIgnoreCase("no zones") && !zone_name.equalsIgnoreCase("all zones"))
					{
						StringTokenizer stz=new StringTokenizer(zone_name,",");
						while(stz.hasMoreTokens())
						{
							if (str_username.equalsIgnoreCase(stz.nextToken()))
							{
								agentInstalled = "Yes";
								break;
							}
						}
					}
					tmpObj.put("AgentInstalled",agentInstalled);

					if (expiry.equalsIgnoreCase("logonsimulatorusers") || expiry.equalsIgnoreCase("logonsimulatoregusers") ||
					expiry.equalsIgnoreCase("nonactiveusers") || expiry.equalsIgnoreCase("cloudusers"))
					{
						csvRow = str_username+","+FirstName+","+LastName+","+PhoneNumber+","+Company+","+StringUtils.replace(regdate,","," ")+","+StringUtils.replace(userExpiry,","," ")+","+StringUtils.replace(timeZoneStr,","," ");

						if (expiry.equalsIgnoreCase("cloudusers"))
						{
							csvRow += ","+agentDownload;
							if (cloudModel != null && cloudModel.equalsIgnoreCase("phoenix"))
							{
								csvRow += ","+agentInstalled;
							}
						}
					}
					else
					{
						csvRow = str_username+","+user_role+","+StringUtils.replace(regdate,","," ")+","+StringUtils.replace(userExpiry,","," ")+","+StringUtils.replace(timeZoneStr,","," ")+","+StringUtils.replace(dateFormat,","," ")+","+StringUtils.replace(toMailId,","," ")+","+StringUtils.replace(ccMailId,","," ")+","+StringUtils.replace(bccMailId,","," ");
					}

					csvData.add(csvRow);

					String userDate = "";
					if(user_date != null && user_date.length() > 0 && !user_date.equalsIgnoreCase("null"))
					{
						com.egurkha.EgTimeZoneConverter egt = new com.egurkha.EgTimeZoneConverter(user_date+" "+"23:59:59", _user);
						userDate = (String) egt.getDate(false);
					}
					String tempUserName = "";
					//if (user_name.indexOf("(Group)") != -1)
					//{
					//	int idx = user_name.indexOf("/");
					//	int nextIdx = user_name.indexOf("(Group)");
					//	String strtempuname = user_name.substring(0,idx);
					//	strtempuname = strtempuname + "/Grp/";
					//	String strtempuname_A = user_name.substring(idx + 1 ,nextIdx);
					//	tempUserName = strtempuname + strtempuname_A;
					//	tempUserName = tempUserName.trim();
					//}
					//else
					//{
						tempUserName = user_name;
					//}
					egurkha.UserInfoBean userinfo = new egurkha.UserInfoBean();
					userinfo.setusername(tempUserName);

					
					//user vms
					if(!hasallcompaccess)
					{
						userVMs = new ArrayList();
						//String [] userVMsAry = com.egurkha.util.StringUtils.getTokens(userinfo.getUserVMs(""),",");
					
						//if(userVMsAry!=null)
						//{
						//	userVMs.addAll(Arrays.asList(userVMsAry));
						//}

						userVMs = (ArrayList) e_users_vm.get(tempUserName);

						//if(userVMs.size() >0)
						//{
						//	Collections.sort(userVMs,String.CASE_INSENSITIVE_ORDER);
						//}
						
						if(userVMs!=null)
						{
							Collections.sort(userVMs,String.CASE_INSENSITIVE_ORDER);
							showVMType = _mapping.getComponentTypeDescription("VM");
							vm_size = userVMs.size();
							if(vm_size > 0)
							{
								for(int y=0; y<vm_size; y++)
								{
									String vm=(String)userVMs.get(y);
									vm_name +=vm + " (" + showVMType + ")"+",";
								}
								if(!vm_name.equals(""))
								{
									vm_name = vm_name.substring(0,vm_name.lastIndexOf(","));
								}
								else
								{
									tmpObj.put("UserVms","no vms");
									vm_name = "no vms";
								}
							}
							else
							{
								tmpObj.put("UserVms","no vms");
								vm_name = "no vms";
							}
						}
						else
						{
							tmpObj.put("UserVms","no vms");
							vm_name = "no vms";
						}
					}
					String dispUser = tempUserName;
					String temp_Usr = egUI.getValue("DBUSER_USER_MAP",tempUserName);
					if (temp_Usr != null && temp_Usr.length() > 0)
					{
						dispUser = temp_Usr;
					}
					if (dispUser.indexOf("/Grp/") != -1)
					{
						String grpDelimiter = "/Grp/";
						int idx = dispUser.indexOf(grpDelimiter);
						String str_uname_A = dispUser.substring(0,idx);
						int nextIdx = idx + grpDelimiter.length();
						String str_uname_B = dispUser.substring(nextIdx);
						dispUser = str_uname_A + "/" + str_uname_B + " (Group)";
					}
					else if (dispUser.indexOf("samlsso/") != -1)
					{
						String str_uname_A = dispUser;
						int idx = str_uname_A.indexOf("/");
						String str_uname_B = str_uname_A.substring(idx+1);
						dispUser = str_uname_B + " (SAML)";
					}

					
					dispUser = StringUtils.replace(dispUser,"<","&lt;");
					dispUser = StringUtils.replace(dispUser,">","&gt;");
					if (dispUser.length() > 90)
					{
						dispUser = dispUser.substring(0,87)+"...";
					}


					if(!zone_name.equalsIgnoreCase("no zones"))
					{
						if(zone_name.equalsIgnoreCase("all zones"))
						{
							tmpObj.put("Zones",zone_name);
						}
						else
						{
							StringTokenizer stz=new StringTokenizer(zone_name,",");
							Vector veczone=new Vector();
							while(stz.hasMoreTokens())
							{
									veczone.add(stz.nextToken());
							}

							JSONArray zonesArr = new JSONArray();
							for(int j=0;j<veczone.size();j++)
							{
								if(j+1==veczone.size())
								{
									zonesArr.add("&nbsp;&nbsp;<a class=\"eg_monlink\" href= 'EgComponentZones.jsp?comefrom=userpage&qctr=0&mode=modify&zone="+EgURLEncoder.encode((String)veczone.get(j),"UTF-8")+"' style=\"text-decoration:none\">"+(String)veczone.get(j)+"</a>");
								}
								else
								{
									zonesArr.add("&nbsp;&nbsp;<a class=\"eg_monlink\" href= 'EgComponentZones.jsp?comefrom=userpage&qctr=0&mode=modify&zone="+EgURLEncoder.encode((String)veczone.get(j),"UTF-8")+"' style=\"text-decoration:none\">"+(String)veczone.get(j)+"</a>");
								}
							}
							tmpObj.put("Zones",zonesArr);
						}
					}

					if(!servicegroup_name.equalsIgnoreCase("no service Groups"))
					{
						if(servicegroup_name.equalsIgnoreCase("all service Groups"))
						{
							tmpObj.put("ServiceGroups",servicegroup_name);
						}
						else
						{
							StringTokenizer stz=new StringTokenizer(servicegroup_name,",");
							Vector sergroup = new Vector();
							while(stz.hasMoreTokens())
							{
								sergroup.add(stz.nextToken());
							}
							JSONArray srvGroupArr = new JSONArray();
							for(int j=0;j<sergroup.size();j++)
							{
								if(j+1==sergroup.size())
								{
									srvGroupArr.add("&nbsp;&nbsp;<a class=\"eg_monlink\" href= 'EgComponentServiceGroup.jsp?returnToMain=userpage&modify=true&site="+EgURLEncoder.encode((String)sergroup.get(j),"UTF-8")+"' style=\"text-decoration:none\">"+(String)sergroup.get(j)+"</a>");
								}
								else
								{
									srvGroupArr.add("&nbsp;&nbsp;<a class=\"eg_monlink\" href= 'EgComponentServiceGroup.jsp?returnToMain=userpage&modify=true&site="+EgURLEncoder.encode((String)sergroup.get(j),"UTF-8")+"' style=\"text-decoration:none\">"+(String)sergroup.get(j)+"</a>");
								}
							}
							tmpObj.put("ServiceGroups",srvGroupArr);
						}
					}

					
					if(!service_name.equalsIgnoreCase("no services"))
					{
						if(servicegroup_name.equalsIgnoreCase("all services"))
						{
							tmpObj.put("Services",service_name);
						}
						else
						{
							StringTokenizer sts=new StringTokenizer(service_name,",");
							Vector vecservice=new Vector();
							while(sts.hasMoreTokens())
							{
								vecservice.add(sts.nextToken());
							}
							JSONArray srvArr = new JSONArray();
							for(int j=0;j<vecservice.size();j++)
							{
								String service=(String)vecservice.get(j);
								if(service.equalsIgnoreCase("all services"))
								{
									service=service;
								}
								else
								{
									service=(String)vecservice.get(j);
								}

								if(j+1==vecservice.size())
								{
									srvArr.add("&nbsp;&nbsp;<a class=\"eg_monlink\" href= 'EgComponentServices.jsp?comefrom=userpage&modify=true&site="+EgURLEncoder.encode((String)vecservice.get(j),"UTF-8")+"' style=\"text-decoration:none\">"+(String)vecservice.get(j)+"</a>");
								}
								else
								{
									srvArr.add("&nbsp;&nbsp;<a class=\"eg_monlink\" href= 'EgComponentServices.jsp?comefrom=userpage&modify=true&site="+EgURLEncoder.encode((String)vecservice.get(j),"UTF-8")+"' style=\"text-decoration:none\">"+(String)vecservice.get(j)+"</a>");
								}
							}
							tmpObj.put("Services",srvArr);
						}
					}

					
					if(!segment_name.equalsIgnoreCase("no segments"))
					{
						if(servicegroup_name.equalsIgnoreCase("all segments"))
						{
							tmpObj.put("Segments",segment_name);
						}
						else
						{
							JSONArray tmpSegments = new JSONArray();
							StringTokenizer stsg=new StringTokenizer(segment_name,",");
							Vector vecsegment=new Vector();
							while(stsg.hasMoreTokens())
							{
								vecsegment.add(stsg.nextToken());
							}
							for(int j=0;j<vecsegment.size();j++)
							{
								if(j+1==vecsegment.size())
								{
									tmpSegments.add("&nbsp;&nbsp;<a class=\"eg_monlink\" href= 'EgComponentSegments.jsp?returnTo=userpage&qctr=0&segment="+EgURLEncoder.encode((String)vecsegment.get(j),"UTF-8")+"' style=\"text-decoration:none\">"+(String)vecsegment.get(j)+"</a>");
								}
								else
								{
									tmpSegments.add("&nbsp;&nbsp;<a class=\"eg_monlink\" href= 'EgComponentSegments.jsp?returnTo=userpage&qctr=0&segment="+EgURLEncoder.encode((String)vecsegment.get(j),"UTF-8")+"' style=\"text-decoration:none\">"+(String)vecsegment.get(j)+"</a>");
								}
							}
							tmpObj.put("Segments",tmpSegments);
						}
					}

					userComptypes = userinfo.getserverTypeDB();
					if(!server_name.equalsIgnoreCase("no components"))
					{
						if(server_name.equalsIgnoreCase("all components"))
						{
							tmpObj.put("Components",server_name);
							tmpObj.put("ComponentName",server_name);
						}
						else
						{
							JSONArray tmpComponents = new JSONArray();
							JSONArray tmpComponents1 = new JSONArray();
							JSONArray tmpComponents2 = new JSONArray();
							JSONArray tmpComponentsName = new JSONArray();

							StringTokenizer stc=new StringTokenizer(server_name,",");
							Vector veccomponent=new Vector();
							while(stc.hasMoreTokens())
							{
								veccomponent.add(stc.nextToken());
							}

							for(int j=0;j<veccomponent.size();j++)
							{
								String component=(String)veccomponent.get(j);
								String type=component.substring((component.indexOf('('))+1,component.lastIndexOf(')'));
								component=component.substring(0,component.indexOf('('));
								String act_comp = type + ":" + component;
								component=com.egurkha.util.StringUtils.replace(component, ":NULL", "");
								if(j+1==veccomponent.size())
								{
									if(type.startsWith("Agg_"))
									{
										tmpComponents.add("&nbsp;&nbsp;<a class=\"eg_monlink\" href= 'EgAggregateTree.jsp?qctr=1&server="+EgURLEncoder.encode(act_comp,"UTF-8")+"&reqfrom=userpage&isAggregateLink=true' style=\"text-decoration:none\">"+component+" ("+_mapping.getComponentTypeDescription(type)+")</a>");
										tmpComponents1.add(_mapping.getComponentTypeDescription(type));
										tmpComponentsName.add(component);
									}
									else
									{
										tmpComponents.add("&nbsp;&nbsp;<a class=\"eg_monlink\" href= 'EgDispServer.jsp?qctr=1&reqfrom=userpage&comptype="+EgURLEncoder.encode(type,"UTF-8")+"' style=\"text-decoration:none\">"+component+" ("+_mapping.getComponentTypeDescription(type)+")</a>");
										tmpComponents1.add(_mapping.getComponentTypeDescription(type));
										tmpComponentsName.add(component);
									}
								}
								else
								{
									if(type.startsWith("Agg_"))
									{
										tmpComponents.add("&nbsp;&nbsp;<a class=\"eg_monlink\" href= 'EgAggregateTree.jsp?qctr=1&server="+EgURLEncoder.encode(act_comp,"UTF-8")+"&reqfrom=userpage&isAggregateLink=true' style=\"text-decoration:none\">"+component+" ("+_mapping.getComponentTypeDescription(type)+")</a>");
										tmpComponents1.add(_mapping.getComponentTypeDescription(type));
										tmpComponentsName.add(component);
									}
									else
									{
										tmpComponents.add("&nbsp;&nbsp;<a class=\"eg_monlink\" href= 'EgDispServer.jsp?qctr=1&reqfrom=userpage&comptype="+EgURLEncoder.encode(type,"UTF-8")+"' style=\"text-decoration:none\">"+component+" ("+_mapping.getComponentTypeDescription(type)+")</a>");
										tmpComponents1.add(_mapping.getComponentTypeDescription(type));
										tmpComponentsName.add(component);
									}
								}
								tmpComponents2.add(act_comp);
							}
							tmpObj.put("ComponentsType",tmpComponents1);
							tmpObj.put("Components",tmpComponents);
							tmpObj.put("ComponentName",tmpComponentsName);
							tmpObj.put("ServersForDeletion",tmpComponents2);
						}
					}

					if(!vm_name.equalsIgnoreCase("no vms"))
					{
						JSONArray tmpVMS = new JSONArray();
						String egText = "admin.service.Virtual Machines";
						StringTokenizer stc=new StringTokenizer(vm_name,",");
						Vector vecVM=new Vector();
						while(stc.hasMoreTokens())
						{
								vecVM.add(stc.nextToken());
						}

						for(int j=0;j<vecVM.size();j++)
						{
							String vm=(String)vecVM.get(j);
							String type=vm.substring((vm.indexOf('('))+1,vm.lastIndexOf(')'));
							vm=vm.substring(0,vm.indexOf('('));
							if(j+1==vecVM.size())
							{
								tmpVMS.add("&nbsp;&nbsp;"+vm + " (" + type + ")");
							}
							else
							{
								tmpVMS.add( "&nbsp;&nbsp;"+vm + " (" + type + ")");
							}
						}
						//tmpObj.put("vms",tmpVMS);
						tmpObj.put("UserVms",tmpVMS);
					}
					else
					{
						tmpObj.put("UserVms","no vms");
					}

					tmpObj.put("hasAutoAsscociatedComponents",new Boolean(false));
					if(!server_name.equalsIgnoreCase("all components") && userComptypes.length() >0 )
					{
						tmpObj.put("hasAutoAsscociatedComponents",new Boolean(true));
						JSONArray tmpComp = new JSONArray();
						List userAssociateCompList = java.util.Arrays.asList(StringUtils.getTokens(userComptypes,","));
						ArrayList userAssoComp = sorter.getSortedCompTypeList(userAssociateCompList);
						int len = userAssoComp.size();
						boolean autoVMExists = false;
						for(int k=0;k<len;k++)
						{
							EgName nameObj = (EgName)userAssoComp.get(k);
							String tmpVal = nameObj.getActualName();
							String tmpDis = nameObj.getLocalName();
							String actualCompName = (String)userAssociateCompList.get(k);
							String localCompName = mappingInfo.getComponentTypeDescription(actualCompName);
							autoVMExists = false;
							String vmLinkType = "";
							if(tmpVal!=null && tmpVal.indexOf(":") > 0)
							{
								autoVMExists = true;
								vmLinkType = tmpVal.substring(0, tmpVal.indexOf(":"));
							}
							if(k+1==len)
							{
								if(tmpVal.startsWith("Agg_"))
								{
									tmpComp.add("&nbsp;&nbsp;<a class=\"eg_monlink\" href= 'EgAggregateTree.jsp?qctr=1&comptype="+EgURLEncoder.encode(tmpVal,"UTF-8")+"&reqfrom=userpage&isAggregateLink=true' style=\"text-decoration:none\">"+tmpDis+"</a>");
								}
								else
								{
									tmpComp.add("&nbsp;&nbsp;<a class=\"eg_monlink\" href= 'EgDispServer.jsp?qctr=1&reqfrom=userpage&comptype="+EgURLEncoder.encode(tmpVal,"UTF-8")+"' style=\"text-decoration:none\">"+tmpDis+"</a>");
								}
							}
							else
							{
								if(tmpVal.startsWith("Agg_"))
								{
									tmpComp.add("&nbsp;&nbsp;<a class=\"eg_monlink\" href= 'EgAggregateTree.jsp?qctr=1&comptype="+EgURLEncoder.encode(tmpVal,"UTF-8")+"&reqfrom=userpage&isAggregateLink=true' style=\"text-decoration:none\">"+tmpDis+"</a>&nbsp;");
								}
								else
								{
									tmpComp.add("&nbsp;&nbsp;<a class=\"eg_monlink\" href= 'EgDispServer.jsp?qctr=1&reqfrom=userpage&comptype="+EgURLEncoder.encode(tmpVal,"UTF-8")+"' style=\"text-decoration:none\">"+tmpDis+"</a>");
								}
							}
						}
						tmpObj.put("Auto",tmpComp);
					}

					tmpObj.put("isElementsAssociated",new Boolean(true));
					if(userComptypes.length() <= 0)
					{
						if(zone_name.equalsIgnoreCase("no zones") && servicegroup_name.equalsIgnoreCase("no service Groups") && service_name.equalsIgnoreCase("no services") && segment_name.equalsIgnoreCase("no segments") && server_name.equalsIgnoreCase("no components") && vm_name.equalsIgnoreCase("no vms"))
						{
							tmpObj.put("isElementsAssociated",new Boolean(false));
						}
					}
					userDetailsGrid.add(tmpObj);
				}
				session.setAttribute("list",csvData);
				session.setAttribute("isAuditlogCSV","true");
			}
			rootObj.put("UserInfo",userDetailsGrid);
			egDb.releaseConnection(false);
		//}
	}
	catch(Exception e)
	{
		e.printStackTrace();
	}
	EgDbAdapterTypeUI.releaseObject(egDb);
	rootObj.put("screenLabels",intnlLabels);
	if(request.getQueryString()!= null)
	{
		session.setAttribute("adminLastAccessedURL","/final/admin/EgDispUserSites.jsp?"+request.getQueryString());
	}
	else
	{
		session.setAttribute("adminLastAccessedURL","/final/admin/EgDispUserSites.jsp?expiry=all");
	}
	out.println(rootObj.toString());
}
catch(Exception e)
{
	e.printStackTrace();
}

%>




