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.DuplicateRoleException;
018    import com.liferay.portal.NoSuchRoleException;
019    import com.liferay.portal.RequiredRoleException;
020    import com.liferay.portal.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.portlet.usersadmin.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                            types = RoleConstants.TYPES_ORGANIZATION_AND_REGULAR;
557                    }
558                    else if (group.isLayout() || group.isLayoutSetPrototype() ||
559                                     group.isSite() || group.isUser()) {
560    
561                            types = RoleConstants.TYPES_REGULAR_AND_SITE;
562                    }
563    
564                    roles.addAll(getRoles(group.getCompanyId(), types));
565    
566                    roles.addAll(getTeamRoles(groupId));
567    
568                    return roles;
569            }
570    
571            @Override
572            public List<Role> getResourceBlockRoles(
573                    long resourceBlockId, String className, String actionId) {
574    
575                    return roleFinder.findByR_N_A(resourceBlockId, className, actionId);
576            }
577    
578            /**
579             * Returns a map of role names to associated action IDs for the named
580             * resource in the company within the permission scope.
581             *
582             * @param  companyId the primary key of the company
583             * @param  name the resource name
584             * @param  scope the permission scope
585             * @param  primKey the primary key of the resource's class
586             * @return the role names and action IDs
587             * @see    com.liferay.portal.service.persistence.RoleFinder#findByC_N_S_P(
588             *         long, String, int, String)
589             */
590            @Override
591            public Map<String, List<String>> getResourceRoles(
592                    long companyId, String name, int scope, String primKey) {
593    
594                    return roleFinder.findByC_N_S_P(companyId, name, scope, primKey);
595            }
596    
597            /**
598             * Returns all the roles associated with the action ID in the company within
599             * the permission scope.
600             *
601             * @param  companyId the primary key of the company
602             * @param  name the resource name
603             * @param  scope the permission scope
604             * @param  primKey the primary key of the resource's class
605             * @param  actionId the name of the resource action
606             * @return the roles
607             * @see    com.liferay.portal.service.persistence.RoleFinder#findByC_N_S_P_A(
608             *         long, String, int, String, String)
609             */
610            @Override
611            public List<Role> getResourceRoles(
612                    long companyId, String name, int scope, String primKey,
613                    String actionId) {
614    
615                    return roleFinder.findByC_N_S_P_A(
616                            companyId, name, scope, primKey, actionId);
617            }
618    
619            /**
620             * Returns the role with the name in the company.
621             *
622             * <p>
623             * The method searches the system roles map first for default roles. If a
624             * role with the name is not found, then the method will query the database.
625             * </p>
626             *
627             * @param  companyId the primary key of the company
628             * @param  name the role's name
629             * @return the role with the name
630             */
631            @Override
632            @Skip
633            public Role getRole(long companyId, String name) throws PortalException {
634                    String companyIdHexString = StringUtil.toHexString(companyId);
635    
636                    Role role = _systemRolesMap.get(companyIdHexString.concat(name));
637    
638                    if (role != null) {
639                            return role;
640                    }
641    
642                    return roleLocalService.loadGetRole(companyId, name);
643            }
644    
645            /**
646             * Returns all the roles of the type and subtype.
647             *
648             * @param  type the role's type (optionally <code>0</code>)
649             * @param  subtype the role's subtype (optionally <code>null</code>)
650             * @return the roles of the type and subtype
651             */
652            @Override
653            public List<Role> getRoles(int type, String subtype) {
654                    return rolePersistence.findByT_S(type, subtype);
655            }
656    
657            /**
658             * Returns all the roles in the company.
659             *
660             * @param  companyId the primary key of the company
661             * @return the roles in the company
662             */
663            @Override
664            public List<Role> getRoles(long companyId) {
665                    return rolePersistence.findByCompanyId(companyId);
666            }
667    
668            /**
669             * Returns all the roles with the types.
670             *
671             * @param  companyId the primary key of the company
672             * @param  types the role types (optionally <code>null</code>)
673             * @return the roles with the types
674             */
675            @Override
676            public List<Role> getRoles(long companyId, int[] types) {
677                    return rolePersistence.findByC_T(companyId, types);
678            }
679    
680            /**
681             * Returns all the roles with the primary keys.
682             *
683             * @param  roleIds the primary keys of the roles
684             * @return the roles with the primary keys
685             */
686            @Override
687            public List<Role> getRoles(long[] roleIds) throws PortalException {
688                    List<Role> roles = new ArrayList<>(roleIds.length);
689    
690                    for (long roleId : roleIds) {
691                            Role role = getRole(roleId);
692    
693                            roles.add(role);
694                    }
695    
696                    return roles;
697            }
698    
699            /**
700             * Returns all the roles of the subtype.
701             *
702             * @param  subtype the role's subtype (optionally <code>null</code>)
703             * @return the roles of the subtype
704             */
705            @Override
706            public List<Role> getSubtypeRoles(String subtype) {
707                    return rolePersistence.findBySubtype(subtype);
708            }
709    
710            /**
711             * Returns the number of roles of the subtype.
712             *
713             * @param  subtype the role's subtype (optionally <code>null</code>)
714             * @return the number of roles of the subtype
715             */
716            @Override
717            public int getSubtypeRolesCount(String subtype) {
718                    return rolePersistence.countBySubtype(subtype);
719            }
720    
721            /**
722             * Returns the team role in the company.
723             *
724             * @param  companyId the primary key of the company
725             * @param  teamId the primary key of the team
726             * @return the team role in the company
727             */
728            @Override
729            public Role getTeamRole(long companyId, long teamId)
730                    throws PortalException {
731    
732                    long classNameId = classNameLocalService.getClassNameId(Team.class);
733    
734                    return rolePersistence.findByC_C_C(companyId, classNameId, teamId);
735            }
736    
737            /**
738             * Returns the team role map for the group.
739             *
740             * @param  groupId the primary key of the group
741             * @return the team role map for the group
742             */
743            @Override
744            public Map<Team, Role> getTeamRoleMap(long groupId) throws PortalException {
745                    return getTeamRoleMap(groupId, null);
746            }
747    
748            /**
749             * Returns the team roles in the group.
750             *
751             * @param  groupId the primary key of the group
752             * @return the team roles in the group
753             */
754            @Override
755            public List<Role> getTeamRoles(long groupId) throws PortalException {
756                    return getTeamRoles(groupId, null);
757            }
758    
759            /**
760             * Returns the team roles in the group, excluding the specified role IDs.
761             *
762             * @param  groupId the primary key of the group
763             * @param  excludedRoleIds the primary keys of the roles to exclude
764             *         (optionally <code>null</code>)
765             * @return the team roles in the group, excluding the specified role IDs
766             */
767            @Override
768            public List<Role> getTeamRoles(long groupId, long[] excludedRoleIds)
769                    throws PortalException {
770    
771                    Map<Team, Role> teamRoleMap = getTeamRoleMap(groupId, excludedRoleIds);
772    
773                    Collection<Role> roles = teamRoleMap.values();
774    
775                    return ListUtil.fromCollection(roles);
776            }
777    
778            /**
779             * Returns all the roles of the type.
780             *
781             * @param  type the role's type (optionally <code>0</code>)
782             * @return the range of the roles of the type
783             */
784            @Override
785            public List<Role> getTypeRoles(int type) {
786                    return rolePersistence.findByType(type);
787            }
788    
789            /**
790             * Returns a range of all the roles of the type.
791             *
792             * @param  type the role's type (optionally <code>0</code>)
793             * @param  start the lower bound of the range of roles to return
794             * @param  end the upper bound of the range of roles to return (not
795             *         inclusive)
796             * @return the range of the roles of the type
797             */
798            @Override
799            public List<Role> getTypeRoles(int type, int start, int end) {
800                    return rolePersistence.findByType(type, start, end);
801            }
802    
803            /**
804             * Returns the number of roles of the type.
805             *
806             * @param  type the role's type (optionally <code>0</code>)
807             * @return the number of roles of the type
808             */
809            @Override
810            public int getTypeRolesCount(int type) {
811                    return rolePersistence.countByType(type);
812            }
813    
814            /**
815             * Returns all the user's roles within the user group.
816             *
817             * @param  userId the primary key of the user
818             * @param  groupId the primary key of the group
819             * @return the user's roles within the user group
820             * @see    com.liferay.portal.service.persistence.RoleFinder#findByUserGroupGroupRole(
821             *         long, long)
822             */
823            @Override
824            public List<Role> getUserGroupGroupRoles(long userId, long groupId) {
825                    return roleFinder.findByUserGroupGroupRole(userId, groupId);
826            }
827    
828            @Override
829            public List<Role> getUserGroupGroupRoles(
830                    long userId, long groupId, int start, int end) {
831    
832                    return roleFinder.findByUserGroupGroupRole(userId, groupId, start, end);
833            }
834    
835            @Override
836            public int getUserGroupGroupRolesCount(long userId, long groupId) {
837                    return roleFinder.countByUserGroupGroupRole(userId, groupId);
838            }
839    
840            /**
841             * Returns all the user's roles within the user group.
842             *
843             * @param  userId the primary key of the user
844             * @param  groupId the primary key of the group
845             * @return the user's roles within the user group
846             * @see    com.liferay.portal.service.persistence.RoleFinder#findByUserGroupRole(
847             *         long, long)
848             */
849            @Override
850            public List<Role> getUserGroupRoles(long userId, long groupId) {
851                    return roleFinder.findByUserGroupRole(userId, groupId);
852            }
853    
854            /**
855             * Returns the union of all the user's roles within the groups.
856             *
857             * @param  userId the primary key of the user
858             * @param  groups the groups (optionally <code>null</code>)
859             * @return the union of all the user's roles within the groups
860             * @see    com.liferay.portal.service.persistence.RoleFinder#findByU_G(long,
861             *         List)
862             */
863            @Override
864            public List<Role> getUserRelatedRoles(long userId, List<Group> groups) {
865                    if ((groups == null) || groups.isEmpty()) {
866                            return Collections.emptyList();
867                    }
868    
869                    return roleFinder.findByU_G(userId, groups);
870            }
871    
872            /**
873             * Returns all the user's roles within the group.
874             *
875             * @param  userId the primary key of the user
876             * @param  groupId the primary key of the group
877             * @return the user's roles within the group
878             * @see    com.liferay.portal.service.persistence.RoleFinder#findByU_G(long,
879             *         long)
880             */
881            @Override
882            public List<Role> getUserRelatedRoles(long userId, long groupId) {
883                    return roleFinder.findByU_G(userId, groupId);
884            }
885    
886            /**
887             * Returns the union of all the user's roles within the groups.
888             *
889             * @param  userId the primary key of the user
890             * @param  groupIds the primary keys of the groups
891             * @return the union of all the user's roles within the groups
892             * @see    com.liferay.portal.service.persistence.RoleFinder#findByU_G(long,
893             *         long[])
894             */
895            @Override
896            public List<Role> getUserRelatedRoles(long userId, long[] groupIds) {
897                    return roleFinder.findByU_G(userId, groupIds);
898            }
899    
900            /**
901             * Returns <code>true</code> if the user is associated with the named
902             * regular role.
903             *
904             * @param  userId the primary key of the user
905             * @param  companyId the primary key of the company
906             * @param  name the name of the role
907             * @param  inherited whether to include the user's inherited roles in the
908             *         search
909             * @return <code>true</code> if the user is associated with the regular
910             *         role; <code>false</code> otherwise
911             */
912            @Override
913            @ThreadLocalCachable
914            public boolean hasUserRole(
915                            long userId, long companyId, String name, boolean inherited)
916                    throws PortalException {
917    
918                    Role role = rolePersistence.fetchByC_N(companyId, name);
919    
920                    if (role == null) {
921                            return false;
922                    }
923    
924                    if (role.getType() != RoleConstants.TYPE_REGULAR) {
925                            throw new IllegalArgumentException(name + " is not a regular role");
926                    }
927    
928                    long defaultUserId = userLocalService.getDefaultUserId(companyId);
929    
930                    if (userId == defaultUserId) {
931                            if (name.equals(RoleConstants.GUEST)) {
932                                    return true;
933                            }
934                            else {
935                                    return false;
936                            }
937                    }
938    
939                    if (inherited) {
940                            if (userPersistence.containsRole(userId, role.getRoleId())) {
941                                    return true;
942                            }
943    
944                            ThreadLocalCache<Boolean> threadLocalCache =
945                                    ThreadLocalCacheManager.getThreadLocalCache(
946                                            Lifecycle.REQUEST, RoleLocalServiceImpl.class.getName());
947    
948                            String key = String.valueOf(role.getRoleId()).concat(
949                                    String.valueOf(userId));
950    
951                            Boolean value = threadLocalCache.get(key);
952    
953                            if (value != null) {
954                                    return value;
955                            }
956    
957                            value = PermissionCacheUtil.getUserRole(userId, role);
958    
959                            if (value == null) {
960                                    int count = roleFinder.countByR_U(role.getRoleId(), userId);
961    
962                                    if (count > 0) {
963                                            value = true;
964                                    }
965                                    else {
966                                            value = false;
967                                    }
968    
969                                    PermissionCacheUtil.putUserRole(userId, role, value);
970                            }
971    
972                            threadLocalCache.put(key, value);
973    
974                            return value;
975                    }
976                    else {
977                            return userPersistence.containsRole(userId, role.getRoleId());
978                    }
979            }
980    
981            /**
982             * Returns <code>true</code> if the user has any one of the named regular
983             * roles.
984             *
985             * @param  userId the primary key of the user
986             * @param  companyId the primary key of the company
987             * @param  names the names of the roles
988             * @param  inherited whether to include the user's inherited roles in the
989             *         search
990             * @return <code>true</code> if the user has any one of the regular roles;
991             *         <code>false</code> otherwise
992             */
993            @Override
994            public boolean hasUserRoles(
995                            long userId, long companyId, String[] names, boolean inherited)
996                    throws PortalException {
997    
998                    for (String name : names) {
999                            if (hasUserRole(userId, companyId, name, inherited)) {
1000                                    return true;
1001                            }
1002                    }
1003    
1004                    return false;
1005            }
1006    
1007            /**
1008             * Returns a role with the name in the company.
1009             *
1010             * @param  companyId the primary key of the company
1011             * @param  name the role's name (optionally <code>null</code>)
1012             * @return the role with the name, or <code>null</code> if a role with the
1013             *         name could not be found in the company
1014             */
1015            @Override
1016            public Role loadFetchRole(long companyId, String name) {
1017                    return rolePersistence.fetchByC_N(companyId, name);
1018            }
1019    
1020            /**
1021             * Returns a role with the name in the company.
1022             *
1023             * @param  companyId the primary key of the company
1024             * @param  name the role's name
1025             * @return the role with the name in the company
1026             */
1027            @Override
1028            public Role loadGetRole(long companyId, String name)
1029                    throws PortalException {
1030    
1031                    return rolePersistence.findByC_N(companyId, name);
1032            }
1033    
1034            /**
1035             * Returns an ordered range of all the roles that match the keywords and
1036             * types.
1037             *
1038             * <p>
1039             * Useful when paginating results. Returns a maximum of <code>end -
1040             * start</code> instances. <code>start</code> and <code>end</code> are not
1041             * primary keys, they are indexes in the result set. Thus, <code>0</code>
1042             * refers to the first result in the set. Setting both <code>start</code>
1043             * and <code>end</code> to {@link
1044             * com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full
1045             * result set.
1046             * </p>
1047             *
1048             * @param  companyId the primary key of the company
1049             * @param  keywords the keywords (space separated), which may occur in the
1050             *         role's name or description (optionally <code>null</code>)
1051             * @param  types the role types (optionally <code>null</code>)
1052             * @param  start the lower bound of the range of roles to return
1053             * @param  end the upper bound of the range of roles to return (not
1054             *         inclusive)
1055             * @param  obc the comparator to order the roles (optionally
1056             *         <code>null</code>)
1057             * @return the ordered range of the matching roles, ordered by
1058             *         <code>obc</code>
1059             * @see    com.liferay.portal.service.persistence.RoleFinder
1060             */
1061            @Override
1062            public List<Role> search(
1063                    long companyId, String keywords, Integer[] types, int start, int end,
1064                    OrderByComparator<Role> obc) {
1065    
1066                    return search(
1067                            companyId, keywords, types, new LinkedHashMap<String, Object>(),
1068                            start, end, obc);
1069            }
1070    
1071            /**
1072             * Returns an ordered range of all the roles that match the keywords, types,
1073             * and params.
1074             *
1075             * <p>
1076             * Useful when paginating results. Returns a maximum of <code>end -
1077             * start</code> instances. <code>start</code> and <code>end</code> are not
1078             * primary keys, they are indexes in the result set. Thus, <code>0</code>
1079             * refers to the first result in the set. Setting both <code>start</code>
1080             * and <code>end</code> to {@link
1081             * com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full
1082             * result set.
1083             * </p>
1084             *
1085             * @param  companyId the primary key of the company
1086             * @param  keywords the keywords (space separated), which may occur in the
1087             *         role's name or description (optionally <code>null</code>)
1088             * @param  types the role types (optionally <code>null</code>)
1089             * @param  params the finder parameters. Can specify values for the
1090             *         "usersRoles" key. For more information, see {@link
1091             *         com.liferay.portal.service.persistence.RoleFinder}
1092             * @param  start the lower bound of the range of roles to return
1093             * @param  end the upper bound of the range of roles to return (not
1094             *         inclusive)
1095             * @param  obc the comparator to order the roles (optionally
1096             *         <code>null</code>)
1097             * @return the ordered range of the matching roles, ordered by
1098             *         <code>obc</code>
1099             * @see    com.liferay.portal.service.persistence.RoleFinder
1100             */
1101            @Override
1102            public List<Role> search(
1103                    long companyId, String keywords, Integer[] types,
1104                    LinkedHashMap<String, Object> params, int start, int end,
1105                    OrderByComparator<Role> obc) {
1106    
1107                    return roleFinder.findByKeywords(
1108                            companyId, keywords, types, params, start, end, obc);
1109            }
1110    
1111            /**
1112             * Returns an ordered range of all the roles that match the name,
1113             * description, and types.
1114             *
1115             * <p>
1116             * Useful when paginating results. Returns a maximum of <code>end -
1117             * start</code> instances. <code>start</code> and <code>end</code> are not
1118             * primary keys, they are indexes in the result set. Thus, <code>0</code>
1119             * refers to the first result in the set. Setting both <code>start</code>
1120             * and <code>end</code> to {@link
1121             * com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full
1122             * result set.
1123             * </p>
1124             *
1125             * @param  companyId the primary key of the company
1126             * @param  name the role's name (optionally <code>null</code>)
1127             * @param  description the role's description (optionally <code>null</code>)
1128             * @param  types the role types (optionally <code>null</code>)
1129             * @param  start the lower bound of the range of the roles to return
1130             * @param  end the upper bound of the range of the roles to return (not
1131             *         inclusive)
1132             * @param  obc the comparator to order the roles (optionally
1133             *         <code>null</code>)
1134             * @return the ordered range of the matching roles, ordered by
1135             *         <code>obc</code>
1136             * @see    com.liferay.portal.service.persistence.RoleFinder
1137             */
1138            @Override
1139            public List<Role> search(
1140                    long companyId, String name, String description, Integer[] types,
1141                    int start, int end, OrderByComparator<Role> obc) {
1142    
1143                    return search(
1144                            companyId, name, description, types,
1145                            new LinkedHashMap<String, Object>(), start, end, obc);
1146            }
1147    
1148            /**
1149             * Returns an ordered range of all the roles that match the name,
1150             * description, types, and params.
1151             *
1152             * <p>
1153             * Useful when paginating results. Returns a maximum of <code>end -
1154             * start</code> instances. <code>start</code> and <code>end</code> are not
1155             * primary keys, they are indexes in the result set. Thus, <code>0</code>
1156             * refers to the first result in the set. Setting both <code>start</code>
1157             * and <code>end</code> to {@link
1158             * com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full
1159             * result set.
1160             * </p>
1161             *
1162             * @param  companyId the primary key of the company
1163             * @param  name the role's name (optionally <code>null</code>)
1164             * @param  description the role's description (optionally <code>null</code>)
1165             * @param  types the role types (optionally <code>null</code>)
1166             * @param  params the finder's parameters. Can specify values for the
1167             *         "usersRoles" key. For more information, see {@link
1168             *         com.liferay.portal.service.persistence.RoleFinder}
1169             * @param  start the lower bound of the range of the roles to return
1170             * @param  end the upper bound of the range of the roles to return (not
1171             *         inclusive)
1172             * @param  obc the comparator to order the roles (optionally
1173             *         <code>null</code>)
1174             * @return the ordered range of the matching roles, ordered by
1175             *         <code>obc</code>
1176             * @see    com.liferay.portal.service.persistence.RoleFinder
1177             */
1178            @Override
1179            public List<Role> search(
1180                    long companyId, String name, String description, Integer[] types,
1181                    LinkedHashMap<String, Object> params, int start, int end,
1182                    OrderByComparator<Role> obc) {
1183    
1184                    return roleFinder.findByC_N_D_T(
1185                            companyId, name, description, types, params, true, start, end, obc);
1186            }
1187    
1188            /**
1189             * Returns the number of roles that match the keywords and types.
1190             *
1191             * @param  companyId the primary key of the company
1192             * @param  keywords the keywords (space separated), which may occur in the
1193             *         role's name or description (optionally <code>null</code>)
1194             * @param  types the role types (optionally <code>null</code>)
1195             * @return the number of matching roles
1196             */
1197            @Override
1198            public int searchCount(long companyId, String keywords, Integer[] types) {
1199                    return searchCount(
1200                            companyId, keywords, types, new LinkedHashMap<String, Object>());
1201            }
1202    
1203            /**
1204             * Returns the number of roles that match the keywords, types and params.
1205             *
1206             * @param  companyId the primary key of the company
1207             * @param  keywords the keywords (space separated), which may occur in the
1208             *         role's name or description (optionally <code>null</code>)
1209             * @param  types the role types (optionally <code>null</code>)
1210             * @param  params the finder parameters. For more information, see {@link
1211             *         com.liferay.portal.service.persistence.RoleFinder}
1212             * @return the number of matching roles
1213             */
1214            @Override
1215            public int searchCount(
1216                    long companyId, String keywords, Integer[] types,
1217                    LinkedHashMap<String, Object> params) {
1218    
1219                    return roleFinder.countByKeywords(companyId, keywords, types, params);
1220            }
1221    
1222            /**
1223             * Returns the number of roles that match the name, description, and types.
1224             *
1225             * @param  companyId the primary key of the company
1226             * @param  name the role's name (optionally <code>null</code>)
1227             * @param  description the role's description (optionally <code>null</code>)
1228             * @param  types the role types (optionally <code>null</code>)
1229             * @return the number of matching roles
1230             */
1231            @Override
1232            public int searchCount(
1233                    long companyId, String name, String description, Integer[] types) {
1234    
1235                    return searchCount(
1236                            companyId, name, description, types,
1237                            new LinkedHashMap<String, Object>());
1238            }
1239    
1240            /**
1241             * Returns the number of roles that match the name, description, types, and
1242             * params.
1243             *
1244             * @param  companyId the primary key of the company
1245             * @param  name the role's name (optionally <code>null</code>)
1246             * @param  description the role's description (optionally <code>null</code>)
1247             * @param  types the role types (optionally <code>null</code>)
1248             * @param  params the finder parameters. Can specify values for the
1249             *         "usersRoles" key. For more information, see {@link
1250             *         com.liferay.portal.service.persistence.RoleFinder}
1251             * @return the number of matching roles
1252             */
1253            @Override
1254            public int searchCount(
1255                    long companyId, String name, String description, Integer[] types,
1256                    LinkedHashMap<String, Object> params) {
1257    
1258                    return roleFinder.countByC_N_D_T(
1259                            companyId, name, description, types, params, true);
1260            }
1261    
1262            /**
1263             * Sets the roles associated with the user, replacing the user's existing
1264             * roles. The user is reindexed after the roles are set.
1265             *
1266             * @param userId the primary key of the user
1267             * @param roleIds the primary keys of the roles
1268             */
1269            @Override
1270            public void setUserRoles(long userId, long[] roleIds)
1271                    throws PortalException {
1272    
1273                    roleIds = UsersAdminUtil.addRequiredRoles(userId, roleIds);
1274    
1275                    userPersistence.setRoles(userId, roleIds);
1276    
1277                    reindex(userId);
1278    
1279                    PermissionCacheUtil.clearCache(userId);
1280            }
1281    
1282            /**
1283             * Removes the matching roles associated with the user. The user is
1284             * reindexed after the roles are removed.
1285             *
1286             * @param userId the primary key of the user
1287             * @param roleIds the primary keys of the roles
1288             */
1289            @Override
1290            public void unsetUserRoles(long userId, long[] roleIds)
1291                    throws PortalException {
1292    
1293                    roleIds = UsersAdminUtil.removeRequiredRoles(userId, roleIds);
1294    
1295                    userPersistence.removeRoles(userId, roleIds);
1296    
1297                    reindex(userId);
1298    
1299                    PermissionCacheUtil.clearCache(userId);
1300            }
1301    
1302            /**
1303             * Updates the role with the primary key.
1304             *
1305             * @param  roleId the primary key of the role
1306             * @param  name the role's new name
1307             * @param  titleMap the new localized titles (optionally <code>null</code>)
1308             *         to replace those existing for the role
1309             * @param  descriptionMap the new localized descriptions (optionally
1310             *         <code>null</code>) to replace those existing for the role
1311             * @param  subtype the role's new subtype (optionally <code>null</code>)
1312             * @param  serviceContext the service context to be applied (optionally
1313             *         <code>null</code>). Can set expando bridge attributes for the
1314             *         role.
1315             * @return the role with the primary key
1316             */
1317            @Override
1318            public Role updateRole(
1319                            long roleId, String name, Map<Locale, String> titleMap,
1320                            Map<Locale, String> descriptionMap, String subtype,
1321                            ServiceContext serviceContext)
1322                    throws PortalException {
1323    
1324                    Role role = rolePersistence.findByPrimaryKey(roleId);
1325    
1326                    validate(roleId, role.getCompanyId(), role.getClassNameId(), name);
1327    
1328                    if (role.isSystem()) {
1329                            name = role.getName();
1330                            subtype = null;
1331                    }
1332    
1333                    role.setName(name);
1334                    role.setTitleMap(titleMap);
1335                    role.setDescriptionMap(descriptionMap);
1336                    role.setSubtype(subtype);
1337                    role.setExpandoBridgeAttributes(serviceContext);
1338    
1339                    rolePersistence.update(role);
1340    
1341                    return role;
1342            }
1343    
1344            protected void checkSystemRole(
1345                            long companyId, String name, Map<Locale, String> descriptionMap,
1346                            int type)
1347                    throws PortalException {
1348    
1349                    String companyIdHexString = StringUtil.toHexString(companyId);
1350    
1351                    String key = companyIdHexString.concat(name);
1352    
1353                    Role role = _systemRolesMap.get(key);
1354    
1355                    try {
1356                            if (role == null) {
1357                                    role = rolePersistence.findByC_N(companyId, name);
1358                            }
1359    
1360                            if (!descriptionMap.equals(role.getDescriptionMap())) {
1361                                    role.setDescriptionMap(descriptionMap);
1362    
1363                                    roleLocalService.updateRole(role);
1364                            }
1365                    }
1366                    catch (NoSuchRoleException nsre) {
1367                            User user = userLocalService.getDefaultUser(companyId);
1368    
1369                            role = roleLocalService.addRole(
1370                                    user.getUserId(), null, 0, name, null, descriptionMap, type,
1371                                    null, null);
1372    
1373                            if (name.equals(RoleConstants.USER)) {
1374                                    initPersonalControlPanelPortletsPermissions(role);
1375                            }
1376                    }
1377    
1378                    _systemRolesMap.put(key, role);
1379            }
1380    
1381            protected String[] getDefaultControlPanelPortlets() {
1382                    String myAccountPortletId = PortletProviderUtil.getPortletId(
1383                            PortalMyAccountApplicationType.MyAccount.CLASS_NAME,
1384                            PortletProvider.Action.VIEW);
1385    
1386                    return new String[] {
1387                            myAccountPortletId, PortletKeys.MY_PAGES,
1388                            PortletKeys.MY_WORKFLOW_INSTANCE, PortletKeys.MY_WORKFLOW_TASK
1389                    };
1390            }
1391    
1392            protected Map<Team, Role> getTeamRoleMap(
1393                            long groupId, long[] excludedRoleIds)
1394                    throws PortalException {
1395    
1396                    Group group = groupPersistence.findByPrimaryKey(groupId);
1397    
1398                    if (group.isLayout()) {
1399                            group = group.getParentGroup();
1400                    }
1401    
1402                    List<Team> teams = teamPersistence.findByGroupId(group.getGroupId());
1403    
1404                    if (teams.isEmpty()) {
1405                            return Collections.emptyMap();
1406                    }
1407    
1408                    Set<Long> roleIds = SetUtil.fromArray(excludedRoleIds);
1409    
1410                    Map<Team, Role> teamRoleMap = new LinkedHashMap<>();
1411    
1412                    for (Team team : teams) {
1413                            Role role = getTeamRole(team.getCompanyId(), team.getTeamId());
1414    
1415                            if (roleIds.contains(role.getRoleId())) {
1416                                    continue;
1417                            }
1418    
1419                            teamRoleMap.put(team, role);
1420                    }
1421    
1422                    return teamRoleMap;
1423            }
1424    
1425            protected void initPersonalControlPanelPortletsPermissions(Role role)
1426                    throws PortalException {
1427    
1428                    for (String portletId : getDefaultControlPanelPortlets()) {
1429                            int count = resourcePermissionPersistence.countByC_N_S_P_R(
1430                                    role.getCompanyId(), portletId, ResourceConstants.SCOPE_COMPANY,
1431                                    String.valueOf(role.getCompanyId()), role.getRoleId());
1432    
1433                            if (count > 0) {
1434                                    continue;
1435                            }
1436    
1437                            ResourceAction resourceAction =
1438                                    resourceActionLocalService.fetchResourceAction(
1439                                            portletId, ActionKeys.ACCESS_IN_CONTROL_PANEL);
1440    
1441                            if (resourceAction == null) {
1442                                    continue;
1443                            }
1444    
1445                            setRolePermissions(
1446                                    role, portletId,
1447                                    new String[] {ActionKeys.ACCESS_IN_CONTROL_PANEL});
1448                    }
1449            }
1450    
1451            protected void reindex(long userId) throws SearchException {
1452                    Indexer<User> indexer = IndexerRegistryUtil.nullSafeGetIndexer(
1453                            User.class);
1454    
1455                    User user = userLocalService.fetchUser(userId);
1456    
1457                    indexer.reindex(user);
1458            }
1459    
1460            protected void setRolePermissions(
1461                            Role role, String name, String[] actionIds)
1462                    throws PortalException {
1463    
1464                    if (resourceBlockLocalService.isSupported(name)) {
1465                            resourceBlockLocalService.setCompanyScopePermissions(
1466                                    role.getCompanyId(), name, role.getRoleId(),
1467                                    Arrays.asList(actionIds));
1468                    }
1469                    else {
1470                            resourcePermissionLocalService.setResourcePermissions(
1471                                    role.getCompanyId(), name, ResourceConstants.SCOPE_COMPANY,
1472                                    String.valueOf(role.getCompanyId()), role.getRoleId(),
1473                                    actionIds);
1474                    }
1475            }
1476    
1477            protected void validate(
1478                            long roleId, long companyId, long classNameId, String name)
1479                    throws PortalException {
1480    
1481                    if (classNameId == classNameLocalService.getClassNameId(Role.class)) {
1482                            if (Validator.isNull(name) ||
1483                                    (name.indexOf(CharPool.COMMA) != -1) ||
1484                                    (name.indexOf(CharPool.STAR) != -1)) {
1485    
1486                                    throw new RoleNameException();
1487                            }
1488    
1489                            if (Validator.isNumber(name) &&
1490                                    !PropsValues.ROLES_NAME_ALLOW_NUMERIC) {
1491    
1492                                    throw new RoleNameException();
1493                            }
1494                    }
1495    
1496                    try {
1497                            Role role = roleFinder.findByC_N(companyId, name);
1498    
1499                            if (role.getRoleId() != roleId) {
1500                                    throw new DuplicateRoleException("{roleId=" + roleId + "}");
1501                            }
1502                    }
1503                    catch (NoSuchRoleException nsre) {
1504                    }
1505    
1506                    if (name.equals(RoleConstants.PLACEHOLDER_DEFAULT_GROUP_ROLE)) {
1507                            throw new RoleNameException(
1508                                    RoleConstants.PLACEHOLDER_DEFAULT_GROUP_ROLE +
1509                                            " is a temporary placeholder that must not be persisted");
1510                    }
1511            }
1512    
1513            private final Map<String, Role> _systemRolesMap = new HashMap<>();
1514    
1515    }