public FileEntry updateFileEntry(
      long fileEntryId,
      String sourceFileName,
      String mimeType,
      String title,
      String description,
      String changeLog,
      boolean majorVersion,
      InputStream is,
      long size,
      ServiceContext serviceContext)
      throws PortalException, SystemException {

    Repository repository = getRepository(0, fileEntryId, 0);

    FileEntry fileEntry =
        repository.updateFileEntry(
            fileEntryId,
            sourceFileName,
            mimeType,
            title,
            description,
            changeLog,
            majorVersion,
            is,
            size,
            serviceContext);

    DLProcessorRegistryUtil.trigger(fileEntry);

    return fileEntry;
  }
  public void deleteFileEntry(FileEntry fileEntry) throws PortalException, SystemException {

    // Subscriptions

    subscriptionLocalService.deleteSubscriptions(
        fileEntry.getCompanyId(), DLFileEntryConstants.getClassName(), fileEntry.getFileEntryId());

    // File previews

    DLProcessorRegistryUtil.cleanUp(fileEntry);

    // File ranks

    dlFileRankLocalService.deleteFileRanksByFileEntryId(fileEntry.getFileEntryId());

    // File shortcuts

    dlFileShortcutLocalService.deleteFileShortcuts(fileEntry.getFileEntryId());

    // Sync

    if (!isStagingGroup(fileEntry.getGroupId())) {
      dlSyncLocalService.updateSync(
          fileEntry.getFileEntryId(),
          fileEntry.getFolderId(),
          fileEntry.getTitle(),
          fileEntry.getDescription(),
          DLSyncConstants.EVENT_DELETE,
          fileEntry.getVersion());
    }

    // Asset

    assetEntryLocalService.deleteEntry(
        DLFileEntryConstants.getClassName(), fileEntry.getFileEntryId());

    // Message boards

    mbMessageLocalService.deleteDiscussionMessages(
        DLFileEntryConstants.getClassName(), fileEntry.getFileEntryId());

    // Ratings

    ratingsStatsLocalService.deleteStats(
        DLFileEntryConstants.getClassName(), fileEntry.getFileEntryId());

    // Trash

    if (fileEntry.getModel() instanceof DLFileEntry) {
      trashEntryLocalService.deleteEntry(
          DLFileEntryConstants.getClassName(), fileEntry.getFileEntryId());
    }
  }
  protected void copyFolder(
      Repository repository, Folder srcFolder, Folder destFolder, ServiceContext serviceContext)
      throws PortalException, SystemException {

    List<FileEntry> srcFileEntries =
        repository.getFileEntries(
            srcFolder.getFolderId(), QueryUtil.ALL_POS, QueryUtil.ALL_POS, null);

    for (FileEntry srcFileEntry : srcFileEntries) {
      try {
        FileEntry fileEntry =
            repository.copyFileEntry(
                destFolder.getGroupId(),
                srcFileEntry.getFileEntryId(),
                destFolder.getFolderId(),
                serviceContext);

        DLProcessorRegistryUtil.trigger(fileEntry);
      } catch (Exception e) {
        _log.error(e, e);

        continue;
      }
    }

    List<Folder> srcSubfolders =
        repository.getFolders(
            srcFolder.getFolderId(), false, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null);

    for (Folder srcSubfolder : srcSubfolders) {
      Folder destSubfolder =
          repository.addFolder(
              destFolder.getFolderId(),
              srcSubfolder.getName(),
              srcSubfolder.getDescription(),
              serviceContext);

      copyFolder(repository, srcSubfolder, destSubfolder, serviceContext);
    }
  }
  public FileEntry addFileEntry(
      long repositoryId,
      long folderId,
      String sourceFileName,
      String mimeType,
      String title,
      String description,
      String changeLog,
      InputStream is,
      long size,
      ServiceContext serviceContext)
      throws PortalException, SystemException {

    if (is == null) {
      is = new UnsyncByteArrayInputStream(new byte[0]);
      size = 0;
    }

    Repository repository = getRepository(repositoryId);

    FileEntry fileEntry =
        repository.addFileEntry(
            folderId,
            sourceFileName,
            mimeType,
            title,
            description,
            changeLog,
            is,
            size,
            serviceContext);

    DLProcessorRegistryUtil.trigger(fileEntry);

    return fileEntry;
  }
  @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());
  }
  @Override
  protected void doExportStagedModel(PortletDataContext portletDataContext, FileEntry fileEntry)
      throws Exception {

    Element fileEntryElement = portletDataContext.getExportDataElement(fileEntry);

    String fileEntryPath = ExportImportPathUtil.getModelPath(fileEntry);

    if (!fileEntry.isDefaultRepository()) {
      Repository repository = RepositoryLocalServiceUtil.getRepository(fileEntry.getRepositoryId());

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

      portletDataContext.addClassedModel(fileEntryElement, fileEntryPath, fileEntry);

      long portletRepositoryClassNameId =
          PortalUtil.getClassNameId(PortletRepository.class.getName());

      if (repository.getClassNameId() != portletRepositoryClassNameId) {
        return;
      }
    }

    if (fileEntry.getFolderId() != DLFolderConstants.DEFAULT_PARENT_FOLDER_ID) {

      StagedModelDataHandlerUtil.exportReferenceStagedModel(
          portletDataContext,
          fileEntry,
          fileEntry.getFolder(),
          PortletDataContext.REFERENCE_TYPE_PARENT);
    }

    LiferayFileEntry liferayFileEntry = (LiferayFileEntry) fileEntry;

    liferayFileEntry.setCachedFileVersion(fileEntry.getFileVersion());

    if (!portletDataContext.isPerformDirectBinaryImport()) {
      InputStream is = null;

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

      if (is == null) {
        fileEntryElement.detach();

        return;
      }

      try {
        String binPath = ExportImportPathUtil.getModelPath(fileEntry, fileEntry.getVersion());

        portletDataContext.addZipEntry(binPath, is);

        fileEntryElement.addAttribute("bin-path", binPath);
      } finally {
        try {
          is.close();
        } catch (IOException ioe) {
          _log.error(ioe, ioe);
        }
      }
    }

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

      DLProcessorRegistryUtil.exportGeneratedFiles(portletDataContext, fileEntry, fileEntryElement);
    }

    exportMetaData(portletDataContext, fileEntryElement, fileEntry);

    portletDataContext.addClassedModel(
        fileEntryElement, fileEntryPath, liferayFileEntry, DLFileEntry.class);
  }