/** createTabFile, added by tbh, 01/2009 */
  public HashMap<String, Integer> createTabFile(
      ExtractBean eb,
      long sysTimeBegin,
      String generalFileDir,
      DatasetBean datasetBean,
      int activeStudyId,
      int parentStudyId,
      String generalFileDirCopy) {

    TabReportBean answer = new TabReportBean();

    DatasetDAO dsdao = new DatasetDAO(ds);
    // create the extract bean here, tbh
    eb = dsdao.getDatasetData(eb, activeStudyId, parentStudyId);
    eb.getMetadata();
    eb.computeReport(answer);

    long sysTimeEnd = System.currentTimeMillis() - sysTimeBegin;
    String TXTFileName = datasetBean.getName() + "_tab.xls";

    int fId =
        this.createFile(
            TXTFileName,
            generalFileDir,
            answer.toString(),
            datasetBean,
            sysTimeEnd,
            ExportFormatBean.TXTFILE,
            true);
    if (!"".equals(generalFileDirCopy)) {
      int fId2 =
          this.createFile(
              TXTFileName,
              generalFileDirCopy,
              answer.toString(),
              datasetBean,
              sysTimeEnd,
              ExportFormatBean.TXTFILE,
              false);
    }
    logger.info("created txt file");
    // return TXTFileName;
    HashMap answerMap = new HashMap<String, Integer>();
    answerMap.put(TXTFileName, new Integer(fId));
    return answerMap;
  }
  public int createFile(
      String name,
      String dir,
      String content,
      DatasetBean datasetBean,
      long time,
      ExportFormatBean efb,
      boolean saveToDB) {
    ArchivedDatasetFileBean fbFinal = new ArchivedDatasetFileBean();
    // >> tbh 04/2010 #4915 replace all names' spaces with underscores
    name = name.replaceAll(" ", "_");
    fbFinal.setId(0);
    try {
      File complete = new File(dir);
      if (!complete.isDirectory()) {
        complete.mkdirs();
      }
      File newFile = new File(complete, name);
      newFile.setLastModified(System.currentTimeMillis());

      BufferedWriter w = new BufferedWriter(new FileWriter(newFile));
      w.write(content);
      w.close();
      logger.info("finished writing the text file...");
      // now, we write the file to the zip file
      FileInputStream is = new FileInputStream(newFile);
      ZipOutputStream z =
          new ZipOutputStream(new FileOutputStream(new File(complete, name + ".zip")));
      logger.info("created zip output stream...");
      // we write over the content no matter what
      // we then check to make sure there are no duplicates
      // TODO need to change the above -- save all content!
      // z.write(content);
      z.putNextEntry(new java.util.zip.ZipEntry(name));
      // int length = (int) newFile.length();
      int bytesRead;
      byte[] buff = new byte[512];
      // read from buffered input stream and put into zip file
      // while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
      while ((bytesRead = is.read(buff)) != -1) {
        z.write(buff, 0, bytesRead);
      }
      logger.info("writing buffer...");
      // }
      z.closeEntry();
      z.finish();
      // newFile = new File(complete, name+".zip");
      // newFile.setLastModified(System.currentTimeMillis());
      //
      // BufferedWriter w2 = new BufferedWriter(new FileWriter(newFile));
      // w2.write(newOut.toString());
      // w2.close();
      if (is != null) {
        try {
          is.close();
        } catch (java.io.IOException ie) {
          ie.printStackTrace();
        }
      }
      logger.info("finished zipping up file...");
      // set up the zip to go into the database
      if (saveToDB) {
        ArchivedDatasetFileBean fb = new ArchivedDatasetFileBean();
        fb.setName(name + ".zip");
        // logger.info("ODM filename: " + name + ".zip");
        fb.setFileReference(dir + name + ".zip");
        // logger.info("ODM fileReference: " + dir + name + ".zip");
        // current location of the file on the system
        fb.setFileSize((int) newFile.length());
        // logger.info("ODM setFileSize: " + (int)newFile.length() );
        // set the above to compressed size?
        fb.setRunTime((int) time);
        // logger.info("ODM setRunTime: " + (int)time );
        // need to set this in milliseconds, get it passed from above
        // methods?
        fb.setDatasetId(datasetBean.getId());
        // logger.info("ODM setDatasetid: " + ds.getId() );
        fb.setExportFormatBean(efb);
        // logger.info("ODM setExportFormatBean: success" );
        fb.setExportFormatId(efb.getId());
        // logger.info("ODM setExportFormatId: " + efb.getId());
        fb.setOwner(userBean);
        // logger.info("ODM setOwner: " + sm.getUserBean());
        fb.setOwnerId(userBean.getId());
        // logger.info("ODM setOwnerId: " + sm.getUserBean().getId() );
        fb.setDateCreated(new Date(System.currentTimeMillis()));
        boolean write = true;
        ArchivedDatasetFileDAO asdfDAO = new ArchivedDatasetFileDAO(ds);
        // eliminating all checks so that we create multiple files, tbh 6-7
        if (write) {
          fbFinal = (ArchivedDatasetFileBean) asdfDAO.create(fb);
        } else {
          logger.info("duplicate found: " + fb.getName());
        }
      }
      // created in database!

    } catch (Exception e) {
      logger.warn(e.getMessage());
      System.out.println("-- exception thrown at createFile: " + e.getMessage());
      logger.info("-- exception thrown at createFile: " + e.getMessage());
      e.printStackTrace();
    }

    return fbFinal.getId();
  }
  public int createFile(
      String zipName,
      ArrayList names,
      String dir,
      ArrayList contents,
      DatasetBean datasetBean,
      long time,
      ExportFormatBean efb,
      boolean saveToDB) {
    ArchivedDatasetFileBean fbFinal = new ArchivedDatasetFileBean();
    // >> tbh #4915
    zipName = zipName.replaceAll(" ", "_");
    fbFinal.setId(0);
    try {
      File complete = new File(dir);
      if (!complete.isDirectory()) {
        complete.mkdirs();
      }
      int totalSize = 0;
      ZipOutputStream z =
          new ZipOutputStream(new FileOutputStream(new File(complete, zipName + ".zip")));
      FileInputStream is = null;
      for (int i = 0; i < names.size(); i++) {
        String name = (String) names.get(i);
        // >> tbh #4915
        name = name.replaceAll(" ", "_");
        String content = (String) contents.get(i);
        File newFile = new File(complete, name);
        // totalSize = totalSize + (int)newFile.length();
        newFile.setLastModified(System.currentTimeMillis());

        BufferedWriter w = new BufferedWriter(new FileWriter(newFile));
        w.write(content);
        w.close();
        logger.info("finished writing the text file...");
        // now, we write the file to the zip file
        is = new FileInputStream(newFile);

        logger.info("created zip output stream...");

        z.putNextEntry(new java.util.zip.ZipEntry(name));

        int bytesRead;
        byte[] buff = new byte[512];

        while ((bytesRead = is.read(buff)) != -1) {
          z.write(buff, 0, bytesRead);
          totalSize += 512;
        }
        z.closeEntry();
        // A. Hamid. 4910
        is.close();
        if (CoreResources.getField("dataset_file_delete").equalsIgnoreCase("true")
            || CoreResources.getField("dataset_file_delete").equals("")) {
          newFile.delete();
        }
      }
      logger.info("writing buffer...");
      // }
      z.flush();
      z.finish();
      z.close();

      if (is != null) {
        try {
          is.close();
        } catch (java.io.IOException ie) {
          ie.printStackTrace();
        }
      }
      logger.info("finished zipping up file...");
      // set up the zip to go into the database
      if (saveToDB) {
        ArchivedDatasetFileBean fb = new ArchivedDatasetFileBean();
        fb.setName(zipName + ".zip");
        fb.setFileReference(dir + zipName + ".zip");
        // current location of the file on the system
        fb.setFileSize(totalSize);
        // set the above to compressed size?
        fb.setRunTime((int) time);
        // need to set this in milliseconds, get it passed from above
        // methods?
        fb.setDatasetId(datasetBean.getId());
        fb.setExportFormatBean(efb);
        fb.setExportFormatId(efb.getId());
        fb.setOwner(userBean);
        fb.setOwnerId(userBean.getId());
        fb.setDateCreated(new Date(System.currentTimeMillis()));

        boolean write = true;
        ArchivedDatasetFileDAO asdfDAO = new ArchivedDatasetFileDAO(ds);

        if (write) {
          fbFinal = (ArchivedDatasetFileBean) asdfDAO.create(fb);
          logger.info("Created ADSFile!: " + fbFinal.getId() + " for " + zipName + ".zip");
        } else {
          logger.info("duplicate found: " + fb.getName());
        }
      }
      // created in database!

    } catch (Exception e) {
      logger.warn(e.getMessage());
      System.out.println("-- exception at create file: " + e.getMessage());
      e.printStackTrace();
    }
    return fbFinal.getId();
  }
  /**
   * createSPSSFile, added by tbh, 01/2009
   *
   * @param db
   * @param eb
   * @param currentstudyid
   * @param parentstudy
   * @return
   */
  public HashMap<String, Integer> createSPSSFile(
      DatasetBean db,
      ExtractBean eb2,
      StudyBean currentStudy,
      StudyBean parentStudy,
      long sysTimeBegin,
      String generalFileDir,
      SPSSReportBean answer,
      String generalFileDirCopy) {
    setUpResourceBundles();

    String SPSSFileName = db.getName() + "_data_spss.dat";
    String DDLFileName = db.getName() + "_ddl_spss.sps";
    String ZIPFileName = db.getName() + "_spss";

    SPSSVariableNameValidationBean svnvbean = new SPSSVariableNameValidationBean();
    answer.setDatFileName(SPSSFileName);
    // DatasetDAO dsdao = new DatasetDAO(ds);

    // create the extract bean here, tbh
    // ExtractBean eb = this.generateExtractBean(db, currentStudy,
    // parentStudy);

    // eb = dsdao.getDatasetData(eb, currentStudy.getId(),
    // parentStudy.getId());

    // eb.getMetadata();

    // eb.computeReport(answer);

    answer.setItems(eb2.getItemNames()); // set up items here to get
    // itemMetadata

    // set up response sets for each item here
    ItemDAO itemdao = new ItemDAO(ds);
    ItemFormMetadataDAO imfdao = new ItemFormMetadataDAO(ds);
    ArrayList items = answer.getItems();
    for (int i = 0; i < items.size(); i++) {
      DisplayItemHeaderBean dih = (DisplayItemHeaderBean) items.get(i);
      ItemBean item = dih.getItem();
      ArrayList metas = imfdao.findAllByItemId(item.getId());
      // for (int h = 0; h < metas.size(); h++) {
      // ItemFormMetadataBean ifmb = (ItemFormMetadataBean)
      // metas.get(h);
      // logger.info("group name found:
      // "+ifmb.getGroupLabel());
      // }
      // logger.info("crf versionname" +
      // meta.getCrfVersionName());
      item.setItemMetas(metas);
    }

    HashMap eventDescs = new HashMap<String, String>();

    eventDescs = eb2.getEventDescriptions();

    eventDescs.put("SubjID", resword.getString("study_subject_ID"));
    eventDescs.put("ProtocolID", resword.getString("protocol_ID_site_ID"));
    eventDescs.put("DOB", resword.getString("date_of_birth"));
    eventDescs.put("YOB", resword.getString("year_of_birth"));
    eventDescs.put("Gender", resword.getString("gender"));
    answer.setDescriptions(eventDescs);

    ArrayList generatedReports = new ArrayList<String>();
    try {
      // YW <<
      generatedReports.add(answer.getMetadataFile(svnvbean, eb2).toString());
      generatedReports.add(answer.getDataFile().toString());
      // YW >>
    } catch (IndexOutOfBoundsException i) {
      generatedReports.add(answer.getMetadataFile(svnvbean, eb2).toString());
      logger.debug("throw the error here");
    }

    long sysTimeEnd = System.currentTimeMillis() - sysTimeBegin;

    ArrayList titles = new ArrayList();
    // YW <<
    titles.add(DDLFileName);
    titles.add(SPSSFileName);
    // YW >>

    // create new createFile method that accepts array lists to
    // put into zip files
    int fId =
        this.createFile(
            ZIPFileName,
            titles,
            generalFileDir,
            generatedReports,
            db,
            sysTimeEnd,
            ExportFormatBean.TXTFILE,
            true);
    if (!"".equals(generalFileDirCopy)) {
      int fId2 =
          this.createFile(
              ZIPFileName,
              titles,
              generalFileDirCopy,
              generatedReports,
              db,
              sysTimeEnd,
              ExportFormatBean.TXTFILE,
              false);
    }
    // return DDLFileName;
    HashMap answerMap = new HashMap<String, Integer>();
    answerMap.put(DDLFileName, new Integer(fId));
    return answerMap;
  }
  public void processRequest() throws Exception {

    StudyDAO sdao = new StudyDAO(sm.getDataSource());
    FormProcessor fp = new FormProcessor(request);
    int studyId = fp.getInt("id");

    StudyBean study = (StudyBean) sdao.findByPK(studyId);
    // find all sites
    ArrayList sites = (ArrayList) sdao.findAllByParent(studyId);

    // find all user and roles in the study, include ones in sites
    UserAccountDAO udao = new UserAccountDAO(sm.getDataSource());
    ArrayList userRoles = udao.findAllByStudyId(studyId);

    // find all subjects in the study, include ones in sites
    StudySubjectDAO ssdao = new StudySubjectDAO(sm.getDataSource());
    ArrayList subjects = ssdao.findAllByStudy(study);

    // find all events in the study, include ones in sites
    StudyEventDefinitionDAO sefdao = new StudyEventDefinitionDAO(sm.getDataSource());
    ArrayList definitions = sefdao.findAllByStudy(study);

    String action = request.getParameter("action");
    if (studyId == 0) {
      addPageMessage("Please choose a study to restore.");
      forwardPage(Page.STUDY_LIST_SERVLET);
    } else {
      if ("confirm".equalsIgnoreCase(action)) {
        request.setAttribute("studyToRestore", study);

        request.setAttribute("sitesToRestore", sites);

        request.setAttribute("userRolesToRestore", userRoles);

        request.setAttribute("subjectsToRestore", subjects);

        request.setAttribute("definitionsToRRestore", definitions);
        forwardPage(Page.RESTORE_STUDY);
      } else {
        logger.info("submit to restore the study");
        // change all statuses to unavailable
        StudyDAO studao = new StudyDAO(sm.getDataSource());
        study.setStatus(Status.AVAILABLE);
        study.setUpdater(ub);
        study.setUpdatedDate(new Date());
        studao.update(study);

        // remove all sites
        for (int i = 0; i < sites.size(); i++) {
          StudyBean site = (StudyBean) sites.get(i);
          site.setStatus(Status.AVAILABLE);
          site.setUpdater(ub);
          site.setUpdatedDate(new Date());
          sdao.update(site);
        }

        // remove all users and roles
        for (int i = 0; i < userRoles.size(); i++) {
          StudyUserRoleBean role = (StudyUserRoleBean) userRoles.get(i);
          role.setStatus(Status.AVAILABLE);
          role.setUpdater(ub);
          role.setUpdatedDate(new Date());
          udao.updateStudyUserRole(role, role.getUserName());
        }

        // remove all subjects
        for (int i = 0; i < subjects.size(); i++) {
          StudySubjectBean subject = (StudySubjectBean) subjects.get(i);
          subject.setStatus(Status.AVAILABLE);
          subject.setUpdater(ub);
          subject.setUpdatedDate(new Date());
          ssdao.update(subject);
        }

        // remove all study_group
        StudyGroupDAO sgdao = new StudyGroupDAO(sm.getDataSource());
        SubjectGroupMapDAO sgmdao = new SubjectGroupMapDAO(sm.getDataSource());
        ArrayList groups = sgdao.findAllByStudy(study);
        for (int i = 0; i < groups.size(); i++) {
          StudyGroupBean group = (StudyGroupBean) groups.get(i);
          group.setStatus(Status.AVAILABLE);
          group.setUpdater(ub);
          group.setUpdatedDate(new Date());
          sgdao.update(group);
          // all subject_group_map
          ArrayList subjectGroupMaps = sgmdao.findAllByStudyGroupId(group.getId());
          for (int j = 0; j < subjectGroupMaps.size(); j++) {
            SubjectGroupMapBean sgMap = (SubjectGroupMapBean) subjectGroupMaps.get(j);
            sgMap.setStatus(Status.AVAILABLE);
            sgMap.setUpdater(ub);
            sgMap.setUpdatedDate(new Date());
            sgmdao.update(sgMap);
          }
        }

        // remove all event definitions and event
        EventDefinitionCRFDAO edcdao = new EventDefinitionCRFDAO(sm.getDataSource());
        StudyEventDAO sedao = new StudyEventDAO(sm.getDataSource());
        for (int i = 0; i < definitions.size(); i++) {
          StudyEventDefinitionBean definition = (StudyEventDefinitionBean) definitions.get(i);
          definition.setStatus(Status.AVAILABLE);
          definition.setUpdater(ub);
          definition.setUpdatedDate(new Date());
          sefdao.update(definition);
          ArrayList edcs = (ArrayList) edcdao.findAllByDefinition(definition.getId());
          for (int j = 0; j < edcs.size(); j++) {
            EventDefinitionCRFBean edc = (EventDefinitionCRFBean) edcs.get(j);
            edc.setStatus(Status.AVAILABLE);
            edc.setUpdater(ub);
            edc.setUpdatedDate(new Date());
            edcdao.update(edc);
          }

          ArrayList events = (ArrayList) sedao.findAllByDefinition(definition.getId());
          EventCRFDAO ecdao = new EventCRFDAO(sm.getDataSource());

          for (int j = 0; j < events.size(); j++) {
            StudyEventBean event = (StudyEventBean) events.get(j);
            event.setStatus(Status.AVAILABLE);
            event.setUpdater(ub);
            event.setUpdatedDate(new Date());
            sedao.update(event);

            ArrayList eventCRFs = ecdao.findAllByStudyEvent(event);

            ItemDataDAO iddao = new ItemDataDAO(sm.getDataSource());
            for (int k = 0; k < eventCRFs.size(); k++) {
              EventCRFBean eventCRF = (EventCRFBean) eventCRFs.get(k);
              eventCRF.setStatus(Status.AVAILABLE);
              eventCRF.setUpdater(ub);
              eventCRF.setUpdatedDate(new Date());
              ecdao.update(eventCRF);

              ArrayList itemDatas = iddao.findAllByEventCRFId(eventCRF.getId());
              for (int a = 0; a < itemDatas.size(); a++) {
                ItemDataBean item = (ItemDataBean) itemDatas.get(a);
                item.setStatus(Status.AVAILABLE);
                item.setUpdater(ub);
                item.setUpdatedDate(new Date());
                iddao.update(item);
              }
            }
          }
        } // for definitions

        DatasetDAO datadao = new DatasetDAO(sm.getDataSource());
        ArrayList dataset = datadao.findAllByStudyId(study.getId());
        for (int i = 0; i < dataset.size(); i++) {
          DatasetBean data = (DatasetBean) dataset.get(i);
          data.setStatus(Status.AVAILABLE);
          data.setUpdater(ub);
          data.setUpdatedDate(new Date());
          datadao.update(data);
        }

        addPageMessage("This study has been restored successfully.");
        forwardPage(Page.STUDY_LIST_SERVLET);
      }
    }
  }
  @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();
    }
  }