private boolean updateStudy2(FormProcessor fp) {

    study.setOldStatus(study.getStatus());
    study.setStatus(Status.get(fp.getInt("statusId")));

    if (StringUtil.isBlank(fp.getString(INPUT_VER_DATE))) {
      study.setProtocolDateVerification(null);
    } else {
      study.setProtocolDateVerification(fp.getDate(INPUT_VER_DATE));
    }

    study.setDatePlannedStart(fp.getDate(INPUT_START_DATE));

    if (StringUtil.isBlank(fp.getString(INPUT_END_DATE))) {
      study.setDatePlannedEnd(null);
    } else {
      study.setDatePlannedEnd(fp.getDate(INPUT_END_DATE));
    }

    study.setPhase(fp.getString("phase"));

    if (fp.getInt("genetic") == 1) {
      study.setGenetic(true);
    } else {
      study.setGenetic(false);
    }

    String interventional = resadmin.getString("interventional");
    return interventional.equalsIgnoreCase(study.getProtocolType());
  }
  private void validateStudy2(FormProcessor fp, Validator v) {

    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(INPUT_VER_DATE))) {
      v.addValidation(INPUT_VER_DATE, Validator.IS_A_DATE);
    }

    errors = v.validate();
    logger.info("has validation errors");
    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_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));
    }
    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));
    }
    updateStudy2(fp);
    setPresetValues(fp.getPresetValues());
  }
  private void updateStudy3(boolean isInterventional, FormProcessor fp) {

    study.setPurpose(fp.getString("purpose"));
    ArrayList interventionArray = new ArrayList();
    if (isInterventional) {
      study.setAllocation(fp.getString("allocation"));
      study.setMasking(fp.getString("masking"));
      study.setControl(fp.getString("control"));
      study.setAssignment(fp.getString("assignment"));
      study.setEndpoint(fp.getString("endpoint"));

      StringBuffer interventions = new StringBuffer();

      for (int i = 0; i < 10; i++) {
        String type = fp.getString("interType" + i);
        String name = fp.getString("interName" + i);
        if (!StringUtil.isBlank(type) && !StringUtil.isBlank(name)) {
          InterventionBean ib =
              new InterventionBean(fp.getString("interType" + i), fp.getString("interName" + i));
          interventionArray.add(ib);
          interventions.append(ib.toString()).append(",");
        }
      }
      study.setInterventions(interventions.toString());

    } else { // type = observational
      study.setDuration(fp.getString("duration"));
      study.setSelection(fp.getString("selection"));
      study.setTiming(fp.getString("timing"));
    }
    request.setAttribute("interventions", interventionArray);
  }
  /**
   * Updates the study bean with inputs from second section
   *
   * @param request
   * @return true if study type is Interventional, otherwise false
   */
  private boolean updateStudy2() {
    FormProcessor fp = new FormProcessor(request);
    StudyBean newStudy = (StudyBean) session.getAttribute("newStudy");
    // this is not fully supported yet, because the system will not handle
    // studies which are pending
    // or private...
    newStudy.setStatus(Status.get(fp.getInt("statusId")));

    newStudy.setProtocolDateVerification(fp.getDate(INPUT_VER_DATE));

    newStudy.setDatePlannedStart(fp.getDate(INPUT_START_DATE));

    if (StringUtil.isBlank(fp.getString(INPUT_END_DATE))) {
      newStudy.setDatePlannedEnd(null);
    } else {
      newStudy.setDatePlannedEnd(fp.getDate(INPUT_END_DATE));
    }

    newStudy.setPhase(fp.getString("phase"));

    if (fp.getInt("genetic") == 1) {
      newStudy.setGenetic(true);
    } else {
      newStudy.setGenetic(false);
    }

    session.setAttribute("newStudy", newStudy);

    String interventional = resadmin.getString("interventional");
    return interventional.equalsIgnoreCase(newStudy.getProtocolType());
  }
  @Override
  protected DisplayItemBean validateCalcTypeDisplayItemBean(
      ScoreItemValidator sv, DisplayItemBean dib, String inputName, HttpServletRequest request) {

    org.akaza.openclinica.bean.core.ResponseType rt =
        dib.getMetadata().getResponseSet().getResponseType();
    ItemDataDAO iddao = new ItemDataDAO(getDataSource());
    boolean isSingleItem = false;
    HttpSession session = request.getSession();
    if (StringUtil.isBlank(inputName)) { // for single items
      inputName = getInputName(dib);
      isSingleItem = true;
    }
    EventCRFBean ecb = (EventCRFBean) request.getAttribute(INPUT_EVENT_CRF);

    // we only give warning to user if data entered in DDE is different from
    // IDE when the first
    // time user hits 'save'
    int keyId = ecb.getId();
    Integer validationCount = (Integer) session.getAttribute(COUNT_VALIDATE + keyId);

    ItemDataBean valueToCompare = new ItemDataBean();
    if (isSingleItem) {
      int idId = dib.getData().getId();
      if (idId > 0) {
        valueToCompare = (ItemDataBean) iddao.findByPK(idId);
      }
    } else {
      valueToCompare = dib.getDbData();
    }
    if (rt.equals(org.akaza.openclinica.bean.core.ResponseType.CALCULATION)
        || rt.equals(org.akaza.openclinica.bean.core.ResponseType.GROUP_CALCULATION)) {
      boolean showOriginalItem =
          getItemMetadataService().isShown(dib.getItem().getId(), ecb, valueToCompare);
      boolean showItem = dib.getMetadata().isShowItem();
      boolean showDuplicateItem =
          getItemMetadataService()
              .hasPassedDDE(
                  dib.getMetadata(),
                  ecb,
                  valueToCompare); // .isShown(dib.getItem().getId(), ecb, dib.getDbData());
      if (showOriginalItem && showDuplicateItem || showItem) {
        dib = validateDisplayItemBeanText(sv, dib, inputName, request);
      }
      if (showOriginalItem && showDuplicateItem || showItem) {
        sv.addValidation(
            inputName, Validator.MATCHES_INITIAL_DATA_ENTRY_VALUE, valueToCompare, false);
        sv.setErrorMessage(
            respage.getString("value_you_specified")
                + " "
                + valueToCompare.getValue()
                + " "
                + respage.getString("from_initial_data_entry"));
      }
    }

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

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

          addPageMessage("Your job has been successfully modified.");
          forwardPage(Page.VIEW_IMPORT_JOB_SERVLET);
        } catch (SchedulerException se) {
          se.printStackTrace();
          // set a message here with the exception message
          setUpServlet(trigger);
          addPageMessage(
              "There was an unspecified error with your creation, please contact an administrator.");
          forwardPage(Page.UPDATE_JOB_IMPORT);
        }
      }
    }
  }
 /*
  * (non-Javadoc)
  *
  * @see
  * org.akaza.openclinica.control.submit.DataEntryServlet#getServletPage()
  */
 @Override
 protected Page getServletPage() {
   String tabId = fp.getString("tab", true);
   String sectionId = fp.getString(DataEntryServlet.INPUT_SECTION_ID, true);
   String eventCRFId = fp.getString(INPUT_EVENT_CRF_ID, true);
   if (StringUtil.isBlank(sectionId) || StringUtil.isBlank(tabId)) {
     return Page.DOUBLE_DATA_ENTRY_SERVLET;
   } else {
     Page target = Page.DOUBLE_DATA_ENTRY_SERVLET;
     target.setFileName(
         target.getFileName()
             + "?eventCRFId="
             + eventCRFId
             + "&sectionId="
             + sectionId
             + "&tab="
             + tabId);
     return target;
   }
 }
  /**
   * Confirms the third input block of study info
   *
   * @throws Exception
   */
  private void confirmStudy3(boolean isInterventional) throws Exception {
    Validator v = new Validator(request);
    FormProcessor fp = new FormProcessor(request);

    v.addValidation("purpose", Validator.NO_BLANKS);
    for (int i = 0; i < 10; i++) {
      String type = fp.getString("interType" + i);
      String name = fp.getString("interName" + i);
      if (!StringUtil.isBlank(type) && StringUtil.isBlank(name)) {
        v.addValidation("interName", Validator.NO_BLANKS);
        request.setAttribute(
            "interventionError", respage.getString("name_cannot_be_blank_if_type"));
        break;
      }
      if (!StringUtil.isBlank(name) && StringUtil.isBlank(type)) {
        v.addValidation("interType", Validator.NO_BLANKS);
        request.setAttribute(
            "interventionError", respage.getString("name_cannot_be_blank_if_name"));
        break;
      }
    }

    errors = v.validate();
    updateStudy3(isInterventional);

    if (errors.isEmpty()) {
      logger.info("no errors");
      request.setAttribute("interventions", session.getAttribute("interventions"));
      forwardPage(Page.UPDATE_STUDY5);

    } else {
      logger.info("has validation errors");
      request.setAttribute("formMessages", errors);
      setMaps(isInterventional, (ArrayList) session.getAttribute("interventions"));
      if (isInterventional) {
        forwardPage(Page.UPDATE_STUDY3);
      } else {
        forwardPage(Page.UPDATE_STUDY4);
      }
    }
  }
  private void validateStudy3(boolean isInterventional, Validator v, FormProcessor fp) {

    v.addValidation("purpose", Validator.NO_BLANKS);
    for (int i = 0; i < 10; i++) {
      String type = fp.getString("interType" + i);
      String name = fp.getString("interName" + i);
      if (!StringUtil.isBlank(type) && StringUtil.isBlank(name)) {
        v.addValidation("interName", Validator.NO_BLANKS);
        request.setAttribute(
            "interventionError", respage.getString("name_cannot_be_blank_if_type"));
        break;
      }
      if (!StringUtil.isBlank(name) && StringUtil.isBlank(type)) {
        v.addValidation("interType", Validator.NO_BLANKS);
        request.setAttribute(
            "interventionError", respage.getString("name_cannot_be_blank_if_name"));
        break;
      }
    }
    updateStudy3(isInterventional, fp);
  }
  private void confirmStudy2() throws Exception {
    Validator v = new Validator(request);
    FormProcessor fp = new FormProcessor(request);

    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);
    }
    v.addValidation(INPUT_VER_DATE, Validator.IS_A_DATE);

    errors = v.validate();
    boolean isInterventional = updateStudy2();

    if (errors.isEmpty()) {
      logger.info("no errors");
      ArrayList interventionArray = new ArrayList();
      if (isInterventional) {
        interventionArray = parseInterventions((StudyBean) session.getAttribute("newStudy"));
        setMaps(isInterventional, interventionArray);
        forwardPage(Page.UPDATE_STUDY3);
      } else {
        setMaps(isInterventional, interventionArray);
        forwardPage(Page.UPDATE_STUDY4);
      }

    } else {
      logger.info("has validation errors");
      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_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));
      }
      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));
      }
      setPresetValues(fp.getPresetValues());
      request.setAttribute("formMessages", errors);
      request.setAttribute("studyPhaseMap", CreateStudyServlet.studyPhaseMap);
      request.setAttribute("statuses", Status.toActiveArrayList());
      forwardPage(Page.UPDATE_STUDY2);
    }
  }
 /**
  * Parses the intetventions of a study and divides it into different type and name pairs type and
  * name are separated by '/', and interventions are separated by ',' examples:
  * type1/name1,type2/name2,type3/name3,
  *
  * @param sb
  * @return
  */
 private ArrayList parseInterventions(StudyBean sb) {
   ArrayList inters = new ArrayList();
   String interventions = sb.getInterventions();
   try {
     if (!StringUtil.isBlank(interventions)) {
       StringTokenizer st = new StringTokenizer(interventions, ",");
       while (st.hasMoreTokens()) {
         String s = st.nextToken();
         StringTokenizer st1 = new StringTokenizer(s, "/");
         String type = st1.nextToken();
         String name = st1.nextToken();
         InterventionBean ib = new InterventionBean(type, name);
         inters.add(ib);
       }
     }
   } catch (NoSuchElementException nse) {
     return new ArrayList();
   }
   return inters;
 }
  @Override
  protected DisplayItemBean validateDisplayItemBean(
      DiscrepancyValidator v,
      DisplayItemBean dib,
      String inputName,
      RuleValidator rv,
      HashMap<String, ArrayList<String>> groupOrdinalPLusItemOid,
      Boolean fireRuleValidation,
      ArrayList<String> messages,
      HttpServletRequest request) {

    org.akaza.openclinica.bean.core.ResponseType rt =
        dib.getMetadata().getResponseSet().getResponseType();
    EventCRFBean ecb = (EventCRFBean) request.getAttribute(INPUT_EVENT_CRF);

    boolean isSingleItem = false;
    if (StringUtil.isBlank(inputName)) { // for single items
      inputName = getInputName(dib);
      isSingleItem = true;
    }
    // we only give warning to user if data entered in DDE is different from
    // IDE when the first
    // time user hits 'save'
    int keyId = ecb.getId();
    Integer validationCount = (Integer) request.getSession().getAttribute(COUNT_VALIDATE + keyId);

    ItemDataBean valueToCompare = dib.getData();
    if (!isSingleItem) {
      valueToCompare = dib.getDbData();
    }

    if (isSingleItem) {
      dib = loadFormValue(dib, request);
    }
    if (groupOrdinalPLusItemOid.containsKey(dib.getItem().getOid()) || fireRuleValidation) {
      messages = messages == null ? groupOrdinalPLusItemOid.get(dib.getItem().getOid()) : messages;
      dib = validateDisplayItemBeanSingleCV(rv, dib, inputName, messages);
    }

    return dib;
  }
  @Override
  protected DisplayItemBean validateDisplayItemBean(
      DiscrepancyValidator v, DisplayItemBean dib, String inputName) {

    org.akaza.openclinica.bean.core.ResponseType rt =
        dib.getMetadata().getResponseSet().getResponseType();

    boolean isSingleItem = false;
    if (StringUtil.isBlank(inputName)) { // for single items
      inputName = getInputName(dib);
      isSingleItem = true;
    }
    // we only give warning to user if data entered in DDE is different from
    // IDE when the first
    // time user hits 'save'
    int keyId = ecb.getId();
    Integer validationCount = (Integer) session.getAttribute(COUNT_VALIDATE + keyId);

    ItemDataBean valueToCompare = dib.getData();
    if (!isSingleItem) {
      valueToCompare = dib.getDbData();
    }
    boolean showOriginalItem =
        getItemMetadataService()
            .isShown(dib.getItem().getId(), ecb, valueToCompare); // was dib.getData()
    boolean showItem = dib.getMetadata().isShowItem();
    boolean showDuplicateItem =
        getItemMetadataService()
            .hasPassedDDE(
                dib.getMetadata(),
                ecb,
                valueToCompare); // .isShown(dib.getItem().getId(), ecb, dib.getDbData());// where
    // is the set db data?
    logger.debug(
        "*** show original item has value "
            + dib.getData().getValue()
            + " and show item has value "
            + valueToCompare.getValue());
    logger.debug(
        "--- show original: "
            + showOriginalItem
            + " show duplicate: "
            + showDuplicateItem
            + " and just show item: "
            + showItem);
    logger.debug("VALIDATION COUNT " + validationCount);
    if (showOriginalItem && showDuplicateItem || showItem) {
      // it should either be shown already, OR shown in the database?
      // logger.debug("=== we passed, adding validation here");
      Integer indValidationCount =
          (Integer) session.getAttribute(COUNT_VALIDATE + keyId + dib.getMetadata().getId());
      if (rt.equals(org.akaza.openclinica.bean.core.ResponseType.TEXT)
          || rt.equals(org.akaza.openclinica.bean.core.ResponseType.TEXTAREA)
          || rt.equals(org.akaza.openclinica.bean.core.ResponseType.FILE)) {
        dib = validateDisplayItemBeanText(v, dib, inputName);
        // necessary?
        // if (indValidationCount == null || validationCount == null || validationCount.intValue()
        // == 0) {
        logger.debug("=== we passed, adding validation here TEXT " + valueToCompare.getId());
        v.addValidation(
            inputName, Validator.MATCHES_INITIAL_DATA_ENTRY_VALUE, valueToCompare, false);
        v.setErrorMessage(
            respage.getString("value_you_specified")
                + " "
                + valueToCompare.getValue()
                + " "
                + respage.getString("from_initial_data_entry"));
        // session.setAttribute(COUNT_VALIDATE + keyId + dib.getMetadata().getId(), new Integer(1));
        // }

      } else if (rt.equals(org.akaza.openclinica.bean.core.ResponseType.RADIO)
          || rt.equals(org.akaza.openclinica.bean.core.ResponseType.SELECT)) {
        dib = validateDisplayItemBeanSingleCV(v, dib, inputName);
        // ItemFormMetadataBean ifmdb = dib.getMetadata();
        // ResponseSetBean rsBean = ifmdb.getResponseSet();
        // logger.info("### found a response set count of "+inputName+"
        // "+rsBean.getOptions().size());
        // TODO sees it at this end tbh 1878
        // if (indValidationCount == null || validationCount == null || validationCount.intValue()
        // == 0) {
        logger.debug("=== we passed, adding validation here RADIO " + valueToCompare.getId());
        v.addValidation(
            inputName, Validator.MATCHES_INITIAL_DATA_ENTRY_VALUE, valueToCompare, false);
        String errorValue = valueToCompare.getValue();

        java.util.ArrayList options = dib.getMetadata().getResponseSet().getOptions();

        for (int u = 0; u < options.size(); u++) {
          ResponseOptionBean rob = (ResponseOptionBean) options.get(u);
          if (rob.getValue().equals(errorValue)) {
            errorValue = rob.getText();
          }
        }
        v.setErrorMessage(
            respage.getString("value_you_specified")
                + " "
                + errorValue
                + " "
                + respage.getString("from_initial_data_entry"));
        // session.setAttribute(COUNT_VALIDATE + keyId + dib.getMetadata().getId(), new Integer(1));
        // }
      } else if (rt.equals(org.akaza.openclinica.bean.core.ResponseType.CHECKBOX)
          || rt.equals(org.akaza.openclinica.bean.core.ResponseType.SELECTMULTI)) {
        dib = validateDisplayItemBeanMultipleCV(v, dib, inputName);
        // if (indValidationCount == null || validationCount == null || validationCount.intValue()
        // == 0) {
        logger.debug("=== we passed, adding validation here CHECKBOX " + valueToCompare.getId());
        v.addValidation(
            inputName, Validator.MATCHES_INITIAL_DATA_ENTRY_VALUE, valueToCompare, true);
        // repeated from above, tbh 112007
        String errorValue = valueToCompare.getValue();
        String errorTexts = "";

        java.util.ArrayList options = dib.getMetadata().getResponseSet().getOptions();

        for (int u = 0; u < options.size(); u++) {
          ResponseOptionBean rob = (ResponseOptionBean) options.get(u);
          if (errorValue.contains(rob.getValue())) {
            errorTexts = errorTexts + rob.getText();
            if (u < options.size() - 1) {
              // the values for multi-select are seperated by
              // comma
              errorTexts = errorTexts + ", ";
            }
          }
        }
        v.setErrorMessage(
            respage.getString("value_you_specified")
                + " "
                + errorTexts
                + " "
                + respage.getString("from_initial_data_entry"));
        // session.setAttribute(COUNT_VALIDATE + keyId + dib.getMetadata().getId(), new Integer(1));
        // }
      }
    }
    // only load form value when an item is not in a group,
    // if in group, the value is already loaded
    // see formGroups = loadFormValueForItemGroup(digb,digbs,formGroups);
    if (isSingleItem) {
      dib = loadFormValue(dib);
    }

    return dib;
  }
  @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);
      }
    }
  }
  @Override
  public void processRequest() throws Exception {
    resetPanel();
    panel.setStudyInfoShown(false);
    panel.setOrderedData(true);
    panel.setExtractData(false);
    panel.setSubmitDataModule(false);
    panel.setCreateDataset(false);
    panel.setIconInfoShown(true);
    panel.setManageSubject(false);

    StudyDAO sdao = new StudyDAO(sm.getDataSource());
    StudyBean study = (StudyBean) session.getAttribute("newStudy");

    if (study == null) {
      addPageMessage(respage.getString("please_choose_a_study_to_edit"));
      forwardPage(Page.STUDY_LIST_SERVLET);
      return;
    }

    // whether the study is interventional
    String interventional = resadmin.getString("interventional");
    boolean isInterventional = interventional.equalsIgnoreCase(study.getProtocolType());

    String action = request.getParameter("action");

    if (StringUtil.isBlank(action)) {
      // request.setAttribute("facRecruitStatusMap",
      // CreateStudyServlet.facRecruitStatusMap);
      request.setAttribute("statuses", Status.toActiveArrayList());
      forwardPage(Page.UPDATE_STUDY1);
    } else {
      if ("confirm".equalsIgnoreCase(action)) {
        confirmWholeStudy();

      } else if ("submit".equalsIgnoreCase(action)) {
        submitStudy();
        addPageMessage(respage.getString("the_study_has_been_updated_succesfully"));
        forwardPage(Page.STUDY_LIST_SERVLET);

      } else if ("next".equalsIgnoreCase(action)) {
        Integer pageNumber = Integer.valueOf(request.getParameter("pageNum"));
        if (pageNumber != null) {
          if (pageNumber.intValue() == 6) {
            confirmStudy6();
          } else if (pageNumber.intValue() == 5) {
            confirmStudy5();
          } else if (pageNumber.intValue() == 4) {
            confirmStudy4();
          } else if (pageNumber.intValue() == 3) {
            confirmStudy3(isInterventional);
          } else if (pageNumber.intValue() == 2) {
            confirmStudy2();
          } else {
            logger.info("confirm study 1" + pageNumber.intValue());
            confirmStudy1();
          }
        } else {
          session.setAttribute("newStudy", study);
          // request.setAttribute("facRecruitStatusMap",
          // CreateStudyServlet.facRecruitStatusMap);
          // request.setAttribute("statuses",
          // Status.toActiveArrayList());
          forwardPage(Page.UPDATE_STUDY1);
        }
      }
    }
  }
  /**
   * Validates the forth section of study and save it into study bean
   *
   * @param request
   * @param response
   * @throws Exception
   */
  private void confirmStudy5() throws Exception {
    FormProcessor fp = new FormProcessor(request);
    Validator v = new Validator(request);
    if (!StringUtil.isBlank(fp.getString("facConEmail"))) {
      v.addValidation("facConEmail", Validator.IS_A_EMAIL);
    }
    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();

    StudyBean newStudy = (StudyBean) session.getAttribute("newStudy");

    newStudy.setFacilityCity(fp.getString("facCity"));
    newStudy.setFacilityContactDegree(fp.getString("facConDrgree"));
    newStudy.setFacilityName(fp.getString("facName"));
    newStudy.setFacilityContactEmail(fp.getString("facConEmail"));
    newStudy.setFacilityContactPhone(fp.getString("facConPhone"));
    newStudy.setFacilityContactName(fp.getString("facConName"));
    newStudy.setFacilityCountry(fp.getString("facCountry"));
    newStudy.setFacilityContactDegree(fp.getString("facConDegree"));
    // newStudy.setFacilityRecruitmentStatus(fp.getString("facRecStatus"));
    newStudy.setFacilityState(fp.getString("facState"));
    newStudy.setFacilityZip(fp.getString("facZip"));

    session.setAttribute("newStudy", newStudy);
    if (errors.isEmpty()) {
      forwardPage(Page.UPDATE_STUDY7);
    } else {
      request.setAttribute("formMessages", errors);
      request.setAttribute("facRecruitStatusMap", CreateStudyServlet.facRecruitStatusMap);
      forwardPage(Page.UPDATE_STUDY6);
    }
  }
  @Override
  protected void processRequest() throws Exception {
    checkStudyLocked(Page.LIST_STUDY_SUBJECTS, respage.getString("current_study_locked"));
    panel.setStudyInfoShown(false);
    fp = new FormProcessor(request);
    FormDiscrepancyNotes discNotes = null;
    int studySubjectId = fp.getInt(INPUT_STUDY_SUBJECT_ID_FROM_VIEWSUBJECT);
    // input from manage subject matrix, user has specified definition id
    int studyEventDefinitionId = fp.getInt(INPUT_STUDY_EVENT_DEFINITION);

    // TODO: make this sensitive to permissions
    StudySubjectDAO sdao = new StudySubjectDAO(sm.getDataSource());
    StudySubjectBean ssb;
    if (studySubjectId <= 0) {
      ssb = (StudySubjectBean) request.getAttribute(INPUT_STUDY_SUBJECT);
    } else {
      // YW 11-08-2007, << a new study event could not be added if its
      // study subject has been removed
      ssb = (StudySubjectBean) sdao.findByPK(studySubjectId);
      Status s = ssb.getStatus();
      if ("removed".equalsIgnoreCase(s.getName()) || "auto-removed".equalsIgnoreCase(s.getName())) {
        addPageMessage(
            resword.getString("study_event")
                + resterm.getString("could_not_be")
                + resterm.getString("added")
                + "."
                + respage.getString("study_subject_has_been_deleted"));
        request.setAttribute("id", new Integer(studySubjectId).toString());
        forwardPage(Page.VIEW_STUDY_SUBJECT_SERVLET);
      }
      // YW >>
      request.setAttribute(INPUT_REQUEST_STUDY_SUBJECT, "no");
    }

    // running this crashes the server, or so we think...instead, let's grab a count
    // or remove it altogether tbh 10/2009
    // ArrayList subjects = sdao.findAllActiveByStudyOrderByLabel(currentStudy);

    // TODO: make this sensitive to permissions
    StudyEventDefinitionDAO seddao = new StudyEventDefinitionDAO(sm.getDataSource());

    StudyBean studyWithEventDefinitions = currentStudy;
    if (currentStudy.getParentStudyId() > 0) {
      studyWithEventDefinitions = new StudyBean();
      studyWithEventDefinitions.setId(currentStudy.getParentStudyId());
    }
    // find all active definitions with CRFs
    ArrayList eventDefinitions = seddao.findAllActiveByStudy(studyWithEventDefinitions);
    // EventDefinitionCRFDAO edcdao = new
    // EventDefinitionCRFDAO(sm.getDataSource());
    // ArrayList definitionsWithCRF = new ArrayList();
    // for (int i=0; i<eventDefinitions.size(); i++) {
    // StudyEventDefinitionBean sed =
    // (StudyEventDefinitionBean)eventDefinitions.get(i);
    // logger.info("StudyEventDefinition name[" + sed.getName() + "]");
    // ArrayList edcs = edcdao.findAllByEventDefinitionId(sed.getId());
    // if (!edcs.isEmpty()) {
    // definitionsWithCRF.add(sed);
    // }
    // }

    // Collections.sort(definitionsWithCRF);
    Collections.sort(eventDefinitions);

    /*
     * ArrayList eventDefinitionsScheduled = new ArrayList(); for (int i =
     * 0; i < eventDefinitions.size(); i++) { StudyEventDefinitionBean sed =
     * (StudyEventDefinitionBean) eventDefinitions.get(i); if
     * (sed.getType().equalsIgnoreCase("scheduled")) {
     * eventDefinitionsScheduled.add(sed); } }
     */
    // all definitions will appear in scheduled event creation box-11/26/05
    ArrayList eventDefinitionsScheduled = eventDefinitions;

    if (!fp.isSubmitted()) {
      // StudyEventDAO sed = new StudyEventDAO(sm.getDataSource());
      // sed.updateSampleOrdinals_v092();

      HashMap presetValues = new HashMap();

      // YW 08-16-2007 << set default as blank for time
      presetValues.put(INPUT_STARTDATE_PREFIX + "Hour", new Integer(-1));
      presetValues.put(INPUT_STARTDATE_PREFIX + "Minute", new Integer(-1));
      presetValues.put(INPUT_STARTDATE_PREFIX + "Half", new String(""));
      presetValues.put(INPUT_ENDDATE_PREFIX + "Hour", new Integer(-1));
      presetValues.put(INPUT_ENDDATE_PREFIX + "Minute", new Integer(-1));
      presetValues.put(INPUT_ENDDATE_PREFIX + "Half", new String(""));
      for (int i = 0; i < ADDITIONAL_SCHEDULED_NUM; ++i) {
        presetValues.put(INPUT_STARTDATE_PREFIX_SCHEDULED[i] + "Hour", new Integer(-1));
        presetValues.put(INPUT_STARTDATE_PREFIX_SCHEDULED[i] + "Minute", new Integer(-1));
        presetValues.put(INPUT_STARTDATE_PREFIX_SCHEDULED[i] + "Half", new String(""));
        presetValues.put(INPUT_ENDDATE_PREFIX_SCHEDULED[i] + "Hour", new Integer(-1));
        presetValues.put(INPUT_ENDDATE_PREFIX_SCHEDULED[i] + "Minute", new Integer(-1));
        presetValues.put(INPUT_ENDDATE_PREFIX_SCHEDULED[i] + "Half", new String(""));
      }

      // SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
      // example of taking the above line and transferring to i18n on the
      // below line, tbh
      String dateValue = local_df.format(new Date(System.currentTimeMillis()));
      presetValues.put(INPUT_STARTDATE_PREFIX + "Date", dateValue);
      for (int i = 0; i < ADDITIONAL_SCHEDULED_NUM; ++i) {
        presetValues.put(INPUT_STARTDATE_PREFIX_SCHEDULED[i] + "Date", dateValue);
        // location
        presetValues.put(INPUT_SCHEDULED_LOCATION[i], currentStudy.getFacilityCity());
        presetValues.put(this.DISPLAY_SCHEDULED[i], "none");
      }
      presetValues.put(INPUT_LOCATION, currentStudy.getFacilityCity()); // defualt

      if (ssb != null && ssb.isActive()) {
        presetValues.put(INPUT_STUDY_SUBJECT, ssb);

        String requestStudySubject = (String) request.getAttribute(INPUT_REQUEST_STUDY_SUBJECT);
        if (requestStudySubject != null) {
          presetValues.put(INPUT_REQUEST_STUDY_SUBJECT, requestStudySubject);

          dateValue = local_df.format(new Date());
          presetValues.put(INPUT_STARTDATE_PREFIX + "Date", dateValue);
        }
      }

      if (studyEventDefinitionId > 0) {
        StudyEventDefinitionBean sed =
            (StudyEventDefinitionBean) seddao.findByPK(studyEventDefinitionId);
        presetValues.put(INPUT_STUDY_EVENT_DEFINITION, sed);
      }

      // tbh
      logger.info("set preset values: " + presetValues.toString());
      System.out.println("set preset values: " + presetValues.toString());
      logger.info("found def.w.CRF list, size " + eventDefinitions.size());
      // tbh
      setPresetValues(presetValues);

      ArrayList subjects = new ArrayList();
      setupBeans(subjects, eventDefinitions);

      discNotes = new FormDiscrepancyNotes();
      session.setAttribute(AddNewSubjectServlet.FORM_DISCREPANCY_NOTES_NAME, discNotes);

      request.setAttribute("eventDefinitionsScheduled", eventDefinitionsScheduled);
      setInputMessages(new HashMap());
      forwardPage(Page.CREATE_NEW_STUDY_EVENT);
    } else {
      // tbh
      // String dateCheck = (String)request.getAttribute("startDate");
      // String endCheck = (String)request.getAttribute("endDate");
      // logger.info(dateCheck+"; "+endCheck);

      String dateCheck2 = request.getParameter("startDate");
      String endCheck2 = request.getParameter("endDate");
      logger.info(dateCheck2 + "; " + endCheck2);

      // YW, 3-12-2008, 2220 fix <<
      String strEnd = fp.getDateTimeInputString(INPUT_ENDDATE_PREFIX);
      String strEndScheduled[] = new String[ADDITIONAL_SCHEDULED_NUM];
      for (int i = 0; i < ADDITIONAL_SCHEDULED_NUM; ++i) {
        strEndScheduled[i] = fp.getDateTimeInputString(INPUT_ENDDATE_PREFIX_SCHEDULED[i]);
      }
      Date start = getInputStartDate();
      Date end = null;
      Date[] startScheduled = new Date[ADDITIONAL_SCHEDULED_NUM];
      for (int i = 0; i < ADDITIONAL_SCHEDULED_NUM; ++i) {
        startScheduled[i] = getInputStartDateScheduled(i);
      }
      Date[] endScheduled = new Date[ADDITIONAL_SCHEDULED_NUM];

      // YW >>

      // for (java.util.Enumeration enu = request.getAttributeNames();
      // enu.hasMoreElements() ;) {
      // logger.info(">>> found "+enu.nextElement().toString());
      // }
      // tbh
      discNotes =
          (FormDiscrepancyNotes)
              session.getAttribute(AddNewSubjectServlet.FORM_DISCREPANCY_NOTES_NAME);
      if (discNotes == null) {
        discNotes = new FormDiscrepancyNotes();
        session.setAttribute(AddNewSubjectServlet.FORM_DISCREPANCY_NOTES_NAME, discNotes);
      }
      DiscrepancyValidator v = new DiscrepancyValidator(request, discNotes);

      v.addValidation(INPUT_STARTDATE_PREFIX, Validator.IS_DATE_TIME);
      v.alwaysExecuteLastValidation(INPUT_STARTDATE_PREFIX);
      if (!strEnd.equals("")) {
        v.addValidation(INPUT_ENDDATE_PREFIX, Validator.IS_DATE_TIME);
        v.alwaysExecuteLastValidation(INPUT_ENDDATE_PREFIX);
      }

      v.addValidation(
          INPUT_STUDY_EVENT_DEFINITION,
          Validator.ENTITY_EXISTS_IN_STUDY,
          seddao,
          studyWithEventDefinitions);
      // v.addValidation(INPUT_STUDY_SUBJECT, Validator.ENTITY_EXISTS_IN_STUDY, sdao, currentStudy);
      // removed tbh 11/2009
      v.addValidation(INPUT_LOCATION, Validator.NO_BLANKS);
      v.addValidation(INPUT_STUDY_SUBJECT_LABEL, Validator.NO_BLANKS);
      v.addValidation(
          INPUT_LOCATION,
          Validator.LENGTH_NUMERIC_COMPARISON,
          NumericComparisonOperator.LESS_THAN_OR_EQUAL_TO,
          2000);
      v.alwaysExecuteLastValidation(INPUT_LOCATION);

      boolean hasScheduledEvent = false;
      for (int i = 0; i < ADDITIONAL_SCHEDULED_NUM; ++i) {
        if (!StringUtil.isBlank(fp.getString(this.INPUT_STUDY_EVENT_DEFINITION_SCHEDULED[i]))) {
          // logger.info("has scheduled definition******");
          v.addValidation(
              this.INPUT_STUDY_EVENT_DEFINITION_SCHEDULED[i],
              Validator.ENTITY_EXISTS_IN_STUDY,
              seddao,
              studyWithEventDefinitions);
          v.addValidation(INPUT_SCHEDULED_LOCATION[i], Validator.NO_BLANKS);
          v.addValidation(
              INPUT_SCHEDULED_LOCATION[i],
              Validator.LENGTH_NUMERIC_COMPARISON,
              NumericComparisonOperator.LESS_THAN_OR_EQUAL_TO,
              2000);
          v.alwaysExecuteLastValidation(INPUT_SCHEDULED_LOCATION[i]);
          v.addValidation(INPUT_STARTDATE_PREFIX_SCHEDULED[i], Validator.IS_DATE_TIME);
          v.alwaysExecuteLastValidation(INPUT_STARTDATE_PREFIX_SCHEDULED[i]);
          if (!strEndScheduled[i].equals("")) {
            v.addValidation(INPUT_ENDDATE_PREFIX_SCHEDULED[i], Validator.IS_DATE_TIME);
            v.alwaysExecuteLastValidation(INPUT_ENDDATE_PREFIX_SCHEDULED[i]);
          }
          hasScheduledEvent = true;
          fp.addPresetValue(DISPLAY_SCHEDULED[i], "all");
        } else {
          fp.addPresetValue(DISPLAY_SCHEDULED[i], "none");
        }
      }

      HashMap errors = v.validate();
      // logger.info("v is not null *****");
      String location = resword.getString("location");
      // don't allow user to use the default value 'Location' since
      // location
      // is a required field
      if (!StringUtil.isBlank(fp.getString(INPUT_LOCATION))
          && fp.getString(INPUT_LOCATION).equalsIgnoreCase(location)) {
        Validator.addError(errors, INPUT_LOCATION, restext.getString("not_a_valid_location"));
      }

      StudyEventDefinitionBean definition =
          (StudyEventDefinitionBean) seddao.findByPK(fp.getInt(INPUT_STUDY_EVENT_DEFINITION));

      // StudySubjectBean studySubject = (StudySubjectBean)
      // sdao.findByPK(fp.getInt(INPUT_STUDY_SUBJECT));
      // sdao.findByLabelAndStudy(label, study)
      StudySubjectBean studySubject =
          (StudySubjectBean)
              sdao.findByLabelAndStudy(fp.getString(INPUT_STUDY_SUBJECT_LABEL), currentStudy);
      // >> 4358 tbh, 11/2009
      // what if we are sent here from AddNewSubjectServlet.java??? we need to get that study
      // subject bean
      if (request.getAttribute(INPUT_STUDY_SUBJECT) != null) {
        studySubject = (StudySubjectBean) request.getAttribute(INPUT_STUDY_SUBJECT);
      }
      // << tbh
      if (studySubject.getLabel() == "") {
        // add an error here, tbh
        System.out.println("tripped the error here 20091109");
        Validator.addError(
            errors,
            INPUT_STUDY_SUBJECT,
            respage.getString("must_enter_subject_ID_for_identifying"));
      }

      if (!subjectMayReceiveStudyEvent(sm.getDataSource(), definition, studySubject)) {
        Validator.addError(
            errors,
            INPUT_STUDY_EVENT_DEFINITION,
            restext.getString("not_added_since_event_not_repeating"));
      }

      ArrayList<StudyEventDefinitionBean> definitionScheduleds =
          new ArrayList<StudyEventDefinitionBean>();
      int[] scheduledDefinitionIds = new int[ADDITIONAL_SCHEDULED_NUM];
      if (hasScheduledEvent) {
        for (int i = 0; i < ADDITIONAL_SCHEDULED_NUM; ++i) {
          int pk = fp.getInt(INPUT_STUDY_EVENT_DEFINITION_SCHEDULED[i]);
          if (pk > 0) {
            StudyEventDefinitionBean sedb = (StudyEventDefinitionBean) seddao.findByPK(pk);
            System.out.println(
                "scheduled def:"
                    + pk
                    + " "
                    + INPUT_STUDY_EVENT_DEFINITION_SCHEDULED[i]
                    + " "
                    + sedb.getName());
            definitionScheduleds.add(sedb);
            scheduledDefinitionIds[i] = pk;
            if (!subjectMayReceiveStudyEvent(sm.getDataSource(), sedb, studySubject)) {
              Validator.addError(
                  errors,
                  INPUT_STUDY_EVENT_DEFINITION_SCHEDULED[i],
                  restext.getString("not_added_since_event_not_repeating"));
            }
          } else {
            definitionScheduleds.add(new StudyEventDefinitionBean());
          }
        }
      }

      // YW, 3-12-2008, 2220 fix >>
      if (!"".equals(strEnd)
          && !errors.containsKey(INPUT_STARTDATE_PREFIX)
          && !errors.containsKey(INPUT_ENDDATE_PREFIX)) {
        end = getInputEndDate();
        if (!fp.getString(INPUT_STARTDATE_PREFIX + "Date")
            .equals(fp.getString(INPUT_ENDDATE_PREFIX + "Date"))) {
          if (end.before(start)) {
            Validator.addError(
                errors,
                INPUT_ENDDATE_PREFIX,
                resexception.getString("input_provided_not_occure_after_previous_start_date_time"));
          }
        } else {
          // if in same date, only check when both had time entered
          if (fp.timeEntered(INPUT_STARTDATE_PREFIX) && fp.timeEntered(INPUT_ENDDATE_PREFIX)) {
            if (end.before(start) || end.equals(start)) {
              Validator.addError(
                  errors,
                  INPUT_ENDDATE_PREFIX,
                  resexception.getString(
                      "input_provided_not_occure_after_previous_start_date_time"));
            }
          }
        }
      }

      String prevStartPrefix = INPUT_STARTDATE_PREFIX;
      Set<Integer> pickedSeds = new TreeSet<Integer>();
      pickedSeds.add(studyEventDefinitionId);
      HashMap<Integer, Integer> scheduledSeds = new HashMap<Integer, Integer>();
      scheduledSeds.put(studyEventDefinitionId, -1);
      for (int i = 0; i < ADDITIONAL_SCHEDULED_NUM; ++i) {
        if (scheduledDefinitionIds[i] > 0
            && !errors.containsKey(INPUT_STARTDATE_PREFIX_SCHEDULED[i])
            && !errors.containsKey(INPUT_ENDDATE_PREFIX_SCHEDULED[i])) {
          if (scheduledSeds.containsKey(scheduledDefinitionIds[i])) {
            int prevStart = scheduledSeds.get(scheduledDefinitionIds[i]);
            prevStartPrefix =
                prevStart == -1
                    ? INPUT_STARTDATE_PREFIX
                    : INPUT_STARTDATE_PREFIX_SCHEDULED[prevStart];
            Date prevStartDate =
                prevStart == -1
                    ? this.getInputStartDate()
                    : this.getInputStartDateScheduled(
                        Integer.parseInt(
                            prevStartPrefix.charAt(prevStartPrefix.length() - 1) + ""));
            if (fp.getString(INPUT_STARTDATE_PREFIX_SCHEDULED[i] + "Date")
                .equals(fp.getString(prevStartPrefix + "Date"))) {
              // if in same day, only check when both have time
              // inputs.
              boolean schStartTime = fp.timeEntered(INPUT_STARTDATE_PREFIX_SCHEDULED[i]);
              boolean startTime = fp.timeEntered(prevStartPrefix);
              if (schStartTime && startTime) {
                if (startScheduled[i].before(prevStartDate)) {
                  Validator.addError(
                      errors,
                      INPUT_STARTDATE_PREFIX_SCHEDULED[i],
                      resexception.getString(
                          "input_provided_not_occure_after_previous_start_date_time"));
                }
              }
            } else {
              if (startScheduled[i].before(prevStartDate)) {
                Validator.addError(
                    errors,
                    INPUT_STARTDATE_PREFIX_SCHEDULED[i],
                    resexception.getString(
                        "input_provided_not_occure_after_previous_start_date_time"));
              }
            }
          }
          scheduledSeds.put(scheduledDefinitionIds[i], i);
          if (!strEndScheduled[i].equals("")) {
            endScheduled[i] = fp.getDateTime(INPUT_ENDDATE_PREFIX_SCHEDULED[i]);
            String prevEndPrefix =
                i > 0 ? INPUT_ENDDATE_PREFIX_SCHEDULED[i - 1] : INPUT_ENDDATE_PREFIX;
            if (!fp.getString(INPUT_STARTDATE_PREFIX_SCHEDULED[i] + "Date")
                .equals(fp.getString(prevEndPrefix + "Date"))) {
              if (endScheduled[i].before(startScheduled[i])) {
                Validator.addError(
                    errors,
                    INPUT_ENDDATE_PREFIX_SCHEDULED[i],
                    resexception.getString(
                        "input_provided_not_occure_after_previous_start_date_time"));
              }
            } else {
              // if in same date, only check when both had time
              // entered
              if (fp.timeEntered(INPUT_STARTDATE_PREFIX_SCHEDULED[i])
                  && fp.timeEntered(INPUT_ENDDATE_PREFIX_SCHEDULED[i])) {
                if (endScheduled[i].before(startScheduled[i])
                    || endScheduled[i].equals(startScheduled[i])) {
                  Validator.addError(
                      errors,
                      INPUT_ENDDATE_PREFIX_SCHEDULED[i],
                      resexception.getString(
                          "input_provided_not_occure_after_previous_start_date_time"));
                }
              }
            }
          }
        }
      }
      // YW >>
      System.out.println("we have errors; number of this; " + errors.size());
      if (!errors.isEmpty()) {
        logger.info("we have errors; number of this; " + errors.size());
        System.out.println(
            "found request study subject: " + fp.getString(INPUT_REQUEST_STUDY_SUBJECT));
        addPageMessage(respage.getString("errors_in_submission_see_below"));
        setInputMessages(errors);

        fp.addPresetValue(INPUT_STUDY_EVENT_DEFINITION, definition);
        fp.addPresetValue(INPUT_STUDY_SUBJECT, studySubject);
        fp.addPresetValue(INPUT_STUDY_SUBJECT_LABEL, fp.getString(INPUT_STUDY_SUBJECT_LABEL));
        fp.addPresetValue(INPUT_REQUEST_STUDY_SUBJECT, fp.getString(INPUT_REQUEST_STUDY_SUBJECT));
        fp.addPresetValue(INPUT_LOCATION, fp.getString(INPUT_LOCATION));

        for (int i = 0; i < ADDITIONAL_SCHEDULED_NUM; ++i) {
          fp.addPresetValue(INPUT_SCHEDULED_LOCATION[i], fp.getString(INPUT_SCHEDULED_LOCATION[i]));
        }
        String prefixes[] = new String[2 + 2 * ADDITIONAL_SCHEDULED_NUM];
        prefixes[0] = INPUT_STARTDATE_PREFIX;
        prefixes[1] = INPUT_ENDDATE_PREFIX;
        int b = ADDITIONAL_SCHEDULED_NUM + 2;
        for (int i = 2; i < b; ++i) {
          prefixes[i] = INPUT_STARTDATE_PREFIX_SCHEDULED[i - 2];
        }
        for (int i = b; i < ADDITIONAL_SCHEDULED_NUM + b; ++i) {
          prefixes[i] = INPUT_ENDDATE_PREFIX_SCHEDULED[i - b];
        }
        fp.setCurrentDateTimeValuesAsPreset(prefixes);

        if (hasScheduledEvent) {
          for (int i = 0; i < ADDITIONAL_SCHEDULED_NUM; ++i) {
            fp.addPresetValue(
                INPUT_STUDY_EVENT_DEFINITION_SCHEDULED[i], definitionScheduleds.get(i));
          }
        }

        setPresetValues(fp.getPresetValues());
        ArrayList subjects = new ArrayList();
        setupBeans(subjects, eventDefinitions);
        request.setAttribute("eventDefinitionsScheduled", eventDefinitionsScheduled);
        forwardPage(Page.CREATE_NEW_STUDY_EVENT);
      } else {
        System.out.println("error is empty");
        StudyEventDAO sed = new StudyEventDAO(sm.getDataSource());

        StudyEventBean studyEvent = new StudyEventBean();
        studyEvent.setStudyEventDefinitionId(definition.getId());
        studyEvent.setStudySubjectId(studySubject.getId());

        // YW 08-17-2007 <<
        if ("-1".equals(getInputStartHour())
            && "-1".equals(getInputStartMinute())
            && "".equals(getInputStartHalf())) {
          studyEvent.setStartTimeFlag(false);
        } else {
          studyEvent.setStartTimeFlag(true);
        }
        // YW >>
        studyEvent.setDateStarted(start);
        // comment to find bug 1389, tbh
        logger.info("found start date: " + local_df.format(start));
        Date startScheduled2[] = new Date[ADDITIONAL_SCHEDULED_NUM];
        for (int i = 0; i < ADDITIONAL_SCHEDULED_NUM; ++i) {
          startScheduled2[i] = getInputStartDateScheduled(i);
        }
        // tbh
        // YW, 3-12-2008, 2220 fix <<
        if (!"".equals(strEnd)) {
          // YW >>
          if ("-1".equals(getInputEndHour())
              && "-1".equals(getInputEndMinute())
              && "".equals(getInputEndHalf())) {
            studyEvent.setEndTimeFlag(false);
          } else {
            studyEvent.setEndTimeFlag(true);
          }
          studyEvent.setDateEnded(end);
        }
        studyEvent.setOwner(ub);
        studyEvent.setStatus(Status.AVAILABLE);
        studyEvent.setLocation(fp.getString(INPUT_LOCATION));
        studyEvent.setSubjectEventStatus(SubjectEventStatus.SCHEDULED);

        // ArrayList subjectsExistingEvents =
        // sed.findAllByStudyAndStudySubjectId(currentStudy,
        // studySubject.getId());
        studyEvent.setSampleOrdinal(sed.getMaxSampleOrdinal(definition, studySubject) + 1);

        studyEvent = (StudyEventBean) sed.create(studyEvent);

        if (!studyEvent.isActive()) {
          throw new OpenClinicaException(restext.getString("event_not_created_in_database"), "2");
        }
        addPageMessage(
            restext.getString("X_event_wiht_definition")
                + definition.getName()
                + restext.getString("X_and_subject")
                + studySubject.getName()
                + respage.getString("X_was_created_succesfully"));

        // save discrepancy notes into DB
        FormDiscrepancyNotes fdn =
            (FormDiscrepancyNotes)
                session.getAttribute(AddNewSubjectServlet.FORM_DISCREPANCY_NOTES_NAME);
        DiscrepancyNoteDAO dndao = new DiscrepancyNoteDAO(sm.getDataSource());
        String[] eventFields = {INPUT_LOCATION, INPUT_STARTDATE_PREFIX, INPUT_ENDDATE_PREFIX};
        for (String element : eventFields) {
          AddNewSubjectServlet.saveFieldNotes(
              element, fdn, dndao, studyEvent.getId(), "studyEvent", currentStudy);
        }
        // logger.info("here ok 3333333333333333");
        if (hasScheduledEvent) {
          for (int i = 0; i < ADDITIONAL_SCHEDULED_NUM; ++i) {

            // should only do the following process if user inputs a
            // scheduled event,
            // which is scheduledDefinitionIds[i] > 0
            if (scheduledDefinitionIds[i] > 0) {
              if (subjectMayReceiveStudyEvent(
                  sm.getDataSource(), definitionScheduleds.get(i), studySubject)) {

                StudyEventBean studyEventScheduled = new StudyEventBean();
                studyEventScheduled.setStudyEventDefinitionId(scheduledDefinitionIds[i]);
                studyEventScheduled.setStudySubjectId(studySubject.getId());

                // YW 11-14-2007
                if ("-1".equals(fp.getString(INPUT_STARTDATE_PREFIX_SCHEDULED[i] + "Hour"))
                    && "-1".equals(fp.getString(INPUT_STARTDATE_PREFIX_SCHEDULED[i] + "Minute"))
                    && "".equals(fp.getString(INPUT_STARTDATE_PREFIX_SCHEDULED[i] + "Half"))) {
                  studyEventScheduled.setStartTimeFlag(false);
                } else {
                  studyEventScheduled.setStartTimeFlag(true);
                }
                // YW >>

                studyEventScheduled.setDateStarted(startScheduled[i]);
                // YW, 3-12-2008, 2220 fix<<
                if (!"".equals(strEndScheduled[i])) {
                  endScheduled[i] = fp.getDateTime(INPUT_ENDDATE_PREFIX_SCHEDULED[i]);
                  if ("-1".equals(fp.getString(INPUT_ENDDATE_PREFIX_SCHEDULED[i] + "Hour"))
                      && "-1".equals(fp.getString(INPUT_ENDDATE_PREFIX_SCHEDULED[i] + "Minute"))
                      && "".equals(fp.getString(INPUT_ENDDATE_PREFIX_SCHEDULED[i] + "Half"))) {
                    studyEventScheduled.setEndTimeFlag(false);
                  } else {
                    studyEventScheduled.setEndTimeFlag(true);
                  }
                }
                studyEventScheduled.setDateEnded(endScheduled[i]);
                // YW >>
                studyEventScheduled.setOwner(ub);
                studyEventScheduled.setStatus(Status.AVAILABLE);
                studyEventScheduled.setLocation(fp.getString(INPUT_SCHEDULED_LOCATION[i]));
                studyEvent.setSubjectEventStatus(SubjectEventStatus.SCHEDULED);

                // subjectsExistingEvents =
                // sed.findAllByStudyAndStudySubjectId(
                // currentStudy,
                // studySubject.getId());
                studyEventScheduled.setSampleOrdinal(
                    sed.getMaxSampleOrdinal(definitionScheduleds.get(i), studySubject) + 1);
                // System.out.println("create scheduled events");
                studyEventScheduled = (StudyEventBean) sed.create(studyEventScheduled);
                if (!studyEventScheduled.isActive()) {
                  throw new OpenClinicaException(
                      restext.getString("scheduled_event_not_created_in_database"), "2");
                }

                AddNewSubjectServlet.saveFieldNotes(
                    INPUT_SCHEDULED_LOCATION[i],
                    fdn,
                    dndao,
                    studyEventScheduled.getId(),
                    "studyEvent",
                    currentStudy);
                // YW 3-12-2008, 2220 fix <<
                AddNewSubjectServlet.saveFieldNotes(
                    INPUT_STARTDATE_PREFIX_SCHEDULED[i],
                    fdn,
                    dndao,
                    studyEventScheduled.getId(),
                    "studyEvent",
                    currentStudy);
                AddNewSubjectServlet.saveFieldNotes(
                    INPUT_ENDDATE_PREFIX_SCHEDULED[i],
                    fdn,
                    dndao,
                    studyEventScheduled.getId(),
                    "studyEvent",
                    currentStudy);
                // YW >>
              } else {
                addPageMessage(
                    restext.getString("scheduled_event_definition")
                        + definitionScheduleds.get(i).getName()
                        + restext.getString("X_and_subject")
                        + studySubject.getName()
                        + restext.getString("not_created_since_event_not_repeating")
                        + restext.getString("event_type_already_exists"));
              }
            }
          }
        } // if

        session.removeAttribute(AddNewSubjectServlet.FORM_DISCREPANCY_NOTES_NAME);
        request.setAttribute(
            EnterDataForStudyEventServlet.INPUT_EVENT_ID, String.valueOf(studyEvent.getId()));
        response.encodeRedirectURL("EnterDataForStudyEvent?eventId=" + studyEvent.getId());
        forwardPage(Page.ENTER_DATA_FOR_STUDY_EVENT_SERVLET);
        // we want to actually have url of entering data in browser, so
        // redirecting
        // response.sendRedirect(response.encodeRedirectURL(
        // "EnterDataForStudyEvent?eventId="
        // + studyEvent.getId()));
        return;
      }
    }
  }
  @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);
      }
    }
  }
  @Override
  protected DisplayItemBean validateDisplayItemBean(
      DiscrepancyValidator v, DisplayItemBean dib, String inputName, HttpServletRequest request) {

    org.akaza.openclinica.bean.core.ResponseType rt =
        dib.getMetadata().getResponseSet().getResponseType();
    HttpSession session = request.getSession();
    EventCRFBean ecb = (EventCRFBean) request.getAttribute(INPUT_EVENT_CRF);

    boolean isSingleItem = false;
    if (StringUtil.isBlank(inputName)) { // for single items
      inputName = getInputName(dib);
      isSingleItem = true;
    }

    // we only give warning to user if data entered in DDE is different from
    // IDE when the first
    // time user hits 'save'
    int keyId = ecb.getId();
    Integer validationCount = (Integer) session.getAttribute(COUNT_VALIDATE + keyId);

    // @pgawade 12-Aug-2011 issue 10601:
    // 1. Moved the call to loadFormValue method setting values
    // from form here. It was at the end
    // of this method before that is after validations and so an extra
    // validation for checking value entered
    // against the data type was getting implemented for non-repeating group
    // items.
    // 2. Copying the form data into new object for non repeating items to
    // pass to validation
    // for matching IDE and DDE values. Id same reference is used, the way
    // code here was written, it affetcs
    // the value used in validation of data entered in DDE against the
    // related data type
    ItemDataBean valueToCompareTmp = dib.getData();
    ItemDataBean valueToCompare = copyItemDataBean(valueToCompareTmp);

    if (!isSingleItem) {
      valueToCompare = dib.getDbData();
    }

    // only load form value when an item is not in a group,
    // if in group, the value is already loaded
    // see formGroups = loadFormValueForItemGroup(digb,digbs,formGroups);
    if (isSingleItem) {
      dib = loadFormValue(dib, request);
    }

    boolean showOriginalItem =
        getItemMetadataService()
            .isShown(dib.getItem().getId(), ecb, valueToCompare); // was dib.getData()
    boolean showItem = dib.getMetadata().isShowItem();
    if (!showItem && dib.getScdData().getScdItemMetadataBean().getScdItemFormMetadataId() > 0) {
      showItem = true;
    }
    boolean showDuplicateItem =
        getItemMetadataService()
            .hasPassedDDE(
                dib.getMetadata(),
                ecb,
                valueToCompare); // .isShown(dib.getItem().getId(), ecb, dib.getDbData());// where
                                 // is the set db data?
    logger.debug(
        "*** show original item has value "
            + dib.getData().getValue()
            + " and show item has value "
            + valueToCompare.getValue());
    logger.debug(
        "--- show original: "
            + showOriginalItem
            + " show duplicate: "
            + showDuplicateItem
            + " and just show item: "
            + showItem);
    logger.debug("VALIDATION COUNT " + validationCount);
    if (showOriginalItem && showDuplicateItem || showItem) {
      if (rt.equals(org.akaza.openclinica.bean.core.ResponseType.TEXT)
          || rt.equals(org.akaza.openclinica.bean.core.ResponseType.TEXTAREA)
          || rt.equals(org.akaza.openclinica.bean.core.ResponseType.FILE)) {
        dib = validateDisplayItemBeanText(v, dib, inputName, request);
        if (validationCount == null || validationCount.intValue() == 0) {
          v.addValidation(
              inputName, Validator.MATCHES_INITIAL_DATA_ENTRY_VALUE, valueToCompare, false);
          v.setErrorMessage(
              respage.getString("value_you_specified")
                  + " "
                  + valueToCompare.getValue()
                  + " "
                  + respage.getString("from_initial_data_entry"));
        }

      } else if (rt.equals(org.akaza.openclinica.bean.core.ResponseType.RADIO)
          || rt.equals(org.akaza.openclinica.bean.core.ResponseType.SELECT)) {
        dib = validateDisplayItemBeanSingleCV(v, dib, inputName);
        // ItemFormMetadataBean ifmdb = dib.getMetadata();
        // ResponseSetBean rsBean = ifmdb.getResponseSet();
        // logger.info("### found a response set count of "+inputName+"
        // "+rsBean.getOptions().size());
        // TODO sees it at this end tbh 1878

        if (validationCount == null || validationCount.intValue() == 0) {
          v.addValidation(
              inputName, Validator.MATCHES_INITIAL_DATA_ENTRY_VALUE, valueToCompare, false);
          String errorValue = valueToCompare.getValue();

          java.util.ArrayList options = dib.getMetadata().getResponseSet().getOptions();

          for (int u = 0; u < options.size(); u++) {
            ResponseOptionBean rob = (ResponseOptionBean) options.get(u);
            if (rob.getValue().equals(errorValue)) {
              errorValue = rob.getText();
            }
          }
          v.setErrorMessage(
              respage.getString("value_you_specified")
                  + " "
                  + errorValue
                  + " "
                  + respage.getString("from_initial_data_entry"));
        }
      } else if (rt.equals(org.akaza.openclinica.bean.core.ResponseType.CHECKBOX)
          || rt.equals(org.akaza.openclinica.bean.core.ResponseType.SELECTMULTI)) {
        dib = validateDisplayItemBeanMultipleCV(v, dib, inputName);

        if (validationCount == null || validationCount.intValue() == 0) {
          v.addValidation(
              inputName, Validator.MATCHES_INITIAL_DATA_ENTRY_VALUE, valueToCompare, true);
          // repeated from above, tbh 112007
          String errorValue = valueToCompare.getValue();
          String errorTexts = "";

          java.util.ArrayList options = dib.getMetadata().getResponseSet().getOptions();

          for (int u = 0; u < options.size(); u++) {
            ResponseOptionBean rob = (ResponseOptionBean) options.get(u);
            if (errorValue.contains(rob.getValue())) {
              errorTexts = errorTexts + rob.getText();
              if (u < options.size() - 1) {
                // the values for multi-select are seperated by
                // comma
                errorTexts = errorTexts + ", ";
              }
            }
          }
          v.setErrorMessage(
              respage.getString("value_you_specified")
                  + " "
                  + errorTexts
                  + " "
                  + respage.getString("from_initial_data_entry"));
        }
      }
    }
    // // only load form value when an item is not in a group,
    // // if in group, the value is already loaded
    // // see formGroups = loadFormValueForItemGroup(digb,digbs,formGroups);
    // if (isSingleItem) {
    // dib = loadFormValue(dib, request);
    // }

    return dib;
  }
  @Override
  public void processRequest() throws Exception {

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

    String action = fp.getString("action");
    if (subjectId == 0 || StringUtil.isBlank(action)) {
      addPageMessage(respage.getString("please_choose_a_subject_to_remove"));
      forwardPage(Page.SUBJECT_LIST_SERVLET);
    } else {

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

      // find all study subjects
      StudySubjectDAO ssdao = new StudySubjectDAO(sm.getDataSource());
      ArrayList studySubs = ssdao.findAllBySubjectId(subjectId);

      // find study events
      StudyEventDAO sedao = new StudyEventDAO(sm.getDataSource());
      ArrayList events = sedao.findAllBySubjectId(subjectId);
      if ("confirm".equalsIgnoreCase(action)) {
        request.setAttribute("subjectToRemove", subject);
        request.setAttribute("studySubs", studySubs);
        request.setAttribute("events", events);
        forwardPage(Page.REMOVE_SUBJECT);
      } else {
        logger.info("submit to remove the subject");
        // change all statuses to deleted
        subject.setStatus(Status.DELETED);
        subject.setUpdater(ub);
        subject.setUpdatedDate(new Date());
        sdao.update(subject);

        // remove subject references from study
        for (int i = 0; i < studySubs.size(); i++) {
          StudySubjectBean studySub = (StudySubjectBean) studySubs.get(i);
          if (!studySub.getStatus().equals(Status.DELETED)) {
            studySub.setStatus(Status.AUTO_DELETED);
            studySub.setUpdater(ub);
            studySub.setUpdatedDate(new Date());
            ssdao.update(studySub);
          }
        }

        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")
                + " "
                + respage.getString("has_been_removed_succesfully");

        addPageMessage(emailBody);
        //                sendEmail(emailBody);

        forwardPage(Page.SUBJECT_LIST_SERVLET);
      }
    }
  }
  @Override
  public void processRequest() throws Exception {
    resetPanel();
    panel.setStudyInfoShown(false);
    panel.setOrderedData(true);

    FormProcessor fp = new FormProcessor(request);
    // checks which module the requests are from
    String module = fp.getString(MODULE);
    // keep the module in the session
    session.setAttribute(MODULE, module);

    String action = request.getParameter("action");
    CRFVersionBean version = (CRFVersionBean) session.getAttribute("version");

    File xsdFile = new File(SpringServletAccess.getPropertiesDir(context) + "ODM1-3-0.xsd");
    File xsdFile2 = new File(SpringServletAccess.getPropertiesDir(context) + "ODM1-2-1.xsd");

    if (StringUtil.isBlank(action)) {
      logger.info("action is blank");
      request.setAttribute("version", version);
      forwardPage(Page.IMPORT_CRF_DATA);
    }
    if ("confirm".equalsIgnoreCase(action)) {
      String dir = SQLInitServlet.getField("filePath");
      if (!(new File(dir)).exists()) {
        logger.info("The filePath in datainfo.properties is invalid " + dir);
        addPageMessage(respage.getString("filepath_you_defined_not_seem_valid"));
        forwardPage(Page.IMPORT_CRF_DATA);
      }
      // All the uploaded files will be saved in filePath/crf/original/
      String theDir = dir + "crf" + File.separator + "original" + File.separator;
      if (!(new File(theDir)).isDirectory()) {
        (new File(theDir)).mkdirs();
        logger.info("Made the directory " + theDir);
      }
      // MultipartRequest multi = new MultipartRequest(request, theDir, 50 * 1024 * 1024);
      File f = null;
      try {
        f = uploadFile(theDir, version);

      } catch (Exception e) {
        logger.warn("*** Found exception during file upload***");
        e.printStackTrace();
      }
      if (f == null) {
        forwardPage(Page.IMPORT_CRF_DATA);
      }

      // TODO
      // validation steps
      // 1. valid xml - validated by file uploader below

      // LocalConfiguration config = LocalConfiguration.getInstance();
      // config.getProperties().setProperty(
      // "org.exolab.castor.parser.namespaces",
      // "true");
      // config
      // .getProperties()
      // .setProperty("org.exolab.castor.sax.features",
      // "http://xml.org/sax/features/validation,
      // http://apache.org/xml/features/validation/schema,
      // http://apache.org/xml/features/validation/schema-full-checking");
      // // above sets to validate against namespace

      Mapping myMap = new Mapping();
      String propertiesPath = CoreResources.PROPERTIES_DIR;
      myMap.loadMapping(propertiesPath + File.separator + "cd_odm_mapping.xml");

      Unmarshaller um1 = new Unmarshaller(myMap);
      // um1.addNamespaceToPackageMapping("http://www.cdisc.org/ns/odm/v1.3"
      // ,
      // "ODMContainer");
      boolean fail = false;
      ODMContainer odmContainer = new ODMContainer();
      try {

        // schemaValidator.validateAgainstSchema(f, xsdFile);
        // utf-8 compliance, tbh 06/2009
        InputStreamReader isr = new InputStreamReader(new FileInputStream(f), "UTF-8");
        odmContainer = (ODMContainer) um1.unmarshal(isr);

        System.out.println(
            "Found crf data container for study oid: "
                + odmContainer.getCrfDataPostImportContainer().getStudyOID());
        System.out.println(
            "found length of subject list: "
                + odmContainer.getCrfDataPostImportContainer().getSubjectData().size());
        // 2. validates against ODM 1.3
        // check it all below, throw an exception and route to a
        // different
        // page if not working

        // TODO this block of code needs the xerces serializer in order
        // to
        // work

        // StringWriter myWriter = new StringWriter();
        // Marshaller m1 = new Marshaller(myWriter);
        //
        // m1.setProperty("org.exolab.castor.parser.namespaces",
        // "true");
        // m1
        // .setProperty("org.exolab.castor.sax.features",
        // "http://xml.org/sax/features/validation,
        // http://apache.org/xml/features/validation/schema,
        // http://apache.org/xml/features/validation/schema-full-checking
        // ");
        //
        // m1.setMapping(myMap);
        // m1.setNamespaceMapping("",
        // "http://www.cdisc.org/ns/odm/v1.3");
        // m1.setSchemaLocation("http://www.cdisc.org/ns/odm/v1.3
        // ODM1-3.xsd");
        // m1.marshal(odmContainer);
        // if you havent thrown it, you wont throw it here
        addPageMessage(respage.getString("passed_xml_validation"));
      } catch (Exception me1) {
        me1.printStackTrace();
        // expanding it to all exceptions, but hoping to catch Marshal
        // Exception or SAX Exceptions
        logger.info("found exception with xml transform");
        //
        logger.info("trying 1.2.1");
        try {
          schemaValidator.validateAgainstSchema(f, xsdFile2);
          // for backwards compatibility, we also try to validate vs
          // 1.2.1 ODM 06/2008
          InputStreamReader isr = new InputStreamReader(new FileInputStream(f), "UTF-8");
          odmContainer = (ODMContainer) um1.unmarshal(isr);
        } catch (Exception me2) {
          // not sure if we want to report me2
          MessageFormat mf = new MessageFormat("");
          mf.applyPattern(respage.getString("your_xml_is_not_well_formed"));
          Object[] arguments = {me1.getMessage()};
          addPageMessage(mf.format(arguments));
          //
          // addPageMessage("Your XML is not well-formed, and does not
          // comply with the ODM 1.3 Schema. Please check it, and try
          // again. It returned the message: "
          // + me1.getMessage());
          // me1.printStackTrace();
          forwardPage(Page.IMPORT_CRF_DATA);
          // you can't really wait to forward because then you throw
          // NPEs
          // in the next few parts of the code
        }
      }
      // TODO need to output further here
      // 2.a. is the study the same one that the user is in right now?
      // 3. validates against study metadata
      // 3.a. is that study subject in that study?
      // 3.b. is that study event def in that study?
      // 3.c. is that site in that study?
      // 3.d. is that crf version in that study event def?
      // 3.e. are those item groups in that crf version?
      // 3.f. are those items in that item group?

      List<String> errors =
          getImportCRFDataService().validateStudyMetadata(odmContainer, ub.getActiveStudyId());
      if (errors != null) {
        // add to session
        // forward to another page
        logger.info(errors.toString());
        for (String error : errors) {
          addPageMessage(error);
        }
        if (errors.size() > 0) {
          // fail = true;
          forwardPage(Page.IMPORT_CRF_DATA);
        } else {
          addPageMessage(respage.getString("passed_study_check"));
          addPageMessage(respage.getString("passed_oid_metadata_check"));
        }
      }
      System.out.println("passed error check");
      // TODO ADD many validation steps before we get to the
      // session-setting below
      // 4. is the event in the correct status to accept data import?
      // -- scheduled, data entry started, completed
      // (and the event should already be created)
      // (and the event should be independent, ie not affected by other
      // events)

      List<EventCRFBean> eventCRFBeans =
          getImportCRFDataService().fetchEventCRFBeans(odmContainer, ub);

      ArrayList<Integer> permittedEventCRFIds = new ArrayList<Integer>();
      logger.info("found a list of eventCRFBeans: " + eventCRFBeans.toString());

      List<DisplayItemBeanWrapper> displayItemBeanWrappers =
          new ArrayList<DisplayItemBeanWrapper>();
      HashMap<String, String> totalValidationErrors = new HashMap<String, String>();
      HashMap<String, String> hardValidationErrors = new HashMap<String, String>();
      System.out.println("found event crfs " + eventCRFBeans.size());
      // -- does the event already exist? if not, fail
      if (!eventCRFBeans.isEmpty()) {
        for (EventCRFBean eventCRFBean : eventCRFBeans) {
          DataEntryStage dataEntryStage = eventCRFBean.getStage();
          Status eventCRFStatus = eventCRFBean.getStatus();

          logger.info(
              "Event CRF Bean: id "
                  + eventCRFBean.getId()
                  + ", data entry stage "
                  + dataEntryStage.getName()
                  + ", status "
                  + eventCRFStatus.getName());
          if (eventCRFStatus.equals(Status.AVAILABLE)
              || dataEntryStage.equals(DataEntryStage.INITIAL_DATA_ENTRY)
              || dataEntryStage.equals(DataEntryStage.INITIAL_DATA_ENTRY_COMPLETE)
              || dataEntryStage.equals(DataEntryStage.DOUBLE_DATA_ENTRY_COMPLETE)
              || dataEntryStage.equals(DataEntryStage.DOUBLE_DATA_ENTRY)) {
            // actually want the negative
            // was status == available and the stage questions, but
            // when you are at 'data entry complete' your status is
            // set to 'unavailable'.
            // >> tbh 09/2008
            // HOWEVER, when one event crf is removed and the rest
            // are good, what happens???
            // need to create a list and inform that one is blocked
            // and the rest are not...
            //
            permittedEventCRFIds.add(new Integer(eventCRFBean.getId()));
          } else {
            // fail = true;
            // addPageMessage(respage.getString(
            // "the_event_crf_not_correct_status"));
            // forwardPage(Page.IMPORT_CRF_DATA);
          }
        }

        // so that we don't repeat this following message
        // did we exclude all the event CRFs? if not, pass, else fail
        if (eventCRFBeans.size() >= permittedEventCRFIds.size()) {
          addPageMessage(respage.getString("passed_event_crf_status_check"));
        } else {
          fail = true;
          addPageMessage(respage.getString("the_event_crf_not_correct_status"));
        }
        // do they all have to have the right status to move
        // forward? answer from bug tracker = no
        // 5. do the items contain the correct data types?

        // 6. are all the related OIDs present?
        // that is to say, do we chain all the way down?
        // this is covered by the OID Metadata Check

        // 7. do the edit checks pass?
        // only then can we pass on to VERIFY_IMPORT_SERVLET

        // do we overwrite?

        // XmlParser xp = new XmlParser();
        // List<HashMap<String, String>> importedData =
        // xp.getData(f);

        // now we generate hard edit checks, and have to set that to the
        // screen. get that from the service, generate a summary bean to
        // set to either
        // page in the workflow, either verifyImport.jsp or import.jsp

        try {
          List<DisplayItemBeanWrapper> tempDisplayItemBeanWrappers =
              new ArrayList<DisplayItemBeanWrapper>();
          tempDisplayItemBeanWrappers =
              getImportCRFDataService()
                  .lookupValidationErrors(
                      request,
                      odmContainer,
                      ub,
                      totalValidationErrors,
                      hardValidationErrors,
                      permittedEventCRFIds);
          System.out.println(
              "generated display item bean wrappers " + tempDisplayItemBeanWrappers.size());
          System.out.println("size of total validation errors: " + totalValidationErrors.size());
          displayItemBeanWrappers.addAll(tempDisplayItemBeanWrappers);
        } catch (NullPointerException npe1) {
          // what if you have 2 event crfs but the third is a fake?
          fail = true;
          logger.debug("threw a NPE after calling lookup validation errors");
          addPageMessage(respage.getString("an_error_was_thrown_while_validation_errors"));
          System.out.println("threw the null pointer at line 323, import");
          // npe1.printStackTrace();
        } catch (OpenClinicaException oce1) {
          fail = true;
          logger.debug(
              "threw an OCE after calling lookup validation errors "
                  + oce1.getOpenClinicaMessage());
          addPageMessage(oce1.getOpenClinicaMessage());
          System.out.println("threw the openclinica message at line 327, import");
        }
      } else {
        fail = true;
        addPageMessage(respage.getString("no_event_crfs_matching_the_xml_metadata"));
      }
      // for (HashMap<String, String> crfData : importedData) {
      // DisplayItemBeanWrapper displayItemBeanWrapper =
      // testing(request,
      // crfData);
      // displayItemBeanWrappers.add(displayItemBeanWrapper);
      // errors = displayItemBeanWrapper.getValidationErrors();
      //
      // }
      if (fail) {
        System.out.println("failed here - forwarding...");
        forwardPage(Page.IMPORT_CRF_DATA);
      } else {
        addPageMessage(respage.getString("passing_crf_edit_checks"));
        session.setAttribute("importedData", displayItemBeanWrappers);
        session.setAttribute("validationErrors", totalValidationErrors);
        session.setAttribute("hardValidationErrors", hardValidationErrors);
        // above are updated 'statically' by the method that originally
        // generated the wrappers; soon the only thing we will use
        // wrappers for is the 'overwrite' flag

        System.out.println("found total validation errors: " + totalValidationErrors.size());
        logger.debug("+++ content of total validation errors: " + totalValidationErrors.toString());
        SummaryStatsBean ssBean =
            getImportCRFDataService()
                .generateSummaryStatsBean(odmContainer, displayItemBeanWrappers);
        session.setAttribute("summaryStats", ssBean);
        // will have to set hard edit checks here as well
        session.setAttribute(
            "subjectData", odmContainer.getCrfDataPostImportContainer().getSubjectData());
        System.out.println("did not fail - forwarding...");
        forwardPage(Page.VERIFY_IMPORT_SERVLET);
      }
    }
  }
  @Override
  public void processRequest() throws Exception {

    CRFVersionDAO cvdao = new CRFVersionDAO(sm.getDataSource());
    FormProcessor fp = new FormProcessor(request);
    int versionId = fp.getInt("id", true);
    String module = fp.getString("module");
    request.setAttribute("module", module);

    String action = fp.getString("action");
    if (versionId == 0) {
      addPageMessage(respage.getString("please_choose_a_CRF_version_to_remove"));
      forwardPage(Page.CRF_LIST_SERVLET);
    } else {
      if (StringUtil.isBlank(action)) {
        addPageMessage(respage.getString("no_action_specified"));
        forwardPage(Page.CRF_LIST_SERVLET);
        return;
      }
      CRFVersionBean version = (CRFVersionBean) cvdao.findByPK(versionId);

      SectionDAO secdao = new SectionDAO(sm.getDataSource());

      EventCRFDAO evdao = new EventCRFDAO(sm.getDataSource());
      // find all event crfs by version id
      ArrayList eventCRFs = evdao.findUndeletedWithStudySubjectsByCRFVersion(versionId);
      if ("confirm".equalsIgnoreCase(action)) {
        request.setAttribute("versionToRemove", version);
        request.setAttribute("eventCRFs", eventCRFs);
        forwardPage(Page.REMOVE_CRF_VERSION);
      } else {
        logger.info("submit to remove the crf version");
        // version
        version.setStatus(Status.DELETED);
        version.setUpdater(ub);
        version.setUpdatedDate(new Date());
        cvdao.update(version);
        // added below tbh 092007, seems that we don't remove the event
        // crfs in the second pass
        for (int ii = 0; ii < eventCRFs.size(); ii++) {
          EventCRFBean ecbean = (EventCRFBean) eventCRFs.get(ii);
          ecbean.setStatus(Status.AUTO_DELETED);
          ecbean.setUpdater(ub);
          ecbean.setUpdatedDate(new Date());
          evdao.update(ecbean);
        }
        // added above tbh 092007, to fix task
        // all sections
        ArrayList sections = secdao.findAllByCRFVersionId(version.getId());
        for (int j = 0; j < sections.size(); j++) {
          SectionBean section = (SectionBean) sections.get(j);
          if (!section.getStatus().equals(Status.DELETED)) {
            section.setStatus(Status.AUTO_DELETED);
            section.setUpdater(ub);
            section.setUpdatedDate(new Date());
            secdao.update(section);
          }
        }

        // all item data related to event crfs
        ItemDataDAO idao = new ItemDataDAO(sm.getDataSource());
        for (int i = 0; i < eventCRFs.size(); i++) {
          EventCRFBean eventCRF = (EventCRFBean) eventCRFs.get(i);
          if (!eventCRF.getStatus().equals(Status.DELETED)) {
            eventCRF.setStatus(Status.AUTO_DELETED);
            eventCRF.setUpdater(ub);
            eventCRF.setUpdatedDate(new Date());
            evdao.update(eventCRF);

            ArrayList items = idao.findAllByEventCRFId(eventCRF.getId());
            for (int j = 0; j < items.size(); j++) {
              ItemDataBean item = (ItemDataBean) items.get(j);
              if (!item.getStatus().equals(Status.DELETED)) {
                item.setStatus(Status.AUTO_DELETED);
                item.setUpdater(ub);
                item.setUpdatedDate(new Date());
                idao.update(item);
              }
            }
          }
        }

        addPageMessage(
            respage.getString("the_CRF")
                + version.getName()
                + " "
                + respage.getString("has_been_removed_succesfully"));
        forwardPage(Page.CRF_LIST_SERVLET);
      }
    }
  }
  @Override
  public void processRequest() throws Exception {
    FormProcessor fp = new FormProcessor(request);
    String action = request.getParameter("action");
    session.setAttribute("sdvOptions", this.setSDVOptions());

    if (StringUtil.isBlank(action)) {
      if (currentStudy.getParentStudyId() > 0) {
        addPageMessage(respage.getString("you_cannot_create_site_itself_site"));

        forwardPage(Page.SITE_LIST_SERVLET);
      } else {
        StudyBean newStudy = new StudyBean();
        newStudy.setParentStudyId(currentStudy.getId());
        // get default facility info from property file
        newStudy.setFacilityName(SQLInitServlet.getField(CreateStudyServlet.FAC_NAME));
        newStudy.setFacilityCity(SQLInitServlet.getField(CreateStudyServlet.FAC_CITY));
        newStudy.setFacilityState(SQLInitServlet.getField(CreateStudyServlet.FAC_STATE));
        newStudy.setFacilityCountry(SQLInitServlet.getField(CreateStudyServlet.FAC_COUNTRY));
        newStudy.setFacilityContactDegree(
            SQLInitServlet.getField(CreateStudyServlet.FAC_CONTACT_DEGREE));
        newStudy.setFacilityContactEmail(
            SQLInitServlet.getField(CreateStudyServlet.FAC_CONTACT_EMAIL));
        newStudy.setFacilityContactName(
            SQLInitServlet.getField(CreateStudyServlet.FAC_CONTACT_NAME));
        newStudy.setFacilityContactPhone(
            SQLInitServlet.getField(CreateStudyServlet.FAC_CONTACT_PHONE));
        newStudy.setFacilityZip(SQLInitServlet.getField(CreateStudyServlet.FAC_ZIP));

        List<StudyParamsConfig> parentConfigs = currentStudy.getStudyParameters();
        // logger.info("parentConfigs size:" + parentConfigs.size());
        ArrayList configs = new ArrayList();

        for (StudyParamsConfig scg : parentConfigs) {
          // StudyParamsConfig scg = (StudyParamsConfig)
          // parentConfigs.get(i);
          if (scg != null) {
            // find the one that sub study can change
            if (scg.getValue().getId() > 0 && scg.getParameter().isOverridable()) {
              logger.info("parameter:" + scg.getParameter().getHandle());
              logger.info("value:" + scg.getValue().getValue());
              // YW 10-12-2007, set overridable study parameters
              // for a site
              if (scg.getParameter().getHandle().equalsIgnoreCase("interviewerNameRequired")) {
                scg.getValue().setValue(fp.getString("interviewerNameRequired"));
              } else if (scg.getParameter()
                  .getHandle()
                  .equalsIgnoreCase("interviewerNameDefault")) {
                scg.getValue().setValue(fp.getString("interviewerNameDefault"));
              } else if (scg.getParameter().getHandle().equalsIgnoreCase("interviewDateRequired")) {
                scg.getValue().setValue(fp.getString("interviewDateRequired"));
              } else if (scg.getParameter().getHandle().equalsIgnoreCase("interviewDateDefault")) {
                scg.getValue().setValue(fp.getString("interviewDateDefault"));
              }
              // YW >>
              configs.add(scg);
            }
          }
        }
        newStudy.setStudyParameters(configs);

        // YW 10-12-2007 <<
        newStudy
            .getStudyParameterConfig()
            .setInterviewerNameRequired(fp.getString("interviewerNameRequired"));
        newStudy
            .getStudyParameterConfig()
            .setInterviewerNameDefault(fp.getString("interviewerNameDefault"));
        newStudy
            .getStudyParameterConfig()
            .setInterviewDateRequired(fp.getString("interviewDateRequired"));
        newStudy
            .getStudyParameterConfig()
            .setInterviewDateDefault(fp.getString("interviewDateDefault"));
        // YW >>

        // BWP 3169 1-12-2008 <<
        newStudy
            .getStudyParameterConfig()
            .setInterviewerNameEditable(
                currentStudy.getStudyParameterConfig().getInterviewerNameEditable());
        newStudy
            .getStudyParameterConfig()
            .setInterviewDateEditable(
                currentStudy.getStudyParameterConfig().getInterviewDateEditable());
        // >>

        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));
        }
        // tbh 3946 07/2009
        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));
        }
        // >> tbh
        setPresetValues(fp.getPresetValues());

        session.setAttribute("newStudy", newStudy);
        session.setAttribute("definitions", this.initDefinitions(newStudy));
        request.setAttribute("facRecruitStatusMap", CreateStudyServlet.facRecruitStatusMap);
        request.setAttribute("statuses", Status.toActiveArrayList());

        forwardPage(Page.CREATE_SUB_STUDY);
      }

    } else {
      if ("confirm".equalsIgnoreCase(action)) {
        confirmStudy();

      } else if ("back".equalsIgnoreCase(action)) {
        StudyBean newStudy = (StudyBean) session.getAttribute("newStudy");
        try {
          fp.addPresetValue(INPUT_START_DATE, local_df.format(newStudy.getDatePlannedEnd()));
        } catch (Exception pe) {
          fp.addPresetValue(INPUT_START_DATE, fp.getString(INPUT_START_DATE));
        }
        try {
          fp.addPresetValue(INPUT_END_DATE, local_df.format(newStudy.getDatePlannedStart()));
        } catch (Exception pe) {
          fp.addPresetValue(INPUT_END_DATE, fp.getString(INPUT_END_DATE));
        }
        try {
          fp.addPresetValue(
              INPUT_VER_DATE, local_df.format(newStudy.getProtocolDateVerification()));
        } catch (Exception pe) {
          fp.addPresetValue(INPUT_VER_DATE, fp.getString(INPUT_VER_DATE));
        }
        setPresetValues(fp.getPresetValues());
        request.setAttribute("facRecruitStatusMap", CreateStudyServlet.facRecruitStatusMap);
        request.setAttribute("statuses", Status.toActiveArrayList());

        forwardPage(Page.CREATE_SUB_STUDY);
      } else if ("submit".equalsIgnoreCase(action)) {
        submitStudy();
      }
    }
  }
  /**
   * Validates the first section of study and save it into study bean
   *
   * @param request
   * @param response
   * @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);
    v.addValidation("description", Validator.NO_BLANKS);
    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);
    }
    // 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();
    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"));
    }

    session.setAttribute("newStudy", createStudyBean());

    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));
      }
      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);
    }
  }
  private void validateStudy5(FormProcessor fp, Validator v) {

    if (!StringUtil.isBlank(fp.getString("facConEmail"))) {
      v.addValidation("facConEmail", Validator.IS_A_EMAIL);
    }
    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();

    study.setFacilityCity(fp.getString("facCity"));
    study.setFacilityContactDegree(fp.getString("facConDrgree"));
    study.setFacilityName(fp.getString("facName"));
    study.setFacilityContactEmail(fp.getString("facConEmail"));
    study.setFacilityContactPhone(fp.getString("facConPhone"));
    study.setFacilityContactName(fp.getString("facConName"));
    study.setFacilityCountry(fp.getString("facCountry"));
    study.setFacilityContactDegree(fp.getString("facConDegree"));
    // newStudy.setFacilityRecruitmentStatus(fp.getString("facRecStatus"));
    study.setFacilityState(fp.getString("facState"));
    study.setFacilityZip(fp.getString("facZip"));

    if (errors.isEmpty()) {
    } else {
      request.setAttribute("formMessages", errors);
      request.setAttribute("facRecruitStatusMap", CreateStudyServlet.facRecruitStatusMap);
    }
  }
  @Override
  public void processRequest() throws Exception {
    FormProcessor fp = new FormProcessor(request);
    String action = request.getParameter("action");

    if (StringUtil.isBlank(action)) {
      if (currentStudy.getParentStudyId() > 0) {
        addPageMessage(respage.getString("you_cannot_create_site_itself_site"));

        forwardPage(Page.SITE_LIST_SERVLET);
      } else {
        StudyBean newStudy = new StudyBean();
        newStudy.setParentStudyId(currentStudy.getId());
        // get default facility info from property file
        newStudy.setFacilityName(SQLInitServlet.getField(CreateStudyServlet.FAC_NAME));
        newStudy.setFacilityCity(SQLInitServlet.getField(CreateStudyServlet.FAC_CITY));
        newStudy.setFacilityState(SQLInitServlet.getField(CreateStudyServlet.FAC_STATE));
        newStudy.setFacilityCountry(SQLInitServlet.getField(CreateStudyServlet.FAC_COUNTRY));
        newStudy.setFacilityContactDegree(
            SQLInitServlet.getField(CreateStudyServlet.FAC_CONTACT_DEGREE));
        newStudy.setFacilityContactEmail(
            SQLInitServlet.getField(CreateStudyServlet.FAC_CONTACT_EMAIL));
        newStudy.setFacilityContactName(
            SQLInitServlet.getField(CreateStudyServlet.FAC_CONTACT_NAME));
        newStudy.setFacilityContactPhone(
            SQLInitServlet.getField(CreateStudyServlet.FAC_CONTACT_PHONE));
        newStudy.setFacilityZip(SQLInitServlet.getField(CreateStudyServlet.FAC_ZIP));

        ArrayList parentConfigs = currentStudy.getStudyParameters();
        // logger.info("parentConfigs size:" + parentConfigs.size());
        ArrayList configs = new ArrayList();

        for (int i = 0; i < parentConfigs.size(); i++) {
          StudyParamsConfig scg = (StudyParamsConfig) parentConfigs.get(i);
          if (scg != null) {
            // find the one that sub study can change
            if (scg.getValue().getId() > 0 && scg.getParameter().isOverridable()) {
              logger.info("parameter:" + scg.getParameter().getHandle());
              logger.info("value:" + scg.getValue().getValue());
              // YW 10-12-2007, set overridable study parameters
              // for a site
              if (scg.getParameter().getHandle().equalsIgnoreCase("interviewerNameRequired")) {
                scg.getValue().setValue(fp.getString("interviewerNameRequired"));
              } else if (scg.getParameter()
                  .getHandle()
                  .equalsIgnoreCase("interviewerNameDefault")) {
                scg.getValue().setValue(fp.getString("interviewerNameDefault"));
              } else if (scg.getParameter().getHandle().equalsIgnoreCase("interviewDateRequired")) {
                scg.getValue().setValue(fp.getString("interviewDateRequired"));
              } else if (scg.getParameter().getHandle().equalsIgnoreCase("interviewDateDefault")) {
                scg.getValue().setValue(fp.getString("interviewDateDefault"));
              }
              // YW >>
              configs.add(scg);
            }
          }
        }

        newStudy.setStudyParameters(configs);

        // YW 10-12-2007 <<
        newStudy
            .getStudyParameterConfig()
            .setInterviewerNameRequired(fp.getString("interviewerNameRequired"));
        newStudy
            .getStudyParameterConfig()
            .setInterviewerNameDefault(fp.getString("interviewerNameDefault"));
        newStudy
            .getStudyParameterConfig()
            .setInterviewDateRequired(fp.getString("interviewDateRequired"));
        newStudy
            .getStudyParameterConfig()
            .setInterviewDateDefault(fp.getString("interviewDateDefault"));
        // YW >>

        session.setAttribute("newStudy", newStudy);
        request.setAttribute("facRecruitStatusMap", CreateStudyServlet.facRecruitStatusMap);
        request.setAttribute("statuses", Status.toActiveArrayList());

        forwardPage(Page.CREATE_SUB_STUDY);
      }

    } else {
      if ("confirm".equalsIgnoreCase(action)) {
        confirmStudy();

      } else if ("back".equalsIgnoreCase(action)) {
        request.setAttribute("facRecruitStatusMap", CreateStudyServlet.facRecruitStatusMap);
        request.setAttribute("statuses", Status.toActiveArrayList());

        forwardPage(Page.CREATE_SUB_STUDY);
      } else if ("submit".equalsIgnoreCase(action)) {
        submitStudy();
      }
    }
  }
  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;
  }