private boolean mayProceedSubmission(String studyOid, StudySubjectBean ssBean) throws Exception {
   boolean accessPermission = false;
   StudyBean study = getParentStudy(studyOid);
   StudyParameterValueDAO spvdao = new StudyParameterValueDAO(dataSource);
   StudyParameterValueBean pStatus =
       spvdao.findByHandleAndStudy(study.getId(), "participantPortal");
   participantPortalRegistrar = new ParticipantPortalRegistrar();
   String pManageStatus =
       participantPortalRegistrar.getRegistrationStatus(studyOid).toString(); // ACTIVE ,
   // PENDING ,
   // INACTIVE
   String participateStatus = pStatus.getValue().toString(); // enabled , disabled
   String studyStatus =
       study.getStatus().getName().toString(); // available , pending , frozen , locked
   logger.info(
       "pManageStatus: "
           + pManageStatus
           + "  participantStatus: "
           + participateStatus
           + "   studyStatus: "
           + studyStatus
           + "  studySubjectStatus: "
           + ssBean.getStatus().getName());
   if (participateStatus.equalsIgnoreCase("enabled")
       && studyStatus.equalsIgnoreCase("available")
       && pManageStatus.equalsIgnoreCase("ACTIVE")
       && ssBean.getStatus() == Status.AVAILABLE) {
     accessPermission = true;
   }
   return accessPermission;
 }
  public StudySubjectBean getSSBean(HashMap<String, String> userContext) throws Exception {
    String studySubjectOid = userContext.get("studySubjectOID");
    StudySubjectBean ssBean = null;
    StudySubjectDAO ssdao = new StudySubjectDAO(dataSource);
    SubjectDAO subjectdao = new SubjectDAO(dataSource);
    UserAccountDAO udao = new UserAccountDAO(dataSource);
    if (studySubjectOid != null) {
      ssBean = ssdao.findByOid(studySubjectOid);
    } else {
      String studyOid = userContext.get("studyOID");

      StudyBean studyBean = sdao.findByOid(studyOid);
      int studyEventDefnId = Integer.valueOf(userContext.get("studyEventDefinitionID"));
      int studyEventOrdinal = Integer.valueOf(userContext.get("studyEventOrdinal"));
      UserAccountBean uBean = (UserAccountBean) udao.findByPK(1);
      // build Subject Account
      SubjectBean subjectBean = createSubjectBean(uBean);
      subjectBean = (SubjectBean) subjectdao.findByPK(subjectBean.getId());
      // build StudySubject Account
      ssBean = createStudySubjectBean(studyBean, subjectBean, uBean);
      ssBean = (StudySubjectBean) ssdao.findByPK(ssBean.getId());
      System.out.println("study subject oid:  " + ssBean.getOid());
      // build User Account
      UserAccountBean userAccountBean = createUserAccount(uBean, studyBean, ssBean);
      userAccountBean = (UserAccountBean) udao.findByPK(userAccountBean.getId());
      // build and schedule study Event
      StudyEventBean studyEventBean =
          createStudyEventBean(ssBean, studyEventDefnId, studyEventOrdinal, userAccountBean);
    }
    return ssBean;
  }
  @SuppressWarnings("unchecked")
  @Override
  public void setDataAndLimitVariables(TableFacade tableFacade) {
    // initialize i18n
    resword = ResourceBundleProvider.getWordsBundle(getLocale());
    resformat = ResourceBundleProvider.getFormatBundle(getLocale());

    Limit limit = tableFacade.getLimit();
    ListSubjectFilter listSubjectFilter = getListSubjectFilter(limit);

    if (!limit.isComplete()) {
      int totalRows = getSubjectDao().getCountWithFilter(listSubjectFilter, getCurrentStudy());
      tableFacade.setTotalRows(totalRows);
    }

    ListSubjectSort listSubjectSort = getListSubjectSort(limit);
    int rowStart = limit.getRowSelect().getRowStart();
    int rowEnd = limit.getRowSelect().getRowEnd();

    Collection<SubjectBean> items =
        getSubjectDao()
            .getWithFilterAndSort(
                getCurrentStudy(), listSubjectFilter, listSubjectSort, rowStart, rowEnd);
    Collection<HashMap<Object, Object>> theItems = new ArrayList<HashMap<Object, Object>>();

    for (SubjectBean subject : items) {
      UserAccountBean owner = (UserAccountBean) getUserAccountDao().findByPK(subject.getOwnerId());
      UserAccountBean updater =
          subject.getUpdaterId() == 0
              ? null
              : (UserAccountBean) getUserAccountDao().findByPK(subject.getUpdaterId());
      HashMap<Object, Object> h = new HashMap<Object, Object>();
      String studySubjectIdAndStudy = "";
      List<StudySubjectBean> studySubjects =
          getStudySubjectDao().findAllBySubjectId(subject.getId());
      for (StudySubjectBean studySubjectBean : studySubjects) {
        StudyBean study = (StudyBean) getStudyDao().findByPK(studySubjectBean.getStudyId());
        studySubjectIdAndStudy += studySubjectIdAndStudy.length() == 0 ? "" : ",";
        studySubjectIdAndStudy += study.getIdentifier() + "-" + studySubjectBean.getLabel();
      }

      h.put("studySubjectIdAndStudy", studySubjectIdAndStudy);
      h.put("subject", subject);
      h.put("subject.uniqueIdentifier", subject.getUniqueIdentifier());
      h.put("subject.gender", subject.getGender());
      h.put("subject.createdDate", subject.getCreatedDate());
      h.put("subject.owner", owner);
      h.put("subject.updatedDate", subject.getUpdatedDate());
      h.put("subject.updater", updater);
      h.put("subject.status", subject.getStatus());

      theItems.add(h);
    }

    tableFacade.setItems(theItems);
  }
  /*
   * (non-Javadoc)
   * @see org.akaza.openclinica.service.subject.SubjectServiceInterface#createSubject(org.akaza.openclinica.bean.submit.SubjectBean,
   * org.akaza.openclinica.bean.managestudy.StudyBean)
   */
  public String createSubject(
      SubjectBean subjectBean, StudyBean studyBean, Date enrollmentDate, String secondaryId) {
    // studyBean = getStudyDao().findByUniqueIdentifier(studyBean.getIdentifier()); // Need to
    if (subjectBean.getUniqueIdentifier() != null
        && getSubjectDao().findByUniqueIdentifier(subjectBean.getUniqueIdentifier()).getId() != 0) {
      subjectBean = getSubjectDao().findByUniqueIdentifier(subjectBean.getUniqueIdentifier());
    } else {
      subjectBean.setStatus(Status.AVAILABLE);
      subjectBean = getSubjectDao().create(subjectBean);
    }

    StudySubjectBean studySubject =
        createStudySubject(subjectBean, studyBean, enrollmentDate, secondaryId);
    getStudySubjectDao().createWithoutGroup(studySubject);
    return studySubject.getLabel();
  }
  public static DiscrepancyNoteBean createDiscrepancyNote(
      ItemBean itemBean,
      String message,
      EventCRFBean eventCrfBean,
      DisplayItemBean displayItemBean,
      Integer parentId,
      UserAccountBean uab,
      DataSource ds,
      StudyBean study) {
    // DisplayItemBean displayItemBean) {
    DiscrepancyNoteBean note = new DiscrepancyNoteBean();
    StudySubjectDAO ssdao = new StudySubjectDAO(ds);
    note.setDescription(message);
    note.setDetailedNotes("Failed Validation Check");
    note.setOwner(uab);
    note.setCreatedDate(new Date());
    note.setResolutionStatusId(ResolutionStatus.OPEN.getId());
    note.setDiscrepancyNoteTypeId(DiscrepancyNoteType.FAILEDVAL.getId());
    if (parentId != null) {
      note.setParentDnId(parentId);
    }

    note.setField(itemBean.getName());
    note.setStudyId(study.getId());
    note.setEntityName(itemBean.getName());
    note.setEntityType("ItemData");
    note.setEntityValue(displayItemBean.getData().getValue());

    note.setEventName(eventCrfBean.getName());
    note.setEventStart(eventCrfBean.getCreatedDate());
    note.setCrfName(displayItemBean.getEventDefinitionCRF().getCrfName());

    StudySubjectBean ss = (StudySubjectBean) ssdao.findByPK(eventCrfBean.getStudySubjectId());
    note.setSubjectName(ss.getName());

    note.setEntityId(displayItemBean.getData().getId());
    note.setColumn("value");

    DiscrepancyNoteDAO dndao = new DiscrepancyNoteDAO(ds);
    note = (DiscrepancyNoteBean) dndao.create(note);
    // so that the below method works, need to set the entity above
    // System.out.println("trying to create mapping with " + note.getId() + " " + note.getEntityId()
    // + " " + note.getColumn() + " " + note.getEntityType());
    dndao.createMapping(note);
    // System.out.println("just created mapping");
    return note;
  }
  public String getInputUsername(StudyBean studyBean, StudySubjectBean studySubjectBean) {
    String inputUserName = null;
    if (studySubjectBean != null) {
      if (studyBean.getParentStudyId() > 0) studyBean = getStudy(studyBean.getParentStudyId());

      inputUserName = studyBean.getOid() + "." + studySubjectBean.getOid();
    }
    return inputUserName;
  }
 private StudySubjectBean createStudySubject(
     SubjectBean subject, StudyBean studyBean, Date enrollmentDate, String secondaryId) {
   StudySubjectBean studySubject = new StudySubjectBean();
   studySubject.setSecondaryLabel(secondaryId);
   studySubject.setOwner(getUserAccount());
   studySubject.setEnrollmentDate(enrollmentDate);
   studySubject.setLabel(subject.getLabel());
   subject.setLabel(null);
   studySubject.setSubjectId(subject.getId());
   studySubject.setStudyId(studyBean.getId());
   studySubject.setStatus(Status.AVAILABLE);
   return studySubject;
 }
 public StudySubjectBean createStudySubjectBean(
     StudyBean sBean, SubjectBean subjectBean, UserAccountBean uBean) {
   StudySubjectBean ssBean = new StudySubjectBean();
   subjectBean.setGender('\0'); // setting null character
   ssBean.setStudyId(sBean.getId());
   ssBean.setSubjectId(subjectBean.getId());
   ssBean.setStatus(Status.AVAILABLE);
   ssBean.setOwner(uBean);
   ssBean.setEnrollmentDate(new Date());
   int nextLabel = getStudySubjectDao().findTheGreatestLabel() + 1;
   ssBean.setLabel(Integer.toString(nextLabel));
   StudySubjectDAO ssdao = new StudySubjectDAO(dataSource);
   ssBean = (StudySubjectBean) ssdao.create(ssBean, false);
   return ssBean;
 }
 public StudyEventBean createStudyEventBean(
     StudySubjectBean ssBean,
     int studyEventDefinitionId,
     int studyEventDefnOrdinal,
     UserAccountBean uBean) {
   StudyEventBean studyEventBean = new StudyEventBean();
   studyEventBean.setStudySubjectId(ssBean.getId());
   studyEventBean.setStudyEventDefinitionId(studyEventDefinitionId);
   studyEventBean.setSampleOrdinal(studyEventDefnOrdinal);
   studyEventBean.setStatus(Status.AVAILABLE);
   studyEventBean.setOwner(uBean);
   studyEventBean.setDateStarted(new Date());
   studyEventBean.setSubjectEventStatus(SubjectEventStatus.SCHEDULED);
   StudyEventDAO studyEventDao = new StudyEventDAO(dataSource);
   studyEventBean = (StudyEventBean) studyEventDao.create(studyEventBean);
   return studyEventBean;
 }
  @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 {
    FormProcessor fp = new FormProcessor(request);
    int studySubId = fp.getInt(STUDY_SUB_ID, true);
    int eventCRFId = fp.getInt(EVENT_CRF_ID);

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

    StudyEventDAO sedao = new StudyEventDAO(sm.getDataSource());
    StudySubjectDAO subdao = new StudySubjectDAO(sm.getDataSource());
    EventCRFDAO ecdao = new EventCRFDAO(sm.getDataSource());
    StudyDAO sdao = new StudyDAO(sm.getDataSource());

    if (eventCRFId == 0) {
      addPageMessage(respage.getString("please_choose_an_event_CRF_to_delete"));
      request.setAttribute("id", new Integer(studySubId).toString());
      forwardPage(Page.VIEW_STUDY_SUBJECT_SERVLET);
    } else {
      EventCRFBean eventCRF = (EventCRFBean) ecdao.findByPK(eventCRFId);

      StudySubjectBean studySub = (StudySubjectBean) subdao.findByPK(studySubId);
      request.setAttribute("studySub", studySub);

      // construct info needed on view event crf page
      CRFDAO cdao = new CRFDAO(sm.getDataSource());
      CRFVersionDAO cvdao = new CRFVersionDAO(sm.getDataSource());

      int crfVersionId = eventCRF.getCRFVersionId();
      CRFBean cb = cdao.findByVersionId(crfVersionId);
      eventCRF.setCrf(cb);

      CRFVersionBean cvb = (CRFVersionBean) cvdao.findByPK(crfVersionId);
      eventCRF.setCrfVersion(cvb);

      // then get the definition so we can call
      // DisplayEventCRFBean.setFlags
      int studyEventId = eventCRF.getStudyEventId();

      StudyEventBean event = (StudyEventBean) sedao.findByPK(studyEventId);

      int studyEventDefinitionId = sedao.getDefinitionIdFromStudyEventId(studyEventId);
      StudyEventDefinitionDAO seddao = new StudyEventDefinitionDAO(sm.getDataSource());
      StudyEventDefinitionBean sed =
          (StudyEventDefinitionBean) seddao.findByPK(studyEventDefinitionId);
      event.setStudyEventDefinition(sed);
      request.setAttribute("event", event);

      EventDefinitionCRFDAO edcdao = new EventDefinitionCRFDAO(sm.getDataSource());

      StudyBean study = (StudyBean) sdao.findByPK(studySub.getStudyId());
      EventDefinitionCRFBean edc =
          edcdao.findByStudyEventDefinitionIdAndCRFId(study, studyEventDefinitionId, cb.getId());

      DisplayEventCRFBean dec = new DisplayEventCRFBean();
      dec.setEventCRF(eventCRF);
      dec.setFlags(eventCRF, ub, currentRole, edc.isDoubleEntry());

      // find all item data
      ItemDataDAO iddao = new ItemDataDAO(sm.getDataSource());
      dnDao = new DiscrepancyNoteDAO(sm.getDataSource());
      ArrayList<ItemDataBean> itemData = iddao.findAllByEventCRFId(eventCRF.getId());
      request.setAttribute("items", itemData);

      if ("confirm".equalsIgnoreCase(action)) {

        request.setAttribute("displayEventCRF", dec);

        forwardPage(Page.DELETE_EVENT_CRF);
      } else {
        logger.info("submit to delete the event CRF from event");

        // OC-6303  Deleting Event CRF resets Show / Hide logic
        // delete records from DynamicItemForm and DynamicItemGroup
        getDynamicsItemFormMetadataDao().delete(eventCRFId);
        getDynamicsItemGroupMetadataDao().delete(eventCRFId);

        eventCRF.setOldStatus(eventCRF.getStatus());
        eventCRF.setStatus(Status.RESET);
        eventCRF.setUpdater(ub);
        ecdao.update(eventCRF);

        for (ItemDataBean itemdata : itemData) {
          // OC-6343 Rule behaviour must be reset if an Event CRF is deleted
          // delete the records from ruleActionRunLogDao
          getRuleActionRunLogDao().delete(itemdata.getId());

          // OC-6344 Notes & Discrepancies must be set to "closed" when event CRF is deleted
          // parentDiscrepancyNoteList is the list of the parent DNs records only
          ArrayList<DiscrepancyNoteBean> parentDiscrepancyNoteList =
              getDnDao().findParentNotesOnlyByItemData(itemdata.getId());
          for (DiscrepancyNoteBean parentDiscrepancyNote : parentDiscrepancyNoteList) {
            if (parentDiscrepancyNote.getResolutionStatusId()
                != 4) { // if the DN's resolution status is not set to Closed
              String description = resword.getString("dn_auto-closed_description");
              String detailedNotes = resword.getString("dn_auto_closed_detailed_notes");
              // create new DN record , new DN Map record , also update the parent record
              createDiscrepancyNoteBean(
                  description, detailedNotes, itemdata.getId(), study, ub, parentDiscrepancyNote);
            }
          }
          iddao = new ItemDataDAO(sm.getDataSource());
          ifmdao = new ItemFormMetadataDAO(sm.getDataSource());
          ItemDataBean idBean = (ItemDataBean) iddao.findByPK(itemdata.getId());

          ItemFormMetadataBean ifmBean =
              ifmdao.findByItemIdAndCRFVersionId(idBean.getItemId(), crfVersionId);

          // Updating Dn_item_data_map actovated column into false for the existing DNs
          ArrayList<DiscrepancyNoteBean> dnBeans =
              getDnDao().findExistingNotesForItemData(itemdata.getId());
          if (dnBeans.size() != 0) {
            DiscrepancyNoteBean dnBean = new DiscrepancyNoteBean();
            dnBean.setEntityId(itemdata.getId());
            dnBean.setActivated(false);
            getDnDao().updateDnMapActivation(dnBean);
          }

          // Default Values are not addressed

          itemdata.setValue("");
          itemdata.setOldStatus(itemdata.getStatus());
          itemdata.setOwner(ub);
          itemdata.setStatus(Status.AVAILABLE);
          itemdata.setUpdater(ub);
          iddao.updateUser(itemdata);
          iddao.update(itemdata);
        }
        // OC-6291 event_crf status change

        eventCRF.setOldStatus(eventCRF.getStatus());
        eventCRF.setStatus(Status.AVAILABLE);
        eventCRF.setUpdater(ub);
        ecdao.update(eventCRF);

        if (event.getSubjectEventStatus().isCompleted()
            || event.getSubjectEventStatus().isSigned()) {
          event.setSubjectEventStatus(SubjectEventStatus.DATA_ENTRY_STARTED);
          event.setUpdater(ub);
          sedao = new StudyEventDAO(sm.getDataSource());
          sedao.update(event);
        }

        String emailBody =
            respage.getString("the_event_CRF")
                + cb.getName()
                + respage.getString("has_been_deleted_from_the_event")
                + event.getStudyEventDefinition().getName()
                + ". "
                + respage.getString("has_been_deleted_from_the_event_cont");

        addPageMessage(emailBody);
        // sendEmail(emailBody);
        request.setAttribute("id", new Integer(studySubId).toString());
        forwardPage(Page.VIEW_STUDY_SUBJECT_SERVLET);
      }
    }
  }
  /*
   * Purpose: Iterates over ODM to populate 2 objects: 1. importCRFList: A List of EventCRFs and information on how to
   * process them. 2. importCRFMap: A Map multi-layer map of Subject/Event/Form only populated when the subsequent
   * EventCRF passes the UpsertOn rules.
   */
  public ImportCRFInfoContainer(ODMContainer odmContainer, DataSource ds) {
    importCRFList = new ArrayList<ImportCRFInfo>();

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

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

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

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

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

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

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

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

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

            for (EventCRFBean ecb : eventCrfBeans) {
              ImportCRFInfo importCrfInfo =
                  new ImportCRFInfo(
                      studyOID,
                      subjectDataBean.getSubjectOID(),
                      studyEventDataBean.getStudyEventOID(),
                      formDataBean.getFormOID());
              importCrfInfo.setPreImportStage(ecb.getStage());
              String crfStatus = formDataBean.getEventCRFStatus();
              if (crfStatus != null
                  && crfStatus.equals(DataEntryStage.INITIAL_DATA_ENTRY.getName()))
                importCrfInfo.setPostImportStage(DataEntryStage.INITIAL_DATA_ENTRY);
              importCrfInfo.setEventCRFID(new Integer(ecb.getId()));
              if (!(ecb.getStage().equals(DataEntryStage.INITIAL_DATA_ENTRY)
                      && upsert.isDataEntryStarted())
                  && !(ecb.getStage().equals(DataEntryStage.DOUBLE_DATA_ENTRY_COMPLETE)
                      && upsert.isDataEntryComplete())) importCrfInfo.setProcessImport(false);
              importCRFList.add(importCrfInfo);
              if (importCrfInfo.isProcessImport()) formMap.put(formDataBean.getFormOID(), "true");
            }
          }
        } // formdata loop
        if (formMap.size() > 0) eventMap.put(studyEventDataBean.getStudyEventOID(), formMap);
      } // study event loop
      if (eventMap.size() > 0) subjectMap.put(subjectDataBean.getSubjectOID(), eventMap);
    } // subject data loop
    importCRFMap = subjectMap;
  }
  /**
   * Organize objects in a certain way so that we can show to Users on UI. step1 : Get StudyEvent ,
   * eventCrf , crfVersion from studyEventId.
   *
   * @param crfViewSpecificOrderedObjects
   * @param ruleSet
   * @param rule
   * @return
   */
  private HashMap<RuleBulkExecuteContainer, HashMap<RuleBulkExecuteContainerTwo, Set<String>>>
      populateForCrfBasedRulesView(
          HashMap<RuleBulkExecuteContainer, HashMap<RuleBulkExecuteContainerTwo, Set<String>>>
              crfViewSpecificOrderedObjects,
          RuleSetBean ruleSet,
          RuleBean rule,
          String result,
          StudyBean currentStudy,
          List<RuleActionBean> actions) {

    // step1
    StudyEventBean studyEvent =
        (StudyEventBean)
            getStudyEventDao()
                .findByPK(
                    Integer.valueOf(
                        getExpressionService()
                            .getStudyEventDefenitionOrdninalCurated(
                                ruleSet.getTarget().getValue())));
    EventCRFBean eventCrf =
        (EventCRFBean)
            getEventCrfDao()
                .findAllByStudyEventAndCrfOrCrfVersionOid(
                    studyEvent, getExpressionService().getCrfOid(ruleSet.getTarget().getValue()))
                .get(0);
    CRFVersionBean crfVersion =
        (CRFVersionBean) getCrfVersionDao().findByPK(eventCrf.getCRFVersionId());

    RuleBulkExecuteContainer key =
        new RuleBulkExecuteContainer(crfVersion.getName(), rule, result, actions);
    String key2String =
        getExpressionService()
            .getCustomExpressionUsedToCreateView(
                ruleSet.getTarget().getValue(), studyEvent.getSampleOrdinal());
    String studyEventDefinitionName =
        getExpressionService()
            .getStudyEventDefinitionFromExpression(ruleSet.getTarget().getValue(), currentStudy)
            .getName();
    studyEventDefinitionName += " [" + studyEvent.getSampleOrdinal() + "]";
    // String itemGroupName =
    // getExpressionService().getItemGroupNameAndOrdinal(ruleSet.getTarget().getValue());
    // String itemName =
    // getExpressionService().getItemGroupExpression(ruleSet.getTarget().getValue()).getName();

    String itemGroupName =
        getExpressionService().getItemGroupNameAndOrdinal(ruleSet.getTarget().getValue());
    ItemGroupBean itemGroupBean =
        getExpressionService().getItemGroupExpression(ruleSet.getTarget().getValue());
    ItemBean itemBean =
        getExpressionService().getItemExpression(ruleSet.getTarget().getValue(), itemGroupBean);
    String itemName = itemBean.getName();

    RuleBulkExecuteContainerTwo key2 =
        new RuleBulkExecuteContainerTwo(
            key2String, studyEvent, studyEventDefinitionName, itemGroupName, itemName);
    StudySubjectBean studySubject =
        (StudySubjectBean) getStudySubjectDao().findByPK(studyEvent.getStudySubjectId());

    if (crfViewSpecificOrderedObjects.containsKey(key)) {
      HashMap<RuleBulkExecuteContainerTwo, Set<String>> k = crfViewSpecificOrderedObjects.get(key);
      if (k.containsKey(key2)) {
        k.get(key2).add(String.valueOf(studySubject.getLabel()));
      } else {
        HashSet<String> values = new HashSet<String>();
        values.add(String.valueOf(studySubject.getLabel()));
        k.put(key2, values);
      }
    } else {
      HashMap<RuleBulkExecuteContainerTwo, Set<String>> k =
          new HashMap<RuleBulkExecuteContainerTwo, Set<String>>();
      HashSet<String> values = new HashSet<String>();
      values.add(String.valueOf(studySubject.getLabel()));
      k.put(key2, values);
      crfViewSpecificOrderedObjects.put(key, k);
    }
    return crfViewSpecificOrderedObjects;
  }
  @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);
      }
    }
  }
  /**
   * @api {post} /pages/api/v1/editform/:studyOid/submission Submit form data
   * @apiName doSubmission
   * @apiPermission admin
   * @apiVersion 1.0.0
   * @apiParam {String} studyOid Study Oid.
   * @apiParam {String} ecid Key that will be used to look up subject context information while
   *     processing submission.
   * @apiGroup Form
   * @apiDescription Submits the data from a completed form.
   */
  @POST
  @Path("/{studyOID}/submission")
  @Produces(MediaType.APPLICATION_XML)
  public Response doSubmission(
      @Context HttpServletRequest request,
      @Context HttpServletResponse response,
      @Context ServletContext servletContext,
      @PathParam("studyOID") String studyOID,
      @QueryParam(FORM_CONTEXT) String context) {

    String output = null;
    Response.ResponseBuilder builder = Response.noContent();
    String studySubjectOid = null;
    Integer studyEventDefnId = null;
    Integer studyEventOrdinal = null;
    String crfVersionOID = null;
    CRFVersionDAO crfvdao = new CRFVersionDAO(dataSource);

    try {

      if (ServletFileUpload.isMultipartContent(request)) {
        LOGGER.warn("WARNING: This prototype doesn't support multipart content.");
      }

      if (!mayProceedSubmission(studyOID))
        builder.status(javax.ws.rs.core.Response.Status.NOT_ACCEPTABLE).build();

      PFormCache cache = PFormCache.getInstance(servletContext);
      HashMap<String, String> userContext = cache.getSubjectContext(context);

      StudySubjectDAO ssdao = new StudySubjectDAO<String, ArrayList>(dataSource);
      StudySubjectBean ssBean = getSSBean(userContext);

      if (!mayProceedSubmission(studyOID, ssBean)) return null;

      studyEventDefnId = Integer.valueOf(userContext.get("studyEventDefinitionID"));
      studyEventOrdinal = Integer.valueOf(userContext.get("studyEventOrdinal"));
      crfVersionOID = userContext.get("crfVersionOID");

      StringWriter writer = new StringWriter();
      String body = IOUtils.toString(request.getInputStream(), "UTF-8");

      CRFVersionBean crfVersion = crfvdao.findByOid(crfVersionOID);
      if (crfVersion.getXform() != null && !crfVersion.getXform().equals("")) {
        body = body.substring(body.indexOf("<" + crfVersion.getXformName()));
        int length = body.indexOf(" ");
        body =
            body.replace(
                body.substring(body.lastIndexOf("<meta>"), body.lastIndexOf("</meta>") + 7), "");
        body = body.substring(0, body.lastIndexOf("</" + crfVersion.getXformName()) + length + 2);
        body = "<instance>" + body + "</instance>";
      } else {
        body = body.substring(body.indexOf("<F_"));
        int length = body.indexOf(" ");
        body =
            body.replace(body.substring(body.indexOf("<meta>"), body.indexOf("</meta>") + 7), "");
        body = body.substring(0, body.indexOf("</F_") + length + 2);
        body = "<instance>" + body + "</instance>";
      }

      Errors errors =
          getPformSubmissionService()
              .saveProcess(
                  body,
                  ssBean.getOid(),
                  studyEventDefnId,
                  studyEventOrdinal,
                  crfvdao.findByOid(crfVersionOID));

      // Set response headers
      Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
      Date currentDate = new Date();
      cal.setTime(currentDate);
      SimpleDateFormat format = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss zz");
      format.setCalendar(cal);
      builder.header("Date", format.format(currentDate));
      builder.header("X-OpenRosa-Version", "1.0");
      builder.type("text/xml; charset=utf-8");

      if (!errors.hasErrors()) {

        builder.entity(
            "<OpenRosaResponse xmlns=\"http://openrosa.org/http/response\">"
                + "<message>success</message>"
                + "</OpenRosaResponse>");
        LOGGER.debug("Successful OpenRosa submission");

      } else {
        LOGGER.error("Failed OpenRosa submission");
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        response.flushBuffer();
      }

    } catch (Exception e) {
      LOGGER.error(e.getMessage());
      LOGGER.error(ExceptionUtils.getStackTrace(e));
      return builder.status(javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR).build();
    }

    try {
      // Notify Participate of successful form submission.
      String pManageUrl = CoreResources.getField("portalURL") + "/app/rest/oc/submission";
      Submission submission = new Submission();
      Study pManageStudy = new Study();
      pManageStudy.setInstanceUrl(
          CoreResources.getField("sysURL.base") + "rest2/openrosa/" + studyOID);
      pManageStudy.setStudyOid(studyOID);
      submission.setStudy(pManageStudy);
      submission.setStudy_event_def_id(studyEventDefnId);
      submission.setStudy_event_def_ordinal(studyEventOrdinal);
      submission.setCrf_version_id(crfvdao.findByOid(crfVersionOID).getId());

      RestTemplate rest = new RestTemplate();
      String result = rest.postForObject(pManageUrl, submission, String.class);
      LOGGER.debug("Notified Participate of CRF submission with a result of: " + result);
    } catch (Exception e) {
      LOGGER.error("Unable to notify Participate of successful CRF submission.");
      LOGGER.error(e.getMessage());
      LOGGER.error(ExceptionUtils.getStackTrace(e));
    }
    return builder.status(javax.ws.rs.core.Response.Status.CREATED).build();
  }
  /*
   * (non-Javadoc)
   *
   * @see org.akaza.openclinica.control.core.SecureController#processRequest()
   */
  @Override
  protected void processRequest() throws Exception {

    FormProcessor fp = new FormProcessor(request);
    int noteId = fp.getInt(INPUT_NOTE_ID);
    String module = (String) session.getAttribute("module");
    // Integer subjectId = (Integer) session.getAttribute("subjectId");

    StudySubjectDAO studySubjectDAO = new StudySubjectDAO(sm.getDataSource());

    DiscrepancyNoteDAO dndao = new DiscrepancyNoteDAO(sm.getDataSource());
    dndao.setFetchMapping(true);

    // check that the note exists
    DiscrepancyNoteBean discrepancyNoteBean = (DiscrepancyNoteBean) dndao.findByPK(noteId);

    if (!discrepancyNoteBean.isActive()) {
      throw new InconsistentStateException(
          Page.MANAGE_STUDY_SERVLET,
          resexception.getString("you_are_trying_resolve_discrepancy_not_exist"));
    }

    // check that the note has not already been closed
    ArrayList children = dndao.findAllByParent(discrepancyNoteBean);
    discrepancyNoteBean.setChildren(children);
    // This logic has been reverted, issue-7459
    //        if (parentNoteIsClosed(discrepancyNoteBean)) {
    //            throw new InconsistentStateException(Page.VIEW_DISCREPANCY_NOTES_IN_STUDY_SERVLET,
    // respage
    //                    .getString("the_discrepancy_choose_has_been_closed_resolved_create_new"));
    //        }

    // all clear, send the user to the resolved screen
    String entityType = discrepancyNoteBean.getEntityType().toLowerCase();
    discrepancyNoteBean.setResStatus(
        ResolutionStatus.get(discrepancyNoteBean.getResolutionStatusId()));
    discrepancyNoteBean.setDisType(
        DiscrepancyNoteType.get(discrepancyNoteBean.getDiscrepancyNoteTypeId()));
    // BWP 03/17/2009 3166: if it's not an ItemData type note, redirect
    // Monitors to View Subject or
    // View Study Events <<
    if (currentRole.getRole().equals(Role.MONITOR)
        && !"itemdata".equalsIgnoreCase(entityType)
        && !"eventcrf".equalsIgnoreCase(entityType)) {
      redirectMonitor(module, discrepancyNoteBean);
      return;
    }
    // >>
    // If Study is Frozen or Locked
    if (currentStudy.getStatus().isFrozen()
        && !"itemdata".equalsIgnoreCase(entityType)
        && !"eventcrf".equalsIgnoreCase(entityType)) {
      redirectMonitor(module, discrepancyNoteBean);
      return;
    }

    boolean toView = false;
    boolean isCompleted = false;
    if ("itemdata".equalsIgnoreCase(entityType)) {
      ItemDataDAO iddao = new ItemDataDAO(sm.getDataSource());
      ItemDataBean idb = (ItemDataBean) iddao.findByPK(discrepancyNoteBean.getEntityId());

      EventCRFDAO ecdao = new EventCRFDAO(sm.getDataSource());

      EventCRFBean ecb = (EventCRFBean) ecdao.findByPK(idb.getEventCRFId());
      StudySubjectBean studySubjectBean =
          (StudySubjectBean) studySubjectDAO.findByPK(ecb.getStudySubjectId());

      discrepancyNoteBean.setSubjectId(studySubjectBean.getId());
      discrepancyNoteBean.setItemId(idb.getItemId());

      if (ecb.getStatus().equals(Status.UNAVAILABLE)) {
        isCompleted = true;
      }

      toView = true; // we want to go to view note page if the note is
      // for item data
    }
    // logger.info("set up pop up url: " + createNoteURL);
    // System.out.println("set up pop up url: " + createNoteURL);
    boolean goNext =
        prepareRequestForResolution(
            request, sm.getDataSource(), currentStudy, discrepancyNoteBean, isCompleted);

    Page p = getPageForForwarding(discrepancyNoteBean, isCompleted);

    // logger.info("found page for forwarding: " + p.getFileName());
    if (p == null) {
      throw new InconsistentStateException(
          Page.VIEW_DISCREPANCY_NOTES_IN_STUDY_SERVLET,
          resexception.getString("the_discrepancy_note_triying_resolve_has_invalid_type"));
    } else {
      if (p.getFileName().contains("?")) {
        if (!p.getFileName().contains("fromViewNotes=1")) {
          p.setFileName(p.getFileName() + "&fromViewNotes=1");
        }
      } else {
        p.setFileName(p.getFileName() + "?fromViewNotes=1");
      }
      String createNoteURL =
          CreateDiscrepancyNoteServlet.getAddChildURL(
              discrepancyNoteBean, ResolutionStatus.CLOSED, true);
      setPopUpURL(createNoteURL);
    }

    if (!goNext) {
      setPopUpURL("");
      addPageMessage(
          respage.getString("you_may_not_perform_admin_edit_on_CRF_not_completed_by_user"));
      p = Page.VIEW_DISCREPANCY_NOTES_IN_STUDY_SERVLET;
    }

    forwardPage(p);
  }
  public void processRequest() throws Exception {

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

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

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

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

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

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

        request.setAttribute("sitesToRestore", sites);

        request.setAttribute("userRolesToRestore", userRoles);

        request.setAttribute("subjectsToRestore", subjects);

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

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

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

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

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

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

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

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

            ArrayList eventCRFs = ecdao.findAllByStudyEvent(event);

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

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

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

        addPageMessage("This study has been restored successfully.");
        forwardPage(Page.STUDY_LIST_SERVLET);
      }
    }
  }
  /** createODMfile, added by tbh, 01/2009 */
  public HashMap<String, Integer> createODMFile(
      String odmVersion,
      long sysTimeBegin,
      String generalFileDir,
      DatasetBean datasetBean,
      StudyBean currentStudy,
      String generalFileDirCopy,
      ExtractBean eb,
      Integer currentStudyId,
      Integer parentStudyId,
      String studySubjectNumber) {

    Integer ssNumber = getStudySubjectNumber(studySubjectNumber);
    MetaDataCollector mdc = new MetaDataCollector(ds, datasetBean, currentStudy);
    AdminDataCollector adc = new AdminDataCollector(ds, datasetBean, currentStudy);
    ClinicalDataCollector cdc = new ClinicalDataCollector(ds, datasetBean, currentStudy);
    MetaDataCollector.setTextLength(200);
    if (odmVersion != null) {
      // by default odmVersion is 1.2
      if ("1.3".equals(odmVersion)) {
        ODMBean odmb = new ODMBean();
        odmb.setSchemaLocation("http://www.cdisc.org/ns/odm/v1.3 ODM1-3-0.xsd");
        ArrayList<String> xmlnsList = new ArrayList<String>();
        xmlnsList.add("xmlns=\"http://www.cdisc.org/ns/odm/v1.3\"");
        odmb.setXmlnsList(xmlnsList);
        odmb.setODMVersion("1.3");
        mdc.setODMBean(odmb);
        adc.setOdmbean(odmb);
        cdc.setODMBean(odmb);
      } else if ("oc1.2".equals(odmVersion)) {
        ODMBean odmb = new ODMBean();
        // odmb.setSchemaLocation("http://www.cdisc.org/ns/odm/v1.2 OpenClinica-ODM1-2-1.xsd");
        odmb.setSchemaLocation("http://www.cdisc.org/ns/odm/v1.2 OpenClinica-ODM1-2-1-OC1.xsd");
        ArrayList<String> xmlnsList = new ArrayList<String>();
        xmlnsList.add("xmlns=\"http://www.cdisc.org/ns/odm/v1.2\"");
        xmlnsList.add("xmlns:OpenClinica=\"http://www.openclinica.org/ns/openclinica_odm/v1.2\"");
        odmb.setXmlnsList(xmlnsList);
        odmb.setODMVersion("oc1.2");
        mdc.setODMBean(odmb);
        adc.setOdmbean(odmb);
        cdc.setODMBean(odmb);
      } else if ("oc1.3".equals(odmVersion)) {
        ODMBean odmb = mdc.getODMBean();
        // odmb.setSchemaLocation("http://www.cdisc.org/ns/odm/v1.3 OpenClinica-ODM1-3-0.xsd");
        odmb.setSchemaLocation("http://www.cdisc.org/ns/odm/v1.3 OpenClinica-ODM1-3-0-OC1.xsd");
        ArrayList<String> xmlnsList = new ArrayList<String>();
        xmlnsList.add("xmlns=\"http://www.cdisc.org/ns/odm/v1.3\"");
        xmlnsList.add("xmlns:OpenClinica=\"http://www.openclinica.org/ns/openclinica_odm/v1.3\"");
        odmb.setXmlnsList(xmlnsList);
        odmb.setODMVersion("oc1.3");
        mdc.setODMBean(odmb);
        adc.setOdmbean(odmb);
        cdc.setODMBean(odmb);
      }
    }

    //////////////////////////////////////////
    ////////// MetaData Extraction //////////
    mdc.collectFileData();
    MetaDataReportBean metaReport = new MetaDataReportBean(mdc.getOdmStudyMap());
    metaReport.setODMVersion(odmVersion);
    metaReport.setOdmBean(mdc.getODMBean());
    metaReport.createChunkedOdmXml(Boolean.TRUE);

    long sysTimeEnd = System.currentTimeMillis() - sysTimeBegin;
    String ODMXMLFileName = mdc.getODMBean().getFileOID() + ".xml";
    int fId =
        this.createFileK(
            ODMXMLFileName,
            generalFileDir,
            metaReport.getXmlOutput().toString(),
            datasetBean,
            sysTimeEnd,
            ExportFormatBean.XMLFILE,
            false);
    if (!"".equals(generalFileDirCopy)) {
      int fId2 =
          this.createFileK(
              ODMXMLFileName,
              generalFileDirCopy,
              metaReport.getXmlOutput().toString(),
              datasetBean,
              sysTimeEnd,
              ExportFormatBean.XMLFILE,
              false);
    }
    //////////////////////////////////////////
    ////////// AdminData Extraction //////////

    adc.collectFileData();
    AdminDataReportBean adminReport = new AdminDataReportBean(adc.getOdmAdminDataMap());
    adminReport.setODMVersion(odmVersion);
    adminReport.setOdmBean(mdc.getODMBean());
    adminReport.createChunkedOdmXml(Boolean.TRUE);

    sysTimeEnd = System.currentTimeMillis() - sysTimeBegin;
    fId =
        this.createFileK(
            ODMXMLFileName,
            generalFileDir,
            adminReport.getXmlOutput().toString(),
            datasetBean,
            sysTimeEnd,
            ExportFormatBean.XMLFILE,
            false);
    if (!"".equals(generalFileDirCopy)) {
      int fId2 =
          this.createFileK(
              ODMXMLFileName,
              generalFileDirCopy,
              adminReport.getXmlOutput().toString(),
              datasetBean,
              sysTimeEnd,
              ExportFormatBean.XMLFILE,
              false);
    }

    //////////////////////////////////////////
    ////////// ClinicalData Extraction ///////

    DatasetDAO dsdao = new DatasetDAO(ds);
    String sql = eb.getDataset().getSQLStatement();
    String st_sed_in = dsdao.parseSQLDataset(sql, true, true);
    String st_itemid_in = dsdao.parseSQLDataset(sql, false, true);
    int datasetItemStatusId = eb.getDataset().getDatasetItemStatus().getId();
    String ecStatusConstraint = dsdao.getECStatusConstraint(datasetItemStatusId);
    String itStatusConstraint = dsdao.getItemDataStatusConstraint(datasetItemStatusId);

    Iterator<OdmStudyBase> it = cdc.getStudyBaseMap().values().iterator();
    while (it.hasNext()) {
      OdmStudyBase u = it.next();
      ArrayList newRows =
          dsdao.selectStudySubjects(
              u.getStudy().getId(),
              0,
              st_sed_in,
              st_itemid_in,
              dsdao.genDatabaseDateConstraint(eb),
              ecStatusConstraint,
              itStatusConstraint);

      ///////////////
      int fromIndex = 0;
      boolean firstIteration = true;
      while (fromIndex < newRows.size()) {
        int toIndex =
            fromIndex + ssNumber < newRows.size() ? fromIndex + ssNumber : newRows.size() - 1;
        List x = newRows.subList(fromIndex, toIndex + 1);
        fromIndex = toIndex + 1;
        String studySubjectIds = "";
        for (int i = 0; i < x.size(); i++) {
          StudySubjectBean sub = new StudySubjectBean();
          sub = (StudySubjectBean) x.get(i);
          studySubjectIds += "," + sub.getId();
        } // for
        studySubjectIds = studySubjectIds.replaceFirst(",", "");

        ClinicalDataUnit cdata =
            new ClinicalDataUnit(
                ds,
                datasetBean,
                cdc.getOdmbean(),
                u.getStudy(),
                cdc.getCategory(),
                studySubjectIds);
        cdata.setCategory(cdc.getCategory());
        cdata.collectOdmClinicalData();

        FullReportBean report = new FullReportBean();
        report.setClinicalData(cdata.getOdmClinicalData());
        report.setOdmStudyMap(mdc.getOdmStudyMap());
        report.setODMVersion(odmVersion);
        // report.setOdmStudy(mdc.getOdmStudy());
        report.setOdmBean(mdc.getODMBean());
        if (firstIteration && fromIndex >= newRows.size()) {
          report.createChunkedOdmXml(Boolean.TRUE, true, true);
          firstIteration = false;
        } else if (firstIteration) {
          report.createChunkedOdmXml(Boolean.TRUE, true, false);
          firstIteration = false;
        } else if (fromIndex >= newRows.size()) {
          report.createChunkedOdmXml(Boolean.TRUE, false, true);
        } else {
          report.createChunkedOdmXml(Boolean.TRUE, false, false);
        }
        fId =
            this.createFileK(
                ODMXMLFileName,
                generalFileDir,
                report.getXmlOutput().toString(),
                datasetBean,
                sysTimeEnd,
                ExportFormatBean.XMLFILE,
                false);
        if (!"".equals(generalFileDirCopy)) {
          int fId2 =
              this.createFileK(
                  ODMXMLFileName,
                  generalFileDirCopy,
                  report.getXmlOutput().toString(),
                  datasetBean,
                  sysTimeEnd,
                  ExportFormatBean.XMLFILE,
                  false);
        }
      }
    }

    sysTimeEnd = System.currentTimeMillis() - sysTimeBegin;
    fId =
        this.createFileK(
            ODMXMLFileName,
            generalFileDir,
            "</ODM>",
            datasetBean,
            sysTimeEnd,
            ExportFormatBean.XMLFILE,
            true);
    if (!"".equals(generalFileDirCopy)) {
      int fId2 =
          this.createFileK(
              ODMXMLFileName,
              generalFileDirCopy,
              "</ODM>",
              datasetBean,
              sysTimeEnd,
              ExportFormatBean.XMLFILE,
              false);
    }

    //////////////////////////////////////////
    ////////// pre pagination extraction /////
    /*
    mdc.collectFileData();
    adc.collectOdmAdminDataMap();
    cdc.collectOdmClinicalDataMap();
    FullReportBean report = new FullReportBean();
    report.setClinicalDataMap(cdc.getOdmClinicalDataMap());
    report.setAdminDataMap(adc.getOdmAdminDataMap());
    report.setOdmStudyMap(mdc.getOdmStudyMap());
    report.setOdmBean(mdc.getODMBean());
    report.setODMVersion(odmVersion);
    report.createOdmXml(Boolean.TRUE);
    long sysTimeEnd = System.currentTimeMillis() - sysTimeBegin;
    String ODMXMLFileName = mdc.getODMBean().getFileOID() + ".xml";
    int fId = this.createFile(ODMXMLFileName, generalFileDir, report.getXmlOutput().toString(), datasetBean, sysTimeEnd, ExportFormatBean.XMLFILE, true);
    if (!"".equals(generalFileDirCopy)) {
    	int fId2 = this.createFile(ODMXMLFileName, generalFileDirCopy, report.getXmlOutput().toString(), datasetBean, sysTimeEnd, ExportFormatBean.XMLFILE, false);
    } */

    // return ODMXMLFileName;
    HashMap answerMap = new HashMap<String, Integer>();
    answerMap.put(ODMXMLFileName, new Integer(fId));
    return answerMap;
  }
  public boolean prepareRequestForResolution(
      HttpServletRequest request,
      DataSource ds,
      StudyBean currentStudy,
      DiscrepancyNoteBean note,
      boolean isCompleted) {
    String entityType = note.getEntityType().toLowerCase();
    int id = note.getEntityId();
    if ("subject".equalsIgnoreCase(entityType)) {
      StudySubjectDAO ssdao = new StudySubjectDAO(ds);
      StudySubjectBean ssb = ssdao.findBySubjectIdAndStudy(id, currentStudy);

      request.setAttribute("action", "show");
      request.setAttribute("id", String.valueOf(note.getEntityId()));
      request.setAttribute("studySubId", String.valueOf(ssb.getId()));
    } else if ("studysub".equalsIgnoreCase(entityType)) {
      request.setAttribute("action", "show");
      request.setAttribute("id", String.valueOf(note.getEntityId()));
    } else if ("eventcrf".equalsIgnoreCase(entityType)) {
      request.setAttribute("editInterview", "1");

      EventCRFDAO ecdao = new EventCRFDAO(ds);
      EventCRFBean ecb = (EventCRFBean) ecdao.findByPK(id);
      request.setAttribute(TableOfContentsServlet.INPUT_EVENT_CRF_BEAN, ecb);
      // If the request is passed along to ViewSectionDataEntryServlet,
      // that code needs
      // an event crf id; the (ecb.getId()+"") is necessary because
      // FormProcessor throws
      // a ClassCastException without the casting to a String
      request.setAttribute(ViewSectionDataEntryServlet.EVENT_CRF_ID, ecb.getId() + "");
    } else if ("studyevent".equalsIgnoreCase(entityType)) {
      StudyEventDAO sedao = new StudyEventDAO(ds);
      StudyEventBean seb = (StudyEventBean) sedao.findByPK(id);
      request.setAttribute(EnterDataForStudyEventServlet.INPUT_EVENT_ID, String.valueOf(id));
      request.setAttribute(UpdateStudyEventServlet.EVENT_ID, String.valueOf(id));
      request.setAttribute(
          UpdateStudyEventServlet.STUDY_SUBJECT_ID, String.valueOf(seb.getStudySubjectId()));
    }

    // this is for item data
    else if ("itemdata".equalsIgnoreCase(entityType)) {
      ItemDataDAO iddao = new ItemDataDAO(ds);
      ItemDataBean idb = (ItemDataBean) iddao.findByPK(id);

      EventCRFDAO ecdao = new EventCRFDAO(ds);

      EventCRFBean ecb = (EventCRFBean) ecdao.findByPK(idb.getEventCRFId());

      StudySubjectDAO ssdao = new StudySubjectDAO(sm.getDataSource());

      StudySubjectBean ssb = (StudySubjectBean) ssdao.findByPK(ecb.getStudySubjectId());

      ItemFormMetadataDAO ifmdao = new ItemFormMetadataDAO(ds);
      ItemFormMetadataBean ifmb =
          ifmdao.findByItemIdAndCRFVersionId(idb.getItemId(), ecb.getCRFVersionId());

      if (currentRole.getRole().equals(Role.MONITOR) || !isCompleted) {
        StudyEventDAO sedao = new StudyEventDAO(ds);
        StudyEventBean seb = (StudyEventBean) sedao.findByPK(id);
        request.setAttribute(EVENT_CRF_ID, String.valueOf(idb.getEventCRFId()));
        request.setAttribute(STUDY_SUB_ID, String.valueOf(seb.getStudySubjectId()));

      } else {
        request.setAttribute(
            DataEntryServlet.INPUT_EVENT_CRF_ID, String.valueOf(idb.getEventCRFId()));
        request.setAttribute(
            DataEntryServlet.INPUT_SECTION_ID, String.valueOf(ifmb.getSectionId()));
      }
      DataEntryStage stage = ecb.getStage();

      // if (!stage.equals(DataEntryStage.DOUBLE_DATA_ENTRY_COMPLETE)) {
      // return false;
      // }
    }

    return true;
  }