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);
  }
Exemple #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());
    }
  }
  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());
    }
  }
  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 _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 _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);
        }
      }
    }
  }
  protected void sendFile(
      HttpServletRequest request, HttpServletResponse response, User user, String[] pathArray)
      throws Exception {

    // Retrieve file details

    FileEntry fileEntry = getFileEntry(pathArray);

    if (fileEntry == null) {
      throw new NoSuchFileEntryException();
    }

    String version = ParamUtil.getString(request, "version");

    if (Validator.isNull(version)) {
      if (Validator.isNotNull(fileEntry.getVersion())) {
        version = fileEntry.getVersion();
      }
    }

    String tempFileId = DLUtil.getTempFileId(fileEntry.getFileEntryId(), version);

    FileVersion fileVersion = fileEntry.getFileVersion(version);

    String fileName = fileVersion.getTitle();

    String extension = fileVersion.getExtension();

    if (Validator.isNotNull(extension) && !fileName.endsWith(StringPool.PERIOD + extension)) {

      fileName += StringPool.PERIOD + extension;
    }

    // Handle requested conversion

    boolean converted = false;

    String targetExtension = ParamUtil.getString(request, "targetExtension");
    int imageThumbnail = ParamUtil.getInteger(request, "imageThumbnail");
    int documentThumbnail = ParamUtil.getInteger(request, "documentThumbnail");
    int previewFileIndex = ParamUtil.getInteger(request, "previewFileIndex");
    boolean audioPreview = ParamUtil.getBoolean(request, "audioPreview");
    boolean imagePreview = ParamUtil.getBoolean(request, "imagePreview");
    boolean videoPreview = ParamUtil.getBoolean(request, "videoPreview");
    int videoThumbnail = ParamUtil.getInteger(request, "videoThumbnail");

    InputStream inputStream = null;
    long contentLength = 0;

    if ((imageThumbnail > 0) && (imageThumbnail <= 3)) {
      fileName =
          FileUtil.stripExtension(fileName)
              .concat(StringPool.PERIOD)
              .concat(ImageProcessorUtil.getThumbnailType(fileVersion));

      int thumbnailIndex = imageThumbnail - 1;

      inputStream = ImageProcessorUtil.getThumbnailAsStream(fileVersion, thumbnailIndex);
      contentLength = ImageProcessorUtil.getThumbnailFileSize(fileVersion, thumbnailIndex);

      converted = true;
    } else if ((documentThumbnail > 0) && (documentThumbnail <= 3)) {
      fileName =
          FileUtil.stripExtension(fileName)
              .concat(StringPool.PERIOD)
              .concat(PDFProcessor.THUMBNAIL_TYPE);

      int thumbnailIndex = documentThumbnail - 1;

      inputStream = PDFProcessorUtil.getThumbnailAsStream(fileVersion, thumbnailIndex);
      contentLength = PDFProcessorUtil.getThumbnailFileSize(fileVersion, thumbnailIndex);

      converted = true;
    } else if (previewFileIndex > 0) {
      fileName =
          FileUtil.stripExtension(fileName)
              .concat(StringPool.PERIOD)
              .concat(PDFProcessor.PREVIEW_TYPE);
      inputStream = PDFProcessorUtil.getPreviewAsStream(fileVersion, previewFileIndex);
      contentLength = PDFProcessorUtil.getPreviewFileSize(fileVersion, previewFileIndex);

      converted = true;
    } else if (audioPreview || videoPreview) {
      String type = ParamUtil.getString(request, "type");

      fileName = FileUtil.stripExtension(fileName).concat(StringPool.PERIOD).concat(type);

      if (audioPreview) {
        inputStream = AudioProcessorUtil.getPreviewAsStream(fileVersion, type);
        contentLength = AudioProcessorUtil.getPreviewFileSize(fileVersion, type);
      } else {
        inputStream = VideoProcessorUtil.getPreviewAsStream(fileVersion, type);
        contentLength = VideoProcessorUtil.getPreviewFileSize(fileVersion, type);
      }

      converted = true;
    } else if (imagePreview) {
      String type = ImageProcessorUtil.getPreviewType(fileVersion);

      fileName = FileUtil.stripExtension(fileName).concat(StringPool.PERIOD).concat(type);

      inputStream = ImageProcessorUtil.getPreviewAsStream(fileVersion);

      contentLength = ImageProcessorUtil.getPreviewFileSize(fileVersion);

      converted = true;
    } else if ((videoThumbnail > 0) && (videoThumbnail <= 3)) {
      fileName =
          FileUtil.stripExtension(fileName)
              .concat(StringPool.PERIOD)
              .concat(VideoProcessor.THUMBNAIL_TYPE);

      int thumbnailIndex = videoThumbnail - 1;

      inputStream = VideoProcessorUtil.getThumbnailAsStream(fileVersion, thumbnailIndex);
      contentLength = VideoProcessorUtil.getThumbnailFileSize(fileVersion, thumbnailIndex);

      converted = true;
    } else {
      inputStream = fileVersion.getContentStream(true);
      contentLength = fileVersion.getSize();

      if (Validator.isNotNull(targetExtension)) {
        File convertedFile =
            DocumentConversionUtil.convert(tempFileId, inputStream, extension, targetExtension);

        if (convertedFile != null) {
          fileName =
              FileUtil.stripExtension(fileName).concat(StringPool.PERIOD).concat(targetExtension);
          inputStream = new FileInputStream(convertedFile);
          contentLength = convertedFile.length();

          converted = true;
        }
      }
    }

    // Determine proper content type

    String contentType = null;

    if (converted) {
      contentType = MimeTypesUtil.getContentType(fileName);
    } else {
      contentType = fileVersion.getMimeType();
    }

    // Support range HTTP header

    response.setHeader(HttpHeaders.ACCEPT_RANGES, HttpHeaders.ACCEPT_RANGES_BYTES_VALUE);

    List<Range> ranges = null;

    try {
      ranges = ServletResponseUtil.getRanges(request, response, contentLength);
    } catch (IOException ioe) {
      if (_log.isErrorEnabled()) {
        _log.error(ioe);
      }

      response.setHeader(HttpHeaders.CONTENT_RANGE, "bytes */" + contentLength);

      response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);

      return;
    }

    if ((ranges == null) || ranges.isEmpty()) {
      ServletResponseUtil.sendFile(
          request, response, fileName, inputStream, contentLength, contentType);
    } else {
      if (_log.isDebugEnabled()) {
        _log.debug("Request has range header " + request.getHeader(HttpHeaders.RANGE));
      }

      ServletResponseUtil.write(
          request, response, fileName, ranges, inputStream, contentLength, contentType);
    }
  }
Exemple #11
0
  protected void getFile(
      long fileEntryId,
      long folderId,
      String name,
      String title,
      String version,
      long fileShortcutId,
      String uuid,
      long groupId,
      String targetExtension,
      HttpServletRequest request,
      HttpServletResponse response)
      throws Exception {

    if (name.startsWith("DLFE-")) {
      name = name.substring(5);
    }

    name = FileUtil.stripExtension(name);

    FileEntry fileEntry = null;

    if (Validator.isNotNull(uuid) && (groupId > 0)) {
      fileEntry = DLAppServiceUtil.getFileEntryByUuidAndGroupId(uuid, groupId);

      folderId = fileEntry.getFolderId();
    }

    if (fileEntryId > 0) {
      fileEntry = DLAppServiceUtil.getFileEntry(fileEntryId);
    } else if (fileShortcutId <= 0) {
      if (Validator.isNotNull(title)) {
        fileEntry = DLAppServiceUtil.getFileEntry(groupId, folderId, title);
      } else if (Validator.isNotNull(name)) {
        DLFileEntry dlFileEntry =
            DLFileEntryLocalServiceUtil.fetchFileEntryByName(groupId, folderId, name);

        if (dlFileEntry == null) {

          // LPS-30374

          List<DLFileEntry> dlFileEntries =
              DLFileEntryLocalServiceUtil.getFileEntries(folderId, name);

          if (!dlFileEntries.isEmpty()) {
            dlFileEntry = dlFileEntries.get(0);
          }
        }

        if (dlFileEntry != null) {
          ThemeDisplay themeDisplay = (ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY);

          PermissionChecker permissionChecker = themeDisplay.getPermissionChecker();

          DLFileEntryPermission.check(permissionChecker, dlFileEntry, ActionKeys.VIEW);

          fileEntry = new LiferayFileEntry(dlFileEntry);
        }
      }
    } else {
      DLFileShortcut fileShortcut = DLAppServiceUtil.getFileShortcut(fileShortcutId);

      fileEntryId = fileShortcut.getToFileEntryId();

      fileEntry = DLAppServiceUtil.getFileEntry(fileEntryId);
    }

    if (Validator.isNull(version)) {
      if ((fileEntry != null) && Validator.isNotNull(fileEntry.getVersion())) {

        version = fileEntry.getVersion();
      } else {
        throw new NoSuchFileEntryException();
      }
    }

    FileVersion fileVersion = fileEntry.getFileVersion(version);

    InputStream is = fileVersion.getContentStream(true);
    String fileName = fileVersion.getTitle();
    long contentLength = fileVersion.getSize();
    String contentType = fileVersion.getMimeType();

    if (Validator.isNotNull(targetExtension)) {
      String id = DLUtil.getTempFileId(fileEntry.getFileEntryId(), version);

      String sourceExtension = fileVersion.getExtension();

      if (!fileName.endsWith(StringPool.PERIOD + sourceExtension)) {
        fileName += StringPool.PERIOD + sourceExtension;
      }

      File convertedFile = DocumentConversionUtil.convert(id, is, sourceExtension, targetExtension);

      if (convertedFile != null) {
        fileName =
            FileUtil.stripExtension(fileName).concat(StringPool.PERIOD).concat(targetExtension);
        is = new FileInputStream(convertedFile);
        contentLength = convertedFile.length();
        contentType = MimeTypesUtil.getContentType(fileName);
      }
    }

    ServletResponseUtil.sendFile(request, response, fileName, is, contentLength, contentType);
  }
  public static void sendFile(PortletRequest portletRequest, PortletResponse portletResponse)
      throws IOException {

    long groupId = ParamUtil.getLong(portletRequest, "groupId");
    String articleId = ParamUtil.getString(portletRequest, "articleId");

    String targetExtension = ParamUtil.getString(portletRequest, "targetExtension");

    PortletPreferences portletPreferences = portletRequest.getPreferences();

    String[] allowedExtensions = StringUtil.split(portletPreferences.getValue("extensions", null));

    String languageId = LanguageUtil.getLanguageId(portletRequest);
    PortletRequestModel portletRequestModel =
        new PortletRequestModel(portletRequest, portletResponse);
    ThemeDisplay themeDisplay = (ThemeDisplay) portletRequest.getAttribute(WebKeys.THEME_DISPLAY);
    HttpServletRequest request = PortalUtil.getHttpServletRequest(portletRequest);
    HttpServletResponse response = PortalUtil.getHttpServletResponse(portletResponse);

    JournalArticleDisplay articleDisplay =
        JournalContentUtil.getDisplay(
            groupId, articleId, null, "export", languageId, 1, portletRequestModel, themeDisplay);

    int pages = articleDisplay.getNumberOfPages();

    StringBundler sb = new StringBundler(pages + 12);

    sb.append("<html>");

    sb.append("<head>");
    sb.append("<meta content=\"");
    sb.append(ContentTypes.TEXT_HTML_UTF8);
    sb.append("\" http-equiv=\"content-type\" />");
    sb.append("<base href=\"");
    sb.append(themeDisplay.getPortalURL());
    sb.append("\" />");
    sb.append("</head>");

    sb.append("<body>");

    sb.append(articleDisplay.getContent());

    for (int i = 2; i <= pages; i++) {
      articleDisplay =
          JournalContentUtil.getDisplay(groupId, articleId, "export", languageId, i, themeDisplay);

      sb.append(articleDisplay.getContent());
    }

    sb.append("</body>");
    sb.append("</html>");

    InputStream is = new UnsyncByteArrayInputStream(sb.toString().getBytes(StringPool.UTF8));

    String title = articleDisplay.getTitle();
    String sourceExtension = "html";

    String fileName = title.concat(StringPool.PERIOD).concat(sourceExtension);

    String contentType = MimeTypesUtil.getContentType(fileName);

    if (Validator.isNull(targetExtension)
        || !ArrayUtil.contains(allowedExtensions, targetExtension)) {

      ServletResponseUtil.sendFile(request, response, fileName, is, contentType);

      return;
    }

    String id =
        DLUtil.getTempFileId(
            articleDisplay.getId(), String.valueOf(articleDisplay.getVersion()), languageId);

    File convertedFile = DocumentConversionUtil.convert(id, is, sourceExtension, targetExtension);

    if (convertedFile != null) {
      fileName = title.concat(StringPool.PERIOD).concat(targetExtension);

      is = new FileInputStream(convertedFile);
    }

    ServletResponseUtil.sendFile(request, response, fileName, is, contentType);
  }