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