/** @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);
 }
 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;
  }
  /**
   * Generates domain authentication properties file
   *
   * @param domainToCreate domain to create
   * @throws DomainCreationException
   */
  private void generateDomainAuthenticationPropertiesFile(Domain domainToCreate)
      throws DomainCreationException {
    SilverTrace.info(
        "admin",
        "SQLDomainService.generateDomainAuthenticationPropertiesFile()",
        "root.MSG_GEN_ENTER_METHOD");

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

    boolean allowPasswordChange = templateSettings.getBoolean("allowPasswordChange", true);
    String cryptMethod =
        templateSettings.getString("database.SQLPasswordEncryption", Authentication.ENC_TYPE_MD5);

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

    template.setAttribute("SQLDriverClass", 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");

    File domainPropertiesFile = new File(domainPropertiesPath);
    File authenticationPropertiesFile = new File(authenticationPropertiesPath);
    PrintWriter out = null;
    try {
      out = new PrintWriter(new FileWriter(authenticationPropertiesFile));
      out.print(template.applyFileTemplate("templateDomainAuthenticationSQL"));
    } catch (IOException e) {
      domainPropertiesFile.delete();
      authenticationPropertiesFile.delete();
      throw new DomainCreationException(
          "SQLDomainService.generateDomainAuthenticationPropertiesFile()",
          domainToCreate.toString(),
          e);
    } finally {
      out.close();
    }
  }
 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;
  }
 /**
  * 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();
 }
  /**
   * @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 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;
 }
  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;
  }