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