public static void copyThumbnail(ForeignPK fromPK, ForeignPK toPK) {
    ThumbnailDetail vignette =
        ThumbnailController.getCompleteThumbnail(
            new ThumbnailDetail(
                fromPK.getInstanceId(),
                Integer.parseInt(fromPK.getId()),
                ThumbnailDetail.THUMBNAIL_OBJECTTYPE_PUBLICATION_VIGNETTE));
    try {
      if (vignette != null) {
        ThumbnailDetail thumbDetail =
            new ThumbnailDetail(
                toPK.getInstanceId(),
                Integer.valueOf(toPK.getId()),
                ThumbnailDetail.THUMBNAIL_OBJECTTYPE_PUBLICATION_VIGNETTE);
        if (vignette.getOriginalFileName().startsWith("/")) {
          thumbDetail.setOriginalFileName(vignette.getOriginalFileName());
          thumbDetail.setMimeType(vignette.getMimeType());
        } else {
          String from = getImageDirectory(fromPK.getInstanceId()) + vignette.getOriginalFileName();

          String type = FilenameUtils.getExtension(vignette.getOriginalFileName());
          String newOriginalImage = String.valueOf(System.currentTimeMillis()) + "." + type;

          String to = getImageDirectory(toPK.getInstanceId()) + newOriginalImage;
          FileRepositoryManager.copyFile(from, to);
          thumbDetail.setOriginalFileName(newOriginalImage);

          // then copy thumbnail image if exists
          if (vignette.getCropFileName() != null) {
            from = getImageDirectory(fromPK.getInstanceId()) + vignette.getCropFileName();
            type = FilenameUtils.getExtension(vignette.getCropFileName());
            String newThumbnailImage = String.valueOf(System.currentTimeMillis()) + "." + type;
            to = getImageDirectory(toPK.getInstanceId()) + newThumbnailImage;
            FileRepositoryManager.copyFile(from, to);
            thumbDetail.setCropFileName(newThumbnailImage);
          }
          thumbDetail.setMimeType(vignette.getMimeType());
          thumbDetail.setXLength(vignette.getXLength());
          thumbDetail.setYLength(vignette.getYLength());
          thumbDetail.setXStart(vignette.getXStart());
          thumbDetail.setYStart(vignette.getYStart());
        }
        getThumbnailService().createThumbnail(thumbDetail);
      }
    } catch (Exception e) {
      throw new ThumbnailRuntimeException(
          "ThumbnailController.copyThumbnail()",
          SilverpeasRuntimeException.ERROR,
          "thumbnail_CANT_COPY_THUMBNAIL",
          e);
    }
  }
 /** Initializes the session file structure. */
 private synchronized void initialize() {
   if (!isHandledOnFileSystem()) {
     uploadSessionFolder = new File(FileRepositoryManager.getTemporaryPath(), uploadSessionId);
     if (!uploadSessionFolder.exists()) {
       uploadSessionFolder.mkdirs();
     }
   }
 }
 /** Centralizes the initialization. */
 private void initialize() {
   synchronized (SILVERPEAS_TRANSLATION_PREFIX) {
     if (descriptor.isFile() && descriptor.length() > 30) {
       try {
         for (String line : FileUtils.readLines(this.descriptor, Charsets.UTF_8)) {
           int splitIndex = line.indexOf("=");
           if (splitIndex > 0) {
             descriptorContent.put(line.substring(0, splitIndex), line.substring(splitIndex + 1));
           }
         }
       } catch (IOException e) {
         throw new RuntimeException(e);
       }
     } else {
       descriptorContent.put(TRANSLATION_ID, UUID.randomUUID().toString());
     }
     this.workspace =
         new File(FileRepositoryManager.getTemporaryPath(), descriptorContent.get(TRANSLATION_ID));
   }
 }
/** @author Yohann Chastagnier */
public class TemporaryDataCleanerSchedulerInitializer implements Initialization {

  protected static final String JOB_NAME = "TemporayDataCleanerJob";
  private static final File tempPath = new File(FileRepositoryManager.getTemporaryPath());

  @Inject private Scheduler scheduler;

  Thread startTask;

  @Override
  public void init() throws Exception {

    // Job instance
    final TemporaryDataCleanerJob temporaryDataCleanerJob = new TemporaryDataCleanerJob();

    // Cleaning temporary data at start if requested
    startTask =
        ManagedThreadPool.invoke(
                () -> {
                  temporaryDataCleanerJob.clean(
                      TemporaryDataManagementSetting
                          .getTimeAfterThatFilesMustBeDeletedAtServerStart());
                })
            .iterator()
            .next();

    // Setting CRON
    final String cron = TemporaryDataManagementSetting.getJobCron();
    scheduler.unscheduleJob(JOB_NAME);
    if (StringUtil.isDefined(cron)) {
      scheduler.scheduleJob(temporaryDataCleanerJob, JobTrigger.triggerAt(cron));
    }
  }

  /**
   * Temporary data cleaner.
   *
   * @author Yohann Chastagnier
   */
  private class TemporaryDataCleanerJob extends Job {

    /** Default constructor. */
    public TemporaryDataCleanerJob() {
      super(JOB_NAME);
    }

    @Override
    public void execute(final JobExecutionContext context) throws Exception {

      // 1 hour minimum or each time
      long nbMilliseconds = TemporaryDataManagementSetting.getTimeAfterThatFilesMustBeDeleted();
      if (nbMilliseconds < 0) {
        nbMilliseconds = 0;
      }
      clean(nbMilliseconds);
    }

    /**
     * Cleaning treatment
     *
     * @param nbMilliseconds : age of files that don't have to be deleted (in milliseconds)
     */
    private synchronized void clean(final long nbMilliseconds) {

      // Temporary temp directory
      if (tempPath.exists()) {

        // Nothing to do if fileAge is negative
        if (nbMilliseconds >= 0) {

          // Calculating the date from which files should be deleted from their date of last
          // modification. (in milliseconds)
          long fileAge = System.currentTimeMillis() - nbMilliseconds;

          // List all files to clean in temp directory and its subdirectories if any
          delete(listFiles(tempPath, new AgeFileFilter(fileAge), TrueFileFilter.TRUE));

          // Calculating the date from which empty directories should be deleted from their date of
          // last modification. (in milliseconds)
          fileAge = System.currentTimeMillis() - nbMilliseconds;

          // Deleting all empty subdirectories
          delete(
              listFilesAndDirs(
                  tempPath,
                  FalseFileFilter.FALSE,
                  new AndFileFilter(
                      new AgeFileFilter(fileAge),
                      new AbstractFileFilter() {

                        @Override
                        public boolean accept(final File file, final String name) {
                          // Checks subdirectories
                          return listFiles(file, TrueFileFilter.TRUE, TrueFileFilter.TRUE).size()
                              == 0;
                        }
                      })));
        }
      }
    }

    /**
     * Deleting files
     *
     * @param filesToDelete
     */
    private void delete(final Collection<File> filesToDelete) {
      if (filesToDelete != null) {
        filesToDelete.remove(tempPath);
        for (final File fileToDelete : filesToDelete) {
          deleteQuietly(fileToDelete);
        }
      }
    }
  }
}
 private TemporaryWorkspaceTranslation(final String id) {
   this.descriptor =
       new File(FileRepositoryManager.getTemporaryPath(), (SILVERPEAS_TRANSLATION_PREFIX + id));
   initialize();
 }
  public static boolean processThumbnail(ForeignPK pk, String objectType, List<FileItem> parameters)
      throws Exception {
    boolean thumbnailChanged = false;
    String mimeType = null;
    String physicalName = null;
    FileItem uploadedFile = FileUploadUtil.getFile(parameters, "WAIMGVAR0");
    if (uploadedFile != null) {
      String logicalName = uploadedFile.getName().replace('\\', '/');
      if (StringUtil.isDefined(logicalName)) {
        logicalName = FilenameUtils.getName(logicalName);
        mimeType = FileUtil.getMimeType(logicalName);
        String type = FileRepositoryManager.getFileExtension(logicalName);
        if (FileUtil.isImage(logicalName)) {
          physicalName = String.valueOf(System.currentTimeMillis()) + '.' + type;
          SilverpeasFileDescriptor descriptor =
              new SilverpeasFileDescriptor(pk.getInstanceId())
                  .mimeType(mimeType)
                  .parentDirectory(publicationSettings.getString("imagesSubDirectory"))
                  .fileName(physicalName);
          SilverpeasFile target = SilverpeasFileProvider.newFile(descriptor);
          target.writeFrom(uploadedFile.getInputStream());
        } else {
          throw new ThumbnailRuntimeException(
              "ThumbnailController.processThumbnail()",
              SilverpeasRuntimeException.ERROR,
              "thumbnail_EX_MSG_WRONG_TYPE_ERROR");
        }
      }
    }

    // If no image have been uploaded, check if one have been picked up from a gallery
    if (physicalName == null) {
      // on a pas d'image, regarder s'il y a une provenant de la galerie
      String nameImageFromGallery = FileUploadUtil.getParameter(parameters, "valueImageGallery");
      if (StringUtil.isDefined(nameImageFromGallery)) {
        physicalName = nameImageFromGallery;
        mimeType = "image/jpeg";
      }
    }

    // If one image is defined, save it through Thumbnail service
    if (StringUtil.isDefined(physicalName)) {
      ThumbnailDetail detail =
          new ThumbnailDetail(
              pk.getInstanceId(),
              Integer.parseInt(pk.getId()),
              ThumbnailDetail.THUMBNAIL_OBJECTTYPE_PUBLICATION_VIGNETTE);
      detail.setOriginalFileName(physicalName);
      detail.setMimeType(mimeType);
      try {
        ThumbnailController.updateThumbnail(detail);
        thumbnailChanged = true;
      } catch (ThumbnailRuntimeException e) {
        SilverTrace.error(
            "thumbnail",
            "KmeliaRequestRouter.processVignette",
            "thumbnail_MSG_UPDATE_THUMBNAIL_KO",
            e);
        try {
          ThumbnailController.deleteThumbnail(detail);
        } catch (Exception exp) {

        }
      }
    }
    return thumbnailChanged;
  }
 protected static String getImageDirectory(String instanceId) {
   return FileRepositoryManager.getAbsolutePath(instanceId)
       + publicationSettings.getString("imagesSubDirectory")
       + File.separatorChar;
 }