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                    int[] types = RoleConstants.TYPES_REGULAR;
627    
628                    if (group.isOrganization()) {
629                            types = RoleConstants.TYPES_ORGANIZATION_AND_REGULAR;
630                    }
631                    else if (group.isLayout() || group.isLayoutSetPrototype() ||
632                                     group.isSite()) {
633    
634                            types = RoleConstants.TYPES_REGULAR_AND_SITE;
635                    }
636    
637                    roles.addAll(getRoles(group.getCompanyId(), types));
638    
639                    roles.addAll(getTeamRoles(groupId));
640    
641                    return roles;
642            }
643    
644            @Override
645            public List<Role> getResourceBlockRoles(
646                            long resourceBlockId, String className, String actionId)
647                    throws SystemException {
648    
649                    return roleFinder.findByR_N_A(resourceBlockId, className, actionId);
650            }
651    
652            /**
653             * Returns a map of role names to associated action IDs for the named
654             * resource in the company within the permission scope.
655             *
656             * @param  companyId the primary key of the company
657             * @param  name the resource name
658             * @param  scope the permission scope
659             * @param  primKey the primary key of the resource's class
660             * @return the role names and action IDs
661             * @throws SystemException if a system exception occurred
662             * @see    com.liferay.portal.service.persistence.RoleFinder#findByC_N_S_P(
663             *         long, String, int, String)
664             */
665            @Override
666            public Map<String, List<String>> getResourceRoles(
667                            long companyId, String name, int scope, String primKey)
668                    throws SystemException {
669    
670                    return roleFinder.findByC_N_S_P(companyId, name, scope, primKey);
671            }
672    
673            /**
674             * Returns all the roles associated with the action ID in the company within
675             * the permission scope.
676             *
677             * @param  companyId the primary key of the company
678             * @param  name the resource name
679             * @param  scope the permission scope
680             * @param  primKey the primary key of the resource's class
681             * @param  actionId the name of the resource action
682             * @return the roles
683             * @throws SystemException if a system exception occurred
684             * @see    com.liferay.portal.service.persistence.RoleFinder#findByC_N_S_P_A(
685             *         long, String, int, String, String)
686             */
687            @Override
688            public List<Role> getResourceRoles(
689                            long companyId, String name, int scope, String primKey,
690                            String actionId)
691                    throws SystemException {
692    
693                    return roleFinder.findByC_N_S_P_A(
694                            companyId, name, scope, primKey, actionId);
695            }
696    
697            /**
698             * Returns the role with the name in the company.
699             *
700             * <p>
701             * The method searches the system roles map first for default roles. If a
702             * role with the name is not found, then the method will query the database.
703             * </p>
704             *
705             * @param  companyId the primary key of the company
706             * @param  name the role's name
707             * @return the role with the name
708             * @throws PortalException if a role with the name could not be found in the
709             *         company
710             * @throws SystemException if a system exception occurred
711             */
712            @Override
713            @Skip
714            public Role getRole(long companyId, String name)
715                    throws PortalException, SystemException {
716    
717                    String companyIdHexString = StringUtil.toHexString(companyId);
718    
719                    Role role = _systemRolesMap.get(companyIdHexString.concat(name));
720    
721                    if (role != null) {
722                            return role;
723                    }
724    
725                    return roleLocalService.loadGetRole(companyId, name);
726            }
727    
728            /**
729             * Returns all the roles of the type and subtype.
730             *
731             * @param  type the role's type (optionally <code>0</code>)
732             * @param  subtype the role's subtype (optionally <code>null</code>)
733             * @return the roles of the type and subtype
734             * @throws SystemException if a system exception occurred
735             */
736            @Override
737            public List<Role> getRoles(int type, String subtype)
738                    throws SystemException {
739    
740                    return rolePersistence.findByT_S(type, subtype);
741            }
742    
743            /**
744             * Returns all the roles in the company.
745             *
746             * @param  companyId the primary key of the company
747             * @return the roles in the company
748             * @throws SystemException if a system exception occurred
749             */
750            @Override
751            public List<Role> getRoles(long companyId) throws SystemException {
752                    return rolePersistence.findByCompanyId(companyId);
753            }
754    
755            /**
756             * Returns all the roles with the types.
757             *
758             * @param  companyId the primary key of the company
759             * @param  types the role types (optionally <code>null</code>)
760             * @return the roles with the types
761             * @throws SystemException if a system exception occurred
762             */
763            @Override
764            public List<Role> getRoles(long companyId, int[] types)
765                    throws SystemException {
766    
767                    return rolePersistence.findByC_T(companyId, types);
768            }
769    
770            /**
771             * Returns all the roles with the primary keys.
772             *
773             * @param  roleIds the primary keys of the roles
774             * @return the roles with the primary keys
775             * @throws PortalException if any one of the roles with the primary keys
776             *         could not be found
777             * @throws SystemException if a system exception occurred
778             */
779            @Override
780            public List<Role> getRoles(long[] roleIds)
781                    throws PortalException, SystemException {
782    
783                    List<Role> roles = new ArrayList<Role>(roleIds.length);
784    
785                    for (long roleId : roleIds) {
786                            Role role = getRole(roleId);
787    
788                            roles.add(role);
789                    }
790    
791                    return roles;
792            }
793    
794            /**
795             * Returns all the roles of the subtype.
796             *
797             * @param  subtype the role's subtype (optionally <code>null</code>)
798             * @return the roles of the subtype
799             * @throws SystemException if a system exception occurred
800             */
801            @Override
802            public List<Role> getSubtypeRoles(String subtype) throws SystemException {
803                    return rolePersistence.findBySubtype(subtype);
804            }
805    
806            /**
807             * Returns the number of roles of the subtype.
808             *
809             * @param  subtype the role's subtype (optionally <code>null</code>)
810             * @return the number of roles of the subtype
811             * @throws SystemException if a system exception occurred
812             */
813            @Override
814            public int getSubtypeRolesCount(String subtype) throws SystemException {
815                    return rolePersistence.countBySubtype(subtype);
816            }
817    
818            /**
819             * Returns the team role in the company.
820             *
821             * @param  companyId the primary key of the company
822             * @param  teamId the primary key of the team
823             * @return the team role in the company
824             * @throws PortalException if a role could not be found in the team and
825             *         company
826             * @throws SystemException if a system exception occurred
827             */
828            @Override
829            public Role getTeamRole(long companyId, long teamId)
830                    throws PortalException, SystemException {
831    
832                    long classNameId = PortalUtil.getClassNameId(Team.class);
833    
834                    return rolePersistence.findByC_C_C(companyId, classNameId, teamId);
835            }
836    
837            /**
838             * Returns the team role map for the group.
839             *
840             * @param  groupId the primary key of the group
841             * @return the team role map for the group
842             * @throws PortalException if a group with the primary key could not be
843             *         found, if a role could not be found in one of the group's teams,
844             *         or if a portal exception occurred
845             * @throws SystemException if a system exception occurred
846             */
847            @Override
848            public Map<Team, Role> getTeamRoleMap(long groupId)
849                    throws PortalException, SystemException {
850    
851                    return getTeamRoleMap(groupId, null);
852            }
853    
854            /**
855             * Returns the team roles in the group.
856             *
857             * @param  groupId the primary key of the group
858             * @return the team roles in the group
859             * @throws PortalException if a group with the primary key could not be
860             *         found, if a role could not be found in one of the group's teams,
861             *         or if a portal exception occurred
862             * @throws SystemException if a system exception occurred
863             */
864            @Override
865            public List<Role> getTeamRoles(long groupId)
866                    throws PortalException, SystemException {
867    
868                    return getTeamRoles(groupId, null);
869            }
870    
871            /**
872             * Returns the team roles in the group, excluding the specified role IDs.
873             *
874             * @param  groupId the primary key of the group
875             * @param  excludedRoleIds the primary keys of the roles to exclude
876             *         (optionally <code>null</code>)
877             * @return the team roles in the group, excluding the specified role IDs
878             * @throws PortalException if a group with the primary key could not be
879             *         found, if a role could not be found in one of the group's teams,
880             *         or if a portal exception occurred
881             * @throws SystemException if a system exception occurred
882             */
883            @Override
884            public List<Role> getTeamRoles(long groupId, long[] excludedRoleIds)
885                    throws PortalException, SystemException {
886    
887                    Map<Team, Role> teamRoleMap = getTeamRoleMap(groupId, excludedRoleIds);
888    
889                    Collection<Role> roles = teamRoleMap.values();
890    
891                    return ListUtil.fromCollection(roles);
892            }
893    
894            /**
895             * Returns all the roles of the type.
896             *
897             * @param  type the role's type (optionally <code>0</code>)
898             * @return the range of the roles of the type
899             * @throws SystemException if a system exception occurred
900             */
901            @Override
902            public List<Role> getTypeRoles(int type) throws SystemException {
903                    return rolePersistence.findByType(type);
904            }
905    
906            /**
907             * Returns a range of all the roles of the type.
908             *
909             * @param  type the role's type (optionally <code>0</code>)
910             * @param  start the lower bound of the range of roles to return
911             * @param  end the upper bound of the range of roles to return (not
912             *         inclusive)
913             * @return the range of the roles of the type
914             * @throws SystemException if a system exception occurred
915             */
916            @Override
917            public List<Role> getTypeRoles(int type, int start, int end)
918                    throws SystemException {
919    
920                    return rolePersistence.findByType(type, start, end);
921            }
922    
923            /**
924             * Returns the number of roles of the type.
925             *
926             * @param  type the role's type (optionally <code>0</code>)
927             * @return the number of roles of the type
928             * @throws SystemException if a system exception occurred
929             */
930            @Override
931            public int getTypeRolesCount(int type) throws SystemException {
932                    return rolePersistence.countByType(type);
933            }
934    
935            /**
936             * Returns all the user's roles within the user group.
937             *
938             * @param  userId the primary key of the user
939             * @param  groupId the primary key of the group
940             * @return the user's roles within the user group
941             * @throws SystemException if a system exception occurred
942             * @see    com.liferay.portal.service.persistence.RoleFinder#findByUserGroupGroupRole(
943             *         long, long)
944             */
945            @Override
946            public List<Role> getUserGroupGroupRoles(long userId, long groupId)
947                    throws SystemException {
948    
949                    return roleFinder.findByUserGroupGroupRole(userId, groupId);
950            }
951    
952            /**
953             * Returns all the user's roles within the user group.
954             *
955             * @param  userId the primary key of the user
956             * @param  groupId the primary key of the group
957             * @return the user's roles within the user group
958             * @throws SystemException if a system exception occurred
959             * @see    com.liferay.portal.service.persistence.RoleFinder#findByUserGroupRole(
960             *         long, long)
961             */
962            @Override
963            public List<Role> getUserGroupRoles(long userId, long groupId)
964                    throws SystemException {
965    
966                    return roleFinder.findByUserGroupRole(userId, groupId);
967            }
968    
969            /**
970             * Returns the union of all the user's roles within the groups.
971             *
972             * @param  userId the primary key of the user
973             * @param  groups the groups (optionally <code>null</code>)
974             * @return the union of all the user's roles within the groups
975             * @throws SystemException if a system exception occurred
976             * @see    com.liferay.portal.service.persistence.RoleFinder#findByU_G(
977             *         long, List)
978             */
979            @Override
980            public List<Role> getUserRelatedRoles(long userId, List<Group> groups)
981                    throws SystemException {
982    
983                    if ((groups == null) || groups.isEmpty()) {
984                            return Collections.emptyList();
985                    }
986    
987                    return roleFinder.findByU_G(userId, groups);
988            }
989    
990            /**
991             * Returns all the user's roles within the group.
992             *
993             * @param  userId the primary key of the user
994             * @param  groupId the primary key of the group
995             * @return the user's roles within the group
996             * @throws SystemException if a system exception occurred
997             * @see    com.liferay.portal.service.persistence.RoleFinder#findByU_G(
998             *         long, long)
999             */
1000            @Override
1001            public List<Role> getUserRelatedRoles(long userId, long groupId)
1002                    throws SystemException {
1003    
1004                    return roleFinder.findByU_G(userId, groupId);
1005            }
1006    
1007            /**
1008             * Returns the union of all the user's roles within the groups.
1009             *
1010             * @param  userId the primary key of the user
1011             * @param  groupIds the primary keys of the groups
1012             * @return the union of all the user's roles within the groups
1013             * @throws SystemException if a system exception occurred
1014             * @see    com.liferay.portal.service.persistence.RoleFinder#findByU_G(
1015             *         long, long[])
1016             */
1017            @Override
1018            public List<Role> getUserRelatedRoles(long userId, long[] groupIds)
1019                    throws SystemException {
1020    
1021                    return roleFinder.findByU_G(userId, groupIds);
1022            }
1023    
1024            /**
1025             * Returns <code>true</code> if the user is associated with the named
1026             * regular role.
1027             *
1028             * @param  userId the primary key of the user
1029             * @param  companyId the primary key of the company
1030             * @param  name the name of the role
1031             * @param  inherited whether to include the user's inherited roles in the
1032             *         search
1033             * @return <code>true</code> if the user is associated with the regular
1034             *         role; <code>false</code> otherwise
1035             * @throws PortalException if a default user for the company could not be
1036             *         found
1037             * @throws SystemException if a system exception occurred
1038             */
1039            @Override
1040            @ThreadLocalCachable
1041            public boolean hasUserRole(
1042                            long userId, long companyId, String name, boolean inherited)
1043                    throws PortalException, SystemException {
1044    
1045                    Role role = rolePersistence.fetchByC_N(companyId, name);
1046    
1047                    if (role == null) {
1048                            return false;
1049                    }
1050    
1051                    if (role.getType() != RoleConstants.TYPE_REGULAR) {
1052                            throw new IllegalArgumentException(name + " is not a regular role");
1053                    }
1054    
1055                    long defaultUserId = userLocalService.getDefaultUserId(companyId);
1056    
1057                    if (userId == defaultUserId) {
1058                            if (name.equals(RoleConstants.GUEST)) {
1059                                    return true;
1060                            }
1061                            else {
1062                                    return false;
1063                            }
1064                    }
1065    
1066                    if (inherited) {
1067                            if (userPersistence.containsRole(userId, role.getRoleId())) {
1068                                    return true;
1069                            }
1070    
1071                            ThreadLocalCache<Integer> threadLocalCache =
1072                                    ThreadLocalCacheManager.getThreadLocalCache(
1073                                            Lifecycle.REQUEST, RoleLocalServiceImpl.class.getName());
1074    
1075                            String key = String.valueOf(role.getRoleId()).concat(
1076                                    String.valueOf(userId));
1077    
1078                            Integer value = threadLocalCache.get(key);
1079    
1080                            if (value == null) {
1081                                    value = roleFinder.countByR_U(role.getRoleId(), userId);
1082    
1083                                    threadLocalCache.put(key, value);
1084                            }
1085    
1086                            if (value > 0) {
1087                                    return true;
1088                            }
1089                            else {
1090                                    return false;
1091                            }
1092                    }
1093                    else {
1094                            return userPersistence.containsRole(userId, role.getRoleId());
1095                    }
1096            }
1097    
1098            /**
1099             * Returns <code>true</code> if the user has any one of the named regular
1100             * roles.
1101             *
1102             * @param  userId the primary key of the user
1103             * @param  companyId the primary key of the company
1104             * @param  names the names of the roles
1105             * @param  inherited whether to include the user's inherited roles in the
1106             *         search
1107             * @return <code>true</code> if the user has any one of the regular roles;
1108             *         <code>false</code> otherwise
1109             * @throws PortalException if any one of the roles with the names could not
1110             *         be found in the company or if the default user for the company
1111             *         could not be found
1112             * @throws SystemException if a system exception occurred
1113             */
1114            @Override
1115            public boolean hasUserRoles(
1116                            long userId, long companyId, String[] names, boolean inherited)
1117                    throws PortalException, SystemException {
1118    
1119                    for (String name : names) {
1120                            if (hasUserRole(userId, companyId, name, inherited)) {
1121                                    return true;
1122                            }
1123                    }
1124    
1125                    return false;
1126            }
1127    
1128            /**
1129             * Returns a role with the name in the company.
1130             *
1131             * @param  companyId the primary key of the company
1132             * @param  name the role's name (optionally <code>null</code>)
1133             * @return the role with the name, or <code>null</code> if a role with the
1134             *         name could not be found in the company
1135             * @throws SystemException if a system exception occurred
1136             */
1137            @Override
1138            public Role loadFetchRole(long companyId, String name)
1139                    throws SystemException {
1140    
1141                    return rolePersistence.fetchByC_N(companyId, name);
1142            }
1143    
1144            /**
1145             * Returns a role with the name in the company.
1146             *
1147             * @param  companyId the primary key of the company
1148             * @param  name the role's name
1149             * @return the role with the name in the company
1150             * @throws PortalException if a role with the name could not be found in the
1151             *         company
1152             * @throws SystemException if a system exception occurred
1153             */
1154            @Override
1155            public Role loadGetRole(long companyId, String name)
1156                    throws PortalException, SystemException {
1157    
1158                    return rolePersistence.findByC_N(companyId, name);
1159            }
1160    
1161            /**
1162             * Returns an ordered range of all the roles that match the keywords and
1163             * types.
1164             *
1165             * <p>
1166             * Useful when paginating results. Returns a maximum of <code>end -
1167             * start</code> instances. <code>start</code> and <code>end</code> are not
1168             * primary keys, they are indexes in the result set. Thus, <code>0</code>
1169             * refers to the first result in the set. Setting both <code>start</code>
1170             * and <code>end</code> to {@link
1171             * com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full
1172             * result set.
1173             * </p>
1174             *
1175             * @param  companyId the primary key of the company
1176             * @param  keywords the keywords (space separated), which may occur in the
1177             *         role's name or description (optionally <code>null</code>)
1178             * @param  types the role types (optionally <code>null</code>)
1179             * @param  start the lower bound of the range of roles to return
1180             * @param  end the upper bound of the range of roles to return (not
1181             *         inclusive)
1182             * @param  obc the comparator to order the roles (optionally
1183             *         <code>null</code>)
1184             * @return the ordered range of the matching roles, ordered by
1185             *         <code>obc</code>
1186             * @throws SystemException if a system exception occurred
1187             * @see    com.liferay.portal.service.persistence.RoleFinder
1188             */
1189            @Override
1190            public List<Role> search(
1191                            long companyId, String keywords, Integer[] types, int start,
1192                            int end, OrderByComparator obc)
1193                    throws SystemException {
1194    
1195                    return search(
1196                            companyId, keywords, types, new LinkedHashMap<String, Object>(),
1197                            start, end, obc);
1198            }
1199    
1200            /**
1201             * Returns an ordered range of all the roles that match the keywords, types,
1202             * and params.
1203             *
1204             * <p>
1205             * Useful when paginating results. Returns a maximum of <code>end -
1206             * start</code> instances. <code>start</code> and <code>end</code> are not
1207             * primary keys, they are indexes in the result set. Thus, <code>0</code>
1208             * refers to the first result in the set. Setting both <code>start</code>
1209             * and <code>end</code> to {@link
1210             * com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full
1211             * result set.
1212             * </p>
1213             *
1214             * @param  companyId the primary key of the company
1215             * @param  keywords the keywords (space separated), which may occur in the
1216             *         role's name or description (optionally <code>null</code>)
1217             * @param  types the role types (optionally <code>null</code>)
1218             * @param  params the finder parameters. Can specify values for the
1219             *         "usersRoles" key. For more information, see {@link
1220             *         com.liferay.portal.service.persistence.RoleFinder}
1221             * @param  start the lower bound of the range of roles to return
1222             * @param  end the upper bound of the range of roles to return (not
1223             *         inclusive)
1224             * @param  obc the comparator to order the roles (optionally
1225             *         <code>null</code>)
1226             * @return the ordered range of the matching roles, ordered by
1227             *         <code>obc</code>
1228             * @throws SystemException if a system exception occurred
1229             * @see    com.liferay.portal.service.persistence.RoleFinder
1230             */
1231            @Override
1232            public List<Role> search(
1233                            long companyId, String keywords, Integer[] types,
1234                            LinkedHashMap<String, Object> params, int start, int end,
1235                            OrderByComparator obc)
1236                    throws SystemException {
1237    
1238                    return roleFinder.findByKeywords(
1239                            companyId, keywords, types, params, start, end, obc);
1240            }
1241    
1242            /**
1243             * Returns an ordered range of all the roles that match the name,
1244             * description, and types.
1245             *
1246             * <p>
1247             * Useful when paginating results. Returns a maximum of <code>end -
1248             * start</code> instances. <code>start</code> and <code>end</code> are not
1249             * primary keys, they are indexes in the result set. Thus, <code>0</code>
1250             * refers to the first result in the set. Setting both <code>start</code>
1251             * and <code>end</code> to {@link
1252             * com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full
1253             * result set.
1254             * </p>
1255             *
1256             * @param  companyId the primary key of the company
1257             * @param  name the role's name (optionally <code>null</code>)
1258             * @param  description the role's description (optionally <code>null</code>)
1259             * @param  types the role types (optionally <code>null</code>)
1260             * @param  start the lower bound of the range of the roles to return
1261             * @param  end the upper bound of the range of the roles to return (not
1262             *         inclusive)
1263             * @param  obc the comparator to order the roles (optionally
1264             *         <code>null</code>)
1265             * @return the ordered range of the matching roles, ordered by
1266             *         <code>obc</code>
1267             * @throws SystemException if a system exception occurred
1268             * @see    com.liferay.portal.service.persistence.RoleFinder
1269             */
1270            @Override
1271            public List<Role> search(
1272                            long companyId, String name, String description, Integer[] types,
1273                            int start, int end, OrderByComparator obc)
1274                    throws SystemException {
1275    
1276                    return search(
1277                            companyId, name, description, types,
1278                            new LinkedHashMap<String, Object>(), start, end, obc);
1279            }
1280    
1281            /**
1282             * Returns an ordered range of all the roles that match the name,
1283             * description, types, and params.
1284             *
1285             * <p>
1286             * Useful when paginating results. Returns a maximum of <code>end -
1287             * start</code> instances. <code>start</code> and <code>end</code> are not
1288             * primary keys, they are indexes in the result set. Thus, <code>0</code>
1289             * refers to the first result in the set. Setting both <code>start</code>
1290             * and <code>end</code> to {@link
1291             * com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full
1292             * result set.
1293             * </p>
1294             *
1295             * @param  companyId the primary key of the company
1296             * @param  name the role's name (optionally <code>null</code>)
1297             * @param  description the role's description (optionally <code>null</code>)
1298             * @param  types the role types (optionally <code>null</code>)
1299             * @param  params the finder's parameters. Can specify values for the
1300             *         "usersRoles" key. For more information, see {@link
1301             *         com.liferay.portal.service.persistence.RoleFinder}
1302             * @param  start the lower bound of the range of the roles to return
1303             * @param  end the upper bound of the range of the roles to return (not
1304             *         inclusive)
1305             * @param  obc the comparator to order the roles (optionally
1306             *         <code>null</code>)
1307             * @return the ordered range of the matching roles, ordered by
1308             *         <code>obc</code>
1309             * @throws SystemException if a system exception occurred
1310             * @see    com.liferay.portal.service.persistence.RoleFinder
1311             */
1312            @Override
1313            public List<Role> search(
1314                            long companyId, String name, String description, Integer[] types,
1315                            LinkedHashMap<String, Object> params, int start, int end,
1316                            OrderByComparator obc)
1317                    throws SystemException {
1318    
1319                    return roleFinder.findByC_N_D_T(
1320                            companyId, name, description, types, params, true, start, end, obc);
1321            }
1322    
1323            /**
1324             * Returns the number of roles that match the keywords and types.
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             * @return the number of matching roles
1331             * @throws SystemException if a system exception occurred
1332             */
1333            @Override
1334            public int searchCount(long companyId, String keywords, Integer[] types)
1335                    throws SystemException {
1336    
1337                    return searchCount(
1338                            companyId, keywords, types, new LinkedHashMap<String, Object>());
1339            }
1340    
1341            /**
1342             * Returns the number of roles that match the keywords, types and params.
1343             *
1344             * @param  companyId the primary key of the company
1345             * @param  keywords the keywords (space separated), which may occur in the
1346             *         role's name or description (optionally <code>null</code>)
1347             * @param  types the role types (optionally <code>null</code>)
1348             * @param  params the finder parameters. For more information, see {@link
1349             *         com.liferay.portal.service.persistence.RoleFinder}
1350             * @return the number of matching roles
1351             * @throws SystemException if a system exception occurred
1352             */
1353            @Override
1354            public int searchCount(
1355                            long companyId, String keywords, Integer[] types,
1356                            LinkedHashMap<String, Object> params)
1357                    throws SystemException {
1358    
1359                    return roleFinder.countByKeywords(companyId, keywords, types, params);
1360            }
1361    
1362            /**
1363             * Returns the number of roles that match the name, description, and types.
1364             *
1365             * @param  companyId the primary key of the company
1366             * @param  name the role's name (optionally <code>null</code>)
1367             * @param  description the role's description (optionally <code>null</code>)
1368             * @param  types the role types (optionally <code>null</code>)
1369             * @return the number of matching roles
1370             * @throws SystemException if a system exception occurred
1371             */
1372            @Override
1373            public int searchCount(
1374                            long companyId, String name, String description, Integer[] types)
1375                    throws SystemException {
1376    
1377                    return searchCount(
1378                            companyId, name, description, types,
1379                            new LinkedHashMap<String, Object>());
1380            }
1381    
1382            /**
1383             * Returns the number of roles that match the name, description, types, and
1384             * params.
1385             *
1386             * @param  companyId the primary key of the company
1387             * @param  name the role's name (optionally <code>null</code>)
1388             * @param  description the role's description (optionally <code>null</code>)
1389             * @param  types the role types (optionally <code>null</code>)
1390             * @param  params the finder parameters. Can specify values for the
1391             *         "usersRoles" key. For more information, see {@link
1392             *         com.liferay.portal.service.persistence.RoleFinder}
1393             * @return the number of matching roles
1394             * @throws SystemException if a system exception occurred
1395             */
1396            @Override
1397            public int searchCount(
1398                            long companyId, String name, String description, Integer[] types,
1399                            LinkedHashMap<String, Object> params)
1400                    throws SystemException {
1401    
1402                    return roleFinder.countByC_N_D_T(
1403                            companyId, name, description, types, params, true);
1404            }
1405    
1406            /**
1407             * Sets the roles associated with the user, replacing the user's existing
1408             * roles. The user is reindexed after the roles are set.
1409             *
1410             * @param  userId the primary key of the user
1411             * @param  roleIds the primary keys of the roles
1412             * @throws PortalException if a user with the primary could not be found or
1413             *         if any one of the roles with the primary keys could not be found
1414             * @throws SystemException if a system exception occurred
1415             */
1416            @Override
1417            public void setUserRoles(long userId, long[] roleIds)
1418                    throws PortalException, SystemException {
1419    
1420                    roleIds = UsersAdminUtil.addRequiredRoles(userId, roleIds);
1421    
1422                    userPersistence.setRoles(userId, roleIds);
1423    
1424                    Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
1425    
1426                    indexer.reindex(userId);
1427    
1428                    PermissionCacheUtil.clearCache();
1429            }
1430    
1431            /**
1432             * Removes the matching roles associated with the user. The user is
1433             * reindexed after the roles are removed.
1434             *
1435             * @param  userId the primary key of the user
1436             * @param  roleIds the primary keys of the roles
1437             * @throws PortalException if a user with the primary key could not be found
1438             *         or if a role with any one of the primary keys could not be found
1439             * @throws SystemException if a system exception occurred
1440             */
1441            @Override
1442            public void unsetUserRoles(long userId, long[] roleIds)
1443                    throws PortalException, SystemException {
1444    
1445                    roleIds = UsersAdminUtil.removeRequiredRoles(userId, roleIds);
1446    
1447                    userPersistence.removeRoles(userId, roleIds);
1448    
1449                    Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
1450    
1451                    indexer.reindex(userId);
1452    
1453                    PermissionCacheUtil.clearCache();
1454            }
1455    
1456            /**
1457             * Updates the role with the primary key.
1458             *
1459             * @param  roleId the primary key of the role
1460             * @param  name the role's new name
1461             * @param  titleMap the new localized titles (optionally <code>null</code>)
1462             *         to replace those existing for the role
1463             * @param  descriptionMap the new localized descriptions (optionally
1464             *         <code>null</code>) to replace those existing for the role
1465             * @param  subtype the role's new subtype (optionally <code>null</code>)
1466             * @param  serviceContext the service context to be applied (optionally
1467             *         <code>null</code>). Can set expando bridge attributes for the
1468             *         role.
1469             * @return the role with the primary key
1470             * @throws PortalException if a role with the primary could not be found or
1471             *         if the role's name was invalid
1472             * @throws SystemException if a system exception occurred
1473             */
1474            @Override
1475            public Role updateRole(
1476                            long roleId, String name, Map<Locale, String> titleMap,
1477                            Map<Locale, String> descriptionMap, String subtype,
1478                            ServiceContext serviceContext)
1479                    throws PortalException, SystemException {
1480    
1481                    Role role = rolePersistence.findByPrimaryKey(roleId);
1482    
1483                    validate(roleId, role.getCompanyId(), role.getClassNameId(), name);
1484    
1485                    if (PortalUtil.isSystemRole(role.getName())) {
1486                            name = role.getName();
1487                            subtype = null;
1488                    }
1489    
1490                    role.setModifiedDate(new Date());
1491                    role.setName(name);
1492                    role.setTitleMap(titleMap);
1493                    role.setDescriptionMap(descriptionMap);
1494                    role.setSubtype(subtype);
1495                    role.setExpandoBridgeAttributes(serviceContext);
1496    
1497                    rolePersistence.update(role);
1498    
1499                    return role;
1500            }
1501    
1502            protected void checkSystemRole(
1503                            long companyId, String name, Map<Locale, String> descriptionMap,
1504                            int type)
1505                    throws PortalException, SystemException {
1506    
1507                    String companyIdHexString = StringUtil.toHexString(companyId);
1508    
1509                    String key = companyIdHexString.concat(name);
1510    
1511                    Role role = _systemRolesMap.get(key);
1512    
1513                    try {
1514                            if (role == null) {
1515                                    role = rolePersistence.findByC_N(companyId, name);
1516                            }
1517    
1518                            if (!descriptionMap.equals(role.getDescriptionMap())) {
1519                                    role.setDescriptionMap(descriptionMap);
1520    
1521                                    roleLocalService.updateRole(role);
1522                            }
1523                    }
1524                    catch (NoSuchRoleException nsre) {
1525                            User user = userLocalService.getDefaultUser(companyId);
1526    
1527                            role = roleLocalService.addRole(
1528                                    user.getUserId(), null, 0, name, null, descriptionMap, type,
1529                                    null, null);
1530    
1531                            if (name.equals(RoleConstants.USER)) {
1532                                    initPersonalControlPanelPortletsPermissions(role);
1533                            }
1534                    }
1535    
1536                    _systemRolesMap.put(key, role);
1537            }
1538    
1539            protected String[] getDefaultControlPanelPortlets() {
1540                    return new String[] {
1541                            PortletKeys.MY_ACCOUNT, PortletKeys.MY_PAGES,
1542                            PortletKeys.MY_WORKFLOW_INSTANCES, PortletKeys.MY_WORKFLOW_TASKS
1543                    };
1544            }
1545    
1546            protected Map<Team, Role> getTeamRoleMap(
1547                            long groupId, long[] excludedRoleIds)
1548                    throws PortalException, SystemException {
1549    
1550                    Group group = groupPersistence.findByPrimaryKey(groupId);
1551    
1552                    if (group.isLayout()) {
1553                            group = group.getParentGroup();
1554                    }
1555    
1556                    List<Team> teams = teamPersistence.findByGroupId(group.getGroupId());
1557    
1558                    if (teams.isEmpty()) {
1559                            return Collections.emptyMap();
1560                    }
1561    
1562                    Set<Long> roleIds = SetUtil.fromArray(excludedRoleIds);
1563    
1564                    Map<Team, Role> teamRoleMap = new LinkedHashMap<Team, Role>();
1565    
1566                    for (Team team : teams) {
1567                            Role role = getTeamRole(team.getCompanyId(), team.getTeamId());
1568    
1569                            if (roleIds.contains(role.getRoleId())) {
1570                                    continue;
1571                            }
1572    
1573                            teamRoleMap.put(team, role);
1574                    }
1575    
1576                    return teamRoleMap;
1577            }
1578    
1579            protected void initPersonalControlPanelPortletsPermissions(Role role)
1580                    throws PortalException, SystemException {
1581    
1582                    for (String portletId : getDefaultControlPanelPortlets()) {
1583                            int count = resourcePermissionPersistence.countByC_N_S_P_R(
1584                                    role.getCompanyId(), portletId, ResourceConstants.SCOPE_COMPANY,
1585                                    String.valueOf(role.getCompanyId()), role.getRoleId());
1586    
1587                            if (count > 0) {
1588                                    continue;
1589                            }
1590    
1591                            ResourceAction resourceAction =
1592                                    resourceActionLocalService.fetchResourceAction(
1593                                            portletId, ActionKeys.ACCESS_IN_CONTROL_PANEL);
1594    
1595                            if (resourceAction == null) {
1596                                    continue;
1597                            }
1598    
1599                            setRolePermissions(
1600                                    role, portletId,
1601                                    new String[] {
1602                                            ActionKeys.ACCESS_IN_CONTROL_PANEL
1603                                    });
1604                    }
1605            }
1606    
1607            protected void setRolePermissions(
1608                            Role role, String name, String[] actionIds)
1609                    throws PortalException, SystemException {
1610    
1611                    if (resourceBlockLocalService.isSupported(name)) {
1612                            resourceBlockLocalService.setCompanyScopePermissions(
1613                                    role.getCompanyId(), name, role.getRoleId(),
1614                                    Arrays.asList(actionIds));
1615                    }
1616                    else {
1617                            resourcePermissionLocalService.setResourcePermissions(
1618                                    role.getCompanyId(), name, ResourceConstants.SCOPE_COMPANY,
1619                                    String.valueOf(role.getCompanyId()), role.getRoleId(),
1620                                    actionIds);
1621                    }
1622            }
1623    
1624            protected void validate(
1625                            long roleId, long companyId, long classNameId, String name)
1626                    throws PortalException, SystemException {
1627    
1628                    if (classNameId == PortalUtil.getClassNameId(Role.class)) {
1629                            if (Validator.isNull(name) ||
1630                                    (name.indexOf(CharPool.COMMA) != -1) ||
1631                                    (name.indexOf(CharPool.STAR) != -1)) {
1632    
1633                                    throw new RoleNameException();
1634                            }
1635    
1636                            if (Validator.isNumber(name) &&
1637                                    !PropsValues.ROLES_NAME_ALLOW_NUMERIC) {
1638    
1639                                    throw new RoleNameException();
1640                            }
1641                    }
1642    
1643                    try {
1644                            Role role = roleFinder.findByC_N(companyId, name);
1645    
1646                            if (role.getRoleId() != roleId) {
1647                                    throw new DuplicateRoleException();
1648                            }
1649                    }
1650                    catch (NoSuchRoleException nsre) {
1651                    }
1652            }
1653    
1654            private Map<String, Role> _systemRolesMap = new HashMap<String, Role>();
1655    
1656    }