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