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