001    /**
002     * Copyright (c) 2000-2013 Liferay, Inc. All rights reserved.
003     *
004     * The contents of this file are subject to the terms of the Liferay Enterprise
005     * Subscription License ("License"). You may not use this file except in
006     * compliance with the License. You can obtain a copy of the License by
007     * contacting Liferay, Inc. See the License for the specific language governing
008     * permissions and limitations under the License, including but not limited to
009     * distribution rights of the Software.
010     *
011     *
012     *
013     */
014    
015    package com.liferay.portlet.usersadmin.util;
016    
017    import com.liferay.portal.kernel.dao.orm.ActionableDynamicQuery;
018    import com.liferay.portal.kernel.exception.PortalException;
019    import com.liferay.portal.kernel.exception.SystemException;
020    import com.liferay.portal.kernel.log.Log;
021    import com.liferay.portal.kernel.log.LogFactoryUtil;
022    import com.liferay.portal.kernel.search.BaseIndexer;
023    import com.liferay.portal.kernel.search.BooleanClauseOccur;
024    import com.liferay.portal.kernel.search.BooleanQuery;
025    import com.liferay.portal.kernel.search.BooleanQueryFactoryUtil;
026    import com.liferay.portal.kernel.search.Document;
027    import com.liferay.portal.kernel.search.Field;
028    import com.liferay.portal.kernel.search.Indexer;
029    import com.liferay.portal.kernel.search.IndexerRegistryUtil;
030    import com.liferay.portal.kernel.search.SearchContext;
031    import com.liferay.portal.kernel.search.SearchEngineUtil;
032    import com.liferay.portal.kernel.search.Summary;
033    import com.liferay.portal.kernel.util.GetterUtil;
034    import com.liferay.portal.kernel.util.Validator;
035    import com.liferay.portal.kernel.workflow.WorkflowConstants;
036    import com.liferay.portal.model.Contact;
037    import com.liferay.portal.model.Organization;
038    import com.liferay.portal.model.User;
039    import com.liferay.portal.model.impl.ContactImpl;
040    import com.liferay.portal.security.auth.FullNameGenerator;
041    import com.liferay.portal.security.auth.FullNameGeneratorFactory;
042    import com.liferay.portal.service.OrganizationLocalServiceUtil;
043    import com.liferay.portal.service.UserLocalServiceUtil;
044    import com.liferay.portal.service.persistence.UserActionableDynamicQuery;
045    import com.liferay.portal.util.PortletKeys;
046    import com.liferay.portal.util.PropsValues;
047    
048    import java.util.ArrayList;
049    import java.util.Collection;
050    import java.util.HashMap;
051    import java.util.LinkedHashMap;
052    import java.util.List;
053    import java.util.Locale;
054    import java.util.Map;
055    
056    import javax.portlet.PortletURL;
057    
058    /**
059     * @author Raymond Aug??
060     * @author Zsigmond Rab
061     * @author Hugo Huijser
062     */
063    public class UserIndexer extends BaseIndexer {
064    
065            public static final String[] CLASS_NAMES = {User.class.getName()};
066    
067            public static final String PORTLET_ID = PortletKeys.USERS_ADMIN;
068    
069            public UserIndexer() {
070                    setCommitImmediately(true);
071                    setIndexerEnabled(PropsValues.USERS_INDEXER_ENABLED);
072                    setPermissionAware(true);
073                    setStagingAware(false);
074            }
075    
076            @Override
077            public String[] getClassNames() {
078                    return CLASS_NAMES;
079            }
080    
081            @Override
082            public String getPortletId() {
083                    return PORTLET_ID;
084            }
085    
086            @Override
087            public void postProcessContextQuery(
088                            BooleanQuery contextQuery, SearchContext searchContext)
089                    throws Exception {
090    
091                    int status = GetterUtil.getInteger(
092                            searchContext.getAttribute(Field.STATUS),
093                            WorkflowConstants.STATUS_APPROVED);
094    
095                    if (status != WorkflowConstants.STATUS_ANY) {
096                            contextQuery.addRequiredTerm(Field.STATUS, status);
097                    }
098    
099                    LinkedHashMap<String, Object> params =
100                            (LinkedHashMap<String, Object>)searchContext.getAttribute("params");
101    
102                    if (params == null) {
103                            return;
104                    }
105    
106                    for (Map.Entry<String, Object> entry : params.entrySet()) {
107                            String key = entry.getKey();
108                            Object value = entry.getValue();
109    
110                            if (value == null) {
111                                    continue;
112                            }
113    
114                            Class<?> clazz = value.getClass();
115    
116                            if (clazz.isArray()) {
117                                    Object[] values = (Object[])value;
118    
119                                    if (values.length == 0) {
120                                            continue;
121                                    }
122                            }
123    
124                            addContextQueryParams(contextQuery, searchContext, key, value);
125                    }
126            }
127    
128            @Override
129            public void postProcessSearchQuery(
130                            BooleanQuery searchQuery, SearchContext searchContext)
131                    throws Exception {
132    
133                    addSearchTerm(searchQuery, searchContext, "city", false);
134                    addSearchTerm(searchQuery, searchContext, "country", false);
135                    addSearchTerm(searchQuery, searchContext, "emailAddress", false);
136                    addSearchTerm(searchQuery, searchContext, "firstName", false);
137                    addSearchTerm(searchQuery, searchContext, "fullName", false);
138                    addSearchTerm(searchQuery, searchContext, "lastName", false);
139                    addSearchTerm(searchQuery, searchContext, "middleName", false);
140                    addSearchTerm(searchQuery, searchContext, "region", false);
141                    addSearchTerm(searchQuery, searchContext, "screenName", false);
142                    addSearchTerm(searchQuery, searchContext, "street", false);
143                    addSearchTerm(searchQuery, searchContext, "zip", false);
144    
145                    LinkedHashMap<String, Object> params =
146                            (LinkedHashMap<String, Object>)searchContext.getAttribute("params");
147    
148                    if (params != null) {
149                            String expandoAttributes = (String)params.get("expandoAttributes");
150    
151                            if (Validator.isNotNull(expandoAttributes)) {
152                                    addSearchExpando(searchQuery, searchContext, expandoAttributes);
153                            }
154                    }
155            }
156    
157            protected void addContextQueryParams(
158                            BooleanQuery contextQuery, SearchContext searchContext, String key,
159                            Object value)
160                    throws Exception {
161    
162                    if (key.equals("usersGroups")) {
163                            if (value instanceof Long[]) {
164                                    Long[] values = (Long[])value;
165    
166                                    BooleanQuery usersGroupsQuery = BooleanQueryFactoryUtil.create(
167                                            searchContext);
168    
169                                    for (long groupId : values) {
170                                            usersGroupsQuery.addTerm("groupIds", groupId);
171                                    }
172    
173                                    contextQuery.add(usersGroupsQuery, BooleanClauseOccur.MUST);
174                            }
175                            else {
176                                    contextQuery.addRequiredTerm("groupIds", String.valueOf(value));
177                            }
178                    }
179                    else if (key.equals("usersOrgs")) {
180                            if (value instanceof Long[]) {
181                                    Long[] values = (Long[])value;
182    
183                                    BooleanQuery usersOrgsQuery = BooleanQueryFactoryUtil.create(
184                                            searchContext);
185    
186                                    for (long organizationId : values) {
187                                            usersOrgsQuery.addTerm("organizationIds", organizationId);
188                                            usersOrgsQuery.addTerm(
189                                                    "ancestorOrganizationIds", organizationId);
190                                    }
191    
192                                    contextQuery.add(usersOrgsQuery, BooleanClauseOccur.MUST);
193                            }
194                            else {
195                                    contextQuery.addRequiredTerm(
196                                            "organizationIds", String.valueOf(value));
197                            }
198                    }
199                    else if (key.equals("usersOrgsCount")) {
200                            contextQuery.addRequiredTerm(
201                                    "organizationCount", String.valueOf(value));
202                    }
203                    else if (key.equals("usersRoles")) {
204                            contextQuery.addRequiredTerm("roleIds", String.valueOf(value));
205                    }
206                    else if (key.equals("usersTeams")) {
207                            contextQuery.addRequiredTerm("teamIds", String.valueOf(value));
208                    }
209                    else if (key.equals("usersUserGroups")) {
210                            contextQuery.addRequiredTerm("userGroupIds", String.valueOf(value));
211                    }
212            }
213    
214            @Override
215            protected void doDelete(Object obj) throws Exception {
216                    User user = (User)obj;
217    
218                    deleteDocument(user.getCompanyId(), user.getUserId());
219    
220                    Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(Contact.class);
221    
222                    Contact contact = new ContactImpl();
223    
224                    contact.setContactId(user.getContactId());
225                    contact.setCompanyId(user.getCompanyId());
226    
227                    indexer.delete(contact);
228            }
229    
230            @Override
231            protected Document doGetDocument(Object obj) throws Exception {
232                    User user = (User)obj;
233    
234                    Document document = getBaseModelDocument(PORTLET_ID, user);
235    
236                    long[] organizationIds = user.getOrganizationIds();
237    
238                    document.addKeyword(Field.COMPANY_ID, user.getCompanyId());
239                    document.addKeyword(Field.GROUP_ID, user.getGroupIds());
240                    document.addDate(Field.MODIFIED_DATE, user.getModifiedDate());
241                    document.addKeyword(Field.SCOPE_GROUP_ID, user.getGroupIds());
242                    document.addKeyword(Field.STATUS, user.getStatus());
243                    document.addKeyword(Field.USER_ID, user.getUserId());
244                    document.addKeyword(Field.USER_NAME, user.getFullName());
245    
246                    document.addKeyword(
247                            "ancestorOrganizationIds",
248                            getAncestorOrganizationIds(
249                                    user.getUserId(), user.getOrganizationIds()));
250                    document.addText("emailAddress", user.getEmailAddress());
251                    document.addText("firstName", user.getFirstName());
252                    document.addText("fullName", user.getFullName());
253                    document.addKeyword("groupIds", user.getGroupIds());
254                    document.addText("jobTitle", user.getJobTitle());
255                    document.addText("lastName", user.getLastName());
256                    document.addText("middleName", user.getMiddleName());
257                    document.addKeyword("organizationIds", organizationIds);
258                    document.addKeyword(
259                            "organizationCount", String.valueOf(organizationIds.length));
260                    document.addKeyword("roleIds", user.getRoleIds());
261                    document.addText("screenName", user.getScreenName());
262                    document.addKeyword("teamIds", user.getTeamIds());
263                    document.addKeyword("userGroupIds", user.getUserGroupIds());
264    
265                    populateAddresses(document, user.getAddresses(), 0, 0);
266    
267                    return document;
268            }
269    
270            @Override
271            protected String doGetSortField(String orderByCol) {
272                    if (orderByCol.equals("email-address")) {
273                            return "emailAddress";
274                    }
275                    else if (orderByCol.equals("first-name")) {
276                            return "firstName";
277                    }
278                    else if (orderByCol.equals("job-title")) {
279                            return "jobTitle";
280                    }
281                    else if (orderByCol.equals("last-name")) {
282                            return "lastName";
283                    }
284                    else if (orderByCol.equals("screen-name")) {
285                            return "screenName";
286                    }
287                    else {
288                            return orderByCol;
289                    }
290            }
291    
292            @Override
293            protected Summary doGetSummary(
294                    Document document, Locale locale, String snippet,
295                    PortletURL portletURL) {
296    
297                    String firstName = document.get("firstName");
298                    String middleName = document.get("middleName");
299                    String lastName = document.get("lastName");
300    
301                    FullNameGenerator fullNameGenerator =
302                            FullNameGeneratorFactory.getInstance();
303    
304                    String title = fullNameGenerator.getFullName(
305                            firstName, middleName, lastName);
306    
307                    String content = null;
308    
309                    String userId = document.get(Field.USER_ID);
310    
311                    portletURL.setParameter("struts_action", "/users_admin/edit_user");
312                    portletURL.setParameter("p_u_i_d", userId);
313    
314                    return new Summary(title, content, portletURL);
315            }
316    
317            @Override
318            protected void doReindex(Object obj) throws Exception {
319                    if (obj instanceof Long) {
320                            long userId = (Long)obj;
321    
322                            User user = UserLocalServiceUtil.getUserById(userId);
323    
324                            doReindex(user);
325                    }
326                    else if (obj instanceof long[]) {
327                            long[] userIds = (long[])obj;
328    
329                            Map<Long, Collection<Document>> documentsMap =
330                                    new HashMap<Long, Collection<Document>>();
331    
332                            for (long userId : userIds) {
333                                    User user = UserLocalServiceUtil.getUserById(userId);
334    
335                                    if (user.isDefaultUser()) {
336                                            continue;
337                                    }
338    
339                                    Document document = getDocument(user);
340    
341                                    long companyId = user.getCompanyId();
342    
343                                    Collection<Document> documents = documentsMap.get(companyId);
344    
345                                    if (documents == null) {
346                                            documents = new ArrayList<Document>();
347    
348                                            documentsMap.put(companyId, documents);
349                                    }
350    
351                                    documents.add(document);
352                            }
353    
354                            for (Map.Entry<Long, Collection<Document>> entry :
355                                            documentsMap.entrySet()) {
356    
357                                    long companyId = entry.getKey();
358                                    Collection<Document> documents = entry.getValue();
359    
360                                    SearchEngineUtil.updateDocuments(
361                                            getSearchEngineId(), companyId, documents,
362                                            isCommitImmediately());
363                            }
364                    }
365                    else if (obj instanceof User) {
366                            User user = (User)obj;
367    
368                            if (user.isDefaultUser()) {
369                                    return;
370                            }
371    
372                            Document document = getDocument(user);
373    
374                            SearchEngineUtil.updateDocument(
375                                    getSearchEngineId(), user.getCompanyId(), document,
376                                    isCommitImmediately());
377    
378                            Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(
379                                    Contact.class);
380    
381                            indexer.reindex(user.getContact());
382                    }
383            }
384    
385            @Override
386            protected void doReindex(String className, long classPK) throws Exception {
387                    User user = UserLocalServiceUtil.getUserById(classPK);
388    
389                    doReindex(user);
390            }
391    
392            @Override
393            protected void doReindex(String[] ids) throws Exception {
394                    long companyId = GetterUtil.getLong(ids[0]);
395    
396                    reindexUsers(companyId);
397            }
398    
399            protected long[] getAncestorOrganizationIds(
400                            long userId, long[] organizationIds)
401                    throws Exception {
402    
403                    List<Organization> ancestorOrganizations =
404                            new ArrayList<Organization>();
405    
406                    for (long organizationId : organizationIds) {
407                            Organization organization =
408                                    OrganizationLocalServiceUtil.getOrganization(organizationId);
409    
410                            ancestorOrganizations.addAll(organization.getAncestors());
411                    }
412    
413                    long[] ancestorOrganizationIds = new long[ancestorOrganizations.size()];
414    
415                    for (int i = 0; i < ancestorOrganizations.size(); i++) {
416                            Organization ancestorOrganization = ancestorOrganizations.get(i);
417    
418                            ancestorOrganizationIds[i] =
419                                    ancestorOrganization.getOrganizationId();
420                    }
421    
422                    return ancestorOrganizationIds;
423            }
424    
425            @Override
426            protected String getPortletId(SearchContext searchContext) {
427                    return PORTLET_ID;
428            }
429    
430            protected void reindexUsers(long companyId)
431                    throws PortalException, SystemException {
432    
433                    ActionableDynamicQuery actionableDynamicQuery =
434                            new UserActionableDynamicQuery() {
435    
436                            @Override
437                            protected void performAction(Object object) {
438                                    User user = (User)object;
439    
440                                    if (!user.isDefaultUser()) {
441                                            try {
442                                                    Document document = getDocument(user);
443    
444                                                    addDocument(document);
445                                            }
446                                            catch (PortalException pe) {
447                                                    if (_log.isWarnEnabled()) {
448                                                            _log.warn(
449                                                                    "Unable to index user " + user.getUserId(), pe);
450                                                    }
451                                            }
452                                    }
453                            }
454    
455                    };
456    
457                    actionableDynamicQuery.setCompanyId(companyId);
458                    actionableDynamicQuery.setSearchEngineId(getSearchEngineId());
459    
460                    actionableDynamicQuery.performActions();
461            }
462    
463            private static Log _log = LogFactoryUtil.getLog(UserIndexer.class);
464    
465    }