@Override
  protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
    // need to generate a Locale so that user beans and other things will
    // generate normally
    Locale locale = new Locale("en-US");
    ResourceBundleProvider.updateLocale(locale);
    ResourceBundle pageMessages = ResourceBundleProvider.getPageMessagesBundle();
    // logger.debug("--");
    // logger.debug("-- executing a job " + message + " at " + new
    // java.util.Date().toString());
    JobDataMap dataMap = context.getMergedJobDataMap();
    SimpleTrigger trigger = (SimpleTrigger) context.getTrigger();
    try {
      ApplicationContext appContext =
          (ApplicationContext) context.getScheduler().getContext().get("applicationContext");
      String studySubjectNumber =
          ((CoreResources) appContext.getBean("coreResources")).getField("extract.number");
      coreResources = (CoreResources) appContext.getBean("coreResources");
      ruleSetRuleDao = (RuleSetRuleDao) appContext.getBean("ruleSetRuleDao");
      dataSource = (DataSource) appContext.getBean("dataSource");
      mailSender = (OpenClinicaMailSender) appContext.getBean("openClinicaMailSender");
      AuditEventDAO auditEventDAO = new AuditEventDAO(dataSource);
      // Scheduler scheduler = context.getScheduler();
      // JobDetail detail = context.getJobDetail();
      // jobDetailBean = (JobDetailBean) detail;
      /*
       * data map here should coincide with the job data map found in
       * CreateJobExportServlet, with the following code: jobDataMap = new
       * JobDataMap(); jobDataMap.put(DATASET_ID, datasetId);
       * jobDataMap.put(PERIOD, period); jobDataMap.put(EMAIL, email);
       * jobDataMap.put(TAB, tab); jobDataMap.put(CDISC, cdisc);
       * jobDataMap.put(SPSS, spss);
       */
      String alertEmail = dataMap.getString(EMAIL);
      String localeStr = dataMap.getString(LOCALE);
      if (localeStr != null) {
        locale = new Locale(localeStr);
        ResourceBundleProvider.updateLocale(locale);
        pageMessages = ResourceBundleProvider.getPageMessagesBundle();
      }
      int dsId = dataMap.getInt(DATASET_ID);
      String tab = dataMap.getString(TAB);
      String cdisc = dataMap.getString(CDISC);
      String cdisc12 = dataMap.getString(CDISC12);
      if (cdisc12 == null) {
        cdisc12 = "0";
      }
      String cdisc13 = dataMap.getString(CDISC13);
      if (cdisc13 == null) {
        cdisc13 = "0";
      }
      String cdisc13oc = dataMap.getString(CDISC13OC);
      if (cdisc13oc == null) {
        cdisc13oc = "0";
      }
      String spss = dataMap.getString(SPSS);
      int userId = dataMap.getInt(USER_ID);
      int studyId = dataMap.getInt(STUDY_ID);

      // String datasetId = dataMap.getString(DATASET_ID);
      // int dsId = new Integer(datasetId).intValue();
      // String userAcctId = dataMap.getString(USER_ID);
      // int userId = new Integer(userAcctId).intValue();
      // why the flip-flop? if one property is set to 'true' we can
      // see jobs in another screen but all properties have to be
      // strings

      logger.debug("-- found the job: " + dsId + " dataset id");

      // for (Iterator it = dataMap.entrySet().iterator(); it.hasNext();)
      // {
      // java.util.Map.Entry entry = (java.util.Map.Entry) it.next();
      // Object key = entry.getKey();
      // Object value = entry.getValue();
      // // logger.debug("-- found datamap property: " + key.toString() +
      // // " : " + value.toString());
      // }
      HashMap fileName = new HashMap<String, Integer>();
      if (dsId > 0) {
        // trying to not throw an error if there's no dataset id
        DatasetDAO dsdao = new DatasetDAO(dataSource);
        DatasetBean datasetBean = (DatasetBean) dsdao.findByPK(dsId);
        StudyDAO studyDao = new StudyDAO(dataSource);
        UserAccountDAO userAccountDAO = new UserAccountDAO(dataSource);
        // hmm, three lines in the if block DRY?
        String generalFileDir = "";
        String generalFileDirCopy = "";
        String exportFilePath = SQLInitServlet.getField("exportFilePath");
        String pattern =
            "yyyy"
                + File.separator
                + "MM"
                + File.separator
                + "dd"
                + File.separator
                + "HHmmssSSS"
                + File.separator;
        SimpleDateFormat sdfDir = new SimpleDateFormat(pattern);
        generalFileDir =
            DATASET_DIR
                + datasetBean.getId()
                + File.separator
                + sdfDir.format(new java.util.Date());
        if (!"".equals(exportFilePath)) {
          generalFileDirCopy =
              SQLInitServlet.getField("filePath") + exportFilePath + File.separator;
        }
        // logger.debug("-- created the following dir: " +
        // generalFileDir);
        long sysTimeBegin = System.currentTimeMillis();
        // set up the user bean here, tbh
        // logger.debug("-- gen tab file 00");

        userBean = (UserAccountBean) userAccountDAO.findByPK(userId);
        // needs to also be captured by the servlet, tbh
        // logger.debug("-- gen tab file 00");
        generateFileService =
            new GenerateExtractFileService(dataSource, userBean, coreResources, ruleSetRuleDao);

        // logger.debug("-- gen tab file 00");

        // tbh #5796 - covers a bug when the user changes studies, 10/2010
        StudyBean activeStudy = (StudyBean) studyDao.findByPK(studyId);
        StudyBean parentStudy = new StudyBean();
        logger.debug(
            "active study: " + studyId + " parent study: " + activeStudy.getParentStudyId());
        if (activeStudy.getParentStudyId() > 0) {
          // StudyDAO sdao = new StudyDAO(sm.getDataSource());
          parentStudy = (StudyBean) studyDao.findByPK(activeStudy.getParentStudyId());
        } else {
          parentStudy = activeStudy;
          // covers a bug in tab file creation, tbh 01/2009
        }

        logger.debug("-- found extract bean ");

        ExtractBean eb =
            generateFileService.generateExtractBean(datasetBean, activeStudy, parentStudy);
        MessageFormat mf = new MessageFormat("");
        StringBuffer message = new StringBuffer();
        StringBuffer auditMessage = new StringBuffer();
        // use resource bundle page messages to generate the email, tbh
        // 02/2009
        // message.append(pageMessages.getString("html_email_header_1")
        // + " " + alertEmail +
        // pageMessages.getString("html_email_header_2") + "<br/>");
        message.append(
            "<p>"
                + pageMessages.getString("email_header_1")
                + " "
                + EmailEngine.getAdminEmail()
                + " "
                + pageMessages.getString("email_header_2")
                + " Job Execution "
                + pageMessages.getString("email_header_3")
                + "</p>");
        message.append("<P>Dataset: " + datasetBean.getName() + "</P>");
        message.append("<P>Study: " + activeStudy.getName() + "</P>");
        message.append(
            "<p>"
                + pageMessages.getString("html_email_body_1")
                + datasetBean.getName()
                + pageMessages.getString("html_email_body_2")
                + SQLInitServlet.getField("sysURL")
                + pageMessages.getString("html_email_body_3")
                + "</p>");
        // logger.debug("-- gen tab file 00");
        if ("1".equals(tab)) {

          logger.debug("-- gen tab file 01");
          fileName =
              generateFileService.createTabFile(
                  eb,
                  sysTimeBegin,
                  generalFileDir,
                  datasetBean,
                  activeStudy.getId(),
                  parentStudy.getId(),
                  generalFileDirCopy);
          message.append(
              "<p>"
                  + pageMessages.getString("html_email_body_4")
                  + " "
                  + getFileNameStr(fileName)
                  + pageMessages.getString("html_email_body_4_5")
                  + SQLInitServlet.getField("sysURL.base")
                  + "AccessFile?fileId="
                  + getFileIdInt(fileName)
                  + pageMessages.getString("html_email_body_3")
                  + "</p>");
          // MessageFormat mf = new MessageFormat("");
          // mf.applyPattern(pageMessages.getString(
          // "you_can_access_tab_delimited"));
          // Object[] arguments = { getFileIdInt(fileName) };
          // auditMessage.append(mf.format(arguments));

          // auditMessage.append(
          // "You can access your tab-delimited file <a href='AccessFile?fileId="
          // + getFileIdInt(fileName) + "'>here</a>.<br/>");
          auditMessage.append(
              pageMessages.getString("you_can_access_tab_delimited")
                  + getFileIdInt(fileName)
                  + pageMessages.getString("access_end"));
        }

        if ("1".equals(cdisc)) {
          String odmVersion = "oc1.2";
          fileName =
              generateFileService.createODMFile(
                  odmVersion,
                  sysTimeBegin,
                  generalFileDir,
                  datasetBean,
                  activeStudy,
                  generalFileDirCopy,
                  eb,
                  activeStudy.getId(),
                  parentStudy.getId(),
                  studySubjectNumber,
                  true,
                  true,
                  true,
                  null);
          logger.debug("-- gen odm file");
          message.append(
              "<p>"
                  + pageMessages.getString("html_email_body_4")
                  + " "
                  + getFileNameStr(fileName)
                  + pageMessages.getString("html_email_body_4_5")
                  + SQLInitServlet.getField("sysURL.base")
                  + "AccessFile?fileId="
                  + getFileIdInt(fileName)
                  + pageMessages.getString("html_email_body_3")
                  + "</p>");

          // MessageFormat mf = new MessageFormat("");
          // mf.applyPattern(pageMessages.getString(
          // "you_can_access_odm_12"));
          // Object[] arguments = { getFileIdInt(fileName) };
          // auditMessage.append(mf.format(arguments));

          // auditMessage.append(
          // "You can access your ODM 1.2 w/OpenClinica Extension XML file <a
          // href='AccessFile?fileId="
          // + getFileIdInt(fileName)
          // + "'>here</a>.<br/>");
          auditMessage.append(
              pageMessages.getString("you_can_access_odm_12")
                  + getFileIdInt(fileName)
                  + pageMessages.getString("access_end"));
        }

        if ("1".equals(cdisc12)) {
          String odmVersion = "1.2";
          fileName =
              generateFileService.createODMFile(
                  odmVersion,
                  sysTimeBegin,
                  generalFileDir,
                  datasetBean,
                  activeStudy,
                  generalFileDirCopy,
                  eb,
                  activeStudy.getId(),
                  parentStudy.getId(),
                  studySubjectNumber,
                  true,
                  true,
                  true,
                  null);
          logger.debug("-- gen odm file 1.2 default");
          message.append(
              "<p>"
                  + pageMessages.getString("html_email_body_4")
                  + " "
                  + getFileNameStr(fileName)
                  + pageMessages.getString("html_email_body_4_5")
                  + SQLInitServlet.getField("sysURL.base")
                  + "AccessFile?fileId="
                  + getFileIdInt(fileName)
                  + pageMessages.getString("html_email_body_3")
                  + "</p>");

          // mf.applyPattern(pageMessages.getString(
          // "you_can_access_odm_12_xml"));
          // Object[] arguments = { getFileIdInt(fileName) };
          // auditMessage.append(mf.format(arguments));
          // // auditMessage.append(
          // "You can access your ODM 1.2 XML file <a href='AccessFile?fileId="
          // + getFileIdInt(fileName) + "'>here</a>.<br/>");
          auditMessage.append(
              pageMessages.getString("you_can_access_odm_12_xml")
                  + getFileIdInt(fileName)
                  + pageMessages.getString("access_end"));
        }

        if ("1".equals(cdisc13)) {
          String odmVersion = "1.3";
          fileName =
              generateFileService.createODMFile(
                  odmVersion,
                  sysTimeBegin,
                  generalFileDir,
                  datasetBean,
                  activeStudy,
                  generalFileDirCopy,
                  eb,
                  activeStudy.getId(),
                  parentStudy.getId(),
                  studySubjectNumber,
                  true,
                  true,
                  true,
                  null);
          logger.debug("-- gen odm file 1.3");
          message.append(
              "<p>"
                  + pageMessages.getString("html_email_body_4")
                  + " "
                  + getFileNameStr(fileName)
                  + pageMessages.getString("html_email_body_4_5")
                  + SQLInitServlet.getField("sysURL.base")
                  + "AccessFile?fileId="
                  + getFileIdInt(fileName)
                  + pageMessages.getString("html_email_body_3")
                  + "</p>");

          // MessageFormat mf = new MessageFormat("");
          // mf.applyPattern(pageMessages.getString(
          // "you_can_access_odm_13"));
          // Object[] arguments = { getFileIdInt(fileName) };
          // auditMessage.append(mf.format(arguments));

          // auditMessage.append(
          // "You can access your ODM 1.3 XML file <a href='AccessFile?fileId="
          // + getFileIdInt(fileName) + "'>here</a>.<br/>");
          auditMessage.append(
              pageMessages.getString("you_can_access_odm_13")
                  + getFileIdInt(fileName)
                  + pageMessages.getString("access_end"));
        }

        if ("1".equals(cdisc13oc)) {
          String odmVersion = "oc1.3";
          fileName =
              generateFileService.createODMFile(
                  odmVersion,
                  sysTimeBegin,
                  generalFileDir,
                  datasetBean,
                  activeStudy,
                  generalFileDirCopy,
                  eb,
                  activeStudy.getId(),
                  parentStudy.getId(),
                  studySubjectNumber,
                  true,
                  true,
                  true,
                  null);
          logger.debug("-- gen odm file 1.3 oc");
          message.append(
              "<p>"
                  + pageMessages.getString("html_email_body_4")
                  + " "
                  + getFileNameStr(fileName)
                  + pageMessages.getString("html_email_body_4_5")
                  + SQLInitServlet.getField("sysURL.base")
                  + "AccessFile?fileId="
                  + getFileIdInt(fileName)
                  + pageMessages.getString("html_email_body_3")
                  + "</p>");

          // MessageFormat mf = new MessageFormat("");
          // mf.applyPattern(pageMessages.getString(
          // "you_can_access_odm_13_xml"));
          // Object[] arguments = { getFileIdInt(fileName) };
          // auditMessage.append(mf.format(arguments));

          // auditMessage.append(
          // "You can access your ODM 1.3 w/OpenClinica Extension XML file <a
          // href='AccessFile?fileId="
          // + getFileIdInt(fileName)
          // + "'>here</a>.<br/>");
          auditMessage.append(
              pageMessages.getString("you_can_access_odm_13_xml")
                  + getFileIdInt(fileName)
                  + pageMessages.getString("access_end"));
        }
        if ("1".equals(spss)) {
          SPSSReportBean answer = new SPSSReportBean();
          fileName =
              generateFileService.createSPSSFile(
                  datasetBean,
                  eb,
                  activeStudy,
                  parentStudy,
                  sysTimeBegin,
                  generalFileDir,
                  answer,
                  generalFileDirCopy);
          logger.debug("-- gen spss file");
          message.append(
              "<p>"
                  + pageMessages.getString("html_email_body_4")
                  + " "
                  + getFileNameStr(fileName)
                  + pageMessages.getString("html_email_body_4_5")
                  + SQLInitServlet.getField("sysURL.base")
                  + "AccessFile?fileId="
                  + getFileIdInt(fileName)
                  + pageMessages.getString("html_email_body_3")
                  + "</p>");

          // MessageFormat mf = new MessageFormat("");
          // mf.applyPattern(pageMessages.getString(
          // "you_can_access_spss"));
          // Object[] arguments = { getFileIdInt(fileName) };
          // auditMessage.append(mf.format(arguments));

          // auditMessage.append(
          // "You can access your SPSS files <a href='AccessFile?fileId="
          // + getFileIdInt(fileName) + "'>here</a>.<br/>");
          auditMessage.append(
              pageMessages.getString("you_can_access_spss")
                  + getFileIdInt(fileName)
                  + pageMessages.getString("access_end"));
        }

        // wrap up the message, and send the email
        message.append(
            "<p>"
                + pageMessages.getString("html_email_body_5")
                + "</P><P>"
                + pageMessages.getString("email_footer"));
        try {
          mailSender.sendEmail(
              alertEmail.trim(),
              pageMessages.getString("job_ran_for") + " " + datasetBean.getName(),
              message.toString(),
              true);
        } catch (OpenClinicaSystemException ose) {
          // Do Nothing, In the future we might want to have an email
          // status added to system.
        }
        TriggerBean triggerBean = new TriggerBean();
        triggerBean.setDataset(datasetBean);
        triggerBean.setUserAccount(userBean);
        triggerBean.setFullName(trigger.getName());
        auditEventDAO.createRowForExtractDataJobSuccess(triggerBean, auditMessage.toString());
      } else {
        TriggerBean triggerBean = new TriggerBean();
        // triggerBean.setDataset(datasetBean);
        triggerBean.setUserAccount(userBean);
        triggerBean.setFullName(trigger.getName());
        auditEventDAO.createRowForExtractDataJobFailure(triggerBean);
        // logger.debug("-- made it here for some reason, ds id: "
        // + dsId);
      }

      // logger.debug("-- generated file: " + fileNameStr);
      // dataSource.
    } catch (Exception e) {
      // TODO Auto-generated catch block -- ideally should generate a fail
      // msg here, tbh 02/2009
      logger.debug("-- found exception: " + e.getMessage());
      e.printStackTrace();
    }
  }
public class UpdateJobImportServlet extends SecureController {

  private static String SCHEDULER = "schedulerFactoryBean";
  private static String TRIGGER_IMPORT_GROUP = "importTrigger";
  private StdScheduler scheduler;
  private SimpleTrigger trigger;
  private JobDataMap dataMap;
  private static final String IMPORT_DIR =
      SQLInitServlet.getField("filePath") + CreateJobImportServlet.DIR_PATH + File.separator;

  @Override
  protected void mayProceed() throws InsufficientPermissionException {
    if (ub.isSysAdmin()) {
      return;
    }
    if (currentRole.getRole().equals(Role.STUDYDIRECTOR)
        || currentRole.getRole().equals(Role.COORDINATOR)) {
      return;
    }

    addPageMessage(
        respage.getString("no_have_correct_privilege_current_study")
            + respage.getString("change_study_contact_sysadmin"));
    throw new InsufficientPermissionException(
        Page.MENU, resexception.getString("not_allowed_access_extract_data_servlet"), "1"); // TODO
  }

  private StdScheduler getScheduler() {
    scheduler =
        this.scheduler != null
            ? scheduler
            : (StdScheduler) SpringServletAccess.getApplicationContext(context).getBean(SCHEDULER);
    return scheduler;
  }

  private void setUpServlet(Trigger trigger) throws Exception {
    FormProcessor fp2 = new FormProcessor(request);

    request.setAttribute(CreateJobImportServlet.JOB_NAME, trigger.getName());
    request.setAttribute(CreateJobImportServlet.JOB_DESC, trigger.getDescription());

    dataMap = trigger.getJobDataMap();
    String contactEmail = dataMap.getString(ImportSpringJob.EMAIL);
    System.out.println("found email: " + contactEmail);
    int userId = dataMap.getInt(ImportSpringJob.USER_ID);
    int hours = dataMap.getInt(CreateJobImportServlet.HOURS);
    int minutes = dataMap.getInt(CreateJobImportServlet.MINUTES);
    String directory = dataMap.getString(ImportSpringJob.DIRECTORY);
    String studyName = dataMap.getString(ImportSpringJob.STUDY_NAME);

    request.setAttribute(ImportSpringJob.EMAIL, contactEmail);
    request.setAttribute(ImportSpringJob.STUDY_NAME, studyName);
    request.setAttribute("filePath", directory);
    request.setAttribute("firstFilePath", IMPORT_DIR);
    request.setAttribute("hours", new Integer(hours).toString());
    request.setAttribute("minutes", new Integer(minutes).toString());

    Date jobDate = trigger.getNextFireTime();

    UserAccountDAO udao = new UserAccountDAO(sm.getDataSource());
    StudyDAO sdao = new StudyDAO(sm.getDataSource());

    // ArrayList studies = udao.findStudyByUser(ub.getName(), (ArrayList)
    // sdao.findAll());
    // request.setAttribute("studies", studies);
    ArrayList<StudyBean> all = (ArrayList<StudyBean>) sdao.findAll();
    ArrayList<StudyBean> finalList = new ArrayList<StudyBean>();
    for (StudyBean sb : all) {
      if (!(sb.getParentStudyId() > 0)) {
        finalList.add(sb);
        // System.out.println("found study name: " + sb.getName());
        finalList.addAll(sdao.findAllByParent(sb.getId()));
      }
    }
    // System.out.println("found list of studies: " + finalList.toString());
    addEntityList(
        "studies",
        finalList,
        respage.getString("a_user_cannot_be_created_no_study_as_active"),
        Page.ADMIN_SYSTEM);
    // tbh >>
    // HashMap presetValues = new HashMap();
    // Calendar calendar = new GregorianCalendar();
    // calendar.setTime(jobDate);
    // presetValues.put(CreateJobImportServlet.DATE_START_JOB + "Hour",
    // calendar.get(Calendar.HOUR_OF_DAY));
    // presetValues.put(CreateJobImportServlet.DATE_START_JOB + "Minute",
    // calendar.get(Calendar.MINUTE));
    // // TODO this will have to match l10n formatting
    // presetValues.put(CreateJobImportServlet.DATE_START_JOB + "Date",
    // (calendar.get(Calendar.MONTH) + 1) + "/" +
    // calendar.get(Calendar.DATE) + "/"
    // + calendar.get(Calendar.YEAR));
    // fp2.setPresetValues(presetValues);
    // setPresetValues(fp2.getPresetValues());

  }

  @Override
  protected void processRequest() throws Exception {
    FormProcessor fp = new FormProcessor(request);
    TriggerService triggerService = new TriggerService();
    String action = fp.getString("action");
    String triggerName = fp.getString("tname");
    scheduler = getScheduler();
    System.out.println("found trigger name " + triggerName);
    Trigger trigger = scheduler.getTrigger(triggerName.trim(), TRIGGER_IMPORT_GROUP);
    System.out.println("found trigger from the other side " + trigger.getFullName());
    if (StringUtil.isBlank(action)) {
      setUpServlet(trigger);
      forwardPage(Page.UPDATE_JOB_IMPORT);
    } else if ("confirmall".equalsIgnoreCase(action)) {
      HashMap errors =
          triggerService.validateImportJobForm(
              fp, request, scheduler.getTriggerNames("DEFAULT"), trigger.getName());
      if (!errors.isEmpty()) {
        // send back
        addPageMessage(
            "Your modifications caused an error, please see the messages for more information.");
        setUpServlet(trigger);
        forwardPage(Page.UPDATE_JOB_IMPORT);
      } else {
        StudyDAO studyDAO = new StudyDAO(sm.getDataSource());
        int studyId = fp.getInt(CreateJobImportServlet.STUDY_ID);
        StudyBean study = (StudyBean) studyDAO.findByPK(studyId);
        // in the place of a users' current study, tbh
        Date startDate = trigger.getStartTime();
        trigger =
            triggerService.generateImportTrigger(
                fp, sm.getUserBean(), study, startDate, request.getLocale().getLanguage());
        // scheduler = getScheduler();
        JobDetailBean jobDetailBean = new JobDetailBean();
        jobDetailBean.setGroup(TRIGGER_IMPORT_GROUP);
        jobDetailBean.setName(trigger.getName());
        jobDetailBean.setJobClass(org.akaza.openclinica.web.job.ImportStatefulJob.class);
        jobDetailBean.setJobDataMap(trigger.getJobDataMap());
        jobDetailBean.setDurability(true); // need durability?
        jobDetailBean.setVolatility(false);

        try {
          scheduler.deleteJob(triggerName, TRIGGER_IMPORT_GROUP);
          Date dateStart = scheduler.scheduleJob(jobDetailBean, trigger);

          addPageMessage("Your job has been successfully modified.");
          forwardPage(Page.VIEW_IMPORT_JOB_SERVLET);
        } catch (SchedulerException se) {
          se.printStackTrace();
          // set a message here with the exception message
          setUpServlet(trigger);
          addPageMessage(
              "There was an unspecified error with your creation, please contact an administrator.");
          forwardPage(Page.UPDATE_JOB_IMPORT);
        }
      }
    }
  }
}
  private void prepareEmail(QueryServiceHelperBean helperBean) throws Exception {
    StringBuffer message = new StringBuffer();

    message.append(
        MessageFormat.format(
            respage.getString("mailDNHeader"),
            helperBean.getUserAccount().getFirstName(),
            helperBean.getUserAccount().getLastName()));
    message.append(
        "<A HREF='"
            + SQLInitServlet.getField("sysURL.base")
            + "ViewNotes?module=submit&listNotes_f_discrepancyNoteBean.user="******"&listNotes_f_entityName="
            + helperBean.getParentElementName()
            + "'>"
            + SQLInitServlet.getField("sysURL.base")
            + "</A><BR/>");
    message.append(respage.getString("you_received_this_from"));
    message.append(respage.getString("email_body_separator"));
    message.append(respage.getString("disc_note_info"));
    message.append(respage.getString("email_body_separator"));
    message.append(
        MessageFormat.format(
            respage.getString("mailDNParameters1"),
            helperBean.getDn().getDescription(),
            helperBean.getDn().getDetailedNotes(),
            helperBean.getUserAccount().getUserName()));
    message.append(respage.getString("email_body_separator"));
    message.append(respage.getString("entity_information"));
    message.append(respage.getString("email_body_separator"));
    message.append(
        MessageFormat.format(
            respage.getString("mailDNParameters2"),
            helperBean.getDn().getStudy().getName(),
            helperBean.getDn().getDescription()));

    if (!("studySub".equalsIgnoreCase(helperBean.getDn().getEntityType())
        || "subject".equalsIgnoreCase(helperBean.getDn().getEntityType()))) {
      message.append(
          MessageFormat.format(
              respage.getString("mailDNParameters3"),
              helperBean.getContainer().getStudyEvent().getStudyEventDefinition().getName()));
      if (!"studyEvent".equalsIgnoreCase(helperBean.getDn().getEntityType())) {
        message.append(
            MessageFormat.format(
                respage.getString("mailDNParameters4"),
                helperBean.getContainer().getCrfVersion().getCrf().getName()));
        if (!"eventCrf".equalsIgnoreCase(helperBean.getDn().getEntityType())) {
          message.append(
              MessageFormat.format(
                  respage.getString("mailDNParameters6"), helperBean.getParentElementName()));
        }
      }
    }

    message.append(respage.getString("email_body_separator"));
    message.append(
        MessageFormat.format(
            respage.getString("mailDNThanks"), helperBean.getDn().getStudy().getName()));
    message.append(respage.getString("email_body_separator"));
    message.append(respage.getString("disclaimer"));
    message.append(respage.getString("email_body_separator"));
    message.append(respage.getString("email_footer"));
    String subject =
        MessageFormat.format(
            respage.getString("mailDNSubject"),
            helperBean.getDn().getStudy().getName(),
            helperBean.getParentElementName());

    String emailBodyString = message.toString();
    try {
      sendEmail(helperBean.getUserAccount().getEmail().trim(), subject, emailBodyString, true);
    } catch (Exception e) {
      logger.error(e.getMessage());
      throw e;
    }
  }