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