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                                    Class<?> clazz = value.getClass();
107    
108                                    if (clazz.isArray()) {
109                                            Object[] values = (Object[])value;
110    
111                                            if (values.length == 0) {
112                                                    continue;
113                                            }
114                                    }
115    
116                                    addContextQueryParams(contextQuery, searchContext, key, value);
117                            }
118                    }
119            }
120    
121            @Override
122            public void postProcessSearchQuery(
123                            BooleanQuery searchQuery, SearchContext searchContext)
124                    throws Exception {
125    
126                    addSearchTerm(searchQuery, searchContext, "city", false);
127                    addSearchTerm(searchQuery, searchContext, "country", false);
128                    addSearchTerm(searchQuery, searchContext, "emailAddress", false);
129                    addSearchTerm(searchQuery, searchContext, "firstName", false);
130                    addSearchTerm(searchQuery, searchContext, "fullName", false);
131                    addSearchTerm(searchQuery, searchContext, "lastName", false);
132                    addSearchTerm(searchQuery, searchContext, "middleName", false);
133                    addSearchTerm(searchQuery, searchContext, "region", false);
134                    addSearchTerm(searchQuery, searchContext, "screenName", false);
135                    addSearchTerm(searchQuery, searchContext, "street", false);
136                    addSearchTerm(searchQuery, searchContext, "zip", false);
137    
138                    LinkedHashMap<String, Object> params =
139                            (LinkedHashMap<String, Object>)searchContext.getAttribute("params");
140    
141                    if (params != null) {
142                            String expandoAttributes = (String)params.get("expandoAttributes");
143    
144                            if (Validator.isNotNull(expandoAttributes)) {
145                                    addSearchExpando(searchQuery, searchContext, expandoAttributes);
146                            }
147                    }
148            }
149    
150            protected void addContextQueryParams(
151                            BooleanQuery contextQuery, SearchContext searchContext, String key,
152                            Object value)
153                    throws Exception {
154    
155                    if (key.equals("usersOrgs")) {
156                            if (value instanceof Long[]) {
157                                    Long[] values = (Long[])value;
158    
159                                    BooleanQuery usersOrgsQuery = BooleanQueryFactoryUtil.create(
160                                            searchContext);
161    
162                                    for (long organizationId : values) {
163                                            usersOrgsQuery.addTerm("organizationIds", organizationId);
164                                            usersOrgsQuery.addTerm(
165                                                    "ancestorOrganizationIds", organizationId);
166                                    }
167    
168                                    contextQuery.add(usersOrgsQuery, BooleanClauseOccur.MUST);
169                            }
170                            else {
171                                    contextQuery.addRequiredTerm(
172                                            "organizationIds", String.valueOf(value));
173                            }
174                    }
175                    else if (key.equals("usersOrgsCount")) {
176                            contextQuery.addRequiredTerm(
177                                    "organizationCount", String.valueOf(value));
178                    }
179                    else if (key.equals("usersRoles")) {
180                            contextQuery.addRequiredTerm("roleIds", String.valueOf(value));
181                    }
182                    else if (key.equals("usersTeams")) {
183                            contextQuery.addRequiredTerm("teamIds", String.valueOf(value));
184                    }
185                    else if (key.equals("usersUserGroups")) {
186                            contextQuery.addRequiredTerm("userGroupIds", String.valueOf(value));
187                    }
188            }
189    
190            @Override
191            protected void doDelete(Object obj) throws Exception {
192                    User user = (User)obj;
193    
194                    deleteDocument(user.getCompanyId(), user.getUserId());
195            }
196    
197            @Override
198            protected Document doGetDocument(Object obj) throws Exception {
199                    User user = (User)obj;
200    
201                    Document document = getBaseModelDocument(PORTLET_ID, user);
202    
203                    long[] organizationIds = user.getOrganizationIds();
204    
205                    document.addKeyword(Field.COMPANY_ID, user.getCompanyId());
206                    document.addDate(Field.MODIFIED_DATE, user.getModifiedDate());
207                    document.addKeyword(Field.STATUS, user.getStatus());
208                    document.addKeyword(Field.USER_ID, user.getUserId());
209                    document.addKeyword(Field.USER_NAME, user.getFullName());
210    
211                    document.addKeyword(
212                            "ancestorOrganizationIds",
213                            getAncestorOrganizationIds(
214                                    user.getUserId(), user.getOrganizationIds()));
215                    document.addText("emailAddress", user.getEmailAddress());
216                    document.addText("firstName", user.getFirstName());
217                    document.addText("fullName", user.getFullName());
218                    document.addKeyword("groupIds", user.getGroupIds());
219                    document.addText("jobTitle", user.getJobTitle());
220                    document.addText("lastName", user.getLastName());
221                    document.addText("middleName", user.getMiddleName());
222                    document.addKeyword("organizationIds", organizationIds);
223                    document.addKeyword(
224                            "organizationCount", String.valueOf(organizationIds.length));
225                    document.addKeyword("roleIds", user.getRoleIds());
226                    document.addText("screenName", user.getScreenName());
227                    document.addKeyword("teamIds", user.getTeamIds());
228                    document.addKeyword("userGroupIds", user.getUserGroupIds());
229    
230                    populateAddresses(document, user.getAddresses(), 0, 0);
231    
232                    return document;
233            }
234    
235            @Override
236            protected String doGetSortField(String orderByCol) {
237                    if (orderByCol.equals("email-address")) {
238                            return "emailAddress";
239                    }
240                    else if (orderByCol.equals("first-name")) {
241                            return "firstName";
242                    }
243                    else if (orderByCol.equals("job-title")) {
244                            return "jobTitle";
245                    }
246                    else if (orderByCol.equals("last-name")) {
247                            return "lastName";
248                    }
249                    else if (orderByCol.equals("screen-name")) {
250                            return "screenName";
251                    }
252                    else {
253                            return orderByCol;
254                    }
255            }
256    
257            @Override
258            protected Summary doGetSummary(
259                    Document document, Locale locale, String snippet,
260                    PortletURL portletURL) {
261    
262                    String firstName = document.get("firstName");
263                    String middleName = document.get("middleName");
264                    String lastName = document.get("lastName");
265    
266                    FullNameGenerator fullNameGenerator =
267                            FullNameGeneratorFactory.getInstance();
268    
269                    String title = fullNameGenerator.getFullName(
270                            firstName, middleName, lastName);
271    
272                    String content = null;
273    
274                    String userId = document.get(Field.USER_ID);
275    
276                    portletURL.setParameter("struts_action", "/users_admin/edit_user");
277                    portletURL.setParameter("p_u_i_d", userId);
278    
279                    return new Summary(title, content, portletURL);
280            }
281    
282            @Override
283            protected void doReindex(Object obj) throws Exception {
284                    if (obj instanceof List<?>) {
285                            List<User> users = (List<User>)obj;
286    
287                            for (User user : users) {
288                                    doReindex(user);
289                            }
290                    }
291                    else if (obj instanceof Long) {
292                            long userId = (Long)obj;
293    
294                            User user = UserLocalServiceUtil.getUserById(userId);
295    
296                            doReindex(user);
297                    }
298                    else if (obj instanceof long[]) {
299                            long[] userIds = (long[])obj;
300    
301                            Map<Long, Collection<Document>> documentsMap =
302                                    new HashMap<Long, Collection<Document>>();
303    
304                            for (long userId : userIds) {
305                                    User user = UserLocalServiceUtil.getUserById(userId);
306    
307                                    if (user.isDefaultUser()) {
308                                            continue;
309                                    }
310    
311                                    Document document = getDocument(user);
312    
313                                    long companyId = user.getCompanyId();
314    
315                                    Collection<Document> documents = documentsMap.get(companyId);
316    
317                                    if (documents == null) {
318                                            documents = new ArrayList<Document>();
319    
320                                            documentsMap.put(companyId, documents);
321                                    }
322    
323                                    documents.add(document);
324                            }
325    
326                            for (Map.Entry<Long, Collection<Document>> entry :
327                                            documentsMap.entrySet()) {
328    
329                                    long companyId = entry.getKey();
330                                    Collection<Document> documents = entry.getValue();
331    
332                                    SearchEngineUtil.updateDocuments(companyId, documents);
333                            }
334                    }
335                    else if (obj instanceof User) {
336                            User user = (User)obj;
337    
338                            if (user.isDefaultUser()) {
339                                    return;
340                            }
341    
342                            Document document = getDocument(user);
343    
344                            SearchEngineUtil.updateDocument(user.getCompanyId(), document);
345                    }
346            }
347    
348            @Override
349            protected void doReindex(String className, long classPK) throws Exception {
350                    User user = UserLocalServiceUtil.getUserById(classPK);
351    
352                    doReindex(user);
353            }
354    
355            @Override
356            protected void doReindex(String[] ids) throws Exception {
357                    long companyId = GetterUtil.getLong(ids[0]);
358    
359                    reindexUsers(companyId);
360            }
361    
362            protected long[] getAncestorOrganizationIds(
363                            long userId, long[] organizationIds)
364                    throws Exception {
365    
366                    List<Organization> ancestorOrganizations =
367                            new ArrayList<Organization>();
368    
369                    for (long organizationId : organizationIds) {
370                            Organization organization =
371                                    OrganizationLocalServiceUtil.getOrganization(organizationId);
372    
373                            ancestorOrganizations.addAll(organization.getAncestors());
374                    }
375    
376                    long[] ancestorOrganizationIds = new long[ancestorOrganizations.size()];
377    
378                    for (int i = 0; i < ancestorOrganizations.size(); i++) {
379                            Organization ancestorOrganization = ancestorOrganizations.get(i);
380    
381                            ancestorOrganizationIds[i] =
382                                    ancestorOrganization.getOrganizationId();
383                    }
384    
385                    return ancestorOrganizationIds;
386            }
387    
388            @Override
389            protected String getPortletId(SearchContext searchContext) {
390                    return PORTLET_ID;
391            }
392    
393            protected void reindexUsers(long companyId) throws Exception {
394                    int count = UserLocalServiceUtil.getCompanyUsersCount(companyId);
395    
396                    int pages = count / UserIndexer.DEFAULT_INTERVAL;
397    
398                    for (int i = 0; i <= pages; i++) {
399                            int start = (i * UserIndexer.DEFAULT_INTERVAL);
400                            int end = start + UserIndexer.DEFAULT_INTERVAL;
401    
402                            reindexUsers(companyId, start, end);
403                    }
404            }
405    
406            protected void reindexUsers(long companyId, int start, int end)
407                    throws Exception {
408    
409                    List<User> users = UserLocalServiceUtil.getCompanyUsers(
410                            companyId, start, end);
411    
412                    if (users.isEmpty()) {
413                            return;
414                    }
415    
416                    Collection<Document> documents = new ArrayList<Document>();
417    
418                    for (User user : users) {
419                            if (user.isDefaultUser()) {
420                                    continue;
421                            }
422    
423                            Document document = getDocument(user);
424    
425                            documents.add(document);
426                    }
427    
428                    SearchEngineUtil.updateDocuments(companyId, documents);
429            }
430    
431            private static final boolean _PERMISSION_AWARE = true;
432    
433    }