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