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