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.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                    setIndexerEnabled(PropsValues.USERS_INDEXER_ENABLED);
069                    setPermissionAware(true);
070                    setStagingAware(false);
071            }
072    
073            public String[] getClassNames() {
074                    return CLASS_NAMES;
075            }
076    
077            public String getPortletId() {
078                    return PORTLET_ID;
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                    Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(Contact.class);
197    
198                    Contact contact = new ContactImpl();
199    
200                    contact.setContactId(user.getContactId());
201                    contact.setCompanyId(user.getCompanyId());
202    
203                    indexer.delete(contact);
204            }
205    
206            @Override
207            protected Document doGetDocument(Object obj) throws Exception {
208                    User user = (User)obj;
209    
210                    Document document = getBaseModelDocument(PORTLET_ID, user);
211    
212                    long[] organizationIds = user.getOrganizationIds();
213    
214                    document.addKeyword(Field.COMPANY_ID, user.getCompanyId());
215                    document.addDate(Field.MODIFIED_DATE, user.getModifiedDate());
216                    document.addKeyword(Field.STATUS, user.getStatus());
217                    document.addKeyword(Field.USER_ID, user.getUserId());
218                    document.addKeyword(Field.USER_NAME, user.getFullName());
219    
220                    document.addKeyword(
221                            "ancestorOrganizationIds",
222                            getAncestorOrganizationIds(
223                                    user.getUserId(), user.getOrganizationIds()));
224                    document.addText("emailAddress", user.getEmailAddress());
225                    document.addText("firstName", user.getFirstName());
226                    document.addText("fullName", user.getFullName());
227                    document.addKeyword("groupIds", user.getGroupIds());
228                    document.addText("jobTitle", user.getJobTitle());
229                    document.addText("lastName", user.getLastName());
230                    document.addText("middleName", user.getMiddleName());
231                    document.addKeyword("organizationIds", organizationIds);
232                    document.addKeyword(
233                            "organizationCount", String.valueOf(organizationIds.length));
234                    document.addKeyword("roleIds", user.getRoleIds());
235                    document.addText("screenName", user.getScreenName());
236                    document.addKeyword("teamIds", user.getTeamIds());
237                    document.addKeyword("userGroupIds", user.getUserGroupIds());
238    
239                    populateAddresses(document, user.getAddresses(), 0, 0);
240    
241                    return document;
242            }
243    
244            @Override
245            protected String doGetSortField(String orderByCol) {
246                    if (orderByCol.equals("email-address")) {
247                            return "emailAddress";
248                    }
249                    else if (orderByCol.equals("first-name")) {
250                            return "firstName";
251                    }
252                    else if (orderByCol.equals("job-title")) {
253                            return "jobTitle";
254                    }
255                    else if (orderByCol.equals("last-name")) {
256                            return "lastName";
257                    }
258                    else if (orderByCol.equals("screen-name")) {
259                            return "screenName";
260                    }
261                    else {
262                            return orderByCol;
263                    }
264            }
265    
266            @Override
267            protected Summary doGetSummary(
268                    Document document, Locale locale, String snippet,
269                    PortletURL portletURL) {
270    
271                    String firstName = document.get("firstName");
272                    String middleName = document.get("middleName");
273                    String lastName = document.get("lastName");
274    
275                    FullNameGenerator fullNameGenerator =
276                            FullNameGeneratorFactory.getInstance();
277    
278                    String title = fullNameGenerator.getFullName(
279                            firstName, middleName, lastName);
280    
281                    String content = null;
282    
283                    String userId = document.get(Field.USER_ID);
284    
285                    portletURL.setParameter("struts_action", "/users_admin/edit_user");
286                    portletURL.setParameter("p_u_i_d", userId);
287    
288                    return new Summary(title, content, portletURL);
289            }
290    
291            @Override
292            protected void doReindex(Object obj) throws Exception {
293                    if (obj instanceof List<?>) {
294                            List<User> users = (List<User>)obj;
295    
296                            for (User user : users) {
297                                    doReindex(user);
298                            }
299                    }
300                    else 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                            }
344                    }
345                    else if (obj instanceof User) {
346                            User user = (User)obj;
347    
348                            if (user.isDefaultUser()) {
349                                    return;
350                            }
351    
352                            Document document = getDocument(user);
353    
354                            SearchEngineUtil.updateDocument(
355                                    getSearchEngineId(), user.getCompanyId(), document);
356    
357                            Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(
358                                    Contact.class);
359    
360                            indexer.reindex(user.getContact());
361                    }
362            }
363    
364            @Override
365            protected void doReindex(String className, long classPK) throws Exception {
366                    User user = UserLocalServiceUtil.getUserById(classPK);
367    
368                    doReindex(user);
369            }
370    
371            @Override
372            protected void doReindex(String[] ids) throws Exception {
373                    long companyId = GetterUtil.getLong(ids[0]);
374    
375                    reindexUsers(companyId);
376            }
377    
378            protected long[] getAncestorOrganizationIds(
379                            long userId, long[] organizationIds)
380                    throws Exception {
381    
382                    List<Organization> ancestorOrganizations =
383                            new ArrayList<Organization>();
384    
385                    for (long organizationId : organizationIds) {
386                            Organization organization =
387                                    OrganizationLocalServiceUtil.getOrganization(organizationId);
388    
389                            ancestorOrganizations.addAll(organization.getAncestors());
390                    }
391    
392                    long[] ancestorOrganizationIds = new long[ancestorOrganizations.size()];
393    
394                    for (int i = 0; i < ancestorOrganizations.size(); i++) {
395                            Organization ancestorOrganization = ancestorOrganizations.get(i);
396    
397                            ancestorOrganizationIds[i] =
398                                    ancestorOrganization.getOrganizationId();
399                    }
400    
401                    return ancestorOrganizationIds;
402            }
403    
404            @Override
405            protected String getPortletId(SearchContext searchContext) {
406                    return PORTLET_ID;
407            }
408    
409            protected void reindexUsers(long companyId)
410                    throws PortalException, SystemException {
411    
412                    final Collection<Document> documents = new ArrayList<Document>();
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                                            documents.add(document);
425                                    }
426                            }
427    
428                    };
429    
430                    actionableDynamicQuery.setCompanyId(companyId);
431    
432                    actionableDynamicQuery.performActions();
433    
434                    SearchEngineUtil.updateDocuments(
435                            getSearchEngineId(), companyId, documents);
436            }
437    
438    }