public ArrayList findAllStudySubjectByStudy(StudyBean study) {
    this.setTypesExpected();
    ArrayList alist = new ArrayList();
    this.setTypeExpected(11, TypeNames.STRING); // ss.label
    this.setTypeExpected(12, TypeNames.STRING); // column_name
    this.setTypeExpected(13, TypeNames.INT); // study_subject_id

    HashMap variables = new HashMap();
    variables.put(new Integer(1), new Integer(study.getId()));
    variables.put(new Integer(2), new Integer(study.getId()));

    alist = this.select(digester.getQuery("findAllStudySubjectByStudy"), variables);

    ArrayList al = new ArrayList();
    Iterator it = alist.iterator();
    while (it.hasNext()) {
      HashMap hm = (HashMap) it.next();
      DiscrepancyNoteBean eb = (DiscrepancyNoteBean) this.getEntityFromHashMap(hm);
      eb.setSubjectName((String) hm.get("label"));
      eb.setColumn((String) hm.get("column_name"));
      eb.setEntityId(((Integer) hm.get("study_subject_id")).intValue());
      al.add(eb);
    }
    return al;
  }
  private DiscrepancyNoteBean findSingleMapping(DiscrepancyNoteBean note) {
    HashMap variables = new HashMap();
    variables.put(new Integer(1), new Integer(note.getId()));

    setMapTypesExpected();
    String entityType = note.getEntityType();
    String sql = "";
    if ("subject".equalsIgnoreCase(entityType)) {
      sql = digester.getQuery("findSubjectMapByDNId");
    } else if ("studySub".equalsIgnoreCase(entityType)) {
      sql = digester.getQuery("findStudySubjectMapByDNId");
    } else if ("eventCrf".equalsIgnoreCase(entityType)) {
      sql = digester.getQuery("findEventCRFMapByDNId");
    } else if ("studyEvent".equalsIgnoreCase(entityType)) {
      sql = digester.getQuery("findStudyEventMapByDNId");
    } else if ("itemData".equalsIgnoreCase(entityType)) {
      sql = digester.getQuery("findItemDataMapByDNId");
    }

    ArrayList hms = select(sql, variables);

    if (hms.size() > 0) {
      HashMap hm = (HashMap) hms.get(0);
      note = getMappingFromHashMap(hm, note);
    }

    return note;
  }
  /**
   * Redirect the request to another page if the user is a Monitor type and the discrepancy note is
   * a type other than item data or event crf.
   *
   * @param module A String like "managestudy" or "admin"
   * @param discrepancyNoteBean
   */
  private void redirectMonitor(String module, DiscrepancyNoteBean discrepancyNoteBean) {

    if (discrepancyNoteBean != null) {

      String createNoteURL = "";
      // This String will determine whether the type is other than
      // itemdata.
      String entityType = discrepancyNoteBean.getEntityType().toLowerCase();
      // The id of the subject, study subject, or study event
      int entityId = discrepancyNoteBean.getEntityId();
      RequestDispatcher dispatcher = null;
      DiscrepancyNoteUtil discNoteUtil = new DiscrepancyNoteUtil();

      if (entityType != null
          && !"".equalsIgnoreCase(entityType)
          && !"itemdata".equalsIgnoreCase(entityType)
          && !"eventcrf".equalsIgnoreCase(entityType)) {
        // redirect to View Study Subject
        // addPageMessage(resword.getString("monitors_do_not_have_permission_to_resolve_discrepancy_notes"));
        if ("studySub".equalsIgnoreCase(entityType)) {
          dispatcher =
              request.getRequestDispatcher(
                  "/ViewStudySubject?id=" + entityId + "&module=" + module);
          discrepancyNoteBean.setSubjectId(entityId);
        } else if ("subject".equalsIgnoreCase(entityType)) {

          int studySubId =
              discNoteUtil.getStudySubjectIdForDiscNote(
                  discrepancyNoteBean, sm.getDataSource(), currentStudy.getId());

          dispatcher =
              request.getRequestDispatcher(
                  "/ViewStudySubject?id=" + studySubId + "&module=" + module);
          discrepancyNoteBean.setSubjectId(studySubId);
        } else if ("studyevent".equalsIgnoreCase(entityType)) {
          dispatcher = request.getRequestDispatcher("/EnterDataForStudyEvent?eventId=" + entityId);
        }

        // This code creates the URL for a popup window, which the
        // processing Servlet will initiate.
        // 'true' parameter means that ViewDiscrepancyNote is the
        // handling Servlet.
        createNoteURL =
            CreateDiscrepancyNoteServlet.getAddChildURL(
                discrepancyNoteBean, ResolutionStatus.CLOSED, true);
        request.setAttribute(POP_UP_URL, createNoteURL);

        try {
          if (dispatcher != null) {
            dispatcher.forward(request, response);
          }
        } catch (ServletException e) {
          e.printStackTrace();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
  }
  private DiscrepancyNoteBean getMappingFromHashMap(HashMap hm, DiscrepancyNoteBean note) {
    String entityType = note.getEntityType();
    String entityIDColumn = getEntityIDColumn(entityType);

    if (!entityIDColumn.equals("")) {
      note.setEntityId(selectInt(hm, entityIDColumn));
    }
    note.setColumn(selectString(hm, "column_name"));
    return note;
  }
  /** Updates a Study event */
  public EntityBean update(EntityBean eb) {
    // update discrepancy_note set
    // description =?,
    // discrepancy_note_type_id =? ,
    // resolution_status_id =? ,
    // detailed_notes =?
    // where discrepancy_note_id=?
    DiscrepancyNoteBean dnb = (DiscrepancyNoteBean) eb;
    dnb.setActive(false);

    HashMap variables = new HashMap();

    variables.put(new Integer(1), dnb.getDescription());
    variables.put(new Integer(2), new Integer(dnb.getDiscrepancyNoteTypeId()));
    variables.put(new Integer(3), new Integer(dnb.getResolutionStatusId()));
    variables.put(new Integer(4), dnb.getDetailedNotes());
    variables.put(new Integer(5), new Integer(dnb.getId()));
    this.execute(digester.getQuery("update"), variables);

    if (isQuerySuccessful()) {
      dnb.setActive(true);
    }

    return dnb;
  }
  /**
   * Determines if a discrepancy note is closed or not. The note is closed if it has status closed,
   * or any of its children have closed status.
   *
   * @param note The discrepancy note. The children should already be set.
   * @return <code>true</code> if the note is closed, <code>false</code> otherwise.
   */
  public static boolean noteIsClosed(DiscrepancyNoteBean note) {
    if (note.getResolutionStatusId() == ResolutionStatus.CLOSED.getId()) {
      return true;
    }

    ArrayList children = note.getChildren();
    for (int i = 0; i < children.size(); i++) {
      DiscrepancyNoteBean child = (DiscrepancyNoteBean) children.get(i);
      if (child.getResolutionStatusId() == ResolutionStatus.CLOSED.getId()) {
        return true;
      }
    }

    return false;
  }
  public ArrayList<DiscrepancyNoteBean> findEventCRFDNotesFromEventCRF(EventCRFBean eventCRFBean) {

    this.setTypesExpected();
    ArrayList dNotelist = new ArrayList();

    HashMap variables = new HashMap();
    variables.put(new Integer(1), new Integer(eventCRFBean.getId()));
    dNotelist = this.select(digester.getQuery("findEventCRFDNotesFromEventCRF"), variables);

    ArrayList<DiscrepancyNoteBean> returnedNotelist = new ArrayList<DiscrepancyNoteBean>();
    Iterator it = dNotelist.iterator();
    while (it.hasNext()) {
      HashMap hm = (HashMap) it.next();
      DiscrepancyNoteBean eb = (DiscrepancyNoteBean) this.getEntityFromHashMap(hm);
      eb.setEventCRFId(eventCRFBean.getId());
      returnedNotelist.add(eb);
    }
    return returnedNotelist;
  }
  /** Creates a new discrepancy note map */
  public void createMapping(DiscrepancyNoteBean eb) {
    HashMap variables = new HashMap();
    variables.put(new Integer(1), new Integer(eb.getEntityId()));
    variables.put(new Integer(2), new Integer(eb.getId()));
    variables.put(new Integer(3), eb.getColumn());
    String entityType = eb.getEntityType();

    if ("subject".equalsIgnoreCase(entityType)) {
      this.execute(digester.getQuery("createSubjectMap"), variables);
    } else if ("studySub".equalsIgnoreCase(entityType)) {
      this.execute(digester.getQuery("createStudySubjectMap"), variables);
    } else if ("eventCrf".equalsIgnoreCase(entityType)) {
      this.execute(digester.getQuery("createEventCRFMap"), variables);
    } else if ("studyEvent".equalsIgnoreCase(entityType)) {
      this.execute(digester.getQuery("createStudyEventMap"), variables);
    } else if ("itemData".equalsIgnoreCase(entityType)) {
      this.execute(digester.getQuery("createItemDataMap"), variables);
    }
  }
  public Collection findAllByEntityAndColumn(String entityName, int entityId, String column) {
    this.setTypesExpected();
    this.setTypeExpected(11, TypeNames.STRING); // ss.label
    ArrayList alist = new ArrayList();
    HashMap variables = new HashMap();
    variables.put(new Integer(1), new Integer(entityId));
    variables.put(new Integer(2), column);
    if ("subject".equalsIgnoreCase(entityName)) {
      alist = this.select(digester.getQuery("findAllBySubjectAndColumn"), variables);
    } else if ("studySub".equalsIgnoreCase(entityName)) {
      alist = this.select(digester.getQuery("findAllByStudySubjectAndColumn"), variables);
    } else if ("eventCrf".equalsIgnoreCase(entityName)) {
      this.setTypeExpected(12, TypeNames.DATE); // date_start
      this.setTypeExpected(13, TypeNames.STRING); // sed_name
      this.setTypeExpected(14, TypeNames.STRING); // crf_name
      alist = this.select(digester.getQuery("findAllByEventCRFAndColumn"), variables);
    } else if ("studyEvent".equalsIgnoreCase(entityName)) {
      this.setTypeExpected(12, TypeNames.DATE); // date_start
      this.setTypeExpected(13, TypeNames.STRING); // sed_name
      alist = this.select(digester.getQuery("findAllByStudyEventAndColumn"), variables);
    } else if ("itemData".equalsIgnoreCase(entityName)) {
      this.setTypeExpected(12, TypeNames.DATE); // date_start
      this.setTypeExpected(13, TypeNames.STRING); // sed_name
      this.setTypeExpected(14, TypeNames.STRING); // crf_name
      this.setTypeExpected(15, TypeNames.STRING); // item_name
      alist = this.select(digester.getQuery("findAllByItemDataAndColumn"), variables);
    }

    ArrayList al = new ArrayList();
    Iterator it = alist.iterator();
    while (it.hasNext()) {
      HashMap hm = (HashMap) it.next();
      DiscrepancyNoteBean eb = (DiscrepancyNoteBean) this.getEntityFromHashMap(hm);
      eb.setSubjectName((String) hm.get("label"));
      if ("eventCrf".equalsIgnoreCase(entityName) || "itemData".equalsIgnoreCase(entityName)) {
        eb.setEventName((String) hm.get("sed_name"));
        eb.setEventStart((Date) hm.get("date_start"));
        eb.setCrfName((String) hm.get("crf_name"));
        eb.setEntityName((String) hm.get("item_name"));

      } else if ("studyEvent".equalsIgnoreCase(entityName)) {
        eb.setEventName((String) hm.get("sed_name"));
        eb.setEventStart((Date) hm.get("date_start"));
      }
      if (fetchMapping) {
        eb = findSingleMapping(eb);
      }

      al.add(eb);
    }
    return al;
  }
  public AuditableEntityBean findEntity(DiscrepancyNoteBean note) {
    AuditableEntityDAO aedao = getAEDAO(note, ds);

    try {
      if (aedao != null) {
        AuditableEntityBean aeb = (AuditableEntityBean) aedao.findByPK(note.getEntityId());
        return aeb;
      }
    } catch (Exception e) {
    }

    return null;
  }
  public static AuditableEntityDAO getAEDAO(DiscrepancyNoteBean note, DataSource ds) {
    String entityType = note.getEntityType();
    if ("subject".equalsIgnoreCase(entityType)) {
      return new SubjectDAO(ds);
    } else if ("studySub".equalsIgnoreCase(entityType)) {
      return new StudySubjectDAO(ds);
    } else if ("eventCrf".equalsIgnoreCase(entityType)) {
      return new EventCRFDAO(ds);
    } else if ("studyEvent".equalsIgnoreCase(entityType)) {
      return new StudyEventDAO(ds);
    } else if ("itemData".equalsIgnoreCase(entityType)) {
      return new ItemDataDAO(ds);
    }

    return null;
  }
  public ArrayList findAllItemDataByStudy(StudyBean study) {
    this.setTypesExpected();
    ArrayList alist = new ArrayList();
    this.setTypeExpected(11, TypeNames.STRING); // ss.label
    this.setTypeExpected(12, TypeNames.DATE); // date_start
    this.setTypeExpected(13, TypeNames.STRING); // sed_name
    this.setTypeExpected(14, TypeNames.STRING); // crf_name
    this.setTypeExpected(15, TypeNames.STRING); // item_name
    this.setTypeExpected(16, TypeNames.STRING); // value
    this.setTypeExpected(17, TypeNames.INT); // item_data_id
    this.setTypeExpected(18, TypeNames.INT); // item_id

    HashMap variables = new HashMap();
    variables.put(new Integer(1), new Integer(study.getId()));
    variables.put(new Integer(2), new Integer(study.getId()));
    alist = this.select(digester.getQuery("findAllItemDataByStudy"), variables);

    ArrayList al = new ArrayList();
    Iterator it = alist.iterator();
    while (it.hasNext()) {
      HashMap hm = (HashMap) it.next();
      DiscrepancyNoteBean eb = (DiscrepancyNoteBean) this.getEntityFromHashMap(hm);
      eb.setEventName((String) hm.get("sed_name"));
      eb.setEventStart((Date) hm.get("date_start"));
      eb.setCrfName((String) hm.get("crf_name"));
      eb.setSubjectName((String) hm.get("label"));
      eb.setEntityName((String) hm.get("item_name"));
      eb.setEntityValue((String) hm.get("value"));
      // YW << change EntityId from item_id to item_data_id.
      eb.setEntityId(((Integer) hm.get("item_data_id")).intValue());
      eb.setItemId(((Integer) hm.get("item_id")).intValue());
      // YW >>
      al.add(eb);
    }
    return al;
  }
  public Page getPageForForwarding(DiscrepancyNoteBean note, boolean isCompleted) {
    String entityType = note.getEntityType().toLowerCase();
    request.setAttribute("fromResolvingNotes", "yes");

    if ("subject".equalsIgnoreCase(entityType)) {
      if (ub.isSysAdmin() || ub.isTechAdmin()) {
        return Page.UPDATE_SUBJECT_SERVLET;
      } else {
        return Page.VIEW_STUDY_SUBJECT_SERVLET;
      }
      // UpdateSubject?id=8&studySubId=8&action=show
    } else if ("studysub".equalsIgnoreCase(entityType)) {
      if (ub.isSysAdmin() || ub.isTechAdmin()) {
        return Page.UPDATE_STUDY_SUBJECT_SERVLET;
      } else {
        return Page.VIEW_STUDY_SUBJECT_SERVLET;
      }
      // UpdateStudySubject?id=8&action=show
    } /*
       * BWP>> 2966, commented this out: else if
       * ("eventcrf".equalsIgnoreCase(entityType)) { return
       * Page.TABLE_OF_CONTENTS_SERVLET; //
       * TableOfContents?action=ae&ecid=51&submitted=1&editInterview=1&interviewer=abc&interviewDate=12/04/2003 }
       */ else if ("studyevent".equalsIgnoreCase(entityType)) {
      if (ub.isSysAdmin() || ub.isTechAdmin()) {
        return Page.UPDATE_STUDY_EVENT_SERVLET;
      } else {
        return Page.ENTER_DATA_FOR_STUDY_EVENT_SERVLET;
      }
      // UpdateStudyEvent?event_id=12&ss_id=12
    } else if ("itemdata".equalsIgnoreCase(entityType) || "eventcrf".equalsIgnoreCase(entityType)) {
      if (currentRole.getRole().equals(Role.MONITOR) || !isCompleted) {
        return Page.VIEW_SECTION_DATA_ENTRY_SERVLET;
        // ViewSectionDataEntry?eventDefinitionCRFId=&ecId=1&tabId=1&studySubjectId=1
      } else {
        return Page.ADMIN_EDIT_SERVLET;
      }
      // eventCRFId=51&sectionId=14
    }
    return null;
  }
  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;
  }
 public static boolean parentNoteIsClosed(DiscrepancyNoteBean parentNote) {
   if (parentNote.getResolutionStatusId() == ResolutionStatus.CLOSED.getId()) {
     return true;
   }
   return false;
 }
  @Override
  protected void processRequest() throws Exception {
    FormProcessor fp = new FormProcessor(request);

    DiscrepancyNoteDAO dndao = new DiscrepancyNoteDAO(sm.getDataSource());
    int noteId = fp.getInt(NOTE_ID, true);

    DiscrepancyNoteBean note = (DiscrepancyNoteBean) dndao.findByPK(noteId);

    String entityType = note.getEntityType();
    UserAccountDAO udao = new UserAccountDAO(sm.getDataSource());

    ArrayList notes = dndao.findAllEntityByPK(note.getEntityType(), noteId);

    Date lastUpdatedDate = note.getCreatedDate();
    UserAccountBean lastUpdator = (UserAccountBean) udao.findByPK(note.getOwnerId());

    for (int i = 0; i < notes.size(); i++) {
      DiscrepancyNoteBean n = (DiscrepancyNoteBean) notes.get(i);
      int pId = n.getParentDnId();
      if (pId == 0) {
        note = n;
        note.setLastUpdator((UserAccountBean) udao.findByPK(n.getOwnerId()));
        note.setLastDateUpdated(n.getCreatedDate());
        lastUpdatedDate = note.getLastDateUpdated();
        lastUpdator = note.getLastUpdator();
      }
    }

    for (int i = 0; i < notes.size(); i++) {
      DiscrepancyNoteBean n = (DiscrepancyNoteBean) notes.get(i);
      int pId = n.getParentDnId();
      if (pId > 0) {
        note.getChildren().add(n);
        if (!n.getCreatedDate().before(lastUpdatedDate)) {
          lastUpdatedDate = n.getCreatedDate();
          lastUpdator = (UserAccountBean) udao.findByPK(n.getOwnerId());
          note.setLastUpdator(lastUpdator);
          note.setLastDateUpdated(lastUpdatedDate);
          note.setResolutionStatusId(n.getResolutionStatusId());
          note.setResStatus(ResolutionStatus.get(n.getResolutionStatusId()));
        }
      }
    }
    note.setNumChildren(note.getChildren().size());
    note.setDisType(DiscrepancyNoteType.get(note.getDiscrepancyNoteTypeId()));
    logger.info("Just set Note: " + note.getCrfName() + " column " + note.getColumn());
    request.setAttribute(DIS_NOTE, note);
    forwardPage(Page.VIEW_SINGLE_NOTE);
  }
  public ArrayList findAllByParent(DiscrepancyNoteBean parent) {
    HashMap variables = new HashMap();
    variables.put(new Integer(1), new Integer(parent.getId()));

    return this.executeFindAllQuery("findAllByParent", variables);
  }
  @Override
  @SuppressWarnings(value = "unchecked")
  public void processRequest() throws Exception {
    ItemDataDAO itemDataDao = new ItemDataDAO(sm.getDataSource());
    EventCRFDAO eventCrfDao = new EventCRFDAO(sm.getDataSource());
    CrfBusinessLogicHelper crfBusinessLogicHelper = new CrfBusinessLogicHelper(sm.getDataSource());
    String action = request.getParameter("action");

    FormProcessor fp = new FormProcessor(request);

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

    resetPanel();
    panel.setStudyInfoShown(false);
    panel.setOrderedData(true);

    setToPanel(resword.getString("create_CRF"), respage.getString("br_create_new_CRF_entering"));

    setToPanel(
        resword.getString("create_CRF_version"), respage.getString("br_create_new_CRF_uploading"));
    setToPanel(
        resword.getString("revise_CRF_version"), respage.getString("br_if_you_owner_CRF_version"));
    setToPanel(
        resword.getString("CRF_spreadsheet_template"),
        respage.getString("br_download_blank_CRF_spreadsheet_from"));
    setToPanel(
        resword.getString("example_CRF_br_spreadsheets"),
        respage.getString("br_download_example_CRF_instructions_from"));

    if ("confirm".equalsIgnoreCase(action)) {
      List<DisplayItemBeanWrapper> displayItemBeanWrappers =
          (List<DisplayItemBeanWrapper>) session.getAttribute("importedData");
      logger.info("Size of displayItemBeanWrappers : " + displayItemBeanWrappers.size());
      forwardPage(Page.VERIFY_IMPORT_CRF_DATA);
    }

    if ("save".equalsIgnoreCase(action)) {
      List<DisplayItemBeanWrapper> displayItemBeanWrappers =
          (List<DisplayItemBeanWrapper>) session.getAttribute("importedData");
      // System.out.println("Size of displayItemBeanWrappers : " + displayItemBeanWrappers.size());

      for (DisplayItemBeanWrapper wrapper : displayItemBeanWrappers) {

        int eventCrfBeanId = -1;
        EventCRFBean eventCrfBean = new EventCRFBean();

        // TODO : tom , the wrapper object has all the necessary data -
        // as you see we check the
        // is to see if this data is Savable if it is then we go ahead
        // and save it. if not we discard.
        // So the change needs to happen here , instead of discarding we
        // need to file discrepancy notes
        // and save the data. If you look in the
        // Page.VERIFY_IMPORT_CRF_DATA jsp file you can see how I am
        // pulling the errors. and use that in the same way.

        logger.info("right before we check to make sure it is savable: " + wrapper.isSavable());
        if (wrapper.isSavable()) {
          ArrayList<Integer> eventCrfInts = new ArrayList<Integer>();
          // based on the use case: "If any of the data does not meet
          // validations specified in the CRF
          // Template, a discrepancy note is automatically logged.
          // The DN will have a type of Failed Validation Check, and
          // a message of Failed Validation check."
          // System.out.println("wrapper problems found : " +
          // wrapper.getValidationErrors().toString());
          for (DisplayItemBean displayItemBean : wrapper.getDisplayItemBeans()) {
            eventCrfBeanId = displayItemBean.getData().getEventCRFId();
            eventCrfBean = (EventCRFBean) eventCrfDao.findByPK(eventCrfBeanId);
            logger.info("found value here: " + displayItemBean.getData().getValue());
            logger.info("found status here: " + eventCrfBean.getStatus().getName());
            // System.out.println("found event crf bean name here: "
            // +
            // eventCrfBean.getEventName()+" id "+eventCrfBean.getId
            // ());
            // SO, items can be created in a wrapper which is set to
            // overwrite
            // we get around this by checking the bean first, to
            // make sure it's not null
            ItemDataBean itemDataBean = new ItemDataBean();
            itemDataBean =
                itemDataDao.findByItemIdAndEventCRFIdAndOrdinal(
                    displayItemBean.getItem().getId(),
                    eventCrfBean.getId(),
                    displayItemBean.getData().getOrdinal());
            if (wrapper.isOverwrite() && itemDataBean.getStatus() != null) {
              // ItemDataBean itemDataBean = new ItemDataBean();
              // itemDataBean =
              // itemDataDao.findByItemIdAndEventCRFIdAndOrdinal(
              // displayItemBean.getItem().getId(),
              // eventCrfBean.getId(), displayItemBean
              // .getData().getOrdinal());
              // itemDataBean =
              // itemDataDao.findByEventCRFIdAndItemName(
              // eventCrfBean,
              // displayItemBean.getItem().getName());
              logger.info(
                  "just tried to find item data bean on item name "
                      + displayItemBean.getItem().getName());
              itemDataBean.setUpdatedDate(new Date());
              itemDataBean.setUpdater(ub);
              itemDataBean.setValue(displayItemBean.getData().getValue());
              // set status?
              itemDataDao.update(itemDataBean);
              logger.info("updated: " + itemDataBean.getItemId());
              // need to set pk here in order to create dn
              displayItemBean.getData().setId(itemDataBean.getId());
            } else {
              itemDataDao.create(displayItemBean.getData());
              logger.info(
                  "created: "
                      + displayItemBean.getData().getItemId()
                      + "event CRF ID = "
                      + eventCrfBean.getId()
                      + "CRF VERSION ID ="
                      + eventCrfBean.getCRFVersionId());

              // does this dao function work for repeating
              // events/groups?
              // ItemDataBean itemDataBean =
              // itemDataDao.findByEventCRFIdAndItemName(
              // eventCrfBean,
              // displayItemBean.getItem().getName());
              ItemDataBean itemDataBean2 =
                  itemDataDao.findByItemIdAndEventCRFIdAndOrdinal(
                      displayItemBean.getItem().getId(),
                      eventCrfBean.getId(),
                      displayItemBean.getData().getOrdinal());
              logger.info(
                  "found: id " + itemDataBean2.getId() + " name " + itemDataBean2.getName());
              displayItemBean.getData().setId(itemDataBean2.getId());
            }
            // logger.info("created item data bean:
            // "+displayItemBean.getData().getId());
            // logger.info("created:
            // "+displayItemBean.getData().getName());
            // logger.info("continued:
            // "+displayItemBean.getData().getItemId());
            ItemDAO idao = new ItemDAO(sm.getDataSource());
            ItemBean ibean = (ItemBean) idao.findByPK(displayItemBean.getData().getItemId());
            // logger.info("continued2: getName " +
            // ibean.getName());
            // System.out.println("*** checking for validation errors: " + ibean.getName());
            String itemOid =
                displayItemBean.getItem().getOid()
                    + "_"
                    + wrapper.getStudyEventRepeatKey()
                    + "_"
                    + displayItemBean.getData().getOrdinal()
                    + "_"
                    + wrapper.getStudySubjectOid();
            if (wrapper.getValidationErrors().containsKey(itemOid)) {
              ArrayList messageList = (ArrayList) wrapper.getValidationErrors().get(itemOid);
              // if
              // (wrapper.getValidationErrors().containsKey(ibean
              // .getName())) {
              // ArrayList messageList = (ArrayList)
              // wrapper.getValidationErrors
              // ().get(ibean.getName());
              // could be more then one will have to iterate
              // could it be more than one? tbh 08/2008
              for (int iter = 0; iter < messageList.size(); iter++) {
                String message = (String) messageList.get(iter);
                DiscrepancyNoteBean parentDn =
                    ImportSpringJob.createDiscrepancyNote(
                        ibean,
                        message,
                        eventCrfBean,
                        displayItemBean,
                        null,
                        ub,
                        sm.getDataSource(),
                        currentStudy);
                ImportSpringJob.createDiscrepancyNote(
                    ibean,
                    message,
                    eventCrfBean,
                    displayItemBean,
                    parentDn.getId(),
                    ub,
                    sm.getDataSource(),
                    currentStudy);
                // System.out.println("*** created disc note with message: " + message);
                // displayItemBean);
              }
            }
            // logger.info("created:
            // "+displayItemBean.getDbData().getName());
            if (!eventCrfInts.contains(new Integer(eventCrfBean.getId()))) {
              crfBusinessLogicHelper.markCRFComplete(eventCrfBean, ub);
              // System.out.println("*** just updated event crf bean: " + eventCrfBean.getId());
              eventCrfInts.add(new Integer(eventCrfBean.getId()));
            }
          }
          // end of item datas, tbh
          // crfBusinessLogicHelper.markCRFComplete(eventCrfBean, ub);
          // System .out.println("*** just updated event crf bean: "+
          // eventCrfBean.getId());
          // need to update the study event status as well, tbh
          // crfBusinessLogicHelper.updateStudyEvent(eventCrfBean,
          // ub);
          // above should do it for us, tbh 08/2008
        }
      }

      addPageMessage(respage.getString("data_has_been_successfully_import"));
      // forwardPage(Page.SUBMIT_DATA_SERVLET);
      forwardPage(Page.LIST_STUDY_SUBJECTS_SERVLET);
      // replaced tbh, 06/2009
    }
  }
  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;
  }
  /** Creates a new discrepancy note */
  public EntityBean create(EntityBean eb) {
    DiscrepancyNoteBean sb = (DiscrepancyNoteBean) eb;
    HashMap variables = new HashMap();
    HashMap nullVars = new HashMap();
    // INSERT INTO discrepancy_note
    // (description, discrepancy_note_type_id ,
    // resolution_status_id , detailed_notes , date_created,
    // owner_id, parent_dn_id)
    // VALUES (?,?,?,?,now(),?,?)
    variables.put(new Integer(1), sb.getDescription());
    variables.put(new Integer(2), new Integer(sb.getDiscrepancyNoteTypeId()));
    variables.put(new Integer(3), new Integer(sb.getResolutionStatusId()));
    variables.put(new Integer(4), sb.getDetailedNotes());

    variables.put(new Integer(5), new Integer(sb.getOwner().getId()));
    if (sb.getParentDnId() == 0) {
      nullVars.put(new Integer(6), new Integer(Types.INTEGER));
      variables.put(new Integer(6), null);
    } else {
      variables.put(new Integer(6), new Integer(sb.getParentDnId()));
    }
    variables.put(new Integer(7), sb.getEntityType());
    variables.put(new Integer(8), new Integer(sb.getStudyId()));

    this.executeWithPK(digester.getQuery("create"), variables, nullVars);
    if (isQuerySuccessful()) {
      sb.setId(getLatestPK());
    }

    return sb;
  }
  private void createDiscrepancyNoteBean(
      String description,
      String detailedNotes,
      int itemDataId,
      StudyBean studyBean,
      UserAccountBean ub,
      DiscrepancyNoteBean parentDiscrepancyNote) {
    DiscrepancyNoteBean dnb = new DiscrepancyNoteBean();
    dnb.setEntityId(itemDataId); // this is needed for DN Map object
    dnb.setStudyId(studyBean.getId());
    dnb.setEntityType(DiscrepancyNoteBean.ITEM_DATA);
    dnb.setDescription(description);
    dnb.setDetailedNotes(detailedNotes);
    dnb.setDiscrepancyNoteTypeId(
        parentDiscrepancyNote.getDiscrepancyNoteTypeId()); // set to parent DN Type Id
    dnb.setResolutionStatusId(4); // set to closed
    dnb.setColumn("value"); // this is needed for DN Map object
    dnb.setAssignedUserId(ub.getId());
    dnb.setOwner(ub);
    dnb.setParentDnId(parentDiscrepancyNote.getId());
    dnb.setActivated(false);
    dnb = (DiscrepancyNoteBean) getDnDao().create(dnb); // create child DN
    getDnDao().createMapping(dnb); // create DN mapping

    DiscrepancyNoteBean itemParentNote =
        (DiscrepancyNoteBean) getDnDao().findByPK(dnb.getParentDnId());
    itemParentNote.setResolutionStatusId(ResolutionStatus.CLOSED.getId());
    itemParentNote.setAssignedUserId(ub.getId());
    getDnDao().update(itemParentNote); // update parent DN
    getDnDao().updateAssignedUser(itemParentNote); // update parent DN assigned user
  }
  @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);
      }
    }
  }
  public ArrayList findAllEntityByPK(String entityName, int noteId) {
    this.setTypesExpected();
    ArrayList alist = new ArrayList();
    this.setTypeExpected(11, TypeNames.STRING); // ss.label

    HashMap variables = new HashMap();
    variables.put(new Integer(1), new Integer(noteId));
    variables.put(new Integer(2), new Integer(noteId));
    if ("subject".equalsIgnoreCase(entityName)) {
      this.setTypeExpected(12, TypeNames.STRING); // column_name
      alist = this.select(digester.getQuery("findAllSubjectByPK"), variables);
    } else if ("studySub".equalsIgnoreCase(entityName)) {
      this.setTypeExpected(12, TypeNames.STRING); // column_name
      alist = this.select(digester.getQuery("findAllStudySubjectByPK"), variables);
    } else if ("eventCrf".equalsIgnoreCase(entityName)) {
      this.setTypeExpected(12, TypeNames.DATE); // date_start
      this.setTypeExpected(13, TypeNames.STRING); // sed_name
      this.setTypeExpected(14, TypeNames.STRING); // crf_name
      this.setTypeExpected(15, TypeNames.STRING); // column_name
      alist = this.select(digester.getQuery("findAllEventCRFByPK"), variables);
    } else if ("studyEvent".equalsIgnoreCase(entityName)) {
      this.setTypeExpected(12, TypeNames.DATE); // date_start
      this.setTypeExpected(13, TypeNames.STRING); // sed_name
      this.setTypeExpected(14, TypeNames.STRING); // column_name
      alist = this.select(digester.getQuery("findAllStudyEventByPK"), variables);
    } else if ("itemData".equalsIgnoreCase(entityName)) {
      this.setTypeExpected(12, TypeNames.DATE); // date_start
      this.setTypeExpected(13, TypeNames.STRING); // sed_name
      this.setTypeExpected(14, TypeNames.STRING); // crf_name
      this.setTypeExpected(15, TypeNames.STRING); // item_name
      this.setTypeExpected(16, TypeNames.STRING); // value
      // YW <<
      this.setTypeExpected(17, TypeNames.INT); // item_data_id
      this.setTypeExpected(18, TypeNames.INT); // item_id
      // YW >>
      alist = this.select(digester.getQuery("findAllItemDataByPK"), variables);
    }

    ArrayList al = new ArrayList();
    Iterator it = alist.iterator();
    while (it.hasNext()) {
      HashMap hm = (HashMap) it.next();
      DiscrepancyNoteBean eb = (DiscrepancyNoteBean) this.getEntityFromHashMap(hm);
      if ("subject".equalsIgnoreCase(entityName) || "studySub".equalsIgnoreCase(entityName)) {
        eb.setSubjectName((String) hm.get("label"));
        eb.setColumn((String) hm.get("column_name"));
      } else if ("eventCrf".equalsIgnoreCase(entityName)) {
        eb.setSubjectName((String) hm.get("label"));
        eb.setEventName((String) hm.get("sed_name"));
        eb.setEventStart((Date) hm.get("date_start"));
        eb.setCrfName((String) hm.get("crf_name"));
        eb.setColumn((String) hm.get("column_name"));
      } else if ("itemData".equalsIgnoreCase(entityName)) {
        eb.setSubjectName((String) hm.get("label"));
        eb.setEventName((String) hm.get("sed_name"));
        eb.setEventStart((Date) hm.get("date_start"));
        eb.setCrfName((String) hm.get("crf_name"));
        eb.setEntityName((String) hm.get("item_name"));
        eb.setEntityValue((String) hm.get("value"));
        // YW <<
        eb.setEntityId(((Integer) hm.get("item_data_id")).intValue());
        eb.setItemId(((Integer) hm.get("item_id")).intValue());
        // YW >>

      } else if ("studyEvent".equalsIgnoreCase(entityName)) {
        eb.setSubjectName((String) hm.get("label"));
        eb.setEventName((String) hm.get("sed_name"));
        eb.setEventStart((Date) hm.get("date_start"));
        eb.setColumn((String) hm.get("column_name"));
      }
      if (fetchMapping) {
        eb = findSingleMapping(eb);
      }
      al.add(eb);
    }
    return al;
  }
  /*
   * (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);
  }
  /** getEntityFromHashMap, the method that gets the object from the database query. */
  public Object getEntityFromHashMap(HashMap hm) {
    DiscrepancyNoteBean eb = new DiscrepancyNoteBean();
    Date dateCreated = (Date) hm.get("date_created");
    Integer ownerId = (Integer) hm.get("owner_id");
    eb.setCreatedDate(dateCreated);
    eb.setOwnerId(ownerId.intValue());

    // discrepancy_note_id serial NOT NULL,
    // description varchar(255),
    // discrepancy_note_type_id numeric,
    // resolution_status_id numeric,

    // detailed_notes varchar(1000),
    // date_created date,
    // owner_id numeric,
    // parent_dn_id numeric,
    eb.setId(selectInt(hm, "discrepancy_note_id"));
    eb.setDescription((String) hm.get("description"));
    eb.setDiscrepancyNoteTypeId(((Integer) hm.get("discrepancy_note_type_id")).intValue());
    eb.setResolutionStatusId(((Integer) hm.get("resolution_status_id")).intValue());
    eb.setParentDnId(((Integer) hm.get("parent_dn_id")).intValue());
    eb.setDetailedNotes((String) hm.get("detailed_notes"));
    eb.setEntityType((String) hm.get("entity_type"));
    eb.setDisType(DiscrepancyNoteType.get(eb.getDiscrepancyNoteTypeId()));
    eb.setResStatus(ResolutionStatus.get(eb.getResolutionStatusId()));
    eb.setStudyId(selectInt(hm, "study_id"));
    return eb;
  }