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