private StudyBean getParentStudy(String studyOid) {
   StudyBean study = getStudy(studyOid);
   if (study.getParentStudyId() == 0) {
     return study;
   } else {
     StudyBean parentStudy = (StudyBean) sdao.findByPK(study.getParentStudyId());
     return parentStudy;
   }
 }
 public MetadataUnit(DataSource ds, StudyBean study, int category) {
   super(ds, study, category);
   this.odmStudy = new OdmStudyBean();
   if (study.getParentStudyId() > 0) {
     this.parentStudy = (StudyBean) new StudyDAO(ds).findByPK(study.getParentStudyId());
   } else {
     this.parentStudy = new StudyBean();
   }
 }
  public String getInputUsername(StudyBean studyBean, StudySubjectBean studySubjectBean) {
    String inputUserName = null;
    if (studySubjectBean != null) {
      if (studyBean.getParentStudyId() > 0) studyBean = getStudy(studyBean.getParentStudyId());

      inputUserName = studyBean.getOid() + "." + studySubjectBean.getOid();
    }
    return inputUserName;
  }
 private StudyUserRoleBean getRole(UserAccountBean userAccount, StudyBean study) throws Exception {
   StudyUserRoleBean role = new StudyUserRoleBean();
   if (study == null || userAccount == null || study.getId() == 0) {
     throw new Exception();
   }
   if (userAccount.getId() > 0
       && study.getId() > 0
       && !study.getStatus().getName().equals("removed")) {
     role = userAccount.getRoleByStudy(study.getId());
     if (study.getParentStudyId() > 0) {
       StudyUserRoleBean roleInParent = userAccount.getRoleByStudy(study.getParentStudyId());
       role.setRole(Role.max(role.getRole(), roleInParent.getRole()));
     }
   } else {
     throw new Exception();
   }
   return role;
 }
 private ArrayList<StudyEventDefinitionBean> initDefinitions(StudyBean site) {
   ArrayList<StudyEventDefinitionBean> seds = new ArrayList<StudyEventDefinitionBean>();
   StudyEventDefinitionDAO sedDao = new StudyEventDefinitionDAO(sm.getDataSource());
   EventDefinitionCRFDAO edcdao = new EventDefinitionCRFDAO(sm.getDataSource());
   CRFVersionDAO cvdao = new CRFVersionDAO(sm.getDataSource());
   CRFDAO cdao = new CRFDAO(sm.getDataSource());
   StudyBean parentStudy =
       (StudyBean) new StudyDAO(sm.getDataSource()).findByPK(site.getParentStudyId());
   seds = sedDao.findAllByStudy(parentStudy);
   int start = 0;
   for (StudyEventDefinitionBean sed : seds) {
     int defId = sed.getId();
     ArrayList<EventDefinitionCRFBean> edcs =
         (ArrayList<EventDefinitionCRFBean>)
             edcdao.findAllByDefinitionAndSiteIdAndParentStudyId(
                 defId, site.getId(), parentStudy.getId());
     ArrayList<EventDefinitionCRFBean> defCrfs = new ArrayList<EventDefinitionCRFBean>();
     // sed.setCrfNum(edcs.size());
     for (EventDefinitionCRFBean edcBean : edcs) {
       int edcStatusId = edcBean.getStatus().getId();
       CRFBean crf = (CRFBean) cdao.findByPK(edcBean.getCrfId());
       int crfStatusId = crf.getStatusId();
       if (edcStatusId == 5 || edcStatusId == 7 || crfStatusId == 5 || crfStatusId == 7) {
       } else {
         ArrayList<CRFVersionBean> versions =
             (ArrayList<CRFVersionBean>) cvdao.findAllActiveByCRF(edcBean.getCrfId());
         edcBean.setVersions(versions);
         edcBean.setCrfName(crf.getName());
         CRFVersionBean defaultVersion =
             (CRFVersionBean) cvdao.findByPK(edcBean.getDefaultVersionId());
         edcBean.setDefaultVersionName(defaultVersion.getName());
         String sversionIds = edcBean.getSelectedVersionIds();
         ArrayList<Integer> idList = new ArrayList<Integer>();
         if (sversionIds.length() > 0) {
           String[] ids = sversionIds.split("\\,");
           for (String id : ids) {
             idList.add(Integer.valueOf(id));
           }
         }
         edcBean.setSelectedVersionIdList(idList);
         defCrfs.add(edcBean);
         ++start;
       }
     }
     logger.debug("definitionCrfs size=" + defCrfs.size() + " total size=" + edcs.size());
     sed.setCrfs(defCrfs);
     sed.setCrfNum(defCrfs.size());
   }
   return seds;
 }
  @RequestMapping(method = RequestMethod.POST)
  public String processSubmit(
      @ModelAttribute("studyModuleStatus") StudyModuleStatus studyModuleStatus,
      BindingResult result,
      SessionStatus status,
      HttpServletRequest request) {
    StudyBean currentStudy = (StudyBean) request.getSession().getAttribute("study");
    studyModuleStatusDao.saveOrUpdate(studyModuleStatus);
    status.setComplete();

    currentStudy.setStatus(Status.get(studyModuleStatus.getStudyStatus()));
    if (currentStudy.getParentStudyId() > 0) {
      studyDao.updateStudyStatus(currentStudy);
    } else {
      studyDao.updateStudyStatus(currentStudy);
    }

    return "redirect:studymodule";
  }
  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());

  }
  private void collectMetaDataVersion() {
    ArrayList<StudyEventDefinitionBean> sedBeansInStudy =
        (ArrayList<StudyEventDefinitionBean>) studyBase.getSedBeansInStudy();
    if (sedBeansInStudy == null || sedBeansInStudy.size() < 1) {
      logger.info("null, because there is no study event definition in this study.");
      return;
    }

    StudyBean study = studyBase.getStudy();
    MetaDataVersionBean metadata = this.odmStudy.getMetaDataVersion();

    StudyParameterValueDAO spvdao = new StudyParameterValueDAO(this.ds);
    int parentId = study.getParentStudyId() > 0 ? study.getParentStudyId() : study.getId();
    StudyParameterValueBean spv = spvdao.findByHandleAndStudy(parentId, "discrepancyManagement");
    metadata.setSoftHard(spv.getValue().equalsIgnoreCase("true") ? "Hard" : "Soft");

    OdmExtractDAO oedao = new OdmExtractDAO(this.ds);
    int studyId = study.getId();
    int parentStudyId = study.getParentStudyId() > 0 ? study.getParentStudyId() : studyId;
    if (this.getCategory() == 1 && study.isSite(study.getParentStudyId())) {
      // populate MetaDataVersion attributes
      if (dataset != null) {
        metadata.setOid(dataset.getODMMetaDataVersionOid() + "-" + study.getOid());
        metadata.setName(dataset.getODMMetaDataVersionName() + "-" + study.getOid());
        this.setParentMetaDataVersionOid(dataset.getODMMetaDataVersionOid());
      }
      if (metadata.getOid() == null || metadata.getOid().length() <= 0) {
        metadata.setOid("v1.0.0" + "-" + study.getOid());
        this.setParentMetaDataVersionOid("v1.0.0");
      }
      if (metadata.getName() == null || metadata.getName().length() <= 0) {
        metadata.setName("MetaDataVersion_v1.0.0" + "-" + study.getOid());
      }

      // populate Include
      this.collectIncludeFromParentInSameFile();

      // populate protocol
      oedao.getUpdatedSiteMetadata(parentStudyId, studyId, metadata, this.odmBean.getODMVersion());
    } else {
      if (dataset != null) {
        metadata.setOid(dataset.getODMMetaDataVersionOid());
        metadata.setName(dataset.getODMMetaDataVersionName());
      }
      if (metadata.getOid() == null || metadata.getOid().length() <= 0) {
        metadata.setOid("v1.0.0");
      }
      if (metadata.getName() == null || metadata.getName().length() <= 0) {
        metadata.setName("MetaDataVersion_v1.0.0");
      }

      // populate Include
      String psOid = new String();
      String pmOid = new String();
      if (dataset != null) {
        psOid = dataset.getODMPriorStudyOid();
        pmOid = dataset.getODMPriorMetaDataVersionOid();
      }
      if (pmOid != null && pmOid.length() > 0) {
        MetaDataVersionIncludeBean ib = metadata.getInclude();
        ib.setMetaDataVersionOID(pmOid);
        if (psOid != null && psOid.length() > 0) {
          ib.setStudyOID(psOid);
        } else {
          ib.setStudyOID(study.getOid());
        }
      }

      // populate protocol
      // Set<Integer> nullCodeSet = oedao.getMetadata(parentStudyId,
      // studyId,
      // metadata, this.getODMBean().getODMVersion());
      // studyBase.setNullClSet(nullCodeSet);
      oedao.getMetadata(parentStudyId, studyId, metadata, this.odmBean.getODMVersion());
    }
  }
  @Override
  public void processRequest() throws Exception {
    resetPanel();
    FormProcessor fp = new FormProcessor(request);
    Validator v = new Validator(request);
    int studyId = fp.getInt("id");
    studyId = studyId == 0 ? fp.getInt("studyId") : studyId;
    String action = fp.getString("action");
    StudyDAO sdao = new StudyDAO(sm.getDataSource());
    boolean isInterventional = false;

    study = (StudyBean) sdao.findByPK(studyId);
    if (study.getId() != currentStudy.getId()) {
      addPageMessage(
          respage.getString("not_current_study")
              + respage.getString("change_study_contact_sysadmin"));
      forwardPage(Page.MENU_SERVLET);
      return;
    }

    study.setId(studyId);
    StudyConfigService scs = new StudyConfigService(sm.getDataSource());
    study = scs.setParametersForStudy(study);
    request.setAttribute("studyToView", study);

    request.setAttribute("studyId", studyId + "");
    request.setAttribute("studyPhaseMap", CreateStudyServlet.studyPhaseMap);
    ArrayList statuses = Status.toStudyUpdateMembersList();
    statuses.add(Status.PENDING);
    request.setAttribute("statuses", statuses);

    String interventional = resadmin.getString("interventional");
    isInterventional = interventional.equalsIgnoreCase(study.getProtocolType());

    request.setAttribute("isInterventional", isInterventional ? "1" : "0");
    String protocolType = study.getProtocolTypeKey();

    // A. Hamid. 5001
    if (study.getParentStudyId() > 0) {
      StudyBean parentStudy = (StudyBean) sdao.findByPK(study.getParentStudyId());
      request.setAttribute("parentStudy", parentStudy);
    }

    ArrayList interventionArray = new ArrayList();
    if (isInterventional) {
      interventionArray = parseInterventions((study));
      setMaps(isInterventional, interventionArray);
    } else {
      setMaps(isInterventional, interventionArray);
    }

    if (!action.equals("submit")) {

      // First Load First Form
      if (study.getDatePlannedStart() != null) {
        fp.addPresetValue(INPUT_START_DATE, local_df.format(study.getDatePlannedStart()));
      }
      if (study.getDatePlannedEnd() != null) {
        fp.addPresetValue(INPUT_END_DATE, local_df.format(study.getDatePlannedEnd()));
      }
      if (study.getProtocolDateVerification() != null) {
        fp.addPresetValue(INPUT_VER_DATE, local_df.format(study.getProtocolDateVerification()));
      }
      setPresetValues(fp.getPresetValues());
      // first load 2nd form
    }
    if (study == null) {
      addPageMessage(respage.getString("please_choose_a_study_to_edit"));
      forwardPage(Page.STUDY_LIST_SERVLET);
      return;
    }
    if (action.equals("submit")) {

      validateStudy1(fp, v);
      validateStudy2(fp, v);
      validateStudy3(isInterventional, v, fp);
      validateStudy4(fp, v);
      validateStudy5(fp, v);
      validateStudy6(fp, v);
      confirmWholeStudy(fp, v);

      request.setAttribute("studyToView", study);
      if (!errors.isEmpty()) {
        System.out.println("found errors : " + errors.toString());
        request.setAttribute("formMessages", errors);

        forwardPage(Page.UPDATE_STUDY_NEW);
      } else {
        study.setProtocolType(protocolType);
        submitStudy(study);
        addPageMessage(respage.getString("the_study_has_been_updated_succesfully"));
        ArrayList pageMessages = (ArrayList) request.getAttribute(PAGE_MESSAGE);
        session.setAttribute("pageMessages", pageMessages);
        response.sendRedirect(request.getContextPath() + "/pages/studymodule");
        // forwardPage(Page.MANAGE_STUDY_MODULE);
      }
    } else {
      forwardPage(Page.UPDATE_STUDY_NEW);
    }
  }
  /*
   * Purpose: Iterates over ODM to populate 2 objects: 1. importCRFList: A List of EventCRFs and information on how to
   * process them. 2. importCRFMap: A Map multi-layer map of Subject/Event/Form only populated when the subsequent
   * EventCRF passes the UpsertOn rules.
   */
  public ImportCRFInfoContainer(ODMContainer odmContainer, DataSource ds) {
    importCRFList = new ArrayList<ImportCRFInfo>();

    ArrayList<EventCRFBean> eventCRFBeans = new ArrayList<EventCRFBean>();
    ArrayList<Integer> eventCRFBeanIds = new ArrayList<Integer>();
    EventCRFDAO eventCrfDAO = new EventCRFDAO(ds);
    StudySubjectDAO studySubjectDAO = new StudySubjectDAO(ds);
    StudyEventDefinitionDAO studyEventDefinitionDAO = new StudyEventDefinitionDAO(ds);
    StudyDAO studyDAO = new StudyDAO(ds);
    StudyEventDAO studyEventDAO = new StudyEventDAO(ds);
    UpsertOnBean upsert = odmContainer.getCrfDataPostImportContainer().getUpsertOn();
    // If Upsert bean is not present, create one with default settings
    if (upsert == null) upsert = new UpsertOnBean();
    String studyOID = odmContainer.getCrfDataPostImportContainer().getStudyOID();
    StudyBean studyBean = studyDAO.findByOid(studyOID);
    ArrayList<SubjectDataBean> subjectDataBeans =
        odmContainer.getCrfDataPostImportContainer().getSubjectData();

    Map<String, Map<String, Map<String, String>>> subjectMap =
        new HashMap<String, Map<String, Map<String, String>>>();
    for (SubjectDataBean subjectDataBean : subjectDataBeans) {
      ArrayList<StudyEventDataBean> studyEventDataBeans = subjectDataBean.getStudyEventData();
      StudySubjectBean studySubjectBean =
          studySubjectDAO.findByOidAndStudy(subjectDataBean.getSubjectOID(), studyBean.getId());

      Map<String, Map<String, String>> eventMap = new HashMap<String, Map<String, String>>();
      for (StudyEventDataBean studyEventDataBean : studyEventDataBeans) {
        ArrayList<FormDataBean> formDataBeans = studyEventDataBean.getFormData();
        String sampleOrdinal =
            studyEventDataBean.getStudyEventRepeatKey() == null
                ? "1"
                : studyEventDataBean.getStudyEventRepeatKey();

        StudyEventDefinitionBean studyEventDefinitionBean =
            studyEventDefinitionDAO.findByOidAndStudy(
                studyEventDataBean.getStudyEventOID(),
                studyBean.getId(),
                studyBean.getParentStudyId());
        logger.info(
            "find all by def and subject "
                + studyEventDefinitionBean.getName()
                + " study subject "
                + studySubjectBean.getName());

        StudyEventBean studyEventBean =
            (StudyEventBean)
                studyEventDAO.findByStudySubjectIdAndDefinitionIdAndOrdinal(
                    studySubjectBean.getId(),
                    studyEventDefinitionBean.getId(),
                    Integer.parseInt(sampleOrdinal));
        // @pgawade 16-March-2011 Do not allow the data import
        // if event status is one of the - stopped, signed,
        // locked
        Map<String, String> formMap = new HashMap<String, String>();
        for (FormDataBean formDataBean : formDataBeans) {

          CRFVersionDAO crfVersionDAO = new CRFVersionDAO(ds);
          ArrayList<CRFVersionBean> crfVersionBeans =
              crfVersionDAO.findAllByOid(formDataBean.getFormOID());
          for (CRFVersionBean crfVersionBean : crfVersionBeans) {

            ArrayList<EventCRFBean> eventCrfBeans =
                eventCrfDAO.findByEventSubjectVersion(
                    studyEventBean, studySubjectBean, crfVersionBean);
            // what if we have begun with creating a study
            // event, but haven't entered data yet? this would
            // have us with a study event, but no corresponding
            // event crf, yet.
            if (eventCrfBeans.isEmpty()) {
              logger.debug(
                  "   found no event crfs from Study Event id "
                      + studyEventBean.getId()
                      + ", location "
                      + studyEventBean.getLocation());

              ImportCRFInfo importCrfInfo =
                  new ImportCRFInfo(
                      studyOID,
                      subjectDataBean.getSubjectOID(),
                      studyEventDataBean.getStudyEventOID(),
                      formDataBean.getFormOID());
              importCrfInfo.setPreImportStage(DataEntryStage.UNCOMPLETED);
              String crfStatus = formDataBean.getEventCRFStatus();
              if (crfStatus != null
                  && crfStatus.equals(DataEntryStage.INITIAL_DATA_ENTRY.getName()))
                importCrfInfo.setPostImportStage(DataEntryStage.INITIAL_DATA_ENTRY);
              if ((studyEventBean.getSubjectEventStatus().equals(SubjectEventStatus.SCHEDULED)
                  || studyEventBean
                      .getSubjectEventStatus()
                      .equals(SubjectEventStatus.DATA_ENTRY_STARTED)
                  || studyEventBean.getSubjectEventStatus().equals(SubjectEventStatus.COMPLETED))) {

                if (!upsert.isNotStarted()) {
                  importCrfInfo.setProcessImport(false);
                  importCrfInfo.setEventCRFID(null);
                }
              }
              importCRFList.add(importCrfInfo);
              if (importCrfInfo.isProcessImport()) formMap.put(formDataBean.getFormOID(), "true");
            }

            for (EventCRFBean ecb : eventCrfBeans) {
              ImportCRFInfo importCrfInfo =
                  new ImportCRFInfo(
                      studyOID,
                      subjectDataBean.getSubjectOID(),
                      studyEventDataBean.getStudyEventOID(),
                      formDataBean.getFormOID());
              importCrfInfo.setPreImportStage(ecb.getStage());
              String crfStatus = formDataBean.getEventCRFStatus();
              if (crfStatus != null
                  && crfStatus.equals(DataEntryStage.INITIAL_DATA_ENTRY.getName()))
                importCrfInfo.setPostImportStage(DataEntryStage.INITIAL_DATA_ENTRY);
              importCrfInfo.setEventCRFID(new Integer(ecb.getId()));
              if (!(ecb.getStage().equals(DataEntryStage.INITIAL_DATA_ENTRY)
                      && upsert.isDataEntryStarted())
                  && !(ecb.getStage().equals(DataEntryStage.DOUBLE_DATA_ENTRY_COMPLETE)
                      && upsert.isDataEntryComplete())) importCrfInfo.setProcessImport(false);
              importCRFList.add(importCrfInfo);
              if (importCrfInfo.isProcessImport()) formMap.put(formDataBean.getFormOID(), "true");
            }
          }
        } // formdata loop
        if (formMap.size() > 0) eventMap.put(studyEventDataBean.getStudyEventOID(), formMap);
      } // study event loop
      if (eventMap.size() > 0) subjectMap.put(subjectDataBean.getSubjectOID(), eventMap);
    } // subject data loop
    importCRFMap = subjectMap;
  }
  private ArrayList<StudyEventDefinitionBean> createSiteEventDefinitions(StudyBean site) {
    FormProcessor fp = new FormProcessor(request);
    ArrayList<StudyEventDefinitionBean> seds = new ArrayList<StudyEventDefinitionBean>();
    StudyBean parentStudy =
        (StudyBean) new StudyDAO(sm.getDataSource()).findByPK(site.getParentStudyId());
    seds = (ArrayList<StudyEventDefinitionBean>) session.getAttribute("definitions");
    if (seds == null || seds.size() <= 0) {
      StudyEventDefinitionDAO sedDao = new StudyEventDefinitionDAO(sm.getDataSource());
      seds = sedDao.findAllByStudy(parentStudy);
    }
    CRFVersionDAO cvdao = new CRFVersionDAO(sm.getDataSource());
    HashMap<String, Boolean> changes = new HashMap<String, Boolean>();
    for (StudyEventDefinitionBean sed : seds) {
      EventDefinitionCRFDAO edcdao = new EventDefinitionCRFDAO(sm.getDataSource());
      ArrayList<EventDefinitionCRFBean> edcs = sed.getCrfs();
      int start = 0;
      for (EventDefinitionCRFBean edcBean : edcs) {
        int edcStatusId = edcBean.getStatus().getId();
        if (edcStatusId == 5 || edcStatusId == 7) {
        } else {
          String order = start + "-" + edcBean.getId();
          int defaultVersionId = fp.getInt("defaultVersionId" + order);
          String requiredCRF = fp.getString("requiredCRF" + order);
          String doubleEntry = fp.getString("doubleEntry" + order);
          String electronicSignature = fp.getString("electronicSignature" + order);
          String hideCRF = fp.getString("hideCRF" + order);
          int sdvId = fp.getInt("sdvOption" + order);
          ArrayList<String> selectedVersionIdList = fp.getStringArray("versionSelection" + order);
          int selectedVersionIdListSize = selectedVersionIdList.size();
          String selectedVersionIds = "";
          if (selectedVersionIdListSize > 0) {
            for (String id : selectedVersionIdList) {
              selectedVersionIds += id + ",";
            }
            selectedVersionIds = selectedVersionIds.substring(0, selectedVersionIds.length() - 1);
          }

          boolean changed = false;
          boolean isRequired =
              !StringUtil.isBlank(requiredCRF) && "yes".equalsIgnoreCase(requiredCRF.trim())
                  ? true
                  : false;
          boolean isDouble =
              !StringUtil.isBlank(doubleEntry) && "yes".equalsIgnoreCase(doubleEntry.trim())
                  ? true
                  : false;
          boolean hasPassword =
              !StringUtil.isBlank(electronicSignature)
                      && "yes".equalsIgnoreCase(electronicSignature.trim())
                  ? true
                  : false;
          boolean isHide =
              !StringUtil.isBlank(hideCRF) && "yes".equalsIgnoreCase(hideCRF.trim()) ? true : false;
          if (edcBean.getParentId() > 0) {
            int dbDefaultVersionId = edcBean.getDefaultVersionId();
            if (defaultVersionId != dbDefaultVersionId) {
              changed = true;
              CRFVersionBean defaultVersion = (CRFVersionBean) cvdao.findByPK(defaultVersionId);
              edcBean.setDefaultVersionId(defaultVersionId);
              edcBean.setDefaultVersionName(defaultVersion.getName());
            }
            if (isRequired != edcBean.isRequiredCRF()) {
              changed = true;
              edcBean.setRequiredCRF(isRequired);
            }
            if (isDouble != edcBean.isDoubleEntry()) {
              changed = true;
              edcBean.setDoubleEntry(isDouble);
            }
            if (hasPassword != edcBean.isElectronicSignature()) {
              changed = true;
              edcBean.setElectronicSignature(hasPassword);
            }
            if (isHide != edcBean.isHideCrf()) {
              changed = true;
              edcBean.setHideCrf(isHide);
            }
            if (!StringUtil.isBlank(selectedVersionIds)
                && !selectedVersionIds.equals(edcBean.getSelectedVersionIds())) {
              changed = true;
              String[] ids = selectedVersionIds.split(",");
              ArrayList<Integer> idList = new ArrayList<Integer>();
              for (String id : ids) {
                idList.add(Integer.valueOf(id));
              }
              edcBean.setSelectedVersionIdList(idList);
              edcBean.setSelectedVersionIds(selectedVersionIds);
            }
            if (sdvId > 0 && sdvId != edcBean.getSourceDataVerification().getCode()) {
              changed = true;
              edcBean.setSourceDataVerification(SourceDataVerification.getByCode(sdvId));
            }
          } else {
            // only if definition-crf has been modified, will it be
            // saved for the site
            int defaultId = defaultVersionId > 0 ? defaultVersionId : edcBean.getDefaultVersionId();
            if (defaultId == defaultVersionId) {
              if (isRequired == edcBean.isRequiredCRF()) {
                if (isDouble == edcBean.isDoubleEntry()) {
                  if (hasPassword == edcBean.isElectronicSignature()) {
                    if (isHide == edcBean.isHideCrf()) {
                      if (selectedVersionIdListSize > 0) {
                        if (selectedVersionIdListSize == edcBean.getVersions().size()) {
                          if (sdvId > 0) {
                            if (sdvId != edcBean.getSourceDataVerification().getCode()) {
                              changed = true;
                              edcBean.setSourceDataVerification(
                                  SourceDataVerification.getByCode(sdvId));
                            }
                          }
                        } else {
                          changed = true;
                          String[] ids = selectedVersionIds.split(",");
                          ArrayList<Integer> idList = new ArrayList<Integer>();
                          for (String id : ids) {
                            idList.add(Integer.valueOf(id));
                          }
                          edcBean.setSelectedVersionIdList(idList);
                          edcBean.setSelectedVersionIds(selectedVersionIds);
                        }
                      }
                    } else {
                      changed = true;
                      edcBean.setHideCrf(isHide);
                    }
                  } else {
                    changed = true;
                    edcBean.setElectronicSignature(hasPassword);
                  }
                } else {
                  changed = true;
                  edcBean.setDoubleEntry(isDouble);
                }
              } else {
                changed = true;
                edcBean.setRequiredCRF(isRequired);
              }
            } else {
              changed = true;
              CRFVersionBean defaultVersion = (CRFVersionBean) cvdao.findByPK(defaultVersionId);
              edcBean.setDefaultVersionId(defaultVersionId);
              edcBean.setDefaultVersionName(defaultVersion.getName());
            }
          }
          changes.put(sed.getId() + "-" + edcBean.getId(), changed);
          ++start;
        }
      }
    }
    session.setAttribute("changed", changes);
    return seds;
  }
  public boolean validate(SubjectTransferBean subjectTransferBean)
      throws OpenClinicaSystemException {

    StudyDAO stdao = new StudyDAO(this.getDataSource());
    StudyBean study = stdao.findByUniqueIdentifier(subjectTransferBean.getStudyOid());
    if (study == null) {
      throw new OpenClinicaSystemException("Study you specified does not exist");
    }

    UserAccountBean ua = subjectTransferBean.getOwner();
    StudyUserRoleBean role = ua.getRoleByStudy(study);
    if (role.getId() == 0 || role.getRole().equals(Role.MONITOR)) {
      throw new OpenClinicaSystemException(
          "You do not have sufficient priviliges to run this service");
    }

    if (subjectTransferBean.getSiteIdentifier() != null) {
      study =
          stdao.findSiteByUniqueIdentifier(
              subjectTransferBean.getStudyOid(), subjectTransferBean.getSiteIdentifier());
    }
    subjectTransferBean.setStudy(study);
    if (study == null) {
      throw new OpenClinicaSystemException("Site you specified does not exist");
    }
    int handleStudyId = study.getParentStudyId() > 0 ? study.getParentStudyId() : study.getId();
    org.akaza.openclinica.dao.service.StudyParameterValueDAO spvdao =
        new StudyParameterValueDAO(this.getDataSource());
    StudyParameterValueBean studyParameter =
        spvdao.findByHandleAndStudy(handleStudyId, "subjectPersonIdRequired");
    String personId = subjectTransferBean.getPersonId();
    if ("required".equals(studyParameter.getValue())
        && (personId == null || personId.length() < 1)) {
      throw new OpenClinicaSystemException(
          "personId is required for the study: " + study.getName());
      // return false;
    }

    if (personId != null && personId.length() > 255) {
      throw new OpenClinicaSystemException("personId should not be longer than 255.");
      // return false;
    }

    String idSetting = "";
    StudyParameterValueBean subjectIdGenerationParameter =
        spvdao.findByHandleAndStudy(handleStudyId, "subjectIdGeneration");
    idSetting = subjectIdGenerationParameter.getValue();
    if (idSetting.equals("auto editable") || idSetting.equals("auto non-editable")) {
      int nextLabel = getStudySubjectDao().findTheGreatestLabel() + 1;
      subjectTransferBean.setStudySubjectId(new Integer(nextLabel).toString());
    }
    String studySubjectId = subjectTransferBean.getStudySubjectId();
    if (studySubjectId == null || studySubjectId.length() < 1) {
      logger.info("studySubjectId is required.");
      throw new OpenClinicaSystemException("studySubjectId is required.");
      // return false;
    } else if (studySubjectId.length() > 30) {
      throw new OpenClinicaSystemException("studySubjectId should not be longer than 30.");
      // return false;
    }

    String secondaryId = subjectTransferBean.getSecondaryId();
    if (secondaryId != null && secondaryId.length() > 30) {
      throw new OpenClinicaSystemException("secondaryId should not be longer than 30.");
      // return false;
    }
    String gender = subjectTransferBean.getGender() + "";
    studyParameter = spvdao.findByHandleAndStudy(handleStudyId, "genderRequired");
    if ("true".equals(studyParameter.getValue()) && (gender == null || gender.length() < 1)) {
      throw new OpenClinicaSystemException("gender is required for the study:" + study.getName());
      // return false;
    }

    Date dateOfBirth = subjectTransferBean.getDateOfBirth();
    String yearOfBirth = subjectTransferBean.getYearOfBirth();
    studyParameter = spvdao.findByHandleAndStudy(handleStudyId, "collectDob");
    if ("1".equals(studyParameter.getValue()) && (dateOfBirth == null)) {
      throw new OpenClinicaSystemException("date Of Birth is required:" + study.getName());
      // return false;
    } else if ("2".equals(studyParameter.getValue()) && (yearOfBirth == null)) {
      throw new OpenClinicaSystemException("Year Of Birth is required:" + study.getName());
    } else if ("2".equals(studyParameter.getValue()) && (yearOfBirth != null)) {
      try {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
        subjectTransferBean.setDateOfBirth(sdf.parse(subjectTransferBean.getYearOfBirth()));
      } catch (ParseException e) {
        throw new OpenClinicaSystemException("Year Of Birth not Valid:" + study.getName());
      }
    }

    Date enrollmentDate = subjectTransferBean.getEnrollmentDate();
    if (enrollmentDate == null) {
      throw new OpenClinicaSystemException("enrollmentDate is required.");
      // return false;
    } else {
      if ((new Date()).compareTo(enrollmentDate) < 0) {
        throw new OpenClinicaSystemException("enrollmentDate should be in the past.");
        // return false;
      }
    }

    return true;
  }
  @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();
    }
  }
  @Override
  public void processRequest() throws Exception {
    UserAccountDAO udao = new UserAccountDAO(sm.getDataSource());
    StudyDAO sdao = new StudyDAO(sm.getDataSource());
    String name = request.getParameter("name");
    String studyIdString = request.getParameter("studyId");
    if (StringUtil.isBlank(name) || StringUtil.isBlank(studyIdString)) {
      addPageMessage(respage.getString("please_choose_a_user_to_set_role_for"));
      forwardPage(Page.LIST_USER_IN_STUDY_SERVLET);
    } else {
      String action = request.getParameter("action");
      FormProcessor fp = new FormProcessor(request);
      UserAccountBean user = (UserAccountBean) udao.findByUserName(name);
      StudyBean userStudy = (StudyBean) sdao.findByPK(fp.getInt("studyId"));
      if ("confirm".equalsIgnoreCase(action)) {
        int studyId = Integer.valueOf(studyIdString.trim()).intValue();

        request.setAttribute("user", user);

        StudyUserRoleBean uRole = udao.findRoleByUserNameAndStudyId(name, studyId);
        uRole.setStudyName(userStudy.getName());
        request.setAttribute("uRole", uRole);

        ArrayList roles = Role.toArrayList();
        roles.remove(Role.ADMIN); // admin is not a user role, only used for tomcat

        StudyBean studyBean = (StudyBean) sdao.findByPK(uRole.getStudyId());

        if (currentStudy.getParentStudyId() > 0) {
          roles.remove(Role.COORDINATOR);
          roles.remove(Role.STUDYDIRECTOR);
        } else if (studyBean.getParentStudyId() > 0) {
          roles.remove(Role.COORDINATOR);
          roles.remove(Role.STUDYDIRECTOR);
          // TODO: redo this fix
          Role r = Role.RESEARCHASSISTANT;
          r.setDescription("site_Data_Entry_Person");
          roles.remove(Role.RESEARCHASSISTANT);
          roles.add(r);
          Role ri = Role.INVESTIGATOR;
          ri.setDescription("site_investigator");
          roles.remove(Role.INVESTIGATOR);

          roles.add(ri);
        }
        request.setAttribute("roles", roles);

        forwardPage(Page.SET_USER_ROLE_IN_STUDY);
      } else {
        // set role

        String userName = fp.getString("name");
        int studyId = fp.getInt("studyId");
        int roleId = fp.getInt("roleId");
        StudyUserRoleBean sur = new StudyUserRoleBean();
        sur.setName(userName);
        sur.setRole(Role.get(roleId));
        sur.setStudyId(studyId);
        sur.setStudyName(userStudy.getName());
        sur.setStatus(Status.AVAILABLE);
        sur.setUpdater(ub);
        sur.setUpdatedDate(new Date());
        udao.updateStudyUserRole(sur, userName);
        addPageMessage(sendEmail(user, sur));
        forwardPage(Page.LIST_USER_IN_STUDY_SERVLET);
      }
    }
  }
  private void submitStudy() {
    StudyDAO sdao = new StudyDAO(sm.getDataSource());
    StudyParameterValueDAO spvdao = new StudyParameterValueDAO(sm.getDataSource());

    StudyBean study1 = (StudyBean) session.getAttribute("newStudy");
    logger.info("study bean to be updated:" + study1.getName());
    study1.setUpdatedDate(new Date());
    study1.setUpdater((UserAccountBean) session.getAttribute("userBean"));
    System.out.println("study's parentId=" + study1.getParentStudyId());
    sdao.update(study1);

    StudyParameterValueBean spv = new StudyParameterValueBean();

    spv.setStudyId(study1.getId());
    spv.setParameter("collectDob");
    spv.setValue(new Integer(study1.getStudyParameterConfig().getCollectDob()).toString());
    updateParameter(spvdao, spv);

    spv.setParameter("discrepancyManagement");
    spv.setValue(study1.getStudyParameterConfig().getDiscrepancyManagement());
    updateParameter(spvdao, spv);

    spv.setParameter("genderRequired");
    spv.setValue(study1.getStudyParameterConfig().getGenderRequired());
    updateParameter(spvdao, spv);

    spv.setParameter("subjectPersonIdRequired");
    spv.setValue(study1.getStudyParameterConfig().getSubjectPersonIdRequired());
    updateParameter(spvdao, spv);

    spv.setParameter("interviewerNameRequired");
    spv.setValue(study1.getStudyParameterConfig().getInterviewerNameRequired());
    updateParameter(spvdao, spv);

    spv.setParameter("interviewerNameDefault");
    spv.setValue(study1.getStudyParameterConfig().getInterviewerNameDefault());
    updateParameter(spvdao, spv);

    spv.setParameter("interviewerNameEditable");
    spv.setValue(study1.getStudyParameterConfig().getInterviewerNameEditable());
    updateParameter(spvdao, spv);

    spv.setParameter("interviewDateRequired");
    spv.setValue(study1.getStudyParameterConfig().getInterviewDateRequired());
    updateParameter(spvdao, spv);

    spv.setParameter("interviewDateDefault");
    spv.setValue(study1.getStudyParameterConfig().getInterviewDateDefault());
    updateParameter(spvdao, spv);

    spv.setParameter("interviewDateEditable");
    spv.setValue(study1.getStudyParameterConfig().getInterviewDateEditable());
    updateParameter(spvdao, spv);

    spv.setParameter("subjectIdGeneration");
    spv.setValue(study1.getStudyParameterConfig().getSubjectIdGeneration());
    updateParameter(spvdao, spv);

    spv.setParameter("subjectIdPrefixSuffix");
    spv.setValue(study1.getStudyParameterConfig().getSubjectIdPrefixSuffix());
    updateParameter(spvdao, spv);

    spv.setParameter("personIdShownOnCRF");
    spv.setValue(study1.getStudyParameterConfig().getPersonIdShownOnCRF());
    updateParameter(spvdao, spv);

    StudyBean curStudy = (StudyBean) session.getAttribute("study");
    if (curStudy != null && study1.getId() == curStudy.getId()) {
      super.currentStudy = study1;
      session.setAttribute("study", study1);
    }
    // update manage_pedigrees for all sites
    ArrayList children = (ArrayList) sdao.findAllByParent(study1.getId());
    for (int i = 0; i < children.size(); i++) {
      StudyBean child = (StudyBean) children.get(i);
      child.setType(study1.getType()); // same as parent's type
      child.setUpdatedDate(new Date());
      child.setUpdater(ub);
      sdao.update(child);
      // YW << update "collectDob" and "genderRequired" for sites
      StudyParameterValueBean childspv = new StudyParameterValueBean();
      childspv.setStudyId(child.getId());
      childspv.setParameter("collectDob");
      childspv.setValue(new Integer(study1.getStudyParameterConfig().getCollectDob()).toString());
      updateParameter(spvdao, childspv);
      childspv.setParameter("genderRequired");
      childspv.setValue(study1.getStudyParameterConfig().getGenderRequired());
      updateParameter(spvdao, childspv);
      // YW >>
    }

    session.removeAttribute("newStudy");
    session.removeAttribute("interventions");
  }
  /** Inserts the new study into database */
  private void submitStudy() {
    FormProcessor fp = new FormProcessor(request);
    StudyDAO sdao = new StudyDAO(sm.getDataSource());
    StudyBean study = (StudyBean) session.getAttribute("newStudy");

    ArrayList parameters = study.getStudyParameters();
    logger.info("study bean to be created:\n");
    logger.info(
        study.getName()
            + "\n"
            + study.getIdentifier()
            + "\n"
            + study.getParentStudyId()
            + "\n"
            + study.getSummary()
            + "\n"
            + study.getPrincipalInvestigator()
            + "\n"
            + study.getDatePlannedStart()
            + "\n"
            + study.getDatePlannedEnd()
            + "\n"
            + study.getFacilityName()
            + "\n"
            + study.getFacilityCity()
            + "\n"
            + study.getFacilityState()
            + "\n"
            + study.getFacilityZip()
            + "\n"
            + study.getFacilityCountry()
            + "\n"
            + study.getFacilityRecruitmentStatus()
            + "\n"
            + study.getFacilityContactName()
            + "\n"
            + study.getFacilityContactEmail()
            + "\n"
            + study.getFacilityContactPhone()
            + "\n"
            + study.getFacilityContactDegree());

    study.setOwner(ub);
    study.setCreatedDate(new Date());
    StudyBean parent = (StudyBean) sdao.findByPK(study.getParentStudyId());
    study.setType(parent.getType());
    // YW 10-10-2007, enable setting site status
    study.setStatus(study.getStatus());
    // YW >>

    study.setGenetic(parent.isGenetic());
    study = (StudyBean) sdao.create(study);

    StudyParameterValueDAO spvdao = new StudyParameterValueDAO(sm.getDataSource());
    for (int i = 0; i < parameters.size(); i++) {
      StudyParamsConfig config = (StudyParamsConfig) parameters.get(i);
      StudyParameterValueBean spv = config.getValue();
      spv.setStudyId(study.getId());
      spv = (StudyParameterValueBean) spvdao.create(config.getValue());
    }

    // YW << here only "collectDob" and "genderRequired" have been corrected
    // for sites.
    StudyParameterValueBean spv = new StudyParameterValueBean();
    StudyParameterValueBean parentSPV = spvdao.findByHandleAndStudy(parent.getId(), "collectDob");
    spv.setStudyId(study.getId());
    spv.setParameter("collectDob");
    spv.setValue(parentSPV.getValue());
    spvdao.create(spv);

    parentSPV = spvdao.findByHandleAndStudy(parent.getId(), "genderRequired");
    spv.setParameter("genderRequired");
    spv.setValue(parentSPV.getValue());
    spvdao.create(spv);
    // YW >>

    // switch user to the newly created site
    session.setAttribute("study", session.getAttribute("newStudy"));
    currentStudy = (StudyBean) session.getAttribute("study");

    session.removeAttribute("newStudy");
    addPageMessage(respage.getString("the_new_site_created_succesfully_current"));
    forwardPage(Page.SITE_LIST_SERVLET);
  }
  /**
   * Validates the first section of study and save it into study bean
   *
   * @throws Exception
   */
  private void confirmStudy() throws Exception {
    Validator v = new Validator(request);
    FormProcessor fp = new FormProcessor(request);

    v.addValidation("name", Validator.NO_BLANKS);
    v.addValidation("uniqueProId", Validator.NO_BLANKS);

    // >> tbh
    // v.addValidation("description", Validator.NO_BLANKS);
    // << tbh, #3943, 07/2009
    v.addValidation("prinInvestigator", Validator.NO_BLANKS);
    if (!StringUtil.isBlank(fp.getString(INPUT_START_DATE))) {
      v.addValidation(INPUT_START_DATE, Validator.IS_A_DATE);
    }
    if (!StringUtil.isBlank(fp.getString(INPUT_END_DATE))) {
      v.addValidation(INPUT_END_DATE, Validator.IS_A_DATE);
    }
    if (!StringUtil.isBlank(fp.getString("facConEmail"))) {
      v.addValidation("facConEmail", Validator.IS_A_EMAIL);
    }
    if (!StringUtil.isBlank(fp.getString(INPUT_VER_DATE))) {
      v.addValidation(INPUT_VER_DATE, Validator.IS_A_DATE);
    }
    // v.addValidation("statusId", Validator.IS_VALID_TERM);
    v.addValidation(
        "secondProId",
        Validator.LENGTH_NUMERIC_COMPARISON,
        NumericComparisonOperator.LESS_THAN_OR_EQUAL_TO,
        255);
    v.addValidation(
        "facName",
        Validator.LENGTH_NUMERIC_COMPARISON,
        NumericComparisonOperator.LESS_THAN_OR_EQUAL_TO,
        255);
    v.addValidation(
        "facCity",
        Validator.LENGTH_NUMERIC_COMPARISON,
        NumericComparisonOperator.LESS_THAN_OR_EQUAL_TO,
        255);
    v.addValidation(
        "facState",
        Validator.LENGTH_NUMERIC_COMPARISON,
        NumericComparisonOperator.LESS_THAN_OR_EQUAL_TO,
        20);
    v.addValidation(
        "facZip",
        Validator.LENGTH_NUMERIC_COMPARISON,
        NumericComparisonOperator.LESS_THAN_OR_EQUAL_TO,
        64);
    v.addValidation(
        "facCountry",
        Validator.LENGTH_NUMERIC_COMPARISON,
        NumericComparisonOperator.LESS_THAN_OR_EQUAL_TO,
        64);
    v.addValidation(
        "facConName",
        Validator.LENGTH_NUMERIC_COMPARISON,
        NumericComparisonOperator.LESS_THAN_OR_EQUAL_TO,
        255);
    v.addValidation(
        "facConDegree",
        Validator.LENGTH_NUMERIC_COMPARISON,
        NumericComparisonOperator.LESS_THAN_OR_EQUAL_TO,
        255);
    v.addValidation(
        "facConPhone",
        Validator.LENGTH_NUMERIC_COMPARISON,
        NumericComparisonOperator.LESS_THAN_OR_EQUAL_TO,
        255);
    v.addValidation(
        "facConEmail",
        Validator.LENGTH_NUMERIC_COMPARISON,
        NumericComparisonOperator.LESS_THAN_OR_EQUAL_TO,
        255);

    errors = v.validate();
    // >> tbh
    StudyDAO studyDAO = new StudyDAO(sm.getDataSource());
    ArrayList<StudyBean> allStudies = (ArrayList<StudyBean>) studyDAO.findAll();
    for (StudyBean thisBean : allStudies) {
      if (fp.getString("uniqueProId").trim().equals(thisBean.getIdentifier())) {
        Validator.addError(
            errors, "uniqueProId", resexception.getString("unique_protocol_id_existed"));
      }
    }
    // << tbh #3999 08/2009
    if (fp.getString("name").trim().length() > 100) {
      Validator.addError(errors, "name", resexception.getString("maximum_lenght_name_100"));
    }
    if (fp.getString("uniqueProId").trim().length() > 30) {
      Validator.addError(
          errors, "uniqueProId", resexception.getString("maximum_lenght_unique_protocol_30"));
    }
    if (fp.getString("description").trim().length() > 255) {
      Validator.addError(
          errors, "description", resexception.getString("maximum_lenght_brief_summary_255"));
    }
    if (fp.getString("prinInvestigator").trim().length() > 255) {
      Validator.addError(
          errors,
          "prinInvestigator",
          resexception.getString("maximum_lenght_principal_investigator_255"));
    }
    if (fp.getInt("expectedTotalEnrollment") <= 0) {
      Validator.addError(
          errors,
          "expectedTotalEnrollment",
          respage.getString("expected_total_enrollment_must_be_a_positive_number"));
    }

    StudyBean newSite = this.createStudyBean();
    StudyBean parentStudy =
        (StudyBean) new StudyDAO(sm.getDataSource()).findByPK(newSite.getParentStudyId());
    session.setAttribute("newStudy", newSite);
    session.setAttribute("definitions", this.createSiteEventDefinitions(parentStudy));

    if (errors.isEmpty()) {
      logger.info("no errors");
      forwardPage(Page.CONFIRM_CREATE_SUB_STUDY);

    } else {
      try {
        local_df.parse(fp.getString(INPUT_START_DATE));
        fp.addPresetValue(INPUT_START_DATE, local_df.format(fp.getDate(INPUT_START_DATE)));
      } catch (ParseException pe) {
        fp.addPresetValue(INPUT_START_DATE, fp.getString(INPUT_START_DATE));
      }
      try {
        local_df.parse(fp.getString(INPUT_END_DATE));
        fp.addPresetValue(INPUT_END_DATE, local_df.format(fp.getDate(INPUT_END_DATE)));
      } catch (ParseException pe) {
        fp.addPresetValue(INPUT_END_DATE, fp.getString(INPUT_END_DATE));
      }
      try {
        local_df.parse(fp.getString(INPUT_VER_DATE));
        fp.addPresetValue(INPUT_VER_DATE, local_df.format(fp.getDate(INPUT_VER_DATE)));
      } catch (ParseException pe) {
        fp.addPresetValue(INPUT_VER_DATE, fp.getString(INPUT_VER_DATE));
      }
      setPresetValues(fp.getPresetValues());
      logger.info("has validation errors");
      request.setAttribute("formMessages", errors);
      // request.setAttribute("facRecruitStatusMap",
      // CreateStudyServlet.facRecruitStatusMap);
      request.setAttribute("statuses", Status.toActiveArrayList());
      forwardPage(Page.CREATE_SUB_STUDY);
    }
  }