/**
   * Increases the ordinal for current object and decrease the ordinal of the previous one
   *
   * @param idCurrent
   * @param idPrevious
   * @param dao
   */
  private void increase(
      int idCurrent,
      int idPrevious,
      int currOrdinal,
      int prevOrdinal,
      int defId,
      EventDefinitionCRFDAO dao) {
    EventDefinitionCRFBean current = (EventDefinitionCRFBean) dao.findByPK(idCurrent);
    EventDefinitionCRFBean previous = (EventDefinitionCRFBean) dao.findByPK(idPrevious);
    if (current.getOrdinal() == currOrdinal && previous.getOrdinal() == prevOrdinal) {
      if (idCurrent > 0) {
        int currentOrdinal = current.getOrdinal();
        current.setOrdinal(currentOrdinal - 1);
        dao.update(current);
      }
      if (idPrevious > 0) {
        int previousOrdinal = previous.getOrdinal();
        previous.setOrdinal(previousOrdinal + 1);

        dao.update(previous);
      }

      ArrayList currOrdlist = dao.findAllByEventDefinitionIdAndOrdinal(defId, current.getOrdinal());
      ArrayList prevOrdlist =
          dao.findAllByEventDefinitionIdAndOrdinal(defId, previous.getOrdinal());
      if (currOrdlist.size() > 1 || prevOrdlist.size() > 1) {
        fixDuplicates(defId, dao);
      }
    }
  }
  /**
   * This method creates a List of DisplaySectionBeans, returning them in the order that the
   * sections appear in a CRF. This List is "lazily" initialized the first time it is requested.
   *
   * @return A List of DisplaySectionBeans.
   * @see org.akaza.openclinica.control.managestudy.PrintCRFServlet
   * @see org.akaza.openclinica.control.managestudy.PrintDataEntryServlet
   */
  public List<DisplaySectionBean> getDisplaySectionBeans() {
    FormBeanUtil formBeanUtil;
    ViewPersistanceHandler persistanceHandler;
    ArrayList<SectionBean> allCrfSections;
    // DAO classes for getting item definitions
    SectionDAO sectionDao;
    CRFVersionDAO crfVersionDao;

    if (displaySectionBeans == null) {
      displaySectionBeans = new ArrayList<DisplaySectionBean>();
      formBeanUtil = new FormBeanUtil();
      if (hasStoredData) persistanceHandler = new ViewPersistanceHandler();

      // We need a CRF version id to populate the form display
      if (this.crfVersionId == 0) {
        return displaySectionBeans;
      }

      sectionDao = new SectionDAO(dataSource);
      allCrfSections = (ArrayList) sectionDao.findByVersionId(this.crfVersionId);

      // for the purposes of null values, try to obtain a valid
      // eventCrfDefinition id
      EventDefinitionCRFBean eventDefBean = null;
      EventCRFBean eventCRFBean = new EventCRFBean();
      if (eventCRFId > 0) {
        EventCRFDAO ecdao = new EventCRFDAO(dataSource);
        eventCRFBean = (EventCRFBean) ecdao.findByPK(eventCRFId);
        StudyEventDAO sedao = new StudyEventDAO(dataSource);
        StudyEventBean studyEvent = (StudyEventBean) sedao.findByPK(eventCRFBean.getStudyEventId());

        EventDefinitionCRFDAO eventDefinitionCRFDAO = new EventDefinitionCRFDAO(dataSource);
        StudyDAO sdao = new StudyDAO(dataSource);
        StudyBean study = sdao.findByStudySubjectId(eventCRFBean.getStudySubjectId());
        eventDefBean =
            eventDefinitionCRFDAO.findByStudyEventIdAndCRFVersionId(
                study, studyEvent.getId(), this.crfVersionId);
      }
      eventDefBean = eventDefBean == null ? new EventDefinitionCRFBean() : eventDefBean;
      // Create an array or List of DisplaySectionBeans representing each
      // section
      // for printing
      DisplaySectionBean displaySectionBean;
      for (SectionBean sectionBean : allCrfSections) {
        displaySectionBean =
            formBeanUtil.createDisplaySectionBWithFormGroups(
                sectionBean.getId(),
                this.crfVersionId,
                dataSource,
                eventDefBean.getId(),
                eventCRFBean,
                context);
        displaySectionBeans.add(displaySectionBean);
      }
    }
    return displaySectionBeans;
  }
  // note that this step sets us up both for
  // displaying the data on the form again, in the event of an error
  // and sending the data to the database, in the event of no error
  //
  // we have to do this after adding the validations, so that we don't
  // overwrite the value the item data bean had from initial data entry
  // before the validator stores it as part of the Matches Initial Data Entry
  // Value validation
  // dib = loadFormValue(dib);
  // return dib;
  // }
  // should be from the db, we check here for a difference
  @Override
  protected List<DisplayItemGroupBean> validateDisplayItemGroupBean(
      DiscrepancyValidator v,
      DisplayItemGroupBean digb,
      List<DisplayItemGroupBean> digbs,
      List<DisplayItemGroupBean> formGroups,
      HttpServletRequest request,
      HttpServletResponse response) {
    EventDefinitionCRFBean edcb = (EventDefinitionCRFBean) request.getAttribute(EVENT_DEF_CRF_BEAN);
    HttpSession session = request.getSession();
    logger.info("===got this far");
    EventCRFBean ecb = (EventCRFBean) request.getAttribute(INPUT_EVENT_CRF);

    int keyId = ecb.getId();
    Integer validationCount = (Integer) session.getAttribute(COUNT_VALIDATE + keyId);

    formGroups = loadFormValueForItemGroup(digb, digbs, formGroups, edcb.getId(), request);
    logger.info(
        "found formgroups size for "
            + digb.getGroupMetaBean().getName()
            + ": "
            + formGroups.size()
            + " compare to db groups size: "
            + digbs.size());

    String inputName = "";
    for (int i = 0; i < formGroups.size(); i++) {
      DisplayItemGroupBean displayGroup = formGroups.get(i);

      List<DisplayItemBean> items = displayGroup.getItems();
      int order = displayGroup.getOrdinal();
      if (displayGroup.isAuto() && displayGroup.getFormInputOrdinal() > 0) {
        order = displayGroup.getFormInputOrdinal();
      }
      for (DisplayItemBean displayItem : items) {
        if (displayGroup.isAuto()) {
          inputName = getGroupItemInputName(displayGroup, order, displayItem);
        } else {
          inputName = getGroupItemManualInputName(displayGroup, order, displayItem);
        }
        validateDisplayItemBean(v, displayItem, inputName, request);
      }

      if (validationCount == null || validationCount.intValue() == 0) {
        if (i == 0 && formGroups.size() != digbs.size()) {
          v.addValidation(inputName + "group", Validator.DIFFERENT_NUMBER_OF_GROUPS_IN_DDE);
          // TODO internationalize this string, tbh
          v.setErrorMessage(
              "There are additional values here that were not present in the initial data entry. You have entered a different number of groups"
                  + " for the item groups containing "
                  + inputName);
        }
      }
    }

    return formGroups;
  }
 private ArrayList<StudyEventDefinitionBean> initDefinitions(StudyBean site) {
   ArrayList<StudyEventDefinitionBean> seds = new ArrayList<StudyEventDefinitionBean>();
   StudyEventDefinitionDAO sedDao = new StudyEventDefinitionDAO(sm.getDataSource());
   EventDefinitionCRFDAO edcdao = new EventDefinitionCRFDAO(sm.getDataSource());
   CRFVersionDAO cvdao = new CRFVersionDAO(sm.getDataSource());
   CRFDAO cdao = new CRFDAO(sm.getDataSource());
   StudyBean parentStudy =
       (StudyBean) new StudyDAO(sm.getDataSource()).findByPK(site.getParentStudyId());
   seds = sedDao.findAllByStudy(parentStudy);
   int start = 0;
   for (StudyEventDefinitionBean sed : seds) {
     int defId = sed.getId();
     ArrayList<EventDefinitionCRFBean> edcs =
         (ArrayList<EventDefinitionCRFBean>)
             edcdao.findAllByDefinitionAndSiteIdAndParentStudyId(
                 defId, site.getId(), parentStudy.getId());
     ArrayList<EventDefinitionCRFBean> defCrfs = new ArrayList<EventDefinitionCRFBean>();
     // sed.setCrfNum(edcs.size());
     for (EventDefinitionCRFBean edcBean : edcs) {
       int edcStatusId = edcBean.getStatus().getId();
       CRFBean crf = (CRFBean) cdao.findByPK(edcBean.getCrfId());
       int crfStatusId = crf.getStatusId();
       if (edcStatusId == 5 || edcStatusId == 7 || crfStatusId == 5 || crfStatusId == 7) {
       } else {
         ArrayList<CRFVersionBean> versions =
             (ArrayList<CRFVersionBean>) cvdao.findAllActiveByCRF(edcBean.getCrfId());
         edcBean.setVersions(versions);
         edcBean.setCrfName(crf.getName());
         CRFVersionBean defaultVersion =
             (CRFVersionBean) cvdao.findByPK(edcBean.getDefaultVersionId());
         edcBean.setDefaultVersionName(defaultVersion.getName());
         String sversionIds = edcBean.getSelectedVersionIds();
         ArrayList<Integer> idList = new ArrayList<Integer>();
         if (sversionIds.length() > 0) {
           String[] ids = sversionIds.split("\\,");
           for (String id : ids) {
             idList.add(Integer.valueOf(id));
           }
         }
         edcBean.setSelectedVersionIdList(idList);
         defCrfs.add(edcBean);
         ++start;
       }
     }
     logger.debug("definitionCrfs size=" + defCrfs.size() + " total size=" + edcs.size());
     sed.setCrfs(defCrfs);
     sed.setCrfNum(defCrfs.size());
   }
   return seds;
 }
 private void submitSiteEventDefinitions(StudyBean site) {
   FormProcessor fp = new FormProcessor(request);
   ArrayList<StudyEventDefinitionBean> seds = new ArrayList<StudyEventDefinitionBean>();
   CRFVersionDAO cvdao = new CRFVersionDAO(sm.getDataSource());
   seds = (ArrayList<StudyEventDefinitionBean>) session.getAttribute("definitions");
   HashMap<String, Boolean> changes = (HashMap<String, Boolean>) session.getAttribute("changed");
   for (StudyEventDefinitionBean sed : seds) {
     EventDefinitionCRFDAO edcdao = new EventDefinitionCRFDAO(sm.getDataSource());
     ArrayList<EventDefinitionCRFBean> edcs = sed.getCrfs();
     for (EventDefinitionCRFBean edcBean : edcs) {
       int edcStatusId = edcBean.getStatus().getId();
       if (edcStatusId == 5 || edcStatusId == 7) {
       } else {
         boolean changed = changes.get(sed.getId() + "-" + edcBean.getId());
         if (changed) {
           edcBean.setParentId(edcBean.getId());
           edcBean.setStudyId(site.getId());
           edcBean.setUpdater(ub);
           edcBean.setUpdatedDate(new Date());
           logger.debug("create for the site");
           edcdao.create(edcBean);
         }
       }
     }
   }
   session.removeAttribute("definitions");
   session.removeAttribute("changed");
   session.removeAttribute("sdvOptions");
 }
  /** @param metadata The metadata to set. */
  public void setMetadata(ItemFormMetadataBean metadata) {
    this.metadata = metadata;

    ResponseSetBean rsb = metadata.getResponseSet();
    // BWP 09/18/07 >> rsb cannot be null here because I added this line to
    // ItemFormMetadataBean's
    // constructor: responseSet=new ResponseSetBean();
    // logger.info("rsb = " + rsb);

    org.akaza.openclinica.bean.core.ResponseType rt = rsb.getResponseType();

    if (rt.equals(org.akaza.openclinica.bean.core.ResponseType.CHECKBOX)
        || rt.equals(org.akaza.openclinica.bean.core.ResponseType.RADIO)
        || rt.equals(org.akaza.openclinica.bean.core.ResponseType.SELECT)
        || rt.equals(org.akaza.openclinica.bean.core.ResponseType.SELECTMULTI)) {

      ArrayList nullValues = eventDefinitionCRF.getNullValuesList();
      for (int i = 0; i < nullValues.size(); i++) {
        NullValue nv = (NullValue) nullValues.get(i);
        ResponseOptionBean ro = new ResponseOptionBean();

        ro.setValue(nv.getName());
        ro.setText(nv.getDescription());
        rsb.addOption(ro);
      }
    }
    metadata.setResponseSet(rsb);
  }
 /**
  * Fixes ordinal values if there is any duplicates
  *
  * @param definitionId
  * @param dao
  */
 private void fixDuplicates(int definitionId, EventDefinitionCRFDAO dao) {
   ArrayList list = dao.findAllByEventDefinitionId(definitionId);
   int prevOrdinal = 0;
   boolean incrementNextOrdinal = false;
   for (int i = 0; i < list.size(); i++) {
     EventDefinitionCRFBean edc = (EventDefinitionCRFBean) list.get(i);
     if (i == 0) {
       if (edc.getOrdinal() != 0) {
         edc.setOrdinal(i);
         dao.update(edc);
       }
       continue;
     }
     if (incrementNextOrdinal) {
       edc.setOrdinal(i);
       dao.update(edc);
       continue;
     }
     if (edc.getOrdinal() != i) {
       edc.setOrdinal(i);
       dao.update(edc);
       incrementNextOrdinal = true;
     }
   }
 }
  public void processRequest() throws Exception {

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

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

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

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

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

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

        request.setAttribute("sitesToRestore", sites);

        request.setAttribute("userRolesToRestore", userRoles);

        request.setAttribute("subjectsToRestore", subjects);

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

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

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

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

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

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

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

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

            ArrayList eventCRFs = ecdao.findAllByStudyEvent(event);

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

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

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

        addPageMessage("This study has been restored successfully.");
        forwardPage(Page.STUDY_LIST_SERVLET);
      }
    }
  }
  @Override
  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);
      }
    }
  }
  @Override
  protected List<DisplayItemGroupBean> validateDisplayItemGroupBean(
      DiscrepancyValidator v,
      DisplayItemGroupBean digb,
      List<DisplayItemGroupBean> digbs,
      List<DisplayItemGroupBean> formGroups,
      RuleValidator rv,
      HashMap<String, ArrayList<String>> groupOrdinalPLusItemOid,
      HttpServletRequest request,
      HttpServletResponse response) {
    EventCRFBean ecb = (EventCRFBean) request.getAttribute(INPUT_EVENT_CRF);
    EventDefinitionCRFBean edcb = (EventDefinitionCRFBean) request.getAttribute(EVENT_DEF_CRF_BEAN);
    // logger.info("===got this far");
    int keyId = ecb.getId();
    Integer validationCount = (Integer) request.getSession().getAttribute(COUNT_VALIDATE + keyId);

    formGroups = loadFormValueForItemGroup(digb, digbs, formGroups, edcb.getId(), request);
    logger.info(
        "found formgroups size for "
            + digb.getGroupMetaBean().getName()
            + ": "
            + formGroups.size()
            + " compare to db groups size: "
            + digbs.size());

    String inputName = "";
    for (int i = 0; i < formGroups.size(); i++) {
      DisplayItemGroupBean displayGroup = formGroups.get(i);

      List<DisplayItemBean> items = displayGroup.getItems();
      int order = displayGroup.getOrdinal();
      if (displayGroup.isAuto() && displayGroup.getFormInputOrdinal() > 0) {
        order = displayGroup.getFormInputOrdinal();
      }
      for (DisplayItemBean displayItem : items) {
        if (displayGroup.isAuto()) {
          inputName = getGroupItemInputName(displayGroup, order, displayItem);
        } else {
          inputName = getGroupItemManualInputName(displayGroup, order, displayItem);
        }
        if (displayItem.getMetadata().isShowItem()
            || getItemMetadataService()
                .isShown(displayItem.getItem().getId(), ecb, displayItem.getData())) {
          // add the validation
          if (groupOrdinalPLusItemOid.containsKey(displayItem.getItem().getOid())
              || groupOrdinalPLusItemOid.containsKey(
                  String.valueOf(order + 1) + displayItem.getItem().getOid())) {
            System.out.println(
                "IN : " + String.valueOf(order + 1) + displayItem.getItem().getOid());
            validateDisplayItemBean(
                v,
                displayItem,
                inputName,
                rv,
                groupOrdinalPLusItemOid,
                true,
                groupOrdinalPLusItemOid.get(
                    String.valueOf(order + 1) + displayItem.getItem().getOid()),
                request);
          } else {
            validateDisplayItemBean(
                v, displayItem, inputName, rv, groupOrdinalPLusItemOid, false, null, request);
          }
        } else {
          System.out.println("OUT : " + String.valueOf(order + 1) + displayItem.getItem().getOid());
        }
        // validateDisplayItemBean(v, displayItem, inputName);
      }
    }
    return formGroups;
  }
  private ArrayList<StudyEventDefinitionBean> createSiteEventDefinitions(StudyBean site) {
    FormProcessor fp = new FormProcessor(request);
    ArrayList<StudyEventDefinitionBean> seds = new ArrayList<StudyEventDefinitionBean>();
    StudyBean parentStudy =
        (StudyBean) new StudyDAO(sm.getDataSource()).findByPK(site.getParentStudyId());
    seds = (ArrayList<StudyEventDefinitionBean>) session.getAttribute("definitions");
    if (seds == null || seds.size() <= 0) {
      StudyEventDefinitionDAO sedDao = new StudyEventDefinitionDAO(sm.getDataSource());
      seds = sedDao.findAllByStudy(parentStudy);
    }
    CRFVersionDAO cvdao = new CRFVersionDAO(sm.getDataSource());
    HashMap<String, Boolean> changes = new HashMap<String, Boolean>();
    for (StudyEventDefinitionBean sed : seds) {
      EventDefinitionCRFDAO edcdao = new EventDefinitionCRFDAO(sm.getDataSource());
      ArrayList<EventDefinitionCRFBean> edcs = sed.getCrfs();
      int start = 0;
      for (EventDefinitionCRFBean edcBean : edcs) {
        int edcStatusId = edcBean.getStatus().getId();
        if (edcStatusId == 5 || edcStatusId == 7) {
        } else {
          String order = start + "-" + edcBean.getId();
          int defaultVersionId = fp.getInt("defaultVersionId" + order);
          String requiredCRF = fp.getString("requiredCRF" + order);
          String doubleEntry = fp.getString("doubleEntry" + order);
          String electronicSignature = fp.getString("electronicSignature" + order);
          String hideCRF = fp.getString("hideCRF" + order);
          int sdvId = fp.getInt("sdvOption" + order);
          ArrayList<String> selectedVersionIdList = fp.getStringArray("versionSelection" + order);
          int selectedVersionIdListSize = selectedVersionIdList.size();
          String selectedVersionIds = "";
          if (selectedVersionIdListSize > 0) {
            for (String id : selectedVersionIdList) {
              selectedVersionIds += id + ",";
            }
            selectedVersionIds = selectedVersionIds.substring(0, selectedVersionIds.length() - 1);
          }

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