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