@Override
  protected DisplayItemBean validateCalcTypeDisplayItemBean(
      ScoreItemValidator sv, DisplayItemBean dib, String inputName, HttpServletRequest request) {

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

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

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

    return dib;
  }
  @Override
  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);
      }
    }
  }
  /*
   * (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 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;
  }