public Folder moveFolderToTrash(long userId, Folder folder)
      throws PortalException, SystemException {

    // Folder

    DLFolder dlFolder =
        dlFolderLocalService.updateStatus(
            userId,
            folder.getFolderId(),
            WorkflowConstants.STATUS_IN_TRASH,
            new HashMap<String, Serializable>(),
            new ServiceContext());

    dlFolder.setName(DLAppUtil.appendTrashNamespace(dlFolder.getName()));

    dlFolderPersistence.update(dlFolder, false);

    // File rank

    dlFileRankLocalService.disableFileRanksByFolderId(folder.getFolderId());

    // Trash

    trashEntryLocalService.addTrashEntry(
        userId,
        folder.getGroupId(),
        DLFolderConstants.getClassName(),
        folder.getFolderId(),
        WorkflowConstants.STATUS_APPROVED,
        null,
        null);

    return new LiferayFolder(dlFolder);
  }
  public void moveFolder(Folder folder) throws PortalException, SystemException {

    if (!isStagingGroup(folder.getGroupId())) {
      dlSyncLocalService.updateSync(
          folder.getFolderId(),
          folder.getParentFolderId(),
          folder.getName(),
          folder.getDescription(),
          DLSyncConstants.EVENT_UPDATE,
          "-1");
    }
  }
  public void addFolder(Folder folder, ServiceContext serviceContext)
      throws PortalException, SystemException {

    if (!isStagingGroup(folder.getGroupId())) {
      dlSyncLocalService.addSync(
          folder.getFolderId(),
          folder.getUuid(),
          folder.getCompanyId(),
          folder.getRepositoryId(),
          folder.getParentFolderId(),
          folder.getName(),
          folder.getDescription(),
          DLSyncConstants.TYPE_FOLDER,
          "-1");
    }
  }
  @Override
  public SyncDLObject moveFolder(long folderId, long parentFolderId, ServiceContext serviceContext)
      throws PortalException {

    try {
      Folder folder = dlAppLocalService.getFolder(folderId);

      SyncUtil.checkSyncEnabled(folder.getGroupId());

      folder = dlAppService.moveFolder(folderId, parentFolderId, serviceContext);

      return toSyncDLObject(folder, SyncConstants.EVENT_MOVE);
    } catch (PortalException pe) {
      throw new PortalException(SyncUtil.buildExceptionMessage(pe), pe);
    }
  }
  @Override
  public SyncDLObject updateFolder(
      long folderId, String name, String description, ServiceContext serviceContext)
      throws PortalException {

    try {
      Folder folder = dlAppLocalService.getFolder(folderId);

      SyncUtil.checkSyncEnabled(folder.getGroupId());

      folder = dlAppService.updateFolder(folderId, name, description, serviceContext);

      return toSyncDLObject(folder, SyncConstants.EVENT_UPDATE);
    } catch (PortalException pe) {
      throw new PortalException(SyncUtil.buildExceptionMessage(pe), pe);
    }
  }
  @Override
  public SyncDLObject restoreFolderFromTrash(long folderId) throws PortalException {

    try {
      Folder folder = dlAppLocalService.getFolder(folderId);

      SyncUtil.checkSyncEnabled(folder.getGroupId());

      dlAppService.restoreFolderFromTrash(folderId);

      folder = dlAppLocalService.getFolder(folderId);

      return toSyncDLObject(folder, SyncConstants.EVENT_RESTORE);
    } catch (PortalException pe) {
      throw new PortalException(SyncUtil.buildExceptionMessage(pe), pe);
    }
  }
  @Override
  public SyncDLObject getFolderSyncDLObject(long folderId) throws PortalException {

    try {
      Folder folder = dlAppLocalService.getFolder(folderId);

      SyncUtil.checkSyncEnabled(folder.getGroupId());

      folder = dlAppService.getFolder(folderId);

      if (!SyncUtil.isSupportedFolder(folder)) {
        return null;
      }

      return toSyncDLObject(folder, SyncConstants.EVENT_GET);
    } catch (PortalException pe) {
      throw new PortalException(SyncUtil.buildExceptionMessage(pe), pe);
    }
  }
  public void deleteFolder(Folder folder) throws PortalException, SystemException {

    // Sync

    if (!isStagingGroup(folder.getGroupId())) {
      dlSyncLocalService.updateSync(
          folder.getFolderId(),
          folder.getParentFolderId(),
          folder.getName(),
          folder.getDescription(),
          DLSyncConstants.EVENT_DELETE,
          "-1");
    }

    // Trash

    if (folder.getModel() instanceof DLFolder) {
      trashEntryLocalService.deleteEntry(DLFolderConstants.getClassName(), folder.getFolderId());
    }
  }
  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);
    }
  }
  @Override
  public SyncDLObject moveFolderToTrash(long folderId) throws PortalException {

    try {
      Folder folder = dlAppLocalService.getFolder(folderId);

      SyncUtil.checkSyncEnabled(folder.getGroupId());

      if (TrashUtil.isInTrash(DLFolderConstants.getClassName(), folderId)) {

        return null;
      }

      folder = dlAppService.moveFolderToTrash(folderId);

      return toSyncDLObject(folder, SyncConstants.EVENT_TRASH);
    } catch (NoSuchFolderException nsfe) {
      return null;
    } catch (PortalException pe) {
      throw new PortalException(SyncUtil.buildExceptionMessage(pe), pe);
    }
  }
  protected FileEntry addFileEntry(ActionRequest actionRequest) throws Exception {

    UploadPortletRequest uploadPortletRequest = PortalUtil.getUploadPortletRequest(actionRequest);

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

    long folderId = ParamUtil.getLong(uploadPortletRequest, "folderId");
    String sourceFileName = uploadPortletRequest.getFileName("file");
    String title = ParamUtil.getString(uploadPortletRequest, "title");
    String description = ParamUtil.getString(uploadPortletRequest, "description");
    String changeLog = ParamUtil.getString(uploadPortletRequest, "changeLog");

    if (folderId > 0) {
      Folder folder = DLAppServiceUtil.getFolder(folderId);

      if (folder.getGroupId() != themeDisplay.getScopeGroupId()) {
        throw new NoSuchFolderException("{folderId=" + folderId + "}");
      }
    }

    InputStream inputStream = null;

    try {
      String contentType = uploadPortletRequest.getContentType("file");

      long size = uploadPortletRequest.getSize("file");

      if (size == 0) {
        contentType = MimeTypesUtil.getContentType(title);
      }

      if (size > 0) {
        HttpServletRequest request = PortalUtil.getHttpServletRequest(actionRequest);

        String[] mimeTypes = DocumentSelectorUtil.getMimeTypes(request);

        if (ArrayUtil.isNotEmpty(mimeTypes) && !ArrayUtil.contains(mimeTypes, contentType)) {

          throw new FileMimeTypeException(contentType);
        }
      }

      inputStream = uploadPortletRequest.getFileAsStream("file");

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

      FileEntry fileEntry =
          DLAppServiceUtil.addFileEntry(
              themeDisplay.getScopeGroupId(),
              folderId,
              sourceFileName,
              contentType,
              title,
              description,
              changeLog,
              inputStream,
              size,
              serviceContext);

      AssetPublisherUtil.addRecentFolderId(actionRequest, DLFileEntry.class.getName(), folderId);

      return fileEntry;
    } catch (Exception e) {
      UploadException uploadException =
          (UploadException) actionRequest.getAttribute(WebKeys.UPLOAD_EXCEPTION);

      if (uploadException != null) {
        if (uploadException.isExceededLiferayFileItemSizeLimit()) {
          throw new LiferayFileItemException();
        } else if (uploadException.isExceededSizeLimit()) {
          throw new FileSizeException(uploadException.getCause());
        }
      }

      throw e;
    } finally {
      StreamUtil.cleanUp(inputStream);
    }
  }
  protected FileEntry updateFileEntry(
      PortletConfig portletConfig, ActionRequest actionRequest, ActionResponse actionResponse)
      throws Exception {

    UploadPortletRequest uploadPortletRequest = PortalUtil.getUploadPortletRequest(actionRequest);

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

    String cmd = ParamUtil.getString(uploadPortletRequest, Constants.CMD);

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

    long repositoryId = ParamUtil.getLong(uploadPortletRequest, "repositoryId");
    long folderId = ParamUtil.getLong(uploadPortletRequest, "folderId");
    String sourceFileName = uploadPortletRequest.getFileName("file");
    String title = ParamUtil.getString(uploadPortletRequest, "title");
    String description = ParamUtil.getString(uploadPortletRequest, "description");
    String changeLog = ParamUtil.getString(uploadPortletRequest, "changeLog");
    boolean majorVersion = ParamUtil.getBoolean(uploadPortletRequest, "majorVersion");

    if (folderId > 0) {
      Folder folder = _dlAppService.getFolder(folderId);

      if (folder.getGroupId() != themeDisplay.getScopeGroupId()) {
        throw new NoSuchFolderException("{folderId=" + folderId + "}");
      }
    }

    InputStream inputStream = null;

    try {
      String contentType = uploadPortletRequest.getContentType("file");
      long size = uploadPortletRequest.getSize("file");

      if ((cmd.equals(Constants.ADD) || cmd.equals(Constants.ADD_DYNAMIC)) && (size == 0)) {

        contentType = MimeTypesUtil.getContentType(title);
      }

      if (cmd.equals(Constants.ADD) || cmd.equals(Constants.ADD_DYNAMIC) || (size > 0)) {

        String portletName = portletConfig.getPortletName();

        if (portletName.equals(DLPortletKeys.MEDIA_GALLERY_DISPLAY)) {
          PortletDisplay portletDisplay = themeDisplay.getPortletDisplay();

          DLPortletInstanceSettings dlPortletInstanceSettings =
              DLPortletInstanceSettings.getInstance(
                  themeDisplay.getLayout(), portletDisplay.getId());

          String[] mimeTypes = dlPortletInstanceSettings.getMimeTypes();

          if (Arrays.binarySearch(mimeTypes, contentType) < 0) {
            throw new FileMimeTypeException(contentType);
          }
        }
      }

      inputStream = uploadPortletRequest.getFileAsStream("file");

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

      FileEntry fileEntry = null;

      if (cmd.equals(Constants.ADD) || cmd.equals(Constants.ADD_DYNAMIC)) {

        // Add file entry

        fileEntry =
            _dlAppService.addFileEntry(
                repositoryId,
                folderId,
                sourceFileName,
                contentType,
                title,
                description,
                changeLog,
                inputStream,
                size,
                serviceContext);

        if (cmd.equals(Constants.ADD_DYNAMIC)) {
          JSONObject jsonObject = JSONFactoryUtil.createJSONObject();

          jsonObject.put("fileEntryId", fileEntry.getFileEntryId());

          JSONPortletResponseUtil.writeJSON(actionRequest, actionResponse, jsonObject);
        }
      } else if (cmd.equals(Constants.UPDATE_AND_CHECKIN)) {

        // Update file entry and checkin

        fileEntry =
            _dlAppService.updateFileEntryAndCheckIn(
                fileEntryId,
                sourceFileName,
                contentType,
                title,
                description,
                changeLog,
                majorVersion,
                inputStream,
                size,
                serviceContext);
      } else {

        // Update file entry

        fileEntry =
            _dlAppService.updateFileEntry(
                fileEntryId,
                sourceFileName,
                contentType,
                title,
                description,
                changeLog,
                majorVersion,
                inputStream,
                size,
                serviceContext);
      }

      return fileEntry;
    } catch (Exception e) {
      UploadException uploadException =
          (UploadException) actionRequest.getAttribute(WebKeys.UPLOAD_EXCEPTION);

      if (uploadException != null) {
        if (uploadException.isExceededLiferayFileItemSizeLimit()) {
          throw new LiferayFileItemException();
        } else if (uploadException.isExceededSizeLimit()) {
          throw new FileSizeException(uploadException.getCause());
        }
      }

      throw e;
    } finally {
      StreamUtil.cleanUp(inputStream);
    }
  }