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