private String getSendDateOrDefault(Referral referral) {
   if (referral.getSentDate() == null) {
     return DateUtil.getCurrentDateAsText();
   } else {
     return DateUtil.convertTimestampToStringDate(referral.getSentDate());
   }
 }
Пример #2
0
  private void addAnalyzerResultFromLine(List<AnalyzerResults> results, String line) {
    String[] fields = StringUtil.separateCSVWithMixedEmbededQuotes(line);

    // This insures that the row has not been truncated
    if (fields.length < maxViewedIndex) {
      return;
    }

    AnalyzerReaderUtil readerUtil = new AnalyzerReaderUtil();
    String analyzerAccessionNumber = fields[Sample_ID].replace("\"", "");
    analyzerAccessionNumber = StringUtil.strip(analyzerAccessionNumber, " ");

    String date = fields[Date_Analyzed].replace("\"", "");

    // this is sort of dumb, we have the indexes we are interested in
    for (int i = 0; i < testNameIndex.length; i++) {
      if (!GenericValidator.isBlankOrNull(testNameIndex[i])) {
        MappedTestName mappedName =
            AnalyzerTestNameCache.instance()
                .getMappedTest(AnalyzerType.FACSCANTO, testNameIndex[i].replace("\"", ""));

        if (mappedName == null) {
          mappedName =
              AnalyzerTestNameCache.instance()
                  .getEmptyMappedTestName(
                      AnalyzerType.FACSCANTO, testNameIndex[i].replace("\"", ""));
        }

        AnalyzerResults analyzerResults = new AnalyzerResults();

        analyzerResults.setAnalyzerId(mappedName.getAnalyzerId());

        String result = fields[i].replace("\"", "");
        result = roundTwoDigits(result);
        analyzerResults.setResult(result);
        analyzerResults.setUnits(unitsIndex[i]);

        analyzerResults.setCompleteDate(
            DateUtil.convertStringDateToTimestampWithPatternNoLocale(date, DATE_PATTERN));
        // analyzerResults.setCompleteTime(DateUtil.convertStringDateToTimestamp(date));
        analyzerResults.setTestId(mappedName.getTestId());
        analyzerResults.setAccessionNumber(analyzerAccessionNumber);
        analyzerResults.setTestName(mappedName.getOpenElisTestName());

        if (analyzerAccessionNumber != null) {
          analyzerResults.setIsControl(
              analyzerAccessionNumber.startsWith(CONTROL_ACCESSION_PREFIX));
        } else {
          analyzerResults.setIsControl(false);
        }

        results.add(analyzerResults);

        AnalyzerResults resultFromDB = readerUtil.createAnalyzerResultFromDB(analyzerResults);
        if (resultFromDB != null) {
          results.add(resultFromDB);
        }
      }
    }
  }
  private double getCurrPatientAge(Patient patient) {
    if (currPatientAge == INVALID_PATIENT_AGE && patient.getBirthDate() != null) {

      Calendar dob = Calendar.getInstance();
      dob.setTime(patient.getBirthDate());

      currPatientAge = DateUtil.getAgeInMonths(patient.getBirthDate(), new Date());
    }

    return currPatientAge;
  }
  private ReportExternalImport createReportExternalImport(
      String sendingSiteId, String eventDate, String data) {
    ReportExternalImport importReport = new ReportExternalImport();

    importReport.setEventDate(
        DateUtil.convertStringDateToTimestampWithPatternNoLocale(eventDate, DATE_PATTERN));
    importReport.setSendingSite(sendingSiteId);
    importReport.setReportType("testIndicators");

    ReportExternalImport rei = reportImportDAO.getReportByEventDateSiteType(importReport);

    if (rei != null) {
      importReport = rei;
    }

    importReport.setData(data);
    importReport.setSysUserId("1");
    importReport.setRecievedDate(DateUtil.getTimestampAtMidnightForDaysAgo(0));

    return importReport;
  }
  @Override
  public void initializeReport(BaseActionForm dynaForm) {
    super.initializeReport();
    errorFound = false;

    lowerDateRange = dynaForm.getString("lowerDateRange");
    upperDateRange = dynaForm.getString("upperDateRange");

    if (GenericValidator.isBlankOrNull(lowerDateRange)) {
      errorFound = true;
      ErrorMessages msgs = new ErrorMessages();
      msgs.setMsgLine1(StringUtil.getMessageForKey("report.error.message.noPrintableItems"));
      errorMsgs.add(msgs);
    }

    if (GenericValidator.isBlankOrNull(upperDateRange)) {
      upperDateRange = lowerDateRange;
    }

    try {
      lowDate = DateUtil.convertStringDateToSqlDate(lowerDateRange);
      highDate = DateUtil.convertStringDateToSqlDate(upperDateRange);
    } catch (LIMSRuntimeException re) {
      errorFound = true;
      ErrorMessages msgs = new ErrorMessages();
      msgs.setMsgLine1(StringUtil.getMessageForKey("report.error.message.date.format"));
      errorMsgs.add(msgs);
    }

    createReportParameters();

    initializeReportItems();

    setTestMapForAllTests();

    setAnalysisForDateRange();

    setTestAggregates();
  }
  protected ActivityReportBean createActivityReportBean(Result result, boolean useTestName) {
    ActivityReportBean item = new ActivityReportBean();

    ResultService resultService = new ResultService(result);
    SampleService sampleService =
        new SampleService(result.getAnalysis().getSampleItem().getSample());
    PatientService patientService = new PatientService(sampleService.getSample());
    item.setResultValue(resultService.getResultValue("\n", true, true));
    item.setTechnician(resultService.getSignature());
    item.setAccessionNumber(sampleService.getAccessionNumber().substring(PREFIX_LENGTH));
    item.setReceivedDate(sampleService.getReceivedDateWithTwoYearDisplay());
    item.setResultDate(DateUtil.convertTimestampToTwoYearStringDate(result.getLastupdated()));
    item.setCollectionDate(
        DateUtil.convertTimestampToTwoYearStringDate(
            result.getAnalysis().getSampleItem().getCollectionDate()));

    List<String> values = new ArrayList<String>();
    values.add(
        patientService.getLastName() == null ? "" : patientService.getLastName().toUpperCase());
    values.add(patientService.getNationalId());

    String referringPatientId =
        ObservationHistoryService.getValueForSample(
            ObservationType.REFERRERS_PATIENT_ID, sampleService.getSample().getId());
    values.add(referringPatientId == null ? "" : referringPatientId);

    String name = StringUtil.buildDelimitedStringFromList(values, " / ", true);

    if (useTestName) {
      item.setPatientOrTestName(resultService.getTestName());
      item.setNonPrintingPatient(name);
    } else {
      item.setPatientOrTestName(name);
    }

    return item;
  }
  protected RejectionReportBean createRejectionReportBean(
      String noteText, Analysis analysis, boolean useTestName) {
    RejectionReportBean item = new RejectionReportBean();

    AnalysisService analysisService = new AnalysisService(analysis);
    SampleService sampleService =
        new SampleService(analysisService.getAnalysis().getSampleItem().getSample());
    PatientService patientService = new PatientService(sampleService.getSample());

    List<Result> results = analysisService.getResults();
    for (Result result : results) {
      String signature = new ResultService(result).getSignature();
      if (!GenericValidator.isBlankOrNull(signature)) {
        item.setTechnician(signature);
        break;
      }
    }

    item.setAccessionNumber(sampleService.getAccessionNumber().substring(PREFIX_LENGTH));
    item.setReceivedDate(sampleService.getTwoYearReceivedDateForDisplay());
    item.setCollectionDate(
        DateUtil.convertTimestampToTwoYearStringDate(
            analysisService.getAnalysis().getSampleItem().getCollectionDate()));
    item.setRejectionReason(noteText);

    StringBuilder nameBuilder = new StringBuilder(patientService.getLastName().toUpperCase());
    if (!GenericValidator.isBlankOrNull(patientService.getNationalId())) {
      if (nameBuilder.length() > 0) {
        nameBuilder.append(" / ");
      }
      nameBuilder.append(patientService.getNationalId());
    }

    if (useTestName) {
      item.setPatientOrTestName(analysisService.getTest().getLocalizedName());
      item.setNonPrintingPatient(nameBuilder.toString());
    } else {
      item.setPatientOrTestName(nameBuilder.toString());
    }

    return item;
  }
  private List<ReferredTest> getAdditionalReferralTests(List<ReferralResult> referralResults) {
    List<ReferredTest> additionalTestList = new ArrayList<ReferredTest>();

    while (!referralResults.isEmpty()) {
      ReferralResult referralResult =
          referralResults.get(0); // use the top one to load various bits of information.
      ReferredTest referralTest = new ReferredTest();
      referralTest.setReferralId(referralResult.getReferralId());
      referralResults =
          setReferralItemForNextTest(
              referralTest,
              referralResults); // remove one or more referralResults from the list as needed (for
                                // multiResults).
      referralTest.setReferredReportDate(
          DateUtil.convertTimestampToStringDate(referralResult.getReferralReportDate()));
      referralTest.setReferralResultId(referralResult.getId());
      additionalTestList.add(referralTest);
    }
    return additionalTestList;
  }
  /**
   * Move everything appropriate to the referralItem including one or more of the referralResults
   * from the given list. Note: This method removes an item from the referralResults list.
   *
   * @param referralItem The source item
   * @param referralResults The created list
   */
  private List<ReferralResult> setReferralItemForNextTest(
      IReferralResultTest referralItem, List<ReferralResult> referralResults) {

    ReferralResult nextTestFirstResult = referralResults.remove(0);
    List<ReferralResult> resultsForOtherTests = new ArrayList<ReferralResult>(referralResults);

    referralItem.setReferredTestId(nextTestFirstResult.getTestId());
    referralItem.setReferredTestIdShadow(referralItem.getReferredTestId());
    referralItem.setReferredReportDate(
        DateUtil.convertTimestampToStringDate(nextTestFirstResult.getReferralReportDate()));
    // We can not use ResultService because that assumes the result is for an analysis, not a
    // referral
    Result result = nextTestFirstResult.getResult();

    String resultType = (result != null) ? result.getResultType() : "N";
    referralItem.setReferredResultType(resultType);
    if (!ResultType.isMultiSelectVariant(resultType)) {
      if (result != null) {
        String resultValue =
            GenericValidator.isBlankOrNull(result.getValue()) ? "" : result.getValue();
        referralItem.setReferredResult(resultValue);
        referralItem.setReferredDictionaryResult(resultValue);
      }
    } else {
      ArrayList<Result> resultList = new ArrayList<Result>();
      resultList.add(nextTestFirstResult.getResult());

      for (ReferralResult referralResult : referralResults) {
        if (nextTestFirstResult.getTestId().equals(referralResult.getTestId())
            && !GenericValidator.isBlankOrNull(referralResult.getResult().getValue())) {
          resultList.add(referralResult.getResult());
          resultsForOtherTests.remove(referralResult);
        }
      }

      referralItem.setMultiSelectResultValues(
          ResultService.getJSONStringForMultiSelect(resultList));
    }

    return resultsForOtherTests;
  }
  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 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 {
    // 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);
  }
 private String getTwoDigitCurrentYear() {
   return DateUtil.getTwoDigitYear();
 }
  private ReferralItem getReferralItem(Referral referral) {
    boolean allReferralResultsHaveResults = true;
    List<ReferralResult> referralResults =
        referralResultDAO.getReferralResultsForReferral(referral.getId());
    for (ReferralResult referralResult : referralResults) {
      if (referralResult.getResult() == null
          || GenericValidator.isBlankOrNull(referralResult.getResult().getValue())) {
        allReferralResultsHaveResults = false;
        break;
      }
    }

    if (allReferralResultsHaveResults) {
      return null;
    }

    ReferralItem referralItem = new ReferralItem();

    AnalysisService analysisService = new AnalysisService(referral.getAnalysis());

    referralItem.setCanceled(false);
    referralItem.setReferredResultType("N");
    referralItem.setAccessionNumber(analysisService.getOrderAccessionNumber());

    TypeOfSample typeOfSample = analysisService.getTypeOfSample();
    referralItem.setSampleType(typeOfSample.getLocalizedName());

    referralItem.setReferringTestName(
        TestService.getUserLocalizedTestName(analysisService.getAnalysis().getTest()));
    List<Result> resultList = analysisService.getResults();
    String resultString = "";

    if (!resultList.isEmpty()) {
      Result result = resultList.get(0);
      resultString = getAppropriateResultValue(resultList);
      referralItem.setInLabResultId(result.getId());
    }

    referralItem.setReferralId(referral.getId());
    if (!referralResults.isEmpty()) {
      referralResults = setReferralItemForNextTest(referralItem, referralResults);
      if (!referralResults.isEmpty()) {
        referralItem.setAdditionalTests(getAdditionalReferralTests(referralResults));
      }
    }
    referralItem.setReferralResults(resultString);
    referralItem.setReferralDate(DateUtil.convertTimestampToStringDate(referral.getRequestDate()));
    referralItem.setReferredSendDate(getSendDateOrDefault(referral));
    referralItem.setReferrer(referral.getRequesterName());
    referralItem.setReferralReasonId(referral.getReferralReasonId());
    referralItem.setTestSelectionList(getTestsForTypeOfSample(typeOfSample));
    referralItem.setReferralId(referral.getId());
    if (referral.getOrganization() != null) {
      referralItem.setReferredInstituteId(referral.getOrganization().getId());
    }
    String notes = analysisService.getNotesAsString(true, true, "<br/>", false);
    if (notes != null) {
      referralItem.setPastNotes(notes);
    }

    return referralItem;
  }