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            @Override
906            public List<Role> getUserGroupGroupRoles(
907                    long userId, long groupId, int start, int end) {
908    
909                    return roleFinder.findByUserGroupGroupRole(userId, groupId, start, end);
910            }
911    
912            @Override
913            public int getUserGroupGroupRolesCount(long userId, long groupId) {
914                    return roleFinder.countByUserGroupGroupRole(userId, groupId);
915            }
916    
917            /**
918             * Returns all the user's roles within the user group.
919             *
920             * @param  userId the primary key of the user
921             * @param  groupId the primary key of the group
922             * @return the user's roles within the user group
923             * @see    com.liferay.portal.service.persistence.RoleFinder#findByUserGroupRole(
924             *         long, long)
925             */
926            @Override
927            public List<Role> getUserGroupRoles(long userId, long groupId) {
928                    return roleFinder.findByUserGroupRole(userId, groupId);
929            }
930    
931            /**
932             * Returns the union of all the user's roles within the groups.
933             *
934             * @param  userId the primary key of the user
935             * @param  groups the groups (optionally <code>null</code>)
936             * @return the union of all the user's roles within the groups
937             * @see    com.liferay.portal.service.persistence.RoleFinder#findByU_G(long,
938             *         List)
939             */
940            @Override
941            public List<Role> getUserRelatedRoles(long userId, List<Group> groups) {
942                    if ((groups == null) || groups.isEmpty()) {
943                            return Collections.emptyList();
944                    }
945    
946                    return roleFinder.findByU_G(userId, groups);
947            }
948    
949            /**
950             * Returns all the user's roles within the group.
951             *
952             * @param  userId the primary key of the user
953             * @param  groupId the primary key of the group
954             * @return the user's roles within the group
955             * @see    com.liferay.portal.service.persistence.RoleFinder#findByU_G(long,
956             *         long)
957             */
958            @Override
959            public List<Role> getUserRelatedRoles(long userId, long groupId) {
960                    return roleFinder.findByU_G(userId, groupId);
961            }
962    
963            /**
964             * Returns the union of all the user's roles within the groups.
965             *
966             * @param  userId the primary key of the user
967             * @param  groupIds the primary keys of the groups
968             * @return the union of all the user's roles within the groups
969             * @see    com.liferay.portal.service.persistence.RoleFinder#findByU_G(long,
970             *         long[])
971             */
972            @Override
973            public List<Role> getUserRelatedRoles(long userId, long[] groupIds) {
974                    return roleFinder.findByU_G(userId, groupIds);
975            }
976    
977            /**
978             * Returns <code>true</code> if the user is associated with the named
979             * regular role.
980             *
981             * @param  userId the primary key of the user
982             * @param  companyId the primary key of the company
983             * @param  name the name of the role
984             * @param  inherited whether to include the user's inherited roles in the
985             *         search
986             * @return <code>true</code> if the user is associated with the regular
987             *         role; <code>false</code> otherwise
988             * @throws PortalException if a default user for the company could not be
989             *         found
990             */
991            @Override
992            @ThreadLocalCachable
993            public boolean hasUserRole(
994                            long userId, long companyId, String name, boolean inherited)
995                    throws PortalException {
996    
997                    Role role = rolePersistence.fetchByC_N(companyId, name);
998    
999                    if (role == null) {
1000                            return false;
1001                    }
1002    
1003                    if (role.getType() != RoleConstants.TYPE_REGULAR) {
1004                            throw new IllegalArgumentException(name + " is not a regular role");
1005                    }
1006    
1007                    long defaultUserId = userLocalService.getDefaultUserId(companyId);
1008    
1009                    if (userId == defaultUserId) {
1010                            if (name.equals(RoleConstants.GUEST)) {
1011                                    return true;
1012                            }
1013                            else {
1014                                    return false;
1015                            }
1016                    }
1017    
1018                    if (inherited) {
1019                            if (userPersistence.containsRole(userId, role.getRoleId())) {
1020                                    return true;
1021                            }
1022    
1023                            ThreadLocalCache<Integer> threadLocalCache =
1024                                    ThreadLocalCacheManager.getThreadLocalCache(
1025                                            Lifecycle.REQUEST, RoleLocalServiceImpl.class.getName());
1026    
1027                            String key = String.valueOf(role.getRoleId()).concat(
1028                                    String.valueOf(userId));
1029    
1030                            Integer value = threadLocalCache.get(key);
1031    
1032                            if (value == null) {
1033                                    value = roleFinder.countByR_U(role.getRoleId(), userId);
1034    
1035                                    threadLocalCache.put(key, value);
1036                            }
1037    
1038                            if (value > 0) {
1039                                    return true;
1040                            }
1041                            else {
1042                                    return false;
1043                            }
1044                    }
1045                    else {
1046                            return userPersistence.containsRole(userId, role.getRoleId());
1047                    }
1048            }
1049    
1050            /**
1051             * Returns <code>true</code> if the user has any one of the named regular
1052             * roles.
1053             *
1054             * @param  userId the primary key of the user
1055             * @param  companyId the primary key of the company
1056             * @param  names the names of the roles
1057             * @param  inherited whether to include the user's inherited roles in the
1058             *         search
1059             * @return <code>true</code> if the user has any one of the regular roles;
1060             *         <code>false</code> otherwise
1061             * @throws PortalException if any one of the roles with the names could not
1062             *         be found in the company or if the default user for the company
1063             *         could not be found
1064             */
1065            @Override
1066            public boolean hasUserRoles(
1067                            long userId, long companyId, String[] names, boolean inherited)
1068                    throws PortalException {
1069    
1070                    for (String name : names) {
1071                            if (hasUserRole(userId, companyId, name, inherited)) {
1072                                    return true;
1073                            }
1074                    }
1075    
1076                    return false;
1077            }
1078    
1079            /**
1080             * Returns a role with the name in the company.
1081             *
1082             * @param  companyId the primary key of the company
1083             * @param  name the role's name (optionally <code>null</code>)
1084             * @return the role with the name, or <code>null</code> if a role with the
1085             *         name could not be found in the company
1086             */
1087            @Override
1088            public Role loadFetchRole(long companyId, String name) {
1089                    return rolePersistence.fetchByC_N(companyId, name);
1090            }
1091    
1092            /**
1093             * Returns a role with the name in the company.
1094             *
1095             * @param  companyId the primary key of the company
1096             * @param  name the role's name
1097             * @return the role with the name in the company
1098             * @throws PortalException if a role with the name could not be found in the
1099             *         company
1100             */
1101            @Override
1102            public Role loadGetRole(long companyId, String name)
1103                    throws PortalException {
1104    
1105                    return rolePersistence.findByC_N(companyId, name);
1106            }
1107    
1108            /**
1109             * Returns an ordered range of all the roles that match the keywords and
1110             * types.
1111             *
1112             * <p>
1113             * Useful when paginating results. Returns a maximum of <code>end -
1114             * start</code> instances. <code>start</code> and <code>end</code> are not
1115             * primary keys, they are indexes in the result set. Thus, <code>0</code>
1116             * refers to the first result in the set. Setting both <code>start</code>
1117             * and <code>end</code> to {@link
1118             * com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full
1119             * result set.
1120             * </p>
1121             *
1122             * @param  companyId the primary key of the company
1123             * @param  keywords the keywords (space separated), which may occur in the
1124             *         role's name or description (optionally <code>null</code>)
1125             * @param  types the role types (optionally <code>null</code>)
1126             * @param  start the lower bound of the range of roles to return
1127             * @param  end the upper bound of the range of roles to return (not
1128             *         inclusive)
1129             * @param  obc the comparator to order the roles (optionally
1130             *         <code>null</code>)
1131             * @return the ordered range of the matching roles, ordered by
1132             *         <code>obc</code>
1133             * @see    com.liferay.portal.service.persistence.RoleFinder
1134             */
1135            @Override
1136            public List<Role> search(
1137                    long companyId, String keywords, Integer[] types, int start, int end,
1138                    OrderByComparator<Role> obc) {
1139    
1140                    return search(
1141                            companyId, keywords, types, new LinkedHashMap<String, Object>(),
1142                            start, end, obc);
1143            }
1144    
1145            /**
1146             * Returns an ordered range of all the roles that match the keywords, types,
1147             * and params.
1148             *
1149             * <p>
1150             * Useful when paginating results. Returns a maximum of <code>end -
1151             * start</code> instances. <code>start</code> and <code>end</code> are not
1152             * primary keys, they are indexes in the result set. Thus, <code>0</code>
1153             * refers to the first result in the set. Setting both <code>start</code>
1154             * and <code>end</code> to {@link
1155             * com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full
1156             * result set.
1157             * </p>
1158             *
1159             * @param  companyId the primary key of the company
1160             * @param  keywords the keywords (space separated), which may occur in the
1161             *         role's name or description (optionally <code>null</code>)
1162             * @param  types the role types (optionally <code>null</code>)
1163             * @param  params the finder parameters. Can specify values for the
1164             *         "usersRoles" key. For more information, see {@link
1165             *         com.liferay.portal.service.persistence.RoleFinder}
1166             * @param  start the lower bound of the range of roles to return
1167             * @param  end the upper bound of the range of roles to return (not
1168             *         inclusive)
1169             * @param  obc the comparator to order the roles (optionally
1170             *         <code>null</code>)
1171             * @return the ordered range of the matching roles, ordered by
1172             *         <code>obc</code>
1173             * @see    com.liferay.portal.service.persistence.RoleFinder
1174             */
1175            @Override
1176            public List<Role> search(
1177                    long companyId, String keywords, Integer[] types,
1178                    LinkedHashMap<String, Object> params, int start, int end,
1179                    OrderByComparator<Role> obc) {
1180    
1181                    return roleFinder.findByKeywords(
1182                            companyId, keywords, types, params, start, end, obc);
1183            }
1184    
1185            /**
1186             * Returns an ordered range of all the roles that match the name,
1187             * description, and types.
1188             *
1189             * <p>
1190             * Useful when paginating results. Returns a maximum of <code>end -
1191             * start</code> instances. <code>start</code> and <code>end</code> are not
1192             * primary keys, they are indexes in the result set. Thus, <code>0</code>
1193             * refers to the first result in the set. Setting both <code>start</code>
1194             * and <code>end</code> to {@link
1195             * com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full
1196             * result set.
1197             * </p>
1198             *
1199             * @param  companyId the primary key of the company
1200             * @param  name the role's name (optionally <code>null</code>)
1201             * @param  description the role's description (optionally <code>null</code>)
1202             * @param  types the role types (optionally <code>null</code>)
1203             * @param  start the lower bound of the range of the roles to return
1204             * @param  end the upper bound of the range of the roles to return (not
1205             *         inclusive)
1206             * @param  obc the comparator to order the roles (optionally
1207             *         <code>null</code>)
1208             * @return the ordered range of the matching roles, ordered by
1209             *         <code>obc</code>
1210             * @see    com.liferay.portal.service.persistence.RoleFinder
1211             */
1212            @Override
1213            public List<Role> search(
1214                    long companyId, String name, String description, Integer[] types,
1215                    int start, int end, OrderByComparator<Role> obc) {
1216    
1217                    return search(
1218                            companyId, name, description, types,
1219                            new LinkedHashMap<String, Object>(), start, end, obc);
1220            }
1221    
1222            /**
1223             * Returns an ordered range of all the roles that match the name,
1224             * description, types, and params.
1225             *
1226             * <p>
1227             * Useful when paginating results. Returns a maximum of <code>end -
1228             * start</code> instances. <code>start</code> and <code>end</code> are not
1229             * primary keys, they are indexes in the result set. Thus, <code>0</code>
1230             * refers to the first result in the set. Setting both <code>start</code>
1231             * and <code>end</code> to {@link
1232             * com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full
1233             * result set.
1234             * </p>
1235             *
1236             * @param  companyId the primary key of the company
1237             * @param  name the role's name (optionally <code>null</code>)
1238             * @param  description the role's description (optionally <code>null</code>)
1239             * @param  types the role types (optionally <code>null</code>)
1240             * @param  params the finder's parameters. Can specify values for the
1241             *         "usersRoles" key. For more information, see {@link
1242             *         com.liferay.portal.service.persistence.RoleFinder}
1243             * @param  start the lower bound of the range of the roles to return
1244             * @param  end the upper bound of the range of the roles to return (not
1245             *         inclusive)
1246             * @param  obc the comparator to order the roles (optionally
1247             *         <code>null</code>)
1248             * @return the ordered range of the matching roles, ordered by
1249             *         <code>obc</code>
1250             * @see    com.liferay.portal.service.persistence.RoleFinder
1251             */
1252            @Override
1253            public List<Role> search(
1254                    long companyId, String name, String description, Integer[] types,
1255                    LinkedHashMap<String, Object> params, int start, int end,
1256                    OrderByComparator<Role> obc) {
1257    
1258                    return roleFinder.findByC_N_D_T(
1259                            companyId, name, description, types, params, true, start, end, obc);
1260            }
1261    
1262            /**
1263             * Returns the number of roles that match the keywords and types.
1264             *
1265             * @param  companyId the primary key of the company
1266             * @param  keywords the keywords (space separated), which may occur in the
1267             *         role's name or description (optionally <code>null</code>)
1268             * @param  types the role types (optionally <code>null</code>)
1269             * @return the number of matching roles
1270             */
1271            @Override
1272            public int searchCount(long companyId, String keywords, Integer[] types) {
1273                    return searchCount(
1274                            companyId, keywords, types, new LinkedHashMap<String, Object>());
1275            }
1276    
1277            /**
1278             * Returns the number of roles that match the keywords, types and params.
1279             *
1280             * @param  companyId the primary key of the company
1281             * @param  keywords the keywords (space separated), which may occur in the
1282             *         role's name or description (optionally <code>null</code>)
1283             * @param  types the role types (optionally <code>null</code>)
1284             * @param  params the finder parameters. For more information, see {@link
1285             *         com.liferay.portal.service.persistence.RoleFinder}
1286             * @return the number of matching roles
1287             */
1288            @Override
1289            public int searchCount(
1290                    long companyId, String keywords, Integer[] types,
1291                    LinkedHashMap<String, Object> params) {
1292    
1293                    return roleFinder.countByKeywords(companyId, keywords, types, params);
1294            }
1295    
1296            /**
1297             * Returns the number of roles that match the name, description, and types.
1298             *
1299             * @param  companyId the primary key of the company
1300             * @param  name the role's name (optionally <code>null</code>)
1301             * @param  description the role's description (optionally <code>null</code>)
1302             * @param  types the role types (optionally <code>null</code>)
1303             * @return the number of matching roles
1304             */
1305            @Override
1306            public int searchCount(
1307                    long companyId, String name, String description, Integer[] types) {
1308    
1309                    return searchCount(
1310                            companyId, name, description, types,
1311                            new LinkedHashMap<String, Object>());
1312            }
1313    
1314            /**
1315             * Returns the number of roles that match the name, description, types, and
1316             * params.
1317             *
1318             * @param  companyId the primary key of the company
1319             * @param  name the role's name (optionally <code>null</code>)
1320             * @param  description the role's description (optionally <code>null</code>)
1321             * @param  types the role types (optionally <code>null</code>)
1322             * @param  params the finder parameters. Can specify values for the
1323             *         "usersRoles" key. For more information, see {@link
1324             *         com.liferay.portal.service.persistence.RoleFinder}
1325             * @return the number of matching roles
1326             */
1327            @Override
1328            public int searchCount(
1329                    long companyId, String name, String description, Integer[] types,
1330                    LinkedHashMap<String, Object> params) {
1331    
1332                    return roleFinder.countByC_N_D_T(
1333                            companyId, name, description, types, params, true);
1334            }
1335    
1336            /**
1337             * Sets the roles associated with the user, replacing the user's existing
1338             * roles. The user is reindexed after the roles are set.
1339             *
1340             * @param  userId the primary key of the user
1341             * @param  roleIds the primary keys of the roles
1342             * @throws PortalException if a user with the primary could not be found or
1343             *         if any one of the roles with the primary keys could not be found
1344             */
1345            @Override
1346            public void setUserRoles(long userId, long[] roleIds)
1347                    throws PortalException {
1348    
1349                    roleIds = UsersAdminUtil.addRequiredRoles(userId, roleIds);
1350    
1351                    userPersistence.setRoles(userId, roleIds);
1352    
1353                    Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
1354    
1355                    indexer.reindex(userId);
1356    
1357                    PermissionCacheUtil.clearCache();
1358            }
1359    
1360            /**
1361             * Removes the matching roles associated with the user. The user is
1362             * reindexed after the roles are removed.
1363             *
1364             * @param  userId the primary key of the user
1365             * @param  roleIds the primary keys of the roles
1366             * @throws PortalException if a user with the primary key could not be found
1367             *         or if a role with any one of the primary keys could not be found
1368             */
1369            @Override
1370            public void unsetUserRoles(long userId, long[] roleIds)
1371                    throws PortalException {
1372    
1373                    roleIds = UsersAdminUtil.removeRequiredRoles(userId, roleIds);
1374    
1375                    userPersistence.removeRoles(userId, roleIds);
1376    
1377                    Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
1378    
1379                    indexer.reindex(userId);
1380    
1381                    PermissionCacheUtil.clearCache();
1382            }
1383    
1384            /**
1385             * Updates the role with the primary key.
1386             *
1387             * @param  roleId the primary key of the role
1388             * @param  name the role's new name
1389             * @param  titleMap the new localized titles (optionally <code>null</code>)
1390             *         to replace those existing for the role
1391             * @param  descriptionMap the new localized descriptions (optionally
1392             *         <code>null</code>) to replace those existing for the role
1393             * @param  subtype the role's new subtype (optionally <code>null</code>)
1394             * @param  serviceContext the service context to be applied (optionally
1395             *         <code>null</code>). Can set expando bridge attributes for the
1396             *         role.
1397             * @return the role with the primary key
1398             * @throws PortalException if a role with the primary could not be found or
1399             *         if the role's name was invalid
1400             */
1401            @Override
1402            public Role updateRole(
1403                            long roleId, String name, Map<Locale, String> titleMap,
1404                            Map<Locale, String> descriptionMap, String subtype,
1405                            ServiceContext serviceContext)
1406                    throws PortalException {
1407    
1408                    Role role = rolePersistence.findByPrimaryKey(roleId);
1409    
1410                    validate(roleId, role.getCompanyId(), role.getClassNameId(), name);
1411    
1412                    if (PortalUtil.isSystemRole(role.getName())) {
1413                            name = role.getName();
1414                            subtype = null;
1415                    }
1416    
1417                    role.setModifiedDate(new Date());
1418                    role.setName(name);
1419                    role.setTitleMap(titleMap);
1420                    role.setDescriptionMap(descriptionMap);
1421                    role.setSubtype(subtype);
1422                    role.setExpandoBridgeAttributes(serviceContext);
1423    
1424                    rolePersistence.update(role);
1425    
1426                    return role;
1427            }
1428    
1429            protected void checkSystemRole(
1430                            long companyId, String name, Map<Locale, String> descriptionMap,
1431                            int type)
1432                    throws PortalException {
1433    
1434                    String companyIdHexString = StringUtil.toHexString(companyId);
1435    
1436                    String key = companyIdHexString.concat(name);
1437    
1438                    Role role = _systemRolesMap.get(key);
1439    
1440                    try {
1441                            if (role == null) {
1442                                    role = rolePersistence.findByC_N(companyId, name);
1443                            }
1444    
1445                            if (!descriptionMap.equals(role.getDescriptionMap())) {
1446                                    role.setDescriptionMap(descriptionMap);
1447    
1448                                    roleLocalService.updateRole(role);
1449                            }
1450                    }
1451                    catch (NoSuchRoleException nsre) {
1452                            User user = userLocalService.getDefaultUser(companyId);
1453    
1454                            role = roleLocalService.addRole(
1455                                    user.getUserId(), null, 0, name, null, descriptionMap, type,
1456                                    null, null);
1457    
1458                            if (name.equals(RoleConstants.USER)) {
1459                                    initPersonalControlPanelPortletsPermissions(role);
1460                            }
1461                    }
1462    
1463                    _systemRolesMap.put(key, role);
1464            }
1465    
1466            protected String[] getDefaultControlPanelPortlets() {
1467                    return new String[] {
1468                            PortletKeys.MY_ACCOUNT, PortletKeys.MY_PAGES,
1469                            PortletKeys.MY_WORKFLOW_INSTANCES, PortletKeys.MY_WORKFLOW_TASKS
1470                    };
1471            }
1472    
1473            protected Map<Team, Role> getTeamRoleMap(
1474                            long groupId, long[] excludedRoleIds)
1475                    throws PortalException {
1476    
1477                    Group group = groupPersistence.findByPrimaryKey(groupId);
1478    
1479                    if (group.isLayout()) {
1480                            group = group.getParentGroup();
1481                    }
1482    
1483                    List<Team> teams = teamPersistence.findByGroupId(group.getGroupId());
1484    
1485                    if (teams.isEmpty()) {
1486                            return Collections.emptyMap();
1487                    }
1488    
1489                    Set<Long> roleIds = SetUtil.fromArray(excludedRoleIds);
1490    
1491                    Map<Team, Role> teamRoleMap = new LinkedHashMap<Team, Role>();
1492    
1493                    for (Team team : teams) {
1494                            Role role = getTeamRole(team.getCompanyId(), team.getTeamId());
1495    
1496                            if (roleIds.contains(role.getRoleId())) {
1497                                    continue;
1498                            }
1499    
1500                            teamRoleMap.put(team, role);
1501                    }
1502    
1503                    return teamRoleMap;
1504            }
1505    
1506            protected void initPersonalControlPanelPortletsPermissions(Role role)
1507                    throws PortalException {
1508    
1509                    for (String portletId : getDefaultControlPanelPortlets()) {
1510                            int count = resourcePermissionPersistence.countByC_N_S_P_R(
1511                                    role.getCompanyId(), portletId, ResourceConstants.SCOPE_COMPANY,
1512                                    String.valueOf(role.getCompanyId()), role.getRoleId());
1513    
1514                            if (count > 0) {
1515                                    continue;
1516                            }
1517    
1518                            ResourceAction resourceAction =
1519                                    resourceActionLocalService.fetchResourceAction(
1520                                            portletId, ActionKeys.ACCESS_IN_CONTROL_PANEL);
1521    
1522                            if (resourceAction == null) {
1523                                    continue;
1524                            }
1525    
1526                            setRolePermissions(
1527                                    role, portletId,
1528                                    new String[] {
1529                                            ActionKeys.ACCESS_IN_CONTROL_PANEL
1530                                    });
1531                    }
1532            }
1533    
1534            protected void setRolePermissions(
1535                            Role role, String name, String[] actionIds)
1536                    throws PortalException {
1537    
1538                    if (resourceBlockLocalService.isSupported(name)) {
1539                            resourceBlockLocalService.setCompanyScopePermissions(
1540                                    role.getCompanyId(), name, role.getRoleId(),
1541                                    Arrays.asList(actionIds));
1542                    }
1543                    else {
1544                            resourcePermissionLocalService.setResourcePermissions(
1545                                    role.getCompanyId(), name, ResourceConstants.SCOPE_COMPANY,
1546                                    String.valueOf(role.getCompanyId()), role.getRoleId(),
1547                                    actionIds);
1548                    }
1549            }
1550    
1551            protected void validate(
1552                            long roleId, long companyId, long classNameId, String name)
1553                    throws PortalException {
1554    
1555                    if (classNameId == classNameLocalService.getClassNameId(Role.class)) {
1556                            if (Validator.isNull(name) ||
1557                                    (name.indexOf(CharPool.COMMA) != -1) ||
1558                                    (name.indexOf(CharPool.STAR) != -1)) {
1559    
1560                                    throw new RoleNameException();
1561                            }
1562    
1563                            if (Validator.isNumber(name) &&
1564                                    !PropsValues.ROLES_NAME_ALLOW_NUMERIC) {
1565    
1566                                    throw new RoleNameException();
1567                            }
1568                    }
1569    
1570                    try {
1571                            Role role = roleFinder.findByC_N(companyId, name);
1572    
1573                            if (role.getRoleId() != roleId) {
1574                                    throw new DuplicateRoleException("{roleId=" + roleId + "}");
1575                            }
1576                    }
1577                    catch (NoSuchRoleException nsre) {
1578                    }
1579            }
1580    
1581            private final Map<String, Role> _systemRolesMap =
1582                    new HashMap<String, Role>();
1583    
1584    }