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