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                    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.addKeyword(Field.GROUP_ID, user.getGroupIds());
216                    document.addDate(Field.MODIFIED_DATE, user.getModifiedDate());
217                    document.addKeyword(Field.SCOPE_GROUP_ID, user.getGroupIds());
218                    document.addKeyword(Field.STATUS, user.getStatus());
219                    document.addKeyword(Field.USER_ID, user.getUserId());
220                    document.addKeyword(Field.USER_NAME, user.getFullName());
221    
222                    document.addKeyword(
223                            "ancestorOrganizationIds",
224                            getAncestorOrganizationIds(
225                                    user.getUserId(), user.getOrganizationIds()));
226                    document.addText("emailAddress", user.getEmailAddress());
227                    document.addText("firstName", user.getFirstName());
228                    document.addText("fullName", user.getFullName());
229                    document.addKeyword("groupIds", user.getGroupIds());
230                    document.addText("jobTitle", user.getJobTitle());
231                    document.addText("lastName", user.getLastName());
232                    document.addText("middleName", user.getMiddleName());
233                    document.addKeyword("organizationIds", organizationIds);
234                    document.addKeyword(
235                            "organizationCount", String.valueOf(organizationIds.length));
236                    document.addKeyword("roleIds", user.getRoleIds());
237                    document.addText("screenName", user.getScreenName());
238                    document.addKeyword("teamIds", user.getTeamIds());
239                    document.addKeyword("userGroupIds", user.getUserGroupIds());
240    
241                    populateAddresses(document, user.getAddresses(), 0, 0);
242    
243                    return document;
244            }
245    
246            @Override
247            protected String doGetSortField(String orderByCol) {
248                    if (orderByCol.equals("email-address")) {
249                            return "emailAddress";
250                    }
251                    else if (orderByCol.equals("first-name")) {
252                            return "firstName";
253                    }
254                    else if (orderByCol.equals("job-title")) {
255                            return "jobTitle";
256                    }
257                    else if (orderByCol.equals("last-name")) {
258                            return "lastName";
259                    }
260                    else if (orderByCol.equals("screen-name")) {
261                            return "screenName";
262                    }
263                    else {
264                            return orderByCol;
265                    }
266            }
267    
268            @Override
269            protected Summary doGetSummary(
270                    Document document, Locale locale, String snippet,
271                    PortletURL portletURL) {
272    
273                    String firstName = document.get("firstName");
274                    String middleName = document.get("middleName");
275                    String lastName = document.get("lastName");
276    
277                    FullNameGenerator fullNameGenerator =
278                            FullNameGeneratorFactory.getInstance();
279    
280                    String title = fullNameGenerator.getFullName(
281                            firstName, middleName, lastName);
282    
283                    String content = null;
284    
285                    String userId = document.get(Field.USER_ID);
286    
287                    portletURL.setParameter("struts_action", "/users_admin/edit_user");
288                    portletURL.setParameter("p_u_i_d", userId);
289    
290                    return new Summary(title, content, portletURL);
291            }
292    
293            @Override
294            protected void doReindex(Object obj) throws Exception {
295                    if (obj instanceof List<?>) {
296                            List<User> users = (List<User>)obj;
297    
298                            for (User user : users) {
299                                    doReindex(user);
300                            }
301                    }
302                    else if (obj instanceof Long) {
303                            long userId = (Long)obj;
304    
305                            User user = UserLocalServiceUtil.getUserById(userId);
306    
307                            doReindex(user);
308                    }
309                    else if (obj instanceof long[]) {
310                            long[] userIds = (long[])obj;
311    
312                            Map<Long, Collection<Document>> documentsMap =
313                                    new HashMap<Long, Collection<Document>>();
314    
315                            for (long userId : userIds) {
316                                    User user = UserLocalServiceUtil.getUserById(userId);
317    
318                                    if (user.isDefaultUser()) {
319                                            continue;
320                                    }
321    
322                                    Document document = getDocument(user);
323    
324                                    long companyId = user.getCompanyId();
325    
326                                    Collection<Document> documents = documentsMap.get(companyId);
327    
328                                    if (documents == null) {
329                                            documents = new ArrayList<Document>();
330    
331                                            documentsMap.put(companyId, documents);
332                                    }
333    
334                                    documents.add(document);
335                            }
336    
337                            for (Map.Entry<Long, Collection<Document>> entry :
338                                            documentsMap.entrySet()) {
339    
340                                    long companyId = entry.getKey();
341                                    Collection<Document> documents = entry.getValue();
342    
343                                    SearchEngineUtil.updateDocuments(
344                                            getSearchEngineId(), companyId, documents);
345                            }
346                    }
347                    else if (obj instanceof User) {
348                            User user = (User)obj;
349    
350                            if (user.isDefaultUser()) {
351                                    return;
352                            }
353    
354                            Document document = getDocument(user);
355    
356                            SearchEngineUtil.updateDocument(
357                                    getSearchEngineId(), user.getCompanyId(), document);
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                    final Collection<Document> documents = new ArrayList<Document>();
415    
416                    ActionableDynamicQuery actionableDynamicQuery =
417                            new UserActionableDynamicQuery() {
418    
419                            @Override
420                            protected void performAction(Object object) throws PortalException {
421                                    User user = (User)object;
422    
423                                    if (!user.isDefaultUser()) {
424                                            Document document = getDocument(user);
425    
426                                            documents.add(document);
427                                    }
428                            }
429    
430                    };
431    
432                    actionableDynamicQuery.setCompanyId(companyId);
433    
434                    actionableDynamicQuery.performActions();
435    
436                    SearchEngineUtil.updateDocuments(
437                            getSearchEngineId(), companyId, documents);
438            }
439    
440    }