protected List<Role> getGroupRoles(long groupId, String resourceName) throws PortalException {

    List<Role> roles = groupRolesMap.get(groupId);

    if (roles != null) {
      return roles;
    }

    Group group = GroupLocalServiceUtil.getGroup(groupId);

    roles =
        ListUtil.copy(
            ResourceActionsUtil.getRoles(group.getCompanyId(), group, resourceName, null));

    Map<Team, Role> teamRoleMap = RoleLocalServiceUtil.getTeamRoleMap(groupId);

    for (Map.Entry<Team, Role> entry : teamRoleMap.entrySet()) {
      Team team = entry.getKey();
      Role teamRole = entry.getValue();

      teamRole.setName(PermissionExporter.ROLE_TEAM_PREFIX + team.getName());
      teamRole.setDescription(team.getDescription());

      roles.add(teamRole);
    }

    groupRolesMap.put(groupId, roles);

    return roles;
  }
  protected void checkSystemRole(
      long companyId, String name, Map<Locale, String> descriptionMap, int type)
      throws PortalException, SystemException {

    String companyIdHexString = StringUtil.toHexString(companyId);

    String key = companyIdHexString.concat(name);

    Role role = _systemRolesMap.get(key);

    try {
      if (role == null) {
        role = rolePersistence.findByC_N(companyId, name);
      }

      if (!descriptionMap.equals(role.getDescriptionMap())) {
        role.setDescriptionMap(descriptionMap);

        roleLocalService.updateRole(role, false);
      }
    } catch (NoSuchRoleException nsre) {
      role = roleLocalService.addRole(0, companyId, name, null, descriptionMap, type);

      if (name.equals(RoleConstants.USER)) {
        initPersonalControlPanelPortletsPermissions(role);
      }
    }

    _systemRolesMap.put(key, role);
  }
  static void ensureUserCustomFieldExists(
      com.liferay.portal.model.User liferayUser, PortletRequest request)
      throws PortalException, SystemException {
    ExpandoBridge exp = liferayUser.getExpandoBridge();
    if (!exp.hasAttribute(CUSTOM_FIELD_PROJECT_GROUP_FILTER)) {
      exp.addAttribute(CUSTOM_FIELD_PROJECT_GROUP_FILTER, ExpandoColumnConstants.STRING, false);
      long companyId = liferayUser.getCompanyId();

      ExpandoColumn column =
          ExpandoColumnLocalServiceUtil.getColumn(
              companyId,
              exp.getClassName(),
              ExpandoTableConstants.DEFAULT_TABLE_NAME,
              CUSTOM_FIELD_PROJECT_GROUP_FILTER);

      String[] roleNames = new String[] {RoleConstants.USER, RoleConstants.POWER_USER};
      for (String roleName : roleNames) {
        Role role = RoleLocalServiceUtil.getRole(companyId, roleName);
        if (role != null && column != null) {
          ResourcePermissionLocalServiceUtil.setResourcePermissions(
              companyId,
              ExpandoColumn.class.getName(),
              ResourceConstants.SCOPE_INDIVIDUAL,
              String.valueOf(column.getColumnId()),
              role.getRoleId(),
              new String[] {ActionKeys.VIEW, ActionKeys.UPDATE});
        }
      }
    }
  }
示例#4
0
  public static void updatePermissions(Layout layout, boolean addDefaultActionIds)
      throws Exception {

    long companyId = layout.getCompanyId();

    Role role = RoleLocalServiceUtil.getRole(companyId, RoleConstants.GUEST);

    String[] actionIds = new String[0];

    String name = Layout.class.getName();
    int scope = ResourceConstants.SCOPE_INDIVIDUAL;
    String primKey = String.valueOf(layout.getPrimaryKey());

    ResourcePermissionLocalServiceUtil.setResourcePermissions(
        companyId, name, scope, primKey, role.getRoleId(), actionIds);

    role = RoleLocalServiceUtil.getRole(companyId, RoleConstants.POWER_USER);

    ResourcePermissionLocalServiceUtil.setResourcePermissions(
        companyId, name, scope, primKey, role.getRoleId(), actionIds);

    if (addDefaultActionIds) {
      actionIds = new String[] {ActionKeys.VIEW};
    }

    role = RoleLocalServiceUtil.getRole(companyId, RoleConstants.USER);

    ResourcePermissionLocalServiceUtil.setResourcePermissions(
        companyId, name, scope, primKey, role.getRoleId(), actionIds);
  }
  protected void updateResourcePermissions(
      long companyId,
      long groupId,
      Resource resource,
      String[] groupPermissions,
      String[] guestPermissions)
      throws PortalException, SystemException {

    Role role = roleLocalService.getDefaultGroupRole(groupId);

    resourcePermissionLocalService.setResourcePermissions(
        resource.getCompanyId(),
        resource.getName(),
        resource.getScope(),
        resource.getPrimKey(),
        role.getRoleId(),
        groupPermissions);

    role = roleLocalService.getRole(companyId, RoleConstants.GUEST);

    resourcePermissionLocalService.setResourcePermissions(
        resource.getCompanyId(),
        resource.getName(),
        resource.getScope(),
        resource.getPrimKey(),
        role.getRoleId(),
        guestPermissions);
  }
  public void editRoleAssignments(ActionRequest actionRequest, ActionResponse actionResponse)
      throws Exception {

    long roleId = ParamUtil.getLong(actionRequest, "roleId");
    Role role = RoleLocalServiceUtil.getRole(roleId);

    if (role.getName().equals(RoleConstants.OWNER)) {
      throw new RoleAssignmentException(role.getName());
    }

    long[] addUserIds = StringUtil.split(ParamUtil.getString(actionRequest, "addUserIds"), 0L);
    long[] removeUserIds =
        StringUtil.split(ParamUtil.getString(actionRequest, "removeUserIds"), 0L);

    if (!ArrayUtil.isEmpty(addUserIds) || !ArrayUtil.isEmpty(removeUserIds)) {

      UserServiceUtil.addRoleUsers(roleId, addUserIds);
      UserServiceUtil.unsetRoleUsers(roleId, removeUserIds);
    }

    long[] addGroupIds = StringUtil.split(ParamUtil.getString(actionRequest, "addGroupIds"), 0L);
    long[] removeGroupIds =
        StringUtil.split(ParamUtil.getString(actionRequest, "removeGroupIds"), 0L);

    if (!ArrayUtil.isEmpty(addGroupIds) || !ArrayUtil.isEmpty(removeGroupIds)) {

      GroupServiceUtil.addRoleGroups(roleId, addGroupIds);
      GroupServiceUtil.unsetRoleGroups(roleId, removeGroupIds);
    }
  }
  @Override
  protected void doUpgrade() throws Exception {
    List<User> users = UserLocalServiceUtil.getUsers(QueryUtil.ALL_POS, QueryUtil.ALL_POS);

    for (User user : users) {
      try {
        if (user.isDefaultUser()) {
          continue;
        }

        Group group = user.getGroup();

        LayoutSet layoutSet = LayoutSetLocalServiceUtil.getLayoutSet(group.getGroupId(), false);

        String themeId = layoutSet.getThemeId();

        if (!themeId.equals("so_WAR_sotheme")) {
          return;
        }

        Role role =
            RoleLocalServiceUtil.getRole(user.getCompanyId(), RoleConstants.SOCIAL_OFFICE_USER);

        UserLocalServiceUtil.addRoleUsers(role.getRoleId(), new long[] {user.getUserId()});

        updateUserGroup(group);
        updateSocialRelations(user);
      } catch (Exception e) {
      }
    }
  }
  protected void updateResourceBlocks(
      long companyId,
      long groupId,
      Resource resource,
      String[] groupPermissions,
      String[] guestPermissions,
      PermissionedModel permissionedModel)
      throws PortalException, SystemException {

    if (permissionedModel == null) {
      throw new IllegalArgumentException("Permissioned model is null");
    }

    // Scope is assumed to always be individual

    Role role = roleLocalService.getDefaultGroupRole(groupId);

    resourceBlockLocalService.setIndividualScopePermissions(
        companyId,
        groupId,
        resource.getName(),
        permissionedModel,
        role.getRoleId(),
        Arrays.asList(groupPermissions));

    role = roleLocalService.getRole(companyId, RoleConstants.GUEST);

    resourceBlockLocalService.setIndividualScopePermissions(
        companyId,
        groupId,
        resource.getName(),
        permissionedModel,
        role.getRoleId(),
        Arrays.asList(guestPermissions));
  }
  protected void validate(long roleId, long companyId, long classNameId, String name)
      throws PortalException, SystemException {

    if (classNameId == PortalUtil.getClassNameId(Role.class)) {
      if (Validator.isNull(name)
          || (name.indexOf(CharPool.COMMA) != -1)
          || (name.indexOf(CharPool.STAR) != -1)) {

        throw new RoleNameException();
      }

      if (Validator.isNumber(name) && !PropsValues.ROLES_NAME_ALLOW_NUMERIC) {

        throw new RoleNameException();
      }
    }

    try {
      Role role = roleFinder.findByC_N(companyId, name);

      if (role.getRoleId() != roleId) {
        throw new DuplicateRoleException();
      }
    } catch (NoSuchRoleException nsre) {
    }
  }
  protected void notifyCommunityAdministrators(MembershipRequest membershipRequest)
      throws IOException, PortalException, SystemException {

    List<UserGroupRole> admins = new UniqueList<UserGroupRole>();

    Role communityAdminRole =
        roleLocalService.getRole(
            membershipRequest.getCompanyId(), RoleConstants.COMMUNITY_ADMINISTRATOR);

    List<UserGroupRole> communityAdmins =
        userGroupRoleLocalService.getUserGroupRolesByGroupAndRole(
            membershipRequest.getGroupId(), communityAdminRole.getRoleId());

    admins.addAll(communityAdmins);

    Role communityOwnerRole =
        rolePersistence.findByC_N(membershipRequest.getCompanyId(), RoleConstants.COMMUNITY_OWNER);

    List<UserGroupRole> communityOwners =
        userGroupRoleLocalService.getUserGroupRolesByGroupAndRole(
            membershipRequest.getGroupId(), communityOwnerRole.getRoleId());

    admins.addAll(communityOwners);

    for (UserGroupRole userGroupRole : admins) {
      notify(
          userGroupRole.getUserId(),
          membershipRequest,
          PropsKeys.COMMUNITIES_EMAIL_MEMBERSHIP_REQUEST_SUBJECT,
          PropsKeys.COMMUNITIES_EMAIL_MEMBERSHIP_REQUEST_BODY);
    }
  }
  public void deletePermission(ActionRequest actionRequest, ActionResponse actionResponse)
      throws Exception {

    ThemeDisplay themeDisplay = (ThemeDisplay) actionRequest.getAttribute(WebKeys.THEME_DISPLAY);

    long roleId = ParamUtil.getLong(actionRequest, "roleId");
    String name = ParamUtil.getString(actionRequest, "name");
    int scope = ParamUtil.getInteger(actionRequest, "scope");
    String primKey = ParamUtil.getString(actionRequest, "primKey");
    String actionId = ParamUtil.getString(actionRequest, "actionId");

    Role role = RoleLocalServiceUtil.getRole(roleId);

    String roleName = role.getName();

    if (roleName.equals(RoleConstants.ADMINISTRATOR)
        || roleName.equals(RoleConstants.ORGANIZATION_ADMINISTRATOR)
        || roleName.equals(RoleConstants.ORGANIZATION_OWNER)
        || roleName.equals(RoleConstants.OWNER)
        || roleName.equals(RoleConstants.SITE_ADMINISTRATOR)
        || roleName.equals(RoleConstants.SITE_OWNER)) {

      throw new RolePermissionsException(roleName);
    }

    if (ResourceBlockLocalServiceUtil.isSupported(name)) {
      if (scope == ResourceConstants.SCOPE_GROUP) {
        ResourceBlockServiceUtil.removeGroupScopePermission(
            themeDisplay.getScopeGroupId(),
            themeDisplay.getCompanyId(),
            GetterUtil.getLong(primKey),
            name,
            roleId,
            actionId);
      } else {
        ResourceBlockServiceUtil.removeCompanyScopePermission(
            themeDisplay.getScopeGroupId(), themeDisplay.getCompanyId(), name, roleId, actionId);
      }
    } else {
      ResourcePermissionServiceUtil.removeResourcePermission(
          themeDisplay.getScopeGroupId(),
          themeDisplay.getCompanyId(),
          name,
          scope,
          primKey,
          roleId,
          actionId);
    }

    // Send redirect

    SessionMessages.add(actionRequest, "permissionDeleted");

    String redirect = PortalUtil.escapeRedirect(ParamUtil.getString(actionRequest, "redirect"));

    if (Validator.isNotNull(redirect)) {
      actionResponse.sendRedirect(redirect);
    }
  }
  public void joinOrganization(ActionRequest actionRequest, ActionResponse actionResponse)
      throws Exception {

    ThemeDisplay themeDisplay = (ThemeDisplay) actionRequest.getAttribute(WebKeys.THEME_DISPLAY);

    Group group = _groupLocalService.getGroup(themeDisplay.getScopeGroupId());

    Organization organization = _organizationLocalService.getOrganization(group.getClassPK());

    Role role =
        _roleLocalService.getRole(themeDisplay.getCompanyId(), "Organization Administrator");

    LinkedHashMap<String, Object> userParams = new LinkedHashMap<>();

    userParams.put("userGroupRole", new Long[] {group.getGroupId(), role.getRoleId()});

    List<User> users =
        _userLocalService.search(
            themeDisplay.getCompanyId(),
            null,
            WorkflowConstants.STATUS_APPROVED,
            userParams,
            QueryUtil.ALL_POS,
            QueryUtil.ALL_POS,
            (OrderByComparator<User>) null);

    if (users.isEmpty()) {
      Role adminRole =
          _roleLocalService.getRole(themeDisplay.getCompanyId(), RoleConstants.ADMINISTRATOR);

      userParams.clear();

      userParams.put("usersRoles", adminRole.getRoleId());

      users =
          _userLocalService.search(
              themeDisplay.getCompanyId(),
              null,
              WorkflowConstants.STATUS_APPROVED,
              userParams,
              QueryUtil.ALL_POS,
              QueryUtil.ALL_POS,
              (OrderByComparator<User>) null);
    }

    JSONObject extraDataJSONObject = getExtraDataJSONObject(actionRequest);

    for (User user : users) {
      _socialRequestLocalService.addRequest(
          themeDisplay.getUserId(),
          0,
          Organization.class.getName(),
          organization.getOrganizationId(),
          MembersRequestKeys.ADD_MEMBER,
          extraDataJSONObject.toString(),
          user.getUserId());
    }
  }
  /**
   * Updates the role with the primary key.
   *
   * @param roleId the primary key of the role
   * @param name the role's new name
   * @param titleMap the new localized titles (optionally <code>null</code>) to replace those
   *     existing for the role
   * @param descriptionMap the new localized descriptions (optionally <code>null</code>) to replace
   *     those existing for the role
   * @param subtype the role's new subtype (optionally <code>null</code>)
   * @return the role with the primary key
   * @throws PortalException if a role with the primary could not be found or if the role's name was
   *     invalid
   * @throws SystemException if a system exception occurred
   */
  public Role updateRole(
      long roleId,
      String name,
      Map<Locale, String> titleMap,
      Map<Locale, String> descriptionMap,
      String subtype)
      throws PortalException, SystemException {

    Role role = rolePersistence.findByPrimaryKey(roleId);

    validate(roleId, role.getCompanyId(), role.getClassNameId(), name);

    if (PortalUtil.isSystemRole(role.getName())) {
      name = role.getName();
      subtype = null;
    }

    role.setName(name);
    role.setTitleMap(titleMap);
    role.setDescriptionMap(descriptionMap);
    role.setSubtype(subtype);

    rolePersistence.update(role, false);

    return role;
  }
  public List<String> getActionIds(Role role) {
    List<String> actionIds = _rolesMap.get(role.getName());

    if (actionIds == null) {
      actionIds = new ArrayList<>();

      _rolesMap.put(role.getName(), actionIds);
    }

    return actionIds;
  }
示例#15
0
  public long[] getRoleIds() throws SystemException {
    List<Role> roles = getRoles();

    long[] roleIds = new long[roles.size()];

    for (int i = 0; i < roles.size(); i++) {
      Role role = roles.get(i);

      roleIds[i] = role.getRoleId();
    }

    return roleIds;
  }
  protected void addGuestPermissions(long companyId, Resource resource, String[] actionIds)
      throws PortalException, SystemException {

    Role guestRole = roleLocalService.getRole(companyId, RoleConstants.GUEST);

    resourcePermissionLocalService.setResourcePermissions(
        resource.getCompanyId(),
        resource.getName(),
        resource.getScope(),
        resource.getPrimKey(),
        guestRole.getRoleId(),
        actionIds);
  }
  protected void addGroupPermissions(long groupId, Resource resource, String[] actionIds)
      throws PortalException, SystemException {

    Role role = roleLocalService.getDefaultGroupRole(groupId);

    resourcePermissionLocalService.setResourcePermissions(
        resource.getCompanyId(),
        resource.getName(),
        resource.getScope(),
        resource.getPrimKey(),
        role.getRoleId(),
        actionIds);
  }
  /**
   * Converts the soap model instance into a normal model instance.
   *
   * @param soapModel the soap model instance to convert
   * @return the normal model instance
   */
  public static Role toModel(RoleSoap soapModel) {
    Role model = new RoleImpl();

    model.setRoleId(soapModel.getRoleId());
    model.setCompanyId(soapModel.getCompanyId());
    model.setClassNameId(soapModel.getClassNameId());
    model.setClassPK(soapModel.getClassPK());
    model.setName(soapModel.getName());
    model.setTitle(soapModel.getTitle());
    model.setDescription(soapModel.getDescription());
    model.setType(soapModel.getType());
    model.setSubtype(soapModel.getSubtype());

    return model;
  }
  protected void addResources(
      long companyId,
      long groupId,
      long userId,
      Resource resource,
      boolean portletActions,
      PermissionedModel permissionedModel)
      throws PortalException, SystemException {

    List<String> actionIds = null;

    if (portletActions) {
      actionIds = ResourceActionsUtil.getPortletResourceActions(resource.getName());
    } else {
      actionIds = ResourceActionsUtil.getModelResourceActions(resource.getName());

      actionIds = ListUtil.copy(actionIds);

      filterOwnerActions(resource.getName(), actionIds);
    }

    Role role = roleLocalService.getRole(companyId, RoleConstants.OWNER);

    if (resourceBlockLocalService.isSupported(resource.getName())) {
      if (permissionedModel == null) {
        throw new IllegalArgumentException("Permissioned model is null");
      }

      // Scope is assumed to always be individual

      resourceBlockLocalService.setIndividualScopePermissions(
          resource.getCompanyId(),
          groupId,
          resource.getName(),
          permissionedModel,
          role.getRoleId(),
          actionIds);
    } else {
      resourcePermissionLocalService.setOwnerResourcePermissions(
          resource.getCompanyId(),
          resource.getName(),
          resource.getScope(),
          resource.getPrimKey(),
          role.getRoleId(),
          userId,
          actionIds.toArray(new String[actionIds.size()]));
    }
  }
  protected void importResourcePermissions(
      PortletDataContext portletDataContext, Role importedRole, Permission permission)
      throws PortalException, SystemException {

    int scope = permission.getScope();

    if (scope == ResourceConstants.SCOPE_COMPANY) {
      ResourcePermissionServiceUtil.addResourcePermission(
          portletDataContext.getCompanyGroupId(),
          portletDataContext.getCompanyId(),
          permission.getName(),
          scope,
          String.valueOf(portletDataContext.getCompanyGroupId()),
          importedRole.getRoleId(),
          permission.getActionId());
    } else if (scope == ResourceConstants.SCOPE_GROUP) {
      long groupId = portletDataContext.getCompanyGroupId();

      long sourceGroupId = GetterUtil.getLong(permission.getPrimKey());

      if (sourceGroupId == portletDataContext.getSourceUserPersonalSiteGroupId()) {

        groupId = portletDataContext.getUserPersonalSiteGroupId();
      }

      ResourcePermissionServiceUtil.addResourcePermission(
          groupId,
          portletDataContext.getCompanyId(),
          permission.getName(),
          ResourceConstants.SCOPE_GROUP,
          String.valueOf(groupId),
          importedRole.getRoleId(),
          permission.getActionId());
    } else if (scope == ResourceConstants.SCOPE_GROUP_TEMPLATE) {
      ResourcePermissionServiceUtil.addResourcePermission(
          GroupConstants.DEFAULT_PARENT_GROUP_ID,
          portletDataContext.getCompanyId(),
          permission.getName(),
          ResourceConstants.SCOPE_GROUP_TEMPLATE,
          String.valueOf(GroupConstants.DEFAULT_PARENT_GROUP_ID),
          importedRole.getRoleId(),
          permission.getActionId());
    } else {
      if (_log.isDebugEnabled()) {
        _log.debug("Individually scoped permissions are not imported");
      }
    }
  }
  protected void setRolePermissions(Role role, String name, String[] actionIds)
      throws PortalException, SystemException {

    if (resourceBlockLocalService.isSupported(name)) {
      resourceBlockLocalService.setCompanyScopePermissions(
          role.getCompanyId(), name, role.getRoleId(), Arrays.asList(actionIds));
    } else {
      resourcePermissionLocalService.setResourcePermissions(
          role.getCompanyId(),
          name,
          ResourceConstants.SCOPE_COMPANY,
          String.valueOf(role.getCompanyId()),
          role.getRoleId(),
          actionIds);
    }
  }
  protected void updateViewControlPanelPermission(
      Role role, long scopeGroupId, String portletId, int scope, String[] groupIds)
      throws Exception {

    PanelCategoryHelper panelCategoryHelper =
        new PanelCategoryHelper(_panelAppRegistry, _panelCategoryRegistry);

    String selResource = null;
    String actionId = null;

    if (panelCategoryHelper.containsPortlet(portletId, PanelCategoryKeys.CONTROL_PANEL)
        && (role.getType() == RoleConstants.TYPE_REGULAR)) {

      selResource = PortletKeys.PORTAL;
      actionId = ActionKeys.VIEW_CONTROL_PANEL;
    } else if (panelCategoryHelper.containsPortlet(
        portletId, PanelCategoryKeys.SITE_ADMINISTRATION)) {

      selResource = Group.class.getName();
      actionId = ActionKeys.VIEW_SITE_ADMINISTRATION;
    }

    if (selResource != null) {
      updateAction(role, scopeGroupId, selResource, actionId, true, scope, groupIds);
    }
  }
  protected List<ResourceTypePermission> getResourceTypePermissions(
      PortletDataContext portletDataContext, Role importedRole) throws SystemException {

    DynamicQuery dynamicQuery = ResourceTypePermissionLocalServiceUtil.dynamicQuery();

    Property companyIdProperty = PropertyFactoryUtil.forName("companyId");

    dynamicQuery.add(companyIdProperty.eq(portletDataContext.getCompanyId()));

    Junction junction = RestrictionsFactoryUtil.disjunction();

    long[] permissibleGroupIds = {
      GroupConstants.DEFAULT_PARENT_GROUP_ID,
      portletDataContext.getCompanyId(),
      portletDataContext.getCompanyGroupId(),
      portletDataContext.getUserPersonalSiteGroupId()
    };

    for (long permissibleGroupId : permissibleGroupIds) {
      Property property = PropertyFactoryUtil.forName("groupId");

      junction.add(property.eq(permissibleGroupId));
    }

    dynamicQuery.add(junction);

    Property roleIdProperty = PropertyFactoryUtil.forName("roleId");

    dynamicQuery.add(roleIdProperty.eq(importedRole.getRoleId()));

    return ResourceTypePermissionLocalServiceUtil.dynamicQuery(dynamicQuery);
  }
  /**
   * Adds a role with additional parameters. The user is reindexed after role is added.
   *
   * @param userId the primary key of the user
   * @param companyId the primary key of the company
   * @param name the role's name
   * @param titleMap the role's localized titles (optionally <code>null</code>)
   * @param descriptionMap the role's localized descriptions (optionally <code>null</code>)
   * @param type the role's type (optionally <code>0</code>)
   * @param className the name of the class for which the role is created (optionally <code>null
   *     </code>)
   * @param classPK the primary key of the class for which the role is created (optionally <code>0
   *     </code>)
   * @return the role
   * @throws PortalException if the class name or the role name were invalid, if the role is a
   *     duplicate, or if a user with the primary key could not be found
   * @throws SystemException if a system exception occurred
   */
  public Role addRole(
      long userId,
      long companyId,
      String name,
      Map<Locale, String> titleMap,
      Map<Locale, String> descriptionMap,
      int type,
      String className,
      long classPK)
      throws PortalException, SystemException {

    // Role

    className = GetterUtil.getString(className);
    long classNameId = PortalUtil.getClassNameId(className);

    long roleId = counterLocalService.increment();

    if ((classNameId <= 0) || className.equals(Role.class.getName())) {
      classNameId = PortalUtil.getClassNameId(Role.class);
      classPK = roleId;
    }

    validate(0, companyId, classNameId, name);

    Role role = rolePersistence.create(roleId);

    role.setCompanyId(companyId);
    role.setClassNameId(classNameId);
    role.setClassPK(classPK);
    role.setName(name);
    role.setTitleMap(titleMap);
    role.setDescriptionMap(descriptionMap);
    role.setType(type);

    rolePersistence.update(role, false);

    // Resources

    if (userId > 0) {
      resourceLocalService.addResources(
          companyId, 0, userId, Role.class.getName(), role.getRoleId(), false, false, false);

      if (!ImportExportThreadLocal.isImportInProcess()) {
        Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);

        indexer.reindex(userId);
      }
    }

    return role;
  }
  protected void updateAction_1to5(
      Role role,
      long groupId,
      String selResource,
      String actionId,
      boolean selected,
      int scope,
      String[] groupIds)
      throws Exception {

    long roleId = role.getRoleId();

    if (selected) {
      if (scope == ResourceConstants.SCOPE_COMPANY) {
        PermissionServiceUtil.setRolePermission(
            roleId, groupId, selResource, scope, String.valueOf(role.getCompanyId()), actionId);
      } else if (scope == ResourceConstants.SCOPE_GROUP_TEMPLATE) {
        PermissionServiceUtil.setRolePermission(
            roleId,
            groupId,
            selResource,
            ResourceConstants.SCOPE_GROUP_TEMPLATE,
            String.valueOf(GroupConstants.DEFAULT_PARENT_GROUP_ID),
            actionId);
      } else {
        PermissionServiceUtil.unsetRolePermissions(
            roleId, groupId, selResource, ResourceConstants.SCOPE_GROUP, actionId);

        for (String curGroupId : groupIds) {
          PermissionServiceUtil.setRolePermission(
              roleId, groupId, selResource, ResourceConstants.SCOPE_GROUP, curGroupId, actionId);
        }
      }
    } else {

      // Remove company, group template, and group permissions

      PermissionServiceUtil.unsetRolePermissions(
          roleId, groupId, selResource, ResourceConstants.SCOPE_COMPANY, actionId);

      PermissionServiceUtil.unsetRolePermissions(
          roleId, groupId, selResource, ResourceConstants.SCOPE_GROUP_TEMPLATE, actionId);

      PermissionServiceUtil.unsetRolePermissions(
          roleId, groupId, selResource, ResourceConstants.SCOPE_GROUP, actionId);
    }
  }
  @Test
  public void testFindByR_N_A() throws Exception {
    List<Role> roles =
        RoleFinderUtil.findByR_N_A(
            _resourceBlock.getResourceBlockId(),
            _resourceBlock.getName(),
            _bookmarkFolderResourceAction.getActionId());

    for (Role role : roles) {
      if (role.getRoleId() == _arbitraryRole.getRoleId()) {
        return;
      }
    }

    Assert.fail(
        "The method findByR_N_A should have returned the role " + _arbitraryRole.getRoleId());
  }
  @Override
  protected boolean hasPermissionImplicitlyGranted(
      PermissionChecker permissionChecker, Group group, Portlet portlet) throws Exception {

    List<UserGroupRole> userGroupRoles =
        UserGroupRoleLocalServiceUtil.getUserGroupRoles(permissionChecker.getUserId());

    for (UserGroupRole userGroupRole : userGroupRoles) {
      Role role = userGroupRole.getRole();

      String roleName = role.getName();

      if (roleName.equals(RoleConstants.ORGANIZATION_ADMINISTRATOR)
          || roleName.equals(RoleConstants.ORGANIZATION_OWNER)) {

        return true;
      }
    }

    List<Organization> organizations =
        OrganizationLocalServiceUtil.getUserOrganizations(permissionChecker.getUserId());

    for (Organization organization : organizations) {
      if (OrganizationPermissionUtil.contains(
          permissionChecker, organization, ActionKeys.MANAGE_USERS)) {

        return true;
      }

      if (OrganizationPermissionUtil.contains(
          permissionChecker, organization, ActionKeys.MANAGE_SUBORGANIZATIONS)) {

        return true;
      }

      /*if (OrganizationPermissionUtil.contains(
      		permissionChecker, organization.getOrganizationId(),
      		ActionKeys.VIEW)) {

      	return true;
      }*/
    }

    return false;
  }
  protected void addPortletModelViewPermission() throws Exception {
    RoleTestUtil.addResourcePermission(
        getRoleName(),
        getResourceName(),
        ResourceConstants.SCOPE_GROUP,
        getPrimKey(),
        ActionKeys.VIEW);

    Role role = RoleLocalServiceUtil.getRole(TestPropsValues.getCompanyId(), getRoleName());

    ResourcePermissionLocalServiceUtil.setResourcePermissions(
        group.getCompanyId(),
        getResourceName(),
        ResourceConstants.SCOPE_INDIVIDUAL,
        getPrimKey(),
        role.getRoleId(),
        new String[] {ActionKeys.VIEW});
  }
  public static void putUserRole(long userId, Role role, Boolean value) {
    if (value == null) {
      return;
    }

    UserRoleKey userRoleKey = new UserRoleKey(userId, role.getRoleId());

    _userRolePortalCache.put(userRoleKey, value);
  }
  protected void addRequiredMemberRole(Group group, BooleanQuery permissionQuery) throws Exception {

    if (group.isOrganization()) {
      Role organizationUserRole =
          RoleLocalServiceUtil.getRole(group.getCompanyId(), RoleConstants.ORGANIZATION_USER);

      permissionQuery.addTerm(
          Field.GROUP_ROLE_ID,
          group.getGroupId() + StringPool.DASH + organizationUserRole.getRoleId());
    }

    if (group.isSite()) {
      Role siteMemberRole =
          RoleLocalServiceUtil.getRole(group.getCompanyId(), RoleConstants.SITE_MEMBER);

      permissionQuery.addTerm(
          Field.GROUP_ROLE_ID, group.getGroupId() + StringPool.DASH + siteMemberRole.getRoleId());
    }
  }