public static String getValue(
      ItemSelectorReturnType itemSelectorReturnType, FileEntry fileEntry, ThemeDisplay themeDisplay)
      throws Exception {

    String className = ClassUtil.getClassName(itemSelectorReturnType);

    if (className.equals(FileEntryItemSelectorReturnType.class.getName())) {
      return getFileEntryValue(fileEntry, themeDisplay);
    } else if (className.equals(URLItemSelectorReturnType.class.getName())) {
      return DLUtil.getPreviewURL(
          fileEntry, fileEntry.getFileVersion(), themeDisplay, StringPool.BLANK, false, false);
    }

    return StringPool.BLANK;
  }
  protected static String getFileEntryValue(FileEntry fileEntry, ThemeDisplay themeDisplay)
      throws Exception {

    JSONObject fileEntryJSONObject = JSONFactoryUtil.createJSONObject();

    fileEntryJSONObject.put("fileEntryId", fileEntry.getFileEntryId());
    fileEntryJSONObject.put("groupId", fileEntry.getGroupId());
    fileEntryJSONObject.put("title", fileEntry.getTitle());
    fileEntryJSONObject.put("type", "document");
    fileEntryJSONObject.put(
        "url",
        DLUtil.getPreviewURL(
            fileEntry, fileEntry.getFileVersion(), themeDisplay, StringPool.BLANK, false, false));
    fileEntryJSONObject.put("uuid", fileEntry.getUuid());

    return fileEntryJSONObject.toString();
  }
  @Test
  public void testUpdateFileName() throws Exception {
    DLFileEntry dlFileEntry = addDLFileEntry(DLFolderConstants.DEFAULT_PARENT_FOLDER_ID, false);

    ServiceContext serviceContext = ServiceContextTestUtil.getServiceContext(_group.getGroupId());

    dlFileEntry = updateStatus(dlFileEntry.getLatestFileVersion(true), serviceContext);

    String title = RandomTestUtil.randomString();

    dlFileEntry.setTitle(title);

    dlFileEntry = updateDLFileEntry(dlFileEntry, serviceContext);

    dlFileEntry = updateStatus(dlFileEntry.getLatestFileVersion(true), serviceContext);

    Assert.assertEquals(
        DLUtil.getSanitizedFileName(title, dlFileEntry.getExtension()), dlFileEntry.getFileName());
  }
  private String _getOnclickMethod() {
    String imageEditorPortletId =
        PortletProviderUtil.getPortletId(Image.class.getName(), PortletProvider.Action.EDIT);

    PortletURL imageEditorURL =
        PortletURLFactoryUtil.create(_request, imageEditorPortletId, PortletRequest.RENDER_PHASE);

    imageEditorURL.setParameter("mvcRenderCommandName", "/image_editor/view");

    try {
      imageEditorURL.setWindowState(LiferayWindowState.POP_UP);
    } catch (Exception e) {
      throw new SystemException("Unable to set window state", e);
    }

    LiferayPortletResponse liferayPortletResponse = _getLiferayPortletResponse();

    PortletURL editURL = liferayPortletResponse.createActionURL();

    editURL.setParameter(
        ActionRequest.ACTION_NAME, "/document_library/edit_file_entry_with_image_editor");

    editURL.setParameter("fileEntryId", String.valueOf(_fileEntry.getFileEntryId()));

    String fileEntryPreviewURL =
        DLUtil.getPreviewURL(_fileEntry, _fileVersion, _themeDisplay, StringPool.BLANK);

    StringBundler sb = new StringBundler(10);

    sb.append(liferayPortletResponse.getNamespace());
    sb.append("editWithImageEditor('");
    sb.append(imageEditorURL.toString());
    sb.append("', '");
    sb.append(editURL.toString());
    sb.append("', '");
    sb.append(_fileEntry.getFileName());
    sb.append("', '");
    sb.append(fileEntryPreviewURL);
    sb.append("');");

    return sb.toString();
  }
 @Override
 public String getIcon() {
   return DLUtil.getFileIcon(getExtension());
 }
  public String processAttachmentsReferences(
      long userId, KBArticle kbArticle, ZipReader zipReader, Map<String, FileEntry> fileEntriesMap)
      throws PortalException {

    Set<Integer> indexes = new TreeSet<>();

    int index = 0;

    while ((index = _html.indexOf("<img", index)) > -1) {
      indexes.add(index);

      index += 4;
    }

    if (indexes.isEmpty()) {
      return _html;
    }

    StringBundler sb = new StringBundler();

    int previousIndex = 0;

    for (int curIndex : indexes) {
      if (curIndex < 0) {
        break;
      }

      if (curIndex > previousIndex) {

        // Append text from previous position up to image tag

        String text = _html.substring(previousIndex, curIndex);

        sb.append(text);
      }

      int pos = _html.indexOf("/>", curIndex);

      if (pos < 0) {
        if (_log.isDebugEnabled()) {
          _log.debug("Expected close tag for image " + _html.substring(curIndex));
        }

        sb.append(_html.substring(curIndex));

        previousIndex = curIndex;

        break;
      }

      String text = _html.substring(curIndex, pos);

      String imageFileName = KBArticleImporterUtil.extractImageFileName(text);

      FileEntry imageFileEntry =
          KBArticleImporterUtil.addImageFileEntry(
              imageFileName, userId, kbArticle, zipReader, fileEntriesMap);

      if (imageFileEntry == null) {
        if (_log.isWarnEnabled()) {
          _log.warn("Unable to find image source " + text);
        }

        sb.append("<img alt=\"missing image\" src=\"\" ");
      } else {
        String imageSrc = StringPool.BLANK;

        try {
          imageSrc =
              DLUtil.getPreviewURL(
                  imageFileEntry, imageFileEntry.getFileVersion(), null, StringPool.BLANK);
        } catch (PortalException pe) {
          if (_log.isWarnEnabled()) {
            _log.warn(
                "Unable to obtain image URL from file entry " + imageFileEntry.getFileEntryId());
          }
        }

        sb.append("<img alt=\"");
        sb.append(HtmlUtil.escapeAttribute(imageFileEntry.getTitle()));
        sb.append("\" src=\"");
        sb.append(imageSrc);
        sb.append("\" ");
      }

      previousIndex = pos;
    }

    if (previousIndex < _html.length()) {
      sb.append(_html.substring(previousIndex));
    }

    return sb.toString();
  }
  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 _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);
    }
  }
  public void sendFile(
      String targetExtension, PortletRequest portletRequest, PortletResponse portletResponse)
      throws IOException {

    if (Validator.isNull(targetExtension)) {
      return;
    }

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

    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 =
        _journalContent.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 =
          _journalContent.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 = ContentTypes.TEXT_HTML;

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

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

    if (convertedFile != null) {
      targetExtension = StringUtil.toLowerCase(targetExtension);

      fileName = title.concat(StringPool.PERIOD).concat(targetExtension);

      contentType = MimeTypesUtil.getContentType(fileName);

      is = new FileInputStream(convertedFile);
    }

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