@Override
  public BaseModelSearchResult<UserGroup> searchUserGroups(
      long companyId,
      String name,
      String description,
      LinkedHashMap<String, Object> params,
      boolean andSearch,
      int start,
      int end,
      Sort sort)
      throws PortalException {

    Indexer<UserGroup> indexer = IndexerRegistryUtil.nullSafeGetIndexer(UserGroup.class);

    SearchContext searchContext =
        buildSearchContext(companyId, name, description, params, andSearch, start, end, sort);

    for (int i = 0; i < 10; i++) {
      Hits hits = indexer.search(searchContext);

      List<UserGroup> userGroups = UsersAdminUtil.getUserGroups(hits);

      if (userGroups != null) {
        return new BaseModelSearchResult<>(userGroups, hits.getLength());
      }
    }

    throw new SearchException("Unable to fix the search index after 10 attempts");
  }
  public EmpDiscipline addEmpDiscipline(
      EmpDiscipline prePersistedObj, ServiceContext serviceContext) {
    try {
      final EmpDiscipline o = super.addEmpDiscipline(prePersistedObj);

      // add permission
      resourceLocalService.addResources(
          o.getCompanyId(),
          o.getGroupId(),
          o.getUserId(),
          EmpDiscipline.class.getName(),
          o.getEmpDisciplineId(),
          false,
          true,
          true);

      // index new EmpDiscipline
      Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(EmpDiscipline.class);
      indexer.reindex(EmpDiscipline.class.getName(), o.getEmpDisciplineId());

      final Emp emp = empLocalService.fetchEmp(o.getEmpId());
      emp.setStatus(EmployeeStatus.DISCIPLINE.toString());
      empLocalService.updateEmp(emp);

      return o;
    } catch (SystemException e) {
      LOGGER.info(e);
    } catch (SearchException e) {
      LOGGER.info(e);
    } catch (PortalException e) {
      LOGGER.info(e);
    }
    return null;
  }
  /**
   * Returns the number of user groups that match the name and description.
   *
   * @param companyId the primary key of the user group's company
   * @param name the user group's name (optionally <code>null</code>)
   * @param description the user group's description (optionally <code>null</code>)
   * @param params the finder params (optionally <code>null</code>). For more information see {@link
   *     com.liferay.portal.service.persistence.UserGroupFinder}
   * @param andOperator whether every field must match its keywords or just one field
   * @return the number of matching user groups
   * @see com.liferay.portal.service.persistence.UserGroupFinder
   */
  @Override
  public int searchCount(
      long companyId,
      String name,
      String description,
      LinkedHashMap<String, Object> params,
      boolean andOperator) {

    Indexer<?> indexer = IndexerRegistryUtil.nullSafeGetIndexer(UserGroup.class);

    if (!indexer.isIndexerEnabled()
        || !PropsValues.USER_GROUPS_SEARCH_WITH_INDEX
        || isUseCustomSQL(params)) {

      return userGroupFinder.countByC_N_D(companyId, name, description, params, andOperator);
    }

    try {
      SearchContext searchContext =
          buildSearchContext(
              companyId,
              name,
              description,
              params,
              true,
              QueryUtil.ALL_POS,
              QueryUtil.ALL_POS,
              null);

      return (int) indexer.searchCount(searchContext);
    } catch (Exception e) {
      throw new SystemException(e);
    }
  }
  @Override
  @SystemEvent(action = SystemEventConstants.ACTION_SKIP, type = SystemEventConstants.TYPE_DELETE)
  public void deleteCategory(MBCategory category, boolean includeTrashedEntries)
      throws PortalException, SystemException {

    // Categories

    List<MBCategory> categories =
        mbCategoryPersistence.findByG_P(category.getGroupId(), category.getCategoryId());

    for (MBCategory curCategory : categories) {
      if (includeTrashedEntries || !curCategory.isInTrash()) {
        deleteCategory(curCategory, includeTrashedEntries);
      }
    }

    // Indexer

    Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(MBMessage.class);

    indexer.delete(category);

    // Threads

    mbThreadLocalService.deleteThreads(
        category.getGroupId(), category.getCategoryId(), includeTrashedEntries);

    // Mailing list

    try {
      mbMailingListLocalService.deleteCategoryMailingList(
          category.getGroupId(), category.getCategoryId());
    } catch (NoSuchMailingListException nsmle) {
    }

    // Subscriptions

    subscriptionLocalService.deleteSubscriptions(
        category.getCompanyId(), MBCategory.class.getName(), category.getCategoryId());

    // Expando

    expandoRowLocalService.deleteRows(category.getCategoryId());

    // Resources

    resourceLocalService.deleteResource(
        category.getCompanyId(),
        MBCategory.class.getName(),
        ResourceConstants.SCOPE_INDIVIDUAL,
        category.getCategoryId());

    // Trash

    trashEntryLocalService.deleteEntry(MBCategory.class.getName(), category.getCategoryId());

    // Category

    mbCategoryPersistence.remove(category);
  }
  /**
   * Updates the user group.
   *
   * @param companyId the primary key of the user group's company
   * @param userGroupId the primary key of the user group
   * @param name the user group's name
   * @param description the user group's description
   * @param serviceContext the service context to be applied (optionally <code>null</code>). Can set
   *     expando bridge attributes for the user group.
   * @return the user group
   */
  @Override
  public UserGroup updateUserGroup(
      long companyId,
      long userGroupId,
      String name,
      String description,
      ServiceContext serviceContext)
      throws PortalException {

    // User group

    validate(userGroupId, companyId, name);

    UserGroup userGroup = userGroupPersistence.findByPrimaryKey(userGroupId);

    userGroup.setName(name);
    userGroup.setDescription(description);
    userGroup.setExpandoBridgeAttributes(serviceContext);

    userGroupPersistence.update(userGroup);

    // Indexer

    Indexer<UserGroup> indexer = IndexerRegistryUtil.nullSafeGetIndexer(UserGroup.class);

    indexer.reindex(userGroup);

    return userGroup;
  }
  @Override
  public MBThread moveThread(long groupId, long categoryId, long threadId)
      throws PortalException, SystemException {

    MBThread thread = mbThreadPersistence.findByPrimaryKey(threadId);

    long oldCategoryId = thread.getCategoryId();

    MBCategory oldCategory = null;

    if (oldCategoryId != MBCategoryConstants.DEFAULT_PARENT_CATEGORY_ID) {
      oldCategory = mbCategoryPersistence.fetchByPrimaryKey(oldCategoryId);
    }

    MBCategory category = null;

    if (categoryId != MBCategoryConstants.DEFAULT_PARENT_CATEGORY_ID) {
      category = mbCategoryPersistence.fetchByPrimaryKey(categoryId);
    }

    // Thread

    thread.setModifiedDate(new Date());
    thread.setCategoryId(categoryId);

    mbThreadPersistence.update(thread);

    // Messages

    List<MBMessage> messages =
        mbMessagePersistence.findByG_C_T(groupId, oldCategoryId, thread.getThreadId());

    for (MBMessage message : messages) {
      message.setCategoryId(categoryId);

      mbMessagePersistence.update(message);

      // Indexer

      if (!message.isDiscussion()) {
        Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(MBMessage.class);

        indexer.reindex(message);
      }
    }

    // Category

    if ((oldCategory != null) && (categoryId != oldCategoryId)) {
      MBUtil.updateCategoryStatistics(oldCategory.getCompanyId(), oldCategory.getCategoryId());
    }

    if ((category != null) && (categoryId != oldCategoryId)) {
      MBUtil.updateCategoryStatistics(category.getCompanyId(), category.getCategoryId());
    }

    return thread;
  }
  public void reindex(List<AssetEntry> entries) throws PortalException {
    for (AssetEntry entry : entries) {
      String className = PortalUtil.getClassName(entry.getClassNameId());

      Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(className);

      indexer.reindex(className, entry.getClassPK());
    }
  }
  /**
   * Adds the roles to the user. The user is reindexed after the roles are added.
   *
   * @param userId the primary key of the user
   * @param roleIds the primary keys of the roles
   * @throws PortalException if a user with the primary key could not be found
   * @throws SystemException if a system exception occurred
   * @see com.liferay.portal.service.persistence.UserPersistence#addRoles( long, long[])
   */
  public void addUserRoles(long userId, long[] roleIds) throws PortalException, SystemException {

    userPersistence.addRoles(userId, roleIds);

    Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);

    indexer.reindex(userId);

    PermissionCacheUtil.clearCache();
  }
 /**
  * Xóa bỏ thông tin một thống kê theo ngày
  *
  * <p>Version: OEP 2.0
  *
  * <p>History: DATE AUTHOR DESCRIPTION -------------------------------------------------
  * 21-September-2015 trungdk Xóa bỏ thông tin thống kê theo ngày
  *
  * @param statisticByDomain thống kê theo ngày được xóa
  * @return
  */
 public void removeStatisticByDomain(StatisticByDomain statisticByDomain)
     throws PortalException, SystemException {
   statisticByDomainPersistence.remove(statisticByDomain);
   Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(StatisticByDomain.class);
   indexer.delete(statisticByDomain);
   resourceLocalService.deleteResource(
       statisticByDomain.getCompanyId(),
       StatisticByDomain.class.getName(),
       ResourceConstants.SCOPE_INDIVIDUAL,
       statisticByDomain.getStatisticByDomainId());
 }
  protected void mergeCategories(MBCategory fromCategory, long toCategoryId)
      throws PortalException, SystemException {

    if ((toCategoryId == MBCategoryConstants.DEFAULT_PARENT_CATEGORY_ID)
        || (toCategoryId == MBCategoryConstants.DISCUSSION_CATEGORY_ID)) {

      return;
    }

    List<MBCategory> categories =
        mbCategoryPersistence.findByG_P(fromCategory.getGroupId(), fromCategory.getCategoryId());

    for (MBCategory category : categories) {
      mergeCategories(category, toCategoryId);
    }

    List<MBThread> threads =
        mbThreadPersistence.findByG_C(fromCategory.getGroupId(), fromCategory.getCategoryId());

    for (MBThread thread : threads) {

      // Thread

      thread.setCategoryId(toCategoryId);

      mbThreadPersistence.update(thread);

      List<MBMessage> messages = mbMessagePersistence.findByThreadId(thread.getThreadId());

      for (MBMessage message : messages) {

        // Message

        message.setCategoryId(toCategoryId);

        mbMessagePersistence.update(message);

        // Indexer

        Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(MBMessage.class);

        indexer.reindex(message);
      }
    }

    MBCategory toCategory = mbCategoryPersistence.findByPrimaryKey(toCategoryId);

    toCategory.setThreadCount(fromCategory.getThreadCount() + toCategory.getThreadCount());
    toCategory.setMessageCount(fromCategory.getMessageCount() + toCategory.getMessageCount());

    mbCategoryPersistence.update(toCategory);

    deleteCategory(fromCategory);
  }
  /**
   * Removes the matching roles associated with the user. The user is reindexed after the roles are
   * removed.
   *
   * @param userId the primary key of the user
   * @param roleIds the primary keys of the roles
   * @throws PortalException if a user with the primary key could not be found or if a role with any
   *     one of the primary keys could not be found
   * @throws SystemException if a system exception occurred
   */
  public void unsetUserRoles(long userId, long[] roleIds) throws PortalException, SystemException {

    roleIds = UsersAdminUtil.removeRequiredRoles(userId, roleIds);

    userPersistence.removeRoles(userId, roleIds);

    Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);

    indexer.reindex(userId);

    PermissionCacheUtil.clearCache();
  }
  /**
   * 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;
  }
Пример #13
0
 public void indexAll() {
   final List<EmpDiscipline> all = findAll();
   // re-index modified employee
   Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(EmpDiscipline.class.getName());
   for (EmpDiscipline item : all) {
     // re-index
     try {
       indexer.reindex(item);
     } catch (SearchException e) {
       LOGGER.info(e);
     }
   }
 }
Пример #14
0
  public EmpDiscipline updateEmpDiscipline(EmpDiscipline empDiscipline) throws SystemException {
    try {
      EmpDiscipline o = super.updateEmpDiscipline(empDiscipline);
      // index new EmpDiscipline
      Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(EmpDiscipline.class);

      indexer.reindex(EmpDiscipline.class.getName(), o.getEmpDisciplineId());
      return o;
    } catch (SearchException e) {
      LOGGER.info(e);
    }
    return null;
  }
Пример #15
0
  public void deleteCategory(MBCategory category) throws PortalException, SystemException {

    // Categories

    List<MBCategory> categories =
        mbCategoryPersistence.findByG_P(category.getGroupId(), category.getCategoryId());

    for (MBCategory curCategory : categories) {
      deleteCategory(curCategory);
    }

    // Indexer

    Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(MBMessage.class);

    indexer.delete(category);

    // Threads

    mbThreadLocalService.deleteThreads(category.getGroupId(), category.getCategoryId());

    // Mailing list

    try {
      mbMailingListLocalService.deleteCategoryMailingList(
          category.getGroupId(), category.getCategoryId());
    } catch (NoSuchMailingListException nsmle) {
    }

    // Subscriptions

    subscriptionLocalService.deleteSubscriptions(
        category.getCompanyId(), MBCategory.class.getName(), category.getCategoryId());

    // Expando

    expandoValueLocalService.deleteValues(MBCategory.class.getName(), category.getCategoryId());

    // Resources

    resourceLocalService.deleteResource(
        category.getCompanyId(),
        MBCategory.class.getName(),
        ResourceConstants.SCOPE_INDIVIDUAL,
        category.getCategoryId());

    // Category

    mbCategoryPersistence.remove(category);
  }
Пример #16
0
  @Override
  protected void doDelete(Object obj) throws Exception {
    User user = (User) obj;

    deleteDocument(user.getCompanyId(), user.getUserId());

    Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(Contact.class);

    Contact contact = new ContactImpl();

    contact.setContactId(user.getContactId());
    contact.setCompanyId(user.getCompanyId());

    indexer.delete(contact);
  }
    @Override
    public Void call() {
      Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);

      long[] userIds = ArrayUtil.toArray(_userIds.toArray(new Long[0]));

      try {
        indexer.reindex(userIds);
      } catch (SearchException se) {
        if (_log.isWarnEnabled()) {
          _log.warn(se, se);
        }
      }

      return null;
    }
  protected void restoreDependentsFromTrash(List<Song> songs, long trashEntryId)
      throws PortalException {

    for (Song song : songs) {

      // Song

      TrashEntry trashEntry =
          trashEntryLocalService.fetchEntry(Song.class.getName(), song.getSongId());

      if (trashEntry != null) {
        continue;
      }

      TrashVersion trashVersion =
          trashVersionLocalService.fetchVersion(
              trashEntryId, Song.class.getName(), song.getSongId());

      int oldStatus = WorkflowConstants.STATUS_APPROVED;

      if (trashVersion != null) {
        oldStatus = trashVersion.getStatus();
      }

      song.setStatus(oldStatus);

      songPersistence.update(song);

      // Trash

      if (trashVersion != null) {
        trashVersionLocalService.deleteTrashVersion(trashVersion);
      }

      // Asset

      if (oldStatus == WorkflowConstants.STATUS_APPROVED) {
        assetEntryLocalService.updateVisible(Song.class.getName(), song.getSongId(), true);
      }

      // Indexer

      Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(Song.class);

      indexer.reindex(song);
    }
  }
  /**
   * Sets the user groups associated with the user copying the user group layouts and removing and
   * adding user group associations for the user as necessary.
   *
   * @param userId the primary key of the user
   * @param userGroupIds the primary keys of the user groups
   */
  @Override
  public void setUserUserGroups(long userId, long[] userGroupIds) throws PortalException {

    if (PropsValues.USER_GROUPS_COPY_LAYOUTS_TO_USER_PERSONAL_SITE) {
      copyUserGroupLayouts(userGroupIds, userId);
    }

    userPersistence.setUserGroups(userId, userGroupIds);

    Indexer<User> indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);

    User user = userLocalService.fetchUser(userId);

    indexer.reindex(user);

    PermissionCacheUtil.clearCache(userId);
  }
  protected BaseModelSearchResult<AssetVocabulary> searchVocabularies(SearchContext searchContext)
      throws PortalException {

    Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(AssetVocabulary.class);

    for (int i = 0; i < 10; i++) {
      Hits hits = indexer.search(searchContext);

      List<AssetVocabulary> vocabularies = getVocabularies(hits);

      if (vocabularies != null) {
        return new BaseModelSearchResult<>(vocabularies, hits.getLength());
      }
    }

    throw new SearchException("Unable to fix the search index after 10 attempts");
  }
  /**
   * Returns the number of user groups that match the keywords
   *
   * @param companyId the primary key of the user group's company
   * @param keywords the keywords (space separated), which may occur in the user group's name or
   *     description (optionally <code>null</code>)
   * @param params the finder params (optionally <code>null</code>). For more information see {@link
   *     com.liferay.portal.service.persistence.UserGroupFinder}
   * @return the number of matching user groups
   * @see com.liferay.portal.service.persistence.UserGroupFinder
   */
  @Override
  public int searchCount(long companyId, String keywords, LinkedHashMap<String, Object> params) {

    Indexer<?> indexer = IndexerRegistryUtil.nullSafeGetIndexer(UserGroup.class);

    if (!indexer.isIndexerEnabled()
        || !PropsValues.USER_GROUPS_SEARCH_WITH_INDEX
        || isUseCustomSQL(params)) {

      return userGroupFinder.countByKeywords(companyId, keywords, params);
    }

    String name = null;
    String description = null;
    boolean andOperator = false;

    if (Validator.isNotNull(keywords)) {
      name = keywords;
      description = keywords;
    } else {
      andOperator = true;
    }

    if (params != null) {
      params.put("keywords", keywords);
    }

    try {
      SearchContext searchContext =
          buildSearchContext(
              companyId,
              name,
              description,
              params,
              andOperator,
              QueryUtil.ALL_POS,
              QueryUtil.ALL_POS,
              null);

      return (int) indexer.searchCount(searchContext);
    } catch (Exception e) {
      throw new SystemException(e);
    }
  }
  @Override
  public void reindexDDMStructures(List<Long> ddmStructureIds) throws SearchException {

    if (IndexWriterHelperUtil.isIndexReadOnly() || !isIndexerEnabled()) {
      return;
    }

    try {
      Indexer<DLFileEntry> indexer = IndexerRegistryUtil.nullSafeGetIndexer(DLFileEntry.class);

      List<DLFileEntry> dlFileEntries =
          DLFileEntryLocalServiceUtil.getDDMStructureFileEntries(
              ArrayUtil.toLongArray(ddmStructureIds));

      for (DLFileEntry dlFileEntry : dlFileEntries) {
        indexer.reindex(dlFileEntry);
      }
    } catch (Exception e) {
      throw new SearchException(e);
    }
  }
  protected void moveDependentsToTrash(List<Song> songs, long trashEntryId) throws PortalException {

    for (Song song : songs) {

      // Entry

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

      int oldStatus = song.getStatus();

      song.setStatus(WorkflowConstants.STATUS_IN_TRASH);

      songPersistence.update(song);

      // Trash

      int status = oldStatus;

      if (oldStatus == WorkflowConstants.STATUS_PENDING) {
        status = WorkflowConstants.STATUS_DRAFT;
      }

      if (oldStatus != WorkflowConstants.STATUS_APPROVED) {
        trashVersionLocalService.addTrashVersion(
            trashEntryId, Song.class.getName(), song.getSongId(), status, null);
      }

      // Asset

      assetEntryLocalService.updateVisible(Song.class.getName(), song.getSongId(), false);

      // Indexer

      Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(Song.class);

      indexer.reindex(song);
    }
  }
  /**
   * Returns an ordered range of all the user groups that match the name and description. It is
   * preferable to use this method instead of the non-indexed version whenever possible for
   * performance reasons.
   *
   * <p>Useful when paginating results. Returns a maximum of <code>end -
   * start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are
   * indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting
   * both <code>start</code> and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full
   * result set.
   *
   * @param companyId the primary key of the user group's company
   * @param name the user group's name (optionally <code>null</code>)
   * @param description the user group's description (optionally <code>null</code>)
   * @param params the finder params (optionally <code>null</code>). For more information see {@link
   *     com.liferay.portlet.usergroupsadmin.util.UserGroupIndexer}
   * @param andSearch whether every field must match its keywords or just one field
   * @param start the lower bound of the range of user groups to return
   * @param end the upper bound of the range of user groups to return (not inclusive)
   * @param sort the field and direction by which to sort (optionally <code>null</code>)
   * @return the matching user groups ordered by sort
   * @see com.liferay.portal.service.persistence.UserGroupFinder
   */
  @Override
  public Hits search(
      long companyId,
      String name,
      String description,
      LinkedHashMap<String, Object> params,
      boolean andSearch,
      int start,
      int end,
      Sort sort) {

    try {
      Indexer<UserGroup> indexer = IndexerRegistryUtil.nullSafeGetIndexer(UserGroup.class);

      SearchContext searchContext =
          buildSearchContext(companyId, name, description, params, andSearch, start, end, sort);

      return indexer.search(searchContext);
    } catch (Exception e) {
      throw new SystemException(e);
    }
  }
  protected void moveChildrenMessages(
      MBMessage parentMessage, MBCategory category, long oldThreadId) throws PortalException {

    List<MBMessage> messages =
        mbMessagePersistence.findByT_P(oldThreadId, parentMessage.getMessageId());

    for (MBMessage message : messages) {
      message.setCategoryId(parentMessage.getCategoryId());
      message.setThreadId(parentMessage.getThreadId());
      message.setRootMessageId(parentMessage.getRootMessageId());

      mbMessagePersistence.update(message);

      if (!message.isDiscussion()) {
        Indexer<MBMessage> indexer = IndexerRegistryUtil.nullSafeGetIndexer(MBMessage.class);

        indexer.reindex(message);
      }

      moveChildrenMessages(message, category, oldThreadId);
    }
  }
  @Override
  public MBThread updateStatus(long userId, long threadId, int status) throws PortalException {

    MBThread thread = mbThreadPersistence.findByPrimaryKey(threadId);

    // Thread

    User user = userPersistence.findByPrimaryKey(userId);

    thread.setStatus(status);
    thread.setStatusByUserId(user.getUserId());
    thread.setStatusByUserName(user.getFullName());
    thread.setStatusDate(new Date());

    mbThreadPersistence.update(thread);

    // Messages

    if (thread.getCategoryId() != MBCategoryConstants.DEFAULT_PARENT_CATEGORY_ID) {

      // Category

      MBCategory category = mbCategoryPersistence.fetchByPrimaryKey(thread.getCategoryId());

      if (category != null) {
        MBUtil.updateCategoryStatistics(category.getCategoryId());
      }
    }

    // Indexer

    Indexer<MBThread> indexer = IndexerRegistryUtil.nullSafeGetIndexer(MBThread.class);

    indexer.reindex(thread);

    return thread;
  }
  protected void updateDependentStatus(long groupId, long threadId, int status)
      throws PortalException, SystemException {

    Set<Long> userIds = new HashSet<Long>();

    List<MBMessage> messages =
        mbMessageLocalService.getThreadMessages(threadId, WorkflowConstants.STATUS_ANY);

    for (MBMessage message : messages) {
      if (message.isDiscussion()) {
        continue;
      }

      userIds.add(message.getUserId());

      if (status == WorkflowConstants.STATUS_IN_TRASH) {

        // Asset

        if (message.getStatus() == WorkflowConstants.STATUS_APPROVED) {
          assetEntryLocalService.updateVisible(
              MBMessage.class.getName(), message.getMessageId(), false);
        }

        // Social

        socialActivityCounterLocalService.disableActivityCounters(
            MBMessage.class.getName(), message.getMessageId());

        // Index

        Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(MBMessage.class);

        indexer.reindex(message);

        // Workflow

        if (message.getStatus() == WorkflowConstants.STATUS_PENDING) {
          message.setStatus(WorkflowConstants.STATUS_DRAFT);

          mbMessagePersistence.update(message);

          workflowInstanceLinkLocalService.deleteWorkflowInstanceLink(
              message.getCompanyId(), message.getGroupId(),
              MBMessage.class.getName(), message.getMessageId());
        }
      } else {

        // Asset

        if (message.getStatus() == WorkflowConstants.STATUS_APPROVED) {
          assetEntryLocalService.updateVisible(
              MBMessage.class.getName(), message.getMessageId(), true);
        }

        // Social

        socialActivityCounterLocalService.enableActivityCounters(
            MBMessage.class.getName(), message.getMessageId());

        // Index

        Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(MBMessage.class);

        indexer.reindex(message);
      }
    }

    // Statistics

    for (long userId : userIds) {
      mbStatsUserLocalService.updateStatsUser(groupId, userId);
    }
  }
  @Override
  public MBThread splitThread(long messageId, String subject, ServiceContext serviceContext)
      throws PortalException, SystemException {

    MBMessage message = mbMessagePersistence.findByPrimaryKey(messageId);

    if (message.isRoot()) {
      throw new SplitThreadException();
    }

    MBCategory category = message.getCategory();
    MBThread oldThread = message.getThread();
    MBMessage rootMessage = mbMessagePersistence.findByPrimaryKey(oldThread.getRootMessageId());

    // Message flags

    mbMessageLocalService.updateAnswer(message, false, true);

    // Create new thread

    MBThread thread = addThread(message.getCategoryId(), message, serviceContext);

    oldThread.setModifiedDate(serviceContext.getModifiedDate(new Date()));

    mbThreadPersistence.update(oldThread);

    // Update messages

    if (Validator.isNotNull(subject)) {
      MBMessageDisplay messageDisplay =
          mbMessageService.getMessageDisplay(
              messageId, WorkflowConstants.STATUS_ANY, MBThreadConstants.THREAD_VIEW_TREE, false);

      MBTreeWalker treeWalker = messageDisplay.getTreeWalker();

      List<MBMessage> messages = treeWalker.getMessages();

      int[] range = treeWalker.getChildrenRange(message);

      for (int i = range[0]; i < range[1]; i++) {
        MBMessage curMessage = messages.get(i);

        String oldSubject = message.getSubject();
        String curSubject = curMessage.getSubject();

        if (oldSubject.startsWith("RE: ")) {
          curSubject = StringUtil.replace(curSubject, rootMessage.getSubject(), subject);
        } else {
          curSubject = StringUtil.replace(curSubject, oldSubject, subject);
        }

        curMessage.setSubject(curSubject);

        mbMessagePersistence.update(curMessage);
      }

      message.setSubject(subject);
    }

    message.setThreadId(thread.getThreadId());
    message.setRootMessageId(thread.getRootMessageId());
    message.setParentMessageId(0);

    mbMessagePersistence.update(message);

    // Indexer

    if (!message.isDiscussion()) {
      Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(MBMessage.class);

      indexer.reindex(message);
    }

    // Update children

    moveChildrenMessages(message, category, oldThread.getThreadId());

    // Update new thread

    MBUtil.updateThreadMessageCount(thread.getCompanyId(), thread.getThreadId());

    // Update old thread

    MBUtil.updateThreadMessageCount(oldThread.getCompanyId(), oldThread.getThreadId());

    // Category

    if ((message.getCategoryId() != MBCategoryConstants.DEFAULT_PARENT_CATEGORY_ID)
        && (message.getCategoryId() != MBCategoryConstants.DISCUSSION_CATEGORY_ID)) {

      MBUtil.updateCategoryThreadCount(category.getCompanyId(), category.getCategoryId());
    }

    return thread;
  }
  protected void doImportPortletInfo(PortletDataContext portletDataContext, long userId)
      throws Exception {

    Map<String, String[]> parameterMap = portletDataContext.getParameterMap();

    boolean importPermissions =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.PERMISSIONS);

    StopWatch stopWatch = new StopWatch();

    stopWatch.start();

    ServiceContext serviceContext = ServiceContextThreadLocal.getServiceContext();

    if (serviceContext == null) {
      serviceContext = new ServiceContext();

      serviceContext.setCompanyId(portletDataContext.getCompanyId());
      serviceContext.setSignedIn(false);
      serviceContext.setUserId(userId);

      ServiceContextThreadLocal.pushServiceContext(serviceContext);
    }

    // LAR validation

    validateFile(
        portletDataContext.getCompanyId(),
        portletDataContext.getGroupId(),
        portletDataContext.getPortletId(),
        portletDataContext.getZipReader());

    // Source and target group id

    Map<Long, Long> groupIds =
        (Map<Long, Long>) portletDataContext.getNewPrimaryKeysMap(Group.class);

    groupIds.put(portletDataContext.getSourceGroupId(), portletDataContext.getGroupId());

    // Manifest

    ManifestSummary manifestSummary = ExportImportHelperUtil.getManifestSummary(portletDataContext);

    if (BackgroundTaskThreadLocal.hasBackgroundTask()) {
      PortletDataHandlerStatusMessageSenderUtil.sendStatusMessage(
          "portlet", portletDataContext.getPortletId(), manifestSummary);
    }

    portletDataContext.setManifestSummary(manifestSummary);

    // Read expando tables, locks and permissions to make them
    // available to the data handlers through the portlet data context

    Element rootElement = portletDataContext.getImportDataRootElement();

    Element portletElement = null;

    try {
      portletElement = rootElement.element("portlet");

      Document portletDocument =
          SAXReaderUtil.read(
              portletDataContext.getZipEntryAsString(portletElement.attributeValue("path")));

      portletElement = portletDocument.getRootElement();
    } catch (DocumentException de) {
      throw new SystemException(de);
    }

    LayoutCache layoutCache = new LayoutCache();

    if (importPermissions) {
      _permissionImporter.checkRoles(
          layoutCache,
          portletDataContext.getCompanyId(),
          portletDataContext.getGroupId(),
          userId,
          portletElement);

      _permissionImporter.readPortletDataPermissions(portletDataContext);
    }

    readExpandoTables(portletDataContext);
    readLocks(portletDataContext);

    Element portletDataElement = portletElement.element("portlet-data");

    Map<String, Boolean> importPortletControlsMap =
        ExportImportHelperUtil.getImportPortletControlsMap(
            portletDataContext.getCompanyId(),
            portletDataContext.getPortletId(),
            parameterMap,
            portletDataElement,
            manifestSummary);

    Layout layout = _layoutLocalService.getLayout(portletDataContext.getPlid());

    try {

      // Portlet preferences

      importPortletPreferences(
          portletDataContext,
          layout.getCompanyId(),
          portletDataContext.getGroupId(),
          layout,
          portletElement,
          true,
          importPortletControlsMap.get(PortletDataHandlerKeys.PORTLET_ARCHIVED_SETUPS),
          importPortletControlsMap.get(PortletDataHandlerKeys.PORTLET_DATA),
          importPortletControlsMap.get(PortletDataHandlerKeys.PORTLET_SETUP),
          importPortletControlsMap.get(PortletDataHandlerKeys.PORTLET_USER_PREFERENCES));

      // Portlet data

      if (importPortletControlsMap.get(PortletDataHandlerKeys.PORTLET_DATA)) {

        if (_log.isDebugEnabled()) {
          _log.debug("Importing portlet data");
        }

        importPortletData(portletDataContext, portletDataElement);
      }
    } finally {
      resetPortletScope(portletDataContext, portletDataContext.getGroupId());
    }

    // Portlet permissions

    if (importPermissions) {
      if (_log.isDebugEnabled()) {
        _log.debug("Importing portlet permissions");
      }

      _permissionImporter.importPortletPermissions(
          layoutCache,
          portletDataContext.getCompanyId(),
          portletDataContext.getGroupId(),
          userId,
          layout,
          portletElement,
          portletDataContext.getPortletId());

      if (userId > 0) {
        Indexer<User> indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);

        User user = _userLocalService.fetchUser(userId);

        indexer.reindex(user);
      }
    }

    // Asset links

    if (_log.isDebugEnabled()) {
      _log.debug("Importing asset links");
    }

    importAssetLinks(portletDataContext);

    // Deletion system events

    _deletionSystemEventImporter.importDeletionSystemEvents(portletDataContext);

    if (_log.isInfoEnabled()) {
      _log.info("Importing portlet takes " + stopWatch.getTime() + " ms");
    }

    // Service portlet preferences

    boolean importPortletSetup = importPortletControlsMap.get(PortletDataHandlerKeys.PORTLET_SETUP);

    if (importPortletSetup) {
      try {
        List<Element> serviceElements = rootElement.elements("service");

        for (Element serviceElement : serviceElements) {
          Document serviceDocument =
              SAXReaderUtil.read(
                  portletDataContext.getZipEntryAsString(serviceElement.attributeValue("path")));

          importServicePortletPreferences(portletDataContext, serviceDocument.getRootElement());
        }
      } catch (DocumentException de) {
        throw new SystemException(de);
      }
    }

    ZipReader zipReader = portletDataContext.getZipReader();

    zipReader.close();
  }
  @Override
  @SystemEvent(
      action = SystemEventConstants.ACTION_SKIP,
      send = false,
      type = SystemEventConstants.TYPE_DELETE)
  public void deleteThread(MBThread thread) throws PortalException, SystemException {

    MBMessage rootMessage = mbMessagePersistence.findByPrimaryKey(thread.getRootMessageId());

    // Indexer

    Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(MBMessage.class);

    indexer.delete(thread);

    // Attachments

    long folderId = thread.getAttachmentsFolderId();

    if (folderId != DLFolderConstants.DEFAULT_PARENT_FOLDER_ID) {
      PortletFileRepositoryUtil.deleteFolder(folderId);
    }

    // Subscriptions

    subscriptionLocalService.deleteSubscriptions(
        thread.getCompanyId(), MBThread.class.getName(), thread.getThreadId());

    // Thread flags

    mbThreadFlagPersistence.removeByThreadId(thread.getThreadId());

    // Messages

    List<MBMessage> messages = mbMessagePersistence.findByThreadId(thread.getThreadId());

    for (MBMessage message : messages) {

      // Ratings

      ratingsStatsLocalService.deleteStats(message.getWorkflowClassName(), message.getMessageId());

      // Asset

      assetEntryLocalService.deleteEntry(message.getWorkflowClassName(), message.getMessageId());

      // Resources

      if (!message.isDiscussion()) {
        resourceLocalService.deleteResource(
            message.getCompanyId(),
            message.getWorkflowClassName(),
            ResourceConstants.SCOPE_INDIVIDUAL,
            message.getMessageId());
      }

      // Message

      mbMessagePersistence.remove(message);

      // Statistics

      if (!message.isDiscussion()) {
        mbStatsUserLocalService.updateStatsUser(message.getGroupId(), message.getUserId());
      }

      // Workflow

      workflowInstanceLinkLocalService.deleteWorkflowInstanceLink(
          message.getCompanyId(), message.getGroupId(),
          message.getWorkflowClassName(), message.getMessageId());
    }

    // Category

    if ((rootMessage.getCategoryId() != MBCategoryConstants.DEFAULT_PARENT_CATEGORY_ID)
        && (rootMessage.getCategoryId() != MBCategoryConstants.DISCUSSION_CATEGORY_ID)) {

      try {
        MBCategory category = mbCategoryPersistence.findByPrimaryKey(thread.getCategoryId());

        MBUtil.updateCategoryStatistics(category.getCompanyId(), category.getCategoryId());
      } catch (NoSuchCategoryException nsce) {
        if (!thread.isInTrash()) {
          throw nsce;
        }
      }
    }

    // Thread Asset

    AssetEntry assetEntry =
        assetEntryLocalService.fetchEntry(MBThread.class.getName(), thread.getThreadId());

    if (assetEntry != null) {
      assetEntry.setTitle(rootMessage.getSubject());

      assetEntryLocalService.updateAssetEntry(assetEntry);
    }

    assetEntryLocalService.deleteEntry(MBThread.class.getName(), thread.getThreadId());

    // Trash

    trashEntryLocalService.deleteEntry(MBThread.class.getName(), thread.getThreadId());

    // Thread

    mbThreadPersistence.remove(thread);
  }