@Override
  @SystemEvent(action = SystemEventConstants.ACTION_SKIP, type = SystemEventConstants.TYPE_DELETE)
  public void deleteFileEntryType(DLFileEntryType dlFileEntryType) throws PortalException {

    if (dlFileEntryPersistence.countByFileEntryTypeId(dlFileEntryType.getFileEntryTypeId()) > 0) {

      throw new RequiredFileEntryTypeException();
    }

    DDMStructure ddmStructure =
        ddmStructureLocalService.fetchStructure(
            dlFileEntryType.getGroupId(),
            classNameLocalService.getClassNameId(DLFileEntryMetadata.class),
            DLUtil.getDDMStructureKey(dlFileEntryType));

    if (ddmStructure == null) {
      ddmStructure =
          ddmStructureLocalService.fetchStructure(
              dlFileEntryType.getGroupId(),
              classNameLocalService.getClassNameId(DLFileEntryMetadata.class),
              DLUtil.getDeprecatedDDMStructureKey(dlFileEntryType));
    }

    if (ddmStructure != null) {
      ddmStructureLocalService.deleteStructure(ddmStructure.getStructureId());
    }

    dlFileEntryTypePersistence.remove(dlFileEntryType);
  }
  protected void updateFileEntryFileNames() throws Exception {
    Connection con = null;
    PreparedStatement ps = null;
    ResultSet rs = null;

    try {
      con = DataAccess.getUpgradeOptimizedConnection();

      ps =
          con.prepareStatement(
              "select fileEntryId, groupId, folderId, extension, title, "
                  + "version from DLFileEntry");

      rs = ps.executeQuery();

      while (rs.next()) {
        long fileEntryId = rs.getLong("fileEntryId");
        long groupId = rs.getLong("groupId");
        long folderId = rs.getLong("folderId");
        String extension = GetterUtil.getString(rs.getString("extension"));
        String title = GetterUtil.getString(rs.getString("title"));
        String version = rs.getString("version");

        String uniqueFileName = DLUtil.getSanitizedFileName(title, extension);

        String titleExtension = StringPool.BLANK;
        String titleWithoutExtension = title;

        if (title.endsWith(StringPool.PERIOD + extension)) {
          titleExtension = extension;
          titleWithoutExtension = FileUtil.stripExtension(title);
        }

        String uniqueTitle = StringPool.BLANK;

        for (int i = 1; ; i++) {
          if (!hasFileEntry(groupId, folderId, uniqueFileName)) {
            break;
          }

          uniqueTitle = titleWithoutExtension + StringPool.UNDERLINE + String.valueOf(i);

          if (Validator.isNotNull(titleExtension)) {
            uniqueTitle += StringPool.PERIOD.concat(titleExtension);
          }

          uniqueFileName = DLUtil.getSanitizedFileName(uniqueTitle, extension);
        }

        updateFileEntryFileName(fileEntryId, uniqueFileName);

        if (Validator.isNotNull(uniqueTitle)) {
          updateFileEntryTitle(fileEntryId, uniqueTitle, version);
        }
      }
    } finally {
      DataAccess.cleanUp(con, ps, rs);
    }
  }
  protected void compareVersions(RenderRequest renderRequest) throws Exception {

    long fileEntryId = ParamUtil.getLong(renderRequest, "fileEntryId");

    String sourceVersion = ParamUtil.getString(renderRequest, "sourceVersion");
    String targetVersion = ParamUtil.getString(renderRequest, "targetVersion");

    FileEntry fileEntry = DLAppServiceUtil.getFileEntry(fileEntryId);

    String extension = fileEntry.getExtension();

    FileVersion sourceFileVersion = fileEntry.getFileVersion(sourceVersion);

    String sourceTitle = sourceFileVersion.getTitle();

    FileVersion targetFileVersion = fileEntry.getFileVersion(targetVersion);

    String targetTitle = targetFileVersion.getTitle();

    InputStream sourceIs = fileEntry.getContentStream(sourceVersion);
    InputStream targetIs = fileEntry.getContentStream(targetVersion);

    if (extension.equals("htm") || extension.equals("html") || extension.equals("xml")) {

      String escapedSource = HtmlUtil.escape(StringUtil.read(sourceIs));
      String escapedTarget = HtmlUtil.escape(StringUtil.read(targetIs));

      sourceIs = new UnsyncByteArrayInputStream(escapedSource.getBytes(StringPool.UTF8));
      targetIs = new UnsyncByteArrayInputStream(escapedTarget.getBytes(StringPool.UTF8));
    }

    if (DocumentConversionUtil.isEnabled()
        && DocumentConversionUtil.isConvertBeforeCompare(extension)) {

      String sourceTempFileId = DLUtil.getTempFileId(fileEntryId, sourceVersion);
      String targetTempFileId = DLUtil.getTempFileId(fileEntryId, targetVersion);

      sourceIs =
          new FileInputStream(
              DocumentConversionUtil.convert(sourceTempFileId, sourceIs, extension, "txt"));
      targetIs =
          new FileInputStream(
              DocumentConversionUtil.convert(targetTempFileId, targetIs, extension, "txt"));
    }

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

    renderRequest.setAttribute(WebKeys.SOURCE_NAME, sourceTitle + StringPool.SPACE + sourceVersion);
    renderRequest.setAttribute(WebKeys.TARGET_NAME, targetTitle + StringPool.SPACE + targetVersion);
    renderRequest.setAttribute(WebKeys.DIFF_RESULTS, diffResults);
  }
  @Test
  public void testGetFieldsFromContentWithDocumentLibraryElement() throws Exception {

    Fields expectedFields = new Fields();

    ServiceContext serviceContext =
        ServiceContextTestUtil.getServiceContext(group.getGroupId(), TestPropsValues.getUserId());

    FileEntry fileEntry =
        DLAppLocalServiceUtil.addFileEntry(
            TestPropsValues.getUserId(),
            group.getGroupId(),
            DLFolderConstants.DEFAULT_PARENT_FOLDER_ID,
            "Test 1.txt",
            ContentTypes.TEXT_PLAIN,
            RandomTestUtil.randomBytes(),
            serviceContext);

    Field documentLibraryField = getDocumentLibraryField(fileEntry, _ddmStructure.getStructureId());

    expectedFields.put(documentLibraryField);

    Field fieldsDisplayField =
        getFieldsDisplayField(_ddmStructure.getStructureId(), "document_library_INSTANCE_4aGOvP3N");

    expectedFields.put(fieldsDisplayField);

    String content = read("test-journal-content-doc-library-field.xml");

    XPath xPathSelector = SAXReaderUtil.createXPath("//dynamic-content");

    Document document = SAXReaderUtil.read(content);

    Element element = (Element) xPathSelector.selectSingleNode(document);

    String[] previewURLs = new String[2];

    previewURLs[0] =
        DLUtil.getPreviewURL(
            fileEntry, fileEntry.getFileVersion(), null, StringPool.BLANK, true, true);
    previewURLs[1] =
        DLUtil.getPreviewURL(
            fileEntry, fileEntry.getFileVersion(), null, StringPool.BLANK, false, false);

    for (int i = 0; i < previewURLs.length; i++) {
      element.addCDATA(previewURLs[i]);

      Fields actualFields = JournalConverterUtil.getDDMFields(_ddmStructure, document.asXML());

      Assert.assertEquals(expectedFields, actualFields);
    }
  }
  protected void fixDDMStructureKey(String fileEntryTypeUuid, long fileEntryTypeId, long groupId) {

    DDMStructure ddmStructure =
        ddmStructureLocalService.fetchStructure(
            groupId,
            classNameLocalService.getClassNameId(DLFileEntryMetadata.class),
            DLUtil.getDeprecatedDDMStructureKey(fileEntryTypeId));

    if (ddmStructure != null) {
      ddmStructure.setStructureKey(DLUtil.getDDMStructureKey(fileEntryTypeUuid));

      ddmStructureLocalService.updateDDMStructure(ddmStructure);
    }
  }
  @Override
  public String getSmallImageURL(ThemeDisplay themeDisplay) throws PortalException {

    if (Validator.isNotNull(getSmallImageURL())) {
      return getSmallImageURL();
    }

    long smallImageFileEntryId = getSmallImageFileEntryId();

    if (smallImageFileEntryId != 0) {
      FileEntry fileEntry = PortletFileRepositoryUtil.getPortletFileEntry(smallImageFileEntryId);

      return DLUtil.getPreviewURL(
          fileEntry, fileEntry.getFileVersion(), themeDisplay, StringPool.BLANK);
    }

    long smallImageId = getSmallImageId();

    if (smallImageId != 0) {
      return themeDisplay.getPathImage()
          + "/blogs/entry?img_id="
          + getSmallImageId()
          + "&t="
          + WebServerServletTokenUtil.getToken(getSmallImageId());
    }

    return getCoverImageURL(themeDisplay);
  }
Exemple #7
0
  protected static String getPathSegment(
      long groupId, long fileEntryId, long fileVersionId, boolean preview) {

    StringBundler sb = null;

    if (fileVersionId > 0) {
      sb = new StringBundler(5);
    } else {
      sb = new StringBundler(3);
    }

    if (preview) {
      sb.append(PREVIEW_PATH);
    } else {
      sb.append(THUMBNAIL_PATH);
    }

    sb.append(groupId);
    sb.append(DLUtil.getDividedPath(fileEntryId));

    if (fileVersionId > 0) {
      sb.append(StringPool.SLASH);
      sb.append(fileVersionId);
    }

    return sb.toString();
  }
  public static String getThumbnailSrc(
      FileEntry fileEntry, DLFileShortcut fileShortcut, ThemeDisplay themeDisplay)
      throws Exception {

    FileVersion fileVersion = fileEntry.getFileVersion();

    StringBundler sb = new StringBundler(4);

    sb.append(themeDisplay.getPathThemeImages());
    sb.append("/file_system/large/");
    sb.append(DLUtil.getGenericName(fileEntry.getExtension()));
    sb.append(".png");

    String thumbnailSrc = sb.toString();

    if (fileShortcut == null) {
      String thumbnailQueryString = null;

      if (ImageProcessorUtil.hasImages(fileVersion)) {
        thumbnailQueryString = "&imageThumbnail=1";
      } else if (PDFProcessorUtil.hasImages(fileVersion)) {
        thumbnailQueryString = "&documentThumbnail=1";
      } else if (VideoProcessorUtil.hasVideo(fileVersion)) {
        thumbnailQueryString = "&videoThumbnail=1";
      }

      if (Validator.isNotNull(thumbnailQueryString)) {
        thumbnailSrc = getPreviewURL(fileEntry, fileVersion, themeDisplay, thumbnailQueryString);
      }
    }

    return thumbnailSrc;
  }
Exemple #9
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;
  }
  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();
  }
  @Override
  public String getURLImagePreview(PortletRequest portletRequest) throws Exception {

    ThemeDisplay themeDisplay = (ThemeDisplay) portletRequest.getAttribute(WebKeys.THEME_DISPLAY);

    return DLUtil.getImagePreviewURL(_fileEntry, _fileVersion, themeDisplay);
  }
  protected void updateFileVersionFileNames() throws Exception {
    Connection con = null;
    PreparedStatement ps = null;
    ResultSet rs = null;

    try {
      con = DataAccess.getUpgradeOptimizedConnection();

      ps = con.prepareStatement("select fileVersionId, extension, title from DLFileVersion");

      rs = ps.executeQuery();

      while (rs.next()) {
        long fileVersionId = rs.getLong("fileVersionId");
        String extension = GetterUtil.getString(rs.getString("extension"));
        String title = GetterUtil.getString(rs.getString("title"));

        String fileName = DLUtil.getSanitizedFileName(title, extension);

        updateFileVersionFileName(fileVersionId, fileName);
      }
    } finally {
      DataAccess.cleanUp(con, ps, rs);
    }
  }
  @Override
  public String getRestoreLink(PortletRequest portletRequest, long classPK)
      throws PortalException, SystemException {

    DLFileShortcut fileShortcut = DLFileShortcutLocalServiceUtil.getDLFileShortcut(classPK);

    return DLUtil.getDLControlPanelLink(portletRequest, fileShortcut.getFolderId());
  }
  @Override
  public String getRestoreMessage(PortletRequest portletRequest, long classPK)
      throws PortalException, SystemException {

    DLFileShortcut fileShortcut = DLFileShortcutLocalServiceUtil.getDLFileShortcut(classPK);

    return DLUtil.getAbsolutePath(portletRequest, fileShortcut.getFolderId());
  }
  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());
    }
  }
  @Override
  public String getThumbnailPath(PortletRequest portletRequest) throws Exception {

    ThemeDisplay themeDisplay = (ThemeDisplay) portletRequest.getAttribute(WebKeys.THEME_DISPLAY);

    String thumbnailSrc = DLUtil.getThumbnailSrc(_fileEntry, themeDisplay);

    if (Validator.isNotNull(thumbnailSrc)) {
      return thumbnailSrc;
    }

    return themeDisplay.getPathThemeImages() + "/file_system/large/document.png";
  }
  @Override
  public String getCoverImageURL(ThemeDisplay themeDisplay) throws PortalException {

    long coverImageFileEntryId = getCoverImageFileEntryId();

    if (coverImageFileEntryId == 0) {
      return null;
    }

    FileEntry fileEntry = PortletFileRepositoryUtil.getPortletFileEntry(coverImageFileEntryId);

    return DLUtil.getPreviewURL(
        fileEntry, fileEntry.getFileVersion(), themeDisplay, StringPool.BLANK);
  }
  public void deleteFileEntryType(DLFileEntryType dlFileEntryType)
      throws PortalException, SystemException {

    DDMStructure ddmStructure =
        ddmStructureLocalService.fetchStructure(
            dlFileEntryType.getGroupId(),
            PortalUtil.getClassNameId(DLFileEntryMetadata.class),
            DLUtil.getDDMStructureKey(dlFileEntryType));

    if (ddmStructure == null) {
      ddmStructure =
          ddmStructureLocalService.fetchStructure(
              dlFileEntryType.getGroupId(),
              PortalUtil.getClassNameId(DLFileEntryMetadata.class),
              DLUtil.getDeprecatedDDMStructureKey(dlFileEntryType));
    }

    if (ddmStructure != null) {
      ddmStructureLocalService.deleteStructure(ddmStructure.getStructureId());
    }

    dlFileEntryTypePersistence.remove(dlFileEntryType);
  }
  private boolean _hasFolderWorkflowDefinitionLink() {
    try {
      ThemeDisplay themeDisplay = (ThemeDisplay) _request.getAttribute(WebKeys.THEME_DISPLAY);

      long folderId = BeanParamUtil.getLong(_fileEntry, _request, "folderId");

      return DLUtil.hasWorkflowDefinitionLink(
          themeDisplay.getCompanyId(),
          themeDisplay.getScopeGroupId(),
          folderId,
          _dlFileEntryType.getFileEntryTypeId());
    } catch (Exception e) {
      throw new SystemException("Unable to check if folder has workflow definition link", e);
    }
  }
  protected boolean isLegacyImageGalleryImageId(
      HttpServletRequest request, HttpServletResponse response) {

    try {
      long imageId = getImageId(request);

      if (imageId == 0) {
        return false;
      }

      DLFileEntry dlFileEntry = DLFileEntryServiceUtil.fetchFileEntryByImageId(imageId);

      if (dlFileEntry == null) {
        return false;
      }

      ThemeDisplay themeDisplay = (ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY);

      String queryString = StringPool.BLANK;

      if (imageId == dlFileEntry.getSmallImageId()) {
        queryString = "&imageThumbnail=1";
      } else if (imageId == dlFileEntry.getSmallImageId()) {
        queryString = "&imageThumbnail=2";
      } else if (imageId == dlFileEntry.getSmallImageId()) {
        queryString = "&imageThumbnail=3";
      }

      String url =
          DLUtil.getPreviewURL(
              new LiferayFileEntry(dlFileEntry),
              new LiferayFileVersion(dlFileEntry.getFileVersion()),
              themeDisplay,
              queryString);

      response.setHeader(HttpHeaders.LOCATION, url);
      response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);

      return true;
    } catch (Exception e) {
    }

    return false;
  }
  protected String processJournalArticleContent(String content) throws Exception {

    Matcher matcher = _fileEntryPattern.matcher(content);

    while (matcher.find()) {
      String fileName = matcher.group(1);

      FileEntry fileEntry = _fileEntries.get(fileName);

      String fileEntryURL = StringPool.BLANK;

      if (fileEntry != null) {
        fileEntryURL =
            DLUtil.getPreviewURL(fileEntry, fileEntry.getFileVersion(), null, StringPool.BLANK);
      }

      content = matcher.replaceFirst(fileEntryURL);

      matcher.reset(content);
    }

    if (content.contains("<?xml version=\"1.0\"")) {
      return content;
    }

    StringBundler sb = new StringBundler(13);

    sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
    sb.append("<root available-locales=\"");
    sb.append(LocaleUtil.getDefault());
    sb.append("\" default-locale=\"");
    sb.append(LocaleUtil.getDefault());
    sb.append("\">");
    sb.append("<static-content language-id=\"");
    sb.append(LocaleUtil.getDefault());
    sb.append("\">");
    sb.append("<![CDATA[");
    sb.append(content);
    sb.append("]]>");
    sb.append("</static-content></root>");

    return sb.toString();
  }
  protected String getHeadVersionLabel(long companyId, long repositoryId, String fileName) {

    File fileNameDir = getFileNameDir(companyId, repositoryId, fileName);

    if (!fileNameDir.exists()) {
      return VERSION_DEFAULT;
    }

    String[] versionLabels = FileUtil.listFiles(fileNameDir);

    String headVersionLabel = VERSION_DEFAULT;

    for (String versionLabel : versionLabels) {
      if (DLUtil.compareVersions(versionLabel, headVersionLabel) > 0) {
        headVersionLabel = versionLabel;
      }
    }

    return headVersionLabel;
  }
  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());
      }
    }
  }
  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);
        }
      }
    }
  }
  protected void addMultipleFileEntries(
      PortletConfig portletConfig,
      ActionRequest actionRequest,
      ActionResponse actionResponse,
      String selectedFileName,
      List<KeyValuePair> validFileNameKVPs,
      List<KeyValuePair> invalidFileNameKVPs)
      throws Exception {

    String originalSelectedFileName = selectedFileName;

    ThemeDisplay themeDisplay = (ThemeDisplay) actionRequest.getAttribute(WebKeys.THEME_DISPLAY);

    long repositoryId = ParamUtil.getLong(actionRequest, "repositoryId");
    long folderId = ParamUtil.getLong(actionRequest, "folderId");
    String description = ParamUtil.getString(actionRequest, "description");
    String changeLog = ParamUtil.getString(actionRequest, "changeLog");

    FileEntry tempFileEntry = null;

    try {
      tempFileEntry =
          TempFileEntryUtil.getTempFileEntry(
              themeDisplay.getScopeGroupId(),
              themeDisplay.getUserId(),
              TEMP_FOLDER_NAME,
              selectedFileName);

      selectedFileName =
          DLUtil.getFileName(
              tempFileEntry.getGroupId(), tempFileEntry.getFolderId(), tempFileEntry.getFileName());

      String mimeType = tempFileEntry.getMimeType();

      InputStream inputStream = tempFileEntry.getContentStream();
      long size = tempFileEntry.getSize();

      ServiceContext serviceContext =
          ServiceContextFactory.getInstance(DLFileEntry.class.getName(), actionRequest);

      _dlAppService.addFileEntry(
          repositoryId,
          folderId,
          selectedFileName,
          mimeType,
          selectedFileName,
          description,
          changeLog,
          inputStream,
          size,
          serviceContext);

      validFileNameKVPs.add(new KeyValuePair(selectedFileName, originalSelectedFileName));

      return;
    } catch (Exception e) {
      String errorMessage =
          getAddMultipleFileEntriesErrorMessage(portletConfig, actionRequest, actionResponse, e);

      invalidFileNameKVPs.add(new KeyValuePair(originalSelectedFileName, errorMessage));
    } finally {
      if (tempFileEntry != null) {
        TempFileEntryUtil.deleteTempFileEntry(tempFileEntry.getFileEntryId());
      }
    }
  }
  protected long updateDDMStructure(
      long userId,
      String fileEntryTypeUuid,
      long fileEntryTypeId,
      long groupId,
      String name,
      String description,
      ServiceContext serviceContext)
      throws PortalException, SystemException {

    fixDDMStructureKey(fileEntryTypeUuid, fileEntryTypeId, groupId);

    String ddmStructureKey = DLUtil.getDDMStructureKey(fileEntryTypeUuid);

    Map<Locale, String> nameMap = new HashMap<Locale, String>();

    Locale locale = serviceContext.getLocale();

    nameMap.put(locale, name);

    Locale defaultLocale = LocaleUtil.getDefault();

    nameMap.put(defaultLocale, name);

    Map<Locale, String> descriptionMap = new HashMap<Locale, String>();

    descriptionMap.put(locale, description);
    descriptionMap.put(defaultLocale, description);

    String xsd = ParamUtil.getString(serviceContext, "xsd");

    DDMStructure ddmStructure =
        ddmStructureLocalService.fetchStructure(
            groupId, PortalUtil.getClassNameId(DLFileEntryMetadata.class), ddmStructureKey);

    if ((ddmStructure != null) && Validator.isNull(xsd)) {
      xsd = ddmStructure.getXsd();
    }

    Locale[] contentAvailableLocales =
        LocaleUtil.fromLanguageIds(LocalizationUtil.getAvailableLocales(xsd));

    for (Locale contentAvailableLocale : contentAvailableLocales) {
      nameMap.put(contentAvailableLocale, name);

      descriptionMap.put(contentAvailableLocale, description);
    }

    try {
      if (ddmStructure == null) {
        ddmStructure =
            ddmStructureLocalService.addStructure(
                userId,
                groupId,
                DDMStructureConstants.DEFAULT_PARENT_STRUCTURE_ID,
                PortalUtil.getClassNameId(DLFileEntryMetadata.class),
                ddmStructureKey,
                nameMap,
                descriptionMap,
                xsd,
                "xml",
                DDMStructureConstants.TYPE_AUTO,
                serviceContext);
      } else {
        ddmStructure =
            ddmStructureLocalService.updateStructure(
                ddmStructure.getStructureId(),
                ddmStructure.getParentStructureId(),
                nameMap,
                descriptionMap,
                xsd,
                serviceContext);
      }

      return ddmStructure.getStructureId();
    } catch (StructureXsdException sxe) {
      if (ddmStructure != null) {
        ddmStructureLocalService.deleteStructure(ddmStructure.getStructureId());
      }
    }

    return 0;
  }
  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);
  }
 @Override
 public String getURLDownload(ThemeDisplay themeDisplay) {
   return DLUtil.getPreviewURL(_fileEntry, _fileVersion, themeDisplay, StringPool.BLANK);
 }