001    /**
002     * Copyright (c) 2000-2012 Liferay, Inc. All rights reserved.
003     *
004     * This library is free software; you can redistribute it and/or modify it under
005     * the terms of the GNU Lesser General Public License as published by the Free
006     * Software Foundation; either version 2.1 of the License, or (at your option)
007     * any later version.
008     *
009     * This library is distributed in the hope that it will be useful, but WITHOUT
010     * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
011     * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
012     * details.
013     */
014    
015    package com.liferay.portlet.usersadmin.util;
016    
017    import com.liferay.portal.kernel.search.BaseIndexer;
018    import com.liferay.portal.kernel.search.BooleanClauseOccur;
019    import com.liferay.portal.kernel.search.BooleanQuery;
020    import com.liferay.portal.kernel.search.BooleanQueryFactoryUtil;
021    import com.liferay.portal.kernel.search.Document;
022    import com.liferay.portal.kernel.search.Field;
023    import com.liferay.portal.kernel.search.SearchContext;
024    import com.liferay.portal.kernel.search.SearchEngineUtil;
025    import com.liferay.portal.kernel.search.Summary;
026    import com.liferay.portal.kernel.util.GetterUtil;
027    import com.liferay.portal.kernel.util.Validator;
028    import com.liferay.portal.kernel.workflow.WorkflowConstants;
029    import com.liferay.portal.model.Organization;
030    import com.liferay.portal.model.User;
031    import com.liferay.portal.security.auth.FullNameGenerator;
032    import com.liferay.portal.security.auth.FullNameGeneratorFactory;
033    import com.liferay.portal.service.OrganizationLocalServiceUtil;
034    import com.liferay.portal.service.UserLocalServiceUtil;
035    import com.liferay.portal.util.PortletKeys;
036    import com.liferay.portal.util.PropsValues;
037    
038    import java.util.ArrayList;
039    import java.util.Collection;
040    import java.util.HashMap;
041    import java.util.LinkedHashMap;
042    import java.util.List;
043    import java.util.Locale;
044    import java.util.Map;
045    
046    import javax.portlet.PortletURL;
047    
048    /**
049     * @author Raymond Augé
050     * @author Zsigmond Rab
051     * @author Hugo Huijser
052     */
053    public class UserIndexer extends BaseIndexer {
054    
055            public static final String[] CLASS_NAMES = {User.class.getName()};
056    
057            public static final String PORTLET_ID = PortletKeys.USERS_ADMIN;
058    
059            public UserIndexer() {
060                    setStagingAware(false);
061            }
062    
063            public String[] getClassNames() {
064                    return CLASS_NAMES;
065            }
066    
067            public String getPortletId() {
068                    return PORTLET_ID;
069            }
070    
071            @Override
072            public boolean isIndexerEnabled() {
073                    return PropsValues.USERS_INDEXER_ENABLED;
074            }
075    
076            @Override
077            public boolean isPermissionAware() {
078                    return _PERMISSION_AWARE;
079            }
080    
081            @Override
082            public void postProcessContextQuery(
083                            BooleanQuery contextQuery, SearchContext searchContext)
084                    throws Exception {
085    
086                    int status = GetterUtil.getInteger(
087                            searchContext.getAttribute(Field.STATUS),
088                            WorkflowConstants.STATUS_APPROVED);
089    
090                    if (status != WorkflowConstants.STATUS_ANY) {
091                            contextQuery.addRequiredTerm(Field.STATUS, status);
092                    }
093    
094                    LinkedHashMap<String, Object> params =
095                            (LinkedHashMap<String, Object>)searchContext.getAttribute("params");
096    
097                    if (params != null) {
098                            for (Map.Entry<String, Object> entry : params.entrySet()) {
099                                    String key = entry.getKey();
100                                    Object value = entry.getValue();
101    
102                                    if (value == null) {
103                                            continue;
104                                    }
105    
106                                    addContextQueryParams(contextQuery, searchContext, key, value);
107                            }
108                    }
109            }
110    
111            @Override
112            public void postProcessSearchQuery(
113                            BooleanQuery searchQuery, SearchContext searchContext)
114                    throws Exception {
115    
116                    addSearchTerm(searchQuery, searchContext, "city", false);
117                    addSearchTerm(searchQuery, searchContext, "country", false);
118                    addSearchTerm(searchQuery, searchContext, "emailAddress", false);
119                    addSearchTerm(searchQuery, searchContext, "firstName", false);
120                    addSearchTerm(searchQuery, searchContext, "fullName", false);
121                    addSearchTerm(searchQuery, searchContext, "lastName", false);
122                    addSearchTerm(searchQuery, searchContext, "middleName", false);
123                    addSearchTerm(searchQuery, searchContext, "region", false);
124                    addSearchTerm(searchQuery, searchContext, "screenName", false);
125                    addSearchTerm(searchQuery, searchContext, "street", false);
126                    addSearchTerm(searchQuery, searchContext, "zip", false);
127    
128                    LinkedHashMap<String, Object> params =
129                            (LinkedHashMap<String, Object>)searchContext.getAttribute("params");
130    
131                    if (params != null) {
132                            String expandoAttributes = (String)params.get("expandoAttributes");
133    
134                            if (Validator.isNotNull(expandoAttributes)) {
135                                    addSearchExpando(searchQuery, searchContext, expandoAttributes);
136                            }
137                    }
138            }
139    
140            protected void addContextQueryParams(
141                            BooleanQuery contextQuery, SearchContext searchContext, String key,
142                            Object value)
143                    throws Exception {
144    
145                    if (key.equals("usersOrgs")) {
146                            if (value instanceof Long[]) {
147                                    Long[] values = (Long[])value;
148    
149                                    BooleanQuery usersOrgsQuery =
150                                            BooleanQueryFactoryUtil.create(searchContext);
151    
152                                    for (long organizationId : values) {
153                                            usersOrgsQuery.addTerm("organizationIds", organizationId);
154                                            usersOrgsQuery.addTerm(
155                                                    "ancestorOrganizationIds", organizationId);
156                                    }
157    
158                                    contextQuery.add(usersOrgsQuery, BooleanClauseOccur.MUST);
159                            }
160                            else {
161                                    contextQuery.addRequiredTerm(
162                                            "organizationIds", String.valueOf(value));
163                            }
164                    }
165                    else if (key.equals("usersOrgsCount")) {
166                            contextQuery.addRequiredTerm(
167                                    "organizationCount", String.valueOf(value));
168                    }
169                    else if (key.equals("usersRoles")) {
170                            contextQuery.addRequiredTerm("roleIds", String.valueOf(value));
171                    }
172                    else if (key.equals("usersTeams")) {
173                            contextQuery.addRequiredTerm("teamIds", String.valueOf(value));
174                    }
175                    else if (key.equals("usersUserGroups")) {
176                            contextQuery.addRequiredTerm("userGroupIds", String.valueOf(value));
177                    }
178            }
179    
180            @Override
181            protected void doDelete(Object obj) throws Exception {
182                    User user = (User)obj;
183    
184                    deleteDocument(user.getCompanyId(), user.getUserId());
185            }
186    
187            @Override
188            protected Document doGetDocument(Object obj) throws Exception {
189                    User user = (User)obj;
190    
191                    Document document = getBaseModelDocument(PORTLET_ID, user);
192    
193                    long[] organizationIds = user.getOrganizationIds();
194    
195                    document.addKeyword(Field.COMPANY_ID, user.getCompanyId());
196                    document.addDate(Field.MODIFIED_DATE, user.getModifiedDate());
197                    document.addKeyword(Field.STATUS, user.getStatus());
198                    document.addKeyword(Field.USER_ID, user.getUserId());
199                    document.addKeyword(Field.USER_NAME, user.getFullName());
200    
201                    document.addKeyword(
202                            "ancestorOrganizationIds",
203                            getAncestorOrganizationIds(
204                                    user.getUserId(), user.getOrganizationIds()));
205                    document.addText("emailAddress", user.getEmailAddress());
206                    document.addText("firstName", user.getFirstName());
207                    document.addText("fullName", user.getFullName());
208                    document.addKeyword("groupIds", user.getGroupIds());
209                    document.addText("jobTitle", user.getJobTitle());
210                    document.addText("lastName", user.getLastName());
211                    document.addText("middleName", user.getMiddleName());
212                    document.addKeyword("organizationIds", organizationIds);
213                    document.addKeyword(
214                            "organizationCount", String.valueOf(organizationIds.length));
215                    document.addKeyword("roleIds", user.getRoleIds());
216                    document.addText("screenName", user.getScreenName());
217                    document.addKeyword("teamIds", user.getTeamIds());
218                    document.addKeyword("userGroupIds", user.getUserGroupIds());
219    
220                    populateAddresses(document, user.getAddresses(), 0, 0);
221    
222                    return document;
223            }
224    
225            @Override
226            protected String doGetSortField(String orderByCol) {
227                    if (orderByCol.equals("email-address")) {
228                            return "emailAddress";
229                    }
230                    else if (orderByCol.equals("first-name")) {
231                            return "firstName";
232                    }
233                    else if (orderByCol.equals("job-title")) {
234                            return "jobTitle";
235                    }
236                    else if (orderByCol.equals("last-name")) {
237                            return "lastName";
238                    }
239                    else if (orderByCol.equals("screen-name")) {
240                            return "screenName";
241                    }
242                    else {
243                            return orderByCol;
244                    }
245            }
246    
247            @Override
248            protected Summary doGetSummary(
249                    Document document, Locale locale, String snippet,
250                    PortletURL portletURL) {
251    
252                    String firstName = document.get("firstName");
253                    String middleName = document.get("middleName");
254                    String lastName = document.get("lastName");
255    
256                    FullNameGenerator fullNameGenerator =
257                            FullNameGeneratorFactory.getInstance();
258    
259                    String title = fullNameGenerator.getFullName(
260                            firstName, middleName, lastName);
261    
262                    String content = null;
263    
264                    String userId = document.get(Field.USER_ID);
265    
266                    portletURL.setParameter("struts_action", "/users_admin/edit_user");
267                    portletURL.setParameter("p_u_i_d", userId);
268    
269                    return new Summary(title, content, portletURL);
270            }
271    
272            @Override
273            protected void doReindex(Object obj) throws Exception {
274                    if (obj instanceof List<?>) {
275                            List<User> users = (List<User>)obj;
276    
277                            for (User user : users) {
278                                    doReindex(user);
279                            }
280                    }
281                    else if (obj instanceof Long) {
282                            long userId = (Long)obj;
283    
284                            User user = UserLocalServiceUtil.getUserById(userId);
285    
286                            doReindex(user);
287                    }
288                    else if (obj instanceof long[]) {
289                            long[] userIds = (long[])obj;
290    
291                            Map<Long, Collection<Document>> documentsMap =
292                                    new HashMap<Long, Collection<Document>>();
293    
294                            for (long userId : userIds) {
295                                    User user = UserLocalServiceUtil.getUserById(userId);
296    
297                                    if (user.isDefaultUser()) {
298                                            continue;
299                                    }
300    
301                                    Document document = getDocument(user);
302    
303                                    long companyId = user.getCompanyId();
304    
305                                    Collection<Document> documents = documentsMap.get(companyId);
306    
307                                    if (documents == null) {
308                                            documents = new ArrayList<Document>();
309    
310                                            documentsMap.put(companyId, documents);
311                                    }
312    
313                                    documents.add(document);
314                            }
315    
316                            for (Map.Entry<Long, Collection<Document>> entry :
317                                            documentsMap.entrySet()) {
318    
319                                    long companyId = entry.getKey();
320                                    Collection<Document> documents = entry.getValue();
321    
322                                    SearchEngineUtil.updateDocuments(companyId, documents);
323                            }
324                    }
325                    else if (obj instanceof User) {
326                            User user = (User)obj;
327    
328                            if (user.isDefaultUser()) {
329                                    return;
330                            }
331    
332                            Document document = getDocument(user);
333    
334                            SearchEngineUtil.updateDocument(user.getCompanyId(), document);
335                    }
336            }
337    
338            @Override
339            protected void doReindex(String className, long classPK) throws Exception {
340                    User user = UserLocalServiceUtil.getUserById(classPK);
341    
342                    doReindex(user);
343            }
344    
345            @Override
346            protected void doReindex(String[] ids) throws Exception {
347                    long companyId = GetterUtil.getLong(ids[0]);
348    
349                    reindexUsers(companyId);
350            }
351    
352            protected long[] getAncestorOrganizationIds(
353                            long userId, long[] organizationIds)
354                    throws Exception {
355    
356                    List<Organization> ancestorOrganizations =
357                            new ArrayList<Organization>();
358    
359                    for (long organizationId : organizationIds) {
360                            Organization organization =
361                                    OrganizationLocalServiceUtil.getOrganization(organizationId);
362    
363                            ancestorOrganizations.addAll(organization.getAncestors());
364                    }
365    
366                    long[] ancestorOrganizationIds = new long[ancestorOrganizations.size()];
367    
368                    for (int i = 0; i < ancestorOrganizations.size(); i++) {
369                            Organization ancestorOrganization = ancestorOrganizations.get(i);
370    
371                            ancestorOrganizationIds[i] =
372                                    ancestorOrganization.getOrganizationId();
373                    }
374    
375                    return ancestorOrganizationIds;
376            }
377    
378            @Override
379            protected String getPortletId(SearchContext searchContext) {
380                    return PORTLET_ID;
381            }
382    
383            protected void reindexUsers(long companyId) throws Exception {
384                    int count = UserLocalServiceUtil.getCompanyUsersCount(companyId);
385    
386                    int pages = count / UserIndexer.DEFAULT_INTERVAL;
387    
388                    for (int i = 0; i <= pages; i++) {
389                            int start = (i * UserIndexer.DEFAULT_INTERVAL);
390                            int end = start + UserIndexer.DEFAULT_INTERVAL;
391    
392                            reindexUsers(companyId, start, end);
393                    }
394            }
395    
396            protected void reindexUsers(long companyId, int start, int end)
397                    throws Exception {
398    
399                    List<User> users = UserLocalServiceUtil.getCompanyUsers(
400                            companyId, start, end);
401    
402                    if (users.isEmpty()) {
403                            return;
404                    }
405    
406                    Collection<Document> documents = new ArrayList<Document>();
407    
408                    for (User user : users) {
409                            if (user.isDefaultUser()) {
410                                    continue;
411                            }
412    
413                            Document document = getDocument(user);
414    
415                            documents.add(document);
416                    }
417    
418                    SearchEngineUtil.updateDocuments(companyId, documents);
419            }
420    
421            private static final boolean _PERMISSION_AWARE = true;
422    
423    }