public RestRequest(HttpServletRequest request) {
   elements = new HashMap<String, String>(10);
   if ("POST".equalsIgnoreCase(request.getMethod())) {
     action = CREATE;
   } else if ("GET".equalsIgnoreCase(request.getMethod())) {
     action = FIND;
   } else if ("PUT".equalsIgnoreCase(request.getMethod())) {
     action = UPDATE;
   } else if ("DELETE".equalsIgnoreCase(request.getMethod())) {
     action = DELETE;
   }
   String pathInfo = request.getRequestURI();
   String context = request.getContextPath();
   int startIndex = pathInfo.indexOf(context) + context.length();
   pathInfo = pathInfo.substring(startIndex);
   // substring du context
   if (pathInfo.startsWith("/")) {
     pathInfo = pathInfo.substring(1);
   }
   SilverTrace.debug(
       "mailingList", "RestRequest()", "root.MSG_GEN_ENTER_METHOD", "Parsing:" + pathInfo);
   StringTokenizer tokenizer = new StringTokenizer(pathInfo, "/", false);
   String element = tokenizer.nextToken();
   String id = tokenizer.nextToken();
   if ("RmailingList".equalsIgnoreCase(element)) {
     componentId = id;
     SilverTrace.debug(
         "mailingList", "RestRequest()", "root.MSG_GEN_ENTER_METHOD", "componentId=" + id);
   } else if (id != null) {
     elements.put(element, id);
     SilverTrace.debug(
         "mailingList", "RestRequest()", "root.MSG_GEN_ENTER_METHOD", element + '=' + id);
   }
   boolean isKey = true;
   String key = null;
   String value = null;
   while (tokenizer.hasMoreTokens()) {
     value = tokenizer.nextToken();
     if (isKey) {
       key = value;
       isKey = false;
     } else {
       elements.put(key, value);
       SilverTrace.debug(
           "mailingList", "RestRequest()", "root.MSG_GEN_ENTER_METHOD", key + '=' + value);
       isKey = true;
     }
   }
   if (DELETE_ACTION.equalsIgnoreCase(value)) {
     this.action = DELETE;
   } else if (UPDATE_ACTION.equalsIgnoreCase(value)) {
     this.action = UPDATE;
   }
 }
  public void delete(Connection con, String spaceId, String componentId, String userId)
      throws InstanciationException {
    SilverTrace.debug(
        "quickinfo", "QuickInfoInstanciator.delete()", "delete called with: space=" + spaceId);

    // delete publication component
    PublicationInstanciator pub = new PublicationInstanciator("com.stratelia.webactiv.quickinfo");
    pub.delete(con, spaceId, componentId, userId);

    SilverTrace.debug(
        "quickinfo", "QuickInfoInstanciator.delete()", "QuickInfoInstanciator.delete finished");
  }
  @Override
  protected void prepareInsert(String insertQuery, PreparedStatement insert, SpaceUserRoleRow row)
      throws SQLException {
    SilverTrace.debug(
        "admin",
        "SpaceUserRoleTable.prepareInsert",
        "root.MSG_GEN_ENTER_METHOD",
        "usr.id = "
            + row.id
            + ", usr.spaceId = "
            + row.spaceId
            + ", usr.roleName = "
            + row.roleName
            + ", usr.isInherited = "
            + row.isInherited);
    if (row.id == -1) {
      row.id = getNextId();
    }

    insert.setInt(1, row.id);
    insert.setInt(2, row.spaceId);
    insert.setString(3, truncate(row.name, 100));
    insert.setString(4, truncate(row.roleName, 100));
    insert.setString(5, truncate(row.description, 500));
    insert.setInt(6, row.isInherited);
  }
  public void deleteGroup(Connection c, int groupId) throws AdminException {
    PreparedStatement statement = null;
    String theQuery =
        "delete from "
            + drvSettings.getGroupTableName()
            + " where "
            + drvSettings.getGroupSpecificIdColumnName()
            + " = ?";

    try {
      SilverTrace.debug("admin", "SQLGroupTable.deleteGroup", "root.MSG_QUERY", theQuery);
      statement = c.prepareStatement(theQuery);
      statement.setInt(1, groupId);
      statement.executeUpdate();
    } catch (Exception e) {
      throw new AdminException(
          "SQLGroupTable.deleteGroup",
          SilverpeasException.ERROR,
          "root.EX_SQL_QUERY_FAILED",
          "Query = " + theQuery,
          e);
    } finally {
      DBUtil.close(statement);
    }
  }
  public void updateGroup(Connection c, Group g) throws AdminException {
    PreparedStatement statement = null;
    String theQuery =
        "update "
            + drvSettings.getGroupTableName()
            + " set "
            + drvSettings.getGroupNameColumnName()
            + " = ?,"
            + drvSettings.getGroupDescriptionColumnName()
            + " = ?"
            + " where "
            + drvSettings.getGroupSpecificIdColumnName()
            + " = ?";

    try {
      SilverTrace.debug("admin", "SQLGroupTable.updateGroup", "root.MSG_QUERY", theQuery);
      statement = c.prepareStatement(theQuery);
      statement.setString(1, drvSettings.trunc(g.getName(), 100));
      statement.setString(2, drvSettings.trunc(g.getDescription(), 400));
      statement.setInt(3, Integer.parseInt(g.getSpecificId()));
      statement.executeUpdate();
    } catch (Exception e) {
      throw new AdminException(
          "SQLGroupTable.updateGroup",
          SilverpeasException.ERROR,
          "root.EX_SQL_QUERY_FAILED",
          "Query = " + theQuery,
          e);
    } finally {
      DBUtil.close(statement);
    }
  }
 /** Returns the Group whith the given name. */
 public Group getGroupByName(Connection c, String groupName) throws AdminException {
   ResultSet rs = null;
   PreparedStatement statement = null;
   String theQuery =
       "select " + getColumns() + " from " + drvSettings.getGroupTableName() + " where name = ?";
   try {
     SilverTrace.debug("admin", "SQLGroupTable.getGroupByName", "root.MSG_QUERY", theQuery);
     statement = c.prepareStatement(theQuery);
     statement.setString(1, groupName);
     rs = statement.executeQuery();
     if (rs.next()) {
       return fetchGroup(rs);
     } else {
       return null;
     }
   } catch (SQLException e) {
     throw new AdminException(
         "SQLGroupTable.getGroupByName",
         SilverpeasException.ERROR,
         "root.EX_SQL_QUERY_FAILED",
         "Query = " + theQuery,
         e);
   } finally {
     DBUtil.close(rs, statement);
   }
 }
  /** Returns the User whith the given id. */
  public List<Group> getDirectSubGroups(Connection c, int groupId) throws AdminException {
    ResultSet rs = null;
    PreparedStatement statement = null;
    List<Group> theResult = new ArrayList<Group>();
    String theQuery =
        "select "
            + getColumns()
            + " from "
            + drvSettings.getGroupTableName()
            + " where "
            + drvSettings.getGroupParentIdColumnName();

    try {
      if (groupId == -1) theQuery = theQuery + " is null";
      else theQuery = theQuery + " = ?";
      SilverTrace.debug("admin", "SQLGroupTable.getGroup", "root.MSG_QUERY", theQuery);
      statement = c.prepareStatement(theQuery);
      if (groupId != -1) statement.setInt(1, groupId);
      rs = statement.executeQuery();
      while (rs.next()) {
        theResult.add(fetchGroup(rs));
      }
      return theResult;
    } catch (SQLException e) {
      throw new AdminException(
          "SQLGroupTable.getAllGroups",
          SilverpeasException.ERROR,
          "root.EX_SQL_QUERY_FAILED",
          "Query = " + theQuery,
          e);
    } finally {
      DBUtil.close(rs, statement);
    }
  }
 private String getParameterValue(List<FileItem> items, String parameterName) {
   SilverTrace.debug(
       "form",
       "XmlSearchForm.getParameterValue",
       "root.MSG_GEN_ENTER_METHOD",
       "parameterName = " + parameterName);
   FileItem item = getParameter(items, parameterName);
   if (item != null && item.isFormField()) {
     SilverTrace.debug(
         "form",
         "XmlSearchForm.getParameterValue",
         "root.MSG_GEN_EXIT_METHOD",
         "parameterValue = " + item.getString());
     return item.getString();
   }
   return null;
 }
  protected List<PublicationDetail> getUpdatedPublications(
      String spaceId, Date since, int nbPublis) {
    SilverTrace.debug(
        "kmelia",
        "KmeliaTransversal.getPublications()",
        "root.MSG_GEN_ENTER_METHOD",
        "spaceId = " + spaceId + ", nbPublis = " + nbPublis);
    List<String> componentIds = getAvailableComponents(spaceId);
    SilverTrace.debug(
        "kmelia",
        "KmeliaTransversal.getPublications()",
        "root.MSG_GEN_PARAM_VALUE",
        "componentIds = " + componentIds.toString());

    List<PublicationPK> publicationPKs = null;
    try {
      publicationPKs =
          (List<PublicationPK>)
              getPublicationBm()
                  .getUpdatedPublicationPKsByStatus(
                      PublicationDetail.VALID, since, 0, componentIds);
    } catch (Exception e) {
      SilverTrace.error(
          "kmelia",
          "KmeliaTransversal.getPublications()",
          "kmelia.CANT_GET_PUBLICATIONS_PKS",
          "spaceId = " + spaceId,
          e);
    }
    Collection<PublicationPK> filteredPublicationPKs =
        filterPublicationPKs(publicationPKs, nbPublis);
    try {
      return (List<PublicationDetail>) getPublicationBm().getPublications(filteredPublicationPKs);
    } catch (Exception e) {
      SilverTrace.error(
          "kmelia",
          "KmeliaTransversal.getPublications()",
          "kmelia.CANT_GET_PUBLICATIONS",
          "spaceId = " + spaceId,
          e);
    }
    return new ArrayList<PublicationDetail>();
  }
  /**
   * Logs in the user.
   *
   * @see javax.security.auth.spi.LoginModule#login()
   */
  @SuppressWarnings("unchecked")
  @Override
  public boolean login() throws LoginException {
    HttpRequestCallback rcb = new HttpRequestCallback();
    AuthorizerCallback acb = new AuthorizerCallback();
    Callback[] callbacks = new Callback[] {rcb, acb};
    try {
      // First, try to extract a Principal object out of the request
      // directly. If we find one, we're done.
      m_handler.handle(callbacks);
      HttpServletRequest request = rcb.getRequest();
      if (request == null) {
        throw new LoginException("No Http request supplied.");
      }
      UserDetail userDetail =
          (UserDetail) request.getAttribute(SilverpeasWikiAuthorizer.USER_ATTR_NAME);
      if (userDetail == null) {
        throw new LoginException("No user supplied.");
      }
      String[] userRoles = (String[]) request.getAttribute(SilverpeasWikiAuthorizer.ROLE_ATTR_NAME);
      Principal principal = new WikiPrincipal(userDetail.getLogin(), WikiPrincipal.LOGIN_NAME);
      Principal principalFullName =
          new WikiPrincipal(userDetail.getDisplayedName(), WikiPrincipal.FULL_NAME);
      Principal principalWikiName =
          new WikiPrincipal(userDetail.getDisplayedName(), WikiPrincipal.WIKI_NAME);
      SilverTrace.debug(
          "wiki",
          "SilverpeasWikiLoginModule",
          "Added Principal " + principal.getName() + ",Role.ANONYMOUS,Role.ALL");
      m_principals.add(new PrincipalWrapper(principal));
      m_principals.add(new PrincipalWrapper(principalWikiName));
      m_principals.add(new PrincipalWrapper(principalFullName));
      // Add any container roles
      injectWebAuthorizerRoles(acb.getAuthorizer(), request);
      // If login succeeds, commit these roles
      for (String userRole : userRoles) {
        m_principals.add(convertSilverpeasRole(userRole));
      }
      // If login succeeds, remove these principals/roles
      m_principalsToOverwrite.add(WikiPrincipal.GUEST);
      m_principalsToOverwrite.add(Role.ANONYMOUS);
      m_principalsToOverwrite.add(Role.ASSERTED);
      // If login fails, remove these roles
      m_principalsToRemove.add(Role.AUTHENTICATED);

      return true;
    } catch (IOException e) {
      SilverTrace.error("wiki", "SilverpeasWikiLoginModule", "wiki.EX_LOGIN", e);
      return false;
    } catch (UnsupportedCallbackException e) {
      SilverTrace.error("wiki", "SilverpeasWikiLoginModule", "wiki.EX_LOGIN", e);
      return false;
    }
  }
 private String getParameterValues(List<FileItem> items, String parameterName) {
   SilverTrace.debug(
       "form",
       "XmlSearchForm.getParameterValues",
       "root.MSG_GEN_ENTER_METHOD",
       "parameterName = " + parameterName);
   String values = "";
   List<FileItem> params = getParameters(items, parameterName);
   FileItem item = null;
   for (int p = 0; p < params.size(); p++) {
     item = params.get(p);
     values += item.getString();
     if (p < params.size() - 1) {
       values += "##";
     }
   }
   SilverTrace.debug(
       "form",
       "XmlSearchForm.getParameterValues",
       "root.MSG_GEN_EXIT_METHOD",
       "parameterValue = " + values);
   return values;
 }
  /**
   * Method declaration
   *
   * @param message
   */
  @Override
  public void onMessage(Message message) {
    TextMessage textMessage = (TextMessage) message;
    try {
      String msg = textMessage.getText();
      SilverTrace.debug(
          "silverstatistics",
          "SilverStatisticsMessageDriven.onMessage",
          "root.MSG_GEN_PARAM_VALUE",
          "msg=" + msg);

      StringTokenizer stData = new StringTokenizer(msg, SEPARATOR);
      if (stData.hasMoreTokens()) {
        String typeOfStats = stData.nextToken();
        if (typeOfStats.length() + SEPARATOR.length() < msg.length()) {
          String stat = msg.substring(typeOfStats.length() + SEPARATOR.length(), msg.length());
          SilverTrace.info(
              "silverstatistics",
              "SilverStatisticsMessageDriven.onMessage",
              "root.MSG_GEN_PARAM_VALUE",
              "before putStats stat=" + stat);
          getSilverStatistics().putStats(StatType.valueOf(typeOfStats), stat);
          SilverTrace.debug(
              "silverstatistics", "SilverStatisticsMessageDriven.onMessage", "after putStats");
        } else {
          SilverTrace.error(
              "silverstatistics",
              "SilverStatisticsMessageDriven.onMessage",
              "Mauvais message",
              msg);
        }
      }
    } catch (Exception e) {
      SilverTrace.error(
          "silverstatistics", "SilverStatisticsMessageDriven.onMessage", "Probleme jms ", e);
    }
  }
  private Iterator<File> getPathContent(File path) {
    SilverTrace.debug(
        "importExport",
        "RepositoriesTypeManager.getPathContent",
        "root.MSG_GEN_ENTER_METHOD",
        "path = " + path.getPath());
    // Récupération du contenu du dossier
    String[] listContenuStringPath = path.list();

    // Tri alphabétique du contenu
    Arrays.sort(listContenuStringPath);

    List<File> listcontenuPath = convertListStringToListFile(listContenuStringPath, path.getPath());

    return listcontenuPath.iterator();
  }
  public List<String> getSuggestions(String fieldName, String templateName, String componentId) {
    List<String> suggestions = new ArrayList<String>();

    Connection connection = null;
    PreparedStatement statement = null;
    ResultSet rs = null;
    try {
      connection = DBUtil.makeConnection(JNDINames.FORMTEMPLATE_DATASOURCE);

      statement = connection.prepareStatement(suggestionsQuery);
      statement.setString(1, fieldName);
      statement.setString(2, componentId + ":" + templateName);

      SilverTrace.debug(
          "formTemplate",
          "TextFieldImpl.getSuggestions",
          "root.MSG_GEN_PARAM_VALUE",
          "fieldName = "
              + fieldName
              + ", componentId = "
              + componentId
              + ", templateName = "
              + templateName);

      rs = statement.executeQuery();

      String oneSuggestion = "";
      while (rs.next()) {
        oneSuggestion = rs.getString(1);
        if (StringUtil.isDefined(oneSuggestion)) suggestions.add(oneSuggestion);
      }
    } catch (Exception e) {
      SilverTrace.error(
          "formTemplate", "TextFieldImpl.getSuggestions", "root.EX_SQL_QUERY_FAILED", e);
    } finally {
      DBUtil.close(rs, statement);
      try {
        if (connection != null && !connection.isClosed()) connection.close();
      } catch (SQLException e) {
        SilverTrace.error(
            "formTemplate", "TextFieldImpl.getSuggestions", "root.EX_CONNECTION_CLOSE_FAILED", e);
      }
    }
    return suggestions;
  }
 /**
  * If the current Authorizer is a {@link com.ecyrd.jwpwiki.auth.authorize.WebAuthorizer}, this
  * method iterates through each role returned by the authorizer (via {@link
  * com.ecyrd.jwpwiki.auth.authorize.WebAuthorizer#isUserInRole(HttpServletRequest, Role)} ) and
  * injects the appropriate ones into the Subject.
  *
  * @param acb the authorizer callback
  * @param rcb the HTTP request
  */
 @SuppressWarnings("unchecked")
 private final void injectWebAuthorizerRoles(Authorizer authorizer, HttpServletRequest request) {
   Principal[] roles = authorizer.getRoles();
   Set<Principal> foundRoles = new HashSet<Principal>();
   if (authorizer instanceof WebAuthorizer) {
     WebAuthorizer wa = (WebAuthorizer) authorizer;
     for (int i = 0; i < roles.length; i++) {
       if (wa.isUserInRole(request, roles[i])) {
         foundRoles.add(roles[i]);
         SilverTrace.debug(
             "wiki", "SilverpeasWikiLoginModule", "Added Principal " + roles[i].getName() + ".");
       }
     }
   }
   // Add these container roles if login succeeds
   m_principals.addAll(foundRoles);
   // Make sure the same ones are removed if login fails
   m_principalsToRemove.addAll(foundRoles);
 }
  /** Inserts in the database a new Group row. */
  public int createGroup(Connection c, Group group) throws AdminException {
    PreparedStatement statement = null;
    int nextId = 0;
    String theQuery =
        "insert into "
            + drvSettings.getGroupTableName()
            + "("
            + getColumns()
            + ") values (?,?,?,?)";

    try {
      SilverTrace.debug("admin", "SQLGroupTable.createGroup", "root.MSG_QUERY", theQuery);
      statement = c.prepareStatement(theQuery);
      nextId =
          DBUtil.getNextId(
              drvSettings.getGroupTableName(), drvSettings.getGroupSpecificIdColumnName());
      statement.setInt(1, nextId);
      String gid = group.getSuperGroupId();
      if ((gid == null) || (gid.length() <= 0) || (gid.equals("-1")))
        statement.setNull(2, Types.INTEGER);
      else statement.setInt(2, Integer.parseInt(gid));
      statement.setString(3, drvSettings.trunc(group.getName(), 100));
      statement.setString(4, drvSettings.trunc(group.getDescription(), 400));
      statement.executeUpdate();
    } catch (Exception e) {
      throw new AdminException(
          "SQLGroupTable.createGroup",
          SilverpeasException.ERROR,
          "root.EX_SQL_QUERY_FAILED",
          "Query = " + theQuery,
          e);
    } finally {
      DBUtil.close(statement);
    }
    return nextId;
  }
 protected List<String> getAvailableComponents(String spaceId) {
   List<String> componentIds = new ArrayList<String>();
   if (!StringUtil.isDefined(spaceId)) {
     String[] cIds = getOrganizationControl().getComponentIdsForUser(userId, "kmelia");
     componentIds.addAll(Arrays.asList(cIds));
     cIds = getOrganizationControl().getComponentIdsForUser(userId, "toolbox");
     componentIds.addAll(Arrays.asList(cIds));
     cIds = getOrganizationControl().getComponentIdsForUser(userId, "kmax");
     componentIds.addAll(Arrays.asList(cIds));
   } else {
     String[] cIds = getOrganizationControl().getAvailCompoIds(spaceId, userId);
     SilverTrace.debug(
         "kmelia",
         "KmeliaTransversal.getPublications()",
         "root.MSG_GEN_PARAM_VALUE",
         "#cIds = " + cIds.length);
     for (String id : cIds) {
       if (id.startsWith("kmelia") || id.startsWith("toolbox") || id.startsWith("kmax")) {
         componentIds.add(id);
       }
     }
   }
   return componentIds;
 }
  /** prepareStatementSetProperties */
  private int prepareStatementSetProperties(PreparedStatement prepStmt, T bean)
      throws IllegalAccessException, SQLException, InvocationTargetException {
    int count = 1;

    for (PropertyDescriptor property : properties) {
      String type = property.getPropertyType().getName();
      if (isInteger(type)) {
        Integer integer = (Integer) property.getReadMethod().invoke(bean);
        if (integer == null) {
          prepStmt.setInt(count, -1);
        } else {
          prepStmt.setInt(count, integer);
        }
        count++;
      } else if (isLong(type)) {
        Long l = (Long) property.getReadMethod().invoke(bean);
        if (l == null) {
          prepStmt.setLong(count, 0);
        } else {
          prepStmt.setLong(count, l);
        }
        count++;
      } else if (isBoolean(type)) {
        Boolean l = (Boolean) property.getReadMethod().invoke(bean);
        if (l == null) {
          prepStmt.setBoolean(count, false);
        } else {
          prepStmt.setBoolean(count, l);
        }
        count++;
      } else if (isString(type)) {
        String string = (String) property.getReadMethod().invoke(bean);
        if (string == null) {
          prepStmt.setNull(count, Types.VARCHAR);
        } else {
          prepStmt.setString(count, string);
        }
        count++;
      } else if (isDate(type)) {
        Date date = (Date) property.getReadMethod().invoke(bean);
        if (date == null) {
          prepStmt.setNull(count, Types.VARCHAR);
        } else {
          prepStmt.setString(count, DateUtil.date2SQLDate(date));
        }
        count++;
      } else if (isFloat(type)) {
        Float f = (Float) property.getReadMethod().invoke(bean);
        if (f == null) {
          prepStmt.setFloat(count, 0);
        } else {
          prepStmt.setFloat(count, f);
        }
        count++;
      } else if (isDouble(type)) {
        Double d = (Double) property.getReadMethod().invoke(bean);
        if (d == null) {
          prepStmt.setDouble(count, 0);
        } else {
          prepStmt.setDouble(count, d);
        }
        count++;
      } else {
        SilverTrace.debug(
            "persistence",
            "SilverpeasBeanDAO.prepareStatementSetProperties",
            "persistence.MSG_WARN_PROPERTIE_NOT_MANAGED",
            type);
      }
    }
    return count;
  }
  /**
   * This method has to be implemented by the component request rooter it has to compute a
   * destination page
   *
   * @param function The entering request function (ex : "Main.jsp")
   * @param jobManagerSC The component Session Control, build and initialised.
   * @return The complete destination URL for a forward (ex :
   *     "/almanach/jsp/almanach.jsp?flag=user")
   */
  public String getDestination(
      String function, JobManagerPeasSessionController jobManagerSC, HttpServletRequest request) {
    String destination = "";
    SilverTrace.info(
        "jobManagerPeas",
        "JobManagerPeasRequestRouter.getDestination()",
        "root.MSG_GEN_PARAM_VALUE",
        "User="******" Function=" + function);

    try {
      if (function.startsWith("Main")) {
        destination = "/jobManagerPeas/jsp/jobManager.jsp";
      } else if (function.startsWith("TopBarManager")) // lors du permier
      // accès=> via jobManager.jsp
      {
        // set le service actif par le service par defaut; active aussi une
        // opération par défaut pour ce service
        jobManagerSC.changeServiceActif(jobManagerSC.getIdDefaultService());
        destination = this.setAttributes(request, jobManagerSC);
      } else if (function.startsWith("ChangeService")) {
        String idService = request.getParameter("Id");
        // changer l'id représentant le service actif
        // set aussi l' idCurrentOperationActif pour ce service (à la vaeleur
        // par defaut ou la valeur précdente si existe
        jobManagerSC.changeServiceActif(idService);
        destination = this.setAttributes(request, jobManagerSC);
      } else if (function.startsWith("ChangeOperation")) {
        String idOperation = request.getParameter("Id");
        if ("15".equals(idOperation)) {
          Boolean mode = jobManagerSC.isAppInMaintenance();
          SilverTrace.debug(
              "jobManagerPeas",
              "ChangeOperation",
              "root.MSG_GEN_PARAM_VALUE",
              "mode=" + mode.toString());
          request.setAttribute("mode", mode.toString());
        }
        // changer l'id représentant l'opération active
        // set idCurrentOperationActif avec cette id
        jobManagerSC.changeOperationActif(idOperation);
        destination = this.setAttributes(request, jobManagerSC);
      } else if (function.startsWith("SetMaintenanceMode")) {
        jobManagerSC.setAppModeMaintenance(Boolean.parseBoolean(request.getParameter("mode")));
        destination = getDestination("ManageMaintenanceMode", jobManagerSC, request);
      } else if (function.startsWith("ManageMaintenanceMode")) {
        Boolean mode = jobManagerSC.isAppInMaintenance();
        SilverTrace.debug(
            "jobManagerPeas",
            "getDestination",
            "root.MSG_GEN_PARAM_VALUE",
            "mode=" + mode.toString());
        request.setAttribute("mode", mode.toString());
        destination = "/jobManagerPeas/jsp/manageMaintenance.jsp";
      } else {
        destination = "/jobManagerPeas/jsp/" + function;
      }
    } catch (Exception e) {
      request.setAttribute("javax.servlet.jsp.jspException", e);
      destination = "/admin/jsp/errorpageMain.jsp";
    }

    SilverTrace.info(
        "jobManagerPeas",
        "JobManagerPeasRequestRouter.getDestination()",
        "root.MSG_GEN_PARAM_VALUE",
        "Destination=" + destination);
    return destination;
  }
  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;
  }
  /**
   * Method declaration
   *
   * @param req
   * @param res
   * @throws IOException
   * @throws ServletException
   * @see
   */
  @Override
  public void doPost(HttpServletRequest req, HttpServletResponse res)
      throws ServletException, IOException {
    SilverTrace.info("peasUtil", "FileServer.doPost", "root.MSG_GEN_ENTER_METHOD");
    String mimeType = req.getParameter(MIME_TYPE_PARAMETER);
    String sourceFile = req.getParameter(SOURCE_FILE_PARAMETER);
    String archiveIt = req.getParameter(ARCHIVE_IT_PARAMETER);
    String dirType = req.getParameter(DIR_TYPE_PARAMETER);
    String userId = req.getParameter(USER_ID_PARAMETER);
    String componentId = req.getParameter(COMPONENT_ID_PARAMETER);
    String typeUpload = req.getParameter(TYPE_UPLOAD_PARAMETER);
    String zip = req.getParameter(ZIP_PARAMETER);
    String fileName = req.getParameter(FILE_NAME_PARAMETER);
    String tempDirectory = FileRepositoryManager.getTemporaryPath("useless", componentId);
    File tempFile = null;
    String attachmentId = req.getParameter(ATTACHMENT_ID_PARAMETER);
    String language = req.getParameter(LANGUAGE_PARAMETER);
    if (!StringUtil.isDefined(attachmentId)) {
      attachmentId = req.getParameter(VERSION_ID_PARAMETER);
    }
    SimpleDocument attachment = null;
    if (StringUtil.isDefined(attachmentId)) {
      attachment =
          AttachmentServiceFactory.getAttachmentService()
              .searchDocumentById(new SimpleDocumentPK(attachmentId, componentId), language);
      if (attachment != null) {
        mimeType = attachment.getContentType();
        sourceFile = attachment.getFilename();
      }
    }
    HttpSession session = req.getSession(true);
    MainSessionController mainSessionCtrl =
        (MainSessionController)
            session.getAttribute(MainSessionController.MAIN_SESSION_CONTROLLER_ATT);
    if ((mainSessionCtrl == null) || (!isUserAllowed(mainSessionCtrl, componentId))) {
      SilverTrace.warn(
          "peasUtil",
          "FileServer.doPost",
          "root.MSG_GEN_SESSION_TIMEOUT",
          "NewSessionId="
              + session.getId()
              + URLManager.getApplicationURL()
              + GeneralPropertiesManager.getString("sessionTimeout"));
      res.sendRedirect(
          URLManager.getApplicationURL() + GeneralPropertiesManager.getString("sessionTimeout"));
      return;
    }

    String filePath = null;
    if (typeUpload != null) {
      filePath = sourceFile;
    } else {
      if (dirType != null) {
        if (dirType.equals(GeneralPropertiesManager.getString("RepositoryTypeTemp"))) {
          filePath = FileRepositoryManager.getTemporaryPath("useless", componentId) + sourceFile;
        }
      } else if (attachment != null) {
        // the file to download is not in a temporary directory
        filePath = attachment.getAttachmentPath();
      } else {
        String directory = req.getParameter(DIRECTORY_PARAMETER);
        filePath =
            FileRepositoryManager.getAbsolutePath(componentId)
                + directory
                + File.separator
                + sourceFile;
      }
    }
    res.setContentType(mimeType);
    SilverTrace.debug("peasUtil", "FileServer.doPost()", "root.MSG_GEN_PARAM_VALUE", " zip=" + zip);
    if (zip != null) {
      res.setContentType(MimeTypes.ARCHIVE_MIME_TYPE);
      tempFile = File.createTempFile("zipfile", ".zip", new File(tempDirectory));
      SilverTrace.debug(
          "peasUtil",
          "FileServer.doPost()",
          "root.MSG_GEN_PARAM_VALUE",
          " filePath ="
              + filePath
              + " tempFile.getCanonicalPath()="
              + tempFile.getCanonicalPath()
              + " fileName="
              + fileName);
      ZipManager.compressFile(filePath, tempFile.getCanonicalPath());
      filePath = tempFile.getCanonicalPath();
    }

    // display the preview code generated by the production tools
    if (zip == null) {
      if (tempFile != null) {
        sendFile(res, tempFile.getCanonicalPath());
      } else {
        sendFile(res, filePath);
      }
    }

    if (tempFile != null) {
      SilverTrace.info(
          "peasUtil",
          "FileServer.doPost()",
          "root.MSG_GEN_ENTER_METHOD",
          " tempFile != null " + tempFile);
      FileUtils.deleteQuietly(tempFile);
    }

    if (StringUtil.isDefined(archiveIt)) {
      String nodeId = req.getParameter(NODE_ID_PARAMETER);
      String pubId = req.getParameter(PUBLICATION_ID_PARAMETER);
      ForeignPK pubPK = new ForeignPK(pubId, componentId);
      try {
        StatisticBm statisticBm =
            EJBUtilitaire.getEJBObjectRef(JNDINames.STATISTICBM_EJBHOME, StatisticBm.class);
        statisticBm.addStat(userId, pubPK, 1, "Publication");
      } catch (Exception ex) {
        SilverTrace.warn(
            "peasUtil",
            "FileServer.doPost",
            "peasUtil.CANNOT_WRITE_STATISTICS",
            "pubPK = " + pubPK + " and nodeId = " + nodeId,
            ex);
      }
    }
  }
  public FileFolder(String rootPath, String path, boolean isAdmin, String componentId) {
    files = new ArrayList(0);
    folders = new ArrayList(0);

    String childPath = null;

    try {
      SilverTrace.debug(
          "silverCrawler",
          "FileFolder.FileFolder()",
          "root.MSG_GEN_PARAM_VALUE",
          "Starting constructor for FileFolder. Path = " + path);
      File f = new File(path);
      File fChild;

      SilverTrace.debug(
          "silverCrawler",
          "FileFolder.FileFolder()",
          "root.MSG_GEN_PARAM_VALUE",
          "isExists " + f.exists() + " isFile=" + f.isFile());
      if (f.exists()) {
        this.name = f.getName();
        String[] children_name = f.list();

        IndexReader reader = null;
        boolean isIndexed = false;

        if (isAdmin) {
          // ouverture de l'index
          String indexPath = FileRepositoryManager.getAbsoluteIndexPath("", componentId);

          if (IndexReader.indexExists(indexPath)) reader = IndexReader.open(indexPath);
        }

        for (int i = 0; children_name != null && i < children_name.length; i++) {
          SilverTrace.debug(
              "silverCrawler",
              "FileFolder.FileFolder()",
              "root.MSG_GEN_PARAM_VALUE",
              "Name = " + children_name[i]);
          fChild = new File(path + File.separator + children_name[i]);
          isIndexed = false;
          if (isAdmin) {
            // rechercher si le répertoire (ou le fichier) est indexé
            String pathIndex = componentId + "|";
            if (fChild.isDirectory()) pathIndex = pathIndex + "LinkedDir" + "|";
            else pathIndex = pathIndex + "LinkedFile" + "|";
            pathIndex = pathIndex + fChild.getPath();
            SilverTrace.debug(
                "silverCrawler",
                "FileFolder.FileFolder()",
                "root.MSG_GEN_PARAM_VALUE",
                "pathIndex = " + pathIndex);

            Term term = new Term("key", pathIndex);
            if (reader != null && reader.docFreq(term) == 1) isIndexed = true;
          }

          if (fChild.isDirectory()) {
            folders.add(
                new FileDetail(
                    fChild.getName(), fChild.getPath(), fChild.length(), true, isIndexed));
          } else {
            childPath = fChild.getPath().substring(rootPath.length() + 1);
            files.add(
                new FileDetail(fChild.getName(), childPath, fChild.length(), false, isIndexed));
          }
        }

        // fermeture de l'index
        if (reader != null && isAdmin) reader.close();
      }
    } catch (Exception e) {
      throw new SilverCrawlerRuntimeException(
          "FileFolder.FileFolder()",
          SilverpeasRuntimeException.ERROR,
          "silverCrawler.IMPOSSIBLE_DACCEDER_AU_REPERTOIRE",
          e);
    }
  }