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