@Indexable(type = IndexableType.REINDEX)
  @Override
  public Album moveAlbumToTrash(long userId, long albumId) throws PortalException {

    ServiceContext serviceContext = new ServiceContext();

    // Folder

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

    Album album = albumPersistence.findByPrimaryKey(albumId);

    int oldStatus = album.getStatus();

    album.setModifiedDate(serviceContext.getModifiedDate(now));
    album.setStatus(WorkflowConstants.STATUS_IN_TRASH);
    album.setStatusByUserId(user.getUserId());
    album.setStatusByUserName(user.getFullName());
    album.setStatusDate(serviceContext.getModifiedDate(now));

    albumPersistence.update(album);

    // Asset

    assetEntryLocalService.updateVisible(Album.class.getName(), album.getAlbumId(), false);

    // Trash

    TrashEntry trashEntry =
        trashEntryLocalService.addTrashEntry(
            userId,
            album.getGroupId(),
            Album.class.getName(),
            album.getAlbumId(),
            album.getUuid(),
            null,
            oldStatus,
            null,
            null);

    // Folders and entries

    List<Song> songs = songLocalService.getSongsByAlbumId(album.getAlbumId());

    moveDependentsToTrash(songs, trashEntry.getEntryId());

    return album;
  }
  @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);
  }
  public void updateFileEntryType(
      long userId,
      long fileEntryTypeId,
      String name,
      String description,
      long[] ddmStructureIds,
      ServiceContext serviceContext)
      throws PortalException, SystemException {

    DLFileEntryType dlFileEntryType = dlFileEntryTypePersistence.findByPrimaryKey(fileEntryTypeId);

    long ddmStructureId =
        updateDDMStructure(
            userId,
            dlFileEntryType.getUuid(),
            fileEntryTypeId,
            dlFileEntryType.getGroupId(),
            name,
            description,
            serviceContext);

    if (ddmStructureId > 0) {
      ddmStructureIds = ArrayUtil.append(ddmStructureIds, ddmStructureId);
    }

    validate(fileEntryTypeId, dlFileEntryType.getGroupId(), name, ddmStructureIds);

    dlFileEntryType.setModifiedDate(serviceContext.getModifiedDate(null));
    dlFileEntryType.setName(name);
    dlFileEntryType.setDescription(description);

    dlFileEntryTypePersistence.update(dlFileEntryType);

    dlFileEntryTypePersistence.setDDMStructures(fileEntryTypeId, ddmStructureIds);
  }
  @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 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;
  }
  @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;
  }
  @Indexable(type = IndexableType.REINDEX)
  public DefaultParameter saveDefaultParameter(
      long id,
      String applicationName,
      String title,
      String parameterName,
      String parameterValue,
      int changeable,
      ServiceContext serviceContext)
      throws PortalException, SystemException {

    validate(applicationName, title, parameterName, parameterValue);

    DefaultParameter defaultParameter = defaultParameterPersistence.findByPrimaryKey(id);

    defaultParameter.setModifiedDate(serviceContext.getModifiedDate(null));
    defaultParameter.setApplicationName(applicationName);
    defaultParameter.setTitle(title);
    defaultParameter.setParameterName(parameterName);
    defaultParameter.setParameterValue(parameterValue);
    defaultParameter.setChangeable(changeable);

    defaultParameterPersistence.update(defaultParameter);

    return getDefaultParameter(defaultParameter.getDefaultParameterId());
  }
  public Books updateStatus(
      long userId, long resourcePrimKey, int status, ServiceContext serviceContext)
      throws PortalException, SystemException {

    User user = userLocalService.getUser(userId);
    Books book = getBooks(resourcePrimKey);

    book.setStatus(status);
    book.setStatusByUserId(userId);
    book.setStatusByUserName(user.getFullName());
    book.setStatusDate(serviceContext.getModifiedDate());

    booksPersistence.update(book, false);

    if (status == WorkflowConstants.STATUS_APPROVED) {
      assetEntryLocalService.updateVisible(Books.class.getName(), resourcePrimKey, true);
    } else {
      assetEntryLocalService.updateVisible(Books.class.getName(), resourcePrimKey, false);
    }

    // Indexer
    Indexer indexer = IndexerRegistryUtil.getIndexer(Books.class);
    indexer.reindex(book);
    return book;
  }
  @Override
  public CalendarResource updateCalendarResource(
      long calendarResourceId,
      Map<Locale, String> nameMap,
      Map<Locale, String> descriptionMap,
      boolean active,
      ServiceContext serviceContext)
      throws PortalException {

    // Calendar resource

    validate(nameMap);

    CalendarResource calendarResource =
        calendarResourcePersistence.findByPrimaryKey(calendarResourceId);

    calendarResource.setModifiedDate(serviceContext.getModifiedDate(null));
    calendarResource.setNameMap(nameMap);
    calendarResource.setDescriptionMap(descriptionMap);
    calendarResource.setActive(active);

    calendarResourcePersistence.update(calendarResource);

    // Asset

    updateAsset(
        calendarResource.getUserId(),
        calendarResource,
        serviceContext.getAssetCategoryIds(),
        serviceContext.getAssetTagNames());

    return calendarResource;
  }
  @Before
  public void setUp() throws Exception {
    ServiceTestUtil.setUser(TestPropsValues.getUser());

    ServiceContext serviceContext = ServiceContextTestUtil.getServiceContext();

    _repository =
        RepositoryLocalServiceUtil.addRepository(
            TestPropsValues.getUserId(),
            TestPropsValues.getGroupId(),
            ClassNameLocalServiceUtil.getClassNameId(_REPOSITORY_CLASS_NAME),
            DLFolderConstants.DEFAULT_PARENT_FOLDER_ID,
            StringUtil.randomString(),
            StringUtil.randomString(),
            StringUtil.randomString(),
            new UnicodeProperties(),
            true,
            serviceContext);

    _repositoryEntry =
        RepositoryEntryLocalServiceUtil.createRepositoryEntry(_repository.getDlFolderId());

    _repositoryEntry.setUuid(serviceContext.getUuid());
    _repositoryEntry.setGroupId(serviceContext.getScopeGroupId());
    _repositoryEntry.setCompanyId(serviceContext.getCompanyId());
    _repositoryEntry.setUserId(serviceContext.getUserId());
    _repositoryEntry.setUserName(StringUtil.randomString());
    _repositoryEntry.setCreateDate(serviceContext.getCreateDate(null));
    _repositoryEntry.setModifiedDate(serviceContext.getModifiedDate(null));
    _repositoryEntry.setRepositoryId(_repository.getRepositoryId());
    _repositoryEntry.setMappedId(_MAPPED_ID);

    RepositoryEntryLocalServiceUtil.addRepositoryEntry(_repositoryEntry);
  }
  public JournalFeed updateFeed(
      long groupId,
      String feedId,
      String name,
      String description,
      String type,
      String structureId,
      String templateId,
      String rendererTemplateId,
      int delta,
      String orderByCol,
      String orderByType,
      String targetLayoutFriendlyUrl,
      String targetPortletId,
      String contentField,
      String feedType,
      double feedVersion,
      ServiceContext serviceContext)
      throws PortalException, SystemException {

    // Feed

    JournalFeed feed = journalFeedPersistence.findByG_F(groupId, feedId);

    validate(
        feed.getCompanyId(), groupId, name, structureId, targetLayoutFriendlyUrl, contentField);

    feed.setModifiedDate(serviceContext.getModifiedDate(null));
    feed.setName(name);
    feed.setDescription(description);
    feed.setType(type);
    feed.setStructureId(structureId);
    feed.setTemplateId(templateId);
    feed.setRendererTemplateId(rendererTemplateId);
    feed.setDelta(delta);
    feed.setOrderByCol(orderByCol);
    feed.setOrderByType(orderByType);
    feed.setTargetLayoutFriendlyUrl(targetLayoutFriendlyUrl);
    feed.setTargetPortletId(targetPortletId);
    feed.setContentField(contentField);

    if (Validator.isNull(feedType)) {
      feed.setFeedType(RSSUtil.TYPE_DEFAULT);
      feed.setFeedVersion(RSSUtil.VERSION_DEFAULT);
    } else {
      feed.setFeedType(feedType);
      feed.setFeedVersion(feedVersion);
    }

    journalFeedPersistence.update(feed, false);

    // Expando

    ExpandoBridge expandoBridge = feed.getExpandoBridge();

    expandoBridge.setAttributes(serviceContext);

    return feed;
  }
  @Override
  public KBComment addKBComment(
      long userId,
      long classNameId,
      long classPK,
      String content,
      boolean helpful,
      ServiceContext serviceContext)
      throws PortalException {

    // KB comment

    User user = userPersistence.findByPrimaryKey(userId);
    long groupId = serviceContext.getScopeGroupId();
    Date now = new Date();

    validate(content);

    long kbCommentId = counterLocalService.increment();

    KBComment kbComment = kbCommentPersistence.create(kbCommentId);

    kbComment.setUuid(serviceContext.getUuid());
    kbComment.setGroupId(groupId);
    kbComment.setCompanyId(user.getCompanyId());
    kbComment.setUserId(user.getUserId());
    kbComment.setUserName(user.getFullName());
    kbComment.setCreateDate(serviceContext.getCreateDate(now));
    kbComment.setModifiedDate(serviceContext.getModifiedDate(now));
    kbComment.setClassNameId(classNameId);
    kbComment.setClassPK(classPK);
    kbComment.setContent(content);
    kbComment.setHelpful(helpful);
    kbComment.setStatus(KBCommentConstants.STATUS_NEW);

    kbCommentPersistence.update(kbComment);

    // Social

    JSONObject extraDataJSONObject = JSONFactoryUtil.createJSONObject();

    putTitle(extraDataJSONObject, kbComment);

    socialActivityLocalService.addActivity(
        userId,
        kbComment.getGroupId(),
        KBComment.class.getName(),
        kbCommentId,
        AdminActivityKeys.ADD_KB_COMMENT,
        extraDataJSONObject.toString(),
        0);

    // Subscriptions

    notifySubscribers(kbComment, serviceContext);

    return kbComment;
  }
  public CalendarBooking updateStatus(
      long userId, long calendarBookingId, int status, ServiceContext serviceContext)
      throws PortalException, SystemException {

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

    CalendarBooking calendarBooking =
        calendarBookingPersistence.findByPrimaryKey(calendarBookingId);

    calendarBooking.setModifiedDate(serviceContext.getModifiedDate(now));
    calendarBooking.setStatus(status);
    calendarBooking.setStatusByUserId(user.getUserId());
    calendarBooking.setStatusByUserName(user.getFullName());
    calendarBooking.setStatusDate(serviceContext.getModifiedDate(now));

    calendarBookingPersistence.update(calendarBooking, false);

    return calendarBooking;
  }
  public PollsVote addVote(
      long userId, long questionId, long choiceId, ServiceContext serviceContext)
      throws PortalException, SystemException {

    // Choice

    Date now = new Date();

    PollsChoice choice = pollsChoicePersistence.findByPrimaryKey(choiceId);

    if (choice.getQuestionId() != questionId) {
      throw new NoSuchQuestionException();
    }

    // Question

    PollsQuestion question = pollsQuestionPersistence.findByPrimaryKey(questionId);

    if (question.isExpired(serviceContext, now)) {
      throw new QuestionExpiredException();
    }

    question.setLastVoteDate(serviceContext.getCreateDate(now));

    pollsQuestionPersistence.update(question, false);

    // Vote

    PollsVote vote = pollsVotePersistence.fetchByQ_U(questionId, userId);

    if (vote != null) {
      throw new DuplicateVoteException();
    } else {
      User user = userPersistence.findByPrimaryKey(userId);

      long voteId = counterLocalService.increment();

      vote = pollsVotePersistence.create(voteId);

      vote.setCompanyId(user.getCompanyId());
      vote.setUserId(user.getUserId());
      vote.setUserName(user.getFullName());
      vote.setCreateDate(serviceContext.getCreateDate(now));
      vote.setModifiedDate(serviceContext.getModifiedDate(now));
      vote.setQuestionId(questionId);
      vote.setChoiceId(choiceId);
      vote.setVoteDate(serviceContext.getCreateDate(now));

      pollsVotePersistence.update(vote, false);
    }

    return vote;
  }
  @Indexable(type = IndexableType.REINDEX)
  @Override
  public Album restoreAlbumFromTrash(long userId, long albumId) throws PortalException {

    ServiceContext serviceContext = new ServiceContext();

    // Folder

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

    Album album = albumPersistence.findByPrimaryKey(albumId);

    TrashEntry trashEntry = trashEntryLocalService.getEntry(Album.class.getName(), albumId);

    album.setModifiedDate(serviceContext.getModifiedDate(now));
    album.setStatus(trashEntry.getStatus());
    album.setStatusByUserId(user.getUserId());
    album.setStatusByUserName(user.getFullName());
    album.setStatusDate(serviceContext.getModifiedDate(now));

    albumPersistence.update(album);

    assetEntryLocalService.updateVisible(Album.class.getName(), album.getAlbumId(), true);

    // Songs

    List<Song> songs =
        songLocalService.getSongsByAlbumId(
            album.getGroupId(), album.getAlbumId(), WorkflowConstants.STATUS_IN_TRASH);

    restoreDependentsFromTrash(songs, trashEntry.getEntryId());

    // Trash

    trashEntryLocalService.deleteEntry(trashEntry.getEntryId());

    return album;
  }
  @Override
  public BackgroundTask addBackgroundTask(
      long userId,
      long groupId,
      String name,
      String[] servletContextNames,
      Class<?> taskExecutorClass,
      Map<String, Serializable> taskContextMap,
      ServiceContext serviceContext)
      throws PortalException, SystemException {

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

    final long backgroundTaskId = counterLocalService.increment();

    BackgroundTask backgroundTask = backgroundTaskPersistence.create(backgroundTaskId);

    backgroundTask.setCompanyId(user.getCompanyId());
    backgroundTask.setCreateDate(serviceContext.getCreateDate(now));
    backgroundTask.setGroupId(groupId);
    backgroundTask.setModifiedDate(serviceContext.getModifiedDate(now));
    backgroundTask.setUserId(userId);
    backgroundTask.setUserName(user.getFullName());
    backgroundTask.setName(name);
    backgroundTask.setServletContextNames(StringUtil.merge(servletContextNames));
    backgroundTask.setTaskExecutorClassName(taskExecutorClass.getName());

    if (taskContextMap != null) {
      String taskContext = JSONFactoryUtil.serialize(taskContextMap);

      backgroundTask.setTaskContext(taskContext);
    }

    backgroundTask.setStatus(BackgroundTaskConstants.STATUS_NEW);

    backgroundTaskPersistence.update(backgroundTask);

    TransactionCommitCallbackRegistryUtil.registerCallback(
        new Callable<Void>() {

          @Override
          public Void call() throws Exception {
            backgroundTaskLocalService.triggerBackgroundTask(backgroundTaskId);

            return null;
          }
        });

    return backgroundTask;
  }
  @Override
  public KBTemplate addKBTemplate(
      long userId, String title, String content, ServiceContext serviceContext)
      throws PortalException {

    // KB template

    User user = userPersistence.findByPrimaryKey(userId);
    long groupId = serviceContext.getScopeGroupId();
    Date now = new Date();

    validate(title, content);

    long kbTemplateId = counterLocalService.increment();

    KBTemplate kbTemplate = kbTemplatePersistence.create(kbTemplateId);

    kbTemplate.setUuid(serviceContext.getUuid());
    kbTemplate.setGroupId(groupId);
    kbTemplate.setCompanyId(user.getCompanyId());
    kbTemplate.setUserId(user.getUserId());
    kbTemplate.setUserName(user.getFullName());
    kbTemplate.setCreateDate(serviceContext.getCreateDate(now));
    kbTemplate.setModifiedDate(serviceContext.getModifiedDate(now));
    kbTemplate.setTitle(title);
    kbTemplate.setContent(content);

    kbTemplatePersistence.update(kbTemplate);

    // Resources

    resourceLocalService.addModelResources(kbTemplate, serviceContext);

    // Social

    JSONObject extraDataJSONObject = JSONFactoryUtil.createJSONObject();

    extraDataJSONObject.put("title", kbTemplate.getTitle());

    socialActivityLocalService.addActivity(
        userId,
        groupId,
        KBTemplate.class.getName(),
        kbTemplateId,
        AdminActivityKeys.ADD_KB_TEMPLATE,
        extraDataJSONObject.toString(),
        0);

    return kbTemplate;
  }
  public static void updateAttachments(KBArticle kbArticle) {
    try {
      long folderId = kbArticle.getClassPK();

      String oldDirName = "knowledgebase/articles/" + folderId;
      String newDirName = "knowledgebase/kbarticles/" + folderId;

      DLLocalServiceUtil.addDirectory(
          kbArticle.getCompanyId(), CompanyConstants.SYSTEM, newDirName);

      String[] fileNames =
          DLLocalServiceUtil.getFileNames(
              kbArticle.getCompanyId(), CompanyConstants.SYSTEM, oldDirName);

      ServiceContext serviceContext = new ServiceContext();

      serviceContext.setCompanyId(kbArticle.getCompanyId());
      serviceContext.setScopeGroupId(kbArticle.getGroupId());

      for (String fileName : fileNames) {
        String shortFileName = FileUtil.getShortFileName(fileName);
        byte[] bytes =
            DLLocalServiceUtil.getFile(kbArticle.getCompanyId(), CompanyConstants.SYSTEM, fileName);

        DLLocalServiceUtil.addFile(
            kbArticle.getCompanyId(),
            CompanyConstants.SYSTEM_STRING,
            GroupConstants.DEFAULT_PARENT_GROUP_ID,
            CompanyConstants.SYSTEM,
            newDirName + StringPool.SLASH + shortFileName,
            0,
            StringPool.BLANK,
            serviceContext.getModifiedDate(null),
            serviceContext,
            bytes);
      }

      DLLocalServiceUtil.deleteDirectory(
          kbArticle.getCompanyId(),
          CompanyConstants.SYSTEM_STRING,
          CompanyConstants.SYSTEM,
          oldDirName);

      if (_log.isInfoEnabled()) {
        _log.info("Added attachments for " + folderId);
      }
    } catch (Exception e) {
      _log.error(e.getMessage());
    }
  }
  public MDRRuleGroup updateRuleGroup(
      long ruleGroupId,
      Map<Locale, String> nameMap,
      Map<Locale, String> descriptionMap,
      ServiceContext serviceContext)
      throws PortalException, SystemException {

    MDRRuleGroup ruleGroup = mdrRuleGroupPersistence.findByPrimaryKey(ruleGroupId);

    ruleGroup.setModifiedDate(serviceContext.getModifiedDate(null));
    ruleGroup.setNameMap(nameMap);
    ruleGroup.setDescriptionMap(descriptionMap);

    mdrRuleGroupPersistence.update(ruleGroup, false);

    return ruleGroup;
  }
  @Override
  public KBComment updateKBComment(
      long kbCommentId,
      long classNameId,
      long classPK,
      String content,
      boolean helpful,
      int status,
      ServiceContext serviceContext)
      throws PortalException {

    // KB comment

    validate(content);

    KBComment kbComment = kbCommentPersistence.findByPrimaryKey(kbCommentId);

    kbComment.setModifiedDate(serviceContext.getModifiedDate(null));
    kbComment.setClassNameId(classNameId);
    kbComment.setClassPK(classPK);
    kbComment.setContent(content);
    kbComment.setHelpful(helpful);
    kbComment.setStatus(status);

    kbCommentPersistence.update(kbComment);

    // Social

    JSONObject extraDataJSONObject = JSONFactoryUtil.createJSONObject();

    putTitle(extraDataJSONObject, kbComment);

    socialActivityLocalService.addActivity(
        kbComment.getUserId(),
        kbComment.getGroupId(),
        KBComment.class.getName(),
        kbCommentId,
        AdminActivityKeys.UPDATE_KB_COMMENT,
        extraDataJSONObject.toString(),
        0);

    return kbComment;
  }
  @Override
  public KBTemplate updateKBTemplate(
      long kbTemplateId, String title, String content, ServiceContext serviceContext)
      throws PortalException {

    // KB template

    validate(title, content);

    KBTemplate kbTemplate = kbTemplatePersistence.findByPrimaryKey(kbTemplateId);

    kbTemplate.setModifiedDate(serviceContext.getModifiedDate(null));
    kbTemplate.setTitle(title);
    kbTemplate.setContent(content);

    kbTemplatePersistence.update(kbTemplate);

    // Resources

    if ((serviceContext.getGroupPermissions() != null)
        || (serviceContext.getGuestPermissions() != null)) {

      updateKBTemplateResources(
          kbTemplate, serviceContext.getGroupPermissions(), serviceContext.getGuestPermissions());
    }

    // Social

    JSONObject extraDataJSONObject = JSONFactoryUtil.createJSONObject();

    extraDataJSONObject.put("title", kbTemplate.getTitle());

    socialActivityLocalService.addActivity(
        kbTemplate.getUserId(),
        kbTemplate.getGroupId(),
        KBTemplate.class.getName(),
        kbTemplateId,
        AdminActivityKeys.UPDATE_KB_TEMPLATE,
        extraDataJSONObject.toString(),
        0);

    return kbTemplate;
  }
  public void addFoo(
      String field1,
      boolean field2,
      int field3,
      Date field4,
      String field5,
      ServiceContext serviceContext)
      throws PortalException, SystemException {

    // Foo

    User user = userLocalService.getUserById(serviceContext.getUserId());
    long groupId = serviceContext.getScopeGroupId();
    Date now = new Date();

    long fooId = counterLocalService.increment();

    Foo foo = fooPersistence.create(fooId);

    foo.setGroupId(groupId);
    foo.setCompanyId(user.getCompanyId());
    foo.setUserId(user.getUserId());
    foo.setUserName(user.getFullName());
    foo.setCreateDate(serviceContext.getCreateDate(now));
    foo.setModifiedDate(serviceContext.getModifiedDate(now));
    foo.setField1(field1);
    foo.setField2(field2);
    foo.setField3(field3);
    foo.setField4(field4);
    foo.setField5(field5);
    foo.setExpandoBridgeAttributes(serviceContext);

    fooPersistence.update(foo, false);

    // Asset

    updateAsset(
        user.getUserId(),
        foo,
        serviceContext.getAssetCategoryIds(),
        serviceContext.getAssetTagNames());
  }
  @Override
  public BackgroundTask amendBackgroundTask(
      long backgroundTaskId,
      Map<String, Serializable> taskContextMap,
      int status,
      String statusMessage,
      ServiceContext serviceContext)
      throws SystemException {

    Date now = new Date();

    BackgroundTask backgroundTask = backgroundTaskPersistence.fetchByPrimaryKey(backgroundTaskId);

    if (backgroundTask == null) {
      return null;
    }

    backgroundTask.setModifiedDate(serviceContext.getModifiedDate(now));

    if (taskContextMap != null) {
      String taskContext = JSONFactoryUtil.serialize(taskContextMap);

      backgroundTask.setTaskContext(taskContext);
    }

    if ((status == BackgroundTaskConstants.STATUS_FAILED)
        || (status == BackgroundTaskConstants.STATUS_SUCCESSFUL)) {

      backgroundTask.setCompleted(true);
      backgroundTask.setCompletionDate(now);
    }

    backgroundTask.setStatus(status);

    if (Validator.isNotNull(statusMessage)) {
      backgroundTask.setStatusMessage(statusMessage);
    }

    backgroundTaskPersistence.update(backgroundTask);

    return backgroundTask;
  }
  @Indexable(type = IndexableType.REINDEX)
  public DLFolder moveFolder(
      long userId, long folderId, long parentFolderId, ServiceContext serviceContext)
      throws PortalException, SystemException {

    boolean hasLock = hasFolderLock(userId, folderId);

    Lock lock = null;

    if (!hasLock) {

      // Lock

      lock = lockFolder(userId, folderId);
    }

    try {
      DLFolder dlFolder = dlFolderPersistence.findByPrimaryKey(folderId);

      parentFolderId = getParentFolderId(dlFolder, parentFolderId);

      validateFolder(
          dlFolder.getFolderId(), dlFolder.getGroupId(), parentFolderId, dlFolder.getName());

      dlFolder.setModifiedDate(serviceContext.getModifiedDate(null));
      dlFolder.setParentFolderId(parentFolderId);
      dlFolder.setExpandoBridgeAttributes(serviceContext);

      dlFolderPersistence.update(dlFolder);

      dlAppHelperLocalService.moveFolder(new LiferayFolder(dlFolder));

      return dlFolder;
    } finally {
      if (!hasLock) {

        // Unlock

        unlockFolder(folderId, lock.getUuid());
      }
    }
  }
  @Override
  public LayoutPrototype updateLayoutPrototype(
      long layoutPrototypeId,
      Map<Locale, String> nameMap,
      String description,
      boolean active,
      ServiceContext serviceContext)
      throws PortalException, SystemException {

    // Layout prototype

    LayoutPrototype layoutPrototype =
        layoutPrototypePersistence.findByPrimaryKey(layoutPrototypeId);

    layoutPrototype.setModifiedDate(serviceContext.getModifiedDate(new Date()));
    layoutPrototype.setNameMap(nameMap);
    layoutPrototype.setDescription(description);
    layoutPrototype.setActive(active);

    layoutPrototypePersistence.update(layoutPrototype);

    // Group

    Group group =
        groupLocalService.getLayoutPrototypeGroup(
            layoutPrototype.getCompanyId(), layoutPrototypeId);

    group.setName(layoutPrototype.getName(LocaleUtil.getDefault()));

    groupPersistence.update(group);

    // Layout

    Layout layout = layoutPrototype.getLayout();

    layout.setModifiedDate(layoutPrototype.getModifiedDate());
    layout.setNameMap(nameMap);

    layoutPersistence.update(layout);

    return layoutPrototype;
  }
  /**
   * Cập nhật thông tin bước trong quy trình mới
   *
   * <p>Version: OEP 2.0
   *
   * <p>History: DATE AUTHOR DESCRIPTION -------------------------------------------------
   * 21-September-2015 trungdk Tạo mới
   *
   * @param id mã bước cần cập nhật thông tin
   * @param dossierProcessId mã quy trình xử lý thủ tục hành chính
   * @param title tiêu đề bước xử lý
   * @param sequenceNo số thứ tự bước xử lý
   * @param daysDuration số ngày cần thiết để xử lý quy trình
   * @param doForm Form xử lý riêng cho quy trình
   * @param formLabel Tên hiển thị nút xử lý hồ sơ
   * @param rollback cờ đánh dấu cho việc roolback trong quy trình
   * @return: bước trong quy trình mới được cập nhật
   */
  @Indexable(type = IndexableType.REINDEX)
  public DossierStep updateDossierStep(
      long id,
      long dossierProcessId,
      String title,
      int sequenceNo,
      int daysDuration,
      String doForm,
      String formLabel,
      int rollback,
      ServiceContext serviceContext)
      throws PortalException, SystemException {

    validate(dossierProcessId, title, sequenceNo);

    DossierStep dossierStep = dossierStepPersistence.findByPrimaryKey(id);

    dossierStep.setModifiedDate(serviceContext.getModifiedDate(null));
    dossierStep.setDossierProcessId(dossierProcessId);
    dossierStep.setTitle(title);
    dossierStep.setSequenceNo(sequenceNo);
    dossierStep.setDaysDuration(daysDuration);
    dossierStep.setDoForm(doForm);
    dossierStep.setFormLabel(formLabel);
    dossierStep.setRollback(rollback);

    dossierStepPersistence.update(dossierStep);

    if ((serviceContext.getGroupPermissions() != null)
        || (serviceContext.getGuestPermissions() != null)) {

      updateDossierStepResources(
          dossierStep,
          serviceContext.getGroupPermissions(),
          serviceContext.getGuestPermissions(),
          serviceContext);
    }

    return getDossierStep(dossierStep.getDossierStepId());
  }
  public JournalStructure updateStructure(
      long groupId,
      String structureId,
      String parentStructureId,
      String name,
      String description,
      String xsd,
      ServiceContext serviceContext)
      throws PortalException, SystemException {

    structureId = structureId.trim().toUpperCase();

    try {
      xsd = JournalUtil.formatXML(xsd);
    } catch (Exception e) {
      throw new StructureXsdException();
    }

    validateParentStructureId(groupId, structureId, parentStructureId);
    validate(name, description, xsd);

    JournalStructure structure = journalStructurePersistence.findByG_S(groupId, structureId);

    structure.setModifiedDate(serviceContext.getModifiedDate(null));
    structure.setParentStructureId(parentStructureId);
    structure.setName(name);
    structure.setDescription(description);
    structure.setXsd(xsd);

    journalStructurePersistence.update(structure, false);

    // Expando

    ExpandoBridge expandoBridge = structure.getExpandoBridge();

    expandoBridge.setAttributes(serviceContext);

    return structure;
  }
  @Override
  public PollsChoice updateChoice(
      long choiceId,
      long questionId,
      String name,
      String description,
      ServiceContext serviceContext)
      throws PortalException {

    validate(name, description);

    pollsQuestionPersistence.findByPrimaryKey(questionId);

    PollsChoice choice = pollsChoicePersistence.findByPrimaryKey(choiceId);

    choice.setModifiedDate(serviceContext.getModifiedDate(null));
    choice.setQuestionId(questionId);
    choice.setName(name);
    choice.setDescription(description);

    pollsChoicePersistence.update(choice);

    return choice;
  }
  @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;
  }
  @Override
  public MBThread addThread(long categoryId, MBMessage message, ServiceContext serviceContext)
      throws PortalException, SystemException {

    // Thread

    Date now = new Date();

    long threadId = message.getThreadId();

    if (!message.isRoot() || (threadId <= 0)) {
      threadId = counterLocalService.increment();
    }

    MBThread thread = mbThreadPersistence.create(threadId);

    thread.setUuid(serviceContext.getUuid());
    thread.setGroupId(message.getGroupId());
    thread.setCompanyId(message.getCompanyId());
    thread.setUserId(message.getUserId());
    thread.setUserName(message.getUserName());
    thread.setCreateDate(serviceContext.getCreateDate(now));
    thread.setModifiedDate(serviceContext.getModifiedDate(now));
    thread.setCategoryId(categoryId);
    thread.setRootMessageId(message.getMessageId());
    thread.setRootMessageUserId(message.getUserId());

    if (message.isAnonymous()) {
      thread.setLastPostByUserId(0);
    } else {
      thread.setLastPostByUserId(message.getUserId());
    }

    thread.setLastPostDate(message.getCreateDate());

    if (message.getPriority() != MBThreadConstants.PRIORITY_NOT_GIVEN) {
      thread.setPriority(message.getPriority());
    }

    thread.setStatus(message.getStatus());
    thread.setStatusByUserId(message.getStatusByUserId());
    thread.setStatusByUserName(message.getStatusByUserName());
    thread.setStatusDate(message.getStatusDate());

    mbThreadPersistence.update(thread);

    // Asset

    if (categoryId >= 0) {
      assetEntryLocalService.updateEntry(
          message.getUserId(),
          message.getGroupId(),
          thread.getStatusDate(),
          thread.getLastPostDate(),
          MBThread.class.getName(),
          thread.getThreadId(),
          thread.getUuid(),
          0,
          new long[0],
          new String[0],
          false,
          null,
          null,
          null,
          null,
          String.valueOf(thread.getRootMessageId()),
          null,
          null,
          null,
          null,
          0,
          0,
          null,
          false);
    }

    return thread;
  }