/** @return new SilverpeasTemplate */
 protected SilverpeasTemplate getNewTemplate() {
   ResourceLocator rs =
       new ResourceLocator("com.silverpeas.questionReply.settings.questionReplySettings", "");
   Properties templateConfiguration = new Properties();
   templateConfiguration.setProperty(
       SilverpeasTemplate.TEMPLATE_ROOT_DIR, rs.getString("templatePath"));
   templateConfiguration.setProperty(
       SilverpeasTemplate.TEMPLATE_CUSTOM_DIR, rs.getString("customersTemplatePath"));
   return SilverpeasTemplateFactory.createSilverpeasTemplate(templateConfiguration);
 }
  /**
   * @param question the current question-reply question
   * @param users list of users to notify
   * @throws QuestionReplyException
   */
  private void notifyTemplateReply(Question question, Reply reply, UserDetail[] users)
      throws QuestionReplyException {
    try {
      UserDetail user = getUserDetail(getUserId());
      String senderName = user.getFirstName() + " " + user.getLastName();
      String subject = getString("questionReply.notification") + getComponentLabel();
      // String message = senderName + intro + " \n" + content + "\n \n";

      // Get default resource bundle
      String resource = "com.stratelia.webactiv.survey.multilang.surveyBundle";
      ResourceLocator message = new ResourceLocator(resource, I18NHelper.defaultLanguage);

      // Initialize templates
      Map<String, SilverpeasTemplate> templates = new HashMap<String, SilverpeasTemplate>();
      NotificationMetaData notifMetaData =
          new NotificationMetaData(NotificationParameters.NORMAL, subject, templates, "reply");

      List<String> languages = DisplayI18NHelper.getLanguages();
      for (String language : languages) {
        // initialize new resource locator
        message = new ResourceLocator(resource, language);

        // Create a new silverpeas template
        SilverpeasTemplate template = getNewTemplate();
        template.setAttribute("UserDetail", user);
        template.setAttribute("userName", senderName);
        template.setAttribute("QuestionDetail", question);
        template.setAttribute("ReplyDetail", reply);
        template.setAttribute("replyTitle", reply.getTitle());
        template.setAttribute("replyContent", reply.getContent());
        templates.put(language, template);
        notifMetaData.addLanguage(
            language,
            message.getString("questionReply.notification", "") + getComponentLabel(),
            "");
      }
      notifMetaData.setSender(getUserId());
      notifMetaData.addUserRecipients(users);
      notifMetaData.setSource(getSpaceLabel() + " - " + getComponentLabel());
      // notifMetaData.setLink(question._getURL());
      getNotificationSender().notifyUser(notifMetaData);
    } catch (Exception e) {
      throw new QuestionReplyException(
          "QuestionReplySessionController.notify()",
          SilverpeasException.ERROR,
          "questionReply.EX_NOTIFICATION_MANAGER_FAILED",
          "",
          e);
    }
  }
 /**
  * gets the list of form XML fields name use to sort search result
  *
  * @return a list of fields name
  */
 public static synchronized List<String> getFieldsNameList() {
   if (fieldsNameList == null) {
     fieldsNameList = new ArrayList<String>();
     ResourceLocator resource =
         new ResourceLocator("com.silverpeas.searchEngine.searchEngineSettings", "");
     String property = resource.getString("sorting.formXML.fields");
     if (StringUtil.isDefined(property)) {
       StringTokenizer tokens = new StringTokenizer(property, ",");
       while (tokens.hasMoreTokens()) {
         fieldsNameList.add(tokens.nextToken());
       }
     }
   }
   return fieldsNameList;
 }
 public String getWebdavUrl() {
   StringBuilder url = new StringBuilder(500);
   ResourceLocator messages = GeneralPropertiesManager.getGeneralResourceLocator();
   String webAppContext = messages.getString("ApplicationURL");
   if (!webAppContext.endsWith("/")) {
     webAppContext += '/';
   }
   url.append(webAppContext)
       .append(messages.getString("webdav.respository"))
       .append('/')
       .append(messages.getString("webdav.workspace"))
       .append('/')
       .append(getJcrPath());
   return url.toString();
 }
 /**
  * Extract the mime-type from the file name.
  *
  * @param fileName the name of the file.
  * @return the mime-type as a String.
  */
 public static String getMimeType(final String fileName) {
   String mimeType = null;
   final String fileExtension = FileRepositoryManager.getFileExtension(fileName).toLowerCase();
   try {
     if (MIME_TYPES_EXTENSIONS != null) {
       mimeType = MIME_TYPES_EXTENSIONS.getString(fileExtension);
     }
   } catch (final MissingResourceException e) {
     SilverTrace.warn(
         "attachment",
         "AttachmentController",
         "attachment.MSG_MISSING_MIME_TYPES_PROPERTIES",
         null,
         e);
   }
   if (mimeType == null) {
     mimeType = MIME_TYPES.getContentType(fileName);
   }
   if (ARCHIVE_MIME_TYPE.equalsIgnoreCase(mimeType)
       || SHORT_ARCHIVE_MIME_TYPE.equalsIgnoreCase(mimeType)) {
     if (JAR_EXTENSION.equalsIgnoreCase(fileExtension)
         || WAR_EXTENSION.equalsIgnoreCase(fileExtension)
         || EAR_EXTENSION.equalsIgnoreCase(fileExtension)) {
       mimeType = JAVA_ARCHIVE_MIME_TYPE;
     } else if ("3D".equalsIgnoreCase(fileExtension)) {
       mimeType = SPINFIRE_MIME_TYPE;
     }
   }
   if (mimeType == null) {
     mimeType = DEFAULT_MIME_TYPE;
   }
   return mimeType;
 }
 protected boolean getBooleanValue(ResourceLocator rs, String key, boolean defaultValue) {
   String res = rs.getString(key, null);
   boolean valret = defaultValue;
   if (res != null) {
     valret = StringUtil.getBooleanValue(res);
   }
   return valret;
 }
  /*
   * (non-Javadoc)
   * @see com.stratelia.silverpeas.silverStatisticsPeas.control.AbstractPieChartBuilder
   * #getChartTitle()
   */
  @Override
  public String getChartTitle() {
    String title = message.getString("silverStatisticsPeas.VolumeDocsNumber") + " ";

    try {
      if (StringUtil.isDefined(this.spaceId) && (!"WA0".equals(this.spaceId))) {
        SpaceInstLight space = AdminReference.getAdminService().getSpaceInstLightById(this.spaceId);
        title += message.getString("silverStatisticsPeas.FromSpace") + " [" + space.getName() + "]";
      }
    } catch (Exception e) {
      SilverTrace.error(
          "silverStatisticsPeas",
          "DocPieChartBuilder.getChartTitle()",
          "root.EX_SQL_QUERY_FAILED",
          e);
    }
    return title;
  }
 protected String getStringValue(ResourceLocator rs, String key, String defaultValue) {
   String valret = defaultValue;
   try {
     valret = rs.getString(key, null);
     if (valret == null) {
       valret = defaultValue;
     }
   } catch (Exception e) {
     valret = defaultValue;
   }
   return valret;
 }
  static {
    ResourceLocator templateSettings =
        new ResourceLocator("org.silverpeas.publicationTemplate.settings.template", "");
    ResourceLocator mappingSettings =
        new ResourceLocator("org.silverpeas.publicationTemplate.settings.mapping", "");

    templateDir = templateSettings.getString("templateDir");
    defaultTemplateDir = System.getenv("SILVERPEAS_HOME") + "/data/templateRepository/";

    String mappingDir = mappingSettings.getString("mappingDir");
    String mappingRecordTemplateFileName = mappingSettings.getString("templateMapping");

    mappingRecordTemplateFilePath = makePath(mappingDir, mappingRecordTemplateFileName);

    try {
      JAXB_CONTEXT =
          JAXBContext.newInstance(com.silverpeas.publicationTemplate.PublicationTemplateImpl.class);
    } catch (JAXBException e) {
      SilverTrace.fatal("form", "PublicationTemplateManager.init", "CANT_GET_JAXB_CONTEXT", e);
    }
  }
  /**
   * Use this function to be sure to obtain a string without error, even if the property is not
   * found. (in that case, returns empty string)
   *
   * @param rs the properties file
   * @param key the key value to retreive
   * @return
   */
  protected String getSureString(ResourceLocator rs, String key) {
    String valret = null;

    try {
      valret = rs.getString(key, null);
      if (valret == null) {
        valret = "";
      }
    } catch (Exception e) {
      valret = "";
    }
    return valret;
  }
Beispiel #11
0
 /**
  * Format a memory value
  *
  * @param value
  * @param from
  * @param to
  * @return formated value
  */
 public static String formatValue(final BigDecimal value, final memUnit from, final memUnit to) {
   final StringBuilder sb = new StringBuilder(128);
   BigDecimal convertedValue = convertTo(value, from, to);
   int nbMaximumFractionDigits = 2;
   if (EnumSet.of(memUnit.B, memUnit.KB).contains(to)) {
     nbMaximumFractionDigits = 0;
   }
   convertedValue = convertedValue.setScale(nbMaximumFractionDigits, BigDecimal.ROUND_HALF_UP);
   sb.append(new DecimalFormat().format(convertedValue));
   sb.append(" ");
   sb.append(utilMessages.getString(to.getBundleKey(), to.getBundleDefault()));
   return sb.toString();
 }
  /**
   * Generates domain properties file
   *
   * @param domainToCreate domain to create
   * @throws DomainCreationException
   */
  private void generateDomainPropertiesFile(Domain domainToCreate) throws DomainCreationException {
    SilverTrace.info(
        "admin", "SQLDomainService.generateDomainPropertiesFile()", "root.MSG_GEN_ENTER_METHOD");

    String domainName = domainToCreate.getName();
    String domainPropertiesPath = FileRepositoryManager.getDomainPropertiesPath(domainName);

    String cryptMethod =
        templateSettings.getString("database.SQLPasswordEncryption", Authentication.ENC_TYPE_MD5);

    SilverpeasTemplate template = getNewTemplate();
    template.setAttribute("SQLPasswordEncryption", cryptMethod);

    template.setAttribute("SQLClassName", adminSettings.getString("AdminDBDriver"));
    template.setAttribute("SQLJDBCUrl", adminSettings.getString("WaProductionDb"));
    template.setAttribute("SQLAccessLogin", adminSettings.getString("WaProductionUser"));
    template.setAttribute("SQLAccessPasswd", adminSettings.getString("WaProductionPswd"));
    template.setAttribute("SQLUserTableName", "Domain" + domainName + "_User");
    template.setAttribute("SQLGroupTableName", "Domain" + domainName + "_Group");
    template.setAttribute("SQLUserGroupTableName", "Domain" + domainName + "_Group_User_Rel");

    File domainPropertiesFile = new File(domainPropertiesPath);
    PrintWriter out = null;
    try {
      out = new PrintWriter(new FileWriter(domainPropertiesFile));
      out.print(template.applyFileTemplate("templateDomainSQL"));
    } catch (IOException e) {
      domainPropertiesFile.delete();
      throw new DomainCreationException(
          "SQLDomainService.generateDomainPropertiesFile()", domainToCreate.toString(), e);
    } finally {
      if (out != null) {
        out.close();
      }
    }
  }
 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;
 }
 protected int getIntValue(ResourceLocator rs, String key, int defaultValue) {
   String res = rs.getString(key, null);
   int valret = defaultValue;
   if (res != null) {
     try {
       valret = Integer.parseInt(res);
     } catch (Exception e) {
       SilverTrace.error(
           "admin",
           "LDAPSettings.getUserIds()",
           "admin.MSG_ERR_LDAP_GENERAL",
           "Int parse error : " + key + " = " + res,
           e);
     }
   }
   return valret;
 }
  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;
  }
  static {
    ResourceLocator resource = new ResourceLocator("com.silverpeas.pdc.pdc", "");

    delegationEnabled = resource.getBoolean("EnableDelegation", false);
  }
  public ExportReport export(ResourcesWrapper resource)
      throws QuestionReplyException, ParseException {
    StringBuilder sb = new StringBuilder("exportFAQ");
    Date date = new Date();
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd-HH'H'mm'm'ss's'");
    String dateFormatee = dateFormat.format(date);
    sb.append("_").append(dateFormatee);
    sb.append("_").append(getUserDetail().getId());
    ExportReport exportReport = new ExportReport();
    // Stockage de la date de démarage de l'export dans l'objet rapport
    exportReport.setDateDebut(new Date());
    String thisExportDir = sb.toString();

    // Création du dossier d'export exportFAQ_aaaa-mm-jj-hhHmmmsss_userId.zip
    String tempDir = FileRepositoryManager.getTemporaryPath();
    File fileExportDir = new File(tempDir + thisExportDir);
    if (!fileExportDir.exists()) {
      try {
        FileFolderManager.createFolder(fileExportDir);
      } catch (UtilException ex) {
        throw new QuestionReplyException(
            "QuestionReplySessionController.export()",
            SilverpeasRuntimeException.ERROR,
            "root.MSG_FOLDER_NOT_CREATE",
            ex);
      }
    }

    // création du dossier "files"
    String dir = tempDir + thisExportDir;
    String nameForFiles = "files";
    File forFiles = new File(dir + File.separator + nameForFiles);
    try {
      FileFolderManager.createFolder(forFiles);
    } catch (UtilException ex) {
      throw new QuestionReplyException(
          "QuestionReplySessionController.export()",
          SilverpeasRuntimeException.ERROR,
          "root.MSG_FOLDER_NOT_CREATE",
          ex);
    }

    // intégrer la css du disque dans "files"
    ResourceLocator settings =
        new ResourceLocator("com.silverpeas.questionReply.settings.questionReplySettings", "");
    try {
      String chemin = (settings.getString("mappingDir"));
      if (chemin.startsWith("file:")) {
        chemin = chemin.substring(8);
      }
      Collection<File> files = FileFolderManager.getAllFile(chemin);
      for (File file : files) {
        File newFile =
            new File(dir + File.separator + nameForFiles + File.separator + file.getName());
        FileRepositoryManager.copyFile(file.getPath(), newFile.getPath());
      }
    } catch (Exception ex) {
      throw new QuestionReplyException(
          "QuestionReplySessionController.export()",
          SilverpeasRuntimeException.ERROR,
          "QuestionReply.EX_CANT_COPY_FILE",
          ex);
    }

    // création du fichier html
    File fileHTML = new File(dir + File.separator + thisExportDir + ".html");
    FileWriter fileWriter = null;
    try {
      fileHTML.createNewFile();
      fileWriter = new FileWriter(fileHTML.getPath());
      fileWriter.write(toHTML(fileHTML, resource));
    } catch (IOException ex) {
      throw new QuestionReplyException(
          "QuestionReplySessioncontroller.export()",
          SilverpeasRuntimeException.ERROR,
          "QuestionReply.MSG_CAN_WRITE_FILE",
          ex);
    } finally {
      try {
        fileWriter.close();
      } catch (Exception ex) {
      }
    }

    // Création du zip
    try {
      String zipFileName = fileExportDir.getName() + ".zip";
      long zipFileSize =
          ZipManager.compressPathToZip(fileExportDir.getPath(), tempDir + zipFileName);
      exportReport.setZipFileName(zipFileName);
      exportReport.setZipFileSize(zipFileSize);
      exportReport.setZipFilePath(FileServerUtils.getUrlToTempDir(zipFileName));
    } catch (Exception ex) {
      throw new QuestionReplyException(
          "QuestionReplySessioncontroller.export()",
          SilverpeasRuntimeException.ERROR,
          "QuestionReply.MSG_CAN_CREATE_ZIP",
          ex);
    }
    // Stockage de la date de fin de l'export dans l'objet rapport
    exportReport.setDateFin(new Date());
    return exportReport;
  }