private void collectGlobalVariables() {
   StudyBean study = studyBase.getStudy();
   String sn = study.getName();
   String sd = study.getSummary().trim();
   String pn = study.getIdentifier();
   if (parentStudy.getId() > 0) {
     sn = parentStudy.getName() + " - " + study.getName();
     sd = parentStudy.getSummary().trim() + " - " + study.getSummary().trim();
     pn = parentStudy.getIdentifier() + " - " + study.getIdentifier();
   }
   GlobalVariablesBean gv = this.odmStudy.getGlobalVariables();
   gv.setStudyName(sn);
   gv.setStudyDescription(sd);
   gv.setProtocolName(pn);
 }
  /**
   * Send email to the user, director and administrator
   *
   * @param request
   * @param response
   */
  private String sendEmail(UserAccountBean u, StudyUserRoleBean sub) throws Exception {

    StudyDAO sdao = new StudyDAO(sm.getDataSource());
    StudyBean study = (StudyBean) sdao.findByPK(sub.getStudyId());
    logger.info("Sending email...");
    String body =
        u.getFirstName()
            + " "
            + u.getLastName()
            + " ("
            + resword.getString("username")
            + ": "
            + u.getName()
            + ") "
            + respage.getString("has_been_granted_the_role")
            + " "
            + sub.getRoleName()
            + " "
            + respage.getString("in_the_study_site")
            + " "
            + study.getName()
            + ".";

    //        boolean emailSent = sendEmail(u.getEmail().trim(), respage.getString("set_user_role"),
    // body, false);
    //        if (emailSent) {
    //            sendEmail(ub.getEmail().trim(), respage.getString("set_user_role"), body, false);
    //            sendEmail(EmailEngine.getAdminEmail(), respage.getString("set_user_role"), body,
    // false);
    //        }
    return body;
  }
  public SimpleTrigger generateImportTrigger(
      FormProcessor fp,
      UserAccountBean userAccount,
      StudyBean study,
      Date startDateTime,
      String locale) {

    String jobName = fp.getString(JOB_NAME);

    String email = fp.getString(EMAIL);
    String jobDesc = fp.getString(JOB_DESC);
    String directory = fp.getString(DIRECTORY);

    // what kinds of periods do we have? hourly, daily, weekly?
    long interval = 0;
    int hours = fp.getInt("hours");
    int minutes = fp.getInt("minutes");
    if (hours > 0) {
      long hoursInt = hours * 3600000;
      interval = interval + hoursInt;
    }
    if (minutes > 0) {
      long minutesInt = minutes * 60000;
      interval = interval + minutesInt;
    }
    SimpleTrigger trigger = new SimpleTrigger(jobName, IMPORT_TRIGGER, 64000, interval);
    trigger.setDescription(jobDesc);
    // set just the start date
    trigger.setStartTime(startDateTime);
    trigger.setName(jobName); // + datasetId);
    trigger.setGroup(IMPORT_TRIGGER); // + datasetId);
    trigger.setMisfireInstruction(
        SimpleTrigger.MISFIRE_INSTRUCTION_RESCHEDULE_NEXT_WITH_EXISTING_COUNT);
    // set job data map
    JobDataMap jobDataMap = new JobDataMap();

    jobDataMap.put(EMAIL, email);
    jobDataMap.put(USER_ID, userAccount.getId());
    jobDataMap.put(STUDY_NAME, study.getName());
    jobDataMap.put(STUDY_OID, study.getOid());
    jobDataMap.put(DIRECTORY, directory);
    jobDataMap.put(ExampleSpringJob.LOCALE, locale);
    jobDataMap.put("hours", hours);
    jobDataMap.put("minutes", minutes);

    trigger.setJobDataMap(jobDataMap);
    trigger.setVolatility(false);
    return trigger;
  }
  /** 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);
  }
  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");
  }
  @RequestMapping(method = RequestMethod.GET)
  public ModelMap handleMainPage(HttpServletRequest request) {
    ModelMap map = new ModelMap();
    // setUpSidebar(request);
    StudyBean currentStudy = (StudyBean) request.getSession().getAttribute("study");

    eventDefinitionCRFDao = new EventDefinitionCRFDAO(dataSource);
    studyEventDefinitionDao = new StudyEventDefinitionDAO(dataSource);
    crfDao = new CRFDAO(dataSource);
    studyGroupClassDao = new StudyGroupClassDAO(dataSource);
    studyDao = new StudyDAO(dataSource);
    userDao = new UserAccountDAO(dataSource);
    ruleDao = new RuleDAO(dataSource);

    StudyModuleStatus sms = studyModuleStatusDao.findByStudyId(currentStudy.getId());
    if (sms == null) {
      sms = new StudyModuleStatus();
      sms.setStudyId(currentStudy.getId());
    }

    int crfCount = crfDao.findAllByStudy(currentStudy.getId()).size();
    int crfWithEventDefinition = crfDao.findAllActiveByDefinitions(currentStudy.getId()).size();
    int totalCrf = crfCount + crfWithEventDefinition;
    // int eventDefinitionCount = eventDefinitionCRFDao.findAllActiveByStudy(currentStudy).size();
    int eventDefinitionCount = studyEventDefinitionDao.findAllActiveByStudy(currentStudy).size();

    int subjectGroupCount = studyGroupClassDao.findAllActiveByStudy(currentStudy).size();

    List<RuleSetBean> ruleSets = ruleSetService.getRuleSetsByStudy(currentStudy);
    ruleSets = ruleSetService.filterByStatusEqualsAvailableOnlyRuleSetRules(ruleSets);
    int ruleCount = ruleSets != null ? ruleSets.size() : 0;

    int siteCount = studyDao.findOlnySiteIdsByStudy(currentStudy).size();
    int userCount = userDao.findAllUsersByStudy(currentStudy.getId()).size();
    Collection childStudies = studyDao.findAllByParent(currentStudy.getId());
    Map childStudyUserCount = new HashMap();
    for (Object sb : childStudies) {
      StudyBean childStudy = (StudyBean) sb;
      childStudyUserCount.put(
          childStudy.getName(), userDao.findAllUsersByStudy(childStudy.getId()).size());
    }

    if (sms.getCrf() == 0) {
      sms.setCrf(StudyModuleStatus.NOT_STARTED);
    }
    if (sms.getCrf() != 3 && totalCrf > 0) {
      sms.setCrf(StudyModuleStatus.IN_PROGRESS);
    }

    if (sms.getEventDefinition() == 0) {
      sms.setEventDefinition(StudyModuleStatus.NOT_STARTED);
    }
    if (sms.getEventDefinition() != 3 && eventDefinitionCount > 0) {
      sms.setEventDefinition(StudyModuleStatus.IN_PROGRESS);
    }

    if (sms.getSubjectGroup() == 0) {
      sms.setSubjectGroup(StudyModuleStatus.NOT_STARTED);
    }
    if (sms.getSubjectGroup() != 3 && subjectGroupCount > 0) {
      sms.setSubjectGroup(StudyModuleStatus.IN_PROGRESS);
    }

    if (sms.getRule() == 0) {
      sms.setRule(StudyModuleStatus.NOT_STARTED);
    }
    if (sms.getRule() != 3 && ruleCount > 0) {
      sms.setRule(StudyModuleStatus.IN_PROGRESS);
    }

    if (sms.getSite() == 0) {
      sms.setSite(StudyModuleStatus.NOT_STARTED);
    }
    if (sms.getSite() != 3 && siteCount > 0) {
      sms.setSite(StudyModuleStatus.IN_PROGRESS);
    }

    if (sms.getUsers() == 0) {
      sms.setUsers(StudyModuleStatus.NOT_STARTED);
    }
    if (sms.getUsers() != 3 && userCount > 0) {
      sms.setUsers(StudyModuleStatus.IN_PROGRESS);
    }

    map.addObject(sms);
    map.addAttribute("crfCount", totalCrf);
    map.addAttribute("eventDefinitionCount", eventDefinitionCount);
    map.addAttribute("subjectGroupCount", subjectGroupCount);
    map.addAttribute("ruleCount", ruleCount);
    map.addAttribute("siteCount", siteCount);
    map.addAttribute("userCount", userCount);
    map.addAttribute("childStudyUserCount", childStudyUserCount);
    map.addAttribute("studyId", currentStudy.getId());
    map.addAttribute("currentStudy", currentStudy);

    UserAccountBean userBean = (UserAccountBean) request.getSession().getAttribute("userBean");
    request.setAttribute("userBean", userBean);
    request.setAttribute("statusMap", Status.toStudyUpdateMembersList());

    ArrayList pageMessages = new ArrayList();
    if (request.getSession().getAttribute("pageMessages") != null) {
      pageMessages.addAll((ArrayList) request.getSession().getAttribute("pageMessages"));
      request.setAttribute("pageMessages", pageMessages);
      request.getSession().removeAttribute("pageMessages");
    }
    return map;
  }
  private void submitStudy(StudyBean newStudy) {
    StudyDAO sdao = new StudyDAO(sm.getDataSource());
    StudyParameterValueDAO spvdao = new StudyParameterValueDAO(sm.getDataSource());

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

    ArrayList siteList = (ArrayList) sdao.findAllByParent(newStudy.getId());
    if (siteList.size() > 0) {
      sdao.updateSitesStatus(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);

    // BWP 1/12/2009 3169 Update interviewerNameEditable and
    // interviewDateEditable parameters for all sites>>
    List<StudyBean> sites = new ArrayList<StudyBean>();
    sites = (ArrayList) sdao.findAllByParent(newStudy.getId());
    if (sites != null && (!sites.isEmpty())) {
      updateInterviewerForSites(newStudy, sites, spvdao, "interviewerNameEditable");
    }
    // >>

    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);
    // BWP 1/12/2009 3169>>
    if (sites != null && (!sites.isEmpty())) {
      updateInterviewerForSites(newStudy, sites, spvdao, "interviewDateEditable");
    }
    // >>
    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);
    spv.setParameter("secondaryLabelViewable");
    spv.setValue(study1.getStudyParameterConfig().getSecondaryLabelViewable());
    updateParameter(spvdao, spv);

    // tbh, 06/04/2009 3684>>
    spv.setParameter("adminForcedReasonForChange");
    spv.setValue(study1.getStudyParameterConfig().getAdminForcedReasonForChange());
    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);
    }
  }
  @Override
  public void processRequest() throws Exception {
    String studySubIdString = request.getParameter("id"); // studySubjectId
    String subIdString = request.getParameter("subjectId");
    String studyIdString = request.getParameter("studyId");

    SubjectDAO sdao = new SubjectDAO(sm.getDataSource());
    StudySubjectDAO subdao = new StudySubjectDAO(sm.getDataSource());

    if (StringUtil.isBlank(studySubIdString)
        || StringUtil.isBlank(subIdString)
        || StringUtil.isBlank(studyIdString)) {
      addPageMessage(respage.getString("please_choose_a_study_subject_to_remove"));
      forwardPage(Page.LIST_STUDY_SUBJECT_SERVLET);
    } else {
      int studyId = Integer.valueOf(studyIdString.trim()).intValue();
      int studySubId = Integer.valueOf(studySubIdString.trim()).intValue();
      int subjectId = Integer.valueOf(subIdString.trim()).intValue();

      SubjectBean subject = (SubjectBean) sdao.findByPK(subjectId);

      StudySubjectBean studySub = (StudySubjectBean) subdao.findByPK(studySubId);

      StudyDAO studydao = new StudyDAO(sm.getDataSource());
      StudyBean study = (StudyBean) studydao.findByPK(studyId);

      // find study events
      StudyEventDAO sedao = new StudyEventDAO(sm.getDataSource());
      ArrayList events = sedao.findAllByStudyAndStudySubjectId(study, studySubId);

      String action = request.getParameter("action");
      if ("confirm".equalsIgnoreCase(action)) {
        if (!studySub.getStatus().equals(Status.AVAILABLE)) {
          addPageMessage(
              respage.getString("this_subject_is_not_available_for_this_study")
                  + " "
                  + respage.getString("please_contact_sysadmin_for_more_information"));
          forwardPage(Page.LIST_STUDY_SUBJECT_SERVLET);
          return;
        }

        request.setAttribute("subject", subject);
        request.setAttribute("study", study);
        request.setAttribute("studySub", studySub);
        request.setAttribute("events", events);

        forwardPage(Page.REMOVE_STUDY_SUBJECT);
      } else {
        logger.info("submit to remove the subject from study");
        // remove subject from study
        studySub.setStatus(Status.DELETED);
        studySub.setUpdater(ub);
        studySub.setUpdatedDate(new Date());
        subdao.update(studySub);

        // remove all study events
        // remove all event crfs
        EventCRFDAO ecdao = new EventCRFDAO(sm.getDataSource());

        for (int j = 0; j < events.size(); j++) {
          StudyEventBean event = (StudyEventBean) events.get(j);
          if (!event.getStatus().equals(Status.DELETED)) {
            event.setStatus(Status.AUTO_DELETED);
            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);
              if (!eventCRF.getStatus().equals(Status.DELETED)) {
                eventCRF.setStatus(Status.AUTO_DELETED);
                eventCRF.setUpdater(ub);
                eventCRF.setUpdatedDate(new Date());
                ecdao.update(eventCRF);
                // remove all the item data
                ArrayList itemDatas = iddao.findAllByEventCRFId(eventCRF.getId());
                for (int a = 0; a < itemDatas.size(); a++) {
                  ItemDataBean item = (ItemDataBean) itemDatas.get(a);
                  if (!item.getStatus().equals(Status.DELETED)) {
                    item.setStatus(Status.AUTO_DELETED);
                    item.setUpdater(ub);
                    item.setUpdatedDate(new Date());
                    iddao.update(item);
                  }
                }
              }
            }
          }
        }

        String emailBody =
            respage.getString("the_subject")
                + " "
                + subject.getName()
                + " "
                + respage.getString("has_been_removed_from_the_study")
                + study.getName()
                + ".";

        addPageMessage(emailBody);
        sendEmail(emailBody);
        forwardPage(Page.LIST_STUDY_SUBJECT_SERVLET);
      }
    }
  }
  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();
    }
  }
  public SimpleTrigger generateTrigger(
      FormProcessor fp, UserAccountBean userAccount, StudyBean study, String locale) {
    Date startDateTime = fp.getDateTime(DATE_START_JOB);
    // check the above?
    int datasetId = fp.getInt(DATASET_ID);
    String period = fp.getString(PERIOD);
    String email = fp.getString(EMAIL);
    String jobName = fp.getString(JOB_NAME);
    String jobDesc = fp.getString(JOB_DESC);
    String spss = fp.getString(SPSS);
    String tab = fp.getString(TAB);
    String cdisc = fp.getString(CDISC);
    String cdisc12 = fp.getString(ExampleSpringJob.CDISC12);
    String cdisc13 = fp.getString(ExampleSpringJob.CDISC13);
    String cdisc13oc = fp.getString(ExampleSpringJob.CDISC13OC);
    BigInteger interval = new BigInteger("0");
    if ("monthly".equalsIgnoreCase(period)) {
      interval = new BigInteger("2419200000"); // how many
      // milliseconds in
      // a month? should
      // be 24192000000
    } else if ("weekly".equalsIgnoreCase(period)) {
      interval = new BigInteger("604800000"); // how many
      // milliseconds in
      // a week? should
      // be 6048000000
    } else { // daily
      interval = new BigInteger("86400000"); // how many
      // milliseconds in a
      // day?
    }
    // set up and commit job here

    SimpleTrigger trigger = new SimpleTrigger(jobName, "DEFAULT", 64000, interval.longValue());

    // set the job detail name,
    // based on our choice of format above
    // what if there is more than one detail?
    // what is the number of times it should repeat?
    // arbitrary large number, 64K should be enough :)

    trigger.setDescription(jobDesc);
    // set just the start date
    trigger.setStartTime(startDateTime);
    trigger.setName(jobName); // + datasetId);
    trigger.setGroup("DEFAULT"); // + datasetId);
    trigger.setMisfireInstruction(
        SimpleTrigger.MISFIRE_INSTRUCTION_RESCHEDULE_NEXT_WITH_EXISTING_COUNT);
    // set job data map
    JobDataMap 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(ExampleSpringJob.CDISC12, cdisc12);
    jobDataMap.put(ExampleSpringJob.LOCALE, locale);
    // System.out.println("found 1.2: " +
    // jobDataMap.get(ExampleSpringJob.CDISC12));
    jobDataMap.put(ExampleSpringJob.CDISC13, cdisc13);
    // System.out.println("found 1.3: " +
    // jobDataMap.get(ExampleSpringJob.CDISC13));
    jobDataMap.put(ExampleSpringJob.CDISC13OC, cdisc13oc);
    // System.out.println("found 1.3oc: " +
    // jobDataMap.get(ExampleSpringJob.CDISC13OC));
    jobDataMap.put(SPSS, spss);
    jobDataMap.put(USER_ID, userAccount.getId());
    // StudyDAO studyDAO = new StudyDAO();
    jobDataMap.put(STUDY_ID, study.getId());
    jobDataMap.put(STUDY_NAME, study.getName());
    jobDataMap.put(STUDY_OID, study.getOid());

    trigger.setJobDataMap(jobDataMap);
    // trigger.setRepeatInterval(interval.longValue());
    // System.out.println("default for volatile: " + trigger.isVolatile());
    trigger.setVolatility(false);
    return trigger;
  }
  @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);
      }
    }
  }