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            /**
708             * Returns all the roles with the primary keys.
709             *
710             * @param  roleIds the primary keys of the roles
711             * @return the roles with the primary keys
712             * @throws PortalException if any one of the roles with the primary keys
713             *         could not be found
714             * @throws SystemException if a system exception occurred
715             */
716            @Override
717            public List<Role> getRoles(long[] roleIds)
718                    throws PortalException, SystemException {
719    
720                    List<Role> roles = new ArrayList<Role>(roleIds.length);
721    
722                    for (long roleId : roleIds) {
723                            Role role = getRole(roleId);
724    
725                            roles.add(role);
726                    }
727    
728                    return roles;
729            }
730    
731            /**
732             * Returns all the roles of the subtype.
733             *
734             * @param  subtype the role's subtype (optionally <code>null</code>)
735             * @return the roles of the subtype
736             * @throws SystemException if a system exception occurred
737             */
738            @Override
739            public List<Role> getSubtypeRoles(String subtype) throws SystemException {
740                    return rolePersistence.findBySubtype(subtype);
741            }
742    
743            /**
744             * Returns the number of roles of the subtype.
745             *
746             * @param  subtype the role's subtype (optionally <code>null</code>)
747             * @return the number of roles of the subtype
748             * @throws SystemException if a system exception occurred
749             */
750            @Override
751            public int getSubtypeRolesCount(String subtype) throws SystemException {
752                    return rolePersistence.countBySubtype(subtype);
753            }
754    
755            /**
756             * Returns the team role in the company.
757             *
758             * @param  companyId the primary key of the company
759             * @param  teamId the primary key of the team
760             * @return the team role in the company
761             * @throws PortalException if a role could not be found in the team and
762             *         company
763             * @throws SystemException if a system exception occurred
764             */
765            @Override
766            public Role getTeamRole(long companyId, long teamId)
767                    throws PortalException, SystemException {
768    
769                    long classNameId = PortalUtil.getClassNameId(Team.class);
770    
771                    return rolePersistence.findByC_C_C(companyId, classNameId, teamId);
772            }
773    
774            /**
775             * Returns all the roles of the type.
776             *
777             * @param  type the role's type (optionally <code>0</code>)
778             * @return the range of the roles of the type
779             * @throws SystemException if a system exception occurred
780             */
781            @Override
782            public List<Role> getTypeRoles(int type) throws SystemException {
783                    return rolePersistence.findByType(type);
784            }
785    
786            /**
787             * Returns a range of all the roles of the type.
788             *
789             * @param  type the role's type (optionally <code>0</code>)
790             * @param  start the lower bound of the range of roles to return
791             * @param  end the upper bound of the range of roles to return (not
792             *         inclusive)
793             * @return the range of the roles of the type
794             * @throws SystemException if a system exception occurred
795             */
796            @Override
797            public List<Role> getTypeRoles(int type, int start, int end)
798                    throws SystemException {
799    
800                    return rolePersistence.findByType(type, start, end);
801            }
802    
803            /**
804             * Returns the number of roles of the type.
805             *
806             * @param  type the role's type (optionally <code>0</code>)
807             * @return the number of roles of the type
808             * @throws SystemException if a system exception occurred
809             */
810            @Override
811            public int getTypeRolesCount(int type) throws SystemException {
812                    return rolePersistence.countByType(type);
813            }
814    
815            /**
816             * Returns all the user's roles within the user group.
817             *
818             * @param  userId the primary key of the user
819             * @param  groupId the primary key of the group
820             * @return the user's roles within the user group
821             * @throws SystemException if a system exception occurred
822             * @see    com.liferay.portal.service.persistence.RoleFinder#findByUserGroupGroupRole(
823             *         long, long)
824             */
825            @Override
826            public List<Role> getUserGroupGroupRoles(long userId, long groupId)
827                    throws SystemException {
828    
829                    return roleFinder.findByUserGroupGroupRole(userId, groupId);
830            }
831    
832            /**
833             * Returns all the user's roles within the user group.
834             *
835             * @param  userId the primary key of the user
836             * @param  groupId the primary key of the group
837             * @return the user's roles within the user group
838             * @throws SystemException if a system exception occurred
839             * @see    com.liferay.portal.service.persistence.RoleFinder#findByUserGroupRole(
840             *         long, long)
841             */
842            @Override
843            public List<Role> getUserGroupRoles(long userId, long groupId)
844                    throws SystemException {
845    
846                    return roleFinder.findByUserGroupRole(userId, groupId);
847            }
848    
849            /**
850             * Returns the union of all the user's roles within the groups.
851             *
852             * @param  userId the primary key of the user
853             * @param  groups the groups (optionally <code>null</code>)
854             * @return the union of all the user's roles within the groups
855             * @throws SystemException if a system exception occurred
856             * @see    com.liferay.portal.service.persistence.RoleFinder#findByU_G(
857             *         long, List)
858             */
859            @Override
860            public List<Role> getUserRelatedRoles(long userId, List<Group> groups)
861                    throws SystemException {
862    
863                    if ((groups == null) || groups.isEmpty()) {
864                            return Collections.emptyList();
865                    }
866    
867                    return roleFinder.findByU_G(userId, groups);
868            }
869    
870            /**
871             * Returns all the user's roles within the group.
872             *
873             * @param  userId the primary key of the user
874             * @param  groupId the primary key of the group
875             * @return the user's roles within the group
876             * @throws SystemException if a system exception occurred
877             * @see    com.liferay.portal.service.persistence.RoleFinder#findByU_G(
878             *         long, long)
879             */
880            @Override
881            public List<Role> getUserRelatedRoles(long userId, long groupId)
882                    throws SystemException {
883    
884                    return roleFinder.findByU_G(userId, groupId);
885            }
886    
887            /**
888             * Returns the union of all the user's roles within the groups.
889             *
890             * @param  userId the primary key of the user
891             * @param  groupIds the primary keys of the groups
892             * @return the union of all the user's roles within the groups
893             * @throws SystemException if a system exception occurred
894             * @see    com.liferay.portal.service.persistence.RoleFinder#findByU_G(
895             *         long, long[])
896             */
897            @Override
898            public List<Role> getUserRelatedRoles(long userId, long[] groupIds)
899                    throws SystemException {
900    
901                    return roleFinder.findByU_G(userId, groupIds);
902            }
903    
904            /**
905             * Returns <code>true</code> if the user is associated with the named
906             * regular role.
907             *
908             * @param  userId the primary key of the user
909             * @param  companyId the primary key of the company
910             * @param  name the name of the role
911             * @param  inherited whether to include the user's inherited roles in the
912             *         search
913             * @return <code>true</code> if the user is associated with the regular
914             *         role; <code>false</code> otherwise
915             * @throws PortalException if a default user for the company could not be
916             *         found
917             * @throws SystemException if a system exception occurred
918             */
919            @Override
920            @ThreadLocalCachable
921            public boolean hasUserRole(
922                            long userId, long companyId, String name, boolean inherited)
923                    throws PortalException, SystemException {
924    
925                    Role role = rolePersistence.fetchByC_N(companyId, name);
926    
927                    if (role == null) {
928                            return false;
929                    }
930    
931                    if (role.getType() != RoleConstants.TYPE_REGULAR) {
932                            throw new IllegalArgumentException(name + " is not a regular role");
933                    }
934    
935                    long defaultUserId = userLocalService.getDefaultUserId(companyId);
936    
937                    if (userId == defaultUserId) {
938                            if (name.equals(RoleConstants.GUEST)) {
939                                    return true;
940                            }
941                            else {
942                                    return false;
943                            }
944                    }
945    
946                    if (inherited) {
947                            if (userPersistence.containsRole(userId, role.getRoleId())) {
948                                    return true;
949                            }
950    
951                            ThreadLocalCache<Integer> threadLocalCache =
952                                    ThreadLocalCacheManager.getThreadLocalCache(
953                                            Lifecycle.REQUEST, RoleLocalServiceImpl.class.getName());
954    
955                            String key = String.valueOf(role.getRoleId()).concat(
956                                    String.valueOf(userId));
957    
958                            Integer value = threadLocalCache.get(key);
959    
960                            if (value == null) {
961                                    value = roleFinder.countByR_U(role.getRoleId(), userId);
962    
963                                    threadLocalCache.put(key, value);
964                            }
965    
966                            if (value > 0) {
967                                    return true;
968                            }
969                            else {
970                                    return false;
971                            }
972                    }
973                    else {
974                            return userPersistence.containsRole(userId, role.getRoleId());
975                    }
976            }
977    
978            /**
979             * Returns <code>true</code> if the user has any one of the named regular
980             * roles.
981             *
982             * @param  userId the primary key of the user
983             * @param  companyId the primary key of the company
984             * @param  names the names of the roles
985             * @param  inherited whether to include the user's inherited roles in the
986             *         search
987             * @return <code>true</code> if the user has any one of the regular roles;
988             *         <code>false</code> otherwise
989             * @throws PortalException if any one of the roles with the names could not
990             *         be found in the company or if the default user for the company
991             *         could not be found
992             * @throws SystemException if a system exception occurred
993             */
994            @Override
995            public boolean hasUserRoles(
996                            long userId, long companyId, String[] names, boolean inherited)
997                    throws PortalException, SystemException {
998    
999                    for (String name : names) {
1000                            if (hasUserRole(userId, companyId, name, inherited)) {
1001                                    return true;
1002                            }
1003                    }
1004    
1005                    return false;
1006            }
1007    
1008            /**
1009             * Returns a role with the name in the company.
1010             *
1011             * @param  companyId the primary key of the company
1012             * @param  name the role's name (optionally <code>null</code>)
1013             * @return the role with the name, or <code>null</code> if a role with the
1014             *         name could not be found in the company
1015             * @throws SystemException if a system exception occurred
1016             */
1017            @Override
1018            public Role loadFetchRole(long companyId, String name)
1019                    throws SystemException {
1020    
1021                    return rolePersistence.fetchByC_N(companyId, name);
1022            }
1023    
1024            /**
1025             * Returns a role with the name in the company.
1026             *
1027             * @param  companyId the primary key of the company
1028             * @param  name the role's name
1029             * @return the role with the name in the company
1030             * @throws PortalException if a role with the name could not be found in the
1031             *         company
1032             * @throws SystemException if a system exception occurred
1033             */
1034            @Override
1035            public Role loadGetRole(long companyId, String name)
1036                    throws PortalException, SystemException {
1037    
1038                    return rolePersistence.findByC_N(companyId, name);
1039            }
1040    
1041            /**
1042             * Returns an ordered range of all the roles that match the keywords and
1043             * types.
1044             *
1045             * <p>
1046             * Useful when paginating results. Returns a maximum of <code>end -
1047             * start</code> instances. <code>start</code> and <code>end</code> are not
1048             * primary keys, they are indexes in the result set. Thus, <code>0</code>
1049             * refers to the first result in the set. Setting both <code>start</code>
1050             * and <code>end</code> to {@link
1051             * com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full
1052             * result set.
1053             * </p>
1054             *
1055             * @param  companyId the primary key of the company
1056             * @param  keywords the keywords (space separated), which may occur in the
1057             *         role's name or description (optionally <code>null</code>)
1058             * @param  types the role types (optionally <code>null</code>)
1059             * @param  start the lower bound of the range of roles to return
1060             * @param  end the upper bound of the range of roles to return (not
1061             *         inclusive)
1062             * @param  obc the comparator to order the roles (optionally
1063             *         <code>null</code>)
1064             * @return the ordered range of the matching roles, ordered by
1065             *         <code>obc</code>
1066             * @throws SystemException if a system exception occurred
1067             * @see    com.liferay.portal.service.persistence.RoleFinder
1068             */
1069            @Override
1070            public List<Role> search(
1071                            long companyId, String keywords, Integer[] types, int start,
1072                            int end, OrderByComparator obc)
1073                    throws SystemException {
1074    
1075                    return search(
1076                            companyId, keywords, types, new LinkedHashMap<String, Object>(),
1077                            start, end, obc);
1078            }
1079    
1080            /**
1081             * Returns an ordered range of all the roles that match the keywords, types,
1082             * and params.
1083             *
1084             * <p>
1085             * Useful when paginating results. Returns a maximum of <code>end -
1086             * start</code> instances. <code>start</code> and <code>end</code> are not
1087             * primary keys, they are indexes in the result set. Thus, <code>0</code>
1088             * refers to the first result in the set. Setting both <code>start</code>
1089             * and <code>end</code> to {@link
1090             * com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full
1091             * result set.
1092             * </p>
1093             *
1094             * @param  companyId the primary key of the company
1095             * @param  keywords the keywords (space separated), which may occur in the
1096             *         role's name or description (optionally <code>null</code>)
1097             * @param  types the role types (optionally <code>null</code>)
1098             * @param  params the finder parameters. Can specify values for the
1099             *         "usersRoles" key. For more information, see {@link
1100             *         com.liferay.portal.service.persistence.RoleFinder}
1101             * @param  start the lower bound of the range of roles to return
1102             * @param  end the upper bound of the range of roles to return (not
1103             *         inclusive)
1104             * @param  obc the comparator to order the roles (optionally
1105             *         <code>null</code>)
1106             * @return the ordered range of the matching roles, ordered by
1107             *         <code>obc</code>
1108             * @throws SystemException if a system exception occurred
1109             * @see    com.liferay.portal.service.persistence.RoleFinder
1110             */
1111            @Override
1112            public List<Role> search(
1113                            long companyId, String keywords, Integer[] types,
1114                            LinkedHashMap<String, Object> params, int start, int end,
1115                            OrderByComparator obc)
1116                    throws SystemException {
1117    
1118                    return roleFinder.findByKeywords(
1119                            companyId, keywords, types, params, start, end, obc);
1120            }
1121    
1122            /**
1123             * Returns an ordered range of all the roles that match the name,
1124             * description, and types.
1125             *
1126             * <p>
1127             * Useful when paginating results. Returns a maximum of <code>end -
1128             * start</code> instances. <code>start</code> and <code>end</code> are not
1129             * primary keys, they are indexes in the result set. Thus, <code>0</code>
1130             * refers to the first result in the set. Setting both <code>start</code>
1131             * and <code>end</code> to {@link
1132             * com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full
1133             * result set.
1134             * </p>
1135             *
1136             * @param  companyId the primary key of the company
1137             * @param  name the role's name (optionally <code>null</code>)
1138             * @param  description the role's description (optionally <code>null</code>)
1139             * @param  types the role types (optionally <code>null</code>)
1140             * @param  start the lower bound of the range of the roles to return
1141             * @param  end the upper bound of the range of the roles to return (not
1142             *         inclusive)
1143             * @param  obc the comparator to order the roles (optionally
1144             *         <code>null</code>)
1145             * @return the ordered range of the matching roles, ordered by
1146             *         <code>obc</code>
1147             * @throws SystemException if a system exception occurred
1148             * @see    com.liferay.portal.service.persistence.RoleFinder
1149             */
1150            @Override
1151            public List<Role> search(
1152                            long companyId, String name, String description, Integer[] types,
1153                            int start, int end, OrderByComparator obc)
1154                    throws SystemException {
1155    
1156                    return search(
1157                            companyId, name, description, types,
1158                            new LinkedHashMap<String, Object>(), start, end, obc);
1159            }
1160    
1161            /**
1162             * Returns an ordered range of all the roles that match the name,
1163             * description, types, and params.
1164             *
1165             * <p>
1166             * Useful when paginating results. Returns a maximum of <code>end -
1167             * start</code> instances. <code>start</code> and <code>end</code> are not
1168             * primary keys, they are indexes in the result set. Thus, <code>0</code>
1169             * refers to the first result in the set. Setting both <code>start</code>
1170             * and <code>end</code> to {@link
1171             * com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full
1172             * result set.
1173             * </p>
1174             *
1175             * @param  companyId the primary key of the company
1176             * @param  name the role's name (optionally <code>null</code>)
1177             * @param  description the role's description (optionally <code>null</code>)
1178             * @param  types the role types (optionally <code>null</code>)
1179             * @param  params the finder's parameters. Can specify values for the
1180             *         "usersRoles" key. For more information, see {@link
1181             *         com.liferay.portal.service.persistence.RoleFinder}
1182             * @param  start the lower bound of the range of the roles to return
1183             * @param  end the upper bound of the range of the roles to return (not
1184             *         inclusive)
1185             * @param  obc the comparator to order the roles (optionally
1186             *         <code>null</code>)
1187             * @return the ordered range of the matching roles, ordered by
1188             *         <code>obc</code>
1189             * @throws SystemException if a system exception occurred
1190             * @see    com.liferay.portal.service.persistence.RoleFinder
1191             */
1192            @Override
1193            public List<Role> search(
1194                            long companyId, String name, String description, Integer[] types,
1195                            LinkedHashMap<String, Object> params, int start, int end,
1196                            OrderByComparator obc)
1197                    throws SystemException {
1198    
1199                    return roleFinder.findByC_N_D_T(
1200                            companyId, name, description, types, params, true, start, end, obc);
1201            }
1202    
1203            /**
1204             * Returns the number of roles that match the keywords and types.
1205             *
1206             * @param  companyId the primary key of the company
1207             * @param  keywords the keywords (space separated), which may occur in the
1208             *         role's name or description (optionally <code>null</code>)
1209             * @param  types the role types (optionally <code>null</code>)
1210             * @return the number of matching roles
1211             * @throws SystemException if a system exception occurred
1212             */
1213            @Override
1214            public int searchCount(long companyId, String keywords, Integer[] types)
1215                    throws SystemException {
1216    
1217                    return searchCount(
1218                            companyId, keywords, types, new LinkedHashMap<String, Object>());
1219            }
1220    
1221            /**
1222             * Returns the number of roles that match the keywords, types and params.
1223             *
1224             * @param  companyId the primary key of the company
1225             * @param  keywords the keywords (space separated), which may occur in the
1226             *         role's name or description (optionally <code>null</code>)
1227             * @param  types the role types (optionally <code>null</code>)
1228             * @param  params the finder parameters. For more information, see {@link
1229             *         com.liferay.portal.service.persistence.RoleFinder}
1230             * @return the number of matching roles
1231             * @throws SystemException if a system exception occurred
1232             */
1233            @Override
1234            public int searchCount(
1235                            long companyId, String keywords, Integer[] types,
1236                            LinkedHashMap<String, Object> params)
1237                    throws SystemException {
1238    
1239                    return roleFinder.countByKeywords(companyId, keywords, types, params);
1240            }
1241    
1242            /**
1243             * Returns the number of roles that match the name, description, and types.
1244             *
1245             * @param  companyId the primary key of the company
1246             * @param  name the role's name (optionally <code>null</code>)
1247             * @param  description the role's description (optionally <code>null</code>)
1248             * @param  types the role types (optionally <code>null</code>)
1249             * @return the number of matching roles
1250             * @throws SystemException if a system exception occurred
1251             */
1252            @Override
1253            public int searchCount(
1254                            long companyId, String name, String description, Integer[] types)
1255                    throws SystemException {
1256    
1257                    return searchCount(
1258                            companyId, name, description, types,
1259                            new LinkedHashMap<String, Object>());
1260            }
1261    
1262            /**
1263             * Returns the number of roles that match the name, description, types, and
1264             * params.
1265             *
1266             * @param  companyId the primary key of the company
1267             * @param  name the role's name (optionally <code>null</code>)
1268             * @param  description the role's description (optionally <code>null</code>)
1269             * @param  types the role types (optionally <code>null</code>)
1270             * @param  params the finder parameters. Can specify values for the
1271             *         "usersRoles" key. For more information, see {@link
1272             *         com.liferay.portal.service.persistence.RoleFinder}
1273             * @return the number of matching roles
1274             * @throws SystemException if a system exception occurred
1275             */
1276            @Override
1277            public int searchCount(
1278                            long companyId, String name, String description, Integer[] types,
1279                            LinkedHashMap<String, Object> params)
1280                    throws SystemException {
1281    
1282                    return roleFinder.countByC_N_D_T(
1283                            companyId, name, description, types, params, true);
1284            }
1285    
1286            /**
1287             * Sets the roles associated with the user, replacing the user's existing
1288             * roles. The user is reindexed after the roles are set.
1289             *
1290             * @param  userId the primary key of the user
1291             * @param  roleIds the primary keys of the roles
1292             * @throws PortalException if a user with the primary could not be found or
1293             *         if any one of the roles with the primary keys could not be found
1294             * @throws SystemException if a system exception occurred
1295             */
1296            @Override
1297            public void setUserRoles(long userId, long[] roleIds)
1298                    throws PortalException, SystemException {
1299    
1300                    roleIds = UsersAdminUtil.addRequiredRoles(userId, roleIds);
1301    
1302                    userPersistence.setRoles(userId, roleIds);
1303    
1304                    Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
1305    
1306                    indexer.reindex(userId);
1307    
1308                    PermissionCacheUtil.clearCache();
1309            }
1310    
1311            /**
1312             * Removes the matching roles associated with the user. The user is
1313             * reindexed after the roles are removed.
1314             *
1315             * @param  userId the primary key of the user
1316             * @param  roleIds the primary keys of the roles
1317             * @throws PortalException if a user with the primary key could not be found
1318             *         or if a role with any one of the primary keys could not be found
1319             * @throws SystemException if a system exception occurred
1320             */
1321            @Override
1322            public void unsetUserRoles(long userId, long[] roleIds)
1323                    throws PortalException, SystemException {
1324    
1325                    roleIds = UsersAdminUtil.removeRequiredRoles(userId, roleIds);
1326    
1327                    userPersistence.removeRoles(userId, roleIds);
1328    
1329                    Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
1330    
1331                    indexer.reindex(userId);
1332    
1333                    PermissionCacheUtil.clearCache();
1334            }
1335    
1336            /**
1337             * Updates the role with the primary key.
1338             *
1339             * @param  roleId the primary key of the role
1340             * @param  name the role's new name
1341             * @param  titleMap the new localized titles (optionally <code>null</code>)
1342             *         to replace those existing for the role
1343             * @param  descriptionMap the new localized descriptions (optionally
1344             *         <code>null</code>) to replace those existing for the role
1345             * @param  subtype the role's new subtype (optionally <code>null</code>)
1346             * @param  serviceContext the service context to be applied (optionally
1347             *         <code>null</code>). Can set expando bridge attributes for the
1348             *         role.
1349             * @return the role with the primary key
1350             * @throws PortalException if a role with the primary could not be found or
1351             *         if the role's name was invalid
1352             * @throws SystemException if a system exception occurred
1353             */
1354            @Override
1355            public Role updateRole(
1356                            long roleId, String name, Map<Locale, String> titleMap,
1357                            Map<Locale, String> descriptionMap, String subtype,
1358                            ServiceContext serviceContext)
1359                    throws PortalException, SystemException {
1360    
1361                    Role role = rolePersistence.findByPrimaryKey(roleId);
1362    
1363                    validate(roleId, role.getCompanyId(), role.getClassNameId(), name);
1364    
1365                    if (PortalUtil.isSystemRole(role.getName())) {
1366                            name = role.getName();
1367                            subtype = null;
1368                    }
1369    
1370                    role.setModifiedDate(new Date());
1371                    role.setName(name);
1372                    role.setTitleMap(titleMap);
1373                    role.setDescriptionMap(descriptionMap);
1374                    role.setSubtype(subtype);
1375                    role.setExpandoBridgeAttributes(serviceContext);
1376    
1377                    rolePersistence.update(role);
1378    
1379                    return role;
1380            }
1381    
1382            protected void checkSystemRole(
1383                            long companyId, String name, Map<Locale, String> descriptionMap,
1384                            int type)
1385                    throws PortalException, SystemException {
1386    
1387                    String companyIdHexString = StringUtil.toHexString(companyId);
1388    
1389                    String key = companyIdHexString.concat(name);
1390    
1391                    Role role = _systemRolesMap.get(key);
1392    
1393                    try {
1394                            if (role == null) {
1395                                    role = rolePersistence.findByC_N(companyId, name);
1396                            }
1397    
1398                            if (!descriptionMap.equals(role.getDescriptionMap())) {
1399                                    role.setDescriptionMap(descriptionMap);
1400    
1401                                    roleLocalService.updateRole(role);
1402                            }
1403                    }
1404                    catch (NoSuchRoleException nsre) {
1405                            User user = userLocalService.getDefaultUser(companyId);
1406    
1407                            role = roleLocalService.addRole(
1408                                    user.getUserId(), null, 0, name, null, descriptionMap, type,
1409                                    null, null);
1410    
1411                            if (name.equals(RoleConstants.USER)) {
1412                                    initPersonalControlPanelPortletsPermissions(role);
1413                            }
1414                    }
1415    
1416                    _systemRolesMap.put(key, role);
1417            }
1418    
1419            protected String[] getDefaultControlPanelPortlets() {
1420                    return new String[] {
1421                            PortletKeys.MY_ACCOUNT, PortletKeys.MY_PAGES,
1422                            PortletKeys.MY_WORKFLOW_INSTANCES, PortletKeys.MY_WORKFLOW_TASKS
1423                    };
1424            }
1425    
1426            protected void initPersonalControlPanelPortletsPermissions(Role role)
1427                    throws PortalException, SystemException {
1428    
1429                    for (String portletId : getDefaultControlPanelPortlets()) {
1430                            int count = resourcePermissionPersistence.countByC_N_S_P_R(
1431                                    role.getCompanyId(), portletId, ResourceConstants.SCOPE_COMPANY,
1432                                    String.valueOf(role.getCompanyId()), role.getRoleId());
1433    
1434                            if (count > 0) {
1435                                    continue;
1436                            }
1437    
1438                            ResourceAction resourceAction =
1439                                    resourceActionLocalService.fetchResourceAction(
1440                                            portletId, ActionKeys.ACCESS_IN_CONTROL_PANEL);
1441    
1442                            if (resourceAction == null) {
1443                                    continue;
1444                            }
1445    
1446                            setRolePermissions(
1447                                    role, portletId,
1448                                    new String[] {
1449                                            ActionKeys.ACCESS_IN_CONTROL_PANEL
1450                                    });
1451                    }
1452            }
1453    
1454            protected void setRolePermissions(
1455                            Role role, String name, String[] actionIds)
1456                    throws PortalException, SystemException {
1457    
1458                    if (resourceBlockLocalService.isSupported(name)) {
1459                            resourceBlockLocalService.setCompanyScopePermissions(
1460                                    role.getCompanyId(), name, role.getRoleId(),
1461                                    Arrays.asList(actionIds));
1462                    }
1463                    else {
1464                            resourcePermissionLocalService.setResourcePermissions(
1465                                    role.getCompanyId(), name, ResourceConstants.SCOPE_COMPANY,
1466                                    String.valueOf(role.getCompanyId()), role.getRoleId(),
1467                                    actionIds);
1468                    }
1469            }
1470    
1471            protected void validate(
1472                            long roleId, long companyId, long classNameId, String name)
1473                    throws PortalException, SystemException {
1474    
1475                    if (classNameId == PortalUtil.getClassNameId(Role.class)) {
1476                            if (Validator.isNull(name) ||
1477                                    (name.indexOf(CharPool.COMMA) != -1) ||
1478                                    (name.indexOf(CharPool.STAR) != -1)) {
1479    
1480                                    throw new RoleNameException();
1481                            }
1482    
1483                            if (Validator.isNumber(name) &&
1484                                    !PropsValues.ROLES_NAME_ALLOW_NUMERIC) {
1485    
1486                                    throw new RoleNameException();
1487                            }
1488                    }
1489    
1490                    try {
1491                            Role role = roleFinder.findByC_N(companyId, name);
1492    
1493                            if (role.getRoleId() != roleId) {
1494                                    throw new DuplicateRoleException();
1495                            }
1496                    }
1497                    catch (NoSuchRoleException nsre) {
1498                    }
1499            }
1500    
1501            private Map<String, Role> _systemRolesMap = new HashMap<String, Role>();
1502    
1503    }