private void _generateImagesPB(FileVersion fileVersion, InputStream inputStream)
      throws Exception {

    boolean generatePreview = _isGeneratePreview(fileVersion);
    boolean generateThumbnail = _isGenerateThumbnail(fileVersion);

    PDDocument pdDocument = null;

    try {
      pdDocument = PDDocument.load(inputStream);

      PDDocumentCatalog pdDocumentCatalog = pdDocument.getDocumentCatalog();

      List<PDPage> pdPages = pdDocumentCatalog.getAllPages();

      for (int i = 0; i < pdPages.size(); i++) {
        PDPage pdPage = pdPages.get(i);

        if (generateThumbnail && (i == 0)) {
          _generateImagesPB(
              fileVersion,
              pdPage,
              PropsValues.DL_FILE_ENTRY_THUMBNAIL_DPI,
              PropsValues.DL_FILE_ENTRY_THUMBNAIL_HEIGHT,
              PropsValues.DL_FILE_ENTRY_THUMBNAIL_WIDTH,
              true,
              0);

          if (_log.isInfoEnabled()) {
            _log.info("PDFBox generated a thumbnail for " + fileVersion.getFileVersionId());
          }
        }

        if (!generatePreview) {
          break;
        }

        _generateImagesPB(
            fileVersion,
            pdPage,
            PropsValues.DL_FILE_ENTRY_PREVIEW_DOCUMENT_DPI,
            PropsValues.DL_FILE_ENTRY_PREVIEW_DOCUMENT_HEIGHT,
            PropsValues.DL_FILE_ENTRY_PREVIEW_DOCUMENT_WIDTH,
            false,
            i + 1);
      }

      if (_log.isInfoEnabled() && generatePreview) {
        _log.info(
            "PDFBox generated "
                + getPreviewFileCount(fileVersion)
                + " preview pages for "
                + fileVersion.getFileVersionId());
      }
    } finally {
      if (pdDocument != null) {
        pdDocument.close();
      }
    }
  }
  private void _queueGeneration(FileVersion sourceFileVersion, FileVersion destinationFileVersion) {

    if (_fileVersionIds.contains(destinationFileVersion.getFileVersionId())) {

      return;
    }

    boolean generateImages = false;

    String extension = destinationFileVersion.getExtension();

    if (extension.equals("pdf")) {
      generateImages = true;
    } else if (DocumentConversionUtil.isEnabled()) {
      String[] conversions = DocumentConversionUtil.getConversions(extension);

      for (String conversion : conversions) {
        if (conversion.equals("pdf")) {
          generateImages = true;

          break;
        }
      }
    }

    if (generateImages) {
      _fileVersionIds.add(destinationFileVersion.getFileVersionId());

      sendGenerationMessage(
          DestinationNames.DOCUMENT_LIBRARY_PDF_PROCESSOR,
          sourceFileVersion,
          destinationFileVersion);
    }
  }
Example #3
0
  public void copy(FileVersion sourceFileVersion, FileVersion destinationFileVersion) {

    if (sourceFileVersion.getFileVersionId() == destinationFileVersion.getFileVersionId()) {

      return;
    }

    copyPreviews(sourceFileVersion, destinationFileVersion);
    copyThumbnails(sourceFileVersion, destinationFileVersion);
  }
Example #4
0
  public void trigger(FileVersion sourceFileVersion, FileVersion destinationFileVersion) {

    if (getFileVersionIds().contains(destinationFileVersion.getFileVersionId())) {

      String processIdentity = Long.toString(destinationFileVersion.getFileVersionId());

      destroyProcess(processIdentity);

      getFileVersionIds().remove(destinationFileVersion.getFileVersionId());
    }
  }
  private void _queueGeneration(FileVersion sourceFileVersion, FileVersion destinationFileVersion) {

    if (_fileVersionIds.contains(destinationFileVersion.getFileVersionId())
        || !isSupported(destinationFileVersion)) {

      return;
    }

    _fileVersionIds.add(destinationFileVersion.getFileVersionId());

    sendGenerationMessage(
        DestinationNames.DOCUMENT_LIBRARY_VIDEO_PROCESSOR,
        sourceFileVersion,
        destinationFileVersion);
  }
  public FileEntry moveFileEntryFromTrash(
      long userId, FileEntry fileEntry, long newFolderId, ServiceContext serviceContext)
      throws PortalException, SystemException {

    // File entry

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

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

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

    dlFileEntryLocalService.updateStatus(
        userId,
        fileVersion.getFileVersionId(),
        fileVersion.getStatus(),
        new HashMap<String, Serializable>(),
        serviceContext);

    // File rank

    dlFileRankLocalService.enableFileRanks(fileEntry.getFileEntryId());

    // App helper

    return dlAppService.moveFileEntry(fileEntry.getFileEntryId(), newFolderId, serviceContext);
  }
Example #7
0
 public void deleteFiles(FileVersion fileVersion, String thumbnailType) {
   deleteFiles(
       fileVersion.getCompanyId(),
       fileVersion.getGroupId(),
       fileVersion.getFileEntryId(),
       fileVersion.getFileVersionId(),
       thumbnailType);
 }
Example #8
0
  protected static String getPathSegment(FileVersion fileVersion, boolean preview) {

    return getPathSegment(
        fileVersion.getGroupId(),
        fileVersion.getFileEntryId(),
        fileVersion.getFileVersionId(),
        preview);
  }
  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());
  }
  private void _generateImages(FileVersion sourceFileVersion, FileVersion destinationFileVersion)
      throws Exception {

    InputStream inputStream = null;

    try {
      if (sourceFileVersion != null) {
        copy(sourceFileVersion, destinationFileVersion);

        return;
      }

      if (_hasImages(destinationFileVersion)) {
        return;
      }

      String extension = destinationFileVersion.getExtension();

      if (extension.equals("pdf")) {
        if (destinationFileVersion instanceof LiferayFileVersion) {
          try {
            LiferayFileVersion liferayFileVersion = (LiferayFileVersion) destinationFileVersion;

            File file = liferayFileVersion.getFile(false);

            _generateImages(destinationFileVersion, file);

            return;
          } catch (UnsupportedOperationException uoe) {
          }
        }

        inputStream = destinationFileVersion.getContentStream(false);

        _generateImages(destinationFileVersion, inputStream);
      } else if (DocumentConversionUtil.isEnabled()) {
        inputStream = destinationFileVersion.getContentStream(false);

        String tempFileId =
            DLUtil.getTempFileId(
                destinationFileVersion.getFileEntryId(), destinationFileVersion.getVersion());

        File file = DocumentConversionUtil.convert(tempFileId, inputStream, extension, "pdf");

        _generateImages(destinationFileVersion, file);
      }
    } catch (NoSuchFileEntryException nsfee) {
    } finally {
      StreamUtil.cleanUp(inputStream);

      _fileVersionIds.remove(destinationFileVersion.getFileVersionId());
    }
  }
  private void _generateImagesIM(FileVersion fileVersion, File file) throws Exception {

    if (_isGeneratePreview(fileVersion)) {
      _generateImagesIM(
          fileVersion,
          file,
          PropsValues.DL_FILE_ENTRY_PREVIEW_DOCUMENT_DEPTH,
          PropsValues.DL_FILE_ENTRY_PREVIEW_DOCUMENT_DPI,
          PropsValues.DL_FILE_ENTRY_PREVIEW_DOCUMENT_HEIGHT,
          PropsValues.DL_FILE_ENTRY_PREVIEW_DOCUMENT_WIDTH,
          false);

      if (_log.isInfoEnabled()) {
        int previewFileCount = getPreviewFileCount(fileVersion);

        _log.info(
            "ImageMagick generated "
                + previewFileCount
                + " preview pages for "
                + fileVersion.getFileVersionId());
      }
    }

    if (_isGenerateThumbnail(fileVersion)) {
      _generateImagesIM(
          fileVersion,
          file,
          PropsValues.DL_FILE_ENTRY_THUMBNAIL_DEPTH,
          PropsValues.DL_FILE_ENTRY_THUMBNAIL_DPI,
          PropsValues.DL_FILE_ENTRY_THUMBNAIL_HEIGHT,
          PropsValues.DL_FILE_ENTRY_THUMBNAIL_WIDTH,
          true);

      if (_log.isInfoEnabled()) {
        _log.info("ImageMagick generated a thumbnail for " + fileVersion.getFileVersionId());
      }
    }
  }
  protected void exportMetaData(
      PortletDataContext portletDataContext, Element fileEntryElement, FileEntry fileEntry)
      throws Exception {

    LiferayFileEntry liferayFileEntry = (LiferayFileEntry) fileEntry;

    DLFileEntry dlFileEntry = liferayFileEntry.getDLFileEntry();

    long fileEntryTypeId = dlFileEntry.getFileEntryTypeId();

    DLFileEntryType dlFileEntryType =
        DLFileEntryTypeLocalServiceUtil.fetchFileEntryType(fileEntryTypeId);

    if ((dlFileEntryType == null) || !dlFileEntryType.isExportable()) {
      return;
    }

    StagedModelDataHandlerUtil.exportReferenceStagedModel(
        portletDataContext, fileEntry, dlFileEntryType, PortletDataContext.REFERENCE_TYPE_STRONG);

    List<DDMStructure> ddmStructures = dlFileEntryType.getDDMStructures();

    for (DDMStructure ddmStructure : ddmStructures) {
      FileVersion fileVersion = fileEntry.getFileVersion();

      DLFileEntryMetadata dlFileEntryMetadata =
          DLFileEntryMetadataLocalServiceUtil.fetchFileEntryMetadata(
              ddmStructure.getStructureId(), fileVersion.getFileVersionId());

      if (dlFileEntryMetadata == null) {
        continue;
      }

      Element structureFields = fileEntryElement.addElement("structure-fields");

      String path =
          ExportImportPathUtil.getModelPath(
              ddmStructure, String.valueOf(dlFileEntryMetadata.getDDMStorageId()));

      structureFields.addAttribute("path", path);

      structureFields.addAttribute("structureUuid", ddmStructure.getUuid());

      DDMFormValues ddmFormValues =
          StorageEngineUtil.getDDMFormValues(dlFileEntryMetadata.getDDMStorageId());

      portletDataContext.addZipEntry(path, ddmFormValues);
    }
  }
  protected void updateThumbnails(long fileEntryId) throws Exception {
    Connection con = null;
    PreparedStatement ps = null;
    ResultSet rs = null;

    try {
      con = DataAccess.getUpgradeOptimizedConnection();

      ps =
          con.prepareStatement(
              "select fileVersionId, userId, extension, mimeType, version "
                  + "from DLFileVersion where fileEntryId = "
                  + fileEntryId
                  + " order by version asc");

      rs = ps.executeQuery();

      while (rs.next()) {
        long fileVersionId = rs.getLong("fileVersionId");
        long userId = rs.getLong("userId");
        String extension = rs.getString("extension");
        String mimeType = rs.getString("mimeType");
        String version = rs.getString("version");

        if (_imageMimeTypes.contains(mimeType)) {
          DLFileVersion dlFileVersion = new DLFileVersionImpl();

          dlFileVersion.setFileVersionId(fileVersionId);
          dlFileVersion.setUserId(userId);
          dlFileVersion.setFileEntryId(fileEntryId);
          dlFileVersion.setExtension(extension);
          dlFileVersion.setMimeType(mimeType);
          dlFileVersion.setVersion(version);

          FileVersion fileVersion = new LiferayFileVersion(dlFileVersion);

          try {
            ImageProcessorUtil.generateImages(null, fileVersion);
          } catch (Exception e) {
            if (_log.isWarnEnabled()) {
              _log.warn("Unable to generate thumbnails for " + fileVersion.getFileVersionId(), e);
            }
          }
        }
      }
    } finally {
      DataAccess.cleanUp(con, ps, rs);
    }
  }
  private void _generateVideoXuggler(
      FileVersion fileVersion, File sourceFile, File[] destinationFiles) {

    try {
      for (int i = 0; i < destinationFiles.length; i++) {
        _generateVideoXuggler(fileVersion, sourceFile, destinationFiles[i], _PREVIEW_TYPES[i]);
      }
    } catch (CancellationException ce) {
      if (_log.isInfoEnabled()) {
        _log.info(
            "Cancellation received for "
                + fileVersion.getFileVersionId()
                + " "
                + fileVersion.getTitle());
      }
    } catch (Exception e) {
      _log.error(e, e);
    }
  }
  private void _generateImages(FileVersion fileVersion) throws Exception {

    try {
      if (_hasImages(fileVersion)) {
        return;
      }

      String extension = fileVersion.getExtension();

      if (extension.equals("pdf")) {
        if (fileVersion instanceof LiferayFileVersion) {
          try {
            LiferayFileVersion liferayFileVersion = (LiferayFileVersion) fileVersion;

            File file = liferayFileVersion.getFile(false);

            _generateImages(fileVersion, file);

            return;
          } catch (UnsupportedOperationException uoe) {
          }
        }

        InputStream inputStream = fileVersion.getContentStream(false);

        _generateImages(fileVersion, inputStream);
      } else if (DocumentConversionUtil.isEnabled()) {
        InputStream inputStream = fileVersion.getContentStream(false);

        String tempFileId =
            DLUtil.getTempFileId(fileVersion.getFileEntryId(), fileVersion.getVersion());

        File file = DocumentConversionUtil.convert(tempFileId, inputStream, extension, "pdf");

        _generateImages(fileVersion, file);
      }
    } catch (NoSuchFileEntryException nsfee) {
    } finally {
      _fileVersionIds.remove(fileVersion.getFileVersionId());
    }
  }
  private void _generateImagesPB(FileVersion fileVersion, File file) throws Exception {

    String tempFileId =
        DLUtil.getTempFileId(fileVersion.getFileEntryId(), fileVersion.getVersion());

    File thumbnailFile = getThumbnailTempFile(tempFileId);

    int previewFilesCount = 0;

    PDDocument pdDocument = null;

    try {
      pdDocument = PDDocument.load(file);

      previewFilesCount = pdDocument.getNumberOfPages();
    } finally {
      if (pdDocument != null) {
        pdDocument.close();
      }
    }

    File[] previewFiles = new File[previewFilesCount];

    for (int i = 0; i < previewFilesCount; i++) {
      previewFiles[i] = getPreviewTempFile(tempFileId, i);
    }

    boolean generatePreview = _isGeneratePreview(fileVersion);
    boolean generateThumbnail = _isGenerateThumbnail(fileVersion);

    if (PropsValues.DL_FILE_ENTRY_PREVIEW_FORK_PROCESS_ENABLED) {
      ProcessCallable<String> processCallable =
          new LiferayPDFBoxProcessCallable(
              ServerDetector.getServerId(),
              PropsUtil.get(PropsKeys.LIFERAY_HOME),
              Log4JUtil.getCustomLogSettings(),
              file,
              thumbnailFile,
              previewFiles,
              getThumbnailType(fileVersion),
              getPreviewType(fileVersion),
              PropsValues.DL_FILE_ENTRY_PREVIEW_DOCUMENT_DPI,
              PropsValues.DL_FILE_ENTRY_PREVIEW_DOCUMENT_MAX_HEIGHT,
              PropsValues.DL_FILE_ENTRY_PREVIEW_DOCUMENT_MAX_WIDTH,
              generatePreview,
              generateThumbnail);

      Future<String> future =
          ProcessExecutor.execute(ClassPathUtil.getPortalClassPath(), processCallable);

      String processIdentity = String.valueOf(fileVersion.getFileVersionId());

      futures.put(processIdentity, future);

      future.get();
    } else {
      LiferayPDFBoxConverter liferayConverter =
          new LiferayPDFBoxConverter(
              file,
              thumbnailFile,
              previewFiles,
              getPreviewType(fileVersion),
              getThumbnailType(fileVersion),
              PropsValues.DL_FILE_ENTRY_PREVIEW_DOCUMENT_DPI,
              PropsValues.DL_FILE_ENTRY_PREVIEW_DOCUMENT_MAX_HEIGHT,
              PropsValues.DL_FILE_ENTRY_PREVIEW_DOCUMENT_MAX_WIDTH,
              generatePreview,
              generateThumbnail);

      liferayConverter.generateImagesPB();
    }

    if (generateThumbnail) {
      try {
        storeThumbnailImages(fileVersion, thumbnailFile);
      } finally {
        FileUtil.delete(thumbnailFile);
      }

      if (_log.isInfoEnabled()) {
        _log.info("PDFBox generated a thumbnail for " + fileVersion.getFileVersionId());
      }
    }

    if (generatePreview) {
      int index = 0;

      for (File previewFile : previewFiles) {
        try {
          addFileToStore(
              fileVersion.getCompanyId(), PREVIEW_PATH,
              getPreviewFilePath(fileVersion, index + 1), previewFile);
        } finally {
          FileUtil.delete(previewFile);
        }

        index++;
      }

      if (_log.isInfoEnabled()) {
        _log.info(
            "PDFBox generated "
                + getPreviewFileCount(fileVersion)
                + " preview pages for "
                + fileVersion.getFileVersionId());
      }
    }
  }
  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);
    }
  }
  private void _generateVideoXuggler(
      FileVersion fileVersion, File sourceFile, File destinationFile, String containerType)
      throws Exception {

    if (hasPreview(fileVersion, containerType)) {
      return;
    }

    StopWatch stopWatch = new StopWatch();

    stopWatch.start();

    if (PropsValues.DL_FILE_ENTRY_PREVIEW_FORK_PROCESS_ENABLED) {
      ProcessCallable<String> processCallable =
          new LiferayVideoProcessCallable(
              ServerDetector.getServerId(),
              PropsUtil.get(PropsKeys.LIFERAY_HOME),
              Log4JUtil.getCustomLogSettings(),
              sourceFile,
              destinationFile,
              containerType,
              PropsUtil.getProperties(PropsKeys.DL_FILE_ENTRY_PREVIEW_VIDEO, false),
              PropsUtil.getProperties(PropsKeys.XUGGLER_FFPRESET, true));

      ProcessChannel<String> processChannel =
          ProcessExecutorUtil.execute(ClassPathUtil.getPortalProcessConfig(), processCallable);

      Future<String> future = processChannel.getProcessNoticeableFuture();

      String processIdentity = String.valueOf(fileVersion.getFileVersionId());

      futures.put(processIdentity, future);

      future.get();
    } else {
      LiferayConverter liferayConverter =
          new LiferayVideoConverter(
              sourceFile.getCanonicalPath(),
              destinationFile.getCanonicalPath(),
              containerType,
              PropsUtil.getProperties(PropsKeys.DL_FILE_ENTRY_PREVIEW_VIDEO, false),
              PropsUtil.getProperties(PropsKeys.XUGGLER_FFPRESET, true));

      liferayConverter.convert();
    }

    addFileToStore(
        fileVersion.getCompanyId(), PREVIEW_PATH,
        getPreviewFilePath(fileVersion, containerType), destinationFile);

    if (_log.isInfoEnabled()) {
      _log.info(
          "Xuggler generated a "
              + containerType
              + " preview video for "
              + fileVersion.getTitle()
              + " in "
              + stopWatch.getTime()
              + " ms");
    }
  }
  private void _generateVideo(FileVersion sourceFileVersion, FileVersion destinationFileVersion)
      throws Exception {

    if (!XugglerUtil.isEnabled() || _hasVideo(destinationFileVersion)) {
      return;
    }

    InputStream inputStream = null;

    File[] previewTempFiles = new File[_PREVIEW_TYPES.length];

    File videoTempFile = null;

    try {
      if (sourceFileVersion != null) {
        copy(sourceFileVersion, destinationFileVersion);

        return;
      }

      File file = null;

      if (!hasPreviews(destinationFileVersion) || !hasThumbnails(destinationFileVersion)) {

        if (destinationFileVersion instanceof LiferayFileVersion) {
          try {
            LiferayFileVersion liferayFileVersion = (LiferayFileVersion) destinationFileVersion;

            file = liferayFileVersion.getFile(false);
          } catch (UnsupportedOperationException uoe) {
          }
        }

        if (file == null) {
          inputStream = destinationFileVersion.getContentStream(false);

          videoTempFile = FileUtil.createTempFile(destinationFileVersion.getExtension());

          FileUtil.write(videoTempFile, inputStream);

          file = videoTempFile;
        }
      }

      if (!hasPreviews(destinationFileVersion)) {
        String tempFileId =
            DLUtil.getTempFileId(
                destinationFileVersion.getFileEntryId(), destinationFileVersion.getVersion());

        for (int i = 0; i < _PREVIEW_TYPES.length; i++) {
          previewTempFiles[i] = getPreviewTempFile(tempFileId, _PREVIEW_TYPES[i]);
        }

        try {
          _generateVideoXuggler(destinationFileVersion, file, previewTempFiles);
        } catch (Exception e) {
          _log.error(e, e);
        }
      }

      if (!hasThumbnails(destinationFileVersion)) {
        try {
          _generateThumbnailXuggler(
              destinationFileVersion,
              file,
              PropsValues.DL_FILE_ENTRY_PREVIEW_VIDEO_HEIGHT,
              PropsValues.DL_FILE_ENTRY_PREVIEW_VIDEO_WIDTH);
        } catch (Exception e) {
          _log.error(e, e);
        }
      }
    } catch (NoSuchFileEntryException nsfee) {
      if (_log.isDebugEnabled()) {
        _log.debug(nsfee, nsfee);
      }
    } finally {
      StreamUtil.cleanUp(inputStream);

      _fileVersionIds.remove(destinationFileVersion.getFileVersionId());

      for (int i = 0; i < previewTempFiles.length; i++) {
        FileUtil.delete(previewTempFiles[i]);
      }

      FileUtil.delete(videoTempFile);
    }
  }
  private void _generateImagesGS(FileVersion fileVersion, File file, boolean thumbnail)
      throws Exception {

    // Generate images

    String tempFileId =
        DLUtil.getTempFileId(fileVersion.getFileEntryId(), fileVersion.getVersion());

    List<String> arguments = new ArrayList<String>();

    arguments.add("-sDEVICE=png16m");

    if (thumbnail) {
      arguments.add("-sOutputFile=" + getThumbnailTempFilePath(tempFileId));
      arguments.add("-dFirstPage=1");
      arguments.add("-dLastPage=1");
    } else {
      arguments.add("-sOutputFile=" + getPreviewTempFilePath(tempFileId, -1));
    }

    arguments.add("-dPDFFitPage");
    arguments.add("-dTextAlphaBits=4");
    arguments.add("-dGraphicsAlphaBits=4");
    arguments.add("-r" + PropsValues.DL_FILE_ENTRY_PREVIEW_DOCUMENT_DPI);

    if (PropsValues.DL_FILE_ENTRY_PREVIEW_DOCUMENT_MAX_WIDTH != 0) {
      arguments.add("-dDEVICEWIDTH" + PropsValues.DL_FILE_ENTRY_PREVIEW_DOCUMENT_MAX_WIDTH);
    }

    if (PropsValues.DL_FILE_ENTRY_PREVIEW_DOCUMENT_MAX_HEIGHT != 0) {
      arguments.add("-dDEVICEHEIGHT" + PropsValues.DL_FILE_ENTRY_PREVIEW_DOCUMENT_MAX_HEIGHT);
    }

    arguments.add(file.getPath());

    Future<?> future = GhostscriptUtil.execute(arguments);

    String processIdentity = String.valueOf(fileVersion.getFileVersionId());

    futures.put(processIdentity, future);

    future.get();

    // Store images

    if (thumbnail) {
      File thumbnailTempFile = getThumbnailTempFile(tempFileId);

      try {
        storeThumbnailImages(fileVersion, thumbnailTempFile);
      } finally {
        FileUtil.delete(thumbnailTempFile);
      }
    } else {
      int total = getPreviewTempFileCount(fileVersion);

      for (int i = 0; i < total; i++) {
        File previewTempFile = getPreviewTempFile(tempFileId, i + 2);

        try {
          addFileToStore(
              fileVersion.getCompanyId(),
              PREVIEW_PATH,
              getPreviewFilePath(fileVersion, i + 1),
              previewTempFile);
        } finally {
          FileUtil.delete(previewTempFile);
        }
      }
    }
  }
  private void _generateThumbnailXuggler(FileVersion fileVersion, File file, int height, int width)
      throws Exception {

    StopWatch stopWatch = new StopWatch();

    stopWatch.start();

    String tempFileId =
        DLUtil.getTempFileId(fileVersion.getFileEntryId(), fileVersion.getVersion());

    File thumbnailTempFile = getThumbnailTempFile(tempFileId);

    try {
      try {
        if (PropsValues.DL_FILE_ENTRY_PREVIEW_FORK_PROCESS_ENABLED) {
          ProcessCallable<String> processCallable =
              new LiferayVideoThumbnailProcessCallable(
                  ServerDetector.getServerId(),
                  PropsUtil.get(PropsKeys.LIFERAY_HOME),
                  Log4JUtil.getCustomLogSettings(),
                  file,
                  thumbnailTempFile,
                  THUMBNAIL_TYPE,
                  height,
                  width,
                  PropsValues.DL_FILE_ENTRY_THUMBNAIL_VIDEO_FRAME_PERCENTAGE);

          ProcessChannel<String> processChannel =
              ProcessExecutorUtil.execute(ClassPathUtil.getPortalProcessConfig(), processCallable);

          Future<String> future = processChannel.getProcessNoticeableFuture();

          String processIdentity = String.valueOf(fileVersion.getFileVersionId());

          futures.put(processIdentity, future);

          future.get();
        } else {
          LiferayConverter liferayConverter =
              new LiferayVideoThumbnailConverter(
                  file.getCanonicalPath(),
                  thumbnailTempFile,
                  THUMBNAIL_TYPE,
                  height,
                  width,
                  PropsValues.DL_FILE_ENTRY_THUMBNAIL_VIDEO_FRAME_PERCENTAGE);

          liferayConverter.convert();
        }
      } catch (CancellationException ce) {
        if (_log.isInfoEnabled()) {
          _log.info(
              "Cancellation received for "
                  + fileVersion.getFileVersionId()
                  + " "
                  + fileVersion.getTitle());
        }
      } catch (Exception e) {
        _log.error(e, e);
      }

      storeThumbnailImages(fileVersion, thumbnailTempFile);

      if (_log.isInfoEnabled()) {
        _log.info(
            "Xuggler generated a thumbnail for "
                + fileVersion.getTitle()
                + " in "
                + stopWatch.getTime()
                + " ms");
      }
    } catch (Exception e) {
      throw new SystemException(e);
    } finally {
      FileUtil.delete(thumbnailTempFile);
    }
  }