/**
   * Methode utilisee par la methode importAttachement(String,String,AttachmentDetail) pour creer un
   * attachement sur la publication creee dans la methode citee.
   *
   * @param pubId - id de la publication dans laquelle creer l'attachment
   * @param componentId - id du composant contenant la publication
   * @param attachment
   * @return AttachmentDetail cree
   */
  private SimpleDocument addAttachmentToPublication(
      String pubId,
      String componentId,
      AttachmentDetail attachment,
      InputStream input,
      boolean indexIt) {
    SimpleDocumentPK attachmentPk = new SimpleDocumentPK(null, componentId);
    ForeignPK foreignKey = new ForeignPK(pubId, componentId);
    List<SimpleDocument> existingAttachments =
        AttachmentServiceFactory.getAttachmentService()
            .listDocumentsByForeignKeyAndType(
                foreignKey, DocumentType.attachment, attachment.getLanguage());

    String logicalName = attachment.getLogicalName();
    if (!StringUtil.isDefined(logicalName)) {
      logicalName = FileUtil.getFilename(attachment.getPhysicalName());
    }
    String userId = attachment.getAuthor();
    String updateRule = attachment.getImportUpdateRule();
    if (!StringUtil.isDefined(updateRule) || "null".equalsIgnoreCase(updateRule)) {
      updateRule = AttachmentDetail.IMPORT_UPDATE_RULE_ADD;
    }

    SilverTrace.info(
        "attachment",
        "AttachmentImportExport.addAttachmentToPublication()",
        "root.MSG_GEN_PARAM_VALUE",
        "updateRule=" + updateRule);

    // Verification s'il existe un attachment de meme nom, si oui, ajout
    // d'un suffixe au nouveau fichier
    logicalName = computeUniqueName(attachment, 0, existingAttachments, logicalName, updateRule);
    attachment.setLogicalName(logicalName);

    Date creationDate = attachment.getCreationDate();
    if (creationDate == null) {
      creationDate = new Date();
    }
    SimpleDocument ad_toCreate =
        new SimpleDocument(
            attachmentPk,
            pubId,
            -1,
            false,
            new SimpleAttachment(
                attachment.getLogicalName(),
                attachment.getLanguage(),
                attachment.getTitle(),
                attachment.getInfo(),
                attachment.getSize(),
                FileUtil.getMimeType(attachment.getPhysicalName()),
                userId,
                creationDate,
                attachment.getXmlForm()));
    return AttachmentServiceFactory.getAttachmentService()
        .createAttachment(ad_toCreate, input, indexIt);
  }
 public File getAttachmentFile(AttachmentDetail attachment) throws FileNotFoundException {
   File file = new File(FileUtil.convertPathToServerOS(attachment.getAttachmentPath()));
   if (file == null || !file.exists() || !file.isFile()) {
     String baseDir = resources.getString("importRepository");
     file =
         new File(
             FileUtil.convertPathToServerOS(
                 baseDir + File.separatorChar + attachment.getPhysicalName()));
   }
   attachment.setSize(file.length());
   attachment.setType(FileUtil.getMimeType(file.getName()));
   if (!StringUtil.isDefined(attachment.getLogicalName())) {
     attachment.setLogicalName(file.getName());
   }
   return file;
 }
 public ResourceBundleWrapper(String file, Locale locale, boolean hasParent) {
   this.bundle = FileUtil.loadBundle(file, locale);
   if (hasParent) {
     this.parentBundle =
         GeneralPropertiesManager.getGeneralMultilang(locale.getLanguage()).getResourceBundle();
   }
 }
 @After
 public void tearDown() throws Exception {
   ctx.close();
   File cache = new File(IMAGE_CACHE_PATH);
   if (cache.exists()) {
     FileUtil.forceDeletion(new File(IMAGE_CACHE_PATH));
   }
 }
 /**
  * If 3d document
  *
  * @return true or false
  */
 public boolean isOpenOfficeCompatibleDocument() {
   boolean isOpenOfficeCompatibleDocument = false;
   if (getLogicalName() != null) {
     isOpenOfficeCompatibleDocument = FileUtil.isOpenOfficeCompatible(getLogicalName());
     SilverTrace.info(
         "versioning",
         "DocumentVersion.isSpinfireDocument()",
         "root.MSG_GEN_PARAM_VALUE",
         "isOpenOfficeCompatibleDocument = " + isOpenOfficeCompatibleDocument);
   }
   return isOpenOfficeCompatibleDocument;
 }
 private String getWallPaperURL(String spaceId) {
   String id = getShortSpaceId(spaceId);
   String basePath = getSpaceBasePath(id);
   File dir = new File(basePath);
   if (dir.exists() && dir.isDirectory()) {
     Collection<File> wallpapers =
         FileUtils.listFiles(
             dir, FileFilterUtils.prefixFileFilter("wallPaper", IOCase.INSENSITIVE), null);
     for (File wallpaper : wallpapers) {
       if (wallpaper.isFile() && FileUtil.isImage(wallpaper.getName())) {
         return getURLOfElement(id, wallpaper.getName());
       }
     }
   }
   return null;
 }
  /**
   * Uploads the file containing the video and that is identified by the specified field name.
   *
   * @param items the items of the form. One of them is containg the video file.
   * @param itemKey the key of the item containing the video.
   * @param pageContext the context of the page displaying the form.
   * @throws Exception if an error occurs while uploading the video file.
   * @return the identifier of the uploaded attached video file.
   */
  private String uploadVideoFile(
      final List<FileItem> items, final String itemKey, final PagesContext pageContext)
      throws Exception {
    String attachmentId = "";

    FileItem item = FileUploadUtil.getFile(items, itemKey);
    if (!item.isFormField()) {
      String componentId = pageContext.getComponentId();
      String userId = pageContext.getUserId();
      String objectId = pageContext.getObjectId();
      String logicalName = item.getName();
      long size = item.getSize();
      if (StringUtil.isDefined(logicalName)) {
        if (!FileUtil.isWindows()) {
          logicalName = logicalName.replace('\\', File.separatorChar);
          SilverTrace.info(
              "form",
              "VideoFieldDisplayer.uploadVideoFile",
              "root.MSG_GEN_PARAM_VALUE",
              "fullFileName on Unix = " + logicalName);
        }

        logicalName =
            logicalName.substring(
                logicalName.lastIndexOf(File.separator) + 1, logicalName.length());
        String type = FileRepositoryManager.getFileExtension(logicalName);
        String mimeType = item.getContentType();
        String physicalName = Long.toString(System.currentTimeMillis()) + "." + type;
        File dir = getVideoPath(componentId, physicalName);
        item.write(dir);
        AttachmentDetail attachmentDetail =
            createAttachmentDetail(
                objectId,
                componentId,
                physicalName,
                logicalName,
                mimeType,
                size,
                VideoFieldDisplayer.CONTEXT_FORM_VIDEO,
                userId);
        attachmentDetail = AttachmentController.createAttachment(attachmentDetail, true);
        attachmentId = attachmentDetail.getPK().getId();
      }
    }

    return attachmentId;
  }
 /**
  * Copy the image used in the tests into the specified location.
  *
  * @param path the absolute path of the directory into which the original image will be copied.
  * @return the path of the copied image.
  * @throws IOException if the copy fails.
  */
 private String copyOriginalImageInto(String path) throws IOException {
   File destination = new File(path + File.separator + originalImage.getName());
   destination.getParentFile().mkdirs();
   FileUtil.copyFile(originalImage, destination);
   return destination.getCanonicalPath();
 }
  /**
   * Method declaration
   *
   * @param req
   * @param res
   * @throws IOException
   * @throws ServletException
   * @see
   */
  @Override
  public void doPost(HttpServletRequest req, HttpServletResponse res)
      throws ServletException, IOException {
    SilverTrace.info("attachment", "DragAndDrop.doPost", "root.MSG_GEN_ENTER_METHOD");
    HttpRequest request = HttpRequest.decorate(req);
    if (!request.isContentInMultipart()) {
      res.getOutputStream().println("SUCCESS");
      return;
    }

    String userId = req.getParameter("UserId");
    try {
      request.setCharacterEncoding(CharEncoding.UTF_8);
      String componentId = request.getParameter("ComponentId");
      String id = request.getParameter("PubId");
      String lang = I18NHelper.checkLanguage(request.getParameter("lang"));
      SilverTrace.info(
          "attachment",
          "DragAndDrop.doPost",
          "root.MSG_GEN_PARAM_VALUE",
          "componentId = " + componentId + ", id = " + id + ", userId = " + userId);
      boolean bIndexIt = StringUtil.getBooleanValue(request.getParameter("IndexIt"));

      List<FileItem> items = request.getFileItems();
      for (FileItem item : items) {
        SilverTrace.info(
            "attachment",
            "DragAndDrop.doPost",
            "root.MSG_GEN_PARAM_VALUE",
            "item = " + item.getFieldName());
        SilverTrace.info(
            "attachment",
            "DragAndDrop.doPost",
            "root.MSG_GEN_PARAM_VALUE",
            "item = " + item.getName() + "; " + item.getString(CharEncoding.UTF_8));

        if (!item.isFormField()) {
          String fileName = item.getName();
          if (fileName != null) {
            String mimeType = FileUtil.getMimeType(fileName);
            SilverTrace.info(
                "attachment",
                "DragAndDrop.doPost",
                "root.MSG_GEN_PARAM_VALUE",
                "item size = " + item.getSize());
            // create AttachmentDetail Object
            SimpleDocument document =
                new SimpleDocument(
                    new SimpleDocumentPK(null, componentId),
                    id,
                    0,
                    false,
                    new SimpleAttachment(
                        fileName,
                        lang,
                        null,
                        null,
                        item.getSize(),
                        mimeType,
                        userId,
                        new Date(),
                        null));
            document.setDocumentType(determineDocumentType(request));
            File tempFile = File.createTempFile("silverpeas_", fileName);
            try {
              FileUploadUtil.saveToFile(tempFile, item);
              MetadataExtractor extractor = MetadataExtractor.getInstance();
              MetaData metadata = extractor.extractMetadata(tempFile);
              document.setSize(tempFile.length());
              document.setTitle(metadata.getTitle());
              document.setDescription(metadata.getSubject());
              document =
                  AttachmentServiceFactory.getAttachmentService()
                      .createAttachment(document, tempFile, bIndexIt);
            } finally {
              FileUtils.deleteQuietly(tempFile);
            }
            // Specific case: 3d file to convert by Actify Publisher
            ActifyDocumentProcessor.getProcessor().process(document);
          }
        }
      }
    } catch (Exception e) {
      SilverTrace.error("attachment", "DragAndDrop.doPost", "ERREUR", e);
      final StringBuilder sb = new StringBuilder("ERROR: ");
      final String errorMessage =
          SilverpeasTransverseWebErrorUtil.performAppletAlertExceptionMessage(
              e, UserDetail.getById(userId).getUserPreferences().getLanguage());
      if (StringUtil.isDefined(errorMessage)) {
        sb.append(errorMessage);
      } else {
        sb.append(e.getMessage());
      }
      res.getOutputStream().println(sb.toString());
      return;
    }
    res.getOutputStream().println("SUCCESS");
  }
  private PublicationDetail importFile(
      File file,
      ImportReportManager reportManager,
      MassiveReport massiveReport,
      GEDImportExport gedIE,
      PdcImportExport pdcIE,
      ImportSettings settings) {
    SilverTrace.debug(
        "importExport",
        "RepositoriesTypeManager.importFile",
        "root.MSG_GEN_ENTER_METHOD",
        "file = " + file.getName());
    String componentId = gedIE.getCurrentComponentId();
    UserDetail userDetail = gedIE.getCurentUserDetail();
    PublicationDetail pubDetailToCreate = null;
    try {
      // Création du rapport unitaire
      UnitReport unitReport = new UnitReport();
      massiveReport.addUnitReport(unitReport);

      // Check the file size
      ResourceLocator uploadSettings =
          new ResourceLocator("org.silverpeas.util.uploads.uploadSettings", "");
      long maximumFileSize = uploadSettings.getLong("MaximumFileSize", 10485760);
      long fileSize = file.length();
      if (fileSize <= 0L) {
        unitReport.setError(UnitReport.ERROR_NOT_EXISTS_OR_INACCESSIBLE_FILE);
        reportManager.addNumberOfFilesNotImported(1);
        return pubDetailToCreate;
      } else if (fileSize > maximumFileSize) {
        unitReport.setError(UnitReport.ERROR_FILE_SIZE_EXCEEDS_LIMIT);
        reportManager.addNumberOfFilesNotImported(1);
        return pubDetailToCreate;
      }

      // On récupére les infos nécéssaires à la création de la publication
      pubDetailToCreate =
          PublicationImportExport.convertFileInfoToPublicationDetail(file, settings);
      pubDetailToCreate.setPk(new PublicationPK("unknown", "useless", componentId));
      if ((settings.isDraftUsed() && pdcIE.isClassifyingMandatory(componentId))
          || settings.isDraftUsed()) {
        pubDetailToCreate.setStatus(PublicationDetail.DRAFT);
        pubDetailToCreate.setStatusMustBeChecked(false);
      }
      SilverTrace.debug(
          "importExport",
          "RepositoriesTypeManager.importFile",
          "root.MSG_GEN_PARAM_VALUE",
          "pubDetailToCreate.status = " + pubDetailToCreate.getStatus());

      // Création de la publication
      pubDetailToCreate =
          gedIE.createPublicationForMassiveImport(unitReport, pubDetailToCreate, settings);
      unitReport.setLabel(pubDetailToCreate.getPK().getId());

      SilverTrace.debug(
          "importExport",
          "RepositoriesTypeManager.importFile",
          "root.MSG_GEN_PARAM_VALUE",
          "pubDetailToCreate created");

      if (FileUtil.isMail(file.getName())) {
        // if imported file is an e-mail, its textual content is saved in a dedicated form
        // and attached files are attached to newly created publication
        processMailContent(
            pubDetailToCreate, file, reportManager, unitReport, gedIE, settings.isVersioningUsed());
      }

      // add attachment
      SimpleDocument document;
      SimpleDocumentPK pk = new SimpleDocumentPK(null, componentId);
      if (settings.isVersioningUsed()) {
        document = new HistorisedDocument();
        document.setPublicDocument(
            settings.getVersionType() == DocumentVersion.TYPE_PUBLIC_VERSION);
      } else {
        document = new SimpleDocument();
      }
      document.setPK(pk);
      document.setFile(new SimpleAttachment());
      document.setFilename(file.getName());
      document.setSize(fileSize);
      document.getFile().setCreatedBy(userDetail.getId());
      if (settings.useFileDates()) {
        document.setCreated(pubDetailToCreate.getCreationDate());
        if (pubDetailToCreate.getUpdateDate() != null) {
          document.setUpdated(pubDetailToCreate.getUpdateDate());
        }
      } else {
        document.setCreated(new Date());
      }
      document.setForeignId(pubDetailToCreate.getPK().getId());
      document.setContentType(FileUtil.getMimeType(file.getName()));
      AttachmentServiceFactory.getAttachmentService()
          .createAttachment(document, file, pubDetailToCreate.isIndexable(), false);
      reportManager.addNumberOfFilesProcessed(1);
      reportManager.addImportedFileSize(document.getSize(), componentId);
    } catch (Exception ex) {
      massiveReport.setError(UnitReport.ERROR_ERROR);
      SilverTrace.error(
          "importExport", "RepositoriesTypeManager.importFile", "root.EX_NO_MESSAGE", ex);
    }
    return pubDetailToCreate;
  }
 private String getURLOfElement(String spaceId, String filename) {
   return FileServerUtils.getOnlineURL(
       "Space" + spaceId, filename, filename, FileUtil.getMimeType(filename), "look");
 }