public HashMap<String, String> getFormValues(String language) {
    HashMap<String, String> formValues = new HashMap<String, String>();
    if ("0".equals(getInfoId())) {
      // this publication does not use a form
      return formValues;
    }

    DataRecord data = null;
    PublicationTemplate pub = null;
    try {
      pub =
          PublicationTemplateManager.getInstance()
              .getPublicationTemplate(getPK().getInstanceId() + ":" + getInfoId());
      data = pub.getRecordSet().getRecord(pk.getId());
    } catch (Exception e) {
      SilverTrace.warn(
          "publication",
          "PublicationDetail.getFormValues",
          "CANT_GET_FORM_RECORD",
          "pubId = " + getPK().getId() + "infoId = " + getInfoId());
    }

    if (data == null) {
      return formValues;
    }

    String fieldNames[] = data.getFieldNames();
    PagesContext pageContext = new PagesContext();
    pageContext.setLanguage(language);
    for (String fieldName : fieldNames) {
      try {
        Field field = data.getField(fieldName);
        GenericFieldTemplate fieldTemplate =
            (GenericFieldTemplate) pub.getRecordTemplate().getFieldTemplate(fieldName);
        FieldDisplayer fieldDisplayer =
            TypeManager.getInstance().getDisplayer(fieldTemplate.getTypeName(), "simpletext");
        StringWriter sw = new StringWriter();
        PrintWriter out = new PrintWriter(sw);
        fieldDisplayer.display(out, field, fieldTemplate, pageContext);
        formValues.put(fieldName, sw.toString());
      } catch (Exception e) {
        SilverTrace.warn(
            "publication",
            "PublicationDetail.getFormValues",
            "CANT_GET_FIELD_VALUE",
            "pubId = " + getPK().getId() + "fieldName = " + fieldName,
            e);
      }
    }
    return formValues;
  }
 /**
  * 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;
 }
  /**
   * Method declaration
   *
   * @param id
   * @param percent
   * @throws TodoException
   * @see
   */
  public void setToDoPercentCompleted(String id, String percent) throws TodoException {
    SilverTrace.info(
        "todo", "ToDoSessionController.setToDoPercentCompleted()", "root.MSG_GEN_ENTER_METHOD");
    ToDoHeader todo = getToDoHeader(id);

    try {
      todo.setPercentCompleted(new Integer(percent).intValue());
    } catch (Exception e) {
      SilverTrace.warn(
          "todo",
          "ToDoSessionController.setToDoPercentCompleted()",
          "todo.MSG_CANT_SET_TODO_PERCENTCOMPLETED");
    }

    try {
      calendarBm.updateToDo(todo);
      SilverTrace.info(
          "todo", "ToDoSessionController.setToDoPercentCompleted()", "root.MSG_GEN_EXIT_METHOD");
    } catch (Exception e) {
      throw new TodoException(
          "ToDoSessionController.setToDoPercentCompleted()",
          SilverpeasException.ERROR,
          "todo.MSG_CANT_UPDATE_TODO_DETAIL",
          e);
    }
  }
  /**
   * Remove domain authentication and settings properties file
   *
   * @param domainToRemove domain to remove
   * @throws DomainDeletionException
   */
  private void removeDomainPropertiesFile(Domain domainToRemove) throws DomainDeletionException {
    SilverTrace.info(
        "admin",
        "SQLDomainService.removeDomainAuthenticationPropertiesFile()",
        "root.MSG_GEN_ENTER_METHOD");

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

    File domainPropertiesFile = new File(domainPropertiesPath);
    File authenticationPropertiesFile = new File(authenticationPropertiesPath);

    boolean domainPropertiesFileDeleted = domainPropertiesFile.delete();
    boolean authenticationPropertiesFileDeleted = authenticationPropertiesFile.delete();

    if ((!domainPropertiesFileDeleted) || (!authenticationPropertiesFileDeleted)) {
      SilverTrace.warn(
          "admin",
          "SQLDomainService.removeDomainAuthenticationPropertiesFile()",
          "admin.EX_DELETE_DOMAIN_PROPERTIES",
          "domainPropertiesFileDeleted:"
              + domainPropertiesFileDeleted
              + ", authenticationPropertiesFileDeleted:"
              + authenticationPropertiesFileDeleted);
    }
  }
  /**
   * Method declaration
   *
   * @param name
   * @param description
   * @param priority
   * @param classification
   * @param startDay
   * @param startHour
   * @param endDay
   * @param endHour
   * @param percent
   * @return
   * @throws TodoException
   * @see
   */
  public String addToDo(
      String name,
      String description,
      String priority,
      String classification,
      Date startDay,
      String startHour,
      Date endDay,
      String endHour,
      String percent)
      throws TodoException {
    String result = null;

    SilverTrace.info("todo", "ToDoSessionController.addToDo()", "root.MSG_GEN_ENTER_METHOD");
    ToDoHeader todo = new ToDoHeader(name, getUserId());

    todo.setDescription(description);
    try {
      todo.getPriority().setValue(new Integer(priority).intValue());
    } catch (Exception e) {
      SilverTrace.warn(
          "todo", "ToDoSessionController.addToDo()", "todo.MSG_CANT_SET_TODO_PRIORITY");
    }
    try {
      todo.setPercentCompleted(new Integer(percent).intValue());
    } catch (Exception e) {
      SilverTrace.warn(
          "todo", "ToDoSessionController.addToDo()", "todo.MSG_CANT_SET_TODO_PERCENTCOMPLETED");
    }
    try {
      todo.getClassification().setString(classification);
      todo.setStartDate(startDay);
      todo.setStartHour(startHour);
      todo.setEndDate(endDay);
      todo.setEndHour(endHour);
      result = calendarBm.addToDo(todo);
    } catch (Exception e) {
      throw new TodoException(
          "ToDoSessionController.addToDo()",
          SilverpeasException.ERROR,
          "todo.MSG_CANT_ADD_TODO",
          e);
    }
    SilverTrace.info("todo", "ToDoSessionController.addToDo()", "root.MSG_GEN_EXIT_METHOD");
    return result;
  }
  /**
   * Method declaration
   *
   * @param id
   * @param name
   * @param description
   * @param priority
   * @param classification
   * @param startDay
   * @param startHour
   * @param endDay
   * @param endHour
   * @param percent
   * @throws TodoException
   * @see
   */
  public void updateToDo(
      String id,
      String name,
      String description,
      String priority,
      String classification,
      Date startDay,
      String startHour,
      Date endDay,
      String endHour,
      String percent)
      throws TodoException {
    SilverTrace.info("todo", "ToDoSessionController.updateToDo()", "root.MSG_GEN_ENTER_METHOD");
    ToDoHeader todo = getToDoHeader(id);

    todo.setName(name);
    todo.setDescription(description);
    try {
      todo.getPriority().setValue(new Integer(priority).intValue());
    } catch (Exception e) {
      SilverTrace.warn(
          "todo", "ToDoSessionController.updateToDo()", "todo.MSG_CANT_SET_TODO_PRIORITY");
    }
    try {
      todo.setPercentCompleted(new Integer(percent).intValue());
    } catch (Exception e) {
      SilverTrace.warn(
          "todo", "ToDoSessionController.updateToDo()", "todo.MSG_CANT_SET_TODO_PERCENTCOMPLETED");
    }
    try {
      todo.getClassification().setString(classification);
      todo.setStartDate(startDay);
      todo.setStartHour(startHour);
      todo.setEndDate(endDay);
      todo.setEndHour(endHour);
      calendarBm.updateToDo(todo);
      SilverTrace.info("todo", "ToDoSessionController.updateToDo()", "root.MSG_GEN_EXIT_METHOD");
    } catch (Exception e) {
      throw new TodoException(
          "ToDoSessionController.updateToDo()",
          SilverpeasException.ERROR,
          "todo.MSG_CANT_UPDATE_TODO_DETAIL",
          e);
    }
  }
 public SearchEngine obtainImplementation() {
   if (searchEngine == null) {
     SilverTrace.warn(
         "SimpleSearchEngine",
         getClass().getSimpleName() + ".getSearchEngine()",
         "EX_NO_MESSAGES",
         "IoC container not bootstrapped or no SearchEngine bean found!");
   }
   return searchEngine;
 }
 /**
  * Builds and sends a webpages notification. A warning message is logged when an exception is
  * catched.
  *
  * @param resource
  * @param userId
  */
 public static void notify(final NodePK resource, final String userId) {
   try {
     UserNotificationHelper.buildAndSend(new WebPagesUserNotifier(resource, userId));
   } catch (final Exception e) {
     SilverTrace.warn(
         "webPages",
         "WebPagesUserNotifier.notify()",
         "webPages.EX_IMPOSSIBLE_DALERTER_LES_UTILISATEURS",
         "nodeId = " + resource.getId(),
         e);
   }
 }
 /**
  * Builds and sends a file sharing notification. A warning message is logged when an exception is
  * catched.
  *
  * @param resource the ticket file sharing resource
  */
 public static void notify(final Ticket resource, final SharingNotificationVO fileSharingParam) {
   try {
     UserNotificationHelper.buildAndSend(
         new FileSharingUserNotification(resource, fileSharingParam));
   } catch (final Exception e) {
     SilverTrace.warn(
         "webPages",
         "FileSharingUserNotification.notify()",
         "fileSharing.EX_ALERT_USERS_ERROR",
         "tocken = " + resource.getToken(),
         e);
   }
 }
  /**
   * Method declaration THIS FUNCTION THROW EXCEPTION ONLY WHEN NO SYNCHRO IS RUNNING
   *
   * @param lds
   * @param parentId
   * @return
   * @throws AdminException
   * @see
   */
  protected LDAPEntry[] getChildGroupsEntry(String lds, String parentId, String extraFilter)
      throws AdminException {
    if ((parentId != null) && (parentId.length() > 0)) { // ALL ROOT GROUPS
      return ArrayUtil.EMPTY_LDAP_ENTRY_ARRAY;
    } else {
      LDAPEntry[] theEntries = null;
      String theFilter;

      if ((extraFilter != null) && (extraFilter.length() > 0)) {
        theFilter = "(&" + extraFilter + driverSettings.getGroupsFullFilter() + ")";
      } else {
        theFilter = driverSettings.getGroupsFullFilter();
      }
      try {
        SilverTrace.info(
            "admin",
            "LDAPGroupSamse.getChildGroupsEntry()",
            "root.MSG_GEN_PARAM_VALUE",
            "Root Group Search");
        theEntries =
            LDAPUtility.search1000Plus(
                lds,
                driverSettings.getGroupsSpecificGroupsBaseDN(),
                driverSettings.getScope(),
                theFilter,
                driverSettings.getGroupsNameField(),
                driverSettings.getGroupAttributes());
        SynchroReport.debug(
            "LDAPGroupSamse.getChildGroupsEntry()",
            "Récupération de " + theEntries.length + " groupes racine",
            null);
      } catch (AdminException e) {
        if (synchroInProcess) {
          SilverTrace.warn(
              "admin",
              "LDAPGroupSamse.getChildGroupsEntry()",
              "admin.EX_ERR_CHILD_GROUPS",
              "ParentGroupId=" + parentId,
              e);
          append("PB getting Group's subgroups : ").append(parentId).append("\n");
          SynchroReport.error(
              "LDAPGroupSamse.getChildGroupsEntry()",
              "Erreur lors de la récupération des groupes racine (parentId = " + parentId + ")",
              e);
        } else {
          throw e;
        }
      }
      return theEntries;
    }
  }
 @Override
 public void generateThumbnailsFrom(File video) {
   if (video.exists() && video.isFile()) {
     MetaData metadata = MetadataExtractor.getInstance().extractMetadata(video);
     TimeData timeData = metadata.getDuration();
     if (timeData != null) {
       File thumbnailDir = video.getParentFile();
       for (ThumbnailPeriod thumbPeriod : ThumbnailPeriod.ALL_VALIDS) {
         double timePeriod = thumbPeriod.getPercent() * timeData.getTimeAsLong() / 1000;
         FFmpegUtil.extractVideoThumbnail(
             video, new File(thumbnailDir, thumbPeriod.getFilename()), (int) timePeriod);
       }
     } else {
       SilverTrace.warn(
           "VideoTool",
           getClass().getSimpleName(),
           "Problem to retrieve video duration, process video thumbnails has failed");
     }
   }
 }
  /**
   * @return the list of PublicationTemplate which contains a search form
   * @throws PublicationTemplateException
   */
  public List<PublicationTemplate> getSearchablePublicationTemplates()
      throws PublicationTemplateException {
    List<PublicationTemplate> searchableTemplates = new ArrayList<PublicationTemplate>();

    List<PublicationTemplate> publicationTemplates = getPublicationTemplates();
    for (PublicationTemplate template : publicationTemplates) {
      try {
        if (template.getSearchForm() != null) {
          searchableTemplates.add(template);
        }
      } catch (PublicationTemplateException e) {
        // Catch exception here in case of one of searchable form is malformed
        // Valid forms must be displayed in search screen
        SilverTrace.warn(
            "form",
            "PublicationTemplateManager.getSearchablePublicationTemplates",
            "form.ERROR_ONE_ILL_FORM",
            template.getName() + " is malformed");
      }
    }

    return searchableTemplates;
  }
 @Override
 public void indexPersonalComponent(String personalComponent) {
   SilverTrace.info(
       silvertraceModule,
       "ApplicationIndexer.indexPersonalComponent()",
       "applicationIndexer.MSG_START_INDEXING_PERSONAL_COMPONENT",
       "personalComponent = " + personalComponent);
   String compoName = firstLetterToLowerCase(personalComponent);
   try {
     ComponentContext componentContext = mainSessionController.createComponentContext(null, null);
     componentContext.setCurrentComponentId(personalComponent);
     ComponentIndexerInterface componentIndexer =
         (ComponentIndexerInterface)
             Class.forName(
                     "com.stratelia.webactiv." + compoName + "." + personalComponent + "Indexer")
                 .newInstance();
     componentIndexer.index(mainSessionController, componentContext);
   } catch (ClassNotFoundException ce) {
     SilverTrace.warn(
         silvertraceModule,
         "ApplicationIndexer.indexPersonalComponent()",
         "applicationIndexer.EX_INDEXER_PERSONAL_COMPONENT_NOT_FOUND",
         "personalComponent = " + personalComponent);
   } catch (Exception e) {
     SilverTrace.error(
         silvertraceModule,
         "ApplicationIndexer.indexPersonalComponent()",
         "applicationIndexer.EX_INDEXING_PERSONAL_COMPONENT_FAILED",
         "personalComponent = " + personalComponent,
         e);
   }
   SilverTrace.info(
       silvertraceModule,
       "ApplicationIndexer.indexPersonalComponent()",
       "applicationIndexer.MSG_END_INDEXING_PERSONAL_COMPONENT",
       "personalComponent = " + personalComponent);
 }
  /**
   * Method declaration THIS FUNCTION THROW EXCEPTION ONLY WHEN NO SYNCHRO IS RUNNING
   *
   * @param lds
   * @param parentId
   * @return
   * @throws AdminException
   * @see
   */
  @Override
  protected LDAPEntry[] getChildGroupsEntry(String lds, String parentId, String extraFilter)
      throws AdminException {
    LDAPEntry theEntry = null;
    LDAPEntry childGroupEntry = null;
    LDAPEntry parentGroupEntry = null;
    Vector<LDAPEntry> entryVector = new Vector<LDAPEntry>();
    String[] stringVals = null;
    LDAPEntry[] theEntries = null;
    int i;
    String theFilter;

    try {
      if ((parentId != null) && (parentId.length() > 0)) {
        SilverTrace.info(
            "admin",
            "LDAPGroupUniqueDescriptor.getChildGroupsEntry()",
            "root.MSG_GEN_PARAM_VALUE",
            "Root Group Search : " + parentId);
        theEntry = getGroupEntry(lds, parentId);
        stringVals =
            LDAPUtility.getAttributeValues(theEntry, driverSettings.getGroupsMemberField());
        for (i = 0; i < stringVals.length; i++) {
          try {
            if ((extraFilter != null) && (extraFilter.length() > 0)) {
              theFilter = "(&" + extraFilter + driverSettings.getGroupsFullFilter() + ")";
            } else {
              theFilter = driverSettings.getGroupsFullFilter();
            }
            childGroupEntry =
                LDAPUtility.getFirstEntryFromSearch(
                    lds,
                    stringVals[i],
                    driverSettings.getScope(),
                    theFilter,
                    driverSettings.getGroupAttributes());
            if (childGroupEntry != null) {
              // Verify that the group exist in the scope
              String groupSpecificId =
                  LDAPUtility.getFirstAttributeValue(
                      childGroupEntry, driverSettings.getGroupsIdField());
              if (LDAPUtility.getFirstEntryFromSearch(
                      lds,
                      driverSettings.getGroupsSpecificGroupsBaseDN(),
                      driverSettings.getScope(),
                      driverSettings.getGroupsIdFilter(groupSpecificId),
                      driverSettings.getGroupAttributes())
                  != null) {
                entryVector.add(childGroupEntry);
              }
            }
          } catch (AdminException e) {
            SilverTrace.error(
                "admin",
                "LDAPGroupUniqueDescriptor.getChildGroupsEntry()",
                "admin.MSG_ERR_LDAP_GENERAL",
                "GROUP NOT FOUND : " + stringVals[i],
                e);
          }
        }
      } else // Retreives the ROOT groups : the groups that are under the base
      // DN but that are not member of another group...
      {
        if ((extraFilter != null) && (extraFilter.length() > 0)) {
          theFilter = "(&" + extraFilter + driverSettings.getGroupsFullFilter() + ")";
        } else {
          theFilter = driverSettings.getGroupsFullFilter();
        }
        SilverTrace.info(
            "admin",
            "LDAPGroupUniqueDescriptor.getChildGroupsEntry()",
            "root.MSG_GEN_PARAM_VALUE",
            "Root Group Search");
        theEntries =
            LDAPUtility.search1000Plus(
                lds,
                driverSettings.getGroupsSpecificGroupsBaseDN(),
                driverSettings.getScope(),
                theFilter,
                driverSettings.getGroupsNameField(),
                driverSettings.getGroupAttributes());
        SynchroReport.debug(
            "LDAPGroupUniqueDescriptor.getChildGroupsEntry()",
            "Récupération de "
                + theEntries.length
                + " groupes en tout, recherche des groupes racine...",
            null);
        for (i = 0; i < theEntries.length; i++) {
          // Search for groups that have at least one member attribute that
          // point to the group
          try {
            parentGroupEntry =
                LDAPUtility.getFirstEntryFromSearch(
                    lds,
                    driverSettings.getGroupsSpecificGroupsBaseDN(),
                    driverSettings.getScope(),
                    "(&"
                        + driverSettings.getGroupsFullFilter()
                        + "("
                        + driverSettings.getGroupsMemberField()
                        + "="
                        + LDAPUtility.dblBackSlashesForDNInFilters(theEntries[i].getDN())
                        + "))",
                    driverSettings.getGroupAttributes());
          } catch (AdminException e) {
            SilverTrace.error(
                "admin",
                "LDAPGroupUniqueDescriptor.getChildGroupsEntry()",
                "admin.MSG_ERR_LDAP_GENERAL",
                "IS ROOT GROUP ? : " + theEntries[i].getDN(),
                e);
            parentGroupEntry = null; // If query failed, set this group as a
            // root group
          }
          if (parentGroupEntry == null) // No parent...
          {
            entryVector.add(theEntries[i]);
          }
        }
        theEntries = null;
      }
    } catch (AdminException e) {
      if (synchroInProcess) {
        SilverTrace.warn(
            "admin",
            "LDAPGroupUniqueDescriptor.getChildGroupsEntry()",
            "admin.EX_ERR_CHILD_GROUPS",
            "ParentGroupId=" + parentId,
            e);
        append("PB getting Group's subgroups : ").append(parentId).append("\n");
        if (parentId == null)
          SynchroReport.error(
              "LDAPGroupUniqueDescriptor.getChildGroupsEntry()",
              "Erreur lors de la récupération des groupes racine",
              e);
        else
          SynchroReport.error(
              "LDAPGroupUniqueDescriptor.getChildGroupsEntry()",
              "Erreur lors de la récupération des groupes fils du groupe " + parentId,
              e);
      } else {
        throw e;
      }
    }
    return entryVector.toArray(new LDAPEntry[entryVector.size()]);
  }
  /**
   * 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);
      }
    }
  }
 ComponentIndexerInterface getIndexer(ComponentInstLight compoInst) {
   ComponentIndexerInterface componentIndexer;
   String compoName = firstLetterToUpperCase(compoInst.getName());
   String className = getClassName(compoInst);
   String packageName = getPackage(compoInst);
   try {
     componentIndexer =
         loadIndexer("com.stratelia.webactiv." + packageName + '.' + className + "Indexer");
     if (componentIndexer == null) {
       componentIndexer =
           loadIndexer("com.silverpeas." + packageName + '.' + className + "Indexer");
     }
     if (componentIndexer == null) {
       componentIndexer =
           loadIndexer("com.silverpeas.components." + packageName + '.' + className + "Indexer");
     }
     if (componentIndexer == null) {
       componentIndexer =
           loadIndexer("org.silverpeas." + packageName + '.' + className + "Indexer");
     }
     if (componentIndexer == null) {
       componentIndexer =
           loadIndexer("org.silverpeas.components." + packageName + '.' + className + "Indexer");
     }
   } catch (InstantiationException e) {
     SilverTrace.warn(
         silvertraceModule,
         "ApplicationIndexer.getIndexer()",
         "applicationIndexer.EX_INDEXING_PERSONAL_COMPONENT_FAILED",
         "component = " + compoName,
         e);
     componentIndexer = new ComponentIndexerAdapter();
   } catch (IllegalAccessException e) {
     SilverTrace.warn(
         silvertraceModule,
         "ApplicationIndexer.getIndexer()",
         "applicationIndexer.EX_INDEXING_PERSONAL_COMPONENT_FAILED",
         "component = " + compoName,
         e);
     componentIndexer = new ComponentIndexerAdapter();
   }
   if (componentIndexer == null) {
     SilverTrace.warn(
         silvertraceModule,
         "ApplicationIndexer.getIndexer()",
         "applicationIndexer.EX_INDEXER_COMPONENT_NOT_FOUND",
         "component = "
             + compoName
             + " with classes com.stratelia.webactiv."
             + packageName
             + "."
             + className
             + "Indexer and com.silverpeas."
             + packageName
             + "."
             + className
             + "Indexer");
     return new ComponentIndexerAdapter();
   }
   return componentIndexer;
 }
  /** ExpandFile */
  private void expandFile(File srcF, File dir) {
    ZipFile zf = null;
    try {

      zf = new ZipFile(srcF);
      ZipEntry ze = null;

      Enumeration<ZipEntry> entries = (Enumeration<ZipEntry>) zf.entries();
      while (entries.hasMoreElements()) {
        ze = entries.nextElement();
        String entryName = dir.getAbsolutePath();
        if (!entryName.endsWith(File.separator) && !ze.getName().startsWith(File.separator)) {
          entryName = entryName + File.separatorChar + ze.getName();
        } else {
          entryName = entryName + ze.getName();
        }
        File f = new File(entryName);
        try {
          // create intermediary directories - sometimes zip don't add them
          File dirF = new File(f.getParent());
          dirF.mkdirs();

          if (ze.isDirectory()) {
            f.mkdirs();
          } else {
            byte[] buffer = new byte[1024];
            int length = 0;
            InputStream zis = zf.getInputStream(ze);
            FileOutputStream fos = new FileOutputStream(f);

            while ((length = zis.read(buffer)) >= 0) {
              fos.write(buffer, 0, length);
            }

            fos.close();
          }

        } catch (FileNotFoundException ex) {
          SilverTrace.warn(
              "webSites",
              "Expand.expandFile()",
              "root.EX_FILE_NOT_FOUND",
              "file = " + f.getPath(),
              ex);
        }
      }
    } catch (IOException ioe) {
      SilverTrace.warn(
          "webSites",
          "Expand.expandFile()",
          "webSites.EXE_ERROR_WHILE_EXPANDING_FILE",
          "sourceFile = " + srcF.getPath(),
          ioe);
    } finally {
      if (zf != null) {
        try {
          zf.close();
        } catch (IOException e) {
          SilverTrace.warn(
              "webSites",
              "Expand.expandFile()",
              "webSites.EXE_ERROR_WHILE_CLOSING_ZIPINPUTSTREAM",
              null,
              e);
        }
      }
    }
  }
  /**
   * Notify user that an action has been done
   *
   * @throws WorkflowException
   */
  @Override
  public void notifyActor(Task task, User sender, User user, String text) throws WorkflowException {
    String componentId = task.getProcessInstance().getModelId();
    List<String> userIds = new ArrayList<String>();
    if (user != null) {
      userIds.add(user.getUserId());
    } else if (StringUtil.isDefined(task.getGroupId())) {
      List<User> usersInGroup = task.getProcessInstance().getUsersInGroup(task.getGroupId());
      for (User userInGroup : usersInGroup) {
        userIds.add(userInGroup.getUserId());
      }
    } else {
      String role = task.getUserRoleName();
      List<User> usersInRole = task.getProcessInstance().getUsersInRole(role);
      for (User userInRole : usersInRole) {
        userIds.add(userInRole.getUserId());
      }
    }

    NotificationSender notifSender = notificationSenders.get(componentId);
    if (notifSender == null) {
      notifSender = new NotificationSender(componentId);
      notificationSenders.put(componentId, notifSender);
    }

    for (String userId : userIds) {
      try {
        String title = task.getProcessInstance().getTitle(task.getUserRoleName(), "");

        DataRecord data = task.getProcessInstance().getAllDataRecord(task.getUserRoleName(), "");
        text = DataRecordUtil.applySubstitution(text, data, "");

        NotificationMetaData notifMetaData =
            new NotificationMetaData(NotificationParameters.NORMAL, title, text);
        if (sender != null) {
          notifMetaData.setSender(sender.getUserId());
        } else {
          notifMetaData.setSender(userId);
        }
        notifMetaData.addUserRecipient(new UserRecipient(userId));
        String link =
            "/RprocessManager/"
                + componentId
                + "/searchResult?Type=ProcessInstance&Id="
                + task.getProcessInstance().getInstanceId()
                + "&role="
                + task.getUserRoleName();
        notifMetaData.setLink(link);
        notifSender.notifyUser(notifMetaData);
      } catch (WorkflowException e) {
        SilverTrace.warn(
            "workflowEngine",
            "TaskManagerImpl.notifyUser()",
            "workflowEngine.EX_ERR_NOTIFY",
            "user = "******"workflowEngine",
            "TaskManagerImpl.notifyUser()",
            "workflowEngine.EX_ERR_NOTIFY",
            "user = " + userId,
            e);
      }
    }
  }
  @SuppressWarnings("unchecked")
  public SilverpeasBeanDAOImpl(String beanClassName) throws PersistenceException {
    try {
      silverpeasBeanClass = (Class<T>) Class.forName(beanClassName);
      T object = silverpeasBeanClass.newInstance();

      if (!(object instanceof SilverpeasBean)) {
        throw new PersistenceException(
            "SilverpeasBeanDAOImpl.SilverpeasBeanDAOImpl( String beanClassName )",
            SilverpeasException.ERROR,
            "persistence.EX_ISNOT_SILVERPEASBEAN",
            "classe= " + beanClassName,
            null);
      }
      BeanInfo infos = Introspector.getBeanInfo(silverpeasBeanClass);
      properties = infos.getPropertyDescriptors();

      for (PropertyDescriptor property : properties) {
        String type = property.getPropertyType().getName();
        SilverTrace.info(
            "persistence",
            "SilverpeasBeanDAOImpl.SilverpeasBeanDAOImpl( String beanClassName )",
            "root.MSG_GEN_PARAM_VALUE",
            "new("
                + beanClassName
                + "), property Name = "
                + property.getName()
                + ", type = "
                + type);
        if (!isTypeValid(type)) {
          SilverTrace.warn(
              "persistence",
              "SilverpeasBeanDAOImpl.SilverpeasBeanDAOImpl( String beanClassName )",
              "persistence.MSG_WARN_PROPERTIE_NOT_MANAGED",
              "");
        }
      }
      connectionType = object._getConnectionType();
      switch (connectionType) {
        case CONNECTION_TYPE_DATASOURCE:
          {
            datasourceName = object._getDatasourceName();
            break;
          }
        case CONNECTION_TYPE_JDBC_CLASSIC:
          {
            jdbcConnectionParameters = object._getJdbcData();
            break;
          }
      }
      tableName = object._getTableName();
    } catch (IntrospectionException ex) {
      throw new PersistenceException(
          "SilverpeasBeanDAOImpl.SilverpeasBeanDAOImpl(String beanClassName)",
          SilverpeasException.ERROR,
          "persistence.EX_CANT_INITIALISE_CLASS",
          "classe= " + beanClassName,
          ex);
    } catch (ClassNotFoundException ex) {
      throw new PersistenceException(
          "SilverpeasBeanDAOImpl.SilverpeasBeanDAOImpl(String beanClassName)",
          SilverpeasException.ERROR,
          "persistence.EX_CANT_INITIALISE_CLASS",
          "classe= " + beanClassName,
          ex);
    } catch (InstantiationException ex) {
      throw new PersistenceException(
          "SilverpeasBeanDAOImpl.SilverpeasBeanDAOImpl(String beanClassName)",
          SilverpeasException.ERROR,
          "persistence.EX_CANT_INITIALISE_CLASS",
          "classe= " + beanClassName,
          ex);
    } catch (IllegalAccessException ex) {
      throw new PersistenceException(
          "SilverpeasBeanDAOImpl.SilverpeasBeanDAOImpl(String beanClassName)",
          SilverpeasException.ERROR,
          "persistence.EX_CANT_INITIALISE_CLASS",
          "classe= " + beanClassName,
          ex);
    }
  }
  /**
   * Get the list of process instances for which timeout date is over
   *
   * @return an array of ProcessInstance objects
   * @throws WorkflowException
   */
  public ProcessInstance[] getTimeOutProcessInstances() throws WorkflowException {
    Database db = null;
    Connection con = null;
    PreparedStatement prepStmt = null;
    ResultSet rs = null;
    String selectQuery = "";
    OQLQuery query = null;
    QueryResults results;
    List<ProcessInstance> instances = new ArrayList<ProcessInstance>();

    try {
      // Constructs the query
      db = WorkflowJDOManager.getDatabase(false);
      db.begin();

      // Need first to make a SQL query to find all concerned instances ids
      con = this.getConnection();

      selectQuery = "SELECT DISTINCT activeState.instanceId ";
      selectQuery += "FROM SB_Workflow_ActiveState activeState ";
      selectQuery += "WHERE activeState.timeoutDate < ? ";

      prepStmt = con.prepareStatement(selectQuery);
      prepStmt.setTimestamp(1, new Timestamp((new Date()).getTime()));
      rs = prepStmt.executeQuery();

      StringBuffer queryBuf = new StringBuffer();
      queryBuf.append(
          "SELECT distinct instance FROM com.silverpeas.workflow.engine.instance.ProcessInstanceImpl instance");
      queryBuf.append(" WHERE instanceId IN LIST(");

      while (rs.next()) {
        String instanceId = rs.getString(1);
        queryBuf.append("\"");
        queryBuf.append(instanceId);
        queryBuf.append("\"");
        queryBuf.append(" ,");
      }
      queryBuf.append(" \"-1\")");

      query = db.getOQLQuery(queryBuf.toString());

      // Execute the query
      try {
        results = query.execute(org.exolab.castor.jdo.Database.ReadOnly);

        // get the instance if any
        while (results.hasMore()) {
          ProcessInstance instance = (ProcessInstance) results.next();
          instances.add(instance);
        }
      } catch (Exception ex) {
        SilverTrace.warn(
            "workflowEngine",
            "ProcessInstanceManagerImpl.getTimeOutProcessInstances",
            "workflowEngine.EX_PROBLEM_GETTING_INSTANCES",
            ex);
      }

      db.commit();

      return (ProcessInstance[]) instances.toArray(new ProcessInstance[0]);
    } catch (SQLException se) {
      throw new WorkflowException(
          "ProcessInstanceManagerImpl.getTimeOutProcessInstances",
          "EX_ERR_CASTOR_GET_TIMEOUT_INSTANCES",
          "sql query : " + selectQuery,
          se);
    } catch (PersistenceException pe) {
      throw new WorkflowException(
          "ProcessInstanceManagerImpl.getTimeOutProcessInstances",
          "EX_ERR_CASTOR_GET_TIMEOUT_INSTANCES",
          pe);
    } finally {
      WorkflowJDOManager.closeDatabase(db);

      try {
        DBUtil.close(rs, prepStmt);
        if (con != null) con.close();
      } catch (SQLException se) {
        SilverTrace.error(
            "workflowEngine",
            "ProcessInstanceManagerImpl.getTimeOutProcessInstances",
            "root.EX_RESOURCE_CLOSE_FAILED",
            se);
      }
    }
  }