/**
   * Get the user infos from a given id record and id entry. <br>
   * The retrieval of the user infos depends on the entry type : <br>
   *
   * <ul>
   *   <li>If it is an {@link EntryTypeMyLuteceUser}, then it will use the {@link SecurityService}
   *       API
   *   <li>If it is an {@link EntryTypeRemoteMyLuteceUser}, then it will use the {@link
   *       UserAttributesService} API
   * </ul>
   *
   * @param strUserGuid the user guid
   * @param nIdEntry the id entry
   * @return a {@link ReferenceList}
   */
  public ReferenceList getUserInfos(String strUserGuid, int nIdEntry) {
    ReferenceList userInfos = null;

    if (StringUtils.isNotBlank(strUserGuid)) {
      Plugin plugin = PluginService.getPlugin(DirectoryPlugin.PLUGIN_NAME);
      IEntry entry = EntryHome.findByPrimaryKey(nIdEntry, plugin);

      if ((entry != null) && (entry.getEntryType() != null)) {
        if ((entry.getEntryType().getIdType()
                == AppPropertiesService.getPropertyInt(
                    PROPERTY_ENTRY_TYPE_REMOTE_MYLUTECE_USER, 21))
            && DirectoryUserAttributesManager.getManager().isEnabled()) {
          userInfos =
              DirectoryUtils.convertMapToReferenceList(
                  DirectoryUserAttributesManager.getManager().getAttributes(strUserGuid));
        } else if (entry.getEntryType().getIdType()
            == AppPropertiesService.getPropertyInt(PROPERTY_ENTRY_TYPE_MYLUTECE_USER, 19)) {
          LuteceUser user = SecurityService.getInstance().getUser(strUserGuid);

          if (user != null) {
            userInfos = DirectoryUtils.convertMapToReferenceList(user.getUserInfos());
          }
        }
      }
    }

    return userInfos;
  }
  /**
   * Get the user guid from a given id record and id entry. <br>
   * Return an empty string if the entry is not an EntryTypeMyLuteceUser nor
   * EntryTypeRemoteMyLuteceUser
   *
   * @param nIdRecord the id record
   * @param nIdEntry the id entry
   * @return the user GUID
   */
  public String getUserGuid(int nIdRecord, int nIdEntry) {
    String strUserGuid = StringUtils.EMPTY;
    Plugin plugin = PluginService.getPlugin(DirectoryPlugin.PLUGIN_NAME);
    IEntry entry = EntryHome.findByPrimaryKey(nIdEntry, plugin);

    if ((entry != null) && (entry.getEntryType() != null)) {
      if (((entry.getEntryType().getIdType()
                  == AppPropertiesService.getPropertyInt(
                      PROPERTY_ENTRY_TYPE_REMOTE_MYLUTECE_USER, 21))
              && DirectoryUserAttributesManager.getManager().isEnabled())
          || (entry.getEntryType().getIdType()
              == AppPropertiesService.getPropertyInt(PROPERTY_ENTRY_TYPE_MYLUTECE_USER, 19))) {
        RecordFieldFilter recordFieldFilter = new RecordFieldFilter();
        recordFieldFilter.setIdRecord(nIdRecord);
        recordFieldFilter.setIdEntry(nIdEntry);

        List<RecordField> listRecordFields =
            DirectoryService.getInstance().getRecordFieldByFilter(recordFieldFilter);

        if ((listRecordFields != null)
            && !listRecordFields.isEmpty()
            && (listRecordFields.get(0) != null)) {
          strUserGuid = listRecordFields.get(0).getValue();
        }
      }
    }

    return strUserGuid;
  }
  @Override
  public String processTicketingTask(
      int nIdResourceHistory, HttpServletRequest request, Locale locale) {
    String strTaskInformation = StringUtils.EMPTY;

    // We get the ticket to modify
    Ticket ticket = getTicket(nIdResourceHistory);
    TicketCategory ticketCategory =
        TicketCategoryHome.findByPrimaryKey(ticket.getIdTicketCategory());
    int nIdWorkflow = ticketCategory.getIdWorkflow();
    State state =
        WorkflowService.getInstance()
            .getState(ticket.getId(), Ticket.TICKET_RESOURCE_TYPE, nIdWorkflow, null);

    IndexerAction indexerAction = new IndexerAction();
    indexerAction.setIdTicket(ticket.getId());

    if ((state == null)
        || (state.getId()
            == AppPropertiesService.getPropertyInt(PROPERTY_WORKFLOW_ACTION_ID_NEW, 301))) {
      indexerAction.setIdTask(IndexerAction.TASK_CREATE);
    } else {
      indexerAction.setIdTask(IndexerAction.TASK_MODIFY);
    }

    IndexerActionHome.create(indexerAction);

    return strTaskInformation;
  }
  /**
   * Get the encoding for export XML
   *
   * @return the encoding for export XML
   */
  public String getExportXMLEncoding() {
    ReferenceItem param = findByKey(PARAMETER_EXPORT_XML_ENCODING);

    if (param == null) {
      return AppPropertiesService.getProperty(PROPERTY_DEFAULT_EXPORT_ENCODING);
    }

    return param.getName();
  }
  /**
   * Build the advanced parameters management
   *
   * @param user the admin user
   * @return The model for the advanced parameters
   */
  public Map<String, Object> getManageAdvancedParameters(AdminUser user) {
    Map<String, Object> model = new HashMap<String, Object>();
    Plugin plugin = PluginService.getPlugin(DatabasePlugin.PLUGIN_NAME);

    if (RBACService.isAuthorized(
        DatabaseResourceIdService.RESOURCE_TYPE,
        RBAC.WILDCARD_RESOURCES_ID,
        DatabaseResourceIdService.PERMISSION_MANAGE,
        user)) {
      // Encryption Password
      String strAlgorithms = AppPropertiesService.getProperty(PROPERTY_ENCRYPTION_ALGORITHMS_LIST);

      if (StringUtils.isNotBlank(strAlgorithms)) {
        String[] listAlgorithms = strAlgorithms.split(COMMA);

        model.put(MARK_ENCRYPTION_ALGORITHMS_LIST, listAlgorithms);
        model.put(MARK_IS_PLUGIN_JCAPTCHA_ENABLE, isPluginJcaptchaEnable());

        if (isPluginJcaptchaEnable()) {
          model.put(
              MARK_ENABLE_JCAPTCHA,
              SecurityUtils.getBooleanSecurityParameter(
                  _userParamService, plugin, MARK_ENABLE_JCAPTCHA));
        }
      }

      model.put(
          PARAMETER_ACCOUNT_CREATION_VALIDATION_EMAIL,
          SecurityUtils.getBooleanSecurityParameter(
              _userParamService, plugin, PARAMETER_ACCOUNT_CREATION_VALIDATION_EMAIL));

      model.put(
          PARAMETER_AUTO_LOGIN_AFTER_VALIDATION_EMAIL,
          SecurityUtils.getBooleanSecurityParameter(
              _userParamService, plugin, PARAMETER_AUTO_LOGIN_AFTER_VALIDATION_EMAIL));

      model.put(
          MARK_BANNED_DOMAIN_NAMES,
          SecurityUtils.getLargeSecurityParameter(
              _userParamService, plugin, MARK_BANNED_DOMAIN_NAMES));

      model = SecurityUtils.checkSecurityParameters(_userParamService, model, plugin);
    }

    return model;
  }
/** class XslExportJspBean */
public class XslExportJspBean extends PluginAdminPageJspBean {
  /** Right to manage XSL Export */
  public static final String RIGHT_MANAGE_XSL_EXPORT = "CORE_XSL_EXPORT_MANAGEMENT";

  /** Serial version UID */
  private static final long serialVersionUID = -8697851692630602527L;

  // templates
  private static final String TEMPLATE_MANAGE_XSL_EXPORT = "admin/xsl/manage_xsl_export.html";
  private static final String TEMPLATE_CREATE_XSL_EXPORT = "admin/xsl/create_xsl_export.html";
  private static final String TEMPLATE_MODIFY_XSL_EXPORT = "admin/xsl/modify_xsl_export.html";

  // Markers
  private static final String MARK_XSL_EXPORT_LIST = "xsl_export_list";
  private static final String MARK_XSL_EXPORT = "xsl_export";
  private static final String MARK_PAGINATOR = "paginator";
  private static final String MARK_NB_ITEMS_PER_PAGE = "nb_items_per_page";
  private static final String MARK_PERMISSION_CREATE = "right_create";
  private static final String MARK_PERMISSION_MODIFY = "right_modify";
  private static final String MARK_PERMISSION_DELETE = "right_delete";
  private static final String MARK_LIST_PLUGINS = "list_plugins";

  // parameters form
  private static final String PARAMETER_ID_XSL_EXPORT = "id_xsl_export";
  private static final String PARAMETER_ID_FILE = "id_file";
  private static final String PARAMETER_TITLE = "title";
  private static final String PARAMETER_DESCRIPTION = "description";
  private static final String PARAMETER_EXTENSION = "extension";
  private static final String PARAMETER_PAGE_INDEX = "page_index";
  private static final String PARAMETER_PLUGIN = "plugin";

  // other constants
  private static final String EMPTY_STRING = "";

  // message
  private static final String MESSAGE_CONFIRM_REMOVE_XSL_EXPORT =
      "portal.xsl.message.confirm_remove_xsl_export";
  private static final String MESSAGE_MANDATORY_FIELD = "portal.util.message.mandatoryField";

  // private static final String MESSAGE_CAN_NOT_REMOVE_XSL_EXPORT =
  // "portal.xsl.message.can_not_remove_xsl_export";
  private static final String FIELD_TITLE = "portal.xsl.create_xsl_export.label_title";
  private static final String FIELD_DESCRIPTION = "portal.xsl.create_xsl_export.label_description";
  private static final String FIELD_EXTENSION = "portal.xsl.create_xsl_export.label_extension";

  // private static final String FIELD_EXTENSION = "portal.xsl.create_xsl_export.label_extension";
  private static final String FIELD_FILE = "portal.xsl.create_xsl_export.label_file";
  private static final String MESSAGE_XML_NOT_VALID = "portal.xsl.message.xml_not_valid";
  private static final String MESSAGE_PERMISSION_DENIED = "portal.xsl.message.permission_denied";

  // properties
  private static final String PROPERTY_ITEM_PER_PAGE = "paginator.xsl.itemsPerPage";
  private static final String PROPERTY_MANAGE_XSL_EXPORT_TITLE =
      "portal.xsl.manage_xsl_export.page_title";
  private static final String PROPERTY_MODIFY_XSL_EXPORT_TITLE =
      "portal.xsl.modify_xsl_export.title";
  private static final String PROPERTY_CREATE_XSL_EXPORT_TITLE =
      "portal.xsl.create_xsl_export.title";

  // Jsp Definition
  private static final String JSP_MANAGE_XSL_EXPORT = "jsp/admin/xsl/ManageXslExport.jsp";
  private static final String JSP_DO_REMOVE_XSL_EXPORT = "jsp/admin/xsl/DoRemoveXslExport.jsp";

  // session fields
  private int _nDefaultItemsPerPage =
      AppPropertiesService.getPropertyInt(PROPERTY_ITEM_PER_PAGE, 15);
  private String _strCurrentPageIndex;
  private int _nItemsPerPage;

  /**
   * Return the xsl export management page ( list of export format )
   *
   * @param request The Http request
   * @return Html of the xsl export management page
   */
  public String getManageXslExport(HttpServletRequest request) {
    HashMap<String, Object> model = new HashMap<String, Object>();
    List<XslExport> listXslExport = XslExportHome.getList();
    _strCurrentPageIndex =
        Paginator.getPageIndex(request, Paginator.PARAMETER_PAGE_INDEX, _strCurrentPageIndex);
    _nItemsPerPage =
        Paginator.getItemsPerPage(
            request, Paginator.PARAMETER_ITEMS_PER_PAGE, _nItemsPerPage, _nDefaultItemsPerPage);

    model.put(
        MARK_PERMISSION_CREATE,
        RBACService.isAuthorized(
            XslExport.RESOURCE_TYPE,
            RBAC.WILDCARD_RESOURCES_ID,
            XslExportResourceIdService.PERMISSION_CREATE,
            getUser()));
    model.put(
        MARK_PERMISSION_MODIFY,
        RBACService.isAuthorized(
            XslExport.RESOURCE_TYPE,
            RBAC.WILDCARD_RESOURCES_ID,
            XslExportResourceIdService.PERMISSION_MODIFY,
            getUser()));
    model.put(
        MARK_PERMISSION_DELETE,
        RBACService.isAuthorized(
            XslExport.RESOURCE_TYPE,
            RBAC.WILDCARD_RESOURCES_ID,
            XslExportResourceIdService.PERMISSION_DELETE,
            getUser()));

    LocalizedPaginator<XslExport> paginator =
        new LocalizedPaginator<XslExport>(
            listXslExport,
            _nItemsPerPage,
            getJspManageXslExport(request),
            PARAMETER_PAGE_INDEX,
            _strCurrentPageIndex,
            getLocale());

    model.put(MARK_PAGINATOR, paginator);
    model.put(MARK_NB_ITEMS_PER_PAGE, EMPTY_STRING + _nItemsPerPage);
    model.put(MARK_XSL_EXPORT_LIST, paginator.getPageItems());
    setPageTitleProperty(PROPERTY_MANAGE_XSL_EXPORT_TITLE);

    HtmlTemplate templateList =
        AppTemplateService.getTemplate(TEMPLATE_MANAGE_XSL_EXPORT, getLocale(), model);

    return getAdminPage(templateList.getHtml());
  }

  /**
   * Gets the xsl export creation page
   *
   * @param request The HTTP request
   * @throws AccessDeniedException the {@link AccessDeniedException}
   * @return The xsl export creation page
   */
  public String getCreateXslExport(HttpServletRequest request) throws AccessDeniedException {
    HashMap<String, Object> model = new HashMap<String, Object>();

    Collection<Plugin> listPlugins = PluginService.getPluginList();
    ReferenceList refListPlugins = new ReferenceList();
    ReferenceItem refItem = new ReferenceItem();
    Plugin pluginCore = PluginService.getCore();
    refItem.setCode(pluginCore.getName());
    refItem.setName(pluginCore.getName());
    refListPlugins.add(refItem);

    for (Plugin plugin : listPlugins) {
      if (plugin != null) {
        refItem = new ReferenceItem();
        refItem.setCode(plugin.getName());
        refItem.setName(plugin.getName());
        refListPlugins.add(refItem);
      }
    }

    model.put(MARK_LIST_PLUGINS, refListPlugins);

    if (!RBACService.isAuthorized(
        XslExport.RESOURCE_TYPE,
        RBAC.WILDCARD_RESOURCES_ID,
        XslExportResourceIdService.PERMISSION_CREATE,
        getUser())) {
      throw new AccessDeniedException(MESSAGE_PERMISSION_DENIED);
    }

    setPageTitleProperty(PROPERTY_CREATE_XSL_EXPORT_TITLE);

    HtmlTemplate template =
        AppTemplateService.getTemplate(TEMPLATE_CREATE_XSL_EXPORT, getLocale(), model);

    return getAdminPage(template.getHtml());
  }

  /**
   * Perform the xsl export creation
   *
   * @param request The HTTP request
   * @throws AccessDeniedException the {@link AccessDeniedException}
   * @return The URL to go after performing the action
   */
  public String doCreateXslExport(HttpServletRequest request) throws AccessDeniedException {
    XslExport xslExport = new XslExport();
    String strError = getXslExportData(request, xslExport);

    if (!RBACService.isAuthorized(
        XslExport.RESOURCE_TYPE,
        RBAC.WILDCARD_RESOURCES_ID,
        XslExportResourceIdService.PERMISSION_CREATE,
        getUser())) {
      throw new AccessDeniedException(MESSAGE_PERMISSION_DENIED);
    }

    if (strError != null) {
      return strError;
    }

    if (xslExport.getFile() != null) {
      xslExport.getFile().setIdFile(FileHome.create(xslExport.getFile()));
    }

    XslExportHome.create(xslExport);

    return getJspManageXslExport(request);
  }

  /**
   * Gets the export format modification page
   *
   * @param request The HTTP request
   * @throws AccessDeniedException the {@link AccessDeniedException}
   * @return The export format creation page
   */
  public String getModifyXslExport(HttpServletRequest request) throws AccessDeniedException {
    if (!RBACService.isAuthorized(
        XslExport.RESOURCE_TYPE,
        RBAC.WILDCARD_RESOURCES_ID,
        XslExportResourceIdService.PERMISSION_MODIFY,
        getUser())) {
      throw new AccessDeniedException(MESSAGE_PERMISSION_DENIED);
    }

    XslExport xslExport;
    String strIdXslExport = request.getParameter(PARAMETER_ID_XSL_EXPORT);
    HashMap<String, Object> model = new HashMap<String, Object>();
    int nIdXslExport = Integer.parseInt(strIdXslExport);
    xslExport = XslExportHome.findByPrimaryKey(nIdXslExport);
    model.put(MARK_XSL_EXPORT, xslExport);

    Collection<Plugin> listPlugins = PluginService.getPluginList();
    ReferenceList refListPlugins = new ReferenceList();
    ReferenceItem refItem = new ReferenceItem();
    Plugin pluginCore = PluginService.getCore();
    refItem.setCode(pluginCore.getName());
    refItem.setName(pluginCore.getName());
    refListPlugins.add(refItem);

    for (Plugin plugin : listPlugins) {
      if (plugin != null) {
        refItem = new ReferenceItem();
        refItem.setCode(plugin.getName());
        refItem.setName(plugin.getName());
        refListPlugins.add(refItem);
      }
    }

    model.put(MARK_LIST_PLUGINS, refListPlugins);

    setPageTitleProperty(PROPERTY_MODIFY_XSL_EXPORT_TITLE);

    HtmlTemplate template =
        AppTemplateService.getTemplate(TEMPLATE_MODIFY_XSL_EXPORT, getLocale(), model);

    return getAdminPage(template.getHtml());
  }

  /**
   * Perform the xsl export modification
   *
   * @param request The HTTP request
   * @throws AccessDeniedException the {@link AccessDeniedException}
   * @return The URL to go after performing the action
   */
  public String doModifyXslExport(HttpServletRequest request) throws AccessDeniedException {
    if (!RBACService.isAuthorized(
        XslExport.RESOURCE_TYPE,
        RBAC.WILDCARD_RESOURCES_ID,
        XslExportResourceIdService.PERMISSION_MODIFY,
        getUser())) {
      throw new AccessDeniedException(MESSAGE_PERMISSION_DENIED);
    }

    XslExport xslExport;
    String strIdXslExport = request.getParameter(PARAMETER_ID_XSL_EXPORT);
    int nIdXslExport = Integer.parseInt(strIdXslExport);
    xslExport = XslExportHome.findByPrimaryKey(nIdXslExport);

    String strError = getXslExportData(request, xslExport);

    if (strError != null) {
      return strError;
    }

    // if xslExport
    File fileStore = XslExportHome.findByPrimaryKey(nIdXslExport).getFile();

    if (xslExport.getFile() != null) {
      // the file has been modified
      File fileSource = xslExport.getFile();
      // init id file source and id physical file before update
      fileSource.setIdFile(fileStore.getIdFile());

      if (fileStore.getPhysicalFile() != null) {
        fileSource
            .getPhysicalFile()
            .setIdPhysicalFile(fileStore.getPhysicalFile().getIdPhysicalFile());
      }

      FileHome.update(fileSource);
    } else {
      xslExport.setFile(fileStore);
    }

    XslExportHome.update(xslExport);

    return getJspManageXslExport(request);
  }

  /**
   * Gets the confirmation page of delete xsl export
   *
   * @param request The HTTP request
   * @throws AccessDeniedException the {@link AccessDeniedException}
   * @return the confirmation page of delete xsl export
   */
  public String getConfirmRemoveXslExport(HttpServletRequest request) throws AccessDeniedException {
    if (!RBACService.isAuthorized(
        XslExport.RESOURCE_TYPE,
        RBAC.WILDCARD_RESOURCES_ID,
        XslExportResourceIdService.PERMISSION_DELETE,
        getUser())) {
      throw new AccessDeniedException(MESSAGE_PERMISSION_DENIED);
    }

    String strIdXslExport = request.getParameter(PARAMETER_ID_XSL_EXPORT);

    UrlItem url = new UrlItem(JSP_DO_REMOVE_XSL_EXPORT);
    url.addParameter(PARAMETER_ID_XSL_EXPORT, strIdXslExport);

    return AdminMessageService.getMessageUrl(
        request, MESSAGE_CONFIRM_REMOVE_XSL_EXPORT, url.getUrl(), AdminMessage.TYPE_CONFIRMATION);
  }

  /**
   * Perform the export format supression
   *
   * @param request The HTTP request
   * @throws AccessDeniedException the {@link AccessDeniedException}
   * @return The URL to go after performing the action
   */
  public String doRemoveXslExport(HttpServletRequest request) throws AccessDeniedException {
    if (!RBACService.isAuthorized(
        XslExport.RESOURCE_TYPE,
        RBAC.WILDCARD_RESOURCES_ID,
        XslExportResourceIdService.PERMISSION_DELETE,
        getUser())) {
      throw new AccessDeniedException(MESSAGE_PERMISSION_DENIED);
    }

    // ArrayList<String> listErrors = new ArrayList<String>( );
    String strIdXslExport = request.getParameter(PARAMETER_ID_XSL_EXPORT);
    int nIdXslExport = Integer.parseInt(strIdXslExport);
    XslExport xslExport = XslExportHome.findByPrimaryKey(nIdXslExport);

    // if ( !XslExportRemovalListenerService.getService( ).checkForRemoval( strIdXslExport,
    // listErrors, getLocale( ) ) )
    // {
    // String strCause = AdminMessageService.getFormattedList( listErrors, getLocale( ) );
    // Object[] args =
    // { strCause };
    //
    // return AdminMessageService.getMessageUrl( request, MESSAGE_CAN_NOT_REMOVE_XSL_EXPORT, args,
    // AdminMessage.TYPE_STOP );
    // }
    XslExportHome.remove(nIdXslExport);

    if (xslExport.getFile() != null) {
      FileHome.remove(xslExport.getFile().getIdFile());
    }

    return getJspManageXslExport(request);
  }

  /**
   * Initiate a download of a XSL file
   *
   * @param request The request
   * @param response The response
   * @throws IOException Throw an exception if the outputstream has error.
   */
  public void doDownloadXslExport(HttpServletRequest request, HttpServletResponse response)
      throws IOException {
    String strXslExportId = request.getParameter(PARAMETER_ID_XSL_EXPORT);

    if (strXslExportId != null) {
      int nXslExportId = Integer.parseInt(strXslExportId);
      XslExport xslExport = XslExportHome.findByPrimaryKey(nXslExportId);

      String strMimetype = xslExport.getFile().getMimeType();
      response.setContentType((strMimetype != null) ? strMimetype : "application/octet-stream");
      response.setHeader(
          "Content-Disposition",
          "attachement; filename=\"" + xslExport.getFile().getTitle() + "\"");

      OutputStream out = response.getOutputStream();
      PhysicalFile physicalFile =
          PhysicalFileHome.findByPrimaryKey(
              xslExport.getFile().getPhysicalFile().getIdPhysicalFile());
      out.write(physicalFile.getValue());
      out.flush();
      out.close();
    }
  }

  /**
   * Get the request data and if there is no error insert the data in the exportFormat object
   * specified in parameter. return null if there is no error or else return the error page url
   *
   * @param request the request
   * @param xslExport the exportFormat Object
   * @return null if there is no error or else return the error page url
   */
  private String getXslExportData(HttpServletRequest request, XslExport xslExport) {
    String strError = StringUtils.EMPTY;
    String strTitle = request.getParameter(PARAMETER_TITLE);
    String strDescription = request.getParameter(PARAMETER_DESCRIPTION);
    String strExtension = request.getParameter(PARAMETER_EXTENSION);
    String strPlugin = request.getParameter(PARAMETER_PLUGIN);
    File fileSource = getFileData(PARAMETER_ID_FILE, request);

    if ((strTitle == null) || strTitle.trim().equals(EMPTY_STRING)) {
      strError = FIELD_TITLE;
    } else if ((strDescription == null) || strDescription.trim().equals(EMPTY_STRING)) {
      strError = FIELD_DESCRIPTION;
    } else if (StringUtils.isBlank(strExtension)) {
      strError = FIELD_EXTENSION;
    } else if ((xslExport.getFile() == null) && (fileSource == null)) {
      strError = FIELD_FILE;
    }

    if (strPlugin == null) {
      strPlugin = StringUtils.EMPTY;
    }

    // Mandatory fields
    if (!strError.equals(EMPTY_STRING)) {
      Object[] tabRequiredFields = {I18nService.getLocalizedString(strError, getLocale())};

      return AdminMessageService.getMessageUrl(
          request, MESSAGE_MANDATORY_FIELD, tabRequiredFields, AdminMessage.TYPE_STOP);
    }

    // Check the XML validity of the XSL stylesheet
    if (fileSource != null) {
      strError = isValid(fileSource.getPhysicalFile().getValue());

      if (strError != null) {
        Object[] args = {strError};

        return AdminMessageService.getMessageUrl(
            request, MESSAGE_XML_NOT_VALID, args, AdminMessage.TYPE_STOP);
      }
    }

    xslExport.setTitle(strTitle);
    xslExport.setDescription(strDescription);
    xslExport.setExtension(strExtension);
    xslExport.setPlugin(strPlugin);

    xslExport.setFile(fileSource);

    return null;
  }

  /**
   * Use parsing for validate the modify xsl file
   *
   * @param baXslSource the xsl source
   * @return the message exception when the validation is false
   */
  private String isValid(byte[] baXslSource) {
    String strError = null;

    try {
      SAXParserFactory factory = SAXParserFactory.newInstance();
      SAXParser analyzer = factory.newSAXParser();
      InputSource is = new InputSource(new ByteArrayInputStream(baXslSource));
      analyzer.getXMLReader().parse(is);
    } catch (Exception e) {
      strError = e.getMessage();
    }

    return strError;
  }

  /**
   * return the url of manage export format
   *
   * @param request the request
   * @return the url of manage export format
   */
  private String getJspManageXslExport(HttpServletRequest request) {
    return AppPathService.getBaseUrl(request) + JSP_MANAGE_XSL_EXPORT;
  }

  /**
   * Get a file contained in the request from the name of the parameter
   *
   * @param strFileInputName name of the file parameter of the request
   * @param request the request
   * @return file the file contained in the request with the given parameter key
   */
  private static File getFileData(String strFileInputName, HttpServletRequest request) {
    MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
    FileItem fileItem = multipartRequest.getFile(strFileInputName);

    if ((fileItem != null)
        && (fileItem.getName() != null)
        && !EMPTY_STRING.equals(fileItem.getName())) {
      File file = new File();
      PhysicalFile physicalFile = new PhysicalFile();
      physicalFile.setValue(fileItem.get());
      file.setTitle(FileUploadService.getFileNameOnly(fileItem));
      file.setSize((int) fileItem.getSize());
      file.setPhysicalFile(physicalFile);
      file.setMimeType(FileSystemUtil.getMIMEType(FileUploadService.getFileNameOnly(fileItem)));

      return file;
    }

    return null;
  }
}
public class ProfanityFilter implements IProfanityFilter {
  private static ProfanityFilter _singleton;

  // bean
  public static final String BEAN_PROFANITY_FILTER_SERVICE =
      "profanityfilter.profanityfilterService";
  public static final String CHARACTER_SPACE_BETWEEN_WORDS =
      AppPropertiesService.getProperty("character_space_between_words", " ");

  /** @return IEudonetWsService */
  public static IProfanityFilter getService() {
    if (_singleton == null) {
      _singleton = SpringContextService.getBean(BEAN_PROFANITY_FILTER_SERVICE);
    }

    return _singleton;
  }

  @Override
  public ProfanityResult checkString(String str) {
    ProfanityResult profResult = new ProfanityResult();
    String[] wordStr = null;
    Pattern p = Pattern.compile("\\W");
    Collection<Word> wordList = WordHome.getWordsList();

    if ((str != null) && StringUtils.isNotEmpty(str) && StringUtils.isNotBlank(str)) {
      wordStr = p.split(str);
    }

    boolean _isSwearWords = false;
    int number = 0;

    if (wordStr != null) {
      for (String word : wordStr) {
        if (containsReferenceTo(wordList, word)) {
          profResult.addWord(word);
          _isSwearWords = true;
          number++;
        }
      }
    }

    profResult.setIsSwearWords(_isSwearWords);
    profResult.setNumberSwearWords(number);

    return profResult;
  }

  @Override
  public ProfanityResult checkStringCounter(String str, String strResourceType) {
    Counter counter = CounterHome.findByResourceTypeKey(strResourceType);
    Pattern p = Pattern.compile("\\W");

    if (counter == null) {
      Counter newCounter = new Counter();
      newCounter.setCounter(0);
      newCounter.setResourceType(strResourceType);
      counter = CounterHome.create(newCounter);
    }

    ProfanityResult profResult = new ProfanityResult();
    String[] wordStr = null;
    Collection<Word> wordList = WordHome.getWordsList();

    if ((str != null) && StringUtils.isNotEmpty(str) && StringUtils.isNotBlank(str)) {
      wordStr = p.split(str);
    }

    boolean _isSwearWords = false;
    int number = 0;

    if (wordStr != null) {
      for (String word : wordStr) {
        if (containsReferenceTo(wordList, word)) {
          profResult.addWord(word);
          _isSwearWords = true;
          number++;
          counter.setCounter(counter.getCounter() + 1);
          CounterHome.update(counter);
          profResult.setCounterSwearWords(counter.getCounter());
        }
      }
    }

    profResult.setIsSwearWords(_isSwearWords);
    profResult.setNumberSwearWords(number);

    return profResult;
  }

  @Override
  public Counter getCounterSwearWords(String strResourceType) {
    return CounterHome.findByResourceTypeKey(strResourceType);
  }

  public static boolean containsReferenceTo(Collection<Word> collection, String element) {
    if (collection == null) {
      throw new NullPointerException("collection cannot be null");
    }

    for (Word x : collection) {
      if (removeAccent(x.getValue()).toUpperCase().equals(removeAccent(element).toUpperCase())
          || removeAccent(element)
              .toUpperCase()
              .contains(removeAccent(x.getValue()).toUpperCase())) {
        return true;
      }
    }

    return false;
  }

  public static String removeAccent(String source) {
    return Normalizer.normalize(source, Normalizer.Form.NFD).replaceAll("[\u0300-\u036F]", "");
  }
}
  /**
   * Returns a no reply email address defined in config.properties
   *
   * @return A no reply email
   */
  public static String getNoReplyEmail() {
    String strDefault = AppPropertiesService.getProperty(PROPERTY_MAIL_NOREPLY_EMAIL);

    return DatastoreService.getDataValue(KEY_NO_REPLY_EMAIL, strDefault);
  }