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);
  }
  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);
  }
  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);
  }
  private HashMap populateHumanSampleOneMap(
      Patient patient,
      Person person,
      Provider provider,
      Person providerPerson,
      Sample sample,
      SampleHuman sampleHuman,
      SampleOrganization sampleOrganization,
      SampleItem sampleItem,
      List analyses) {
    HashMap humanSampleOneMap = new HashMap();

    List sampleProjects = new ArrayList();
    SampleProject sampleProject = null;
    SampleProject sampleProject2 = null;

    sampleProjects = sample.getSampleProjects();

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

    if (sample.getAccessionNumber() != null) {
      humanSampleOneMap.put("accessionNumber", sample.getAccessionNumber());
    } else {
      humanSampleOneMap.put("accessionNumber", "");
    }

    if (patient.getBirthDateForDisplay() != null) {
      humanSampleOneMap.put("birthDateForDisplay", patient.getBirthDateForDisplay());
    } else {
      humanSampleOneMap.put("birthDateForDisplay", "");
    }

    if (sample.getCollectionDateForDisplay() != null) {
      humanSampleOneMap.put("collectionDateForDisplay", sample.getCollectionDateForDisplay());
    } else {
      humanSampleOneMap.put("collectionDateForDisplay", "");
    }

    if (sample.getCollectionTimeForDisplay() != null) {
      humanSampleOneMap.put("collectionTimeForDisplay", sample.getCollectionTimeForDisplay());
    } else {
      // bugzilla 1894
      humanSampleOneMap.put(
          "collectionTimeForDisplay",
          SystemConfiguration.getInstance().getHumanSampleOneDefaultCollectionTimeForDisplay());
    }

    // bugzilla 1904
    if (patient.getChartNumber() != null) {
      humanSampleOneMap.put("chartNumber", patient.getChartNumber());
    } else {
      humanSampleOneMap.put("chartNumber", "");
    }

    if (person.getCity() != null) {
      // bugzilla 1766
      humanSampleOneMap.put("city", person.getCity().toUpperCase().trim());
    } else {
      humanSampleOneMap.put("city", "");
    }

    if (sample.getClientReference() != null) {
      humanSampleOneMap.put("clientReference", sample.getClientReference());
    } else {
      humanSampleOneMap.put("clientReference", "");
    }

    if (patient.getExternalId() != null) {
      humanSampleOneMap.put("externalId", patient.getExternalId());
    } else {
      humanSampleOneMap.put("externalId", "");
    }

    if (person.getFirstName() != null) {
      humanSampleOneMap.put("firstName", person.getFirstName());
    } else {
      humanSampleOneMap.put("firstName", "");
    }

    if (patient.getGender() != null) {
      humanSampleOneMap.put("gender", patient.getGender());
    } else {
      humanSampleOneMap.put("gender", "");
    }

    if (person.getLastName() != null) {
      humanSampleOneMap.put("lastName", person.getLastName());
    } else {
      humanSampleOneMap.put("lastName", "");
    }

    if (person.getMiddleName() != null) {
      humanSampleOneMap.put("middleName", person.getMiddleName());
    } else {
      humanSampleOneMap.put("middleName", "");
    }

    if (person.getMultipleUnit() != null) {
      humanSampleOneMap.put("multipleUnit", person.getMultipleUnit());
    } else {
      humanSampleOneMap.put("multipleUnit", "");
    }

    if (sampleOrganization != null && sampleOrganization.getOrganization() != null) {
      // bugzilla 2069
      humanSampleOneMap.put(
          "organizationLocalAbbreviation",
          sampleOrganization.getOrganization().getOrganizationLocalAbbreviation());
      humanSampleOneMap.put(
          "organizationNameForDisplay", sampleOrganization.getOrganization().getOrganizationName());
    } else {
      humanSampleOneMap.put("organizationLocalAbbreviation", "");
      humanSampleOneMap.put("organizationNameForDisplay", "");
    }
    if (sampleProject != null && sampleProject.getProject() != null) {
      // bugzilla 2438
      humanSampleOneMap.put("projectId", sampleProject.getProject().getLocalAbbreviation());
      // bugzilla 1766 since we capitolize project name do this here
      // for comparison purposes
      humanSampleOneMap.put(
          "projectName", sampleProject.getProject().getProjectName().toUpperCase().trim());
    } else {
      humanSampleOneMap.put("projectId", "");
      humanSampleOneMap.put("projectName", "");
    }

    if (sampleProject2 != null && sampleProject2.getProject() != null) {
      // bugzilla 2438
      humanSampleOneMap.put("projectId2", sampleProject2.getProject().getLocalAbbreviation());
      // bugzilla 1766 since we capitolize project name do this here
      // for comparison purposes
      humanSampleOneMap.put(
          "projectName2", sampleProject2.getProject().getProjectName().toUpperCase().trim());
    } else {
      humanSampleOneMap.put("projectId2", "");
      humanSampleOneMap.put("projectName2", "");
    }

    if (providerPerson.getFirstName() != null) {
      humanSampleOneMap.put("providerFirstName", providerPerson.getFirstName());
    } else {
      humanSampleOneMap.put("providerFirstName", "");
    }

    if (providerPerson.getLastName() != null) {
      humanSampleOneMap.put("providerLastName", providerPerson.getLastName());
    } else {
      humanSampleOneMap.put("providerLastName", "");
    }

    if (providerPerson.getWorkPhone() != null) {
      String storedResult = providerPerson.getWorkPhone();
      humanSampleOneMap.put("providerWorkPhone", StringUtil.formatPhoneForDisplay(storedResult));
    } else {
      humanSampleOneMap.put("providerWorkPhone", "");
    }

    if (providerPerson.getWorkPhone() != null) {
      String storedResult = providerPerson.getWorkPhone();
      // bugzilla 2442
      String extension = StringUtil.formatExtensionForDisplay(storedResult);
      humanSampleOneMap.put("providerWorkPhoneExtension", StringUtil.trim(extension));
    } else {
      humanSampleOneMap.put("providerWorkPhoneExtension", "");
    }

    if (sample.getReceivedDateForDisplay() != null) {
      humanSampleOneMap.put("receivedDateForDisplay", sample.getReceivedDateForDisplay());
    } else {
      humanSampleOneMap.put("receivedDateForDisplay", "");
    }

    if (sample.getReferredCultureFlag() != null) {
      humanSampleOneMap.put("referredCultureFlag", sample.getReferredCultureFlag());
    } else {
      humanSampleOneMap.put("referredCultureFlag", "");
    }

    if (sampleItem.getSourceOfSample() != null) {
      SourceOfSample sos = (SourceOfSample) sampleItem.getSourceOfSample();
      // bugzilla 1766
      humanSampleOneMap.put("sourceOfSampleDesc", sos.getDescription().toUpperCase().trim());
      // bugzilla 1465
      humanSampleOneMap.put("sourceOfSampleId", sos.getId());
    } else {
      humanSampleOneMap.put("sourceOfSampleDesc", "");
      // bugzilla 1465
      humanSampleOneMap.put("sourceOfSampleId", "");
    }

    if (sampleItem.getSourceOther() != null) {
      humanSampleOneMap.put("sourceOther", sampleItem.getSourceOther().trim());
    } else {
      humanSampleOneMap.put("sourceOther", "");
    }

    if (person.getState() != null) {
      humanSampleOneMap.put("state", person.getState());
    } else {
      humanSampleOneMap.put("state", "");
    }

    if (sample.getStickerReceivedFlag() != null) {
      humanSampleOneMap.put("stickerReceivedFlag", sample.getStickerReceivedFlag());
    } else {
      humanSampleOneMap.put("stickerReceivedFlag", "");
    }

    if (person.getStreetAddress() != null) {
      humanSampleOneMap.put("streetAddress", person.getStreetAddress().trim());
    } else {
      humanSampleOneMap.put("streetAddress", "");
    }

    if (sampleItem.getTypeOfSample() != null) {
      TypeOfSample tos = (TypeOfSample) sampleItem.getTypeOfSample();
      // bugzilla 1766
      humanSampleOneMap.put("typeOfSampleDesc", tos.getDescription().toUpperCase().trim());
      // bugzilla 1465
      humanSampleOneMap.put("typeOfSampleId", tos.getId());
    } else {
      humanSampleOneMap.put("typeOfSampleDesc", "");
      // bugzilla 1465
      humanSampleOneMap.put("typeOfSampleId", "");
    }

    if (person.getZipCode() != null) {
      humanSampleOneMap.put("zipCode", person.getZipCode().trim());
    } else {
      humanSampleOneMap.put("zipCode", "");
    }

    return humanSampleOneMap;
  }