--- /dev/null
+package com.pentila.entSavoie.utils;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.LinkedHashMap;
+import java.util.List;
+
+import javax.portlet.RenderRequest;
+import javax.portlet.ResourceRequest;
+
+import com.liferay.contacts.util.ListFicheFactory;
+import com.liferay.contacts.util.ProxyFiche;
+import com.liferay.portal.kernel.dao.orm.QueryUtil;
+import com.liferay.portal.kernel.exception.SystemException;
+import com.liferay.portal.kernel.json.JSONArray;
+import com.liferay.portal.kernel.json.JSONFactoryUtil;
+import com.liferay.portal.kernel.json.JSONObject;
+import com.liferay.portal.kernel.log.Log;
+import com.liferay.portal.kernel.log.LogFactoryUtil;
+import com.liferay.portal.kernel.util.OrderByComparator;
+import com.liferay.portal.kernel.util.ParamUtil;
+import com.liferay.portal.kernel.workflow.WorkflowConstants;
+import com.liferay.portal.model.Organization;
+import com.liferay.portal.model.Role;
+import com.liferay.portal.model.User;
+import com.liferay.portal.service.ExtUserLocalServiceUtil;
+import com.liferay.portal.service.RoleLocalServiceUtil;
+import com.liferay.portal.service.UserLocalServiceUtil;
+import com.liferay.portal.util.comparator.UserFirstNameComparator;
+import com.liferay.portal.util.comparator.UserLastNameComparator;
+import com.liferay.portal.util.comparator.UserScreenNameComparator;
+import com.pentila.entSavoie.ENTRoleUtilFactory;
+import com.pentila.entSavoie.ENTRolesConstants;
+import com.pentila.entSavoie.amis.model.Relationship;
+import com.pentila.entSavoie.amis.service.RelationshipLocalServiceUtil;
+import com.pentila.entSavoie.carnetDAdresses.CANameComparator;
+import com.pentila.entSavoie.carnetDAdresses.CAStatusComparator;
+import com.pentila.entSavoie.carnetDAdresses.CAfirstNameComparator;
+import com.pentila.entSavoie.carnetDAdresses.model.Liste;
+import com.pentila.entSavoie.carnetDAdresses.service.ListeLocalServiceUtil;
+import com.pentila.entSavoie.directory.OrganizationFinderServiceUtil;
+import com.pentila.entSavoie.userProperties.model.UserProperties;
+import com.pentila.entSavoie.userProperties.model.UserRelationship;
+import com.pentila.entSavoie.userProperties.service.UserPropertiesLocalServiceUtil;
+import com.pentila.entSavoie.userProperties.service.UserRelationshipLocalServiceUtil;
+import com.pentila.entSavoie.userRelationship.UserRelationshipConstants;
+
+import edu.emory.mathcs.backport.java.util.Arrays;
+
+public class ENTUserListUtil {
+
+ private static Log logger = LogFactoryUtil.getLog(ENTUserListUtil.class);
+ private final static int COMPARE_ON_USER = 0;
+ private final static int COMPARE_ON_PROXYLIST = 1;
+
+ /**
+ * Return a JSONObject that contains a users list which is the result of the search
+ * @param renderRequest The request containing all the parameters
+ * @param user The user currently searching
+ * @return a JSONObject with all the search results
+ */
+ public static JSONObject getUserListFromSearch(RenderRequest renderRequest, User user) {
+ return getUserListFromSearch(renderRequest, user, JsonUserProxyFactory.SIMPLE_USER_SEARCH, "");
+ }
+
+ /**
+ * Return a JSONObject that contains a users list which is the result of the search
+ * @param renderRequest The request containing all the parameters
+ * @param user The user currently searching
+ * @return a JSONObject with all the search results
+ */
+ public static JSONObject getUserListFromSearch(ResourceRequest resourceRequest, User user) {
+ return getUserListFromSearch(resourceRequest, user, JsonUserProxyFactory.SIMPLE_USER_SEARCH, "");
+ }
+
+ /**
+ * Return a JSONObject that contains a users list which is the result of the search
+ * @param renderRequest The request containing all the parameters
+ * @param user The user currently searching
+ * @param typeSearch
+ * @param themeImagesUrl
+ * @return a JSONObject with all the search results
+ */
+ public static JSONObject getUserListFromSearch(RenderRequest renderRequest, User user, String typeSearch, String themeImagesUrl) {
+ JSONObject ret = JSONFactoryUtil.createJSONObject();
+
+ final int start = ParamUtil.getInteger(renderRequest, "start", 0);
+ final int limit = ParamUtil.getInteger(renderRequest, "limit", 0);
+ final int stop = start+limit;
+
+ //Get the request parameters
+ String firstName = renderRequest.getParameter("firstName");
+ if (firstName != null) {
+ firstName = firstName.trim();
+ firstName = firstName.toLowerCase();
+ }
+
+ String lastName = renderRequest.getParameter("lastName");
+ if (lastName != null) {
+ lastName = lastName.trim();
+ lastName = lastName.toLowerCase();
+ }
+ final String middleName = null;
+ final String screenName = null;
+ final String email = null;
+
+ LinkedHashMap<String, Object> userParams = buildUserParams(renderRequest, user);
+
+ OrderByComparator obc = buildComparator(renderRequest, COMPARE_ON_USER);
+
+ List<User> usersList = new ArrayList<User>();
+ try {
+ usersList = ExtUserLocalServiceUtil.search(
+ user.getCompanyId(),
+ firstName,
+ middleName,
+ lastName,
+ screenName,
+ email,
+ WorkflowConstants.STATUS_APPROVED,
+ userParams,
+ true,
+ start,
+ stop,
+ obc);
+ } catch (SystemException e) {
+ logger.error(e);
+ }
+
+ usersList = userListFilter(usersList);
+
+ long nbTotalResults = 0;
+ try {
+ nbTotalResults = ExtUserLocalServiceUtil.searchCount(
+ user.getCompanyId(),
+ firstName,
+ middleName,
+ lastName,
+ screenName,
+ email,
+ WorkflowConstants.STATUS_APPROVED,
+ userParams,
+ true);
+ } catch (SystemException e) {
+ logger.error(e);
+ }
+
+ ret.put("users", (new JsonUserProxyFactory()).format(user, usersList, typeSearch, themeImagesUrl));
+ ret.put("nombreTotal", nbTotalResults);
+
+ return ret;
+ }
+
+ /**
+ * Return a JSONObject that contains a users list which is the result of the search
+ * @param renderRequest The request containing all the parameters
+ * @param user The user currently searching
+ * @param typeSearch
+ * @param themeImagesUrl
+ * @return a JSONObject with all the search results
+ */
+ public static JSONObject getUserListFromSearch(ResourceRequest resourceRequest, User user, String typeSearch, String themeImagesUrl) {
+ JSONObject ret = JSONFactoryUtil.createJSONObject();
+
+ final int start = ParamUtil.getInteger(resourceRequest, "start", QueryUtil.ALL_POS);
+ final int limit = ParamUtil.getInteger(resourceRequest, "limit", 0);
+ final int stop = start+limit;
+
+ // Get the request parameters
+ String name = ParamUtil.getString(resourceRequest, "name", "");
+ String firstName = null;
+ String lastName = null;
+ if (!name.equals("")) {
+ firstName = name.trim();
+ firstName = name.toLowerCase();
+ lastName = name.trim();
+ lastName = name.toLowerCase();
+ }
+
+ final String middleName = null;
+ final String screenName = null;
+ final String email = null;
+
+ LinkedHashMap<String, Object> userParams = buildUserParams(resourceRequest, user);
+
+ OrderByComparator obc = buildComparator(resourceRequest, COMPARE_ON_USER);
+
+ List<User> usersList = new ArrayList<User>();
+ try {
+ usersList = ExtUserLocalServiceUtil.search(
+ user.getCompanyId(),
+ firstName,
+ middleName,
+ lastName,
+ screenName,
+ email,
+ WorkflowConstants.STATUS_APPROVED,
+ userParams,
+ false,
+ start,
+ stop,
+ obc);
+ } catch (SystemException e) {
+ logger.error(e);
+ }
+
+ String scholarship = ParamUtil.getString(resourceRequest, "scholarship", "");
+ int grant = ParamUtil.getInteger(resourceRequest, "grant", -1);
+ int transport = ParamUtil.getInteger(resourceRequest, "transport", -1);
+
+ // Filter over scholarship and grant
+ if (!scholarship.equals("") || grant > -1 || transport > -1) {
+ List<UserProperties> userPropertiesList = UserPropertiesLocalServiceUtil.filterScholarshipAndGrant(usersList, scholarship, grant, transport);
+ List<User> filteredList = new ArrayList<User>();
+ for (User resultUser : usersList) {
+ for (UserProperties userProperties : userPropertiesList) {
+ if (resultUser.getUserId() == userProperties.getUserId()) {
+ filteredList.add(resultUser);
+ }
+ }
+ }
+ usersList = filteredList;
+ }
+
+ usersList = userListFilter(usersList);
+
+ long nbTotalResults = 0;
+ try {
+ nbTotalResults = ExtUserLocalServiceUtil.searchCount(
+ user.getCompanyId(),
+ firstName,
+ middleName,
+ lastName,
+ screenName,
+ email,
+ WorkflowConstants.STATUS_APPROVED,
+ userParams,
+ true);
+ } catch (SystemException e) {
+ logger.error(e);
+ }
+
+ ret.put("users", (new JsonUserProxyFactory()).format(user, usersList, typeSearch, themeImagesUrl));
+ ret.put("nombreTotal", nbTotalResults);
+
+ return ret;
+ }
+
+ public static JSONObject getContactsFromSearch(ResourceRequest resourceRequest, User user) {
+ JSONObject result = JSONFactoryUtil.createJSONObject();
+
+ final int start = ParamUtil.getInteger(resourceRequest, "start", QueryUtil.ALL_POS);
+
+ JSONArray jsonContactList = JSONFactoryUtil.createJSONArray();
+
+ // Get the request parameters
+ Boolean myChildren = ParamUtil.getBoolean(resourceRequest, "myChildren", false);
+ Boolean myParents = ParamUtil.getBoolean(resourceRequest, "myParents", false);
+ if (myChildren) {
+ logger.info("Fetch myChildren list elements");
+ try {
+ List<UserRelationship> parentRelationships = UserRelationshipLocalServiceUtil.getUserRelationshipByFromUserIdRelationType(user.getUserId(), UserRelationshipConstants.PARENT_RELATION);
+ for (UserRelationship parentRelationship : parentRelationships) {
+ jsonContactList.put(JsonUserFactory.convertUserToJson(UserLocalServiceUtil.getUser(parentRelationship.getToUserId())));
+ }
+ result.put("nbResults", jsonContactList.length());
+ } catch (Exception e) {
+ logger.error("Error when fetching user "+user.getFullName()+" children", e);
+ }
+ }
+ else if (myParents) {
+ logger.info("Fetch myParents list elements");
+ try {
+ List<UserRelationship> parentRelationships = UserRelationshipLocalServiceUtil.getUserRelationshipByToUserIdRelationType(user.getUserId(), UserRelationshipConstants.PARENT_RELATION);
+ for (UserRelationship parentRelationship : parentRelationships) {
+ jsonContactList.put(JsonUserFactory.convertUserToJson(UserLocalServiceUtil.getUser(parentRelationship.getFromUserId())));
+ }
+ result.put("nbResults", jsonContactList.length());
+ } catch (Exception e) {
+ logger.error("Error when fetching user "+user.getFullName()+" parents", e);
+ }
+
+ } else {
+ String name = ParamUtil.getString(resourceRequest, "name", "");
+
+ Long[] usersOrgs = getUsersOrgs(resourceRequest, user);
+ List<Long> orgIds = null;
+ if (usersOrgs != null) {
+ orgIds = Arrays.asList(usersOrgs);
+ }
+
+ Long[] usersRoles = getUsersRoles(resourceRequest, user);
+ List<Long> roleIds = null;
+ if (usersRoles != null) {
+ roleIds = Arrays.asList(usersRoles);
+ }
+
+ String scholarship = ParamUtil.getString(resourceRequest, "scholarship", "");
+
+ List<String> scholarshipLabels = getScholarshipLabels(scholarship);
+
+ // -1 -> no filter
+ // 0 -> value is false
+ // 1 -> value is true
+ int grant = ParamUtil.getInteger(resourceRequest, "grant", -1);
+ int transport = ParamUtil.getInteger(resourceRequest, "transport", -1);
+
+ List<User> contacts = getUserListFromContactSearch(resourceRequest, name, orgIds, roleIds, scholarshipLabels, grant, transport);
+
+ // convert result to JSON
+ long timer = System.currentTimeMillis();
+ for (User u : contacts) {
+ jsonContactList.put(JsonUserFactory.convertUserToJson(u));
+ }
+ System.out.println("convert to json took "+(System.currentTimeMillis() - timer)+" ms");
+
+ if (start == 0) {
+ try {
+ Long nbTotalResults = new Long(0);
+ timer = System.currentTimeMillis();
+ nbTotalResults = UserPropertiesLocalServiceUtil.getUserCountFromContactSearch(name, orgIds, roleIds, scholarshipLabels, grant, transport);
+ System.out.println("count query users (" + nbTotalResults + ") took "+(System.currentTimeMillis() - timer)+" ms");
+ result.put("nbResults", nbTotalResults);
+ } catch (Exception e) {
+ logger.error(e);
+ }
+ }
+ }
+ result.put("contacts", jsonContactList);
+
+
+
+ return result;
+ }
+
+ public static List<User> getUserListFromContactSearch(ResourceRequest resourceRequest, String name,
+ List<Long> orgIds, List<Long> roleIds, List<String> scholarshipLabels, int grant, int transport) {
+
+ final int start = ParamUtil.getInteger(resourceRequest, "start", QueryUtil.ALL_POS);
+ final int limit = ParamUtil.getInteger(resourceRequest, "limit", 0);
+ final int stop = start + limit;
+
+ OrderByComparator obc = buildComparator(resourceRequest, COMPARE_ON_USER);
+
+ List<User> usersList = new ArrayList<User>();
+
+ try {
+
+ long timer = System.currentTimeMillis();
+ usersList = UserPropertiesLocalServiceUtil.getUserFromContactSearch(name, orgIds, roleIds, scholarshipLabels, grant, transport, start, stop, obc);
+ System.out.println("query users took "+(System.currentTimeMillis() - timer)+" ms");
+
+ } catch (Exception e) {
+ logger.error(e);
+ }
+ System.out.println("Returned " + usersList.size() + " users");
+
+ //Check if we still found double. TODO Do we still need to check ?
+ //usersList = userListFilter(usersList);
+
+ return usersList;
+ }
+
+ private static List<String> getScholarshipLabels(String scholarship) {
+ if (scholarship.equals("internal")) {
+ return UserInformationsUtil.getInternalScholarshipLabels();
+ } else if (scholarship.equals("external")) {
+ return UserInformationsUtil.getExternalScholarshipLabels();
+ } else if (scholarship.equals("semi")) {
+ return UserInformationsUtil.getSemiPensionScholarshipLabels();
+ }
+
+ return new ArrayList<String>();
+ }
+
+ /**
+ * Get the users from a list and apply a filter if a search is entered
+ * @param renderRequest Request which contains the list and search parameters
+ * @param user User who currently displays the list
+ * @return a ProxyFiche list containing all the users that matches the search
+ */
+ public static List<ProxyFiche> getUsersFromList(RenderRequest renderRequest, User user) {
+ final String query = ParamUtil.getString(renderRequest, "recherche", "").toLowerCase();
+
+ OrderByComparator obc = buildComparator(renderRequest, COMPARE_ON_PROXYLIST);
+
+ List<ProxyFiche> fullListResult = getListFromType(renderRequest, user);
+
+ List<ProxyFiche> usersPFList = ENTAutoCompletionUtil.getFilteredListFromProxyFicheList(fullListResult, query);
+ Collections.sort(usersPFList, obc);
+
+ return usersPFList;
+ }
+
+ /**
+ * Get a sub list from the one in parameter (used for pagination)
+ * @param pfList ProxyFiche List to cut
+ * @param start The first element from the list to get
+ * @param limit The number of element we want
+ * @return a ProxyFiche List which is a sub list from the one received
+ */
+ public static List<ProxyFiche> getSubList(List<ProxyFiche> pfList, int start, int limit) {
+ int stop = start + limit;
+
+ if (stop > pfList.size()) {
+ stop = pfList.size();
+ }
+
+ pfList = pfList.subList(start, stop);
+
+ return pfList;
+ }
+
+ /**
+ * Build a LinkedHashMap which will be use as a parameter container in the search
+ * @param renderRequest The request with the parameters
+ * @param user The user currently searching
+ * @return LinkedHashMap with the parameters set for the search
+ */
+ private static LinkedHashMap<String, Object> buildUserParams(RenderRequest renderRequest, User user) {
+ LinkedHashMap<String, Object> userParams = new LinkedHashMap<String, Object>();
+
+ //Get searching parameters
+ long roleId = ParamUtil.getLong(renderRequest, "statut", 0);
+ long organizationId = ParamUtil.getLong(renderRequest, "organizationId", 0);
+ long etabId = ParamUtil.getLong(renderRequest, "etabId", 0);
+ long matiereId = ParamUtil.getLong(renderRequest, "matiereId", 0);
+ long[] etabStore = ParamUtil.getLongValues(renderRequest, "etabStore", null);
+
+ //User has restrictions : we search only on his school and students can only see other students
+ try {
+ if (OrganizationFinderServiceUtil.hasRestriction(user)) {
+ final Organization etabRattach = OrganizationFinderServiceUtil.getEtabRatachement(user);
+ etabId = etabRattach.getOrganizationId();
+ }
+ } catch (Exception e) {
+ logger.error(e);
+ }
+
+ try {
+ if (RoleLocalServiceUtil.hasUserRole(user.getUserId(), user.getCompanyId(), ENTRolesConstants.NATIONAL_1, false)) {
+ roleId = ENTRoleUtilFactory.getInstance(user.getCompanyId()).getRole(ENTRolesConstants.NATIONAL_1).getRoleId();
+ }
+ } catch (Exception e) {
+ logger.error(e);
+ }
+
+ // Check organizations : We search in the one selected, or in the restricted one,
+ //or in all schools of the list (after removing first empty value)
+ if (organizationId > 0) {
+ userParams.put("usersOrgs", new Long(organizationId));
+ } else if (etabId > 0) {
+ userParams.put("usersOrgs", new Long(etabId));
+ } else if (etabStore != null && etabStore.length < 5){
+ Long[] etabList = new Long[etabStore.length-1];
+ for (int i=1 ; i<etabStore.length ; ++i) {
+ etabList[i-1] = etabStore[i];
+ }
+ userParams.put("usersOrgs", etabList);
+ }
+
+ // Add role criterion if selected (or restriction)
+ if (roleId > 0){
+ userParams.put("usersRoles", new Long(roleId));
+ }
+
+ // Add courses filter
+ if (matiereId > 0) {
+ userParams.put("userEnseignement", new Long(matiereId));
+ }
+
+ return userParams;
+ }
+
+ /**
+ * Build a LinkedHashMap which will be use as a parameter container in the search
+ * @param renderRequest The request with the parameters
+ * @param user The user currently searching
+ * @return LinkedHashMap with the parameters set for the search
+ */
+ private static LinkedHashMap<String, Object> buildUserParams(ResourceRequest resourceRequest, User user) {
+ LinkedHashMap<String, Object> userParams = new LinkedHashMap<String, Object>();
+
+ System.out.println("ENTUserListUtil - buildUserParams over ResourceRequest");
+
+ Long[] usersOrgsList = getUsersOrgs(resourceRequest, user);
+ if (usersOrgsList != null) {
+ userParams.put("usersOrgs", usersOrgsList);
+ }
+
+ Long[] usersRolesList = getUsersRoles(resourceRequest, user);
+ // Role restriction
+ if (usersRolesList != null && usersRolesList.length > 0){
+ // TODO : manage multipe roles
+ userParams.put("usersRoles", usersRolesList[0]);
+ }
+
+ return userParams;
+ }
+
+ private static Long[] getUsersRoles(ResourceRequest resourceRequest, User user) {
+ // Get searching parameters
+ long[] roleIds = ParamUtil.getLongValues(resourceRequest, "roleIds");
+
+ Long[] longRoleIds = new Long[roleIds.length];
+ for (int i = 0 ; i < roleIds.length ; i++) {
+ long roleId = roleIds[i];
+ System.out.println(" > roleId="+roleId);
+ longRoleIds[i] = roleId;
+ }
+
+ // Students are only allowed to search among students
+ try {
+ if (RoleLocalServiceUtil.hasUserRole(user.getUserId(), user.getCompanyId(), ENTRolesConstants.NATIONAL_1, false)) {
+ roleIds = new long[1];
+ roleIds[0] = ENTRoleUtilFactory.getInstance(user.getCompanyId()).getRole(ENTRolesConstants.NATIONAL_1).getRoleId();
+ }
+ } catch (Exception e) {
+ logger.error(e);
+ }
+
+ // Role restriction
+ if (longRoleIds.length > 0){
+ // TODO : manage multipe roles
+ return longRoleIds;
+ }
+
+ return null;
+ }
+
+ private static Long[] getUsersOrgs(ResourceRequest resourceRequest, User user) {
+ // Get searching parameters
+ long[] organizationIds = ParamUtil.getLongValues(resourceRequest, "classIds");
+ long[] schoolIds = ParamUtil.getLongValues(resourceRequest, "schoolIds");
+
+ Long[] longSchoolIds = new Long[schoolIds.length];
+ for (int i = 0 ; i < schoolIds.length ; i++) {
+ long schoolId = schoolIds[i];
+ longSchoolIds[i] = schoolId;
+ }
+
+ Long[] longOrgIds = new Long[organizationIds.length];
+ for (int i = 0 ; i < organizationIds.length ; i++) {
+ long orgId = organizationIds[i];
+ longOrgIds[i] = orgId;
+ }
+
+ //User has restrictions : we search only on his school and students can only see other students
+ try {
+ if (OrganizationFinderServiceUtil.hasRestriction(user)) {
+ final Organization etabRattach = OrganizationFinderServiceUtil.getEtabRatachement(user);
+ longSchoolIds = new Long[1];
+ longSchoolIds[0] = etabRattach.getOrganizationId();
+ }
+ } catch (Exception e) {
+ logger.error(e);
+ }
+
+ // Check organizations : We search in the one selected, or in the restricted one,
+ //or in all schools of the list (after removing first empty value)
+ if (longOrgIds.length > 0) {
+ return longOrgIds;
+ } else if (longSchoolIds.length > 0) {
+ return longSchoolIds;
+ }
+
+ try {
+ if (!ENTRolesConstants.hasGlobalVisibilityOnGroupClassOnItsSchool(user)) {
+ // If no org filter then we check if the user is admin or limit him to his schools
+ JSONArray schools = GroupCacheUtil.getUserSchools(user);
+ longSchoolIds = new Long[schools.length()];
+
+ for (int i = 0 ; i < schools.length() ; ++i) {
+ long schoolId = schools.getJSONObject(i).getLong(GroupCacheUtil.GROUP_ORG_ID);
+ longSchoolIds[i] = schoolId;
+ }
+
+ return longSchoolIds;
+ }
+ } catch (Exception e) {
+ logger.error(e);
+ }
+
+
+ return null;
+ }
+
+ /**
+ * Build an OrderByComparator which will serve to sort list thanks to parameters in request
+ * @param renderRequest The request with the parameters
+ * @return an OrderByComparator to sort the search results
+ */
+ private static OrderByComparator buildComparator(RenderRequest renderRequest, int typeComparator) {
+ //Handle result sorting
+ final boolean asc = ParamUtil.getString(renderRequest, "dir", "ASC").equals("ASC")?true:false;
+ final String sort = ParamUtil.getString(renderRequest, "sort", "nom");
+
+ OrderByComparator obc;
+
+ //Use custom comparator for ProxyList, the default case is to compare users
+ if (typeComparator == COMPARE_ON_PROXYLIST) {
+ if (sort.equals("prenom")) {
+ obc = new CAfirstNameComparator(asc);
+ } else if (sort.equals("statut")) {
+ obc = new CAStatusComparator(asc);
+ } else {
+ obc = new CANameComparator(asc);
+ }
+ } else {
+ if (sort.equals("prenom")) {
+ obc = new UserFirstNameComparator(asc);
+ } else if (sort.equals("login")) {
+ obc = new UserScreenNameComparator(asc);
+ } else {
+ obc = new UserLastNameComparator(asc);
+ }
+ }
+
+ return obc;
+ }
+
+ /**
+ * Build an OrderByComparator which will serve to sort list thanks to parameters in request
+ * @param renderRequest The request with the parameters
+ * @return an OrderByComparator to sort the search results
+ */
+ private static OrderByComparator buildComparator(ResourceRequest resourceRequest, int typeComparator) {
+ //Handle result sorting
+ final boolean asc = ParamUtil.getString(resourceRequest, "dir", "ASC").equals("ASC")?true:false;
+ final String sort = ParamUtil.getString(resourceRequest, "sort", "nom");
+
+ OrderByComparator obc;
+
+ //Use custom comparator for ProxyList, the default case is to compare users
+ if (typeComparator == COMPARE_ON_PROXYLIST) {
+ if (sort.equals("prenom")) {
+ obc = new CAfirstNameComparator(asc);
+ } else if (sort.equals("statut")) {
+ obc = new CAStatusComparator(asc);
+ } else {
+ obc = new CANameComparator(asc);
+ }
+ } else {
+ if (sort.equals("prenom")) {
+ obc = new UserFirstNameComparator(asc);
+ } else if (sort.equals("login")) {
+ obc = new UserScreenNameComparator(asc);
+ } else {
+ obc = new UserLastNameComparator(asc);
+ }
+ }
+
+ return obc;
+ }
+
+ /**
+ * Remove double from a users list and return the filtered list
+ * @param usersList The users list which possibly contains double
+ * @return a User's List without double left
+ */
+ private static List<User> userListFilter(List<User> usersList) {
+ // Avoid duplicate user
+ List<Long> listExistingUserId = new ArrayList<Long>();
+ List<User> filteredUsers = new ArrayList<User>();
+ for(User u : usersList){
+ if(!listExistingUserId.contains(u.getUserId())){
+ filteredUsers.add(u);
+ listExistingUserId.add(u.getUserId());
+ }
+ }
+
+ return filteredUsers;
+ }
+
+ /**
+ * Return the users from the selected list
+ * @param renderRequest Request that contains all the parameters which describe the list
+ * @param user The owner of the list
+ * @return a ProxyFiche list with all the list users
+ */
+ private static List<ProxyFiche> getListFromType(RenderRequest renderRequest, User user) {
+ List<ProxyFiche> userListFromType = new ArrayList<ProxyFiche>();
+
+ final Long listId = ParamUtil.getLong(renderRequest, "listId", 0);
+ final Long roleId = ParamUtil.getLong(renderRequest, "roleId", 0);
+ final Long orgId = ParamUtil.getLong(renderRequest, "orgId", 0);
+ final String type = ParamUtil.getString(renderRequest, "type", "");
+ final String parentList = ParamUtil.getString(renderRequest, "parentList", "");
+ final String childrenList = ParamUtil.getString(renderRequest, "childrenList", "");
+
+ if (type.equals("local")) {
+ // personal lists (created by user)
+ try {
+ Liste userListe = ListeLocalServiceUtil.getListe(listId);
+ userListFromType = ListFicheFactory.createUserListContacts(user, userListe);
+ } catch (Exception e) {
+ logger.error(e);
+ }
+ }
+ else if (type.equals("search")) {
+ // organizations lists / groups lists
+ try {
+ userListFromType = ListFicheFactory.createSearchContacts(user, orgId, roleId, listId, parentList, childrenList, true);
+ } catch (SystemException e) {
+ logger.error(e);
+ }
+ }
+ // Global and friends lists
+ else if (type.equals("perso")) {
+ userListFromType = ListFicheFactory.createPersoContacts(user);
+ }
+ else if (type.equals("inst")) {
+ userListFromType = ListFicheFactory.createInstContacts(user);
+ }
+ else if (type.equals("all")) {
+ userListFromType = ListFicheFactory.createAllContacts(user);
+ }
+ else if (type.equals("allAmis")) {
+ try {
+ List<Relationship> listAllRel = RelationshipLocalServiceUtil.getRelationshipByUserIdStateId(user.getUserId(), 2, QueryUtil.ALL_POS, QueryUtil.ALL_POS);
+
+ List<Long> lesAmis = new ArrayList<Long>();
+ for(Relationship rel : listAllRel){
+ lesAmis.add(rel.getFriendId());
+ }
+ userListFromType = ListFicheFactory.createAmisContacts(user, lesAmis);
+ } catch (Exception e) {
+ logger.error(e);
+ }
+
+ }
+ else if (type.equals("amis")) {
+ try {
+ List<Relationship> listRel = RelationshipLocalServiceUtil.getRelationshipByUserIdFriendFolderIdStateId(user.getUserId(), listId, 2, QueryUtil.ALL_POS, QueryUtil.ALL_POS);
+ List<Long> lesAmis = new ArrayList<Long>();
+ for(Relationship rel : listRel){
+ lesAmis.add(rel.getFriendId());
+ }
+ userListFromType = ListFicheFactory.createAmisContacts(user, lesAmis);
+ } catch (Exception e) {
+ logger.error(e);
+ }
+ }
+
+ return userListFromType;
+ }
+
+ /**
+ * Method which get all user from an organization
+ * @param companyId
+ * @param organizationId
+ * @return List<User> representing the list of user of the organization, return empty list in error case
+ */
+ public static List<User> getUserFromAnOrganization(long companyId, long organizationId){
+ List<User> usersList = new ArrayList<User>();
+
+ try {
+ LinkedHashMap<String, Object> userParams = new LinkedHashMap<String, Object>();
+ userParams.put("usersOrgs", new Long(organizationId));
+ usersList = ExtUserLocalServiceUtil.search(
+ companyId,
+ null,
+ null,
+ null,
+ null,
+ null,
+ WorkflowConstants.STATUS_APPROVED,
+ userParams,
+ true,
+ QueryUtil.ALL_POS,
+ QueryUtil.ALL_POS,
+ (OrderByComparator) null);
+
+ } catch (SystemException e) {
+ logger.error(e);
+ }
+ return usersList;
+ }
+
+ /**
+ * Method which get all user with role from an organization
+ * @param companyId
+ * @param userRoleFilter the role it filter on
+ * @param organizationId
+ * @param comparator the comparator to order the
+ * @return List<User> representing the list of specific role user of the organization, return empty list in error case
+ */
+ public static List<User> getUserWithSpecificRoleForOrganization(long companyId, Role userRoleFilter,
+ long organizationId, OrderByComparator comparator){
+ List<User> usersList = new ArrayList<User>();
+
+ try {
+ LinkedHashMap<String, Object> userParams = new LinkedHashMap<String, Object>();
+ userParams.put("usersRoles", new Long(userRoleFilter.getRoleId()));
+ userParams.put("usersOrgs", new Long(organizationId));
+
+ usersList = ExtUserLocalServiceUtil.search(
+ companyId,
+ null,
+ null,
+ null,
+ null,
+ null,
+ WorkflowConstants.STATUS_APPROVED,
+ userParams,
+ true,
+ QueryUtil.ALL_POS,
+ QueryUtil.ALL_POS,
+ (OrderByComparator) null);
+
+ } catch (SystemException e) {
+ logger.error(e);
+ }
+ return usersList;
+ }
+
+ /**
+ * Method which get all user with role from a group
+ * @param companyId
+ * @param userRoleFilter the role it filter on
+ * @param groupId
+ * @return List<User> representing the list of specific role user of the organization, return empty list in error case
+ */
+ public static List<User> getUserWithSpecificRoleForGroup(long companyId, Role userRoleFilter,
+ long groupId){
+ List<User> usersList = new ArrayList<User>();
+
+ try {
+ LinkedHashMap<String, Object> userParams = new LinkedHashMap<String, Object>();
+ userParams.put("usersRoles", new Long(userRoleFilter.getRoleId()));
+ userParams.put("usersGroups", new Long(groupId));
+
+ usersList = ExtUserLocalServiceUtil.search(
+ companyId,
+ null,
+ null,
+ null,
+ null,
+ null,
+ WorkflowConstants.STATUS_APPROVED,
+ userParams,
+ true,
+ QueryUtil.ALL_POS,
+ QueryUtil.ALL_POS,
+ (OrderByComparator) null);
+
+ } catch (SystemException e) {
+ logger.error(e);
+ }
+ return usersList;
+ }
+
+}