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