@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 boolean isDisabled(Object obj) {
    if (!PropsValues.ORGANIZATIONS_ASSIGNMENT_STRICT) {
      return false;
    }

    User user = (User) obj;

    try {
      PermissionChecker permissionChecker = PermissionThreadLocal.getPermissionChecker();

      if (isChecked(user)) {
        if (OrganizationMembershipPolicyUtil.isMembershipProtected(
                permissionChecker, user.getUserId(), _organization.getOrganizationId())
            || OrganizationMembershipPolicyUtil.isMembershipRequired(
                user.getUserId(), _organization.getOrganizationId())) {

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

          return true;
        }
      }

      return !UserPermissionUtil.contains(permissionChecker, user.getUserId(), ActionKeys.UPDATE);
    } catch (Exception e) {
      _log.error(e, e);
    }

    return super.isDisabled(obj);
  }
  protected void updateCustomFields(
      User user, Userinfo userinfo, String accessToken, String refreshToken)
      throws PortalException, SystemException {

    ExpandoValueLocalServiceUtil.addValue(
        user.getCompanyId(),
        User.class.getName(),
        ExpandoTableConstants.DEFAULT_TABLE_NAME,
        GOOGLE_ACCESS_TOKEN,
        user.getUserId(),
        accessToken);

    ExpandoValueLocalServiceUtil.addValue(
        user.getCompanyId(),
        User.class.getName(),
        ExpandoTableConstants.DEFAULT_TABLE_NAME,
        GOOGLE_REFRESH_TOKEN,
        user.getUserId(),
        refreshToken);

    ExpandoValueLocalServiceUtil.addValue(
        user.getCompanyId(),
        User.class.getName(),
        ExpandoTableConstants.DEFAULT_TABLE_NAME,
        GOOGLE_USER_ID,
        user.getUserId(),
        userinfo.getId());
  }
  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;
  }
  /**
   * Create a work flow task for the new content created and send a email to the corresponding role
   * moderator users
   *
   * @param contentlet The content
   * @param user The user that add the content
   * @param moderatorRole The role to assign the work flow
   * @throws DotDataException
   * @throws DotDataException
   */
  public static void createWorkFlowTask(Contentlet contentlet, String userId, String moderatorRole)
      throws DotDataException {

    User user = getUserFromId(userId);
    StringBuffer changeHist = new StringBuffer("Task Added<br>");
    WorkflowTask task = new WorkflowTask();

    changeHist.append("Title: " + UtilHTML.escapeHTMLSpecialChars(contentlet.getTitle()) + "<br>");
    task.setTitle(
        "A new content titled: "
            + UtilHTML.escapeHTMLSpecialChars(contentlet.getTitle())
            + " has been posted.");
    task.setDescription(
        "A new content titled \""
            + UtilHTML.escapeHTMLSpecialChars(contentlet.getTitle().trim())
            + "\" has been posted by "
            + UtilHTML.escapeHTMLSpecialChars(user.getFullName())
            + " ("
            + user.getEmailAddress()
            + ")");
    changeHist.append(
        "Description: " + UtilHTML.escapeHTMLSpecialChars(task.getDescription()) + "<br>");

    Role role = roleAPI.loadRoleByKey(moderatorRole);
    task.setBelongsTo(role.getId());
    task.setAssignedTo("Nobody");
    task.setModDate(new Date());
    task.setCreationDate(new Date());
    task.setCreatedBy(user.getUserId());

    task.setStatus(WorkflowStatuses.OPEN.toString());
    changeHist.append("Due Date: " + UtilMethods.dateToHTMLDate(task.getDueDate()) + " -> <br>");
    task.setDueDate(null);
    task.setWebasset(contentlet.getInode());

    // HibernateUtil.saveOrUpdate(task);

    // Save the work flow comment
    WorkflowComment taskComment = new WorkflowComment();
    taskComment.setComment(task.getDescription());
    taskComment.setCreationDate(new Date());
    taskComment.setPostedBy(user.getUserId());
    HibernateUtil.saveOrUpdate(taskComment);
    relAPI.addRelationship(task.getInode(), taskComment.getInode(), "child");

    // Save the work flow history
    WorkflowHistory hist = new WorkflowHistory();
    hist.setChangeDescription("Task Creation");
    hist.setCreationDate(new Date());
    hist.setMadeBy(user.getUserId());
    HibernateUtil.saveOrUpdate(hist);
    relAPI.addRelationship(task.getInode(), hist.getInode(), "child");

    // WorkflowEmailUtil.sendWorkflowChangeEmails (task, "New user content has been submitted", "New
    // Task", null);

  }
  public static List<Group> getGroups(User user) throws Exception {

    // Guest

    if (user.isDefaultUser()) {
      List<Group> groups = new ArrayList<>();

      Group group = GroupLocalServiceUtil.getGroup(user.getCompanyId(), GroupConstants.GUEST);

      groups.add(group);

      return groups;
    }

    // Communities

    Set<Group> groups = new HashSet<>();

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

    params.put("usersGroups", user.getUserId());

    OrderByComparator<Group> orderByComparator = new GroupFriendlyURLComparator(true);

    groups.addAll(
        GroupLocalServiceUtil.search(
            user.getCompanyId(),
            null,
            null,
            params,
            QueryUtil.ALL_POS,
            QueryUtil.ALL_POS,
            orderByComparator));

    // Organizations

    groups.addAll(
        GroupLocalServiceUtil.getUserOrganizationsGroups(
            user.getUserId(), QueryUtil.ALL_POS, QueryUtil.ALL_POS));

    // User

    if (!user.isDefaultUser()) {
      groups.add(user.getGroup());
    }

    List<Group> groupsList = new ArrayList<>(groups);

    Collections.sort(groupsList, orderByComparator);

    return groupsList;
  }
  protected void searchRecentEntries() throws Exception {
    long initialSearchGroupEntriesCount = searchGroupEntriesCount(group.getGroupId(), 0);

    ServiceContext serviceContext = ServiceContextTestUtil.getServiceContext(group.getGroupId());

    BaseModel<?> parentBaseModel1 = getParentBaseModel(group, serviceContext);
    BaseModel<?> parentBaseModel2 = getParentBaseModel(group, serviceContext);

    String name = PrincipalThreadLocal.getName();

    try {
      User user1 = UserTestUtil.addUser(null, 0);

      PrincipalThreadLocal.setName(user1.getUserId());

      baseModel =
          addBaseModel(parentBaseModel1, true, RandomTestUtil.randomString(), serviceContext);
      baseModel =
          addBaseModel(parentBaseModel1, true, RandomTestUtil.randomString(), serviceContext);
      baseModel =
          addBaseModel(parentBaseModel2, true, RandomTestUtil.randomString(), serviceContext);

      User user2 = UserTestUtil.addUser(null, 0);

      PrincipalThreadLocal.setName(user2.getUserId());

      baseModel =
          addBaseModel(parentBaseModel1, true, RandomTestUtil.randomString(), serviceContext);
      baseModel =
          addBaseModel(parentBaseModel2, true, RandomTestUtil.randomString(), serviceContext);
    } finally {
      PrincipalThreadLocal.setName(name);
    }

    Assert.assertEquals(
        initialSearchGroupEntriesCount + 5, searchGroupEntriesCount(group.getGroupId(), 0));

    moveParentBaseModelToTrash((Long) parentBaseModel2.getPrimaryKeyObj());

    Assert.assertEquals(
        initialSearchGroupEntriesCount + 3, searchGroupEntriesCount(group.getGroupId(), 0));

    TrashHandler parentTrashHandler =
        TrashHandlerRegistryUtil.getTrashHandler(getParentBaseModelClassName());

    parentTrashHandler.restoreTrashEntry(
        TestPropsValues.getUserId(), (Long) parentBaseModel2.getPrimaryKeyObj());

    Assert.assertEquals(
        initialSearchGroupEntriesCount + 5, searchGroupEntriesCount(group.getGroupId(), 0));
  }
  protected void addEquityLog(
      User user, AssetEntry assetEntry, User assetEntryUser, SocialEquitySetting equitySetting)
      throws PortalException, SystemException {

    if (!isAddEquityLog(user.getUserId(), assetEntry.getEntryId(), equitySetting)) {

      return;
    }

    int actionDate = getEquityDate();

    double k = calculateK(equitySetting.getValue(), equitySetting.getLifespan());
    double b = calculateB(actionDate, equitySetting.getValue(), equitySetting.getLifespan());

    SocialEquityValue socialEquity = new SocialEquityValue(k, b);

    if (equitySetting.getType() == SocialEquitySettingConstants.TYPE_INFORMATION) {

      socialEquityLogLocalService.incrementSocialEquityAssetEntry_IQ(
          assetEntry.getEntryId(), socialEquity);

      if ((assetEntryUser != null) && !assetEntryUser.isDefaultUser()) {
        socialEquityLogLocalService.incrementSocialEquityUser_CQ(
            assetEntry.getGroupId(), assetEntryUser.getUserId(), socialEquity);
      }
    } else if (equitySetting.getType() == SocialEquitySettingConstants.TYPE_PARTICIPATION) {

      if (!user.isDefaultUser()) {
        socialEquityLogLocalService.incrementSocialEquityUser_PQ(
            assetEntry.getGroupId(), user.getUserId(), socialEquity);
      }
    }

    long equityLogId = counterLocalService.increment();

    SocialEquityLog equityLog = socialEquityLogPersistence.create(equityLogId);

    equityLog.setGroupId(assetEntry.getGroupId());
    equityLog.setCompanyId(user.getCompanyId());
    equityLog.setUserId(user.getUserId());
    equityLog.setAssetEntryId(assetEntry.getEntryId());
    equityLog.setActionId(equitySetting.getActionId());
    equityLog.setActionDate(actionDate);
    equityLog.setType(equitySetting.getType());
    equityLog.setValue(equitySetting.getValue());
    equityLog.setExpiration(actionDate + equitySetting.getLifespan());
    equityLog.setActive(true);

    socialEquityLogPersistence.update(equityLog, false);
  }
  /*
   * NOTE FOR DEVELOPERS:
   *
   * Never reference this interface directly. Always use {@link com.primum.service.WizardServiceLocalServiceUtil} to access the wizard service local service.
   */
  public boolean updateConfig(
      User creatorUser,
      long deviceConfigId,
      String deviceConfigName,
      long patientId,
      Date startDate,
      Date endDate,
      List<MedicalTestType> medicalTestTypeList,
      ServiceContext serviceContext)
      throws PortalException, SystemException {

    debug("dates:" + startDate + " to " + endDate);

    Date now = new Date();

    DeviceConfig deviceConfig = null;
    if (deviceConfigId > 0) {
      debug("finding deviceConfig for deviceConfigId: " + deviceConfigId);
      deviceConfig = DeviceConfigLocalServiceUtil.getDeviceConfig(deviceConfigId);
    } else {
      debug("Creating deviceUser");
      User deviceUser = createDeviceUser(creatorUser, deviceConfigName, serviceContext);
      debug("finding deviceConfig for new User");
      deviceConfig = DeviceConfigLocalServiceUtil.getDeviceConfigByDeviceId(deviceUser.getUserId());
    }

    debug("deviceConfig found: " + deviceConfig);

    if (deviceConfig != null) {
      deviceConfig.setModifiedDate(now);
      deviceConfig.setPatientId(patientId);
      deviceConfig.setCreatorUserId(creatorUser.getUserId());
      deviceConfig = DeviceConfigLocalServiceUtil.updateDeviceConfig(deviceConfig);
      debug("deviceConfig updated: " + deviceConfig);
      updatePeripherals(deviceConfig, medicalTestTypeList);
      CalEvent calEvent =
          createEvent4Patient(
              deviceConfigName, creatorUser, patientId, startDate, endDate, serviceContext);

    } else {
      throw new SystemException("Unable to create a valid deviceConfig");
    }

    _log.info("Patient (#" + patientId + ") config was updated: " + deviceConfig);
    for (MedicalTestType mtt : medicalTestTypeList) {
      _log.info("   new medicalTestType added: " + mtt.getMedicalTestTypeKey());
    }

    return true;
  }
  protected void updateSocialRelations(User user) throws Exception {
    List<User> socialUsers =
        UserLocalServiceUtil.getSocialUsers(
            user.getUserId(),
            SocialRelationConstants.TYPE_BI_FRIEND,
            QueryUtil.ALL_POS,
            QueryUtil.ALL_POS,
            null);

    for (User socialUser : socialUsers) {
      SocialRelationLocalServiceUtil.addRelation(
          user.getUserId(), socialUser.getUserId(), SocialRelationConstants.TYPE_BI_CONNECTION);
    }
  }
  protected File[] exportLayouts(long userGroupId, Map<String, String[]> parameterMap)
      throws PortalException {

    File[] files = new File[2];

    UserGroup userGroup = userGroupPersistence.findByPrimaryKey(userGroupId);

    User user = userLocalService.getUser(GetterUtil.getLong(PrincipalThreadLocal.getName()));

    Group group = userGroup.getGroup();

    if (userGroup.hasPrivateLayouts()) {
      Map<String, Serializable> exportLayoutSettingsMap =
          ExportImportConfigurationSettingsMapFactory.buildExportLayoutSettingsMap(
              user,
              group.getGroupId(),
              true,
              ExportImportHelperUtil.getAllLayoutIds(group.getGroupId(), true),
              parameterMap);

      ExportImportConfiguration exportImportConfiguration =
          exportImportConfigurationLocalService.addDraftExportImportConfiguration(
              user.getUserId(),
              ExportImportConfigurationConstants.TYPE_EXPORT_LAYOUT,
              exportLayoutSettingsMap);

      files[0] = exportImportLocalService.exportLayoutsAsFile(exportImportConfiguration);
    }

    if (userGroup.hasPublicLayouts()) {
      Map<String, Serializable> exportLayoutSettingsMap =
          ExportImportConfigurationSettingsMapFactory.buildExportLayoutSettingsMap(
              user,
              group.getGroupId(),
              false,
              ExportImportHelperUtil.getAllLayoutIds(group.getGroupId(), false),
              parameterMap);

      ExportImportConfiguration exportImportConfiguration =
          exportImportConfigurationLocalService.addDraftExportImportConfiguration(
              user.getUserId(),
              ExportImportConfigurationConstants.TYPE_EXPORT_LAYOUT,
              exportLayoutSettingsMap);

      files[1] = exportImportLocalService.exportLayoutsAsFile(exportImportConfiguration);
    }

    return files;
  }
  @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));
  }
  @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;
  }
  protected void lockProtectedGetActivityLimit(
      final long groupId,
      final User user,
      final SocialActivity activity,
      final SocialActivityCounterDefinition activityCounterDefinition)
      throws PortalException {

    final long classPK = getLimitClassPK(activity, activityCounterDefinition);

    String lockKey =
        StringUtil.merge(
            new Object[] {
              groupId,
              user.getUserId(),
              activity.getClassNameId(),
              classPK,
              activity.getType(),
              activityCounterDefinition.getName()
            },
            StringPool.POUND);

    LockProtectedAction<SocialActivityLimit> lockProtectedAction =
        new LockProtectedAction<SocialActivityLimit>(
            SocialActivityLimit.class,
            lockKey,
            PropsValues.SOCIAL_ACTIVITY_LOCK_TIMEOUT,
            PropsValues.SOCIAL_ACTIVITY_LOCK_RETRY_DELAY) {

          @Override
          protected SocialActivityLimit performProtectedAction() throws PortalException {

            SocialActivityLimit activityLimit =
                socialActivityLimitPersistence.fetchByG_U_C_C_A_A(
                    groupId,
                    user.getUserId(),
                    activity.getClassNameId(),
                    classPK,
                    activity.getType(),
                    activityCounterDefinition.getName());

            if (activityLimit == null) {
              activityLimit =
                  socialActivityLimitLocalService.addActivityLimit(
                      user.getUserId(),
                      activity.getGroupId(),
                      activity.getClassNameId(),
                      classPK,
                      activity.getType(),
                      activityCounterDefinition.getName(),
                      activityCounterDefinition.getLimitPeriod());
            }

            return activityLimit;
          }
        };

    lockProtectedAction.performAction();

    socialActivityLimitPersistence.cacheResult(lockProtectedAction.getReturnValue());
  }
  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;
  }
  protected void redirectUpdateAccount(
      HttpServletRequest request, HttpServletResponse response, User user) throws Exception {

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

    PortletURL portletURL =
        PortletURLFactoryUtil.create(
            request, PortletKeys.LOGIN, themeDisplay.getPlid(), PortletRequest.RENDER_PHASE);

    portletURL.setParameter("saveLastPath", Boolean.FALSE.toString());
    portletURL.setParameter("struts_action", "/login/update_account");

    PortletURL redirectURL =
        PortletURLFactoryUtil.create(
            request, PortletKeys.FAST_LOGIN, themeDisplay.getPlid(), PortletRequest.RENDER_PHASE);

    redirectURL.setParameter("struts_action", "/login/login_redirect");
    redirectURL.setParameter("emailAddress", user.getEmailAddress());
    redirectURL.setParameter("anonymousUser", Boolean.FALSE.toString());
    redirectURL.setPortletMode(PortletMode.VIEW);
    redirectURL.setWindowState(LiferayWindowState.POP_UP);

    portletURL.setParameter("redirect", redirectURL.toString());
    portletURL.setParameter("userId", String.valueOf(user.getUserId()));
    portletURL.setParameter("emailAddress", user.getEmailAddress());
    portletURL.setParameter("firstName", user.getFirstName());
    portletURL.setParameter("lastName", user.getLastName());
    portletURL.setPortletMode(PortletMode.VIEW);
    portletURL.setWindowState(LiferayWindowState.POP_UP);

    response.sendRedirect(portletURL.toString());
  }
  @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;
  }
  @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;
  }
 @Override
 public void run(String[] arg0) throws ActionException {
   Properties props = new Properties();
   try {
     props.load(
         this.getClass().getClassLoader().getResourceAsStream("password.changer.properties"));
     String type = props.getProperty("type");
     String virtualHost = props.getProperty("virtualhost");
     Company c = CompanyUtil.fetchByVirtualHost(virtualHost);
     User u = null;
     String name = null;
     if ("screenname".equals(type)) {
       String screenName = props.getProperty("screenname");
       u = UserLocalServiceUtil.getUserByScreenName(c.getCompanyId(), screenName);
       name = screenName;
     } else if ("e-mail".equals(type)) {
       String emailAddress = props.getProperty("emailaddress");
       u = UserLocalServiceUtil.getUserByEmailAddress(c.getCompanyId(), emailAddress);
       name = emailAddress;
     } else {
       _log.error(
           "You should set type to screenname or e-mail if you want to use the password updater.");
     }
     String password = props.getProperty("password");
     UserLocalServiceUtil.updatePasswordManually(u.getUserId(), password, false, true, new Date());
     _log.info("Password for " + name + " was updated.");
   } catch (Exception e) {
     _log.error(e);
   }
 }
  @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);
  }
Beispiel #23
0
  /** @deprecated As of 6.2.0, replaced by {@link #getUserName(long, ServiceContext)} */
  protected String getUserName(long userId, ThemeDisplay themeDisplay) {
    try {
      if (userId <= 0) {
        return StringPool.BLANK;
      }

      User user = UserLocalServiceUtil.getUserById(userId);

      if (user.getUserId() == themeDisplay.getUserId()) {
        return HtmlUtil.escape(user.getFirstName());
      }

      String userName = user.getFullName();

      Group group = user.getGroup();

      if (group.getGroupId() == themeDisplay.getScopeGroupId()) {
        return HtmlUtil.escape(userName);
      }

      String userDisplayURL = user.getDisplayURL(themeDisplay);

      userName =
          "******"user\" href=\"" + userDisplayURL + "\">" + HtmlUtil.escape(userName) + "</a>";

      return userName;
    } catch (Exception e) {
      return StringPool.BLANK;
    }
  }
  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 KaleoTaskInstanceToken addKaleoTaskInstanceToken(
      long kaleoInstanceTokenId,
      long kaleoTaskId,
      String kaleoTaskName,
      Collection<KaleoTaskAssignment> kaleoTaskAssignments,
      Date dueDate,
      Map<String, Serializable> workflowContext,
      ServiceContext serviceContext)
      throws PortalException, SystemException {

    KaleoInstanceToken kaleoInstanceToken =
        kaleoInstanceTokenPersistence.findByPrimaryKey(kaleoInstanceTokenId);

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

    long kaleoTaskInstanceTokenId = counterLocalService.increment();

    KaleoTaskInstanceToken kaleoTaskInstanceToken =
        kaleoTaskInstanceTokenPersistence.create(kaleoTaskInstanceTokenId);

    long groupId = StagingUtil.getLiveGroupId(serviceContext.getScopeGroupId());

    kaleoTaskInstanceToken.setGroupId(groupId);

    kaleoTaskInstanceToken.setCompanyId(user.getCompanyId());
    kaleoTaskInstanceToken.setUserId(user.getUserId());
    kaleoTaskInstanceToken.setUserName(user.getFullName());
    kaleoTaskInstanceToken.setCreateDate(now);
    kaleoTaskInstanceToken.setModifiedDate(now);
    kaleoTaskInstanceToken.setDueDate(dueDate);
    kaleoTaskInstanceToken.setKaleoDefinitionId(kaleoInstanceToken.getKaleoDefinitionId());
    kaleoTaskInstanceToken.setKaleoInstanceId(kaleoInstanceToken.getKaleoInstanceId());
    kaleoTaskInstanceToken.setKaleoInstanceTokenId(kaleoInstanceTokenId);

    kaleoTaskInstanceToken.setKaleoTaskId(kaleoTaskId);
    kaleoTaskInstanceToken.setKaleoTaskName(kaleoTaskName);

    if (workflowContext != null) {
      kaleoTaskInstanceToken.setClassName(
          (String) workflowContext.get(WorkflowConstants.CONTEXT_ENTRY_CLASS_NAME));

      if (workflowContext.containsKey(WorkflowConstants.CONTEXT_ENTRY_CLASS_PK)) {

        kaleoTaskInstanceToken.setClassPK(
            GetterUtil.getLong(
                (String) workflowContext.get(WorkflowConstants.CONTEXT_ENTRY_CLASS_PK)));
      }
    }

    kaleoTaskInstanceToken.setCompleted(false);
    kaleoTaskInstanceToken.setWorkflowContext(WorkflowContextUtil.convert(workflowContext));

    kaleoTaskInstanceTokenPersistence.update(kaleoTaskInstanceToken, false);

    kaleoTaskAssignmentInstanceLocalService.addTaskAssignmentInstances(
        kaleoTaskInstanceToken, kaleoTaskAssignments, workflowContext, serviceContext);

    return kaleoTaskInstanceToken;
  }
  protected void exportImportLayouts(boolean privateLayout) throws Exception {
    List<Layout> layouts =
        LayoutLocalServiceUtil.getLayouts(_stagingGroup.getGroupId(), privateLayout);

    User user = TestPropsValues.getUser();

    Map<String, Serializable> publishLayoutLocalSettingsMap =
        ExportImportConfigurationSettingsMapFactory.buildPublishLayoutLocalSettingsMap(
            user,
            _stagingGroup.getGroupId(),
            _liveGroup.getGroupId(),
            privateLayout,
            ExportImportHelperUtil.getLayoutIds(layouts),
            new HashMap<String, String[]>());

    ExportImportConfiguration exportImportConfiguration =
        ExportImportConfigurationLocalServiceUtil.addDraftExportImportConfiguration(
            user.getUserId(),
            ExportImportConfigurationConstants.TYPE_PUBLISH_LAYOUT_LOCAL,
            publishLayoutLocalSettingsMap);

    File larFile = ExportImportLocalServiceUtil.exportLayoutsAsFile(exportImportConfiguration);

    ExportImportLocalServiceUtil.importLayouts(exportImportConfiguration, larFile);
  }
  @Override
  public void updateDependentStatus(User user, List<Object> categoriesAndThreads, int status)
      throws PortalException, SystemException {

    for (Object object : categoriesAndThreads) {
      if (object instanceof MBThread) {
        MBThread thread = (MBThread) object;

        if ((status == WorkflowConstants.STATUS_APPROVED)
            && (thread.getStatus() == WorkflowConstants.STATUS_IN_TRASH)) {

          continue;
        }

        mbThreadLocalService.updateStatus(user.getUserId(), thread.getThreadId(), status, status);
      } else if (object instanceof MBCategory) {
        MBCategory category = (MBCategory) object;

        if (category.isInTrash()) {
          continue;
        }

        updateDependentStatus(
            user, getCategoriesAndThreads(category.getGroupId(), category.getCategoryId()), status);
      }
    }
  }
 public NotificationRecipient(User user) {
   _companyId = user.getCompanyId();
   _emailAddress = user.getEmailAddress();
   _fullName = user.getFullName();
   _screenName = user.getScreenName();
   _userId = user.getUserId();
 }