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