001    /**
002     * Copyright (c) 2000-2013 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.portal.service.impl;
016    
017    import com.liferay.portal.DuplicateRoleException;
018    import com.liferay.portal.NoSuchRoleException;
019    import com.liferay.portal.NoSuchShardException;
020    import com.liferay.portal.RequiredRoleException;
021    import com.liferay.portal.RoleNameException;
022    import com.liferay.portal.kernel.cache.Lifecycle;
023    import com.liferay.portal.kernel.cache.ThreadLocalCachable;
024    import com.liferay.portal.kernel.cache.ThreadLocalCache;
025    import com.liferay.portal.kernel.cache.ThreadLocalCacheManager;
026    import com.liferay.portal.kernel.dao.db.DB;
027    import com.liferay.portal.kernel.dao.db.DBFactoryUtil;
028    import com.liferay.portal.kernel.dao.shard.ShardUtil;
029    import com.liferay.portal.kernel.exception.PortalException;
030    import com.liferay.portal.kernel.exception.SystemException;
031    import com.liferay.portal.kernel.lar.ExportImportThreadLocal;
032    import com.liferay.portal.kernel.search.Indexer;
033    import com.liferay.portal.kernel.search.IndexerRegistryUtil;
034    import com.liferay.portal.kernel.spring.aop.Skip;
035    import com.liferay.portal.kernel.systemevent.SystemEvent;
036    import com.liferay.portal.kernel.transaction.Propagation;
037    import com.liferay.portal.kernel.transaction.Transactional;
038    import com.liferay.portal.kernel.util.ArrayUtil;
039    import com.liferay.portal.kernel.util.CharPool;
040    import com.liferay.portal.kernel.util.GetterUtil;
041    import com.liferay.portal.kernel.util.ListUtil;
042    import com.liferay.portal.kernel.util.LocaleUtil;
043    import com.liferay.portal.kernel.util.OrderByComparator;
044    import com.liferay.portal.kernel.util.SetUtil;
045    import com.liferay.portal.kernel.util.StringUtil;
046    import com.liferay.portal.kernel.util.Validator;
047    import com.liferay.portal.model.Company;
048    import com.liferay.portal.model.Group;
049    import com.liferay.portal.model.Layout;
050    import com.liferay.portal.model.ResourceAction;
051    import com.liferay.portal.model.ResourceBlockPermission;
052    import com.liferay.portal.model.ResourceConstants;
053    import com.liferay.portal.model.ResourcePermission;
054    import com.liferay.portal.model.ResourceTypePermission;
055    import com.liferay.portal.model.Role;
056    import com.liferay.portal.model.RoleConstants;
057    import com.liferay.portal.model.Shard;
058    import com.liferay.portal.model.SystemEventConstants;
059    import com.liferay.portal.model.Team;
060    import com.liferay.portal.model.User;
061    import com.liferay.portal.security.auth.CompanyThreadLocal;
062    import com.liferay.portal.security.permission.ActionKeys;
063    import com.liferay.portal.security.permission.PermissionCacheUtil;
064    import com.liferay.portal.security.permission.PermissionThreadLocal;
065    import com.liferay.portal.service.ServiceContext;
066    import com.liferay.portal.service.base.RoleLocalServiceBaseImpl;
067    import com.liferay.portal.util.PortalUtil;
068    import com.liferay.portal.util.PortletKeys;
069    import com.liferay.portal.util.PropsUtil;
070    import com.liferay.portal.util.PropsValues;
071    import com.liferay.portlet.usersadmin.util.UsersAdminUtil;
072    
073    import java.io.IOException;
074    
075    import java.util.ArrayList;
076    import java.util.Arrays;
077    import java.util.Collection;
078    import java.util.Collections;
079    import java.util.Date;
080    import java.util.HashMap;
081    import java.util.LinkedHashMap;
082    import java.util.List;
083    import java.util.Locale;
084    import java.util.Map;
085    import java.util.Set;
086    
087    /**
088     * Provides the local service for accessing, adding, checking, deleting, and
089     * updating roles.
090     *
091     * @author Brian Wing Shun Chan
092     * @author Marcellus Tavares
093     */
094    public class RoleLocalServiceImpl extends RoleLocalServiceBaseImpl {
095    
096            /**
097             * Adds a role. The user is reindexed after role is added.
098             *
099             * @param      userId the primary key of the user
100             * @param      companyId the primary key of the company
101             * @param      name the role's name
102             * @param      titleMap the role's localized titles (optionally
103             *             <code>null</code>)
104             * @param      descriptionMap the role's localized descriptions (optionally
105             *             <code>null</code>)
106             * @param      type the role's type (optionally <code>0</code>)
107             * @return     the role
108             * @throws     PortalException if the class name or the role name were
109             *             invalid, if the role is a duplicate, or if a user with the
110             *             primary key could not be found
111             * @throws     SystemException if a system exception occurred
112             * @deprecated As of 6.2.0, replaced by {@link #addRole(long, String, long,
113             *             String, Map, Map, int, String, ServiceContext)}
114             */
115            @Override
116            public Role addRole(
117                            long userId, long companyId, String name,
118                            Map<Locale, String> titleMap, Map<Locale, String> descriptionMap,
119                            int type)
120                    throws PortalException, SystemException {
121    
122                    return addRole(
123                            userId, null, 0, name, titleMap, descriptionMap, type, null, null);
124            }
125    
126            /**
127             * Adds a role with additional parameters. The user is reindexed after role
128             * is added.
129             *
130             * @param      userId the primary key of the user
131             * @param      companyId the primary key of the company
132             * @param      name the role's name
133             * @param      titleMap the role's localized titles (optionally
134             *             <code>null</code>)
135             * @param      descriptionMap the role's localized descriptions (optionally
136             *             <code>null</code>)
137             * @param      type the role's type (optionally <code>0</code>)
138             * @param      className the name of the class for which the role is created
139             *             (optionally <code>null</code>)
140             * @param      classPK the primary key of the class for which the role is
141             *             created (optionally <code>0</code>)
142             * @return     the role
143             * @throws     PortalException if the class name or the role name were
144             *             invalid, if the role is a duplicate, or if a user with the
145             *             primary key could not be found
146             * @throws     SystemException if a system exception occurred
147             * @deprecated As of 6.2.0, replaced by {@link #addRole(long, String, long,
148             *             String, Map, Map, int, String, ServiceContext)}
149             */
150            @Override
151            public Role addRole(
152                            long userId, long companyId, String name,
153                            Map<Locale, String> titleMap, Map<Locale, String> descriptionMap,
154                            int type, String className, long classPK)
155                    throws PortalException, SystemException {
156    
157                    return addRole(
158                            userId, className, classPK, name, titleMap, descriptionMap, type,
159                            null, null);
160            }
161    
162            /**
163             * Adds a role with additional parameters. The user is reindexed after role
164             * is added.
165             *
166             * @param  userId the primary key of the user
167             * @param  className the name of the class for which the role is created
168             *         (optionally <code>null</code>)
169             * @param  classPK the primary key of the class for which the role is
170             *         created (optionally <code>0</code>)
171             * @param  name the role's name
172             * @param  titleMap the role's localized titles (optionally
173             *         <code>null</code>)
174             * @param  descriptionMap the role's localized descriptions (optionally
175             *         <code>null</code>)
176             * @param  type the role's type (optionally <code>0</code>)
177             * @param  subtype the role's subtype (optionally <code>null</code>)
178             * @param  serviceContext the service context to be applied (optionally
179             *         <code>null</code>). Can set expando bridge attributes for the
180             *         role.
181             * @return the role
182             * @throws PortalException if the class name or the role name were invalid,
183             *         if the role is a duplicate, or if a user with the primary key
184             *         could not be found
185             * @throws SystemException if a system exception occurred
186             */
187            @Override
188            public Role addRole(
189                            long userId, String className, long classPK, String name,
190                            Map<Locale, String> titleMap, Map<Locale, String> descriptionMap,
191                            int type, String subtype, ServiceContext serviceContext)
192                    throws PortalException, SystemException {
193    
194                    // Role
195    
196                    User user = userPersistence.findByPrimaryKey(userId);
197                    className = GetterUtil.getString(className);
198                    long classNameId = PortalUtil.getClassNameId(className);
199    
200                    long roleId = counterLocalService.increment();
201    
202                    if ((classNameId <= 0) || className.equals(Role.class.getName())) {
203                            classNameId = PortalUtil.getClassNameId(Role.class);
204                            classPK = roleId;
205                    }
206    
207                    Date now = new Date();
208    
209                    validate(0, user.getCompanyId(), classNameId, name);
210    
211                    Role role = rolePersistence.create(roleId);
212    
213                    if (serviceContext != null) {
214                            role.setUuid(serviceContext.getUuid());
215                    }
216    
217                    role.setCompanyId(user.getCompanyId());
218                    role.setUserId(user.getUserId());
219                    role.setUserName(user.getFullName());
220    
221                    if (serviceContext != null) {
222                            role.setCreateDate(serviceContext.getCreateDate(now));
223                            role.setModifiedDate(serviceContext.getModifiedDate(now));
224                    }
225                    else {
226                            role.setCreateDate(now);
227                            role.setModifiedDate(now);
228                    }
229    
230                    role.setClassNameId(classNameId);
231                    role.setClassPK(classPK);
232                    role.setName(name);
233                    role.setTitleMap(titleMap);
234                    role.setDescriptionMap(descriptionMap);
235                    role.setType(type);
236                    role.setSubtype(subtype);
237                    role.setExpandoBridgeAttributes(serviceContext);
238    
239                    rolePersistence.update(role);
240    
241                    // Resources
242    
243                    long ownerId = userId;
244    
245                    if (user.isDefaultUser()) {
246                            ownerId = 0;
247                    }
248    
249                    resourceLocalService.addResources(
250                            user.getCompanyId(), 0, ownerId, Role.class.getName(),
251                            role.getRoleId(), false, false, false);
252    
253                    if (!user.isDefaultUser()) {
254                            resourceLocalService.addResources(
255                                    user.getCompanyId(), 0, userId, Role.class.getName(),
256                                    role.getRoleId(), false, false, false);
257    
258                            if (!ExportImportThreadLocal.isImportInProcess()) {
259                                    Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(
260                                            User.class);
261    
262                                    indexer.reindex(userId);
263                            }
264                    }
265    
266                    return role;
267            }
268    
269            /**
270             * Adds the role to the user. The user is reindexed after the role is added.
271             *
272             * @param  userId the primary key of the user
273             * @param  roleId the role
274             * @throws PortalException if a user with the primary key could not be found
275             * @throws SystemException if a system exception occurred
276             * @see    com.liferay.portal.service.persistence.UserPersistence#addRole(
277             *         long, long)
278             */
279            @Override
280            public void addUserRole(long userId, long roleId)
281                    throws PortalException, SystemException {
282    
283                    userPersistence.addRole(userId, roleId);
284    
285                    Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
286    
287                    indexer.reindex(userId);
288    
289                    PermissionCacheUtil.clearCache(userId);
290            }
291    
292            /**
293             * Adds the role to the user. The user is reindexed after the role is added.
294             *
295             * @param  userId the primary key of the user
296             * @param  role the primary key of the role
297             * @throws PortalException if a user with the primary key could not be found
298             * @throws SystemException if a system exception occurred
299             * @see    com.liferay.portal.service.persistence.UserPersistence#addRole(
300             *         long, Role)
301             */
302            @Override
303            public void addUserRole(long userId, Role role)
304                    throws PortalException, SystemException {
305    
306                    userPersistence.addRole(userId, role);
307    
308                    Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
309    
310                    indexer.reindex(userId);
311    
312                    PermissionCacheUtil.clearCache(userId);
313            }
314    
315            /**
316             * Adds the roles to the user. The user is reindexed after the roles are
317             * added.
318             *
319             * @param  userId the primary key of the user
320             * @param  roles the roles
321             * @throws PortalException if a user with the primary key could not be found
322             * @throws SystemException if a system exception occurred
323             * @see    com.liferay.portal.service.persistence.UserPersistence#addRoles(
324             *         long, List)
325             */
326            @Override
327            public void addUserRoles(long userId, List<Role> roles)
328                    throws PortalException, SystemException {
329    
330                    userPersistence.addRoles(userId, roles);
331    
332                    Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
333    
334                    indexer.reindex(userId);
335    
336                    PermissionCacheUtil.clearCache(userId);
337            }
338    
339            /**
340             * Adds the roles to the user. The user is reindexed after the roles are
341             * added.
342             *
343             * @param  userId the primary key of the user
344             * @param  roleIds the primary keys of the roles
345             * @throws PortalException if a user with the primary key could not be found
346             * @throws SystemException if a system exception occurred
347             * @see    com.liferay.portal.service.persistence.UserPersistence#addRoles(
348             *         long, long[])
349             */
350            @Override
351            public void addUserRoles(long userId, long[] roleIds)
352                    throws PortalException, SystemException {
353    
354                    userPersistence.addRoles(userId, roleIds);
355    
356                    Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
357    
358                    indexer.reindex(userId);
359    
360                    PermissionCacheUtil.clearCache(userId);
361            }
362    
363            /**
364             * Checks to ensure that the system roles map has appropriate default roles
365             * in each company.
366             *
367             * @throws PortalException if the current user did not have permission to
368             *         set applicable permissions on a role
369             * @throws SystemException if a system exception occurred
370             */
371            @Override
372            public void checkSystemRoles() throws PortalException, SystemException {
373                    List<Company> companies = companyLocalService.getCompanies();
374    
375                    String currentShardName = ShardUtil.getCurrentShardName();
376    
377                    for (Company company : companies) {
378                            String shardName = null;
379    
380                            try {
381                                    shardName = company.getShardName();
382                            }
383                            catch (NoSuchShardException nsse) {
384                                    Shard shard = shardLocalService.addShard(
385                                            Company.class.getName(), company.getCompanyId(),
386                                            PropsValues.SHARD_DEFAULT_NAME);
387    
388                                    shardName = shard.getName();
389                            }
390    
391                            if (!ShardUtil.isEnabled() || shardName.equals(currentShardName)) {
392                                    checkSystemRoles(company.getCompanyId());
393                            }
394                    }
395            }
396    
397            /**
398             * Checks to ensure that the system roles map has appropriate default roles
399             * in the company.
400             *
401             * @param  companyId the primary key of the company
402             * @throws PortalException if the current user did not have permission to
403             *         set applicable permissions on a role
404             * @throws SystemException if a system exception occurred
405             */
406            @Override
407            @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
408            public void checkSystemRoles(long companyId)
409                    throws PortalException, SystemException {
410    
411                    String companyIdHexString = StringUtil.toHexString(companyId);
412    
413                    List<Role> roles = null;
414    
415                    try {
416                            roles = roleFinder.findBySystem(companyId);
417                    }
418                    catch (Exception e) {
419    
420                            // LPS-34324
421    
422                            DB db = DBFactoryUtil.getDB();
423    
424                            try {
425                                    runSQL(
426                                            db.buildSQL(
427                                                    "alter table Role_ add uuid_ VARCHAR(75) null"));
428                                    runSQL(db.buildSQL("alter table Role_ add userId LONG"));
429                                    runSQL(
430                                            db.buildSQL(
431                                                    "alter table Role_ add userName VARCHAR(75) null"));
432                                    runSQL(
433                                            db.buildSQL("alter table Role_ add createDate DATE null"));
434                                    runSQL(
435                                            db.buildSQL(
436                                                    "alter table Role_ add modifiedDate DATE null"));
437                            }
438                            catch (IOException ioe) {
439                                    throw new SystemException(ioe);
440                            }
441    
442                            roles = roleFinder.findBySystem(companyId);
443                    }
444    
445                    for (Role role : roles) {
446                            _systemRolesMap.put(
447                                    companyIdHexString.concat(role.getName()), role);
448                    }
449    
450                    // Regular roles
451    
452                    String[] systemRoles = PortalUtil.getSystemRoles();
453    
454                    for (String name : systemRoles) {
455                            String key =
456                                    "system.role." +
457                                            StringUtil.replace(name, CharPool.SPACE, CharPool.PERIOD) +
458                                                    ".description";
459    
460                            Map<Locale, String> descriptionMap = new HashMap<Locale, String>();
461    
462                            descriptionMap.put(LocaleUtil.getDefault(), PropsUtil.get(key));
463    
464                            int type = RoleConstants.TYPE_REGULAR;
465    
466                            checkSystemRole(companyId, name, descriptionMap, type);
467                    }
468    
469                    // Organization roles
470    
471                    String[] systemOrganizationRoles =
472                            PortalUtil.getSystemOrganizationRoles();
473    
474                    for (String name : systemOrganizationRoles) {
475                            String key =
476                                    "system.organization.role." +
477                                            StringUtil.replace(name, CharPool.SPACE, CharPool.PERIOD) +
478                                                    ".description";
479    
480                            Map<Locale, String> descriptionMap = new HashMap<Locale, String>();
481    
482                            descriptionMap.put(LocaleUtil.getDefault(), PropsUtil.get(key));
483    
484                            int type = RoleConstants.TYPE_ORGANIZATION;
485    
486                            checkSystemRole(companyId, name, descriptionMap, type);
487                    }
488    
489                    // Site roles
490    
491                    String[] systemSiteRoles = PortalUtil.getSystemSiteRoles();
492    
493                    for (String name : systemSiteRoles) {
494                            String key =
495                                    "system.site.role." +
496                                            StringUtil.replace(name, CharPool.SPACE, CharPool.PERIOD) +
497                                                    ".description";
498    
499                            Map<Locale, String> descriptionMap = new HashMap<Locale, String>();
500    
501                            descriptionMap.put(LocaleUtil.getDefault(), PropsUtil.get(key));
502    
503                            int type = RoleConstants.TYPE_SITE;
504    
505                            checkSystemRole(companyId, name, descriptionMap, type);
506                    }
507    
508                    String[] allSystemRoles = ArrayUtil.append(
509                            systemRoles, systemOrganizationRoles, systemSiteRoles);
510    
511                    for (String roleName : allSystemRoles) {
512                            Role role = getRole(companyId, roleName);
513    
514                            resourceLocalService.addResources(
515                                    companyId, 0, 0, Role.class.getName(), role.getRoleId(), false,
516                                    false, false);
517                    }
518    
519                    // All users should be able to view all system roles
520    
521                    Role userRole = getRole(companyId, RoleConstants.USER);
522    
523                    for (String roleName : allSystemRoles) {
524                            Role role = getRole(companyId, roleName);
525    
526                            resourcePermissionLocalService.setResourcePermissions(
527                                    companyId, Role.class.getName(),
528                                    ResourceConstants.SCOPE_INDIVIDUAL,
529                                    String.valueOf(role.getRoleId()), userRole.getRoleId(),
530                                    new String[] {ActionKeys.VIEW});
531                    }
532            }
533    
534            /**
535             * Removes every role from the user. The user is reindexed after the roles
536             * are removed.
537             *
538             * @param  userId the primary key of the user
539             * @throws PortalException if a user with the primary key could not be found
540             * @throws SystemException if a system exception occurred
541             * @see    com.liferay.portal.service.persistence.UserPersistence#clearRoles(
542             *         long)
543             */
544            @Override
545            public void clearUserRoles(long userId)
546                    throws PortalException, SystemException {
547    
548                    userPersistence.clearRoles(userId);
549    
550                    Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
551    
552                    indexer.reindex(userId);
553    
554                    PermissionCacheUtil.clearCache(userId);
555            }
556    
557            /**
558             * Deletes the role with the primary key and its associated permissions.
559             *
560             * @param  roleId the primary key of the role
561             * @return the deleted role
562             * @throws PortalException if a role with the primary key could not be
563             *         found, if the role is a default system role, or if the role's
564             *         resource could not be found
565             * @throws SystemException if a system exception occurred
566             */
567            @Override
568            public Role deleteRole(long roleId)
569                    throws PortalException, SystemException {
570    
571                    Role role = rolePersistence.findByPrimaryKey(roleId);
572    
573                    return roleLocalService.deleteRole(role);
574            }
575    
576            /**
577             * Deletes the role and its associated permissions.
578             *
579             * @param  role the role
580             * @return the deleted role
581             * @throws PortalException if the role is a default system role or if the
582             *         role's resource could not be found
583             * @throws SystemException if a system exception occurred
584             */
585            @Override
586            @SystemEvent(
587                    action = SystemEventConstants.ACTION_SKIP,
588                    type = SystemEventConstants.TYPE_DELETE)
589            public Role deleteRole(Role role) throws PortalException, SystemException {
590                    if (PortalUtil.isSystemRole(role.getName()) &&
591                            !CompanyThreadLocal.isDeleteInProcess()) {
592    
593                            throw new RequiredRoleException();
594                    }
595    
596                    // Resources
597    
598                    List<ResourceBlockPermission> resourceBlockPermissions =
599                            resourceBlockPermissionPersistence.findByRoleId(role.getRoleId());
600    
601                    for (ResourceBlockPermission resourceBlockPermission :
602                                    resourceBlockPermissions) {
603    
604                            resourceBlockPermissionLocalService.deleteResourceBlockPermission(
605                                    resourceBlockPermission);
606                    }
607    
608                    List<ResourcePermission> resourcePermissions =
609                            resourcePermissionPersistence.findByRoleId(role.getRoleId());
610    
611                    for (ResourcePermission resourcePermission : resourcePermissions) {
612                            resourcePermissionLocalService.deleteResourcePermission(
613                                    resourcePermission);
614                    }
615    
616                    List<ResourceTypePermission> resourceTypePermissions =
617                            resourceTypePermissionPersistence.findByRoleId(role.getRoleId());
618    
619                    for (ResourceTypePermission resourceTypePermission :
620                                    resourceTypePermissions) {
621    
622                            resourceTypePermissionLocalService.deleteResourceTypePermission(
623                                    resourceTypePermission);
624                    }
625    
626                    String className = role.getClassName();
627                    long classNameId = role.getClassNameId();
628    
629                    if ((classNameId <= 0) || className.equals(Role.class.getName())) {
630                            resourceLocalService.deleteResource(
631                                    role.getCompanyId(), Role.class.getName(),
632                                    ResourceConstants.SCOPE_INDIVIDUAL, role.getRoleId());
633                    }
634    
635                    if ((role.getType() == RoleConstants.TYPE_ORGANIZATION) ||
636                            (role.getType() == RoleConstants.TYPE_SITE)) {
637    
638                            userGroupRoleLocalService.deleteUserGroupRolesByRoleId(
639                                    role.getRoleId());
640    
641                            userGroupGroupRoleLocalService.deleteUserGroupGroupRolesByRoleId(
642                                    role.getRoleId());
643                    }
644    
645                    // Role
646    
647                    rolePersistence.remove(role);
648    
649                    // Expando
650    
651                    expandoRowLocalService.deleteRows(role.getRoleId());
652    
653                    // Permission cache
654    
655                    PermissionCacheUtil.clearCache();
656    
657                    return role;
658            }
659    
660            /**
661             * Removes the role from the user. The user is reindexed after the role is
662             * removed.
663             *
664             * @param  userId the primary key of the user
665             * @param  roleId the primary key of the role
666             * @throws PortalException if a user with the primary key could not be found
667             * @throws SystemException if a system exception occurred
668             * @see    com.liferay.portal.service.persistence.UserPersistence#removeRole(
669             *         long, long)
670             */
671            @Override
672            public void deleteUserRole(long userId, long roleId)
673                    throws PortalException, SystemException {
674    
675                    userPersistence.removeRole(userId, roleId);
676    
677                    Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
678    
679                    indexer.reindex(userId);
680    
681                    PermissionCacheUtil.clearCache(userId);
682            }
683    
684            /**
685             * Removes the role from the user. The user is reindexed after the role is
686             * removed.
687             *
688             * @param  userId the primary key of the user
689             * @param  role the role
690             * @throws PortalException if a user with the primary key could not be found
691             * @throws SystemException if a system exception occurred
692             * @see    com.liferay.portal.service.persistence.UserPersistence#removeRole(
693             *         long, Role)
694             */
695            @Override
696            public void deleteUserRole(long userId, Role role)
697                    throws PortalException, SystemException {
698    
699                    userPersistence.removeRole(userId, role);
700    
701                    Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
702    
703                    indexer.reindex(userId);
704    
705                    PermissionCacheUtil.clearCache(userId);
706            }
707    
708            /**
709             * Removes the roles from the user. The user is reindexed after the roles
710             * are removed.
711             *
712             * @param  userId the primary key of the user
713             * @param  roles the roles
714             * @throws PortalException if a user with the primary key could not be found
715             * @throws SystemException if a system exception occurred
716             * @see    com.liferay.portal.service.persistence.UserPersistence#removeRoles(
717             *         long, List)
718             */
719            @Override
720            public void deleteUserRoles(long userId, List<Role> roles)
721                    throws PortalException, SystemException {
722    
723                    userPersistence.removeRoles(userId, roles);
724    
725                    Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
726    
727                    indexer.reindex(userId);
728    
729                    PermissionCacheUtil.clearCache(userId);
730            }
731    
732            /**
733             * Removes the roles from the user. The user is reindexed after the roles
734             * are removed.
735             *
736             * @param  userId the primary key of the user
737             * @param  roleIds the primary keys of the roles
738             * @throws PortalException if a user with the primary key could not be found
739             * @throws SystemException if a system exception occurred
740             * @see    com.liferay.portal.service.persistence.UserPersistence#removeRoles(
741             *         long, long[])
742             */
743            @Override
744            public void deleteUserRoles(long userId, long[] roleIds)
745                    throws PortalException, SystemException {
746    
747                    userPersistence.removeRoles(userId, roleIds);
748    
749                    Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
750    
751                    indexer.reindex(userId);
752    
753                    PermissionCacheUtil.clearCache(userId);
754            }
755    
756            /**
757             * Returns the role with the name in the company.
758             *
759             * <p>
760             * The method searches the system roles map first for default roles. If a
761             * role with the name is not found, then the method will query the database.
762             * </p>
763             *
764             * @param  companyId the primary key of the company
765             * @param  name the role's name
766             * @return Returns the role with the name or <code>null</code> if a role
767             *         with the name could not be found in the company
768             * @throws SystemException if a system exception occurred
769             */
770            @Override
771            @Skip
772            public Role fetchRole(long companyId, String name) throws SystemException {
773                    String companyIdHexString = StringUtil.toHexString(companyId);
774    
775                    Role role = _systemRolesMap.get(companyIdHexString.concat(name));
776    
777                    if (role != null) {
778                            return role;
779                    }
780    
781                    return roleLocalService.loadFetchRole(companyId, name);
782            }
783    
784            /**
785             * Returns the default role for the group with the primary key.
786             *
787             * <p>
788             * If the group is a site, then the default role is {@link
789             * com.liferay.portal.model.RoleConstants#SITE_MEMBER}. If the group is an
790             * organization, then the default role is {@link
791             * com.liferay.portal.model.RoleConstants#ORGANIZATION_USER}. If the group
792             * is a user or user group, then the default role is {@link
793             * com.liferay.portal.model.RoleConstants#POWER_USER}. For all other group
794             * types, the default role is {@link
795             * com.liferay.portal.model.RoleConstants#USER}.
796             * </p>
797             *
798             * @param  groupId the primary key of the group
799             * @return the default role for the group with the primary key
800             * @throws PortalException if a group with the primary key could not be
801             *         found, or if a default role could not be found for the group
802             * @throws SystemException if a system exception occurred
803             */
804            @Override
805            public Role getDefaultGroupRole(long groupId)
806                    throws PortalException, SystemException {
807    
808                    Group group = groupPersistence.findByPrimaryKey(groupId);
809    
810                    if (group.isLayout()) {
811                            Layout layout = layoutLocalService.getLayout(group.getClassPK());
812    
813                            group = layout.getGroup();
814                    }
815    
816                    if (group.isStagingGroup()) {
817                            group = group.getLiveGroup();
818                    }
819    
820                    Role role = null;
821    
822                    if (group.isCompany()) {
823                            role = getRole(group.getCompanyId(), RoleConstants.USER);
824                    }
825                    else if (group.isLayoutPrototype() || group.isLayoutSetPrototype() ||
826                                     group.isRegularSite() || group.isSite()) {
827    
828                            role = getRole(group.getCompanyId(), RoleConstants.SITE_MEMBER);
829                    }
830                    else if (group.isOrganization()) {
831                            role = getRole(
832                                    group.getCompanyId(), RoleConstants.ORGANIZATION_USER);
833                    }
834                    else {
835                            role = getRole(group.getCompanyId(), RoleConstants.USER);
836                    }
837    
838                    return role;
839            }
840    
841            @Override
842            public List<Role> getGroupRelatedRoles(long groupId)
843                    throws PortalException, SystemException {
844    
845                    List<Role> roles = new ArrayList<Role>();
846    
847                    Group group = groupLocalService.getGroup(groupId);
848    
849                    if (group.isStagingGroup()) {
850                            group = group.getLiveGroup();
851                    }
852    
853                    int[] types = RoleConstants.TYPES_REGULAR;
854    
855                    if (group.isOrganization()) {
856                            types = RoleConstants.TYPES_ORGANIZATION_AND_REGULAR;
857                    }
858                    else if (group.isLayout() || group.isLayoutSetPrototype() ||
859                                     group.isSite() || group.isUser()) {
860    
861                            types = RoleConstants.TYPES_REGULAR_AND_SITE;
862                    }
863    
864                    roles.addAll(getRoles(group.getCompanyId(), types));
865    
866                    roles.addAll(getTeamRoles(groupId));
867    
868                    return roles;
869            }
870    
871            @Override
872            public List<Role> getResourceBlockRoles(
873                            long resourceBlockId, String className, String actionId)
874                    throws SystemException {
875    
876                    return roleFinder.findByR_N_A(resourceBlockId, className, actionId);
877            }
878    
879            /**
880             * Returns a map of role names to associated action IDs for the named
881             * resource in the company within the permission scope.
882             *
883             * @param  companyId the primary key of the company
884             * @param  name the resource name
885             * @param  scope the permission scope
886             * @param  primKey the primary key of the resource's class
887             * @return the role names and action IDs
888             * @throws SystemException if a system exception occurred
889             * @see    com.liferay.portal.service.persistence.RoleFinder#findByC_N_S_P(
890             *         long, String, int, String)
891             */
892            @Override
893            public Map<String, List<String>> getResourceRoles(
894                            long companyId, String name, int scope, String primKey)
895                    throws SystemException {
896    
897                    return roleFinder.findByC_N_S_P(companyId, name, scope, primKey);
898            }
899    
900            /**
901             * Returns all the roles associated with the action ID in the company within
902             * the permission scope.
903             *
904             * @param  companyId the primary key of the company
905             * @param  name the resource name
906             * @param  scope the permission scope
907             * @param  primKey the primary key of the resource's class
908             * @param  actionId the name of the resource action
909             * @return the roles
910             * @throws SystemException if a system exception occurred
911             * @see    com.liferay.portal.service.persistence.RoleFinder#findByC_N_S_P_A(
912             *         long, String, int, String, String)
913             */
914            @Override
915            public List<Role> getResourceRoles(
916                            long companyId, String name, int scope, String primKey,
917                            String actionId)
918                    throws SystemException {
919    
920                    return roleFinder.findByC_N_S_P_A(
921                            companyId, name, scope, primKey, actionId);
922            }
923    
924            /**
925             * Returns the role with the name in the company.
926             *
927             * <p>
928             * The method searches the system roles map first for default roles. If a
929             * role with the name is not found, then the method will query the database.
930             * </p>
931             *
932             * @param  companyId the primary key of the company
933             * @param  name the role's name
934             * @return the role with the name
935             * @throws PortalException if a role with the name could not be found in the
936             *         company
937             * @throws SystemException if a system exception occurred
938             */
939            @Override
940            @Skip
941            public Role getRole(long companyId, String name)
942                    throws PortalException, SystemException {
943    
944                    String companyIdHexString = StringUtil.toHexString(companyId);
945    
946                    Role role = _systemRolesMap.get(companyIdHexString.concat(name));
947    
948                    if (role != null) {
949                            return role;
950                    }
951    
952                    return roleLocalService.loadGetRole(companyId, name);
953            }
954    
955            /**
956             * Returns all the roles of the type and subtype.
957             *
958             * @param  type the role's type (optionally <code>0</code>)
959             * @param  subtype the role's subtype (optionally <code>null</code>)
960             * @return the roles of the type and subtype
961             * @throws SystemException if a system exception occurred
962             */
963            @Override
964            public List<Role> getRoles(int type, String subtype)
965                    throws SystemException {
966    
967                    return rolePersistence.findByT_S(type, subtype);
968            }
969    
970            /**
971             * Returns all the roles in the company.
972             *
973             * @param  companyId the primary key of the company
974             * @return the roles in the company
975             * @throws SystemException if a system exception occurred
976             */
977            @Override
978            public List<Role> getRoles(long companyId) throws SystemException {
979                    return rolePersistence.findByCompanyId(companyId);
980            }
981    
982            /**
983             * Returns all the roles with the types.
984             *
985             * @param  companyId the primary key of the company
986             * @param  types the role types (optionally <code>null</code>)
987             * @return the roles with the types
988             * @throws SystemException if a system exception occurred
989             */
990            @Override
991            public List<Role> getRoles(long companyId, int[] types)
992                    throws SystemException {
993    
994                    return rolePersistence.findByC_T(companyId, types);
995            }
996    
997            /**
998             * Returns all the roles with the primary keys.
999             *
1000             * @param  roleIds the primary keys of the roles
1001             * @return the roles with the primary keys
1002             * @throws PortalException if any one of the roles with the primary keys
1003             *         could not be found
1004             * @throws SystemException if a system exception occurred
1005             */
1006            @Override
1007            public List<Role> getRoles(long[] roleIds)
1008                    throws PortalException, SystemException {
1009    
1010                    List<Role> roles = new ArrayList<Role>(roleIds.length);
1011    
1012                    for (long roleId : roleIds) {
1013                            Role role = getRole(roleId);
1014    
1015                            roles.add(role);
1016                    }
1017    
1018                    return roles;
1019            }
1020    
1021            /**
1022             * Returns all the roles of the subtype.
1023             *
1024             * @param  subtype the role's subtype (optionally <code>null</code>)
1025             * @return the roles of the subtype
1026             * @throws SystemException if a system exception occurred
1027             */
1028            @Override
1029            public List<Role> getSubtypeRoles(String subtype) throws SystemException {
1030                    return rolePersistence.findBySubtype(subtype);
1031            }
1032    
1033            /**
1034             * Returns the number of roles of the subtype.
1035             *
1036             * @param  subtype the role's subtype (optionally <code>null</code>)
1037             * @return the number of roles of the subtype
1038             * @throws SystemException if a system exception occurred
1039             */
1040            @Override
1041            public int getSubtypeRolesCount(String subtype) throws SystemException {
1042                    return rolePersistence.countBySubtype(subtype);
1043            }
1044    
1045            /**
1046             * Returns the team role in the company.
1047             *
1048             * @param  companyId the primary key of the company
1049             * @param  teamId the primary key of the team
1050             * @return the team role in the company
1051             * @throws PortalException if a role could not be found in the team and
1052             *         company
1053             * @throws SystemException if a system exception occurred
1054             */
1055            @Override
1056            public Role getTeamRole(long companyId, long teamId)
1057                    throws PortalException, SystemException {
1058    
1059                    long classNameId = PortalUtil.getClassNameId(Team.class);
1060    
1061                    return rolePersistence.findByC_C_C(companyId, classNameId, teamId);
1062            }
1063    
1064            /**
1065             * Returns the team role map for the group.
1066             *
1067             * @param  groupId the primary key of the group
1068             * @return the team role map for the group
1069             * @throws PortalException if a group with the primary key could not be
1070             *         found, if a role could not be found in one of the group's teams,
1071             *         or if a portal exception occurred
1072             * @throws SystemException if a system exception occurred
1073             */
1074            @Override
1075            public Map<Team, Role> getTeamRoleMap(long groupId)
1076                    throws PortalException, SystemException {
1077    
1078                    return getTeamRoleMap(groupId, null);
1079            }
1080    
1081            /**
1082             * Returns the team roles in the group.
1083             *
1084             * @param  groupId the primary key of the group
1085             * @return the team roles in the group
1086             * @throws PortalException if a group with the primary key could not be
1087             *         found, if a role could not be found in one of the group's teams,
1088             *         or if a portal exception occurred
1089             * @throws SystemException if a system exception occurred
1090             */
1091            @Override
1092            public List<Role> getTeamRoles(long groupId)
1093                    throws PortalException, SystemException {
1094    
1095                    return getTeamRoles(groupId, null);
1096            }
1097    
1098            /**
1099             * Returns the team roles in the group, excluding the specified role IDs.
1100             *
1101             * @param  groupId the primary key of the group
1102             * @param  excludedRoleIds the primary keys of the roles to exclude
1103             *         (optionally <code>null</code>)
1104             * @return the team roles in the group, excluding the specified role IDs
1105             * @throws PortalException if a group with the primary key could not be
1106             *         found, if a role could not be found in one of the group's teams,
1107             *         or if a portal exception occurred
1108             * @throws SystemException if a system exception occurred
1109             */
1110            @Override
1111            public List<Role> getTeamRoles(long groupId, long[] excludedRoleIds)
1112                    throws PortalException, SystemException {
1113    
1114                    Map<Team, Role> teamRoleMap = getTeamRoleMap(groupId, excludedRoleIds);
1115    
1116                    Collection<Role> roles = teamRoleMap.values();
1117    
1118                    return ListUtil.fromCollection(roles);
1119            }
1120    
1121            /**
1122             * Returns all the roles of the type.
1123             *
1124             * @param  type the role's type (optionally <code>0</code>)
1125             * @return the range of the roles of the type
1126             * @throws SystemException if a system exception occurred
1127             */
1128            @Override
1129            public List<Role> getTypeRoles(int type) throws SystemException {
1130                    return rolePersistence.findByType(type);
1131            }
1132    
1133            /**
1134             * Returns a range of all the roles of the type.
1135             *
1136             * @param  type the role's type (optionally <code>0</code>)
1137             * @param  start the lower bound of the range of roles to return
1138             * @param  end the upper bound of the range of roles to return (not
1139             *         inclusive)
1140             * @return the range of the roles of the type
1141             * @throws SystemException if a system exception occurred
1142             */
1143            @Override
1144            public List<Role> getTypeRoles(int type, int start, int end)
1145                    throws SystemException {
1146    
1147                    return rolePersistence.findByType(type, start, end);
1148            }
1149    
1150            /**
1151             * Returns the number of roles of the type.
1152             *
1153             * @param  type the role's type (optionally <code>0</code>)
1154             * @return the number of roles of the type
1155             * @throws SystemException if a system exception occurred
1156             */
1157            @Override
1158            public int getTypeRolesCount(int type) throws SystemException {
1159                    return rolePersistence.countByType(type);
1160            }
1161    
1162            /**
1163             * Returns all the user's roles within the user group.
1164             *
1165             * @param  userId the primary key of the user
1166             * @param  groupId the primary key of the group
1167             * @return the user's roles within the user group
1168             * @throws SystemException if a system exception occurred
1169             * @see    com.liferay.portal.service.persistence.RoleFinder#findByUserGroupGroupRole(
1170             *         long, long)
1171             */
1172            @Override
1173            public List<Role> getUserGroupGroupRoles(long userId, long groupId)
1174                    throws SystemException {
1175    
1176                    return roleFinder.findByUserGroupGroupRole(userId, groupId);
1177            }
1178    
1179            @Override
1180            public List<Role> getUserGroupGroupRoles(
1181                            long userId, long groupId, int start, int end)
1182                    throws SystemException {
1183    
1184                    return roleFinder.findByUserGroupGroupRole(userId, groupId, start, end);
1185            }
1186    
1187            @Override
1188            public int getUserGroupGroupRolesCount(long userId, long groupId)
1189                    throws SystemException {
1190    
1191                    return roleFinder.countByUserGroupGroupRole(userId, groupId);
1192            }
1193    
1194            /**
1195             * Returns all the user's roles within the user group.
1196             *
1197             * @param  userId the primary key of the user
1198             * @param  groupId the primary key of the group
1199             * @return the user's roles within the user group
1200             * @throws SystemException if a system exception occurred
1201             * @see    com.liferay.portal.service.persistence.RoleFinder#findByUserGroupRole(
1202             *         long, long)
1203             */
1204            @Override
1205            public List<Role> getUserGroupRoles(long userId, long groupId)
1206                    throws SystemException {
1207    
1208                    return roleFinder.findByUserGroupRole(userId, groupId);
1209            }
1210    
1211            /**
1212             * Returns the union of all the user's roles within the groups.
1213             *
1214             * @param  userId the primary key of the user
1215             * @param  groups the groups (optionally <code>null</code>)
1216             * @return the union of all the user's roles within the groups
1217             * @throws SystemException if a system exception occurred
1218             * @see    com.liferay.portal.service.persistence.RoleFinder#findByU_G(
1219             *         long, List)
1220             */
1221            @Override
1222            public List<Role> getUserRelatedRoles(long userId, List<Group> groups)
1223                    throws SystemException {
1224    
1225                    if ((groups == null) || groups.isEmpty()) {
1226                            return Collections.emptyList();
1227                    }
1228    
1229                    return roleFinder.findByU_G(userId, groups);
1230            }
1231    
1232            /**
1233             * Returns all the user's roles within the group.
1234             *
1235             * @param  userId the primary key of the user
1236             * @param  groupId the primary key of the group
1237             * @return the user's roles within the group
1238             * @throws SystemException if a system exception occurred
1239             * @see    com.liferay.portal.service.persistence.RoleFinder#findByU_G(
1240             *         long, long)
1241             */
1242            @Override
1243            public List<Role> getUserRelatedRoles(long userId, long groupId)
1244                    throws SystemException {
1245    
1246                    return roleFinder.findByU_G(userId, groupId);
1247            }
1248    
1249            /**
1250             * Returns the union of all the user's roles within the groups.
1251             *
1252             * @param  userId the primary key of the user
1253             * @param  groupIds the primary keys of the groups
1254             * @return the union of all the user's roles within the groups
1255             * @throws SystemException if a system exception occurred
1256             * @see    com.liferay.portal.service.persistence.RoleFinder#findByU_G(
1257             *         long, long[])
1258             */
1259            @Override
1260            public List<Role> getUserRelatedRoles(long userId, long[] groupIds)
1261                    throws SystemException {
1262    
1263                    return roleFinder.findByU_G(userId, groupIds);
1264            }
1265    
1266            /**
1267             * Returns <code>true</code> if the user is associated with the named
1268             * regular role.
1269             *
1270             * @param  userId the primary key of the user
1271             * @param  companyId the primary key of the company
1272             * @param  name the name of the role
1273             * @param  inherited whether to include the user's inherited roles in the
1274             *         search
1275             * @return <code>true</code> if the user is associated with the regular
1276             *         role; <code>false</code> otherwise
1277             * @throws PortalException if a default user for the company could not be
1278             *         found
1279             * @throws SystemException if a system exception occurred
1280             */
1281            @Override
1282            @ThreadLocalCachable
1283            public boolean hasUserRole(
1284                            long userId, long companyId, String name, boolean inherited)
1285                    throws PortalException, SystemException {
1286    
1287                    Role role = rolePersistence.fetchByC_N(companyId, name);
1288    
1289                    if (role == null) {
1290                            return false;
1291                    }
1292    
1293                    if (role.getType() != RoleConstants.TYPE_REGULAR) {
1294                            throw new IllegalArgumentException(name + " is not a regular role");
1295                    }
1296    
1297                    long defaultUserId = userLocalService.getDefaultUserId(companyId);
1298    
1299                    if (userId == defaultUserId) {
1300                            if (name.equals(RoleConstants.GUEST)) {
1301                                    return true;
1302                            }
1303                            else {
1304                                    return false;
1305                            }
1306                    }
1307    
1308                    if (inherited) {
1309                            if (userPersistence.containsRole(userId, role.getRoleId())) {
1310                                    return true;
1311                            }
1312    
1313                            ThreadLocalCache<Boolean> threadLocalCache =
1314                                    ThreadLocalCacheManager.getThreadLocalCache(
1315                                            Lifecycle.REQUEST, RoleLocalServiceImpl.class.getName());
1316    
1317                            String key = String.valueOf(role.getRoleId()).concat(
1318                                    String.valueOf(userId));
1319    
1320                            Boolean value = threadLocalCache.get(key);
1321    
1322                            if (value != null) {
1323                                    return value;
1324                            }
1325    
1326                            value = PermissionCacheUtil.getUserRole(userId, role);
1327    
1328                            if (value == null) {
1329                                    int count = roleFinder.countByR_U(role.getRoleId(), userId);
1330    
1331                                    if (count > 0) {
1332                                            value = true;
1333                                    }
1334                                    else {
1335                                            value = false;
1336                                    }
1337    
1338                                    PermissionCacheUtil.putUserRole(userId, role, value);
1339                            }
1340    
1341                            threadLocalCache.put(key, value);
1342    
1343                            return value;
1344                    }
1345                    else {
1346                            return userPersistence.containsRole(userId, role.getRoleId());
1347                    }
1348            }
1349    
1350            /**
1351             * Returns <code>true</code> if the user has any one of the named regular
1352             * roles.
1353             *
1354             * @param  userId the primary key of the user
1355             * @param  companyId the primary key of the company
1356             * @param  names the names of the roles
1357             * @param  inherited whether to include the user's inherited roles in the
1358             *         search
1359             * @return <code>true</code> if the user has any one of the regular roles;
1360             *         <code>false</code> otherwise
1361             * @throws PortalException if any one of the roles with the names could not
1362             *         be found in the company or if the default user for the company
1363             *         could not be found
1364             * @throws SystemException if a system exception occurred
1365             */
1366            @Override
1367            public boolean hasUserRoles(
1368                            long userId, long companyId, String[] names, boolean inherited)
1369                    throws PortalException, SystemException {
1370    
1371                    for (String name : names) {
1372                            if (hasUserRole(userId, companyId, name, inherited)) {
1373                                    return true;
1374                            }
1375                    }
1376    
1377                    return false;
1378            }
1379    
1380            /**
1381             * Returns a role with the name in the company.
1382             *
1383             * @param  companyId the primary key of the company
1384             * @param  name the role's name (optionally <code>null</code>)
1385             * @return the role with the name, or <code>null</code> if a role with the
1386             *         name could not be found in the company
1387             * @throws SystemException if a system exception occurred
1388             */
1389            @Override
1390            public Role loadFetchRole(long companyId, String name)
1391                    throws SystemException {
1392    
1393                    return rolePersistence.fetchByC_N(companyId, name);
1394            }
1395    
1396            /**
1397             * Returns a role with the name in the company.
1398             *
1399             * @param  companyId the primary key of the company
1400             * @param  name the role's name
1401             * @return the role with the name in the company
1402             * @throws PortalException if a role with the name could not be found in the
1403             *         company
1404             * @throws SystemException if a system exception occurred
1405             */
1406            @Override
1407            public Role loadGetRole(long companyId, String name)
1408                    throws PortalException, SystemException {
1409    
1410                    return rolePersistence.findByC_N(companyId, name);
1411            }
1412    
1413            /**
1414             * Returns an ordered range of all the roles that match the keywords and
1415             * types.
1416             *
1417             * <p>
1418             * Useful when paginating results. Returns a maximum of <code>end -
1419             * start</code> instances. <code>start</code> and <code>end</code> are not
1420             * primary keys, they are indexes in the result set. Thus, <code>0</code>
1421             * refers to the first result in the set. Setting both <code>start</code>
1422             * and <code>end</code> to {@link
1423             * com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full
1424             * result set.
1425             * </p>
1426             *
1427             * @param  companyId the primary key of the company
1428             * @param  keywords the keywords (space separated), which may occur in the
1429             *         role's name or description (optionally <code>null</code>)
1430             * @param  types the role types (optionally <code>null</code>)
1431             * @param  start the lower bound of the range of roles to return
1432             * @param  end the upper bound of the range of roles to return (not
1433             *         inclusive)
1434             * @param  obc the comparator to order the roles (optionally
1435             *         <code>null</code>)
1436             * @return the ordered range of the matching roles, ordered by
1437             *         <code>obc</code>
1438             * @throws SystemException if a system exception occurred
1439             * @see    com.liferay.portal.service.persistence.RoleFinder
1440             */
1441            @Override
1442            public List<Role> search(
1443                            long companyId, String keywords, Integer[] types, int start,
1444                            int end, OrderByComparator obc)
1445                    throws SystemException {
1446    
1447                    return search(
1448                            companyId, keywords, types, new LinkedHashMap<String, Object>(),
1449                            start, end, obc);
1450            }
1451    
1452            /**
1453             * Returns an ordered range of all the roles that match the keywords, types,
1454             * and params.
1455             *
1456             * <p>
1457             * Useful when paginating results. Returns a maximum of <code>end -
1458             * start</code> instances. <code>start</code> and <code>end</code> are not
1459             * primary keys, they are indexes in the result set. Thus, <code>0</code>
1460             * refers to the first result in the set. Setting both <code>start</code>
1461             * and <code>end</code> to {@link
1462             * com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full
1463             * result set.
1464             * </p>
1465             *
1466             * @param  companyId the primary key of the company
1467             * @param  keywords the keywords (space separated), which may occur in the
1468             *         role's name or description (optionally <code>null</code>)
1469             * @param  types the role types (optionally <code>null</code>)
1470             * @param  params the finder parameters. Can specify values for the
1471             *         "usersRoles" key. For more information, see {@link
1472             *         com.liferay.portal.service.persistence.RoleFinder}
1473             * @param  start the lower bound of the range of roles to return
1474             * @param  end the upper bound of the range of roles to return (not
1475             *         inclusive)
1476             * @param  obc the comparator to order the roles (optionally
1477             *         <code>null</code>)
1478             * @return the ordered range of the matching roles, ordered by
1479             *         <code>obc</code>
1480             * @throws SystemException if a system exception occurred
1481             * @see    com.liferay.portal.service.persistence.RoleFinder
1482             */
1483            @Override
1484            public List<Role> search(
1485                            long companyId, String keywords, Integer[] types,
1486                            LinkedHashMap<String, Object> params, int start, int end,
1487                            OrderByComparator obc)
1488                    throws SystemException {
1489    
1490                    return roleFinder.findByKeywords(
1491                            companyId, keywords, types, params, start, end, obc);
1492            }
1493    
1494            /**
1495             * Returns an ordered range of all the roles that match the name,
1496             * description, and types.
1497             *
1498             * <p>
1499             * Useful when paginating results. Returns a maximum of <code>end -
1500             * start</code> instances. <code>start</code> and <code>end</code> are not
1501             * primary keys, they are indexes in the result set. Thus, <code>0</code>
1502             * refers to the first result in the set. Setting both <code>start</code>
1503             * and <code>end</code> to {@link
1504             * com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full
1505             * result set.
1506             * </p>
1507             *
1508             * @param  companyId the primary key of the company
1509             * @param  name the role's name (optionally <code>null</code>)
1510             * @param  description the role's description (optionally <code>null</code>)
1511             * @param  types the role types (optionally <code>null</code>)
1512             * @param  start the lower bound of the range of the roles to return
1513             * @param  end the upper bound of the range of the roles to return (not
1514             *         inclusive)
1515             * @param  obc the comparator to order the roles (optionally
1516             *         <code>null</code>)
1517             * @return the ordered range of the matching roles, ordered by
1518             *         <code>obc</code>
1519             * @throws SystemException if a system exception occurred
1520             * @see    com.liferay.portal.service.persistence.RoleFinder
1521             */
1522            @Override
1523            public List<Role> search(
1524                            long companyId, String name, String description, Integer[] types,
1525                            int start, int end, OrderByComparator obc)
1526                    throws SystemException {
1527    
1528                    return search(
1529                            companyId, name, description, types,
1530                            new LinkedHashMap<String, Object>(), start, end, obc);
1531            }
1532    
1533            /**
1534             * Returns an ordered range of all the roles that match the name,
1535             * description, types, and params.
1536             *
1537             * <p>
1538             * Useful when paginating results. Returns a maximum of <code>end -
1539             * start</code> instances. <code>start</code> and <code>end</code> are not
1540             * primary keys, they are indexes in the result set. Thus, <code>0</code>
1541             * refers to the first result in the set. Setting both <code>start</code>
1542             * and <code>end</code> to {@link
1543             * com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full
1544             * result set.
1545             * </p>
1546             *
1547             * @param  companyId the primary key of the company
1548             * @param  name the role's name (optionally <code>null</code>)
1549             * @param  description the role's description (optionally <code>null</code>)
1550             * @param  types the role types (optionally <code>null</code>)
1551             * @param  params the finder's parameters. Can specify values for the
1552             *         "usersRoles" key. For more information, see {@link
1553             *         com.liferay.portal.service.persistence.RoleFinder}
1554             * @param  start the lower bound of the range of the roles to return
1555             * @param  end the upper bound of the range of the roles to return (not
1556             *         inclusive)
1557             * @param  obc the comparator to order the roles (optionally
1558             *         <code>null</code>)
1559             * @return the ordered range of the matching roles, ordered by
1560             *         <code>obc</code>
1561             * @throws SystemException if a system exception occurred
1562             * @see    com.liferay.portal.service.persistence.RoleFinder
1563             */
1564            @Override
1565            public List<Role> search(
1566                            long companyId, String name, String description, Integer[] types,
1567                            LinkedHashMap<String, Object> params, int start, int end,
1568                            OrderByComparator obc)
1569                    throws SystemException {
1570    
1571                    return roleFinder.findByC_N_D_T(
1572                            companyId, name, description, types, params, true, start, end, obc);
1573            }
1574    
1575            /**
1576             * Returns the number of roles that match the keywords and types.
1577             *
1578             * @param  companyId the primary key of the company
1579             * @param  keywords the keywords (space separated), which may occur in the
1580             *         role's name or description (optionally <code>null</code>)
1581             * @param  types the role types (optionally <code>null</code>)
1582             * @return the number of matching roles
1583             * @throws SystemException if a system exception occurred
1584             */
1585            @Override
1586            public int searchCount(long companyId, String keywords, Integer[] types)
1587                    throws SystemException {
1588    
1589                    return searchCount(
1590                            companyId, keywords, types, new LinkedHashMap<String, Object>());
1591            }
1592    
1593            /**
1594             * Returns the number of roles that match the keywords, types and params.
1595             *
1596             * @param  companyId the primary key of the company
1597             * @param  keywords the keywords (space separated), which may occur in the
1598             *         role's name or description (optionally <code>null</code>)
1599             * @param  types the role types (optionally <code>null</code>)
1600             * @param  params the finder parameters. For more information, see {@link
1601             *         com.liferay.portal.service.persistence.RoleFinder}
1602             * @return the number of matching roles
1603             * @throws SystemException if a system exception occurred
1604             */
1605            @Override
1606            public int searchCount(
1607                            long companyId, String keywords, Integer[] types,
1608                            LinkedHashMap<String, Object> params)
1609                    throws SystemException {
1610    
1611                    return roleFinder.countByKeywords(companyId, keywords, types, params);
1612            }
1613    
1614            /**
1615             * Returns the number of roles that match the name, description, and types.
1616             *
1617             * @param  companyId the primary key of the company
1618             * @param  name the role's name (optionally <code>null</code>)
1619             * @param  description the role's description (optionally <code>null</code>)
1620             * @param  types the role types (optionally <code>null</code>)
1621             * @return the number of matching roles
1622             * @throws SystemException if a system exception occurred
1623             */
1624            @Override
1625            public int searchCount(
1626                            long companyId, String name, String description, Integer[] types)
1627                    throws SystemException {
1628    
1629                    return searchCount(
1630                            companyId, name, description, types,
1631                            new LinkedHashMap<String, Object>());
1632            }
1633    
1634            /**
1635             * Returns the number of roles that match the name, description, types, and
1636             * params.
1637             *
1638             * @param  companyId the primary key of the company
1639             * @param  name the role's name (optionally <code>null</code>)
1640             * @param  description the role's description (optionally <code>null</code>)
1641             * @param  types the role types (optionally <code>null</code>)
1642             * @param  params the finder parameters. Can specify values for the
1643             *         "usersRoles" key. For more information, see {@link
1644             *         com.liferay.portal.service.persistence.RoleFinder}
1645             * @return the number of matching roles
1646             * @throws SystemException if a system exception occurred
1647             */
1648            @Override
1649            public int searchCount(
1650                            long companyId, String name, String description, Integer[] types,
1651                            LinkedHashMap<String, Object> params)
1652                    throws SystemException {
1653    
1654                    return roleFinder.countByC_N_D_T(
1655                            companyId, name, description, types, params, true);
1656            }
1657    
1658            /**
1659             * Sets the roles associated with the user, replacing the user's existing
1660             * roles. The user is reindexed after the roles are set.
1661             *
1662             * @param  userId the primary key of the user
1663             * @param  roleIds the primary keys of the roles
1664             * @throws PortalException if a user with the primary could not be found or
1665             *         if any one of the roles with the primary keys could not be found
1666             * @throws SystemException if a system exception occurred
1667             */
1668            @Override
1669            public void setUserRoles(long userId, long[] roleIds)
1670                    throws PortalException, SystemException {
1671    
1672                    roleIds = UsersAdminUtil.addRequiredRoles(userId, roleIds);
1673    
1674                    userPersistence.setRoles(userId, roleIds);
1675    
1676                    Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
1677    
1678                    indexer.reindex(userId);
1679    
1680                    PermissionCacheUtil.clearCache(userId);
1681            }
1682    
1683            /**
1684             * Removes the matching roles associated with the user. The user is
1685             * reindexed after the roles are removed.
1686             *
1687             * @param  userId the primary key of the user
1688             * @param  roleIds the primary keys of the roles
1689             * @throws PortalException if a user with the primary key could not be found
1690             *         or if a role with any one of the primary keys could not be found
1691             * @throws SystemException if a system exception occurred
1692             */
1693            @Override
1694            public void unsetUserRoles(long userId, long[] roleIds)
1695                    throws PortalException, SystemException {
1696    
1697                    roleIds = UsersAdminUtil.removeRequiredRoles(userId, roleIds);
1698    
1699                    userPersistence.removeRoles(userId, roleIds);
1700    
1701                    Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
1702    
1703                    indexer.reindex(userId);
1704    
1705                    PermissionCacheUtil.clearCache(userId);
1706            }
1707    
1708            /**
1709             * Updates the role with the primary key.
1710             *
1711             * @param  roleId the primary key of the role
1712             * @param  name the role's new name
1713             * @param  titleMap the new localized titles (optionally <code>null</code>)
1714             *         to replace those existing for the role
1715             * @param  descriptionMap the new localized descriptions (optionally
1716             *         <code>null</code>) to replace those existing for the role
1717             * @param  subtype the role's new subtype (optionally <code>null</code>)
1718             * @param  serviceContext the service context to be applied (optionally
1719             *         <code>null</code>). Can set expando bridge attributes for the
1720             *         role.
1721             * @return the role with the primary key
1722             * @throws PortalException if a role with the primary could not be found or
1723             *         if the role's name was invalid
1724             * @throws SystemException if a system exception occurred
1725             */
1726            @Override
1727            public Role updateRole(
1728                            long roleId, String name, Map<Locale, String> titleMap,
1729                            Map<Locale, String> descriptionMap, String subtype,
1730                            ServiceContext serviceContext)
1731                    throws PortalException, SystemException {
1732    
1733                    Role role = rolePersistence.findByPrimaryKey(roleId);
1734    
1735                    validate(roleId, role.getCompanyId(), role.getClassNameId(), name);
1736    
1737                    if (PortalUtil.isSystemRole(role.getName())) {
1738                            name = role.getName();
1739                            subtype = null;
1740                    }
1741    
1742                    role.setModifiedDate(new Date());
1743                    role.setName(name);
1744                    role.setTitleMap(titleMap);
1745                    role.setDescriptionMap(descriptionMap);
1746                    role.setSubtype(subtype);
1747                    role.setExpandoBridgeAttributes(serviceContext);
1748    
1749                    rolePersistence.update(role);
1750    
1751                    return role;
1752            }
1753    
1754            protected void checkSystemRole(
1755                            long companyId, String name, Map<Locale, String> descriptionMap,
1756                            int type)
1757                    throws PortalException, SystemException {
1758    
1759                    String companyIdHexString = StringUtil.toHexString(companyId);
1760    
1761                    String key = companyIdHexString.concat(name);
1762    
1763                    Role role = _systemRolesMap.get(key);
1764    
1765                    try {
1766                            if (role == null) {
1767                                    role = rolePersistence.findByC_N(companyId, name);
1768                            }
1769    
1770                            if (!descriptionMap.equals(role.getDescriptionMap())) {
1771                                    role.setDescriptionMap(descriptionMap);
1772    
1773                                    roleLocalService.updateRole(role);
1774                            }
1775                    }
1776                    catch (NoSuchRoleException nsre) {
1777                            User user = userLocalService.getDefaultUser(companyId);
1778    
1779                            PermissionThreadLocal.setAddResource(false);
1780    
1781                            try {
1782                                    role = roleLocalService.addRole(
1783                                            user.getUserId(), null, 0, name, null, descriptionMap, type,
1784                                            null, null);
1785                            }
1786                            finally {
1787                                    PermissionThreadLocal.setAddResource(true);
1788                            }
1789    
1790                            if (name.equals(RoleConstants.USER)) {
1791                                    initPersonalControlPanelPortletsPermissions(role);
1792                            }
1793                    }
1794    
1795                    _systemRolesMap.put(key, role);
1796            }
1797    
1798            protected String[] getDefaultControlPanelPortlets() {
1799                    return new String[] {
1800                            PortletKeys.MY_ACCOUNT, PortletKeys.MY_PAGES,
1801                            PortletKeys.MY_WORKFLOW_INSTANCES, PortletKeys.MY_WORKFLOW_TASKS
1802                    };
1803            }
1804    
1805            protected Map<Team, Role> getTeamRoleMap(
1806                            long groupId, long[] excludedRoleIds)
1807                    throws PortalException, SystemException {
1808    
1809                    Group group = groupPersistence.findByPrimaryKey(groupId);
1810    
1811                    if (group.isLayout()) {
1812                            group = group.getParentGroup();
1813                    }
1814    
1815                    List<Team> teams = teamPersistence.findByGroupId(group.getGroupId());
1816    
1817                    if (teams.isEmpty()) {
1818                            return Collections.emptyMap();
1819                    }
1820    
1821                    Set<Long> roleIds = SetUtil.fromArray(excludedRoleIds);
1822    
1823                    Map<Team, Role> teamRoleMap = new LinkedHashMap<Team, Role>();
1824    
1825                    for (Team team : teams) {
1826                            Role role = getTeamRole(team.getCompanyId(), team.getTeamId());
1827    
1828                            if (roleIds.contains(role.getRoleId())) {
1829                                    continue;
1830                            }
1831    
1832                            teamRoleMap.put(team, role);
1833                    }
1834    
1835                    return teamRoleMap;
1836            }
1837    
1838            protected void initPersonalControlPanelPortletsPermissions(Role role)
1839                    throws PortalException, SystemException {
1840    
1841                    for (String portletId : getDefaultControlPanelPortlets()) {
1842                            int count = resourcePermissionPersistence.countByC_N_S_P_R(
1843                                    role.getCompanyId(), portletId, ResourceConstants.SCOPE_COMPANY,
1844                                    String.valueOf(role.getCompanyId()), role.getRoleId());
1845    
1846                            if (count > 0) {
1847                                    continue;
1848                            }
1849    
1850                            ResourceAction resourceAction =
1851                                    resourceActionLocalService.fetchResourceAction(
1852                                            portletId, ActionKeys.ACCESS_IN_CONTROL_PANEL);
1853    
1854                            if (resourceAction == null) {
1855                                    continue;
1856                            }
1857    
1858                            setRolePermissions(
1859                                    role, portletId,
1860                                    new String[] {
1861                                            ActionKeys.ACCESS_IN_CONTROL_PANEL
1862                                    });
1863                    }
1864            }
1865    
1866            protected void setRolePermissions(
1867                            Role role, String name, String[] actionIds)
1868                    throws PortalException, SystemException {
1869    
1870                    if (resourceBlockLocalService.isSupported(name)) {
1871                            resourceBlockLocalService.setCompanyScopePermissions(
1872                                    role.getCompanyId(), name, role.getRoleId(),
1873                                    Arrays.asList(actionIds));
1874                    }
1875                    else {
1876                            resourcePermissionLocalService.setResourcePermissions(
1877                                    role.getCompanyId(), name, ResourceConstants.SCOPE_COMPANY,
1878                                    String.valueOf(role.getCompanyId()), role.getRoleId(),
1879                                    actionIds);
1880                    }
1881            }
1882    
1883            protected void validate(
1884                            long roleId, long companyId, long classNameId, String name)
1885                    throws PortalException, SystemException {
1886    
1887                    if (classNameId == PortalUtil.getClassNameId(Role.class)) {
1888                            if (Validator.isNull(name) ||
1889                                    (name.indexOf(CharPool.COMMA) != -1) ||
1890                                    (name.indexOf(CharPool.STAR) != -1)) {
1891    
1892                                    throw new RoleNameException();
1893                            }
1894    
1895                            if (Validator.isNumber(name) &&
1896                                    !PropsValues.ROLES_NAME_ALLOW_NUMERIC) {
1897    
1898                                    throw new RoleNameException();
1899                            }
1900                    }
1901    
1902                    try {
1903                            Role role = roleFinder.findByC_N(companyId, name);
1904    
1905                            if (role.getRoleId() != roleId) {
1906                                    throw new DuplicateRoleException("{roleId=" + roleId + "}");
1907                            }
1908                    }
1909                    catch (NoSuchRoleException nsre) {
1910                    }
1911            }
1912    
1913            private Map<String, Role> _systemRolesMap = new HashMap<String, Role>();
1914    
1915    }