public void restoreFileEntryFromTrash(long userId, FileEntry fileEntry)
      throws PortalException, SystemException {

    // File entry

    DLFileEntry dlFileEntry = (DLFileEntry) fileEntry.getModel();

    dlFileEntry.setTitle(DLAppUtil.stripTrashNamespace(dlFileEntry.getTitle()));

    dlFileEntryPersistence.update(dlFileEntry, false);

    FileVersion fileVersion = new LiferayFileVersion(dlFileEntry.getLatestFileVersion(true));

    TrashEntry trashEntry =
        trashEntryLocalService.getEntry(
            DLFileEntryConstants.getClassName(), fileEntry.getFileEntryId());

    // File version

    Map<String, Serializable> workflowContext = new HashMap<String, Serializable>();

    List<TrashVersion> trashVersions = trashEntryLocalService.getVersions(trashEntry.getEntryId());

    workflowContext.put("trashVersions", (Serializable) trashVersions);

    dlFileEntryLocalService.updateStatus(
        userId,
        fileVersion.getFileVersionId(),
        trashEntry.getStatus(),
        workflowContext,
        new ServiceContext());

    // File shortcut

    dlFileShortcutLocalService.enableFileShortcuts(fileEntry.getFileEntryId());

    // File rank

    dlFileRankLocalService.enableFileRanks(fileEntry.getFileEntryId());

    // Social

    socialActivityCounterLocalService.enableActivityCounters(
        DLFileEntryConstants.getClassName(), fileEntry.getFileEntryId());

    socialActivityLocalService.addActivity(
        userId,
        fileEntry.getGroupId(),
        DLFileEntryConstants.getClassName(),
        fileEntry.getFileEntryId(),
        SocialActivityConstants.TYPE_RESTORE_FROM_TRASH,
        StringPool.BLANK,
        0);

    // Trash

    trashEntryLocalService.deleteEntry(trashEntry.getClassName(), trashEntry.getClassPK());
  }
  public void deleteFileEntry(FileEntry fileEntry) throws PortalException, SystemException {

    // Subscriptions

    subscriptionLocalService.deleteSubscriptions(
        fileEntry.getCompanyId(), DLFileEntryConstants.getClassName(), fileEntry.getFileEntryId());

    // File previews

    DLProcessorRegistryUtil.cleanUp(fileEntry);

    // File ranks

    dlFileRankLocalService.deleteFileRanksByFileEntryId(fileEntry.getFileEntryId());

    // File shortcuts

    dlFileShortcutLocalService.deleteFileShortcuts(fileEntry.getFileEntryId());

    // Sync

    if (!isStagingGroup(fileEntry.getGroupId())) {
      dlSyncLocalService.updateSync(
          fileEntry.getFileEntryId(),
          fileEntry.getFolderId(),
          fileEntry.getTitle(),
          fileEntry.getDescription(),
          DLSyncConstants.EVENT_DELETE,
          fileEntry.getVersion());
    }

    // Asset

    assetEntryLocalService.deleteEntry(
        DLFileEntryConstants.getClassName(), fileEntry.getFileEntryId());

    // Message boards

    mbMessageLocalService.deleteDiscussionMessages(
        DLFileEntryConstants.getClassName(), fileEntry.getFileEntryId());

    // Ratings

    ratingsStatsLocalService.deleteStats(
        DLFileEntryConstants.getClassName(), fileEntry.getFileEntryId());

    // Trash

    if (fileEntry.getModel() instanceof DLFileEntry) {
      trashEntryLocalService.deleteEntry(
          DLFileEntryConstants.getClassName(), fileEntry.getFileEntryId());
    }
  }
  public void getFileAsStream(long userId, FileEntry fileEntry, boolean incrementCounter)
      throws SystemException {

    if (!incrementCounter) {
      return;
    }

    // File rank

    if (userId > 0) {
      dlFileRankLocalService.updateFileRank(
          fileEntry.getGroupId(),
          fileEntry.getCompanyId(),
          userId,
          fileEntry.getFileEntryId(),
          new ServiceContext());
    }

    // File read count

    assetEntryLocalService.incrementViewCounter(
        userId, DLFileEntryConstants.getClassName(), fileEntry.getFileEntryId(), 1);

    List<DLFileShortcut> fileShortcuts =
        dlFileShortcutPersistence.findByToFileEntryId(fileEntry.getFileEntryId());

    for (DLFileShortcut fileShortcut : fileShortcuts) {
      assetEntryLocalService.incrementViewCounter(
          userId, DLFileShortcut.class.getName(), fileShortcut.getFileShortcutId(), 1);
    }
  }
  public void cancelCheckOut(
      long userId,
      FileEntry fileEntry,
      FileVersion sourceFileVersion,
      FileVersion destinationFileVersion,
      FileVersion draftFileVersion,
      ServiceContext serviceContext)
      throws PortalException, SystemException {

    updateFileEntry(userId, fileEntry, sourceFileVersion, destinationFileVersion, serviceContext);

    if (draftFileVersion == null) {
      return;
    }

    AssetEntry draftAssetEntry = null;

    try {
      draftAssetEntry =
          assetEntryLocalService.getEntry(
              DLFileEntryConstants.getClassName(), draftFileVersion.getPrimaryKey());

      assetEntryLocalService.deleteEntry(draftAssetEntry.getEntryId());
    } catch (NoSuchEntryException nsee) {
    }
  }
  @Test
  public void testUpdateAssetWhenUpdatingFileEntry() throws Throwable {
    ServiceContext serviceContext = ServiceContextTestUtil.getServiceContext(_group.getGroupId());

    FileEntry fileEntry =
        DLAppLocalServiceUtil.addFileEntry(
            TestPropsValues.getUserId(),
            _group.getGroupId(),
            DLFolderConstants.DEFAULT_PARENT_FOLDER_ID,
            RandomTestUtil.randomString(),
            ContentTypes.TEXT_PLAIN,
            "Old Title",
            RandomTestUtil.randomString(),
            null,
            RandomTestUtil.randomBytes(),
            serviceContext);

    DLAppLocalServiceUtil.updateFileEntry(
        TestPropsValues.getUserId(),
        fileEntry.getFileEntryId(),
        RandomTestUtil.randomString(),
        ContentTypes.TEXT_PLAIN,
        "New Title",
        RandomTestUtil.randomString(),
        null,
        true,
        RandomTestUtil.randomBytes(),
        serviceContext);

    AssetEntry assetEntry =
        AssetEntryLocalServiceUtil.getEntry(
            DLFileEntryConstants.getClassName(), fileEntry.getFileEntryId());

    Assert.assertEquals("New Title", assetEntry.getTitle());
  }
  public AssetEntry updateAsset(
      long userId, FileEntry fileEntry, FileVersion fileVersion, long assetClassPk)
      throws PortalException, SystemException {

    long[] assetCategoryIds =
        assetCategoryLocalService.getCategoryIds(DLFileEntryConstants.getClassName(), assetClassPk);
    String[] assetTagNames =
        assetTagLocalService.getTagNames(DLFileEntryConstants.getClassName(), assetClassPk);

    AssetEntry assetEntry =
        assetEntryLocalService.getEntry(DLFileEntryConstants.getClassName(), assetClassPk);

    List<AssetLink> assetLinks = assetLinkLocalService.getDirectLinks(assetEntry.getEntryId());

    long[] assetLinkIds =
        StringUtil.split(ListUtil.toString(assetLinks, AssetLink.ENTRY_ID2_ACCESSOR), 0L);

    return updateAsset(
        userId, fileEntry, fileVersion, assetCategoryIds, assetTagNames, assetLinkIds);
  }
  protected void search(
      FileEntry fileEntry, boolean rootFolder, String keywords, boolean assertTrue)
      throws Exception {

    SearchContext searchContext = new SearchContext();

    searchContext.setAttribute("paginationType", "regular");
    searchContext.setCompanyId(fileEntry.getCompanyId());
    searchContext.setFolderIds(new long[] {fileEntry.getFolderId()});
    searchContext.setGroupIds(new long[] {fileEntry.getRepositoryId()});
    searchContext.setKeywords(keywords);

    QueryConfig queryConfig = new QueryConfig();

    queryConfig.setHighlightEnabled(false);
    queryConfig.setScoreEnabled(false);

    searchContext.setQueryConfig(queryConfig);

    Indexer indexer = IndexerRegistryUtil.getIndexer(DLFileEntryConstants.getClassName());

    Hits hits = indexer.search(searchContext);

    List<Document> documents = hits.toList();

    boolean found = false;

    for (Document document : documents) {
      long fileEntryId = GetterUtil.getLong(document.get(Field.ENTRY_CLASS_PK));

      if (fileEntryId == fileEntry.getFileEntryId()) {
        found = true;

        break;
      }
    }

    String message = "Search engine could not find ";

    if (rootFolder) {
      message += "root file entry by " + keywords;
    } else {
      message += "file entry by " + keywords;
    }

    message += " using query " + hits.getQuery();

    if (assertTrue) {
      Assert.assertTrue(message, found);
    } else {
      Assert.assertFalse(message, found);
    }
  }
  public void addFileEntry(
      long userId, FileEntry fileEntry, FileVersion fileVersion, ServiceContext serviceContext)
      throws PortalException, SystemException {

    updateAsset(
        userId,
        fileEntry,
        fileVersion,
        serviceContext.getAssetCategoryIds(),
        serviceContext.getAssetTagNames(),
        serviceContext.getAssetLinkEntryIds());

    if (PropsValues.DL_FILE_ENTRY_COMMENTS_ENABLED) {
      mbMessageLocalService.addDiscussionMessage(
          fileEntry.getUserId(), fileEntry.getUserName(),
          fileEntry.getGroupId(), DLFileEntryConstants.getClassName(),
          fileEntry.getFileEntryId(), WorkflowConstants.ACTION_PUBLISH);
    }

    if (fileVersion instanceof LiferayFileVersion) {
      DLFileVersion dlFileVersion = (DLFileVersion) fileVersion.getModel();

      Map<String, Serializable> workflowContext = new HashMap<String, Serializable>();

      workflowContext.put("event", DLSyncConstants.EVENT_ADD);

      WorkflowHandlerRegistryUtil.startWorkflowInstance(
          dlFileVersion.getCompanyId(),
          dlFileVersion.getGroupId(),
          userId,
          DLFileEntryConstants.getClassName(),
          dlFileVersion.getFileVersionId(),
          dlFileVersion,
          serviceContext,
          workflowContext);
    }

    registerDLProcessorCallback(fileEntry, null);
  }
  @Override
  public SyncDLObject moveFileEntryToTrash(long fileEntryId) throws PortalException {

    try {
      FileEntry fileEntry = dlAppLocalService.getFileEntry(fileEntryId);

      SyncUtil.checkSyncEnabled(fileEntry.getGroupId());

      if (TrashUtil.isInTrash(DLFileEntryConstants.getClassName(), fileEntryId)) {

        return null;
      }

      fileEntry = dlAppService.moveFileEntryToTrash(fileEntryId);

      return toSyncDLObject(fileEntry, SyncConstants.EVENT_TRASH);
    } catch (NoSuchFileEntryException nsfee) {
      return null;
    } catch (PortalException pe) {
      throw new PortalException(SyncUtil.buildExceptionMessage(pe), pe);
    }
  }
  private void _trashWikiAttachments(boolean restore) throws Exception {
    int initialNotInTrashCount = _page.getAttachmentsFileEntriesCount();
    int initialTrashEntriesCount = _page.getDeletedAttachmentsFileEntriesCount();

    String fileName = RandomTestUtil.randomString() + ".docx";

    WikiTestUtil.addWikiAttachment(
        TestPropsValues.getUserId(), _node.getNodeId(), _page.getTitle(), fileName, getClass());

    Assert.assertEquals(initialNotInTrashCount + 1, _page.getAttachmentsFileEntriesCount());
    Assert.assertEquals(initialTrashEntriesCount, _page.getDeletedAttachmentsFileEntriesCount());

    FileEntry fileEntry =
        WikiPageLocalServiceUtil.movePageAttachmentToTrash(
            TestPropsValues.getUserId(), _page.getNodeId(), _page.getTitle(), fileName);

    Assert.assertEquals(initialNotInTrashCount, _page.getAttachmentsFileEntriesCount());
    Assert.assertEquals(
        initialTrashEntriesCount + 1, _page.getDeletedAttachmentsFileEntriesCount());

    if (restore) {
      TrashEntryServiceUtil.restoreEntry(
          DLFileEntryConstants.getClassName(), fileEntry.getFileEntryId());

      Assert.assertEquals(initialNotInTrashCount + 1, _page.getAttachmentsFileEntriesCount());
      Assert.assertEquals(initialTrashEntriesCount, _page.getDeletedAttachmentsFileEntriesCount());

      WikiPageLocalServiceUtil.deletePageAttachment(_page.getNodeId(), _page.getTitle(), fileName);
    } else {
      WikiPageLocalServiceUtil.deletePageAttachment(
          _page.getNodeId(), _page.getTitle(), fileEntry.getTitle());

      Assert.assertEquals(initialNotInTrashCount, _page.getAttachmentsFileEntriesCount());
      Assert.assertEquals(initialTrashEntriesCount, _page.getDeletedAttachmentsFileEntriesCount());
    }
  }
  @Test
  public void testAsstTags() throws Exception {
    long folderId = parentFolder.getFolderId();
    String name = "TestTags.txt";
    String description = StringPool.BLANK;
    String changeLog = StringPool.BLANK;
    byte[] bytes = CONTENT.getBytes();

    ServiceContext serviceContext = new ServiceContext();

    serviceContext.setAddGroupPermissions(true);
    serviceContext.setAddGuestPermissions(true);
    serviceContext.setScopeGroupId(group.getGroupId());

    String[] assetTagNames = new String[] {"hello", "world"};

    serviceContext.setAssetTagNames(assetTagNames);

    FileEntry fileEntry =
        DLAppServiceUtil.addFileEntry(
            group.getGroupId(),
            folderId,
            name,
            ContentTypes.TEXT_PLAIN,
            name,
            description,
            changeLog,
            bytes,
            serviceContext);

    AssetEntry assetEntry =
        AssetEntryLocalServiceUtil.fetchEntry(
            DLFileEntryConstants.getClassName(), fileEntry.getFileEntryId());

    AssertUtils.assertEqualsSorted(assetTagNames, assetEntry.getTagNames());

    Thread.sleep(1000 * TestPropsValues.JUNIT_DELAY_FACTOR);

    _fileEntry = fileEntry;

    search(_fileEntry, false, "hello", true);
    search(_fileEntry, false, "world", true);
    search(_fileEntry, false, "liferay", false);

    assetTagNames = new String[] {"hello", "world", "liferay"};

    serviceContext.setAssetTagNames(assetTagNames);

    fileEntry =
        DLAppServiceUtil.updateFileEntry(
            fileEntry.getFileEntryId(),
            name,
            ContentTypes.TEXT_PLAIN,
            name,
            description,
            changeLog,
            false,
            bytes,
            serviceContext);

    assetEntry =
        AssetEntryLocalServiceUtil.fetchEntry(
            DLFileEntryConstants.getClassName(), fileEntry.getFileEntryId());

    AssertUtils.assertEqualsSorted(assetTagNames, assetEntry.getTagNames());

    Thread.sleep(1000 * TestPropsValues.JUNIT_DELAY_FACTOR);

    _fileEntry = fileEntry;

    search(_fileEntry, false, "hello", true);
    search(_fileEntry, false, "world", true);
    search(_fileEntry, false, "liferay", true);

    DLAppServiceUtil.deleteFileEntry(_fileEntry.getFileEntryId());

    _fileEntry = null;
  }
  public void updateStatus(
      long userId,
      FileEntry fileEntry,
      FileVersion latestFileVersion,
      int oldStatus,
      int newStatus,
      Map<String, Serializable> workflowContext)
      throws PortalException, SystemException {

    if (newStatus == WorkflowConstants.STATUS_APPROVED) {

      // Asset

      String latestFileVersionVersion = latestFileVersion.getVersion();

      if (latestFileVersionVersion.equals(fileEntry.getVersion())) {
        if (!latestFileVersionVersion.equals(DLFileEntryConstants.VERSION_DEFAULT)) {

          AssetEntry draftAssetEntry = null;

          try {
            long fileEntryTypeId = getFileEntryTypeId(fileEntry);

            draftAssetEntry =
                assetEntryLocalService.getEntry(
                    DLFileEntryConstants.getClassName(), latestFileVersion.getPrimaryKey());

            long[] assetCategoryIds = draftAssetEntry.getCategoryIds();
            String[] assetTagNames = draftAssetEntry.getTagNames();

            List<AssetLink> assetLinks =
                assetLinkLocalService.getDirectLinks(
                    draftAssetEntry.getEntryId(), AssetLinkConstants.TYPE_RELATED);

            long[] assetLinkEntryIds =
                StringUtil.split(ListUtil.toString(assetLinks, AssetLink.ENTRY_ID2_ACCESSOR), 0L);

            AssetEntry assetEntry =
                assetEntryLocalService.updateEntry(
                    userId,
                    fileEntry.getGroupId(),
                    DLFileEntryConstants.getClassName(),
                    fileEntry.getFileEntryId(),
                    fileEntry.getUuid(),
                    fileEntryTypeId,
                    assetCategoryIds,
                    assetTagNames,
                    true,
                    null,
                    null,
                    null,
                    draftAssetEntry.getMimeType(),
                    fileEntry.getTitle(),
                    fileEntry.getDescription(),
                    null,
                    null,
                    null,
                    0,
                    0,
                    null,
                    false);

            assetLinkLocalService.updateLinks(
                userId,
                assetEntry.getEntryId(),
                assetLinkEntryIds,
                AssetLinkConstants.TYPE_RELATED);

            assetEntryLocalService.deleteEntry(draftAssetEntry.getEntryId());
          } catch (NoSuchEntryException nsee) {
          }
        }

        assetEntryLocalService.updateVisible(
            DLFileEntryConstants.getClassName(), fileEntry.getFileEntryId(), true);
      }

      // Sync

      String event = (String) workflowContext.get("event");

      if (!isStagingGroup(fileEntry.getGroupId()) && Validator.isNotNull(event)) {

        if (event.equals(DLSyncConstants.EVENT_ADD)) {
          dlSyncLocalService.addSync(
              fileEntry.getFileEntryId(),
              fileEntry.getUuid(),
              fileEntry.getCompanyId(),
              fileEntry.getRepositoryId(),
              fileEntry.getFolderId(),
              fileEntry.getTitle(),
              fileEntry.getDescription(),
              DLSyncConstants.TYPE_FILE,
              fileEntry.getVersion());
        } else if (event.equals(DLSyncConstants.EVENT_UPDATE)) {
          dlSyncLocalService.updateSync(
              fileEntry.getFileEntryId(),
              fileEntry.getFolderId(),
              fileEntry.getTitle(),
              fileEntry.getDescription(),
              DLSyncConstants.EVENT_UPDATE,
              fileEntry.getVersion());
        }
      }

      // Social

      int activityType = DLActivityKeys.UPDATE_FILE_ENTRY;

      if (latestFileVersionVersion.equals(DLFileEntryConstants.VERSION_DEFAULT)) {

        activityType = DLActivityKeys.ADD_FILE_ENTRY;
      }

      if (oldStatus != WorkflowConstants.STATUS_IN_TRASH) {
        socialActivityLocalService.addUniqueActivity(
            latestFileVersion.getStatusByUserId(),
            fileEntry.getGroupId(),
            latestFileVersion.getCreateDate(),
            DLFileEntryConstants.getClassName(),
            fileEntry.getFileEntryId(),
            activityType,
            StringPool.BLANK,
            0);
      }
    } else {

      // Asset

      if (newStatus == WorkflowConstants.STATUS_IN_TRASH) {
        assetEntryLocalService.moveEntryToTrash(
            DLFileEntryConstants.getClassName(), fileEntry.getFileEntryId());
      } else {
        boolean visible = false;

        if (Validator.isNotNull(fileEntry.getVersion())) {
          visible = true;
        }

        assetEntryLocalService.updateVisible(
            DLFileEntryConstants.getClassName(), fileEntry.getFileEntryId(), visible);
      }
    }
  }
  public AssetEntry updateAsset(
      long userId,
      FileEntry fileEntry,
      FileVersion fileVersion,
      long[] assetCategoryIds,
      String[] assetTagNames,
      long[] assetLinkEntryIds)
      throws PortalException, SystemException {

    AssetEntry assetEntry = null;

    boolean visible = false;

    boolean addDraftAssetEntry = false;

    if (fileEntry instanceof LiferayFileEntry) {
      DLFileVersion dlFileVersion = (DLFileVersion) fileVersion.getModel();

      if (dlFileVersion.isApproved()) {
        visible = true;
      } else {
        String version = dlFileVersion.getVersion();

        if (!version.equals(DLFileEntryConstants.VERSION_DEFAULT)) {
          addDraftAssetEntry = true;
        }
      }
    } else {
      visible = true;
    }

    long fileEntryTypeId = getFileEntryTypeId(fileEntry);

    if (addDraftAssetEntry) {
      assetEntry =
          assetEntryLocalService.updateEntry(
              userId,
              fileEntry.getGroupId(),
              DLFileEntryConstants.getClassName(),
              fileVersion.getFileVersionId(),
              fileEntry.getUuid(),
              fileEntryTypeId,
              assetCategoryIds,
              assetTagNames,
              false,
              null,
              null,
              null,
              fileEntry.getMimeType(),
              fileEntry.getTitle(),
              fileEntry.getDescription(),
              null,
              null,
              null,
              0,
              0,
              null,
              false);
    } else {
      assetEntry =
          assetEntryLocalService.updateEntry(
              userId,
              fileEntry.getGroupId(),
              DLFileEntryConstants.getClassName(),
              fileEntry.getFileEntryId(),
              fileEntry.getUuid(),
              fileEntryTypeId,
              assetCategoryIds,
              assetTagNames,
              visible,
              null,
              null,
              null,
              fileEntry.getMimeType(),
              fileEntry.getTitle(),
              fileEntry.getDescription(),
              null,
              null,
              null,
              0,
              0,
              null,
              false);

      List<DLFileShortcut> dlFileShortcuts =
          dlFileShortcutPersistence.findByToFileEntryId(fileEntry.getFileEntryId());

      for (DLFileShortcut dlFileShortcut : dlFileShortcuts) {
        assetEntryLocalService.updateEntry(
            userId,
            dlFileShortcut.getGroupId(),
            DLFileShortcut.class.getName(),
            dlFileShortcut.getFileShortcutId(),
            dlFileShortcut.getUuid(),
            fileEntryTypeId,
            assetCategoryIds,
            assetTagNames,
            true,
            null,
            null,
            null,
            fileEntry.getMimeType(),
            fileEntry.getTitle(),
            fileEntry.getDescription(),
            null,
            null,
            null,
            0,
            0,
            null,
            false);
      }
    }

    assetLinkLocalService.updateLinks(
        userId, assetEntry.getEntryId(), assetLinkEntryIds, AssetLinkConstants.TYPE_RELATED);

    return assetEntry;
  }
  public FileEntry moveFileEntryToTrash(long userId, FileEntry fileEntry)
      throws PortalException, SystemException {

    // File entry

    DLFileEntry dlFileEntry = (DLFileEntry) fileEntry.getModel();

    dlFileEntry.setTitle(DLAppUtil.appendTrashNamespace(dlFileEntry.getTitle()));

    dlFileEntryPersistence.update(dlFileEntry, false);

    List<DLFileVersion> dlFileVersions =
        dlFileVersionLocalService.getFileVersions(
            fileEntry.getFileEntryId(), WorkflowConstants.STATUS_ANY);

    dlFileVersions = ListUtil.sort(dlFileVersions, new FileVersionVersionComparator());

    FileVersion fileVersion = new LiferayFileVersion(dlFileVersions.get(0));

    int oldStatus = fileVersion.getStatus();

    // File version

    dlFileEntryLocalService.updateStatus(
        userId,
        fileVersion.getFileVersionId(),
        WorkflowConstants.STATUS_IN_TRASH,
        new HashMap<String, Serializable>(),
        new ServiceContext());

    // File shortcut

    dlFileShortcutLocalService.disableFileShortcuts(fileEntry.getFileEntryId());

    // File rank

    dlFileRankLocalService.disableFileRanks(fileEntry.getFileEntryId());

    // Social

    socialActivityLocalService.addActivity(
        userId,
        fileEntry.getGroupId(),
        DLFileEntryConstants.getClassName(),
        fileEntry.getFileEntryId(),
        SocialActivityConstants.TYPE_MOVE_TO_TRASH,
        StringPool.BLANK,
        0);

    // Trash

    List<ObjectValuePair<Long, Integer>> fileVersionStatuses =
        new ArrayList<ObjectValuePair<Long, Integer>>(dlFileVersions.size());

    for (DLFileVersion dlFileVersion : dlFileVersions) {
      ObjectValuePair<Long, Integer> fileVersionStatus = new ObjectValuePair<Long, Integer>();

      fileVersionStatus.setKey(dlFileVersion.getFileVersionId());

      int status = dlFileVersion.getStatus();

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

      fileVersionStatus.setValue(status);

      fileVersionStatuses.add(fileVersionStatus);
    }

    trashEntryLocalService.addTrashEntry(
        userId,
        fileEntry.getGroupId(),
        DLFileEntryConstants.getClassName(),
        fileEntry.getFileEntryId(),
        oldStatus,
        fileVersionStatuses,
        null);

    // Workflow

    if (oldStatus == WorkflowConstants.STATUS_PENDING) {
      workflowInstanceLinkLocalService.deleteWorkflowInstanceLink(
          fileVersion.getCompanyId(),
          fileVersion.getGroupId(),
          DLFileEntryConstants.getClassName(),
          fileVersion.getFileVersionId());
    }

    return fileEntry;
  }
  public void checkAssetEntry(long userId, FileEntry fileEntry, FileVersion fileVersion)
      throws PortalException, SystemException {

    AssetEntry fileEntryAssetEntry =
        assetEntryLocalService.fetchEntry(
            DLFileEntryConstants.getClassName(), fileEntry.getFileEntryId());

    long[] assetCategoryIds = new long[0];
    String[] assetTagNames = new String[0];

    long fileEntryTypeId = getFileEntryTypeId(fileEntry);

    if (fileEntryAssetEntry == null) {
      fileEntryAssetEntry =
          assetEntryLocalService.updateEntry(
              userId,
              fileEntry.getGroupId(),
              DLFileEntryConstants.getClassName(),
              fileEntry.getFileEntryId(),
              fileEntry.getUuid(),
              fileEntryTypeId,
              assetCategoryIds,
              assetTagNames,
              false,
              null,
              null,
              null,
              fileEntry.getMimeType(),
              fileEntry.getTitle(),
              fileEntry.getDescription(),
              null,
              null,
              null,
              0,
              0,
              null,
              false);
    }

    AssetEntry fileVersionAssetEntry =
        assetEntryLocalService.fetchEntry(
            DLFileEntryConstants.getClassName(), fileVersion.getFileVersionId());

    if ((fileVersionAssetEntry == null)
        && !fileVersion.isApproved()
        && !fileVersion.getVersion().equals(DLFileEntryConstants.VERSION_DEFAULT)) {

      assetCategoryIds =
          assetCategoryLocalService.getCategoryIds(
              DLFileEntryConstants.getClassName(), fileEntry.getFileEntryId());
      assetTagNames =
          assetTagLocalService.getTagNames(
              DLFileEntryConstants.getClassName(), fileEntry.getFileEntryId());

      fileVersionAssetEntry =
          assetEntryLocalService.updateEntry(
              userId,
              fileEntry.getGroupId(),
              DLFileEntryConstants.getClassName(),
              fileVersion.getFileVersionId(),
              fileEntry.getUuid(),
              fileEntryTypeId,
              assetCategoryIds,
              assetTagNames,
              false,
              null,
              null,
              null,
              fileEntry.getMimeType(),
              fileEntry.getTitle(),
              fileEntry.getDescription(),
              null,
              null,
              null,
              0,
              0,
              null,
              false);

      List<AssetLink> assetLinks =
          assetLinkLocalService.getDirectLinks(fileEntryAssetEntry.getEntryId());

      long[] assetLinkIds =
          StringUtil.split(ListUtil.toString(assetLinks, AssetLink.ENTRY_ID2_ACCESSOR), 0L);

      assetLinkLocalService.updateLinks(
          userId,
          fileVersionAssetEntry.getEntryId(),
          assetLinkIds,
          AssetLinkConstants.TYPE_RELATED);
    }
  }
  public void updateStatuses(User user, List<Object> dlFileEntriesAndDLFolders, int status)
      throws PortalException, SystemException {

    for (Object object : dlFileEntriesAndDLFolders) {
      if (object instanceof DLFileEntry) {
        DLFileEntry dlFileEntry = (DLFileEntry) object;

        List<DLFileVersion> dlFileVersions =
            dlFileVersionLocalService.getFileVersions(
                dlFileEntry.getFileEntryId(), WorkflowConstants.STATUS_ANY);

        dlFileVersions = ListUtil.copy(dlFileVersions);

        Collections.sort(dlFileVersions, new FileVersionVersionComparator());

        DLFileVersion latestDlFileVersion = dlFileVersions.get(0);

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

          continue;
        }

        // Asset

        if (status == WorkflowConstants.STATUS_APPROVED) {
          if (latestDlFileVersion.isApproved()) {
            assetEntryLocalService.updateVisible(
                DLFileEntryConstants.getClassName(), dlFileEntry.getFileEntryId(), true);
          }
        } else {
          assetEntryLocalService.moveEntryToTrash(
              DLFileEntryConstants.getClassName(), dlFileEntry.getFileEntryId());
        }

        // Social

        if (status == WorkflowConstants.STATUS_APPROVED) {
          socialActivityCounterLocalService.enableActivityCounters(
              DLFileEntryConstants.getClassName(), dlFileEntry.getFileEntryId());

          socialActivityLocalService.addActivity(
              user.getUserId(),
              dlFileEntry.getGroupId(),
              DLFileEntryConstants.getClassName(),
              dlFileEntry.getFileEntryId(),
              SocialActivityConstants.TYPE_RESTORE_FROM_TRASH,
              StringPool.BLANK,
              0);
        } else if (latestDlFileVersion.getStatus() == WorkflowConstants.STATUS_APPROVED) {

          socialActivityLocalService.addActivity(
              user.getUserId(),
              dlFileEntry.getGroupId(),
              DLFileEntryConstants.getClassName(),
              dlFileEntry.getFileEntryId(),
              SocialActivityConstants.TYPE_MOVE_TO_TRASH,
              StringPool.BLANK,
              0);
        }

        // Index

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

        if (status == WorkflowConstants.STATUS_APPROVED) {
          indexer.reindex(dlFileEntry);
        } else {
          indexer.delete(dlFileEntry);
        }

        // Workflow

        if (status != WorkflowConstants.STATUS_APPROVED) {
          for (DLFileVersion dlFileVersion : dlFileVersions) {
            if (!dlFileVersion.isPending()) {
              continue;
            }

            dlFileVersion.setStatus(WorkflowConstants.STATUS_DRAFT);

            dlFileVersionPersistence.update(dlFileVersion, false);

            workflowInstanceLinkLocalService.deleteWorkflowInstanceLink(
                dlFileVersion.getCompanyId(),
                dlFileVersion.getGroupId(),
                DLFileEntryConstants.getClassName(),
                dlFileVersion.getFileVersionId());
          }
        }
      } else if (object instanceof DLFolder) {
        DLFolder dlFolder = (DLFolder) object;

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

        QueryDefinition queryDefinition = new QueryDefinition(WorkflowConstants.STATUS_ANY);

        List<Object> foldersAndFileEntriesAndFileShortcuts =
            dlFolderLocalService.getFoldersAndFileEntriesAndFileShortcuts(
                dlFolder.getGroupId(), dlFolder.getFolderId(), null, false, queryDefinition);

        updateStatuses(user, foldersAndFileEntriesAndFileShortcuts, status);
      }
    }
  }
Example #17
0
  public Hits search(
      long companyId,
      long userId,
      String portletId,
      long groupId,
      long[] repositoryIds,
      String keywords,
      int start,
      int end) {

    try {
      SearchContext searchContext = new SearchContext();

      searchContext.setCompanyId(companyId);
      searchContext.setEnd(end);
      searchContext.setEntryClassNames(new String[] {DLFileEntryConstants.getClassName()});
      searchContext.setGroupIds(new long[] {groupId});

      Indexer indexer = IndexerRegistryUtil.getIndexer(DLFileEntryConstants.getClassName());

      searchContext.setSearchEngineId(indexer.getSearchEngineId());

      searchContext.setStart(start);
      searchContext.setUserId(userId);

      BooleanQuery contextQuery = BooleanQueryFactoryUtil.create(searchContext);

      contextQuery.addRequiredTerm(Field.PORTLET_ID, portletId);

      if (groupId > 0) {
        Group group = groupLocalService.getGroup(groupId);

        if (group.isLayout()) {
          contextQuery.addRequiredTerm(Field.SCOPE_GROUP_ID, groupId);

          groupId = group.getParentGroupId();
        }

        contextQuery.addRequiredTerm(Field.GROUP_ID, groupId);
      }

      if (ArrayUtil.isNotEmpty(repositoryIds)) {
        BooleanQuery repositoryIdsQuery = BooleanQueryFactoryUtil.create(searchContext);

        for (long repositoryId : repositoryIds) {
          try {
            if (userId > 0) {
              PermissionChecker permissionChecker = PermissionThreadLocal.getPermissionChecker();

              DLFolderPermission.check(permissionChecker, groupId, repositoryId, ActionKeys.VIEW);
            }

            if (repositoryId == DLFolderConstants.DEFAULT_PARENT_FOLDER_ID) {

              repositoryId = groupId;
            }

            TermQuery termQuery =
                TermQueryFactoryUtil.create(searchContext, "repositoryId", repositoryId);

            repositoryIdsQuery.add(termQuery, BooleanClauseOccur.SHOULD);
          } catch (Exception e) {
          }
        }

        contextQuery.add(repositoryIdsQuery, BooleanClauseOccur.MUST);
      }

      BooleanQuery searchQuery = BooleanQueryFactoryUtil.create(searchContext);

      searchQuery.addTerms(_KEYWORDS_FIELDS, keywords);

      BooleanQuery fullQuery = BooleanQueryFactoryUtil.create(searchContext);

      fullQuery.add(contextQuery, BooleanClauseOccur.MUST);

      List<BooleanClause> clauses = searchQuery.clauses();

      if (!clauses.isEmpty()) {
        fullQuery.add(searchQuery, BooleanClauseOccur.MUST);
      }

      return SearchEngineUtil.search(searchContext, fullQuery);
    } catch (Exception e) {
      throw new SystemException(e);
    }
  }
 @Override
 public StagedModelType getStagedModelType() {
   return new StagedModelType(DLFileEntryConstants.getClassName());
 }