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