protected String getBody(String className, long classPK, ServiceContext serviceContext)
      throws Exception {

    StringBundler sb = new StringBundler(11);

    sb.append("<div class=\"activity-body document\">");
    sb.append("<span class=\"document-thumbnail\"><img src=\"");

    FileEntry fileEntry = DLAppLocalServiceUtil.getFileEntry(classPK);

    FileVersion fileVersion = fileEntry.getFileVersion();

    String thumbnailSrc =
        DLUtil.getThumbnailSrc(fileEntry, fileVersion, null, serviceContext.getThemeDisplay());

    sb.append(thumbnailSrc);
    sb.append("\"></span>");
    sb.append("<div class=\"document-container\"><div class=\"title\">");
    sb.append(getPageTitle(className, classPK, serviceContext));
    sb.append("</div><div class=\"version\">");
    sb.append(serviceContext.translate("version-x", fileVersion.getVersion()));
    sb.append("</div><div class=\"document-content\">");

    AssetRenderer assetRenderer = getAssetRenderer(className, classPK);

    sb.append(StringUtil.shorten(assetRenderer.getSummary(serviceContext.getLocale()), 200));

    sb.append("</div></div></div>");

    return sb.toString();
  }
示例#2
0
  protected int getPreviewTempFileCount(FileVersion fileVersion, String type) {

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

    StringBundler sb = new StringBundler(5);

    sb.append(tempFileId);
    sb.append(StringPool.DASH);
    sb.append("(.*)");
    sb.append(StringPool.PERIOD);
    sb.append(type);

    File dir = new File(PREVIEW_TMP_PATH);

    File[] files = dir.listFiles(new FileFilter(sb.toString()));

    if (_log.isDebugEnabled()) {
      for (File file : files) {
        _log.debug("Preview page for " + tempFileId + " " + file);
      }
    }

    return files.length;
  }
  private void _generateImagesPB(
      FileVersion fileVersion,
      PDPage pdPage,
      int dpi,
      int height,
      int width,
      boolean thumbnail,
      int index)
      throws Exception {

    // Generate images

    RenderedImage renderedImage =
        pdPage.convertToImage(BufferedImage.TYPE_INT_RGB, PropsValues.DL_FILE_ENTRY_THUMBNAIL_DPI);

    if (height != 0) {
      renderedImage = ImageProcessorUtil.scale(renderedImage, width, height);
    } else {
      renderedImage = ImageProcessorUtil.scale(renderedImage, width);
    }

    // Store images

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

    File thumbnailTempFile = null;

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

        thumbnailTempFile.createNewFile();

        ImageIO.write(renderedImage, THUMBNAIL_TYPE, new FileOutputStream(thumbnailTempFile));

        addFileToStore(
            fileVersion.getCompanyId(), THUMBNAIL_PATH,
            getThumbnailFilePath(fileVersion), thumbnailTempFile);
      } else {
        thumbnailTempFile = getPreviewTempFile(tempFileId, index);

        thumbnailTempFile.createNewFile();

        ImageIO.write(renderedImage, PREVIEW_TYPE, new FileOutputStream(thumbnailTempFile));

        addFileToStore(
            fileVersion.getCompanyId(), PREVIEW_PATH,
            getPreviewFilePath(fileVersion, index), thumbnailTempFile);
      }
    } finally {
      FileUtil.delete(thumbnailTempFile);
    }
  }
  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());
    }
  }
  protected void testVersionUpdate(
      String addFileName,
      byte[] addBytes,
      String addMimeType,
      String updateFileName,
      byte[] updateBytes,
      String updateMimeType)
      throws PortalException, SystemException {

    String description = StringPool.BLANK;
    String changeLog = StringPool.BLANK;

    ServiceContext serviceContext = ServiceTestUtil.getServiceContext(group.getGroupId());

    FileEntry fileEntry =
        DLAppServiceUtil.addFileEntry(
            group.getGroupId(),
            parentFolder.getFolderId(),
            addFileName,
            addMimeType,
            addFileName,
            description,
            changeLog,
            addBytes,
            serviceContext);

    fileEntry =
        DLAppServiceUtil.updateFileEntry(
            fileEntry.getFileEntryId(),
            updateFileName,
            updateMimeType,
            updateFileName,
            description,
            changeLog,
            false,
            updateBytes,
            serviceContext);

    FileVersion fileVersion = fileEntry.getFileVersion();

    Assert.assertEquals(DLFileEntryConstants.VERSION_DEFAULT, fileVersion.getVersion());
    Assert.assertEquals(updateMimeType, fileVersion.getMimeType());
    Assert.assertEquals(updateBytes.length, fileVersion.getSize());
    Assert.assertEquals(fileVersion.getExtension(), fileEntry.getExtension());
    Assert.assertEquals(fileVersion.getMimeType(), fileEntry.getMimeType());
    Assert.assertEquals(fileVersion.getSize(), fileEntry.getSize());
  }
  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());
    }
  }
  public void updateFileEntry(
      long userId,
      FileEntry fileEntry,
      FileVersion sourceFileVersion,
      FileVersion destinationFileVersion,
      long assetClassPk)
      throws PortalException, SystemException {

    boolean updateAsset = true;

    if (fileEntry instanceof LiferayFileEntry
        && fileEntry.getVersion().equals(destinationFileVersion.getVersion())) {

      updateAsset = false;
    }

    if (updateAsset) {
      updateAsset(userId, fileEntry, destinationFileVersion, assetClassPk);
    }

    registerDLProcessorCallback(fileEntry, sourceFileVersion);
  }
  public static String getPreviewURL(
      FileEntry fileEntry,
      FileVersion fileVersion,
      ThemeDisplay themeDisplay,
      String queryString,
      boolean appendToken) {

    StringBundler sb = new StringBundler(13);

    sb.append(themeDisplay.getPortalURL());
    sb.append(themeDisplay.getPathContext());
    sb.append("/documents/");
    sb.append(fileEntry.getRepositoryId());
    sb.append(StringPool.SLASH);
    sb.append(fileEntry.getFolderId());
    sb.append(StringPool.SLASH);
    sb.append(HttpUtil.encodeURL(HtmlUtil.unescape(fileEntry.getTitle()), true));
    sb.append("?version=");
    sb.append(fileVersion.getVersion());

    if (appendToken) {
      sb.append("&t=");

      Date modifiedDate = fileVersion.getModifiedDate();

      sb.append(modifiedDate.getTime());
    }

    sb.append(queryString);

    String previewURL = sb.toString();

    if (themeDisplay.isAddSessionIdToURL()) {
      return PortalUtil.getURLWithSessionId(previewURL, themeDisplay.getSessionId());
    }

    return previewURL;
  }
  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 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 _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());
      }
    }
  }
  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 _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 _generateImagesIM(
      FileVersion fileVersion,
      File file,
      int depth,
      int dpi,
      int height,
      int width,
      boolean thumbnail)
      throws Exception {

    // Generate images

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

    IMOperation imOperation = new IMOperation();

    imOperation.alpha("off");

    imOperation.density(dpi, dpi);

    if (height != 0) {
      imOperation.adaptiveResize(width, height);
    } else {
      imOperation.adaptiveResize(width);
    }

    imOperation.depth(depth);

    if (thumbnail) {
      imOperation.addImage(file.getPath() + "[0]");
      imOperation.addImage(getThumbnailTempFilePath(tempFileId));
    } else {
      imOperation.addImage(file.getPath());
      imOperation.addImage(getPreviewTempFilePath(tempFileId, -1));
    }

    _convertCmd.run(imOperation);

    // Store images

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

      try {
        addFileToStore(
            fileVersion.getCompanyId(), THUMBNAIL_PATH,
            getThumbnailFilePath(fileVersion), thumbnailTempFile);
      } finally {
        FileUtil.delete(thumbnailTempFile);
      }
    } else {

      // ImageMagick converts single page PDFs without appending an
      // index. Rename file for consistency.

      File singlePagePreviewFile = getPreviewTempFile(tempFileId, -1);

      if (singlePagePreviewFile.exists()) {
        singlePagePreviewFile.renameTo(getPreviewTempFile(tempFileId, 1));
      }

      int total = getPreviewTempFileCount(fileVersion);

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

        try {
          addFileToStore(
              fileVersion.getCompanyId(),
              PREVIEW_PATH,
              getPreviewFilePath(fileVersion, i + 1),
              previewTempFile);
        } finally {
          FileUtil.delete(previewTempFile);
        }
      }
    }
  }
示例#15
0
  @Override
  public String getPreviewURL(
      FileEntry fileEntry,
      FileVersion fileVersion,
      ThemeDisplay themeDisplay,
      String queryString,
      boolean appendVersion,
      boolean absoluteURL) {

    StringBundler sb = new StringBundler(17);

    if (themeDisplay != null) {
      if (absoluteURL) {
        sb.append(themeDisplay.getPortalURL());
      }
    }

    sb.append(PortalUtil.getPathContext());
    sb.append("/documents/");
    sb.append(fileEntry.getRepositoryId());
    sb.append(StringPool.SLASH);
    sb.append(fileEntry.getFolderId());
    sb.append(StringPool.SLASH);

    String title = fileEntry.getTitle();

    if (fileEntry.isInTrash()) {
      title = TrashUtil.getOriginalTitle(fileEntry.getTitle());
    }

    sb.append(HttpUtil.encodeURL(HtmlUtil.unescape(title)));

    sb.append(StringPool.SLASH);
    sb.append(fileEntry.getUuid());

    if (appendVersion) {
      sb.append("?version=");
      sb.append(fileVersion.getVersion());
    }

    if (ImageProcessorUtil.isImageSupported(fileVersion)) {
      if (appendVersion) {
        sb.append("&t=");
      } else {
        sb.append("?t=");
      }

      Date modifiedDate = fileVersion.getModifiedDate();

      sb.append(modifiedDate.getTime());
    }

    sb.append(queryString);

    if (themeDisplay != null) {
      PortletDisplay portletDisplay = themeDisplay.getPortletDisplay();

      if (portletDisplay != null) {
        String portletId = portletDisplay.getId();

        if (portletId.equals(PortletKeys.TRASH)) {
          sb.append("&status=");
          sb.append(WorkflowConstants.STATUS_IN_TRASH);
        }
      }
    }

    String previewURL = sb.toString();

    if ((themeDisplay != null) && themeDisplay.isAddSessionIdToURL()) {
      return PortalUtil.getURLWithSessionId(previewURL, themeDisplay.getSessionId());
    }

    return previewURL;
  }
  @Override
  protected void doImportStagedModel(PortletDataContext portletDataContext, FileEntry fileEntry)
      throws Exception {

    long userId = portletDataContext.getUserId(fileEntry.getUserUuid());

    if (!fileEntry.isDefaultRepository()) {

      // References has been automatically imported, nothing to do here

      return;
    }

    Map<Long, Long> folderIds =
        (Map<Long, Long>) portletDataContext.getNewPrimaryKeysMap(Folder.class);

    long folderId = MapUtil.getLong(folderIds, fileEntry.getFolderId(), fileEntry.getFolderId());

    long[] assetCategoryIds =
        portletDataContext.getAssetCategoryIds(DLFileEntry.class, fileEntry.getFileEntryId());
    String[] assetTagNames =
        portletDataContext.getAssetTagNames(DLFileEntry.class, fileEntry.getFileEntryId());

    ServiceContext serviceContext =
        portletDataContext.createServiceContext(fileEntry, DLFileEntry.class);

    serviceContext.setAttribute("sourceFileName", "A." + fileEntry.getExtension());
    serviceContext.setUserId(userId);

    Element fileEntryElement = portletDataContext.getImportDataElement(fileEntry);

    String binPath = fileEntryElement.attributeValue("bin-path");

    InputStream is = null;

    if (Validator.isNull(binPath) && portletDataContext.isPerformDirectBinaryImport()) {

      try {
        is = FileEntryUtil.getContentStream(fileEntry);
      } catch (Exception e) {
        if (_log.isWarnEnabled()) {
          _log.warn("Unable to retrieve content for file entry " + fileEntry.getFileEntryId(), e);
        }

        return;
      }
    } else {
      is = portletDataContext.getZipEntryAsInputStream(binPath);
    }

    if (is == null) {
      if (_log.isWarnEnabled()) {
        _log.warn("No file found for file entry " + fileEntry.getFileEntryId());
      }

      return;
    }

    importMetaData(portletDataContext, fileEntryElement, fileEntry, serviceContext);

    FileEntry importedFileEntry = null;

    String titleWithExtension = DLUtil.getTitleWithExtension(fileEntry);
    String extension = fileEntry.getExtension();

    String periodAndExtension = StringPool.PERIOD.concat(extension);

    if (portletDataContext.isDataStrategyMirror()) {
      FileEntry existingFileEntry =
          fetchStagedModelByUuidAndGroupId(
              fileEntry.getUuid(), portletDataContext.getScopeGroupId());

      FileVersion fileVersion = fileEntry.getFileVersion();

      if (existingFileEntry == null) {
        String fileEntryTitle = fileEntry.getTitle();

        FileEntry existingTitleFileEntry =
            FileEntryUtil.fetchByR_F_T(
                portletDataContext.getScopeGroupId(), folderId, fileEntryTitle);

        if (existingTitleFileEntry != null) {
          if ((fileEntry.getGroupId() == portletDataContext.getSourceGroupId())
              && portletDataContext.isDataStrategyMirrorWithOverwriting()) {

            DLAppLocalServiceUtil.deleteFileEntry(existingTitleFileEntry.getFileEntryId());
          } else {
            boolean titleHasExtension = false;

            if (fileEntryTitle.endsWith(periodAndExtension)) {
              fileEntryTitle = FileUtil.stripExtension(fileEntryTitle);

              titleHasExtension = true;
            }

            for (int i = 1; ; i++) {
              fileEntryTitle += StringPool.SPACE + i;

              titleWithExtension = fileEntryTitle + periodAndExtension;

              existingTitleFileEntry =
                  FileEntryUtil.fetchByR_F_T(
                      portletDataContext.getScopeGroupId(), folderId, titleWithExtension);

              if (existingTitleFileEntry == null) {
                if (titleHasExtension) {
                  fileEntryTitle += periodAndExtension;
                }

                break;
              }
            }
          }
        }

        serviceContext.setAttribute("fileVersionUuid", fileVersion.getUuid());
        serviceContext.setUuid(fileEntry.getUuid());

        importedFileEntry =
            DLAppLocalServiceUtil.addFileEntry(
                userId,
                portletDataContext.getScopeGroupId(),
                folderId,
                titleWithExtension,
                fileEntry.getMimeType(),
                fileEntryTitle,
                fileEntry.getDescription(),
                null,
                is,
                fileEntry.getSize(),
                serviceContext);

        if (fileEntry.isInTrash()) {
          importedFileEntry =
              DLAppServiceUtil.moveFileEntryToTrash(importedFileEntry.getFileEntryId());
        }
      } else {
        FileVersion latestExistingFileVersion = existingFileEntry.getLatestFileVersion(true);

        boolean indexEnabled = serviceContext.isIndexingEnabled();

        boolean deleteFileEntry = false;
        boolean updateFileEntry = false;

        if (!Validator.equals(fileVersion.getUuid(), latestExistingFileVersion.getUuid())) {

          deleteFileEntry = true;
          updateFileEntry = true;
        } else {
          InputStream existingFileVersionInputStream = null;

          try {
            existingFileVersionInputStream = latestExistingFileVersion.getContentStream(false);
          } catch (Exception e) {
            if (_log.isDebugEnabled()) {
              _log.debug(e, e);
            }
          } finally {
            if (existingFileVersionInputStream != null) {
              existingFileVersionInputStream.close();
            }
          }

          if (existingFileVersionInputStream == null) {
            updateFileEntry = true;
          }
        }

        try {
          serviceContext.setIndexingEnabled(false);

          if (updateFileEntry) {
            DLFileVersion alreadyExistingFileVersion =
                DLFileVersionLocalServiceUtil.getFileVersionByUuidAndGroupId(
                    fileVersion.getUuid(), existingFileEntry.getGroupId());

            if (alreadyExistingFileVersion != null) {
              serviceContext.setAttribute(
                  "existingDLFileVersionId", alreadyExistingFileVersion.getFileVersionId());
            }

            serviceContext.setUuid(fileVersion.getUuid());

            importedFileEntry =
                DLAppLocalServiceUtil.updateFileEntry(
                    userId,
                    existingFileEntry.getFileEntryId(),
                    titleWithExtension,
                    fileEntry.getMimeType(),
                    fileEntry.getTitle(),
                    fileEntry.getDescription(),
                    null,
                    false,
                    is,
                    fileEntry.getSize(),
                    serviceContext);
          } else {
            DLAppLocalServiceUtil.updateAsset(
                userId, existingFileEntry,
                latestExistingFileVersion, assetCategoryIds,
                assetTagNames, null);

            importedFileEntry = existingFileEntry;
          }

          if (importedFileEntry.getFolderId() != folderId) {
            importedFileEntry =
                DLAppLocalServiceUtil.moveFileEntry(
                    userId, importedFileEntry.getFileEntryId(), folderId, serviceContext);
          }

          if (importedFileEntry instanceof LiferayFileEntry) {
            LiferayFileEntry liferayFileEntry = (LiferayFileEntry) importedFileEntry;

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

            indexer.reindex((DLFileEntry) liferayFileEntry.getModel());
          }

          if (deleteFileEntry && ExportImportThreadLocal.isStagingInProcess()) {

            DLAppServiceUtil.deleteFileVersion(
                latestExistingFileVersion.getFileEntryId(), latestExistingFileVersion.getVersion());
          }
        } finally {
          serviceContext.setIndexingEnabled(indexEnabled);
        }
      }
    } else {
      try {
        importedFileEntry =
            DLAppLocalServiceUtil.addFileEntry(
                userId,
                portletDataContext.getScopeGroupId(),
                folderId,
                titleWithExtension,
                fileEntry.getMimeType(),
                fileEntry.getTitle(),
                fileEntry.getDescription(),
                null,
                is,
                fileEntry.getSize(),
                serviceContext);
      } catch (DuplicateFileException dfe) {
        String title = fileEntry.getTitle();

        String[] titleParts = title.split("\\.", 2);

        title = titleParts[0] + StringUtil.randomString();

        if (titleParts.length > 1) {
          title += StringPool.PERIOD + titleParts[1];
        }

        if (!title.endsWith(periodAndExtension)) {
          title += periodAndExtension;
        }

        importedFileEntry =
            DLAppLocalServiceUtil.addFileEntry(
                userId,
                portletDataContext.getScopeGroupId(),
                folderId,
                title,
                fileEntry.getMimeType(),
                title,
                fileEntry.getDescription(),
                null,
                is,
                fileEntry.getSize(),
                serviceContext);
      }
    }

    if (portletDataContext.getBooleanParameter(
        DLPortletDataHandler.NAMESPACE, "previews-and-thumbnails")) {

      DLProcessorRegistryUtil.importGeneratedFiles(
          portletDataContext, fileEntry, importedFileEntry, fileEntryElement);
    }

    portletDataContext.importClassedModel(fileEntry, importedFileEntry, DLFileEntry.class);

    Map<Long, Long> fileEntryIds =
        (Map<Long, Long>) portletDataContext.getNewPrimaryKeysMap(FileEntry.class);

    fileEntryIds.put(fileEntry.getFileEntryId(), importedFileEntry.getFileEntryId());
  }
  protected void compareVersions(RenderRequest renderRequest) throws Exception {

    long sourceFileVersionId = ParamUtil.getLong(renderRequest, "sourceFileVersionId");
    long targetFileVersionId = ParamUtil.getLong(renderRequest, "targetFileVersionId");

    FileVersion sourceFileVersion = _dlAppService.getFileVersion(sourceFileVersionId);

    InputStream sourceIs = sourceFileVersion.getContentStream(false);

    String sourceExtension = sourceFileVersion.getExtension();

    if (sourceExtension.equals("css")
        || sourceExtension.equals("htm")
        || sourceExtension.equals("html")
        || sourceExtension.equals("js")
        || sourceExtension.equals("txt")
        || sourceExtension.equals("xml")) {

      String sourceContent = HtmlUtil.escape(StringUtil.read(sourceIs));

      sourceIs = new UnsyncByteArrayInputStream(sourceContent.getBytes(StringPool.UTF8));
    }

    FileVersion targetFileVersion = _dlAppLocalService.getFileVersion(targetFileVersionId);

    InputStream targetIs = targetFileVersion.getContentStream(false);

    String targetExtension = targetFileVersion.getExtension();

    if (targetExtension.equals("css")
        || targetExtension.equals("htm")
        || targetExtension.equals("html")
        || targetExtension.equals("js")
        || targetExtension.equals("txt")
        || targetExtension.equals("xml")) {

      String targetContent = HtmlUtil.escape(StringUtil.read(targetIs));

      targetIs = new UnsyncByteArrayInputStream(targetContent.getBytes(StringPool.UTF8));
    }

    if (DocumentConversionUtil.isEnabled()) {
      if (DocumentConversionUtil.isConvertBeforeCompare(sourceExtension)) {

        String sourceTempFileId =
            DLUtil.getTempFileId(
                sourceFileVersion.getFileEntryId(), sourceFileVersion.getVersion());

        sourceIs =
            new FileInputStream(
                DocumentConversionUtil.convert(sourceTempFileId, sourceIs, sourceExtension, "txt"));
      }

      if (DocumentConversionUtil.isConvertBeforeCompare(targetExtension)) {

        String targetTempFileId =
            DLUtil.getTempFileId(
                targetFileVersion.getFileEntryId(), targetFileVersion.getVersion());

        targetIs =
            new FileInputStream(
                DocumentConversionUtil.convert(targetTempFileId, targetIs, targetExtension, "txt"));
      }
    }

    List<DiffResult>[] diffResults =
        DiffUtil.diff(new InputStreamReader(sourceIs), new InputStreamReader(targetIs));

    renderRequest.setAttribute(
        WebKeys.SOURCE_NAME,
        sourceFileVersion.getTitle() + StringPool.SPACE + sourceFileVersion.getVersion());
    renderRequest.setAttribute(
        WebKeys.TARGET_NAME,
        targetFileVersion.getTitle() + StringPool.SPACE + targetFileVersion.getVersion());
    renderRequest.setAttribute(WebKeys.DIFF_RESULTS, diffResults);
  }
  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);
    }
  }