protected ActionForward getForward(ActionForward forward, String accessionNumber) {
    ActionRedirect redirect = new ActionRedirect(forward);
    if (!StringUtil.isNullorNill(accessionNumber))
      redirect.addParameter(ACCESSION_NUMBER, accessionNumber);

    return redirect;
  }
 protected String convertToDisplayableXML(String xml) {
   if (!StringUtil.isNullorNill(xml)) {
     xml = xml.replaceAll("<", "&lt;");
     xml = xml.replaceAll(">", "&gt;");
     // the following 2 lines are for display on page (not for system
     // out)
     xml = xml.replaceAll("\n", "<br>");
     xml = xml.replaceAll(" ", "&nbsp;");
   }
   return xml;
 }
  // bugzilla 1482
  private boolean duplicateReferenceTablesExists(ReferenceTables referenceTables, boolean isNew)
      throws LIMSRuntimeException {
    try {

      List list = new ArrayList();
      String sql;

      // not case sensitive hemolysis and Hemolysis are considered
      // duplicates
      if (isNew) {
        sql = "from ReferenceTables t where trim(lower(t.tableName)) = :param";
      } else {
        sql = "from ReferenceTables t where trim(lower(t.tableName)) = :param and id != :param2";
      }

      // System.out.println("Yi in duplicateReferencetables sql is " + sql);
      org.hibernate.Query query = HibernateUtil.getSession().createQuery(sql);
      // System.out.println("duplicateReferencetables sql is " + sql);

      query.setParameter("param", referenceTables.getTableName().toLowerCase().trim());

      // initialize with 0 (for new records where no id has been generated
      // yet
      String referenceTablesId = "0";
      if (!StringUtil.isNullorNill(referenceTables.getId())) {
        referenceTablesId = referenceTables.getId();
      }

      if (!isNew) {
        query.setParameter("param2", referenceTablesId);
      }
      list = query.list();
      HibernateUtil.getSession().flush();
      HibernateUtil.getSession().clear();

      if (list.size() > 0) {
        return true;
      } else {
        return false;
      }

    } catch (Exception e) {
      // bugzilla 2154
      LogEvent.logError("ReferenceTablesDAOImpl", "duplicateReferenceTablesExists()", e.toString());
      throw new LIMSRuntimeException("Error in duplicateReferenceTablesExists()", e);
    }
  }
  protected ActionForward performAction(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response)
      throws Exception {
    DynaActionForm dynaForm = (DynaActionForm) form;

    HttpSession session = request.getSession();

    String forward = FWD_SUCCESS;

    ResultsEntryRoutingSwitchSessionHandler.switchOff(
        RESULTS_ENTRY_ROUTING_FROM_QAEVENTS_ENTRY_LINELISTING, session);

    String accessionNumber = (String) request.getParameter(ACCESSION_NUMBER);
    if (StringUtil.isNullorNill(accessionNumber)) {
      accessionNumber = (String) dynaForm.get("accessionNumber");
    }

    return getForward(mapping.findForward(forward), accessionNumber);
  }
  protected ActionForward performAction(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response)
      throws Exception {

    String forward = FWD_SUCCESS;
    request.setAttribute(ALLOW_EDITS_KEY, "true");
    request.setAttribute(PREVIOUS_DISABLED, "true");
    request.setAttribute(NEXT_DISABLED, "true");

    BaseActionForm dynaForm = (BaseActionForm) form;
    HttpSession session = request.getSession();

    String accessionNumber = (String) request.getParameter(ACCESSION_NUMBER);
    String viewMode = (String) dynaForm.get("viewMode");
    String fullScreenSection = (String) dynaForm.get("fullScreenSection");
    String multipleSampleMode = (String) dynaForm.get("multipleSampleMode");
    // bugzila 2555 initialize the form
    dynaForm.initialize(mapping);
    // initialize test management routing switch to on/initializes other switches to off
    QaEventRoutingSwitchSessionHandler.switchOn(
        QA_EVENTS_ENTRY_ROUTING_FROM_QAEVENTS_ENTRY_LINELISTING, session);

    // PropertyUtils.setProperty(dynaForm, "viewMode", viewMode);
    // PropertyUtils.setProperty(dynaForm, "fullScreenSection", fullScreenSection);
    session.setAttribute(QAEVENTS_ENTRY_PARAM_VIEW_MODE, viewMode);
    session.setAttribute(QAEVENTS_ENTRY_FULL_SCREEN_VIEW_SECTION, fullScreenSection);
    request.setAttribute(ACCESSION_NUMBER, accessionNumber);

    if (!StringUtil.isNullorNill(multipleSampleMode)) {
      forward = FWD_SUCCESS_MULTIPLE_SAMPLE_MODE;
    }
    return mapping.findForward(forward);
  }
  protected ActionForward performAction(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response)
      throws Exception {

    String forward = FWD_SUCCESS;
    request.setAttribute(ALLOW_EDITS_KEY, "true");

    BaseActionForm dynaForm = (BaseActionForm) form;
    // server-side validation (validation.xml)
    ActionMessages errors = dynaForm.validate(mapping, request);

    // bugzilla 2614 allow for NB domain samples
    String selectedTestId = "";

    String referenceTableId = SystemConfiguration.getInstance().getResultReferenceTableId();
    String refId = (String) dynaForm.get("noteRefId");

    String noteIds = (String) dynaForm.get("noteIds");
    String noteSubjects = (String) dynaForm.get("noteSubjects");
    String noteTexts = (String) dynaForm.get("noteTexts");
    String noteTypes = (String) dynaForm.get("noteTypes");
    String noteLastupdateds = (String) dynaForm.get("noteLastupdateds");

    List noteIdList = new ArrayList();
    List noteSubjectList = new ArrayList();
    List noteTextList = new ArrayList();
    List noteTypeList = new ArrayList();
    List noteLastupdatedList = new ArrayList();

    String textSeparator = SystemConfiguration.getInstance().getDefaultTextSeparator();

    NoteDAO noteDAO = new NoteDAOImpl();
    SystemUserDAO systemUserDAO = new SystemUserDAOImpl();
    // bugzilla 2571 go through ReferenceTablesDAO to get reference tables info
    ReferenceTablesDAO referenceTablesDAO = new ReferenceTablesDAOImpl();

    // get sysUserId from login module
    UserSessionData usd = (UserSessionData) request.getSession().getAttribute(USER_SESSION_DATA);
    String sysUserId = String.valueOf(usd.getSystemUserId());
    org.hibernate.Transaction tx = HibernateUtil.getSession().beginTransaction();

    try {

      textSeparator = StringUtil.convertStringToRegEx(textSeparator);

      SystemUser systemUser = new SystemUser();
      systemUser.setId(sysUserId);
      systemUserDAO.getData(systemUser);

      // get all the data required to forward to correct page

      // get analysis id from result
      ResultDAO resultDAO = new ResultDAOImpl();
      Result result = new Result();
      result.setId(refId);
      resultDAO.getData(result);

      String analysisId = result.getAnalysis().getId();

      AnalysisDAO analysisDAO = new AnalysisDAOImpl();
      Analysis analysis = new Analysis();
      analysis.setId(analysisId);
      analysisDAO.getData(analysis);

      // get test id from analysis
      selectedTestId = analysis.getTest().getId();

      // get domain from sample
      SampleItemDAO sampleItemDAO = new SampleItemDAOImpl();
      SampleItem sampleItem = new SampleItem();
      sampleItem.setId(analysis.getSampleItem().getId());
      sampleItemDAO.getData(sampleItem);

      SampleDAO sampleDAO = new SampleDAOImpl();
      Sample sample = new Sample();
      // bugzilla 1773 need to store sample not sampleId for use in sorting
      sample.setId(sampleItem.getSample().getId());
      sampleDAO.getData(sample);

      // bugzilla 2614 allow for NB domain samples
      // now that we have the domain (for forwarding to correct fail page)
      // validate note popup form data!
      try {
        // bugzilla 2254 moved loadListFromStringOfElements to StringUtil
        noteIdList = StringUtil.loadListFromStringOfElements(noteIds, textSeparator, false);
        noteLastupdatedList =
            StringUtil.loadListFromStringOfElements(noteLastupdateds, textSeparator, false);
        // these three need to be validated for empty strings
        noteSubjectList =
            StringUtil.loadListFromStringOfElements(noteSubjects, textSeparator, true);
        noteTextList = StringUtil.loadListFromStringOfElements(noteTexts, textSeparator, true);
        noteTypeList = StringUtil.loadListFromStringOfElements(noteTypes, textSeparator, true);

      } catch (Exception e) {
        // bugzilla 2154
        LogEvent.logError("ResultsEntryNotesUpdateAction", "performAction()", e.toString());
        String messageKey = "note.note";
        ActionError error = new ActionError("errors.invalid", getMessageForKey(messageKey), null);
        errors.add(ActionMessages.GLOBAL_MESSAGE, error);
        saveErrors(request, errors);
        forward = FWD_FAIL;

        return mapping.findForward(forward);
      }

      for (int i = 0; i < noteIdList.size(); i++) {
        Note note = new Note();

        String noteId = (String) noteIdList.get(i);
        note.setReferenceId(refId);
        // bugzilla 1922
        // bugzilla 2571 go through ReferenceTablesDAO to get reference tables info
        ReferenceTables referenceTables = new ReferenceTables();
        referenceTables.setId(referenceTableId);
        // bugzilla 2571
        referenceTablesDAO.getData(referenceTables);
        note.setReferenceTables(referenceTables);
        note.setSystemUser(systemUser);
        note.setSystemUserId(sysUserId);
        // 1926 for audit trail
        note.setSysUserId(sysUserId);

        if (noteId != null && !noteId.equals("0")) {
          note.setId((String) noteIdList.get(i));
          note.setSubject((String) noteSubjectList.get(i));
          note.setText((String) noteTextList.get(i));
          note.setNoteType((String) noteTypeList.get(i));

          Timestamp noteTimestamp = null;
          if (!StringUtil.isNullorNill((String) noteLastupdatedList.get(i))) {

            noteTimestamp = DateUtil.formatStringToTimestamp((String) noteLastupdatedList.get(i));
          }

          note.setLastupdated(noteTimestamp);

          // UPDATE
          noteDAO.updateData(note);
          // }

        } else {
          // this is a new note
          note.setSubject((String) noteSubjectList.get(i));
          note.setText((String) noteTextList.get(i));
          note.setNoteType((String) noteTypeList.get(i));
          // INSERT
          noteDAO.insertData(note);
        }
      }

      tx.commit();

      return getForward(mapping.findForward(forward), selectedTestId, analysisId);

    } catch (LIMSRuntimeException lre) {
      // bugzilla 2154
      LogEvent.logError("ResultsEntryNotesUpdateAction", "performAction()", lre.toString());
      tx.rollback();
      errors = new ActionMessages();
      ActionError error = null;
      if (lre.getException() instanceof org.hibernate.StaleObjectStateException) {
        error = new ActionError("errors.OptimisticLockException", null, null);
      } else {
        if (lre.getException() instanceof LIMSDuplicateRecordException) {
          java.util.Locale locale =
              (java.util.Locale)
                  request.getSession().getAttribute("org.apache.struts.action.LOCALE");
          String messageKey = "note.note";
          String msg =
              ResourceLocator.getInstance().getMessageResources().getMessage(locale, messageKey);
          error = new ActionError("errors.DuplicateRecord", msg, null);

        } else {
          error = new ActionError("errors.UpdateException", null, null);
        }
      }
      errors.add(ActionMessages.GLOBAL_MESSAGE, error);
      saveErrors(request, errors);
      request.setAttribute(Globals.ERROR_KEY, errors);

      // disable previous and next
      request.setAttribute(PREVIOUS_DISABLED, "true");
      request.setAttribute(NEXT_DISABLED, "true");

      // default forward fail
      forward = FWD_FAIL;

    } finally {
      HibernateUtil.closeSession();
    }
    if (forward.equals(FWD_FAIL)
        || forward.equals(FWD_FAIL_HUMAN)
        || forward.equals(FWD_FAIL_ANIMAL)) return mapping.findForward(forward);

    // initialize the form
    dynaForm.initialize(mapping);

    // we need this for subsequent actions to
    // get data related to note parent for forwarding to next page
    request.setAttribute("refId", refId);
    request.setAttribute(SELECTED_TEST_ID, selectedTestId);

    return mapping.findForward(forward);
  }
  // modified for efficiency bugzilla 1367
  public String validate(String targetId) throws LIMSRuntimeException {
    StringBuffer s = new StringBuffer();

    // bgm added StringUtil to check against a space being entered.
    if (!StringUtil.isNullorNill(targetId)) {
      ProjectDAO projectDAO = new ProjectDAOImpl();
      Project project = new Project();
      try {
        int i = Integer.parseInt(targetId);
        // bugzilla 2438
        project.setLocalAbbreviation(targetId.trim());

      } catch (NumberFormatException nfe) {
        // bugzilla 2154
        LogEvent.logError("ProjectIdOrNameValidationProvider", "validate()", nfe.toString());
        // if the id was not a number
        project = null;
      }

      if (project != null) {
        // bugzilla 2438
        project = projectDAO.getProjectByLocalAbbreviation(project, true);
      }
      // bugzilla 2112
      try {
        if (null != project) {
          // bugzilla 1978
          if (project.getIsActive().equals(YES)) {
            // This is particular to projId validation for HSE1 and HSE2:
            // the message appended to VALID is the projectName that
            // can then be displayed when User enters valid Project Id
            // (see humanSampleOne.jsp, humanSampleTwo.jsp)

            // bgm - bugzilla 1535 commented out s.append(project.getProjectName()); to check first
            if (null != project.getProjectName()) {
              s.append(VALID);
              s.append(project.getProjectName());
            } else s.append(INVALID);
          } else {
            s.append(INVALID);
          }
        } else {
          project = new Project();
          project.setId("");
          project.setProjectName(targetId.trim());
          project = projectDAO.getProjectByName(project, true, true);
          if (project != null) {
            s.append(VALID);
            // bugzilla 2438
            s.append(project.getLocalAbbreviation());
          } else {
            s.append(INVALID);
          }
        }
      } catch (Exception e) {
        // bugzilla 2154
        LogEvent.logError("ProjectIdOrNameValidationProvider", "validate()", e.toString());
        s.append(INVALID);
      }
    } else {
      // bugzilla 1697
      s.append(VALID);
    }

    /*
     * System.out.println("I am in projIdValidator returning " +
     * s.toString() + " targetId " + targetId);
     */
    return s.toString();
  }
  protected ActionForward performAction(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response)
      throws Exception {
    // The first job is to determine if we are coming to this action with an
    // ID parameter in the request. If there is no parameter, we are
    // creating a new TestAnalyte.
    // If there is a parameter present, we should bring up an existing
    // TestAnalyte to edit.
    TestAnalyteTestResultActionForm dynaForm = (TestAnalyteTestResultActionForm) form;

    String forward = FWD_SUCCESS;
    request.setAttribute(ALLOW_EDITS_KEY, "false");
    request.setAttribute(PREVIOUS_DISABLED, "true");
    request.setAttribute(NEXT_DISABLED, "true");

    // CHANGED
    // String selectedTestId = (String) request.getParameter("Test");

    List methods = new ArrayList();
    MethodDAO methodDAO = new MethodDAOImpl();
    methods = methodDAO.getAllMethods();

    // Get tests/testsections by user system id
    // bugzilla 2160
    UserTestSectionDAO userTestSectionDAO = new UserTestSectionDAOImpl();
    List testSections = userTestSectionDAO.getAllUserTestSections(request);
    // bugzilla 2291
    List tests = userTestSectionDAO.getAllUserTests(request, false);

    List selectedAnalyteTypes = new ArrayList();
    // bugzilla 1870
    List selectedAnalyteIsReportables = new ArrayList();
    List selectedAnalyteResultGroups = new ArrayList();
    List selectedAnalyteIds = new ArrayList();
    List selectedAnalyteNames = new ArrayList();
    List selectedTestAnalyteIds = new ArrayList();
    List testAnalyteLastupdatedList = new ArrayList();

    List testResultResultGroups = new ArrayList();
    List testResultResultGroupTypes = new ArrayList();
    List testResultValueList = new ArrayList();
    List dictionaryEntryIdList = new ArrayList();
    List flagsList = new ArrayList();
    // bugzilla 1845 add testResult sortOrder
    List sortList = new ArrayList();
    List significantDigitsList = new ArrayList();
    List quantLimitList = new ArrayList();
    List testResultIdList = new ArrayList();
    List testResultLastupdatedList = new ArrayList();
    Test test = new Test();

    // FIXED BUG - NEED TO REFRESH SELECTIONS ON GOING INTO FORM
    // get 3 drop down selections so we can repopulate
    // String selectedTestSectionId = (String) dynaForm
    // .get("selectedTestSectionId");
    // String selectedMethodId = (String) dynaForm.get("selectedMethodId");
    // String selectedTestId = (String) dynaForm.get("selectedTestId");

    String selectedTestId = null;
    String selectedTestSectionId = null;
    String selectedMethodId = null;
    // END BUG FIX

    // initialize the form
    dynaForm.initialize(mapping);
    dynaForm.resetLists();

    // bugzilla 1350 need to check if test has been selected so stray
    // components don't display
    if (!StringUtil.isNullorNill(selectedTestId)) {
      // if test is selected enable the save button
      request.setAttribute(ALLOW_EDITS_KEY, "true");
      test.setId(selectedTestId);
      TestDAO testDAO = new TestDAOImpl();
      testDAO.getData(test);

      TestAnalyteDAO testAnalyteDAO = new TestAnalyteDAOImpl();
      List testAnalytes = testAnalyteDAO.getAllTestAnalytesPerTest(test);

      TestResultDAO testResultDAO = new TestResultDAOImpl();
      List testResults = testResultDAO.getAllActiveTestResultsPerTest(test);

      DictionaryDAO dictDAO = new DictionaryDAOImpl();

      if (testAnalytes != null && testAnalytes.size() > 0) {

        for (int i = 0; i < testAnalytes.size(); i++) {
          TestAnalyte ta = (TestAnalyte) testAnalytes.get(i);
          selectedAnalyteTypes.add(ta.getTestAnalyteType());
          // bugzilla 1870
          selectedAnalyteIsReportables.add(ta.getIsReportable());
          if (ta.getResultGroup() != null) {
            selectedAnalyteResultGroups.add(ta.getResultGroup());
          } else {
            selectedAnalyteResultGroups.add("");
          }
          selectedAnalyteIds.add(ta.getAnalyte().getId());
          selectedAnalyteNames.add(ta.getAnalyte().getAnalyteName());
          selectedTestAnalyteIds.add(ta.getId());
        }

        if (testResults != null && testResults.size() > 0) {
          for (int i = 0; i < testResults.size(); i++) {
            TestResult tr = (TestResult) testResults.get(i);
            testResultIdList.add(tr.getId());
            testResultLastupdatedList.add(tr.getLastupdated());
            testResultResultGroups.add(tr.getResultGroup());
            testResultResultGroupTypes.add(tr.getTestResultType());
            if (tr.getTestResultType()
                .equals(SystemConfiguration.getInstance().getDictionaryType())) {
              dictionaryEntryIdList.add(tr.getValue());
              Dictionary dict = new Dictionary();
              dict.setId(tr.getValue());
              dictDAO.getData(dict);
              // bugzilla 1847: use dictEntryDisplayValue
              testResultValueList.add(dict.getDictEntryDisplayValue());
            } else {
              dictionaryEntryIdList.add("");
              testResultValueList.add(tr.getValue());
            }
            if (tr.getFlags() == null) {
              flagsList.add("");
            } else {
              flagsList.add(tr.getFlags());
            }
            // bugzilla 1845 add testResult sortOrder
            if (tr.getSortOrder() == null) {
              sortList.add("");
            } else {
              sortList.add(tr.getSortOrder());
            }
            if (tr.getSignificantDigits() == null) {
              significantDigitsList.add("");
            } else {
              significantDigitsList.add(tr.getSignificantDigits());
            }
            if (tr.getQuantLimit() == null) {
              quantLimitList.add("");
            } else {
              quantLimitList.add(tr.getQuantLimit());
            }
          }
        }
        isNew = false;
      } else {

        isNew = true;
      }
    } else {
      isNew = true;
    }

    PropertyUtils.setProperty(dynaForm, "selectedAnalyteTypes", selectedAnalyteTypes);
    // bugzilla 1870
    PropertyUtils.setProperty(
        dynaForm, "selectedAnalyteIsReportables", selectedAnalyteIsReportables);
    PropertyUtils.setProperty(dynaForm, "selectedAnalyteResultGroups", selectedAnalyteResultGroups);
    PropertyUtils.setProperty(dynaForm, "selectedAnalyteIds", selectedAnalyteIds);
    PropertyUtils.setProperty(dynaForm, "selectedTestAnalyteIds", selectedTestAnalyteIds);
    PropertyUtils.setProperty(dynaForm, "testAnalyteLastupdatedList", testAnalyteLastupdatedList);
    PropertyUtils.setProperty(dynaForm, "selectedAnalyteNames", selectedAnalyteNames);

    PropertyUtils.setProperty(dynaForm, "testResultResultGroups", testResultResultGroups);

    PropertyUtils.setProperty(dynaForm, "testResultResultGroupTypes", testResultResultGroupTypes);

    PropertyUtils.setProperty(dynaForm, "testResultValueList", testResultValueList);

    PropertyUtils.setProperty(dynaForm, "testResultIdList", testResultIdList);

    PropertyUtils.setProperty(dynaForm, "testResultLastupdatedList", testResultLastupdatedList);

    PropertyUtils.setProperty(dynaForm, "dictionaryEntryIdList", dictionaryEntryIdList);

    PropertyUtils.setProperty(dynaForm, "flagsList", flagsList);
    // bugzilla 1845 add testResult sortOrder
    PropertyUtils.setProperty(dynaForm, "sortList", sortList);

    PropertyUtils.setProperty(dynaForm, "significantDigitsList", significantDigitsList);

    PropertyUtils.setProperty(dynaForm, "quantLimitList", quantLimitList);

    PropertyUtils.setProperty(dynaForm, "test", (test == null ? new Test() : test));

    // sort three drop down lists
    Collections.sort(testSections, TestSectionComparator.NAME_COMPARATOR);

    // bugzilla 1844 - no longer sort by name but by description
    Collections.sort(tests, TestComparator.DESCRIPTION_COMPARATOR);
    Collections.sort(methods, MethodComparator.NAME_COMPARATOR);

    PropertyUtils.setProperty(dynaForm, "testSections", testSections);
    PropertyUtils.setProperty(dynaForm, "methods", methods);
    PropertyUtils.setProperty(dynaForm, "tests", tests);

    PropertyUtils.setProperty(dynaForm, "selectedTestSectionId", selectedTestSectionId);
    PropertyUtils.setProperty(dynaForm, "selectedMethodId", selectedMethodId);
    PropertyUtils.setProperty(dynaForm, "selectedTestId", selectedTestId);
    return mapping.findForward(forward);
  }
  protected ActionForward performAction(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response)
      throws Exception {

    String forward = FWD_SUCCESS;
    request.setAttribute(ALLOW_EDITS_KEY, TRUE);

    BaseActionForm dynaForm = (BaseActionForm) form;

    ActionMessages errors = dynaForm.validate(mapping, request);

    UserSessionData usd = (UserSessionData) request.getSession().getAttribute(USER_SESSION_DATA);
    String sysUserId = String.valueOf(usd.getSystemUserId());

    String birthDateForDisplay = dynaForm.getString("birthDateForDisplay");
    String birthTimeForDisplay = dynaForm.getString("birthTimeForDisplay");
    String format = "MM/dd/yyyy";
    java.sql.Timestamp dob = null;
    if ((birthDateForDisplay != null) && (birthDateForDisplay.length() > 0)) {
      java.text.SimpleDateFormat f = new java.text.SimpleDateFormat(format);
      dob = new java.sql.Timestamp(f.parse(birthDateForDisplay).getTime());

      if ((birthTimeForDisplay != null) && (birthTimeForDisplay.length() > 0)) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(dob);
        cal.set(
            Calendar.HOUR_OF_DAY, Integer.valueOf(birthTimeForDisplay.substring(0, 2)).intValue());
        cal.set(Calendar.MINUTE, Integer.valueOf(birthTimeForDisplay.substring(3, 5)).intValue());
        dob = new java.sql.Timestamp(cal.getTimeInMillis());
      }
    }

    String dateFirstFeedingForDisplay = dynaForm.getString("dateFirstFeedingForDisplay");
    String timeFirstFeedingForDisplay = dynaForm.getString("timeFirstFeedingForDisplay");
    java.sql.Timestamp dateFirstFeeding = null;
    if ((dateFirstFeedingForDisplay != null) && (dateFirstFeedingForDisplay.length() > 0)) {
      java.text.SimpleDateFormat f = new java.text.SimpleDateFormat(format);
      dateFirstFeeding = new java.sql.Timestamp(f.parse(dateFirstFeedingForDisplay).getTime());

      if ((timeFirstFeedingForDisplay != null) && (timeFirstFeedingForDisplay.length() > 0)) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(dob);
        cal.set(
            Calendar.HOUR_OF_DAY,
            Integer.valueOf(timeFirstFeedingForDisplay.substring(0, 2)).intValue());
        cal.set(
            Calendar.MINUTE,
            Integer.valueOf(timeFirstFeedingForDisplay.substring(3, 5)).intValue());
        dateFirstFeeding = new java.sql.Timestamp(cal.getTimeInMillis());
      }
    }

    String collectionDateForDisplay = dynaForm.getString("collectionDateForDisplay");
    String collectionTimeForDisplay = dynaForm.getString("collectionTimeForDisplay");
    java.sql.Timestamp collDate = null;
    if ((collectionDateForDisplay != null) && (collectionDateForDisplay.length() > 0)) {
      java.text.SimpleDateFormat f = new java.text.SimpleDateFormat(format);
      collDate = new java.sql.Timestamp(f.parse(collectionDateForDisplay).getTime());

      if ((collectionTimeForDisplay != null) && (collectionTimeForDisplay.length() > 0)) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(collDate);
        cal.set(
            Calendar.HOUR_OF_DAY,
            Integer.valueOf(collectionTimeForDisplay.substring(0, 2)).intValue());
        cal.set(
            Calendar.MINUTE, Integer.valueOf(collectionTimeForDisplay.substring(3, 5)).intValue());
        collDate = new java.sql.Timestamp(cal.getTimeInMillis());
      }
    }

    String dateTransfutionForDisplay = (String) dynaForm.getString("dateTransfutionForDisplay");
    java.sql.Timestamp dateTransfution = null;
    if ((dateTransfutionForDisplay != null) && (dateTransfutionForDisplay.length() > 0)) {
      java.text.SimpleDateFormat f = new java.text.SimpleDateFormat(format);
      dateTransfution = new java.sql.Timestamp(f.parse(dateTransfutionForDisplay).getTime());
    }

    String motherBirthDateForDisplay = (String) dynaForm.get("motherBirthDateForDisplay");
    java.sql.Timestamp motherBirthDate = null;
    if ((motherBirthDateForDisplay != null) && (motherBirthDateForDisplay.length() > 0)) {
      java.text.SimpleDateFormat f = new java.text.SimpleDateFormat(format);
      motherBirthDate = new java.sql.Timestamp(f.parse(motherBirthDateForDisplay).getTime());
    }

    org.hibernate.Transaction tx = HibernateUtil.getSession().beginTransaction();
    String accessionNumber = (String) dynaForm.get("accessionNumber");
    try {
      // Sample
      Sample sample = new Sample();
      SampleDAO sampleDAO = new SampleDAOImpl();
      sample.setSysUserId(sysUserId);
      sample.setAccessionNumber(accessionNumber);
      sampleDAO.getSampleByAccessionNumber(sample);
      sample.setBarCode((String) dynaForm.get("barcode"));
      sample.setStatus(SystemConfiguration.getInstance().getSampleStatusEntry2Complete());
      sample.setCollectionDate(collDate);
      sampleDAO.updateData(sample);

      // SampleHuman
      SampleHumanDAO sampleHumanDAO = new SampleHumanDAOImpl();
      SampleHuman sampleHuman = new SampleHuman();
      sampleHuman.setSampleId(sample.getId());
      sampleHumanDAO.getDataBySample(sampleHuman);

      // Patient - child
      Patient childPatient = new Patient();
      PatientDAO patientDAO = new PatientDAOImpl();
      Person childPerson = new Person();
      childPatient.setId(sampleHuman.getPatientId());
      patientDAO.getData(childPatient);

      // Person - child
      PersonDAO personDAO = new PersonDAOImpl();
      childPerson = childPatient.getPerson();
      personDAO.getData(childPerson);
      childPerson.setSysUserId(sysUserId);
      childPerson.setLastName((String) dynaForm.get("lastName"));
      childPerson.setFirstName((String) dynaForm.get("firstName"));
      personDAO.updateData(childPerson);

      childPatient.setSysUserId(sysUserId);
      childPatient.setBirthDate(dob);
      childPatient.setGender((String) dynaForm.get("gender"));
      patientDAO.updateData(childPatient);

      // PatientRelation
      PatientRelation patientRelation = new PatientRelation();
      PatientRelationDAO patientRelationDAO = new PatientRelationDAOImpl();
      patientRelation.setPatientIdSource(childPatient.getId());
      patientRelation = patientRelationDAO.getPatientRelationByChildId(patientRelation);
      Person motherPerson = new Person();
      Patient motherPatient = new Patient();
      if (!StringUtil.isNullorNill(patientRelation.getId())) {
        motherPatient.setId(patientRelation.getPatientId());
        patientDAO.getData(motherPatient);
        motherPerson = motherPatient.getPerson();
        personDAO.getData(motherPerson);
      }
      motherPerson.setLastName((String) dynaForm.get("motherLastName"));
      motherPerson.setFirstName((String) dynaForm.get("motherFirstName"));
      String motherHomePhone = (String) dynaForm.get("motherPhoneNumber");
      if ((motherHomePhone != null) && (motherHomePhone.length() > 0))
        motherHomePhone = StringUtil.formatPhone(motherHomePhone, null);
      motherPerson.setHomePhone(motherHomePhone);
      motherPerson.setStreetAddress((String) dynaForm.get("motherStreetAddress"));
      motherPerson.setCity((String) dynaForm.get("city"));
      motherPerson.setState((String) dynaForm.get("state"));
      motherPerson.setZipCode((String) dynaForm.get("zipCode"));
      motherPerson.setSysUserId(sysUserId);
      if (!StringUtil.isNullorNill(motherPerson.getId())) personDAO.updateData(motherPerson);
      else personDAO.insertData(motherPerson);

      motherPatient.setBirthDate(motherBirthDate);
      motherPatient.setPerson(motherPerson);
      motherPatient.setSysUserId(sysUserId);
      if (!StringUtil.isNullorNill(motherPatient.getId())) patientDAO.updateData(motherPatient);
      else patientDAO.insertData(motherPatient);

      patientRelation.setSysUserId(sysUserId);
      patientRelation.setPatientId(motherPatient.getId());

      String motherRelation = SystemConfiguration.getInstance().getNewbornPatientRelation();
      patientRelation.setRelation(motherRelation);
      if (!StringUtil.isNullorNill(patientRelation.getId()))
        patientRelationDAO.updateData(patientRelation);
      else patientRelationDAO.insertData(patientRelation);

      // SampleNewborn
      SampleNewborn sampleNewborn = new SampleNewborn();
      SampleNewbornDAO sampleNewbornDAO = new SampleNewbornDAOImpl();
      sampleNewborn.setId(sampleHuman.getId());
      sampleNewbornDAO.getData(sampleNewborn);
      sampleNewborn.setSysUserId(sysUserId);
      sampleNewborn.setMedicalRecordNumber((String) dynaForm.get("medicalRecordNumber"));
      sampleNewborn.setYnumber((String) dynaForm.get("ynumber"));
      sampleNewborn.setYellowCard((String) dynaForm.get("yellowCard"));
      sampleNewborn.setWeight((String) dynaForm.get("birthWeight"));
      sampleNewborn.setMultiBirth((String) dynaForm.get("multipleBirth"));
      sampleNewborn.setBirthOrder((String) dynaForm.get("birthOrder"));
      sampleNewborn.setGestationalWeek((Double) dynaForm.get("gestationalWeek"));
      sampleNewborn.setDateFirstFeeding(dateFirstFeeding);
      sampleNewborn.setBreast((String) dynaForm.get("breast"));
      sampleNewborn.setTpn((String) dynaForm.get("tpn"));
      sampleNewborn.setFormula((String) dynaForm.get("formula"));
      sampleNewborn.setMilk((String) dynaForm.get("milk"));
      sampleNewborn.setSoy((String) dynaForm.get("soy"));
      sampleNewborn.setJaundice((String) dynaForm.get("jaundice"));
      sampleNewborn.setAntibiotic((String) dynaForm.get("antibiotic"));
      sampleNewborn.setTransfused((String) dynaForm.get("transfused"));
      sampleNewborn.setNicu((String) dynaForm.get("nicuPatient"));
      sampleNewborn.setBirthDefect((String) dynaForm.get("birthDefect"));
      sampleNewborn.setPregnancyComplication((String) dynaForm.get("pregnancyComplication"));
      sampleNewborn.setDeceasedSibling((String) dynaForm.get("deceasedSibling"));
      sampleNewborn.setCauseOfDeath((String) dynaForm.get("causeOfDeath"));
      sampleNewborn.setFamilyHistory((String) dynaForm.get("familyHistory"));
      sampleNewborn.setOther((String) dynaForm.get("other"));
      sampleNewborn.setDateTransfution(dateTransfution);
      if (!StringUtil.isNullorNill(sampleNewborn.getId()))
        sampleNewbornDAO.updateData(sampleNewborn);
      else {
        sampleNewborn.setId(sampleHuman.getId());
        sampleNewbornDAO.insertData(sampleNewborn);
      }

      // Provider
      Provider provider = new Provider();
      Person providerPerson = new Person();
      ProviderDAO providerDAO = new ProviderDAOImpl();
      if (!StringUtil.isNullorNill(sampleHuman.getProviderId())) {
        provider.setId(sampleHuman.getProviderId());
        providerDAO.getData(provider);
      }

      if (!StringUtil.isNullorNill(sampleHuman.getProviderId())) {
        provider.setId(sampleHuman.getProviderId());
        providerDAO.getData(provider);
        providerPerson = (Person) provider.getPerson();
      }

      // SampleOrganization
      Organization o = new Organization();
      OrganizationDAO organizationDAO = new OrganizationDAOImpl();
      o.setOrganizationLocalAbbreviation((String) dynaForm.get("submitterNumber"));
      o = organizationDAO.getOrganizationByLocalAbbreviation(o, true);
      SampleOrganization sampleOrganization = new SampleOrganization();
      SampleOrganizationDAO sampleOrganizationDAO = new SampleOrganizationDAOImpl();
      sampleOrganizationDAO.getDataBySample(sampleOrganization);
      sampleOrganization.setSample(sample);
      sampleOrganization.setOrganization(o);
      sampleOrganization.setSysUserId(sysUserId);
      if (!StringUtil.isNullorNill(sampleOrganization.getId()))
        sampleOrganizationDAO.updateData(sampleOrganization);
      else sampleOrganizationDAO.insertData(sampleOrganization);

      // Person - provider
      providerPerson.setSysUserId(sysUserId);
      providerPerson.setFirstName((String) dynaForm.get("physicianFirstName"));
      providerPerson.setLastName((String) dynaForm.get("physicianLastName"));
      String providerHomePhone = (String) dynaForm.get("physicianPhoneNumber");
      if ((providerHomePhone != null) && (providerHomePhone.length() > 0))
        providerHomePhone = StringUtil.formatPhone(providerHomePhone, null);
      providerPerson.setHomePhone(providerHomePhone);
      if (!StringUtil.isNullorNill(providerPerson.getId())) personDAO.updateData(providerPerson);
      else personDAO.insertData(providerPerson);

      provider.setPerson(providerPerson);
      provider.setExternalId(BLANK);
      provider.setSysUserId(sysUserId);
      if (!StringUtil.isNullorNill(provider.getId())) providerDAO.updateData(provider);
      else providerDAO.insertData(provider);

      sampleHuman.setProviderId(provider.getId());
      sampleHuman.setSysUserId(sysUserId);
      sampleHumanDAO.updateData(sampleHuman);

      tx.commit();
    } catch (LIMSRuntimeException lre) {
      LogEvent.logError("NewbornSampleFullUpdateAction", "performAction()", lre.toString());
      tx.rollback();
      errors = new ActionMessages();
      ActionError error = null;
      if (lre.getException() instanceof org.hibernate.StaleObjectStateException) {
        error = new ActionError("errors.OptimisticLockException", null, null);
      } else {
        error = new ActionError("errors.UpdateException", null, null);
      }
      errors.add(ActionMessages.GLOBAL_MESSAGE, error);
      saveErrors(request, errors);
      request.setAttribute(Globals.ERROR_KEY, errors);
      request.setAttribute(ALLOW_EDITS_KEY, "false");
      forward = FWD_FAIL;

    } finally {
      HibernateUtil.closeSession();
    }
    if (forward.equals(FWD_FAIL)) return mapping.findForward(forward);

    // Trigger QA if birthWeight < 200 grams
    int birthWeight = Integer.parseInt((String) dynaForm.get("birthWeight"));
    if ((birthWeight > 0) && (birthWeight < 200)) {
      forward = FWD_SUCCESS_QA_EVENTS_ENTRY;
      return getForward(mapping.findForward(forward), accessionNumber);
    }

    return mapping.findForward(FWD_SUCCESS);
  }
Exemplo n.º 10
0
  protected ActionForward performAction(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response)
      throws Exception {
    // The first job is to determine if we are coming to this action with an
    // ID parameter in the request. If there is no parameter, we are
    // creating a new Scriptlet.
    // If there is a parameter present, we should bring up an existing
    // Scriptlet to edit.
    String forward = FWD_SUCCESS;
    request.setAttribute(ALLOW_EDITS_KEY, "true");
    request.setAttribute(PREVIOUS_DISABLED, "false");
    request.setAttribute(NEXT_DISABLED, "false");

    String id = request.getParameter(ID);

    if (StringUtil.isNullorNill(id) || "0".equals(id)) {
      isNew = true;
    } else {
      isNew = false;
    }

    BaseActionForm dynaForm = (BaseActionForm) form;

    // server-side validation (validation.xml)
    ActionMessages errors = dynaForm.validate(mapping, request);
    if (errors != null && errors.size() > 0) {
      saveErrors(request, errors);
      // since we forward to jsp - not Action we don't need to repopulate
      // the lists here
      return mapping.findForward(FWD_FAIL);
    }

    String start = (String) request.getParameter("startingRecNo");
    String direction = (String) request.getParameter("direction");

    Scriptlet scriptlet = new Scriptlet();
    // get sysUserId from login module
    UserSessionData usd = (UserSessionData) request.getSession().getAttribute(USER_SESSION_DATA);
    String sysUserId = String.valueOf(usd.getSystemUserId());
    scriptlet.setSysUserId(sysUserId);

    // populate valueholder from form
    PropertyUtils.copyProperties(scriptlet, dynaForm);

    try {

      ScriptletDAO scriptletDAO = new ScriptletDAOImpl();

      if (!isNew) {
        // UPDATE
        scriptletDAO.updateData(scriptlet);

      } else {
        // INSERT
        scriptletDAO.insertData(scriptlet);
      }
    } catch (LIMSRuntimeException lre) {
      // bugzilla 2154
      LogEvent.logError("ScriptletUpdateAction", "performAction()", lre.toString());
      request.setAttribute(IActionConstants.REQUEST_FAILED, true);
      errors = new ActionMessages();
      java.util.Locale locale =
          (java.util.Locale) request.getSession().getAttribute("org.apache.struts.action.LOCALE");
      ActionError error = null;
      if (lre.getException() instanceof org.hibernate.StaleObjectStateException) {
        // how can I get popup instead of struts error at the top of
        // page?
        // ActionMessages errors = dynaForm.validate(mapping, request);
        error = new ActionError("errors.OptimisticLockException", null, null);
      } else {
        // bugzilla 1482
        if (lre.getException() instanceof LIMSDuplicateRecordException) {
          String messageKey = "scriptlet.scriptletName";
          String msg =
              ResourceLocator.getInstance().getMessageResources().getMessage(locale, messageKey);
          error = new ActionError("errors.DuplicateRecord", msg, null);

        } else {
          error = new ActionError("errors.UpdateException", null, null);
        }
      }
      errors.add(ActionMessages.GLOBAL_MESSAGE, error);
      saveErrors(request, errors);
      request.setAttribute(Globals.ERROR_KEY, errors);
      // bugzilla 1485: allow change and try updating again (enable save button)
      // request.setAttribute(IActionConstants.ALLOW_EDITS_KEY, "false");
      // disable previous and next
      request.setAttribute(PREVIOUS_DISABLED, "true");
      request.setAttribute(NEXT_DISABLED, "true");
      forward = FWD_FAIL;
    }
    if (forward.equals(FWD_FAIL)) return mapping.findForward(forward);

    // initialize the form
    dynaForm.initialize(mapping);
    // repopulate the form from valueholder
    PropertyUtils.copyProperties(dynaForm, scriptlet);

    if ("true".equalsIgnoreCase(request.getParameter("close"))) {
      forward = FWD_CLOSE;
    }

    if (scriptlet.getId() != null && !scriptlet.getId().equals("0")) {
      request.setAttribute(ID, scriptlet.getId());
    }

    // bugzilla 1400
    if (isNew) forward = FWD_SUCCESS_INSERT;
    // bugzilla 1467 added direction for redirect to NextPreviousAction
    return getForward(mapping.findForward(forward), scriptlet.getId(), start, direction);
  }
  protected List populateHistoryList(
      HttpServletRequest request,
      List historyRecords,
      String rootNodeName,
      String xslMappingFileName)
      throws LIMSRuntimeException {
    List list = new ArrayList();
    try {
      SystemUserDAO systemUserDAO = new SystemUserDAOImpl();
      AuditTrailDAO auditTrailDAO = new AuditTrailDAOImpl();

      for (int i = 0; i < historyRecords.size(); i++) {

        History historyRecord = (History) historyRecords.get(i);
        Timestamp date = historyRecord.getTimestamp();
        String stringLocale = SystemConfiguration.getInstance().getDefaultLocale().toString();
        String dateForDisplay = DateUtil.convertTimestampToStringDateAndTime(date, stringLocale);

        SystemUser systemUser = new SystemUser();
        systemUser.setId(historyRecord.getSysUserId());
        systemUserDAO.getData(systemUser);
        String blob = null;
        if (!historyRecord.getActivity().equals(AUDIT_TRAIL_INSERT)) {
          blob = auditTrailDAO.retrieveBlobData(historyRecord.getId());
        }

        // this is temporary until 2593 has been completed

        if (historyRecord.getActivity().equals(IActionConstants.AUDIT_TRAIL_UPDATE)) {
          blob = "<" + rootNodeName + ">" + blob + "</" + rootNodeName + ">";
        }

        if (!StringUtil.isNullorNill(blob)) {
          HistoryXmlHelper historyXmlHelper = new HistoryXmlHelper();
          historyXmlHelper.setActivity(historyRecord.getActivity());
          historyXmlHelper.setUserName(systemUser.getNameForDisplay());

          String media = null, title = null, charset = null, xsldata = "";
          ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
          try {

            //						NOTE!!!!
            //						in order to run this in oc4j I needed to do the following:
            // add this to OC4J startup:
            // -Djavax.xml.transform.TransformerFactory=org.apache.xalan.processor.TransformerFactoryImpl
            // to make sure that oc4j uses correct XSL processor (else it could not handle "function
            // extensions" used to bring in MessageResources labels
            // place xalan.jar, xml-apis.jar, XercesImpl.jar into the applib folder of the oc4j
            // installation

            TransformerFactory tFactory = TransformerFactory.newInstance();

            HttpSession session = request.getSession();
            ServletContext context = session.getServletContext();

            File xslFile =
                new File(context.getRealPath("/WEB-INF/transformation/" + xslMappingFileName));

            Source stylesheet = new StreamSource(xslFile);

            Transformer transformer = tFactory.newTransformer(stylesheet);

            System.out.println("This is blob " + blob);
            transformer.transform(
                new StreamSource(new StringReader(blob)), new StreamResult(outputStream));

          } catch (TransformerConfigurationException tce) {
            tce.printStackTrace();
          } catch (TransformerException te) {
            te.printStackTrace();
          } catch (Exception e) {
            e.printStackTrace();
          }

          System.out.println("This is xml " + outputStream.toString());
          historyXmlHelper.setChange(outputStream.toString());

          historyXmlHelper.setDate(dateForDisplay);

          if (!StringUtil.isNullorNill(historyXmlHelper.getChange())) {
            historyXmlHelper.setChange(historyXmlHelper.getChange().trim());
          }

          if (!StringUtil.isNullorNill(historyXmlHelper.getChange())) {
            list.add(historyXmlHelper);
          }
        }
      }
    } catch (Exception e) {
      throw new LIMSRuntimeException(e);
    }
    return list;
  }
  protected ActionForward performAction(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response)
      throws Exception {
    String forward = FWD_SUCCESS;
    BaseActionForm dynaForm = (BaseActionForm) form;
    ActionMessages errors = null;

    request.setAttribute(ALLOW_EDITS_KEY, "false");
    request.setAttribute(PREVIOUS_DISABLED, "true");
    request.setAttribute(NEXT_DISABLED, "true");

    String accessionNumber = (String) dynaForm.getString("accessionNumber");
    SampleXmlHelper sampleXmlHelper = new SampleXmlHelper();

    if (!StringUtil.isNullorNill(accessionNumber)) {
      Sample sample = new Sample();
      SampleDAO sampleDAO = new SampleDAOImpl();
      sample.setAccessionNumber(accessionNumber);

      List testTestAnalytes = new ArrayList();
      try {
        sampleDAO.getSampleByAccessionNumber(sample);

        if (!StringUtil.isNullorNill(sample.getStatus())
            && sample
                .getStatus()
                .equals(SystemConfiguration.getInstance().getSampleStatusLabelPrinted())) {
          dynaForm.set("accessionNumber", accessionNumber);
          request.setAttribute(ALLOW_EDITS_KEY, "false");
          return mapping.findForward(FWD_FAIL);
        }

      } catch (LIMSRuntimeException lre) {

        LogEvent.logError(
            "AuditTrailReportBySampleProcessAction", "performAction()", lre.toString());
        errors = new ActionMessages();
        ActionError error = null;
        error = new ActionError("errors.GetException", null, null);
        errors.add(ActionMessages.GLOBAL_MESSAGE, error);
        saveErrors(request, errors);
        request.setAttribute(Globals.ERROR_KEY, errors);
        request.setAttribute(ALLOW_EDITS_KEY, "false");
        return mapping.findForward(FWD_FAIL);
      }

      String domain = sample.getDomain();

      String humanDomain = SystemConfiguration.getInstance().getHumanDomain();

      String animalDomain = SystemConfiguration.getInstance().getAnimalDomain();

      if (domain != null && domain.equals(humanDomain)) {
        // go to human view

        Patient patient = new Patient();
        Person patientPerson = new Person();
        Provider provider = new Provider();
        Person providerPerson = new Person();
        SampleHuman sampleHuman = new SampleHuman();
        SampleOrganization sampleOrganization = new SampleOrganization();
        Organization organization = new Organization();
        List sampleProjects = new ArrayList();
        Project project = new Project();
        Project project2 = new Project();
        SampleItem sampleItem = new SampleItem();

        try {

          PatientDAO patientDAO = new PatientDAOImpl();
          ProviderDAO providerDAO = new ProviderDAOImpl();
          SampleItemDAO sampleItemDAO = new SampleItemDAOImpl();
          SampleHumanDAO sampleHumanDAO = new SampleHumanDAOImpl();
          SampleOrganizationDAO sampleOrganizationDAO = new SampleOrganizationDAOImpl();
          AuditTrailDAO auditTrailDAO = new AuditTrailDAOImpl();
          SystemUserDAO systemUserDAO = new SystemUserDAOImpl();

          if (!StringUtil.isNullorNill(sample.getId())) {
            sampleHuman.setSampleId(sample.getId());
            sampleHumanDAO.getDataBySample(sampleHuman);
            sampleOrganization.setSampleId(sample.getId());
            sampleOrganizationDAO.getDataBySample(sampleOrganization);
            sampleItem.setSample(sample);
            sampleItemDAO.getDataBySample(sampleItem);

            if (sampleHuman != null) {
              if (sampleHuman.getPatientId() != null) {
                patient.setId(sampleHuman.getPatientId());
                patientDAO.getData(patient);
                patientPerson = patient.getPerson();
                provider.setId(sampleHuman.getProviderId());
                providerDAO.getData(provider);
                providerPerson = provider.getPerson();
              }
            }
          }
          organization = (Organization) sampleOrganization.getOrganization();
          sampleProjects = sample.getSampleProjects();

          if (sampleProjects != null && sampleProjects.size() > 0) {
            SampleProject sampleProject = (SampleProject) sampleProjects.get(0);
            project = sampleProject.getProject();
            if (sampleProjects.size() > 1) {
              SampleProject sampleProject2 = (SampleProject) sampleProjects.get(1);
              project2 = sampleProject2.getProject();
            }
          }

          String tableName = "SAMPLE";
          ReferenceTablesDAO referenceTablesDAO = new ReferenceTablesDAOImpl();
          ReferenceTables referenceTables = new ReferenceTables();
          referenceTables.setTableName(tableName);
          ReferenceTables rt = referenceTablesDAO.getReferenceTableByName(referenceTables);

          PropertyUtils.copyProperties(sampleXmlHelper, sample);

          // String data = auditTrailDAO.retrieveBlobData(sample.getId());
          // String data = auditTrailDAO.retrieveBlobData("9446");
          History history = new History();
          history.setReferenceId(sample.getId());
          history.setReferenceTable(rt.getId());
          List historyRecords = auditTrailDAO.getHistoryByRefIdAndRefTableId(history);

          List sampleHistoryRecords =
              populateHistoryList(request, historyRecords, "sample", "sampleHistoryMapping.xsl");
          sampleXmlHelper.setHistoryRecords((ArrayList) sampleHistoryRecords);

          tableName = "SAMPLE_ITEM";
          referenceTables = new ReferenceTables();
          referenceTables.setTableName(tableName);
          rt = referenceTablesDAO.getReferenceTableByName(referenceTables);
          history = new History();
          history.setReferenceId(sampleItem.getId());
          history.setReferenceTable(rt.getId());
          historyRecords = auditTrailDAO.getHistoryByRefIdAndRefTableId(history);

          List sampleItemHistoryRecords =
              populateHistoryList(
                  request, historyRecords, "sampleItem", "sampleItemHistoryMapping.xsl");
          sampleXmlHelper.addHistoryRecords((ArrayList) sampleItemHistoryRecords);

          tableName = "PATIENT";
          referenceTables = new ReferenceTables();
          referenceTables.setTableName(tableName);
          rt = referenceTablesDAO.getReferenceTableByName(referenceTables);
          history = new History();
          history.setReferenceId(patient.getId());
          history.setReferenceTable(rt.getId());
          historyRecords = auditTrailDAO.getHistoryByRefIdAndRefTableId(history);

          List patientHistoryRecords =
              populateHistoryList(request, historyRecords, "patient", "patientHistoryMapping.xsl");
          sampleXmlHelper.addHistoryRecords((ArrayList) patientHistoryRecords);

          tableName = "PERSON";
          referenceTables = new ReferenceTables();
          referenceTables.setTableName(tableName);
          rt = referenceTablesDAO.getReferenceTableByName(referenceTables);
          history = new History();
          history.setReferenceId(patientPerson.getId());
          history.setReferenceTable(rt.getId());
          historyRecords = auditTrailDAO.getHistoryByRefIdAndRefTableId(history);

          // List patientPersonHistoryRecords = populateHistoryList(request, historyRecords,
          // "person", "personHistoryMapping.xsl");
          // sampleXmlHelper.addHistoryRecords((ArrayList)patientPersonHistoryRecords);

          tableName = "PERSON";
          referenceTables = new ReferenceTables();
          referenceTables.setTableName(tableName);
          rt = referenceTablesDAO.getReferenceTableByName(referenceTables);
          history = new History();
          history.setReferenceId(providerPerson.getId());
          history.setReferenceTable(rt.getId());
          historyRecords = auditTrailDAO.getHistoryByRefIdAndRefTableId(history);

          // List providerPersonHistoryRecords = populateHistoryList(request, historyRecords,
          // "person", "personHistoryMapping.xsl");
          // sampleXmlHelper.addHistoryRecords((ArrayList)providerPersonHistoryRecords);

          tableName = "SAMPLE_PROJECTS";
          referenceTables = new ReferenceTables();
          referenceTables.setTableName(tableName);
          rt = referenceTablesDAO.getReferenceTableByName(referenceTables);
          history = new History();
          history.setReferenceId(providerPerson.getId());
          history.setReferenceTable(rt.getId());
          historyRecords = auditTrailDAO.getHistoryByRefIdAndRefTableId(history);

          List sampleProjectHistoryRecords =
              populateHistoryList(
                  request, historyRecords, "sampleProject", "sampleProjectHistoryMapping.xsl");
          sampleXmlHelper.addHistoryRecords((ArrayList) sampleProjectHistoryRecords);

          // initialize the form
          dynaForm.initialize(mapping);

          tableName = "SAMPLE_ORGANIZATION";
          referenceTables = new ReferenceTables();
          referenceTables.setTableName(tableName);
          rt = referenceTablesDAO.getReferenceTableByName(referenceTables);
          history = new History();
          history.setReferenceId(sampleOrganization.getId());
          history.setReferenceTable(rt.getId());
          historyRecords = auditTrailDAO.getHistoryByRefIdAndRefTableId(history);

          List sampleOrganizationHistoryRecords =
              populateHistoryList(
                  request,
                  historyRecords,
                  "sampleOrganization",
                  "sampleOrganizationHistoryMapping.xsl");
          sampleXmlHelper.addHistoryRecords((ArrayList) sampleOrganizationHistoryRecords);

          List historyRecordsForSorting = sampleXmlHelper.getHistoryRecords();

          Collections.sort(historyRecordsForSorting, HistoryComparator.NAME_COMPARATOR);

          String savedUserName = "";
          List dateSortList = new ArrayList();
          List finalList = new ArrayList();
          // now within name sort by date desc
          for (int i = 0; i < historyRecordsForSorting.size(); i++) {
            // break down into chunks by name
            HistoryXmlHelper hist = (HistoryXmlHelper) historyRecordsForSorting.get(i);

            if (i > 0 && !hist.getUserName().equals(savedUserName)) {
              // now sort chunk so far
              Collections.sort(dateSortList, HistoryComparator.DATE_COMPARATOR);
              finalList.addAll(dateSortList);
              dateSortList.clear();
            }
            dateSortList.add(hist);
            savedUserName = hist.getUserName();
          }

          if (dateSortList != null && dateSortList.size() > 0) {
            Collections.sort(dateSortList, HistoryComparator.DATE_COMPARATOR);
            finalList.addAll(dateSortList);
            dateSortList.clear();
          }

          sampleXmlHelper.setHistoryRecords((ArrayList) finalList);

          // initialize the form
          dynaForm.initialize(mapping);

        } catch (LIMSRuntimeException lre) {
          // if error then forward to fail and don't update to blank
          // page
          // = false
          // bugzilla 2154
          LogEvent.logError("ResultsEntryViewAction", "performAction()", lre.toString());
          errors = new ActionMessages();
          ActionError error = null;
          error = new ActionError("errors.GetException", null, null);
          errors.add(ActionMessages.GLOBAL_MESSAGE, error);
          saveErrors(request, errors);
          request.setAttribute(Globals.ERROR_KEY, errors);
          request.setAttribute(ALLOW_EDITS_KEY, "false");
          return mapping.findForward(FWD_FAIL);
        }

        // populate form from valueholder
        // PropertyUtils.setProperty(dynaForm, "sampleLastupdated", sample
        // .getLastupdated());
        PropertyUtils.setProperty(dynaForm, "patientFirstName", patientPerson.getFirstName());
        PropertyUtils.setProperty(dynaForm, "patientLastName", patientPerson.getLastName());
        PropertyUtils.setProperty(dynaForm, "patientId", patient.getExternalId());

        PropertyUtils.setProperty(dynaForm, "gender", patient.getGender());

        PropertyUtils.setProperty(dynaForm, "chartNumber", patient.getChartNumber());

        PropertyUtils.setProperty(
            dynaForm, "birthDateForDisplay", (String) patient.getBirthDateForDisplay());
        TypeOfSample typeOfSample = sampleItem.getTypeOfSample();
        SourceOfSample sourceOfSample = sampleItem.getSourceOfSample();
        if (typeOfSample == null) {
          PropertyUtils.setProperty(dynaForm, "typeOfSample", new TypeOfSample());
        } else {
          PropertyUtils.setProperty(dynaForm, "typeOfSample", typeOfSample);
        }
        if (sourceOfSample == null) {
          PropertyUtils.setProperty(dynaForm, "sourceOfSample", new SourceOfSample());
        } else {
          PropertyUtils.setProperty(dynaForm, "sourceOfSample", sourceOfSample);
        }

        PropertyUtils.setProperty(dynaForm, "sourceOther", sampleItem.getSourceOther());
        PropertyUtils.setProperty(
            dynaForm, "receivedDateForDisplay", (String) sample.getReceivedDateForDisplay());
        PropertyUtils.setProperty(
            dynaForm, "collectionDateForDisplay", (String) sample.getCollectionDateForDisplay());

        PropertyUtils.setProperty(
            dynaForm, "collectionTimeForDisplay", (String) sample.getCollectionTimeForDisplay());

        PropertyUtils.setProperty(
            dynaForm, "referredCultureFlag", (String) sample.getReferredCultureFlag());

        PropertyUtils.setProperty(
            dynaForm, "stickerReceivedFlag", (String) sample.getStickerReceivedFlag());

        if (organization == null) {
          PropertyUtils.setProperty(dynaForm, "organization", new Organization());
        } else {
          PropertyUtils.setProperty(dynaForm, "organization", organization);
        }

        if (project == null) {
          PropertyUtils.setProperty(dynaForm, "project", new Project());
        } else {
          PropertyUtils.setProperty(dynaForm, "project", project);
        }

        if (project2 == null) {
          PropertyUtils.setProperty(dynaForm, "project2", new Project());
        } else {
          PropertyUtils.setProperty(dynaForm, "project2", project2);
        }

        // reload accession number
        PropertyUtils.setProperty(dynaForm, "accessionNumber", accessionNumber);
        PropertyUtils.setProperty(dynaForm, "domain", domain);

        PropertyUtils.setProperty(dynaForm, "sampleXmlHelper", sampleXmlHelper);

        forward = FWD_SUCCESS_HUMAN;
      } else if (domain != null && domain.equals(animalDomain)) {
        // go to animal view
        // System.out.println("Going to animal view");
        forward = FWD_SUCCESS_ANIMAL;
      } else {
        forward = FWD_SUCCESS;
      }
    }

    return mapping.findForward(forward);
  }
Exemplo n.º 13
0
  protected ActionForward performAction(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response)
      throws Exception {
    // The first job is to determine if we are coming to this action with an
    // ID parameter in the request. If there is no parameter, we are
    // creating a new Analyte.
    // If there is a parameter present, we should bring up an existing
    // Analyte to edit.
    String forward = FWD_SUCCESS;
    request.setAttribute(ALLOW_EDITS_KEY, "true");
    request.setAttribute(PREVIOUS_DISABLED, "false");
    request.setAttribute(NEXT_DISABLED, "false");

    String id = request.getParameter(ID);

    if (StringUtil.isNullorNill(id) || "0".equals(id)) {
      isNew = true;
    } else {
      isNew = false;
    }

    BaseActionForm dynaForm = (BaseActionForm) form;

    String start = (String) request.getParameter("startingRecNo");
    String direction = (String) request.getParameter("direction");

    // System.out.println("This is ID from request " + id);
    Panel panel = new Panel();

    panel.setId(id);
    try {

      PanelDAO panelDAO = new PanelDAOImpl();
      // retrieve analyte by id since the name may have changed
      panelDAO.getData(panel);

      if (FWD_NEXT.equals(direction)) {
        // bugzilla 1427 pass in name not id
        List panels = panelDAO.getNextPanelRecord(panel.getPanelName());
        if (panels != null && panels.size() > 0) {
          panel = (Panel) panels.get(0);
          panelDAO.getData(panel);
          if (panels.size() < 2) {
            // disable next button
            request.setAttribute(NEXT_DISABLED, "true");
          }
          id = panel.getId();
        } else {
          // just disable next button
          request.setAttribute(NEXT_DISABLED, "true");
        }
      }

      if (FWD_PREVIOUS.equals(direction)) {
        // bugzilla 1427 pass in name not id
        List panels = panelDAO.getPreviousPanelRecord(panel.getPanelName());
        if (panels != null && panels.size() > 0) {
          panel = (Panel) panels.get(0);
          panelDAO.getData(panel);
          if (panels.size() < 2) {
            // disable previous button
            request.setAttribute(PREVIOUS_DISABLED, "true");
          }
          id = panel.getId();
        } else {
          // just disable next button
          request.setAttribute(PREVIOUS_DISABLED, "true");
        }
      }

    } catch (LIMSRuntimeException lre) {
      // bugzilla 2154
      LogEvent.logError("PanelNextPreviousAction", "performAction()", lre.toString());
      request.setAttribute(ALLOW_EDITS_KEY, "false");
      // disable previous and next
      request.setAttribute(PREVIOUS_DISABLED, "true");
      request.setAttribute(NEXT_DISABLED, "true");
      forward = FWD_FAIL;
    }
    if (forward.equals(FWD_FAIL)) return mapping.findForward(forward);

    if (panel.getId() != null && !panel.getId().equals("0")) {
      request.setAttribute(ID, panel.getId());
    }

    return getForward(mapping.findForward(forward), id, start);
  }
Exemplo n.º 14
0
  protected List createMenuList(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response)
      throws Exception {

    // System.out.println("I am in OrganizationMenuAction createMenuList()");

    List organizations = new ArrayList();

    String stringStartingRecNo = (String) request.getAttribute("startingRecNo");
    int startingRecNo = Integer.parseInt(stringStartingRecNo);

    // bugzilla 2372
    String searchString = (String) request.getParameter("searchString");

    String doingSearch = (String) request.getParameter("search");

    OrganizationDAO organizationDAO = new OrganizationDAOImpl();

    if (!StringUtil.isNullorNill(doingSearch) && doingSearch.equals(YES))
      organizations = organizationDAO.getPagesOfSearchedOrganizations(startingRecNo, searchString);
    else organizations = organizationDAO.getPageOfOrganizations(startingRecNo);

    request.setAttribute("menuDefinition", "OrganizationMenuDefinition");

    // bugzilla 1411 set pagination variables
    // bugzilla 2372 set pagination variables for searched results
    if (!StringUtil.isNullorNill(doingSearch) && doingSearch.equals(YES))
      request.setAttribute(
          MENU_TOTAL_RECORDS,
          String.valueOf(organizationDAO.getTotalSearchedOrganizationCount(searchString)));
    else
      request.setAttribute(
          MENU_TOTAL_RECORDS, String.valueOf(organizationDAO.getTotalOrganizationCount()));

    request.setAttribute(MENU_FROM_RECORD, String.valueOf(startingRecNo));
    int numOfRecs = 0;
    if (organizations != null) {
      if (organizations.size() > SystemConfiguration.getInstance().getDefaultPageSize()) {
        numOfRecs = SystemConfiguration.getInstance().getDefaultPageSize();
      } else {
        numOfRecs = organizations.size();
      }
      numOfRecs--;
    }
    int endingRecNo = startingRecNo + numOfRecs;
    request.setAttribute(MENU_TO_RECORD, String.valueOf(endingRecNo));
    // end bugzilla 1411

    // bugzilla 2372
    request.setAttribute(MENU_SEARCH_BY_TABLE_COLUMN, "organization.organizationName");
    // bugzilla 2372 set up a seraching mode so the next and previous action will know
    // what to do

    if (!StringUtil.isNullorNill(doingSearch) && doingSearch.equals(YES)) {

      request.setAttribute(IN_MENU_SELECT_LIST_HEADER_SEARCH, "true");

      request.setAttribute(MENU_SELECT_LIST_HEADER_SEARCH_STRING, searchString);
    }

    return organizations;
  }
  protected ActionForward performAction(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response)
      throws Exception {
    // The first job is to determine if we are coming to this action with an
    // ID parameter in the request. If there is no parameter, we are
    // creating a new Sample.
    // If there is a parameter present, we should bring up an existing
    // Sample to edit.

    String forward = FWD_SUCCESS;
    request.setAttribute(ALLOW_EDITS_KEY, "true");

    String id = request.getParameter(ID);

    if (StringUtil.isNullorNill(id) || "0".equals(id)) {
      isNew = true;
    } else {
      isNew = false;
    }

    BaseActionForm dynaForm = (BaseActionForm) form;

    // first get the accessionNumber and whether we are on blank page or not
    String accessionNumber = (String) dynaForm.get("accessionNumber");
    // bugzilla 2154
    LogEvent.logDebug(
        "HumanSampleTwoPopulateHashMapFromDE1Action",
        "performAction()",
        "accessionNumber coming in: " + accessionNumber);
    String start = (String) request.getParameter("startingRecNo");

    String typeOfSample = (String) dynaForm.get("typeOfSampleDesc");
    String sourceOfSample = (String) dynaForm.get("sourceOfSampleDesc");

    List typeOfSamples = new ArrayList();
    List sourceOfSamples = new ArrayList();

    if (dynaForm.get("typeOfSamples") != null) {
      typeOfSamples = (List) dynaForm.get("typeOfSamples");
    } else {
      TypeOfSampleDAO typeOfSampleDAO = new TypeOfSampleDAOImpl();
      typeOfSamples = typeOfSampleDAO.getAllTypeOfSamples();
    }
    if (dynaForm.get("sourceOfSamples") != null) {
      sourceOfSamples = (List) dynaForm.get("sourceOfSamples");
    } else {
      SourceOfSampleDAO sourceOfSampleDAO = new SourceOfSampleDAOImpl();
      sourceOfSamples = sourceOfSampleDAO.getAllSourceOfSamples();
    }

    HashMap humanSampleOneMap = new HashMap();
    if (dynaForm.get("humanSampleOneMap") != null) {
      humanSampleOneMap = (HashMap) dynaForm.get("humanSampleOneMap");
    }

    String projectIdOrName = (String) dynaForm.get("projectIdOrName");
    String project2IdOrName = (String) dynaForm.get("project2IdOrName");

    String projectNameOrId = (String) dynaForm.get("projectNameOrId");
    String project2NameOrId = (String) dynaForm.get("project2NameOrId");

    String projectId = null;
    String project2Id = null;
    if (projectIdOrName != null && projectNameOrId != null) {
      try {
        Integer i = Integer.valueOf(projectIdOrName);
        projectId = projectIdOrName;

      } catch (NumberFormatException nfe) {
        // bugzilla 2154
        LogEvent.logError(
            "HumanSampleTwoPopulateHashMapFromDE1Action", "performAction()", nfe.toString());
        projectId = projectNameOrId;
      }
    }

    if (project2IdOrName != null && project2NameOrId != null) {
      try {
        Integer i = Integer.valueOf(project2IdOrName);
        project2Id = project2IdOrName;

      } catch (NumberFormatException nfe) {
        // bugzilla 2154
        LogEvent.logError(
            "HumanSampleTwoPopulateHashMapFromDE1Action", "performAction()", nfe.toString());
        project2Id = project2NameOrId;
      }
    }

    // bugzilla 2154
    LogEvent.logDebug(
        "HumanSampleTwoPopulateHashMapFromDE1Action",
        "performAction()",
        "ProjectId is: " + projectId + " Project2Id is: " + project2Id);

    // set current date for validation of dates
    Date today = Calendar.getInstance().getTime();
    Locale locale = (Locale) request.getSession().getAttribute("org.apache.struts.action.LOCALE");
    String dateAsText = DateUtil.formatDateAsText(today, locale);

    Patient patient = new Patient();
    Person person = new Person();
    Provider provider = new Provider();
    Person providerPerson = new Person();
    Sample sample = new Sample();
    SampleHuman sampleHuman = new SampleHuman();
    SampleOrganization sampleOrganization = new SampleOrganization();
    List sampleProjects = new ArrayList();
    List updatedSampleProjects = new ArrayList();
    SampleItem sampleItem = new SampleItem();
    // TODO need to populate this with tests entered in HSE I
    List analyses = new ArrayList();

    // tests are not handled in HSE II
    /*
     * String stringOfTestIds = (String) dynaForm.get("selectedTestIds");
     *
     * String[] listOfTestIds = stringOfTestIds.split(SystemConfiguration
     * .getInstance().getDefaultIdSeparator(), -1);
     *
     * List analyses = new ArrayList(); for (int i = 0; i <
     * listOfTestIds.length; i++) { if
     * (!StringUtil.isNullorNill(listOfTestIds[i])) { Analysis analysis =
     * new Analysis(); analysis.setTestId(listOfTestIds[i]); // TODO: need
     * to populate this with actual data!!!
     * analysis.setAnalysisType("TEST"); analyses.add(analysis); } }
     */

    ActionMessages errors = null;

    // validate on server-side sample accession number

    try {
      errors = new ActionMessages();
      errors = validateAccessionNumber(request, errors, dynaForm);
      // System.out.println("Just validated accessionNumber");
    } catch (Exception e) {
      // bugzilla 2154
      LogEvent.logError(
          "HumanSampleTwoPopulateHashMapFromDE1Action", "performAction()", e.toString());
      ActionError error = new ActionError("errors.ValidationException", null, null);
      errors.add(ActionMessages.GLOBAL_MESSAGE, error);
    }
    // System.out.println("This is errors after validation of accn Number "
    // + errors);
    if (errors != null && errors.size() > 0) {
      saveErrors(request, errors);
      // initialize the form but retain the invalid accessionNumber
      dynaForm.initialize(mapping);
      dynaForm.set("accessionNumber", accessionNumber);

      // repopulate lists
      PropertyUtils.setProperty(dynaForm, "typeOfSamples", typeOfSamples);
      PropertyUtils.setProperty(dynaForm, "sourceOfSamples", sourceOfSamples);
      request.setAttribute(ALLOW_EDITS_KEY, "false");

      return mapping.findForward(FWD_FAIL);
    }
    // System.out.println("Now try to get data for accession number ");
    try {

      PatientDAO patientDAO = new PatientDAOImpl();
      PersonDAO personDAO = new PersonDAOImpl();
      ProviderDAO providerDAO = new ProviderDAOImpl();
      SampleDAO sampleDAO = new SampleDAOImpl();
      SampleItemDAO sampleItemDAO = new SampleItemDAOImpl();
      SampleHumanDAO sampleHumanDAO = new SampleHumanDAOImpl();
      SampleOrganizationDAO sampleOrganizationDAO = new SampleOrganizationDAOImpl();
      AnalysisDAO analysisDAO = new AnalysisDAOImpl();

      sample.setAccessionNumber(accessionNumber);
      sampleDAO.getSampleByAccessionNumber(sample);
      if (!StringUtil.isNullorNill(sample.getId())) {
        sampleHuman.setSampleId(sample.getId());
        sampleHumanDAO.getDataBySample(sampleHuman);
        sampleOrganization.setSampleId(sample.getId());
        sampleOrganizationDAO.getDataBySample(sampleOrganization);
        // bugzilla 1773 need to store sample not sampleId for use in
        // sorting
        sampleItem.setSample(sample);
        sampleItemDAO.getDataBySample(sampleItem);
        patient.setId(sampleHuman.getPatientId());
        patientDAO.getData(patient);
        person = patient.getPerson();
        personDAO.getData(person);

        provider.setId(sampleHuman.getProviderId());
        providerDAO.getData(provider);
        providerPerson = provider.getPerson();
        personDAO.getData(providerPerson);
        // bugzilla 2227
        analyses = analysisDAO.getMaxRevisionAnalysesBySample(sampleItem);

        humanSampleOneMap =
            populateHumanSampleOneMap(
                patient,
                person,
                provider,
                providerPerson,
                sample,
                sampleHuman,
                sampleOrganization,
                sampleItem,
                analyses);
      }

    } catch (LIMSRuntimeException lre) {
      // if error then forward to fail and don't update to blank page
      // = false
      // bugzilla 2154
      LogEvent.logError(
          "HumanSampleTwoPopulateHashMapFromDE1Action", "performAction()", lre.toString());
      errors = new ActionMessages();
      ActionError error = null;
      if (lre.getException() instanceof org.hibernate.StaleObjectStateException) {
        // how can I get popup instead of struts error at the top of
        // page?
        // ActionMessages errors = dynaForm.validate(mapping,
        // request);
        error = new ActionError("errors.OptimisticLockException", null, null);
        // bugzilla 2154
        LogEvent.logError(
            "HumanSampleTwoPopulateHashMapFromDE1Action",
            "performAction()",
            "errors.OptimisticLockException");
      } else {
        error = new ActionError("errors.GetException", null, null);
        // bugzilla 2154
        LogEvent.logError(
            "HumanSampleTwoPopulateHashMapFromDE1Action", "performAction()", "errors.GetException");
      }
      errors.add(ActionMessages.GLOBAL_MESSAGE, error);
      saveErrors(request, errors);
      request.setAttribute(Globals.ERROR_KEY, errors);
      request.setAttribute(ALLOW_EDITS_KEY, "false");
      return mapping.findForward(FWD_FAIL);
    }

    // initialize the form
    dynaForm.initialize(mapping);

    // set lastupdated fields
    dynaForm.set("lastupdated", sample.getLastupdated());
    dynaForm.set("personLastupdated", person.getLastupdated());
    dynaForm.set("patientLastupdated", patient.getLastupdated());
    dynaForm.set("providerPersonLastupdated", providerPerson.getLastupdated());
    dynaForm.set("providerLastupdated", provider.getLastupdated());
    dynaForm.set("sampleItemLastupdated", sampleItem.getLastupdated());
    dynaForm.set("sampleHumanLastupdated", sampleHuman.getLastupdated());
    dynaForm.set("sampleOrganizationLastupdated", sampleOrganization.getLastupdated());

    if (updatedSampleProjects != null && updatedSampleProjects.size() > 0) {
      if (updatedSampleProjects.size() == 1) {
        SampleProject sp = (SampleProject) updatedSampleProjects.get(0);
        dynaForm.set("sampleProject1Lastupdated", sp.getLastupdated());
        // bugzilla 1857 deprecated stuff
        // System.out.println("This is sp ts "
        //		+ StringUtil.formatDateAsText(sp.getLastupdated(),
        //				SystemConfiguration.getInstance()
        //						.getDefaultLocale()));
      }
      if (updatedSampleProjects.size() == 2) {
        SampleProject sp2 = (SampleProject) updatedSampleProjects.get(1);
        dynaForm.set("sampleProject2Lastupdated", sp2.getLastupdated());
        // bugzilla 1857 deprecated stuff
        // System.out.println("This is sp2 ts "
        //		+ StringUtil.formatDateAsText(sp2.getLastupdated(),
        //				SystemConfiguration.getInstance()
        //						.getDefaultLocale()));
      }
    }

    if (dynaForm.get("sampleProject1Lastupdated") == null) {
      PropertyUtils.setProperty(
          form, "sampleProject1Lastupdated", new Timestamp(System.currentTimeMillis()));
    }
    if (dynaForm.get("sampleProject2Lastupdated") == null) {
      PropertyUtils.setProperty(
          form, "sampleProject2Lastupdated", new Timestamp(System.currentTimeMillis()));
    }

    PropertyUtils.setProperty(dynaForm, "currentDate", dateAsText);
    PropertyUtils.setProperty(dynaForm, "accessionNumber", sample.getAccessionNumber());
    // set receivedDate
    PropertyUtils.setProperty(
        dynaForm, "receivedDateForDisplay", (String) sample.getReceivedDateForDisplay());

    PropertyUtils.setProperty(dynaForm, "typeOfSamples", typeOfSamples);
    PropertyUtils.setProperty(dynaForm, "sourceOfSamples", sourceOfSamples);
    PropertyUtils.setProperty(dynaForm, "humanSampleOneMap", humanSampleOneMap);

    if ("true".equalsIgnoreCase(request.getParameter("close"))) {
      forward = FWD_CLOSE;
    }

    if (sample.getId() != null && !sample.getId().equals("0")) {
      request.setAttribute(ID, sample.getId());
    }

    if (forward.equals(FWD_SUCCESS)) {
      request.setAttribute("menuDefinition", "default");
    }

    // bugzilla 2154
    LogEvent.logDebug(
        "HumanSampleTwoPopulateHashMapFromDE1Action",
        "performAction()",
        "forwarding to: " + forward);

    // pdf - get accession number List
    if (SystemConfiguration.getInstance().getEnabledSamplePdf().equals(YES)) {
      String status =
          SystemConfiguration.getInstance().getSampleStatusEntry1Complete(); // status = 2
      String humanDomain = SystemConfiguration.getInstance().getHumanDomain();
      UserTestSectionDAO userTestSectionDAO = new UserTestSectionDAOImpl();
      List accessionNumberListTwo =
          userTestSectionDAO.getSamplePdfList(request, locale, status, humanDomain);
      PropertyUtils.setProperty(form, "accessionNumberListTwo", accessionNumberListTwo);
    }

    // return getForward(mapping.findForward(forward), id, start);
    return mapping.findForward(forward);
  }
  // compares values against HashMap of HSE1 values before going to dbase to
  // revalidate submitted values
  // bugzilla 1765 changes to  city state zip validation
  protected ActionMessages validateAll(
      HttpServletRequest request,
      ActionMessages errors,
      BaseActionForm dynaForm,
      HashMap humanSampleOneMap)
      throws Exception {

    String result;
    String messageKey;
    ProjectIdValidationProvider projIdValidator = new ProjectIdValidationProvider();

    String projNum = (String) dynaForm.get("projectIdOrName");
    if (!StringUtil.isNullorNill(projNum)) {
      // project ID validation against database (reusing ajax
      // validation logic)
      result = compareAgainstHSE1HashMap(humanSampleOneMap, projNum, "projectId");
      if (result.equals(INVALID)) {
        result = projIdValidator.validate(projNum);
        messageKey = "humansampleone.projectNumber";
        if (result.equals(INVALID)) {
          String projName = (String) dynaForm.get("projectNameOrId");
          result = compareAgainstHSE1HashMap(humanSampleOneMap, projName, "projectName");
          if (result.equals(INVALID)) {
            result = projIdValidator.validate(projName);
            if (result.equals(INVALID)) {
              ActionError error =
                  new ActionError("errors.invalid", getMessageForKey(messageKey), null);
              errors.add(ActionMessages.GLOBAL_MESSAGE, error);
            }
          }
        }
      }
    }

    String proj2Num = (String) dynaForm.get("project2IdOrName");
    if (!StringUtil.isNullorNill(proj2Num)) {
      result = compareAgainstHSE1HashMap(humanSampleOneMap, proj2Num, "projectId2");
      if (result.equals(INVALID)) {
        result = projIdValidator.validate(proj2Num);
        messageKey = "humansampleone.project2Number";
        if (result.equals(INVALID)) {
          String proj2Name = (String) dynaForm.get("project2NameOrId");
          result = compareAgainstHSE1HashMap(humanSampleOneMap, proj2Name, "projectName2");
          if (result.equals(INVALID)) {
            result = projIdValidator.validate(proj2Name);
            if (result.equals(INVALID)) {
              ActionError error =
                  new ActionError("errors.invalid", getMessageForKey(messageKey), null);
              errors.add(ActionMessages.GLOBAL_MESSAGE, error);
            }
          }
        }
      }
    }

    // accession number validation against database (reusing ajax
    // validation logic)
    String accnNum = (String) dynaForm.get("accessionNumber");
    if (!StringUtil.isNullorNill(accnNum)) {
      result = compareAgainstHSE1HashMap(humanSampleOneMap, accnNum, "accessionNumber");
      if (result.equals(INVALID)) {
        errors = validateAccessionNumber(request, errors, dynaForm);
      }
    }

    // organization ID (submitter) validation against database (reusing ajax
    // validation logic)
    // bugzilla 2069
    String organizationLocalAbbreviation = (String) dynaForm.get("organizationLocalAbbreviation");
    if (!StringUtil.isNullorNill(organizationLocalAbbreviation)) {
      result =
          compareAgainstHSE1HashMap(
              humanSampleOneMap, organizationLocalAbbreviation, "organizationLocalAbbreviation");
      if (result.equals(INVALID)) {
        // bugzilla 2531
        OrganizationLocalAbbreviationValidationProvider organizationLocalAbbreviationValidator =
            new OrganizationLocalAbbreviationValidationProvider();
        result =
            organizationLocalAbbreviationValidator.validate(
                (String) dynaForm.get("organizationLocalAbbreviation"), null);
        messageKey = "humansampleone.provider.organization.localAbbreviation";
        if (result.equals(INVALID)) {
          ActionError error = new ActionError("errors.invalid", getMessageForKey(messageKey), null);
          errors.add(ActionMessages.GLOBAL_MESSAGE, error);
        }
      }
    }

    boolean stateValid = true;
    String state = (String) dynaForm.get("state");
    if (!StringUtil.isNullorNill(state)) {
      result = compareAgainstHSE1HashMap(humanSampleOneMap, state, "state");
      if (result.equals(INVALID)) {
        // state validation against database (reusing ajax validation
        // logic
        StateValidationProvider stateValidator = new StateValidationProvider();
        result = stateValidator.validate(state);
        messageKey = "person.state";
        if (result.equals(INVALID)) {
          stateValid = false;
          ActionError error = new ActionError("errors.invalid", getMessageForKey(messageKey), null);
          errors.add(ActionMessages.GLOBAL_MESSAGE, error);
        }
      }
    }

    boolean cityValid = true;
    String city = (String) dynaForm.get("city");
    if (!StringUtil.isNullorNill(city)) {
      result = compareAgainstHSE1HashMap(humanSampleOneMap, city, "city");
      if (result.equals(INVALID)) {
        // city validation against database (reusing ajax validation
        // logic
        CityValidationProvider cityValidator = new CityValidationProvider();
        result = cityValidator.validate(city);
        messageKey = "person.city";
        if (result.equals(INVALID)) {
          cityValid = false;
          ActionError error = new ActionError("errors.invalid", getMessageForKey(messageKey), null);
          errors.add(ActionMessages.GLOBAL_MESSAGE, error);
        }
      }
    }

    boolean zipValid = true;
    String zip = (String) dynaForm.get("zipCode");
    if (!StringUtil.isNullorNill(zip)) {
      result = compareAgainstHSE1HashMap(humanSampleOneMap, zip, "zipCode");
      if (result.equals(INVALID)) {
        // zip validation against database (reusing ajax validation
        // logic
        ZipValidationProvider zipValidator = new ZipValidationProvider();
        result = zipValidator.validate((String) dynaForm.get("zipCode"));
        messageKey = "person.zipCode";
        if (result.equals(INVALID)) {
          zipValid = false;
          ActionError error = new ActionError("errors.invalid", getMessageForKey(messageKey), null);
          errors.add(ActionMessages.GLOBAL_MESSAGE, error);
        }
      }
    }

    if (stateValid && cityValid && zipValid) {
      String messageKey1 = "person.city";
      String messageKey2 = "person.zipCode";
      String messageKey3 = "person.state";
      CityStateZipComboValidationProvider cityStateZipComboValidator =
          new CityStateZipComboValidationProvider();
      result =
          cityStateZipComboValidator.validate(
              (String) dynaForm.get("city"),
              (String) dynaForm.get("state"),
              (String) dynaForm.get("zipCode"));
      // combination is invalid if result is invalid
      if ("invalid".equals(result)) {
        ActionError error =
            new ActionError(
                "errors.combo.3.invalid",
                getMessageForKey(messageKey1),
                getMessageForKey(messageKey2),
                getMessageForKey(messageKey3),
                null);
        errors.add(ActionMessages.GLOBAL_MESSAGE, error);
      }
    }

    // sample type validation against database (reusing ajax validation
    // logic
    String sampleType = (String) dynaForm.get("typeOfSampleDesc");
    if (!StringUtil.isNullorNill(sampleType)) {
      result = compareAgainstHSE1HashMap(humanSampleOneMap, sampleType, "typeOfSampleDesc");
      if (result.equals(INVALID)) {
        HumanSampleTypeValidationProvider typeValidator = new HumanSampleTypeValidationProvider();
        result = typeValidator.validate(sampleType);
        messageKey = "sampleitem.typeOfSample";
        if (result.equals(INVALID)) {
          ActionError error = new ActionError("errors.invalid", getMessageForKey(messageKey), null);
          errors.add(ActionMessages.GLOBAL_MESSAGE, error);
        }
      }
    }

    String sampleSource = (String) dynaForm.get("sourceOfSampleDesc");
    if (!StringUtil.isNullorNill(sampleSource)) {
      result = compareAgainstHSE1HashMap(humanSampleOneMap, sampleSource, "sourceOfSampleDesc");
      // sample source validation against database (reusing ajax
      // validation
      // logic
      if (result.equals(INVALID)) {
        HumanSampleSourceValidationProvider sourceValidator =
            new HumanSampleSourceValidationProvider();
        result = sourceValidator.validate(sampleSource);
        messageKey = "sampleitem.sourceOfSample";
        if (result.equals(INVALID)) {
          ActionError error = new ActionError("errors.invalid", getMessageForKey(messageKey), null);
          errors.add(ActionMessages.GLOBAL_MESSAGE, error);
        }
      }
    }

    return errors;
  }