@Test
  public void testUnassignUserFromRequiredGroups() throws Exception {
    long[] userIds = addUsers();
    long[] standardGroupIds = addStandardGroups();
    long[] requiredGroupIds = addRequiredGroups();

    User user = UserLocalServiceUtil.getUser(userIds[0]);

    List<Group> groups = user.getGroups();

    Assert.assertEquals(1, groups.size());

    long[] userGroupIds =
        ArrayUtil.append(standardGroupIds, requiredGroupIds, new long[] {user.getGroupId()});

    MembershipPolicyTestUtil.updateUser(
        user, null, null, userGroupIds, null, Collections.<UserGroupRole>emptyList());

    groups = user.getGroups();

    Assert.assertEquals(userGroupIds.length, groups.size());

    MembershipPolicyTestUtil.updateUser(
        user, null, null, requiredGroupIds, null, Collections.<UserGroupRole>emptyList());

    groups = user.getGroups();

    Assert.assertEquals(requiredGroupIds.length, groups.size());
  }
  public static long getGroupId(long companyId, String[] pathArray) throws WebDAVException {

    try {
      if (pathArray.length == 0) {
        return 0;
      }

      String name = pathArray[0];

      Group group = GroupLocalServiceUtil.fetchFriendlyURLGroup(companyId, StringPool.SLASH + name);

      if (group != null) {
        return group.getGroupId();
      }

      User user = UserLocalServiceUtil.fetchUserByScreenName(companyId, name);

      if (user != null) {
        group = user.getGroup();

        return group.getGroupId();
      }
    } catch (Exception e) {
      throw new WebDAVException(e);
    }

    return 0;
  }
  @Override
  public String getURLViewInContext(
      LiferayPortletRequest liferayPortletRequest,
      LiferayPortletResponse liferayPortletResponse,
      String noSuchEntryRedirect) {

    try {
      ThemeDisplay themeDisplay =
          (ThemeDisplay) liferayPortletRequest.getAttribute(WebKeys.THEME_DISPLAY);

      User user = themeDisplay.getUser();

      long portletPlid =
          PortalUtil.getPlidFromPortletId(user.getGroupId(), true, PortletKeys.TASKS);

      PortletURL portletURL =
          PortletURLFactoryUtil.create(
              liferayPortletRequest, PortletKeys.TASKS, portletPlid, PortletRequest.RENDER_PHASE);

      portletURL.setParameter("mvcPath", "/tasks/view.jsp");

      return portletURL.toString();
    } catch (Exception e) {
    }

    return null;
  }
  protected List<User> parseRecipients(long userId, String to) throws PortalException {

    User user = UserLocalServiceUtil.getUser(userId);

    String[] recipients = StringUtil.split(to);

    List<User> users = new ArrayList<>();

    for (String recipient : recipients) {
      int x = recipient.indexOf(CharPool.LESS_THAN);
      int y = recipient.indexOf(CharPool.GREATER_THAN);

      try {
        String screenName = recipient;

        if ((x != -1) && (y != -1)) {
          screenName = recipient.substring(x + 1, y);
        }

        User recipientUser =
            UserLocalServiceUtil.getUserByScreenName(user.getCompanyId(), screenName);

        if (!users.contains(recipientUser)) {
          users.add(recipientUser);
        }
      } catch (NoSuchUserException nsue) {
      }
    }

    return users;
  }
  @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) {
      }
    }
  }
  public Website addWebsite(
      long userId, String className, long classPK, String url, int typeId, boolean primary)
      throws PortalException, SystemException {

    User user = userPersistence.findByPrimaryKey(userId);
    long classNameId = PortalUtil.getClassNameId(className);
    Date now = new Date();

    validate(0, user.getCompanyId(), classNameId, classPK, url, typeId, primary);

    long websiteId = counterLocalService.increment();

    Website website = websitePersistence.create(websiteId);

    website.setCompanyId(user.getCompanyId());
    website.setUserId(user.getUserId());
    website.setUserName(user.getFullName());
    website.setCreateDate(now);
    website.setModifiedDate(now);
    website.setClassNameId(classNameId);
    website.setClassPK(classPK);
    website.setUrl(url);
    website.setTypeId(typeId);
    website.setPrimary(primary);

    websitePersistence.update(website);

    return website;
  }
  @Override
  public MBMessage updateDiscussionMessage(
      String className,
      long classPK,
      String permissionClassName,
      long permissionClassPK,
      long permissionOwnerId,
      long messageId,
      String subject,
      String body,
      ServiceContext serviceContext)
      throws PortalException, SystemException {

    User user = getUser();

    MBDiscussionPermission.check(
        getPermissionChecker(),
        user.getCompanyId(),
        serviceContext.getScopeGroupId(),
        permissionClassName,
        permissionClassPK,
        messageId,
        permissionOwnerId,
        ActionKeys.UPDATE_DISCUSSION);

    return mbMessageLocalService.updateDiscussionMessage(
        getUserId(), messageId, className, classPK, subject, body, serviceContext);
  }
  protected long getImageId(HttpServletRequest request) {

    // The image id may be passed in as image_id, img_id, or i_id

    long imageId = ParamUtil.getLong(request, "image_id");

    if (imageId <= 0) {
      imageId = ParamUtil.getLong(request, "img_id");
    }

    if (imageId <= 0) {
      imageId = ParamUtil.getLong(request, "i_id");
    }

    if (imageId <= 0) {
      long companyId = ParamUtil.getLong(request, "companyId");
      String screenName = ParamUtil.getString(request, "screenName");

      try {
        if ((companyId > 0) && Validator.isNotNull(screenName)) {
          User user = UserLocalServiceUtil.getUserByScreenName(companyId, screenName);

          imageId = user.getPortraitId();
        }
      } catch (Exception e) {
      }
    }

    return imageId;
  }
  protected Map<String, String> getPortletPreferencesMap() throws PortalException {

    Map<String, String> portletPreferencesMap = new HashMap<>();

    User user = getUser();

    int maxConnections =
        PrefsPropsUtil.getInteger(
            user.getCompanyId(),
            PortletPropsKeys.SYNC_CLIENT_MAX_CONNECTIONS,
            PortletPropsValues.SYNC_CLIENT_MAX_CONNECTIONS);

    portletPreferencesMap.put(
        PortletPropsKeys.SYNC_CLIENT_MAX_CONNECTIONS, String.valueOf(maxConnections));

    int pollInterval =
        PrefsPropsUtil.getInteger(
            user.getCompanyId(),
            PortletPropsKeys.SYNC_CLIENT_POLL_INTERVAL,
            PortletPropsValues.SYNC_CLIENT_POLL_INTERVAL);

    portletPreferencesMap.put(
        PortletPropsKeys.SYNC_CLIENT_POLL_INTERVAL, String.valueOf(pollInterval));

    return portletPreferencesMap;
  }
  public MembershipRequest addMembershipRequest(long userId, long groupId, String comments)
      throws PortalException, SystemException {

    User user = userPersistence.findByPrimaryKey(userId);
    Date now = new Date();

    validate(comments);

    long membershipRequestId = counterLocalService.increment();

    MembershipRequest membershipRequest = membershipRequestPersistence.create(membershipRequestId);

    membershipRequest.setCompanyId(user.getCompanyId());
    membershipRequest.setUserId(userId);
    membershipRequest.setCreateDate(now);
    membershipRequest.setGroupId(groupId);
    membershipRequest.setComments(comments);
    membershipRequest.setStatusId(MembershipRequestConstants.STATUS_PENDING);

    membershipRequestPersistence.update(membershipRequest, false);

    try {
      notifyCommunityAdministrators(membershipRequest);
    } catch (IOException ioe) {
      throw new SystemException(ioe);
    }

    return membershipRequest;
  }
  public KaleoTaskAssignment addKaleoTaskAssignment(
      String kaleoClassName,
      long kaleoClassPK,
      long kaleoDefinitionId,
      Assignment assignment,
      ServiceContext serviceContext)
      throws PortalException, SystemException {

    User user = userPersistence.findByPrimaryKey(serviceContext.getGuestOrUserId());
    Date now = new Date();

    long kaleoTaskAssignmentId = counterLocalService.increment();

    KaleoTaskAssignment kaleoTaskAssignment =
        kaleoTaskAssignmentPersistence.create(kaleoTaskAssignmentId);

    kaleoTaskAssignment.setCompanyId(user.getCompanyId());
    kaleoTaskAssignment.setUserId(user.getUserId());
    kaleoTaskAssignment.setUserName(user.getFullName());
    kaleoTaskAssignment.setCreateDate(now);
    kaleoTaskAssignment.setModifiedDate(now);
    kaleoTaskAssignment.setKaleoClassName(kaleoClassName);
    kaleoTaskAssignment.setKaleoClassPK(kaleoClassPK);
    kaleoTaskAssignment.setKaleoDefinitionId(kaleoDefinitionId);
    setAssignee(kaleoTaskAssignment, assignment, serviceContext);

    kaleoTaskAssignmentPersistence.update(kaleoTaskAssignment);

    return kaleoTaskAssignment;
  }
  @Override
  public MDRRuleGroup addRuleGroup(
      long groupId,
      Map<Locale, String> nameMap,
      Map<Locale, String> descriptionMap,
      ServiceContext serviceContext)
      throws PortalException, SystemException {

    User user = userPersistence.findByPrimaryKey(serviceContext.getUserId());
    Date now = new Date();

    long ruleGroupId = counterLocalService.increment();

    MDRRuleGroup ruleGroup = createMDRRuleGroup(ruleGroupId);

    ruleGroup.setUuid(serviceContext.getUuid());
    ruleGroup.setGroupId(groupId);
    ruleGroup.setCompanyId(serviceContext.getCompanyId());
    ruleGroup.setCreateDate(serviceContext.getCreateDate(now));
    ruleGroup.setModifiedDate(serviceContext.getModifiedDate(now));
    ruleGroup.setUserId(user.getUserId());
    ruleGroup.setUserName(user.getFullName());
    ruleGroup.setNameMap(nameMap);
    ruleGroup.setDescriptionMap(descriptionMap);

    return updateMDRRuleGroup(ruleGroup);
  }
  // TODO: allow for dynamic user url building classes to be injected
  private void addUsers(Element element, Group suppliedGroup, ThemeDisplay themeDisplay)
      throws PortalException, SystemException {

    // get all users
    List<User> users = UserLocalServiceUtil.getGroupUsers(suppliedGroup.getGroupId());

    // we're only displaying users with blogs for now
    for (User u : users) {
      Group usersOwnGroup =
          GroupLocalServiceUtil.getUserGroup(suppliedGroup.getCompanyId(), u.getUserId());

      int count = BlogsEntryLocalServiceUtil.getGroupEntriesCount(usersOwnGroup.getGroupId());
      List<BlogsEntry> entries =
          BlogsEntryLocalServiceUtil.getGroupEntries(usersOwnGroup.getGroupId(), 0, count);

      // only add if the user has blogs
      if (entries != null && entries.size() > 0) {

        // index the user, as well
        StringBuffer baseUrl = new StringBuffer(themeDisplay.getPortalURL());

        // TODO figure out where web comes from
        baseUrl.append("/web");
        baseUrl.append(usersOwnGroup.getFriendlyURL());

        Element userUrlElement = element.addElement("url");

        userUrlElement.addElement("loc").addText(encodeXML(baseUrl.toString()));
        userUrlElement.addElement("changefreq").addText("daily");
      }
    }
  }
  public Entry addEntry(long userId, String fullName, String emailAddress, String comments)
      throws PortalException {

    User user = userPersistence.findByPrimaryKey(userId);
    Date now = new Date();

    validate(0, userId, fullName, emailAddress);

    long contactId = counterLocalService.increment();

    Entry entry = entryPersistence.create(contactId);

    entry.setCompanyId(user.getCompanyId());
    entry.setUserId(user.getUserId());
    entry.setUserName(user.getFullName());
    entry.setCreateDate(now);
    entry.setModifiedDate(now);
    entry.setFullName(fullName);
    entry.setEmailAddress(emailAddress);
    entry.setComments(comments);

    entryPersistence.update(entry);

    return entry;
  }
  private static void _updateCompany(HttpServletRequest request) throws Exception {

    Company company = CompanyLocalServiceUtil.getCompanyById(PortalInstances.getDefaultCompanyId());

    Account account = company.getAccount();

    String currentName = account.getName();

    String newName = ParamUtil.getString(request, "companyName", PropsValues.COMPANY_DEFAULT_NAME);

    if (!currentName.equals(newName)) {
      account.setName(newName);

      AccountLocalServiceUtil.updateAccount(account);
    }

    String languageId =
        ParamUtil.getString(request, "companyLocale", PropsValues.COMPANY_DEFAULT_LOCALE);

    User defaultUser = company.getDefaultUser();

    defaultUser.setLanguageId(languageId);

    UserLocalServiceUtil.updateUser(defaultUser);

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

    themeDisplay.setCompany(company);
  }
  protected int authenticateOmniadmin(
      long companyId, String emailAddress, String screenName, long userId) throws Exception {

    // Only allow omniadmin if Liferay password checking is enabled

    if (PropsValues.AUTH_PIPELINE_ENABLE_LIFERAY_CHECK) {
      if (userId > 0) {
        if (OmniadminUtil.isOmniadmin(userId)) {
          return SUCCESS;
        }
      } else if (Validator.isNotNull(emailAddress)) {
        try {
          User user = UserLocalServiceUtil.getUserByEmailAddress(companyId, emailAddress);

          if (OmniadminUtil.isOmniadmin(user.getUserId())) {
            return SUCCESS;
          }
        } catch (NoSuchUserException nsue) {
        }
      } else if (Validator.isNotNull(screenName)) {
        try {
          User user = UserLocalServiceUtil.getUserByScreenName(companyId, screenName);

          if (OmniadminUtil.isOmniadmin(user.getUserId())) {
            return SUCCESS;
          }
        } catch (NoSuchUserException nsue) {
        }
      }
    }

    return FAILURE;
  }
  public void addActivityAchievement(long userId, long groupId, SocialAchievement achievement)
      throws PortalException, SystemException {

    SocialActivityAchievement activityAchievement =
        socialActivityAchievementPersistence.fetchByG_U_N(groupId, userId, achievement.getName());

    if (activityAchievement != null) {
      return;
    }

    User user = userPersistence.findByPrimaryKey(userId);

    long activityAchievementId = counterLocalService.increment();

    activityAchievement = socialActivityAchievementPersistence.create(activityAchievementId);

    activityAchievement.setGroupId(groupId);
    activityAchievement.setCompanyId(user.getCompanyId());
    activityAchievement.setUserId(userId);
    activityAchievement.setCreateDate(System.currentTimeMillis());

    int count = socialActivityAchievementPersistence.countByG_N(groupId, achievement.getName());

    if (count == 0) {
      activityAchievement.setFirstInGroup(true);
    }

    activityAchievement.setName(achievement.getName());

    socialActivityAchievementPersistence.update(activityAchievement, false);

    socialActivityCounterLocalService.incrementUserAchievementCounter(userId, groupId);
  }
  @Override
  public boolean isDisabled(Object obj) {
    User user = (User) obj;

    try {
      PermissionChecker permissionChecker = PermissionThreadLocal.getPermissionChecker();

      if (isChecked(user)) {
        if (OrganizationMembershipPolicyUtil.isRoleProtected(
                permissionChecker,
                user.getUserId(),
                _organization.getOrganizationId(),
                _role.getRoleId())
            || OrganizationMembershipPolicyUtil.isRoleRequired(
                user.getUserId(), _organization.getOrganizationId(), _role.getRoleId())) {

          return true;
        }
      } else {
        if (!OrganizationMembershipPolicyUtil.isRoleAllowed(
            user.getUserId(), _organization.getOrganizationId(), _role.getRoleId())) {

          return true;
        }
      }
    } catch (Exception e) {
      _log.error(e, e);
    }

    return super.isDisabled(obj);
  }
  @Override
  public void deleteDiscussionMessage(
      long groupId,
      String className,
      long classPK,
      String permissionClassName,
      long permissionClassPK,
      long permissionOwnerId,
      long messageId)
      throws PortalException, SystemException {

    User user = getUser();

    MBDiscussionPermission.check(
        getPermissionChecker(),
        user.getCompanyId(),
        groupId,
        permissionClassName,
        permissionClassPK,
        messageId,
        permissionOwnerId,
        ActionKeys.DELETE_DISCUSSION);

    mbMessageLocalService.deleteDiscussionMessage(messageId);
  }
 public NotificationRecipient(User user) {
   _companyId = user.getCompanyId();
   _emailAddress = user.getEmailAddress();
   _fullName = user.getFullName();
   _screenName = user.getScreenName();
   _userId = user.getUserId();
 }
  @Test
  public void testFailedPortletLocalPublishing() throws Exception {
    User user = TestPropsValues.getUser();

    try (CaptureAppender captureAppender =
        Log4JLoggerTestUtil.configureLog4JLogger(
            BackgroundTaskMessageListener.class.getName(), Level.ERROR)) {

      StagingUtil.publishPortlet(
          user.getUserId(),
          _group.getGroupId(),
          _liveGroup.getGroupId(),
          0,
          0,
          StringPool.BLANK,
          _parameterMap);

      List<LoggingEvent> loggingEvents = captureAppender.getLoggingEvents();

      LoggingEvent loggingEvent = loggingEvents.get(0);

      Assert.assertEquals("Unable to execute background task", loggingEvent.getMessage());

      ThrowableInformation throwableInformation = loggingEvent.getThrowableInformation();

      Throwable throwable = throwableInformation.getThrowable();

      Assert.assertSame(NoSuchLayoutException.class, throwable.getClass());
    }

    Assert.assertTrue(
        _firedExportImportLifecycleEventsMap.containsKey(
            ExportImportLifecycleConstants.EVENT_PUBLICATION_PORTLET_LOCAL_FAILED));
  }
  private void update() {

    if (!IConstants.CFG_NOTIFY_OLD_USERS) return;

    DynamicQuery dynamicQuery =
        DynamicQueryFactoryUtil.forClass(User.class, PortalClassLoaderUtil.getClassLoader());
    dynamicQuery.add(RestrictionsFactoryUtil.eq("jobTitle", "mail-not-sent"));

    try {
      @SuppressWarnings("unchecked")
      List<User> users = UserLocalServiceUtil.dynamicQuery(dynamicQuery);

      int cnt = 0;

      for (User user : users) {
        // notifyUser thru email and SMS

        user.setJobTitle(StringPool.BLANK);
        user.setLastName(StringPool.BLANK);
        user = UserLocalServiceUtil.updateUser(user);
        cnt++;

        if (cnt == 200) break;
      }
    } catch (SystemException e) {
      e.printStackTrace();
    }
  }
  private String _getLogin() {
    String login = PrincipalThreadLocal.getName();

    if (Validator.isNull(login) || _isDefaultUser(login)) {
      return PropsUtil.get(PropsKeys.DL_REPOSITORY_GUEST_USERNAME);
    }

    try {
      String authType = getAuthType();

      if (!authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
        User user = userLocalService.getUser(GetterUtil.getLong(login));

        if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
          login = user.getEmailAddress();
        } else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
          login = user.getScreenName();
        }
      }
    } catch (PortalException | SystemException e) {
      if (_log.isWarnEnabled()) {
        _log.warn("Unable to get login to connect to external repository " + _extRepository, e);
      }

      login = null;
    }

    return login;
  }
  @Override
  public AnonymousUser updateAnonymousUser(
      long anonymousUserId,
      long userId,
      String lastIp,
      String typeSettings,
      ServiceContext serviceContext)
      throws PortalException, SystemException {

    Date now = new Date();

    AnonymousUser anonymousUser = anonymousUserPersistence.findByPrimaryKey(anonymousUserId);

    User user = UserLocalServiceUtil.fetchUser(userId);

    if (user != null) {
      anonymousUser.setUserId(user.getUserId());
      anonymousUser.setUserName(user.getFullName());
    }

    anonymousUser.setModifiedDate(serviceContext.getModifiedDate(now));
    anonymousUser.setLastIp(lastIp);
    anonymousUser.setTypeSettings(typeSettings);

    anonymousUserPersistence.update(anonymousUser);

    return anonymousUser;
  }
  protected void addComment(ClassedModel classedModel, String body, ServiceContext serviceContext)
      throws Exception {

    User user = TestPropsValues.getUser();

    List<MBMessage> messages =
        MBMessageLocalServiceUtil.getMessages(
            getBaseModelClassName(),
            getBaseModelClassPK(classedModel),
            WorkflowConstants.STATUS_ANY);

    MBMessage message = messages.get(0);

    MBMessageLocalServiceUtil.addDiscussionMessage(
        user.getUserId(),
        user.getFullName(),
        serviceContext.getScopeGroupId(),
        getBaseModelClassName(),
        getBaseModelClassPK(classedModel),
        message.getThreadId(),
        message.getMessageId(),
        message.getSubject(),
        body,
        serviceContext);
  }
  @Override
  public AnonymousUser addAnonymousUser(
      long userId, String lastIp, String typeSettings, ServiceContext serviceContext)
      throws PortalException, SystemException {

    User user = UserLocalServiceUtil.fetchUser(userId);

    Date now = new Date();

    long anonymousUserId = CounterLocalServiceUtil.increment();

    AnonymousUser anonymousUser = anonymousUserPersistence.create(anonymousUserId);

    anonymousUser.setCompanyId(serviceContext.getCompanyId());

    if (user != null) {
      anonymousUser.setUserId(user.getUserId());
      anonymousUser.setUserName(user.getFullName());
    }

    anonymousUser.setCreateDate(serviceContext.getCreateDate(now));
    anonymousUser.setModifiedDate(serviceContext.getModifiedDate(now));
    anonymousUser.setLastIp(lastIp);
    anonymousUser.setTypeSettings(typeSettings);

    anonymousUserPersistence.update(anonymousUser);

    return anonymousUser;
  }
  public void testFetchByPrimaryKeyExisting() throws Exception {
    User newUser = addUser();

    User existingUser = _persistence.fetchByPrimaryKey(newUser.getPrimaryKey());

    assertEquals(existingUser, newUser);
  }
  @Override
  public PollsChoice addChoice(
      long userId, long questionId, String name, String description, ServiceContext serviceContext)
      throws PortalException {

    validate(name, description);

    User user = userPersistence.findByPrimaryKey(userId);
    Date now = new Date();

    long choiceId = counterLocalService.increment();

    PollsChoice choice = pollsChoicePersistence.create(choiceId);

    choice.setUuid(serviceContext.getUuid());
    choice.setGroupId(serviceContext.getScopeGroupId());
    choice.setCompanyId(user.getCompanyId());
    choice.setUserId(user.getUserId());
    choice.setUserName(user.getFullName());
    choice.setCreateDate(serviceContext.getCreateDate(now));
    choice.setModifiedDate(serviceContext.getModifiedDate(now));
    choice.setQuestionId(questionId);
    choice.setName(name);
    choice.setDescription(description);

    pollsChoicePersistence.update(choice);

    return choice;
  }
  public void addMemberRequests(
      long userId,
      long groupId,
      long[] receiverUserIds,
      long invitedRoleId,
      long invitedTeamId,
      ThemeDisplay themeDisplay)
      throws PortalException, SystemException {

    for (long receiverUserId : receiverUserIds) {
      if (hasPendingMemberRequest(groupId, receiverUserId)) {
        continue;
      }

      User user = userLocalService.getUser(receiverUserId);

      String emailAddress = user.getEmailAddress();

      addMemberRequest(
          userId,
          groupId,
          receiverUserId,
          emailAddress,
          invitedRoleId,
          invitedTeamId,
          themeDisplay);
    }
  }
  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});
        }
      }
    }
  }