/**
   * Converts the soap model instance into a normal model instance.
   *
   * @param soapModel the soap model instance to convert
   * @return the normal model instance
   */
  public static MBMessage toModel(MBMessageSoap soapModel) {
    if (soapModel == null) {
      return null;
    }

    MBMessage model = new MBMessageImpl();

    model.setUuid(soapModel.getUuid());
    model.setMessageId(soapModel.getMessageId());
    model.setGroupId(soapModel.getGroupId());
    model.setCompanyId(soapModel.getCompanyId());
    model.setUserId(soapModel.getUserId());
    model.setUserName(soapModel.getUserName());
    model.setCreateDate(soapModel.getCreateDate());
    model.setModifiedDate(soapModel.getModifiedDate());
    model.setClassNameId(soapModel.getClassNameId());
    model.setClassPK(soapModel.getClassPK());
    model.setCategoryId(soapModel.getCategoryId());
    model.setThreadId(soapModel.getThreadId());
    model.setRootMessageId(soapModel.getRootMessageId());
    model.setParentMessageId(soapModel.getParentMessageId());
    model.setSubject(soapModel.getSubject());
    model.setBody(soapModel.getBody());
    model.setFormat(soapModel.getFormat());
    model.setAnonymous(soapModel.getAnonymous());
    model.setPriority(soapModel.getPriority());
    model.setAllowPingbacks(soapModel.getAllowPingbacks());
    model.setAnswer(soapModel.getAnswer());
    model.setStatus(soapModel.getStatus());
    model.setStatusByUserId(soapModel.getStatusByUserId());
    model.setStatusByUserName(soapModel.getStatusByUserName());
    model.setStatusDate(soapModel.getStatusDate());

    return model;
  }
  protected MBMessage addMBMessage() throws Exception {
    long pk = RandomTestUtil.nextLong();

    MBMessage mbMessage = _persistence.create(pk);

    mbMessage.setUuid(RandomTestUtil.randomString());

    mbMessage.setGroupId(RandomTestUtil.nextLong());

    mbMessage.setCompanyId(RandomTestUtil.nextLong());

    mbMessage.setUserId(RandomTestUtil.nextLong());

    mbMessage.setUserName(RandomTestUtil.randomString());

    mbMessage.setCreateDate(RandomTestUtil.nextDate());

    mbMessage.setModifiedDate(RandomTestUtil.nextDate());

    mbMessage.setClassNameId(RandomTestUtil.nextLong());

    mbMessage.setClassPK(RandomTestUtil.nextLong());

    mbMessage.setCategoryId(RandomTestUtil.nextLong());

    mbMessage.setThreadId(RandomTestUtil.nextLong());

    mbMessage.setRootMessageId(RandomTestUtil.nextLong());

    mbMessage.setParentMessageId(RandomTestUtil.nextLong());

    mbMessage.setSubject(RandomTestUtil.randomString());

    mbMessage.setBody(RandomTestUtil.randomString());

    mbMessage.setFormat(RandomTestUtil.randomString());

    mbMessage.setAnonymous(RandomTestUtil.randomBoolean());

    mbMessage.setPriority(RandomTestUtil.nextDouble());

    mbMessage.setAllowPingbacks(RandomTestUtil.randomBoolean());

    mbMessage.setAnswer(RandomTestUtil.randomBoolean());

    mbMessage.setStatus(RandomTestUtil.nextInt());

    mbMessage.setStatusByUserId(RandomTestUtil.nextLong());

    mbMessage.setStatusByUserName(RandomTestUtil.randomString());

    mbMessage.setStatusDate(RandomTestUtil.nextDate());

    _mbMessages.add(_persistence.update(mbMessage));

    return mbMessage;
  }
  @Override
  protected BaseModel<?> updateBaseModel(
      BaseModel<?> baseModel, String keywords, ServiceContext serviceContext) throws Exception {

    MBMessage message = (MBMessage) baseModel;

    message.setSubject(keywords);
    message.setBody(keywords);

    return MBTestUtil.updateMessage(message, keywords, keywords, true);
  }
  @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;
  }
  @Test
  public void testUpdateExisting() throws Exception {
    long pk = RandomTestUtil.nextLong();

    MBMessage newMBMessage = _persistence.create(pk);

    newMBMessage.setUuid(RandomTestUtil.randomString());

    newMBMessage.setGroupId(RandomTestUtil.nextLong());

    newMBMessage.setCompanyId(RandomTestUtil.nextLong());

    newMBMessage.setUserId(RandomTestUtil.nextLong());

    newMBMessage.setUserName(RandomTestUtil.randomString());

    newMBMessage.setCreateDate(RandomTestUtil.nextDate());

    newMBMessage.setModifiedDate(RandomTestUtil.nextDate());

    newMBMessage.setClassNameId(RandomTestUtil.nextLong());

    newMBMessage.setClassPK(RandomTestUtil.nextLong());

    newMBMessage.setCategoryId(RandomTestUtil.nextLong());

    newMBMessage.setThreadId(RandomTestUtil.nextLong());

    newMBMessage.setRootMessageId(RandomTestUtil.nextLong());

    newMBMessage.setParentMessageId(RandomTestUtil.nextLong());

    newMBMessage.setSubject(RandomTestUtil.randomString());

    newMBMessage.setBody(RandomTestUtil.randomString());

    newMBMessage.setFormat(RandomTestUtil.randomString());

    newMBMessage.setAnonymous(RandomTestUtil.randomBoolean());

    newMBMessage.setPriority(RandomTestUtil.nextDouble());

    newMBMessage.setAllowPingbacks(RandomTestUtil.randomBoolean());

    newMBMessage.setAnswer(RandomTestUtil.randomBoolean());

    newMBMessage.setStatus(RandomTestUtil.nextInt());

    newMBMessage.setStatusByUserId(RandomTestUtil.nextLong());

    newMBMessage.setStatusByUserName(RandomTestUtil.randomString());

    newMBMessage.setStatusDate(RandomTestUtil.nextDate());

    _mbMessages.add(_persistence.update(newMBMessage));

    MBMessage existingMBMessage = _persistence.findByPrimaryKey(newMBMessage.getPrimaryKey());

    Assert.assertEquals(existingMBMessage.getUuid(), newMBMessage.getUuid());
    Assert.assertEquals(existingMBMessage.getMessageId(), newMBMessage.getMessageId());
    Assert.assertEquals(existingMBMessage.getGroupId(), newMBMessage.getGroupId());
    Assert.assertEquals(existingMBMessage.getCompanyId(), newMBMessage.getCompanyId());
    Assert.assertEquals(existingMBMessage.getUserId(), newMBMessage.getUserId());
    Assert.assertEquals(existingMBMessage.getUserName(), newMBMessage.getUserName());
    Assert.assertEquals(
        Time.getShortTimestamp(existingMBMessage.getCreateDate()),
        Time.getShortTimestamp(newMBMessage.getCreateDate()));
    Assert.assertEquals(
        Time.getShortTimestamp(existingMBMessage.getModifiedDate()),
        Time.getShortTimestamp(newMBMessage.getModifiedDate()));
    Assert.assertEquals(existingMBMessage.getClassNameId(), newMBMessage.getClassNameId());
    Assert.assertEquals(existingMBMessage.getClassPK(), newMBMessage.getClassPK());
    Assert.assertEquals(existingMBMessage.getCategoryId(), newMBMessage.getCategoryId());
    Assert.assertEquals(existingMBMessage.getThreadId(), newMBMessage.getThreadId());
    Assert.assertEquals(existingMBMessage.getRootMessageId(), newMBMessage.getRootMessageId());
    Assert.assertEquals(existingMBMessage.getParentMessageId(), newMBMessage.getParentMessageId());
    Assert.assertEquals(existingMBMessage.getSubject(), newMBMessage.getSubject());
    Assert.assertEquals(existingMBMessage.getBody(), newMBMessage.getBody());
    Assert.assertEquals(existingMBMessage.getFormat(), newMBMessage.getFormat());
    Assert.assertEquals(existingMBMessage.getAnonymous(), newMBMessage.getAnonymous());
    AssertUtils.assertEquals(existingMBMessage.getPriority(), newMBMessage.getPriority());
    Assert.assertEquals(existingMBMessage.getAllowPingbacks(), newMBMessage.getAllowPingbacks());
    Assert.assertEquals(existingMBMessage.getAnswer(), newMBMessage.getAnswer());
    Assert.assertEquals(existingMBMessage.getStatus(), newMBMessage.getStatus());
    Assert.assertEquals(existingMBMessage.getStatusByUserId(), newMBMessage.getStatusByUserId());
    Assert.assertEquals(
        existingMBMessage.getStatusByUserName(), newMBMessage.getStatusByUserName());
    Assert.assertEquals(
        Time.getShortTimestamp(existingMBMessage.getStatusDate()),
        Time.getShortTimestamp(newMBMessage.getStatusDate()));
  }
  protected void addMBMessage(
      String uuid,
      long messageId,
      long groupId,
      long companyId,
      long userId,
      String userName,
      Date createDate,
      Date modifiedDate,
      long classNameId,
      long classPK,
      long categoryId,
      long threadId,
      long rootMessageId,
      long parentMessageId,
      String subject,
      String body,
      String format,
      boolean anonymous,
      double priority,
      boolean allowPingbacks,
      boolean answer,
      int status,
      long statusByUserId,
      String statusByUserName,
      Date statusDate,
      Map<Long, Long> mbMessageIds)
      throws PortalException, SystemException {

    if (parentMessageId == MBMessageConstants.DEFAULT_PARENT_MESSAGE_ID) {
      rootMessageId = messageId;
    } else {
      rootMessageId = importMBMessage(rootMessageId, threadId, classPK, mbMessageIds);

      parentMessageId = importMBMessage(parentMessageId, threadId, classPK, mbMessageIds);
    }

    MBMessage mbMessage = mbMessagePersistence.create(messageId);

    mbMessage.setUuid(uuid);
    mbMessage.setGroupId(groupId);
    mbMessage.setCompanyId(companyId);
    mbMessage.setUserId(userId);
    mbMessage.setUserName(userName);
    mbMessage.setCreateDate(createDate);
    mbMessage.setModifiedDate(modifiedDate);
    mbMessage.setClassNameId(classNameId);
    mbMessage.setClassPK(classPK);
    mbMessage.setCategoryId(categoryId);
    mbMessage.setThreadId(threadId);
    mbMessage.setRootMessageId(rootMessageId);
    mbMessage.setParentMessageId(parentMessageId);
    mbMessage.setSubject(subject);
    mbMessage.setBody(body);
    mbMessage.setFormat(format);
    mbMessage.setAnonymous(anonymous);
    mbMessage.setPriority(priority);
    mbMessage.setAllowPingbacks(allowPingbacks);
    mbMessage.setAnswer(answer);
    mbMessage.setStatus(status);
    mbMessage.setStatusByUserId(statusByUserId);
    mbMessage.setStatusByUserName(statusByUserName);
    mbMessage.setStatusDate(statusDate);

    mbMessagePersistence.update(mbMessage);
  }
  public AssetEntry updateEntry(
      long userId,
      long groupId,
      Date createDate,
      Date modifiedDate,
      String className,
      long classPK,
      String classUuid,
      long classTypeId,
      long[] categoryIds,
      String[] tagNames,
      boolean visible,
      Date startDate,
      Date endDate,
      Date expirationDate,
      String mimeType,
      String title,
      String description,
      String summary,
      String url,
      String layoutUuid,
      int height,
      int width,
      Integer priority,
      boolean sync)
      throws PortalException, SystemException {

    // Entry

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

    validate(groupId, className, categoryIds, tagNames);

    AssetEntry entry = assetEntryPersistence.fetchByC_C(classNameId, classPK);

    boolean oldVisible = false;

    if (entry != null) {
      oldVisible = entry.isVisible();
    }

    if (modifiedDate == null) {
      modifiedDate = new Date();
    }

    if (entry == null) {
      long entryId = counterLocalService.increment();

      entry = assetEntryPersistence.create(entryId);

      entry.setCompanyId(user.getCompanyId());
      entry.setUserId(user.getUserId());
      entry.setUserName(user.getFullName());

      if (createDate == null) {
        createDate = new Date();
      }

      entry.setCreateDate(createDate);

      entry.setModifiedDate(modifiedDate);
      entry.setClassNameId(classNameId);
      entry.setClassPK(classPK);
      entry.setClassUuid(classUuid);
      entry.setVisible(visible);
      entry.setExpirationDate(expirationDate);

      if (priority == null) {
        entry.setPriority(0);
      }

      entry.setViewCount(0);
    }

    entry.setGroupId(groupId);
    entry.setModifiedDate(modifiedDate);
    entry.setClassTypeId(classTypeId);
    entry.setVisible(visible);
    entry.setStartDate(startDate);
    entry.setEndDate(endDate);
    entry.setExpirationDate(expirationDate);
    entry.setMimeType(mimeType);
    entry.setTitle(title);
    entry.setDescription(description);
    entry.setSummary(summary);
    entry.setUrl(url);
    entry.setLayoutUuid(layoutUuid);
    entry.setHeight(height);
    entry.setWidth(width);

    if (priority != null) {
      entry.setPriority(priority.intValue());
    }

    // Categories

    if (categoryIds != null) {
      assetEntryPersistence.setAssetCategories(entry.getEntryId(), categoryIds);
    }

    // Tags

    if (tagNames != null) {
      long siteGroupId = PortalUtil.getSiteGroupId(groupId);

      List<AssetTag> tags = new ArrayList<AssetTag>(tagNames.length);

      for (String tagName : tagNames) {
        AssetTag tag = null;

        try {
          tag = assetTagLocalService.getTag(siteGroupId, tagName);
        } catch (NoSuchTagException nste) {
          ServiceContext serviceContext = new ServiceContext();

          serviceContext.setAddGroupPermissions(true);
          serviceContext.setAddGuestPermissions(true);
          serviceContext.setScopeGroupId(siteGroupId);

          tag =
              assetTagLocalService.addTag(
                  user.getUserId(),
                  tagName,
                  PropsValues.ASSET_TAG_PROPERTIES_DEFAULT,
                  serviceContext);
        }

        if (tag != null) {
          tags.add(tag);
        }
      }

      List<AssetTag> oldTags = assetEntryPersistence.getAssetTags(entry.getEntryId());

      assetEntryPersistence.setAssetTags(entry.getEntryId(), tags);

      if (entry.isVisible()) {
        boolean isNew = entry.isNew();

        assetEntryPersistence.updateImpl(entry);

        if (isNew) {
          for (AssetTag tag : tags) {
            assetTagLocalService.incrementAssetCount(tag.getTagId(), classNameId);
          }
        } else {
          for (AssetTag oldTag : oldTags) {
            if (!tags.contains(oldTag)) {
              assetTagLocalService.decrementAssetCount(oldTag.getTagId(), classNameId);
            }
          }

          for (AssetTag tag : tags) {
            if (!oldTags.contains(tag)) {
              assetTagLocalService.incrementAssetCount(tag.getTagId(), classNameId);
            }
          }
        }
      } else if (oldVisible) {
        for (AssetTag oldTag : oldTags) {
          assetTagLocalService.decrementAssetCount(oldTag.getTagId(), classNameId);
        }
      }
    }

    // Update entry after tags so that entry listeners have access to the
    // saved categories and tags

    assetEntryPersistence.update(entry);

    // Synchronize

    if (!sync) {
      return entry;
    }

    if (className.equals(BlogsEntry.class.getName())) {
      BlogsEntry blogsEntry = blogsEntryPersistence.findByPrimaryKey(classPK);

      blogsEntry.setTitle(title);

      blogsEntryPersistence.update(blogsEntry);
    } else if (className.equals(BookmarksEntry.class.getName())) {
      BookmarksEntry bookmarksEntry = bookmarksEntryPersistence.findByPrimaryKey(classPK);

      bookmarksEntry.setName(title);
      bookmarksEntry.setDescription(description);
      bookmarksEntry.setUrl(url);

      bookmarksEntryPersistence.update(bookmarksEntry);
    } else if (className.equals(DLFileEntry.class.getName())) {
      DLFileEntry dlFileEntry = dlFileEntryPersistence.findByPrimaryKey(classPK);

      dlFileEntry.setTitle(title);
      dlFileEntry.setDescription(description);

      dlFileEntryPersistence.update(dlFileEntry);
    } else if (className.equals(JournalArticle.class.getName())) {
      JournalArticle journalArticle = journalArticlePersistence.findByPrimaryKey(classPK);

      journalArticle.setTitle(title);
      journalArticle.setDescription(description);

      journalArticlePersistence.update(journalArticle);
    } else if (className.equals(MBMessage.class.getName())) {
      MBMessage mbMessage = mbMessagePersistence.findByPrimaryKey(classPK);

      mbMessage.setSubject(title);

      mbMessagePersistence.update(mbMessage);
    } else if (className.equals(WikiPage.class.getName())) {
      WikiPage wikiPage = wikiPagePersistence.findByPrimaryKey(classPK);

      wikiPage.setTitle(title);

      wikiPagePersistence.update(wikiPage);
    }

    return entry;
  }