/**
   * gets patients pediatrics who have adult who stage
   *
   * @param session
   * @return patientsPediatricsWhoHaveAdultWhoStage
   */
  public List<Patient> getPatientsPediatricsWhoHaveAdultWhoStage() {
    List<Patient> patientsInHIVProgram = new ArrayList<Patient>();
    List<Patient> patientsPediatricsInHIVProgram = new ArrayList<Patient>();

    List<Patient> patientsPediatricsWhoHaveAdultWhoStage = new ArrayList<Patient>();
    List<Patient> patientsWhoHaveAdultWhoStage = new ArrayList<Patient>();
    //		List<Person> persons = new ArrayList<Person>();
    //		List<Obs> observers = new ArrayList<Obs>();
    ProgramWorkflowService programService = Context.getProgramWorkflowService();
    Program program = programService.getProgram(2);

    patientsInHIVProgram = getPatientsCurrentlyInHIVProgram(program);

    for (Patient patient : patientsInHIVProgram) {
      if (patient.getAge() < 15) {
        patientsPediatricsInHIVProgram.add(patient);
      }
    }
    DataQualityService dqs = ((DataQualityService) Context.getService(DataQualityService.class));
    List<Integer> patientIds = dqs.getPatientsWhoHaveAdultWhoStage();
    for (Integer patientId : patientIds) {
      patientsWhoHaveAdultWhoStage.add(getPatientById(patientId));
    }

    for (Patient patient : patientsWhoHaveAdultWhoStage) {
      if (patientsPediatricsInHIVProgram.contains(patient)) {
        patientsPediatricsWhoHaveAdultWhoStage.add(patient);
      }
    }

    return patientsPediatricsWhoHaveAdultWhoStage;
  }
  @Test
  @Verifies(
      value = "should return program enrollment after specified date",
      method = "getClosestFutureProgramEnrollment(Patient,Program,Date)")
  public void shouldReturnPatientProgramWithEnrollmentAfterSpecifiedDate() throws Exception {
    // load this data set so that we get the additional patient program created in this data case
    executeDataSet(
        XML_DATASET_PATH + new TestUtil().getTestDatasetFilename(XML_REGRESSION_TEST_DATASET));

    ProgramWorkflowService pws = Context.getProgramWorkflowService();
    Patient patient = Context.getPatientService().getPatient(2);
    Program program = pws.getProgram(1);

    Calendar cal = Calendar.getInstance();
    cal.set(2001, 6, 31);
    Date date = cal.getTime();

    PatientProgram pp = HtmlFormEntryUtil.getClosestFutureProgramEnrollment(patient, program, date);
    Assert.assertEquals("32296060-03aa-102d-b0e3-001ec94a0cc5", pp.getUuid());

    // now, if we roll the date back a year earlier, it should get the earlier of the two programs
    // for this patient
    cal.set(2000, 6, 31);
    date = cal.getTime();

    pp = HtmlFormEntryUtil.getClosestFutureProgramEnrollment(patient, program, date);
    Assert.assertEquals("32596060-03aa-102d-b0e3-001ec94a0cc5", pp.getUuid());
  }
  @Test
  @Verifies(
      value = "should return a list consisting of active, not retired, states",
      method = "getPossibleNextStates")
  public void getPossibleNextStates_shouldReturnNonRetiredStates() throws Exception {
    executeDataSet(PROGRAM_NEXT_STATES_XML);

    Integer patient = 11;
    Integer workflow = 501;
    Vector<ListItem> possibleNextStates;

    /* retire a workflow state  */
    PatientProgram pp = Context.getProgramWorkflowService().getPatientProgram(patient);
    ProgramWorkflow pw = pp.getProgram().getWorkflow(workflow);
    Set<ProgramWorkflowState> pwss = pw.getStates();

    for (ProgramWorkflowState pws : pwss) {
      Concept cp = pws.getConcept();
      ConceptName cn = cp.getName();
      if (cn != null) {
        String cnn = cn.getName();
        if (cnn.equalsIgnoreCase("Test State 3")) {
          pws.setRetired(true);
        }
      }
    }

    possibleNextStates = dwrProgramWorkflowService.getPossibleNextStates(patient, workflow);
    assertFalse(possibleNextStates.isEmpty());
    assertEquals(2, possibleNextStates.size());
  }
  public void controller(
      FragmentModel model,
      @FragmentParam("patient") Patient patient,
      @FragmentParam("program") Program program,
      @FragmentParam(required = false, value = "registrationFormUuid") String regFormUuid,
      @FragmentParam(required = false, value = "exitFormUuid") String exitFormUuid) {

    ProgramWorkflowService pws = Context.getProgramWorkflowService();
    PatientProgram currentEnrollment = null;
    List<PatientProgram> pastEnrollments = new ArrayList<PatientProgram>();
    for (PatientProgram pp :
        pws.getPatientPrograms(patient, program, null, null, null, null, false)) {
      if (pp.getActive()) {
        currentEnrollment = pp;
      } else {
        pastEnrollments.add(pp);
      }
    }

    model.addAttribute("patient", patient);
    model.addAttribute("program", program);
    model.addAttribute("registrationFormUuid", regFormUuid);
    model.addAttribute("exitFormUuid", exitFormUuid);
    model.addAttribute("currentEnrollment", currentEnrollment);
    model.addAttribute("pastEnrollments", pastEnrollments);
  }
 /**
  * Gets the specified program
  *
  * @param uuid the uuid
  * @return the program
  */
 public static Program getProgram(String uuid) {
   Program ret = Context.getProgramWorkflowService().getProgramByUuid(uuid);
   if (ret == null) {
     throw new IllegalArgumentException("No such program with identifier " + uuid);
   }
   return ret;
 }
 /** @see {@link HtmlFormEntryUtil#isEnrolledInProgram(Patient,Program,Date)} */
 @Test
 @Verifies(
     value = "should return false if the patient is not enrolled in the program",
     method = "isEnrolledInProgram(Patient,Program,Date)")
 public void isEnrolledInProgram_shouldReturnFalseIfThePatientIsNotEnrolledInTheProgram()
     throws Exception {
   Patient patient = Context.getPatientService().getPatient(6);
   Program program = Context.getProgramWorkflowService().getProgram(1);
   Assert.assertFalse(HtmlFormEntryUtil.isEnrolledInProgramOnDate(patient, program, new Date()));
 }
 /** @see {@link HtmlFormEntryUtil#getState(String,Program)} */
 @Test
 @Verifies(
     value = "should return the state with the matching id",
     method = "getState(String,Program)")
 public void getStateProgram_shouldReturnTheStateWithTheMatchingId() throws Exception {
   Assert.assertEquals(
       "92584cdc-6a20-4c84-a659-e035e45d36b0",
       HtmlFormEntryUtil.getState("1", Context.getProgramWorkflowService().getProgram(1))
           .getUuid());
 }
 /** @see {@link HtmlFormEntryUtil#isEnrolledInProgram(Patient,Program,Date)} */
 @Test
 @Verifies(
     value = "should return true if the patient is enrolled in the program at the specified date",
     method = "isEnrolledInProgram(Patient,Program,Date)")
 public void
     isEnrolledInProgram_shouldReturnTrueIfThePatientIsEnrolledInTheProgramAtTheSpecifiedDate()
         throws Exception {
   Patient patient = Context.getPatientService().getPatient(2);
   Program program = Context.getProgramWorkflowService().getProgram(1);
   Assert.assertTrue(HtmlFormEntryUtil.isEnrolledInProgramOnDate(patient, program, new Date()));
 }
Ejemplo n.º 9
0
  /**
   * * Get the program by: 1)an integer id like 5090 or 2) uuid like
   * "a3e12268-74bf-11df-9768-17cfc9833272"
   *
   * @param Id
   * @return the program if exist, else null
   * @should find a program by its id
   * @should find a program by its uuid
   * @should return null otherwise
   */
  public static Program getProgram(String id) {
    Program program = null;

    if (id != null) {

      try { // handle integer: id
        int programId = Integer.parseInt(id);
        program = Context.getProgramWorkflowService().getProgram(programId);
        return program;
      } catch (Exception ex) {
        // do nothing
      }

      // handle uuid id: "a3e1302b-74bf-11df-9768-17cfc9833272", if id matches uuid pattern
      if (Pattern.compile("\\w+-\\w+-\\w+-\\w+-\\w+").matcher(id).matches()) {
        program = Context.getProgramWorkflowService().getProgramByUuid(id);
        return program;
      }
    }
    return program;
  }
 @Test
 @Verifies(
     value = "should return null if program enrollment date same as specified date",
     method = "getClosestFutureProgramEnrollment(Patient,Program,Date)")
 public void
     getClosestFutureProgramEnrollment_shouldReturnNullIfProgramEnrollmentSameAsSpecifiedDate()
         throws Exception {
   ProgramWorkflowService pws = Context.getProgramWorkflowService();
   Patient patient = Context.getPatientService().getPatient(2);
   Program program = pws.getProgram(1);
   Date date = pws.getPatientProgram(1).getDateEnrolled();
   Assert.assertNull(HtmlFormEntryUtil.getClosestFutureProgramEnrollment(patient, program, date));
 }
 @Test
 @Verifies(
     value = "should return null if no program enrollment after specified date",
     method = "getClosestFutureProgramEnrollment(Patient,Program,Date)")
 public void
     getClosestFutureProgramEnrollment_shouldReturnNullIfNoProgramEnrollmentAfterSpecifiedDate()
         throws Exception {
   ProgramWorkflowService pws = Context.getProgramWorkflowService();
   Patient patient = Context.getPatientService().getPatient(2);
   Program program = pws.getProgram(1);
   Assert.assertNull(
       HtmlFormEntryUtil.getClosestFutureProgramEnrollment(patient, program, new Date()));
 }
 /** @see {@link HtmlFormEntryUtil#getState(String,Program)} */
 @Test
 @Verifies(
     value = "should look up a state by a concept mapping",
     method = "getState(String,Program)")
 public void getStateProgram_shouldLookUpAStateByAConceptMapping() throws Exception {
   // load this data set so that we get the additional patient program with concept mapping
   executeDataSet(
       XML_DATASET_PATH + new TestUtil().getTestDatasetFilename(XML_REGRESSION_TEST_DATASET));
   Assert.assertEquals(
       "6de7ed10-53ad-11e1-8cb6-00248140a5eb",
       HtmlFormEntryUtil.getState(
               "SNOMED CT: Test Code", Context.getProgramWorkflowService().getProgram(10))
           .getUuid());
 }
  /**
   * Takes a "program_id:list" where program_id is the id of the program that this collection is for
   * (or not present, if it's a new program) and list is a space-separated list of concept ids. This
   * class is a bit of a hack, because I don't know a better way to do this. -DJ The purpose is to
   * retire and un-retire workflows where possible rather than deleting and creating them.
   */
  public void setAsText(String text) throws IllegalArgumentException {
    if (StringUtils.hasText(text)) {
      ConceptService cs = Context.getConceptService();
      ProgramWorkflowService pws = Context.getProgramWorkflowService();
      try {
        int ind = text.indexOf(":");
        String progIdStr = text.substring(0, ind);
        text = text.substring(ind + 1);
        if (program == null)
          // if a program wasn't passed in, try to look it up now
          program = pws.getProgram(Integer.valueOf(progIdStr));
      } catch (Exception ex) {
      }

      String[] conceptIds = text.split(" ");
      Set<ProgramWorkflow> oldSet =
          program == null ? new HashSet<ProgramWorkflow>() : program.getAllWorkflows();
      Set<Integer> newConceptIds = new HashSet<Integer>();

      for (String id : conceptIds) {
        if (id.trim().length() == 0) continue;
        log.debug("trying " + id);
        newConceptIds.add(Integer.valueOf(id.trim()));
      }

      // go through oldSet and see what we need to keep and what we need to unvoid
      Set<Integer> alreadyDone = new HashSet<Integer>();
      for (ProgramWorkflow pw : oldSet) {
        if (!newConceptIds.contains(pw.getConcept().getConceptId())) {
          pw.setRetired(true);
        } else if (pw.isRetired()) { // && newConceptIds.contains(pw...)
          pw.setRetired(false);
        }
        alreadyDone.add(pw.getConcept().getConceptId());
      }

      // now add any new ones
      newConceptIds.removeAll(alreadyDone);
      for (Integer conceptId : newConceptIds) {
        ProgramWorkflow pw = new ProgramWorkflow();
        pw.setProgram(program);
        pw.setConcept(cs.getConcept(conceptId));
        oldSet.add(pw);
      }

      setValue(oldSet);
    } else {
      setValue(null);
    }
  }
 /** @see {@link HtmlFormEntryUtil#getState(String,Program)} */
 @SuppressWarnings("deprecation")
 @Test
 @Verifies(
     value = "should return the state with the matching uuid",
     method = "getState(String,ProgramWorkflow)")
 public void getStateWorkflow_shouldReturnTheStateWithTheMatchingUuid() throws Exception {
   Assert.assertEquals(
       "1",
       HtmlFormEntryUtil.getState(
               "92584cdc-6a20-4c84-a659-e035e45d36b0",
               Context.getProgramWorkflowService().getWorkflow(1))
           .getId()
           .toString());
 }
  private void setupMappings() {
    MetadataSource metadataSource = new MetadataSource();
    metadataSource.setName("source");
    metadataSource.setDateCreated(new Date());
    metadataSource.setRetired(false);
    metadataSource.setId(1);
    metadataSource =
        Context.getService(MetadataMappingService.class).saveMetadataSource(metadataSource);

    MetadataTermMapping metadataTermMapping1 =
        new MetadataTermMapping(
            metadataSource, "DataClerk", Context.getUserService().getRole("Data Clerk"));
    metadataTermMapping1.setName("mapping1");
    Context.getService(MetadataMappingService.class).saveMetadataTermMapping(metadataTermMapping1);

    MetadataTermMapping metadataTermMapping2 =
        new MetadataTermMapping(
            metadataSource, "ROLE", Context.getUserService().getRole("Provider"));
    metadataTermMapping2.setName("mapping2");
    Context.getService(MetadataMappingService.class).saveMetadataTermMapping(metadataTermMapping2);

    MetadataTermMapping metadataTermMapping3 =
        new MetadataTermMapping(
            metadataSource,
            "Location",
            Context.getLocationService().getLocationByUuid("9356400c-a5a2-4532-8f2b-2361b3446eb8"));
    metadataTermMapping3.setName("mapping3");
    Context.getService(MetadataMappingService.class).saveMetadataTermMapping(metadataTermMapping3);

    MetadataTermMapping metadataTermMapping4 =
        new MetadataTermMapping(
            metadataSource,
            "MDR-TB PROGRAM",
            Context.getProgramWorkflowService().getProgramByName("MDR-TB PROGRAM"));
    metadataTermMapping4.setName("mapping4");
    Context.getService(MetadataMappingService.class).saveMetadataTermMapping(metadataTermMapping4);

    MetadataTermMapping metadataTermMapping5 =
        new MetadataTermMapping(
            metadataSource, "1", Context.getPatientService().getPatientIdentifierType(1));
    metadataTermMapping5.setName("mapping5");
    Context.getService(MetadataMappingService.class).saveMetadataTermMapping(metadataTermMapping5);

    Context.flushSession();
  }
  /** @see {@link HtmlFormEntryUtil#isEnrolledInProgram(Patient,Program,Date)} */
  @Test
  @Verifies(
      value = "should return false if the program was completed",
      method = "isEnrolledInProgram(Patient,Program,Date)")
  public void isEnrolledInProgram_shouldReturnFalseIfTheProgramWasCompleted() throws Exception {
    ProgramWorkflowService pws = Context.getProgramWorkflowService();
    Patient patient = Context.getPatientService().getPatient(2);

    // for test purposes, lets set a program as complete
    PatientProgram pp = pws.getPatientProgram(1);
    Assert.assertSame(patient, pp.getPatient());
    pp.setDateCompleted(new Date());
    Thread.sleep(100);
    pws.savePatientProgram(pp);

    Assert.assertFalse(
        HtmlFormEntryUtil.isEnrolledInProgramOnDate(patient, pws.getProgram(1), new Date()));
  }
  /**
   * gets patients who are in PMTCT program with no CPN ID
   *
   * @param session
   * @return
   */
  public List<Patient> getPatientsWhoAreInPMTCTWithNoCPNId() {
    List<Patient> patientsInPMTCTProgram = new ArrayList<Patient>();
    List<Patient> patientsWithNoCPN = new ArrayList<Patient>();
    List<Patient> patientsInPMTCTWithNoCPNId = new ArrayList<Patient>();

    ProgramWorkflowService programService = Context.getProgramWorkflowService();
    Program program = programService.getProgram(1);

    patientsInPMTCTProgram = getPatientsCurrentlyInHIVProgram(program);
    patientsWithNoCPN =
        getPatientWithNoGivenAttribute(getGlobalProperty("patientIdentifierType.CPNID"));

    for (Patient patient : patientsInPMTCTProgram) {
      if (patientsWithNoCPN.contains(patient)) {
        patientsInPMTCTWithNoCPNId.add(patient);
      }
    }

    return patientsInPMTCTWithNoCPNId;
  }
  /** @see {@link HtmlFormEntryUtil#isEnrolledInProgram(Patient,Program,Date)} */
  @Test
  @Verifies(
      value =
          "should return false if the date is before the existing patient program enrollment date",
      method = "isEnrolledInProgram(Patient,Program,Date)")
  public void
      isEnrolledInProgram_shouldReturnFalseIfTheDateIsBeforeTheExistingPatientProgramEnrollmentDateIgnoringTimeFields()
          throws Exception { // 2008-08-01 00:00:00.0
    ProgramWorkflowService pws = Context.getProgramWorkflowService();
    Patient patient = Context.getPatientService().getPatient(2);
    Program program = pws.getProgram(1);
    PatientProgram pp = pws.getPatientProgram(1);

    Calendar cal = Calendar.getInstance();
    cal.set(2008, 6, 31);
    Date newEnrollmentDate = cal.getTime();
    Assert.assertTrue(newEnrollmentDate.before(pp.getDateEnrolled())); // sanity check
    Assert.assertFalse(
        HtmlFormEntryUtil.isEnrolledInProgramOnDate(patient, program, newEnrollmentDate));
  }
  @Test
  public void shouldRespectClassesNotToExportGlobalProperty() throws Exception {

    // include this set so that we get the mapping concept
    executeDataSet(
        XML_DATASET_PATH + new TestUtil().getTestDatasetFilename(XML_HTML_FORM_ENTRY_TEST_DATASET));
    Context.getAdministrationService()
        .saveGlobalProperty(
            new GlobalProperty(
                HtmlFormEntryConstants.GP_CLASSES_NOT_TO_EXPORT_WITH_MDS, "org.openmrs.Program"));

    HtmlForm form = new HtmlForm();
    form.setXmlData(
        new TestUtil().loadXmlFromFile(XML_DATASET_PATH + "metadataSharingTestForm.xml"));

    HtmlFormExporter exporter = new HtmlFormExporter(form);
    HtmlForm formClone = exporter.export(true, true, true, true);

    Collection<OpenmrsObject> dependencies = formClone.getDependencies();

    // make sure all the appropriate concepts have been added to the dependencies
    Assert.assertTrue(
        dependencies.contains(
            Context.getConceptService().getConceptByUuid("32296060-03aa-102d-b0e3-001ec94a0cc1")));
    Assert.assertTrue(
        dependencies.contains(
            Context.getConceptService().getConceptByUuid("32296060-03aa-102d-b0e3-001ec94a0cc4")));
    Assert.assertTrue(
        dependencies.contains(
            Context.getConceptService().getConceptByUuid("32296060-03aa-102d-b0e3-001ec94a0cc5")));
    Assert.assertTrue(
        dependencies.contains(
            Context.getConceptService().getConceptByUuid("32296060-03aa-102d-b0e3-001ec94a0cc6")));
    Assert.assertTrue(
        dependencies.contains(
            Context.getConceptService().getConceptByUuid("32296060-03aa-102d-b0e3-001ec94a0cc3")));
    Assert.assertTrue(
        dependencies.contains(
            Context.getConceptService().getConceptByUuid("aa52296060-03-102d-b0e3-001ec94a0cc1")));
    // this is the mapped concept XYZ:HT found in HtmlFormEntryTest-data
    Assert.assertTrue(
        dependencies.contains(
            Context.getConceptService().getConceptByUuid("44d3611a-6699-4d52-823f-b4b788bac3e3")));

    // drug discontinue reason, corresponds to concept 555 in regressionTest-data
    Assert.assertTrue(
        dependencies.contains(
            Context.getConceptService().getConceptByUuid("32296060-0370-102d-b0e3-123456789011")));

    // make sure the programs have NOT been added to the dependencies
    Assert.assertFalse(
        dependencies.contains(
            Context.getProgramWorkflowService()
                .getProgramByUuid("da4a0391-ba62-4fad-ad66-1e3722d16380")));
    Assert.assertFalse(
        dependencies.contains(
            Context.getProgramWorkflowService()
                .getProgramByUuid("71779c39-d289-4dfe-91b5-e7cfaa27c78b")));

    // make sure the program workflows have been added to the dependencies
    Assert.assertTrue(
        dependencies.contains(
            Context.getProgramWorkflowService()
                .getWorkflowByUuid("72a90efc-5140-11e1-a3e3-00248140a5eb")));
    Assert.assertTrue(
        dependencies.contains(
            Context.getProgramWorkflowService()
                .getWorkflowByUuid("7c3e071a-53a7-11e1-8cb6-00248140a5eb")));

    // make sure the program workflow states have been added to the dependencies
    Assert.assertTrue(
        dependencies.contains(
            Context.getProgramWorkflowService()
                .getStateByUuid("92584cdc-6a20-4c84-a659-e035e45d36b0")));
    Assert.assertTrue(
        dependencies.contains(
            Context.getProgramWorkflowService()
                .getStateByUuid("e938129e-248a-482a-acea-f85127251472")));
    Assert.assertTrue(
        dependencies.contains(
            Context.getProgramWorkflowService()
                .getStateByUuid("860b3a13-d4b1-4f0a-b526-278652fa1809")));
    Assert.assertTrue(
        dependencies.contains(
            Context.getProgramWorkflowService()
                .getStateByUuid("8ef66ca8-5140-11e1-a3e3-00248140a5eb")));
    Assert.assertTrue(
        dependencies.contains(
            Context.getProgramWorkflowService()
                .getStateByUuid("67337cdc-53ad-11e1-8cb6-00248140a5eb")));

    // make sure the drugs have been added to the dependencies
    Assert.assertTrue(
        dependencies.contains(
            Context.getConceptService().getDrugByUuid("3cfcf118-931c-46f7-8ff6-7b876f0d4202")));
    Assert.assertTrue(
        dependencies.contains(
            Context.getConceptService().getDrugByUuid("05ec820a-d297-44e3-be6e-698531d9dd3f")));
    Assert.assertTrue(
        dependencies.contains(
            Context.getConceptService().getDrugByUuid("7e2323fa-0fa0-461f-9b59-6765997d849e")));

    // make sure the locations have been added to the dependencies
    Assert.assertTrue(
        dependencies.contains(Context.getLocationService().getLocation("Never Never Land")));
    Assert.assertTrue(
        dependencies.contains(
            Context.getLocationService()
                .getLocationByUuid("9356400c-a5a2-4532-8f2b-2361b3446eb8")));
    Assert.assertTrue(dependencies.contains(Context.getLocationService().getLocation(1)));

    // make sure the provider has been added to the list of dependencies
    Assert.assertTrue(
        dependencies.contains(
            Context.getPersonService().getPersonByUuid("c04ee3c8-b68f-43cc-bff3-5a831ee7225f")));

    // make sure the patient identifier types have been added to the list of dependencies
    Assert.assertTrue(
        dependencies.contains(
            Context.getPatientService()
                .getPatientIdentifierTypeByUuid("1a339fe9-38bc-4ab3-b180-320988c0b968")));
    Assert.assertTrue(
        dependencies.contains(
            Context.getPatientService()
                .getPatientIdentifierTypeByUuid("2f470aa8-1d73-43b7-81b5-01f0c0dfa53c")));

    // make sure the roles have been added to the list of dependencies
    Assert.assertTrue(
        dependencies.contains(
            Context.getUserService().getRoleByUuid("92b70b00-58b1-11e0-80e3-0800200c9a66")));
    Assert.assertTrue(
        dependencies.contains(
            Context.getUserService().getRoleByUuid("a238c500-58b1-11e0-80e3-0800200c9a66")));
  }
  @Test
  @Verifies(
      value = "should create cloned form to export with appropriate dependencies",
      method = "createCloneForExport(HtmlForm)")
  public void createCloneForExport_shouldCreateCloneWithDependencies() throws Exception {

    // include this set so that we get the mapping concept
    executeDataSet(
        XML_DATASET_PATH + new TestUtil().getTestDatasetFilename(XML_HTML_FORM_ENTRY_TEST_DATASET));

    HtmlForm form = new HtmlForm();
    form.setXmlData(
        new TestUtil().loadXmlFromFile(XML_DATASET_PATH + "metadataSharingTestForm.xml"));

    HtmlFormExporter exporter = new HtmlFormExporter(form);
    HtmlForm formClone = exporter.export(true, true, true, true);

    Collection<OpenmrsObject> dependencies = formClone.getDependencies();

    // make sure all the appropriate concepts have been added to the dependencies
    Assert.assertTrue(
        dependencies.contains(
            Context.getConceptService().getConceptByUuid("32296060-03aa-102d-b0e3-001ec94a0cc1")));
    Assert.assertTrue(
        dependencies.contains(
            Context.getConceptService().getConceptByUuid("32296060-03aa-102d-b0e3-001ec94a0cc4")));
    Assert.assertTrue(
        dependencies.contains(
            Context.getConceptService().getConceptByUuid("32296060-03aa-102d-b0e3-001ec94a0cc5")));
    Assert.assertTrue(
        dependencies.contains(
            Context.getConceptService().getConceptByUuid("32296060-03aa-102d-b0e3-001ec94a0cc6")));
    Assert.assertTrue(
        dependencies.contains(
            Context.getConceptService().getConceptByUuid("32296060-03aa-102d-b0e3-001ec94a0cc3")));
    Assert.assertTrue(
        dependencies.contains(
            Context.getConceptService().getConceptByUuid("aa52296060-03-102d-b0e3-001ec94a0cc1")));
    // this is the mapped concept XYZ:HT found in HtmlFormEntryTest-data
    Assert.assertTrue(
        dependencies.contains(
            Context.getConceptService().getConceptByUuid("44d3611a-6699-4d52-823f-b4b788bac3e3")));

    // drug discontinue reason, corresponds to concept 555 in regressionTest-data
    Assert.assertTrue(
        dependencies.contains(
            Context.getConceptService().getConceptByUuid("32296060-0370-102d-b0e3-123456789011")));

    // make sure the programs have been added to the dependencies
    Assert.assertTrue(
        dependencies.contains(
            Context.getProgramWorkflowService()
                .getProgramByUuid("da4a0391-ba62-4fad-ad66-1e3722d16380")));
    Assert.assertTrue(
        dependencies.contains(
            Context.getProgramWorkflowService()
                .getProgramByUuid("71779c39-d289-4dfe-91b5-e7cfaa27c78b")));

    // make sure the program workflows have been added to the dependencies
    Assert.assertTrue(
        dependencies.contains(
            Context.getProgramWorkflowService()
                .getWorkflowByUuid("72a90efc-5140-11e1-a3e3-00248140a5eb")));
    Assert.assertTrue(
        dependencies.contains(
            Context.getProgramWorkflowService()
                .getWorkflowByUuid("7c3e071a-53a7-11e1-8cb6-00248140a5eb")));

    // make sure the program workflow states have been added to the dependencies
    Assert.assertTrue(
        dependencies.contains(
            Context.getProgramWorkflowService()
                .getStateByUuid("92584cdc-6a20-4c84-a659-e035e45d36b0")));
    Assert.assertTrue(
        dependencies.contains(
            Context.getProgramWorkflowService()
                .getStateByUuid("e938129e-248a-482a-acea-f85127251472")));
    Assert.assertTrue(
        dependencies.contains(
            Context.getProgramWorkflowService()
                .getStateByUuid("860b3a13-d4b1-4f0a-b526-278652fa1809")));
    Assert.assertTrue(
        dependencies.contains(
            Context.getProgramWorkflowService()
                .getStateByUuid("8ef66ca8-5140-11e1-a3e3-00248140a5eb")));
    Assert.assertTrue(
        dependencies.contains(
            Context.getProgramWorkflowService()
                .getStateByUuid("67337cdc-53ad-11e1-8cb6-00248140a5eb")));

    // note this this assertion fails--currently, the exporter WILL NOT be able to pick up states
    // referenced concept map
    // (this is because the exporter considers each attribute separately, and to you can't get a
    // state referenced by concept map without knowing the corresponding program or workflow)
    // however, this should not be a problem because the state should be included by MDS when it's
    // parent program or workflow is exported
    // Assert.assertTrue(dependencies.contains(Context.getProgramWorkflowService().getStateByUuid(
    // "6de7ed10-53ad-11e1-8cb6-00248140a5eb")));

    // make sure the drugs have been added to the dependencies
    Assert.assertTrue(
        dependencies.contains(
            Context.getConceptService().getDrugByUuid("3cfcf118-931c-46f7-8ff6-7b876f0d4202")));
    Assert.assertTrue(
        dependencies.contains(
            Context.getConceptService().getDrugByUuid("05ec820a-d297-44e3-be6e-698531d9dd3f")));
    Assert.assertTrue(
        dependencies.contains(
            Context.getConceptService().getDrugByUuid("7e2323fa-0fa0-461f-9b59-6765997d849e")));

    // make sure the locations have been added to the dependencies
    Assert.assertTrue(
        dependencies.contains(Context.getLocationService().getLocation("Never Never Land")));
    Assert.assertTrue(
        dependencies.contains(
            Context.getLocationService()
                .getLocationByUuid("9356400c-a5a2-4532-8f2b-2361b3446eb8")));
    Assert.assertTrue(dependencies.contains(Context.getLocationService().getLocation(1)));

    // make sure the provider has been added to the list of dependencies
    Assert.assertTrue(
        dependencies.contains(
            Context.getPersonService().getPersonByUuid("c04ee3c8-b68f-43cc-bff3-5a831ee7225f")));

    // make sure the patient identifier types have been added to the list of dependencies
    Assert.assertTrue(
        dependencies.contains(
            Context.getPatientService()
                .getPatientIdentifierTypeByUuid("1a339fe9-38bc-4ab3-b180-320988c0b968")));
    Assert.assertTrue(
        dependencies.contains(
            Context.getPatientService()
                .getPatientIdentifierTypeByUuid("2f470aa8-1d73-43b7-81b5-01f0c0dfa53c")));

    // make sure the roles have been added to the list of dependencies
    Assert.assertTrue(
        dependencies.contains(
            Context.getUserService().getRoleByUuid("92b70b00-58b1-11e0-80e3-0800200c9a66")));
    Assert.assertTrue(
        dependencies.contains(
            Context.getUserService().getRoleByUuid("a238c500-58b1-11e0-80e3-0800200c9a66")));

    // TODO test exporting location tags once we upgrade to only supporting OpenMRS 1.7 and above
    // (since in 1.6, locations tags don't have names)

  }
  @Override
  public String getOverrideContent(String str) {
    if (!Context.isAuthenticated()) {
      return "";
    }
    String gp =
        Context.getAdministrationService()
            .getGlobalProperty("htmlformflowsheet.patientChartFormIds");

    if (StringUtils.isEmpty(gp)) {
      return "";
    }

    StringBuilder sbExisting = new StringBuilder("");
    StringBuilder sbNonExisting = new StringBuilder("");
    try {
      String patientId = this.getParameterMap().get("patientId");
      Patient p = Context.getPatientService().getPatient(Integer.valueOf(patientId));

      for (StringTokenizer st = new StringTokenizer(gp, ","); st.hasMoreTokens(); ) {

        Map<Integer, Set<Integer>> progForms = new HashMap<Integer, Set<Integer>>();
        Set<Integer> programIds = new HashSet<Integer>();

        String formId = st.nextToken().trim();
        if (formId.contains(":")) {
          String[] formIdSplit = formId.split(":");
          formId = formIdSplit[0];
          // check for required programs:
          String programInfo = formIdSplit[1];
          if (programInfo.contains("|")) {
            for (StringTokenizer strTok = new StringTokenizer(programInfo, "|");
                strTok.hasMoreTokens(); ) {
              String sTmp = strTok.nextToken().trim();
              addFormToProgramList(progForms, Integer.valueOf(formId), Integer.valueOf(sTmp));
              programIds.add(Integer.valueOf(sTmp));
            }
          } else {
            // todo: support lookup programs by uuid and forms by uuid?
            addFormToProgramList(progForms, Integer.valueOf(formId), Integer.valueOf(programInfo));
            programIds.add(Integer.valueOf(programInfo));
          }
        }
        Form form = HtmlFormFlowsheetUtil.getFormFromString(formId);
        List<PatientProgram> pps =
            Context.getProgramWorkflowService()
                .getPatientPrograms(p, null, null, null, null, null, false);
        List<Encounter> encs =
            Context.getEncounterService()
                .getEncounters(
                    p, null, null, null, Collections.singletonList(form), null, null, false);

        //	            for (Map.Entry<Integer, Set<Integer>> m : progForms.entrySet()){
        //	            	System.out.println(m.getKey()+ ":" + m.getValue());
        //	            }

        // 1. no program association to form.  always show.
        if (progForms.get(Integer.valueOf(formId)) == null
            || progForms.get(Integer.valueOf(formId)).size() == 0) {
          if (encs.size() == 0) {
            // if no encs, show add new
            sbNonExisting.append(
                " | <a href=\"/"
                    + WebConstants.WEBAPP_NAME
                    + "/module/htmlformentry/htmlFormEntry.form?personId="
                    + p.getPersonId()
                    + "&patientId="
                    + p.getPatientId()
                    + "&returnUrl=&formId="
                    + form.getFormId()
                    + "\">"
                    + form.getName()
                    + "</a> | ");
          } else {
            // if encs, show existing flowsheet parent(s)
            for (Encounter e : encs) {
              sbExisting.append(
                  " | <a href=\"/"
                      + WebConstants.WEBAPP_NAME
                      + "/module/htmlformentry/htmlFormEntry.form?encounterId="
                      + e.getEncounterId()
                      + "&mode=EDIT\">"
                      + form.getName()
                      + " "
                      + "("
                      + Context.getDateFormat().format(e.getEncounterDatetime())
                      + ")</a> | ");
            }
          }
        } else {
          // 2. program(s) specified for form
          // this builds a map of encounter corresponding to the parent form creation to the
          // patientProgram is was created in.
          Map<Encounter, PatientProgram> encounterToPatientProgram =
              new HashMap<Encounter, PatientProgram>();
          for (Encounter e : encs) {
            for (PatientProgram pp : pps) {

              // if encounter is later than start date and less than end date or end date is null
              if (programIds.contains(pp.getProgram().getProgramId())
                  && e.getEncounterDatetime().getTime() >= pp.getDateEnrolled().getTime()
                  && ((pp.getDateCompleted() == null
                      || pp.getDateCompleted().getTime() >= e.getEncounterDatetime().getTime()))) {
                // encounter is in patientprogram
                encounterToPatientProgram.put(e, pp);
              }
            }
          }
          // show existing based on the map
          for (Map.Entry<Encounter, PatientProgram> m : encounterToPatientProgram.entrySet()) {
            sbExisting.append(
                " | <a href=\"/"
                    + WebConstants.WEBAPP_NAME
                    + "/module/htmlformentry/htmlFormEntry.form?encounterId="
                    + m.getKey().getEncounterId()
                    + "&mode=EDIT\">"
                    + form.getName());
            if (m.getValue() != null) {
              sbExisting.append(
                  " "
                      + "("
                      + Context.getDateFormat().format(m.getValue().getDateEnrolled())
                      + " - ");
              if (m.getValue().getDateCompleted() != null)
                sbExisting.append(Context.getDateFormat().format(m.getValue().getDateCompleted()));
              sbExisting.append(")");
            }
            sbExisting.append("</a> | ");
          }

          // show add new
          // if patient is in program currently, AND patient doesn't have an encounter for this
          // program
          PatientProgram ppActive = activePatientProgram(pps, programIds);
          boolean found = false;
          if (ppActive != null) {
            for (Map.Entry<Encounter, PatientProgram> m : encounterToPatientProgram.entrySet()) {
              if (m.getValue() != null && m.getValue().equals(ppActive)) found = true;
            }
            if (!found)
              sbNonExisting.append(
                  " | <a href=\"/"
                      + WebConstants.WEBAPP_NAME
                      + "/module/htmlformentry/htmlFormEntry.form?personId="
                      + p.getPersonId()
                      + "&patientId="
                      + p.getPatientId()
                      + "&returnUrl=&formId="
                      + form.getFormId()
                      + "\"> "
                      + form.getName()
                      + "</a> | ");
          }
        }
      }
      String retString = "<table><tr><td>";
      if (!sbExisting.toString().equals(""))
        retString += "Existing Patient Chart(s): " + sbExisting.toString();
      retString += "</td></tr><tr><td>";
      if (!sbNonExisting.toString().equals(""))
        retString += "Create A New Patient Charts: " + sbNonExisting.toString();
      retString += "</td></tr></table>";
      return retString.replace("|  |", " | ");

    } catch (Exception ex) {
      ex.printStackTrace();
      return "";
    }
  }
  /**
   * gets patients by checking Type of abnormal datas
   *
   * @param programIdKey
   * @param session
   * @param valueRangeType
   * @return
   */
  public List<Patient> checkTypeController(String programIdKey, String valueRangeType)
      throws Exception {

    // log.info("@@@@@@@@@@@@@@@@@@@@@ programIdKey "+programIdKey);

    List<Patient> patients = new ArrayList<Patient>();
    List<Patient> activePatients = new ArrayList<Patient>();
    List<Patient> patientsInHIVProgram = new ArrayList<Patient>();
    if (programIdKey.equals("PatientsWithNoProgramsEnrollmentDates")) {
      patients = getPatientsWithNoProgramsEnrollmentDates();
      DataqualityFormController.setMsgToDisplay("Patients with no programs enrollment dates");
    } else if (programIdKey.equals("PatientsDrugsWithDiscontinuedDateWithoutStartDate")) {
      patients = getPatientsDrugsWithDiscontinuedDateWithoutStartDate();
      DataqualityFormController.setMsgToDisplay(
          "Patients Drugs with discontinued date without start date");
    } else if (programIdKey.equals("DrugsWithDiscontinuedDateHigherThanDrugStartDate")) {
      patients = getPatientsWithDiscontinuedDateHigherThanDrugStartDate();
      DataqualityFormController.setMsgToDisplay("");
    } else if (programIdKey.equals("DrugsWithoutStartDate")) {
      patients = getPatientsWithoutStartDate();
      DataqualityFormController.setMsgToDisplay("Patients with Drugs without start date");
    } else if (programIdKey.equals("patientrsWithoutNames")) {
      patients = getPatientsWithoutNames();
      DataqualityFormController.setMsgToDisplay("Patientrs without names");
    } else if (programIdKey.equals("patientInAnyHivProgramWithoutAdmitionMode")) {
      // log.info("top  patientInAnyHivProgramWithoutAdmitionMode");
      patientsInHIVProgram = new ArrayList<Patient>();
      List<Patient> patientsWithNoAdmitionMode = new ArrayList<Patient>();
      // getting programs
      ProgramWorkflowService programService = Context.getProgramWorkflowService();
      Program hivProgram = programService.getProgram(getGlobalProperty("HIVProgramId"));
      patientsInHIVProgram = getPatientsCurrentlyInHIVProgram(hivProgram);
      patientsWithNoAdmitionMode =
          getPatientWithoutAdmitionModeConcept(
              getConcept(getGlobalProperty("concept.methodOfEnrollement")));
      for (Patient patient : patientsWithNoAdmitionMode) {
        if (patientsInHIVProgram.contains(patient)) {
          patients.add(patient);
        }
      }
      DataqualityFormController.setMsgToDisplay(
          "tracdataquality.indicator.patientInAnyHivProgramWithoutAdmitionMode");
      log.info("bottom  patientInAnyHivProgramWithoutAdmitionMode");
    } else if (programIdKey.equals("patientsWithoutProgram")) {
      log.info("top  patientsWithoutProgram");
      patients = getPatientWithoutProgram();
      DataqualityFormController.setMsgToDisplay("tracdataquality.indicator.patientsWithoutProgram");
      log.info("bottom  patientsWithoutProgram");
    } else if (programIdKey.equals("patientsWithnoWeight")) {
      log.info("top  patientsWithnoWeight");
      Concept concept = getConcept(getGlobalProperty("concept.weight"));
      patients = getPatientWithoutAgivenConcept(concept);
      DataqualityFormController.setMsgToDisplay("tracdataquality.indicator.patientsWithnoWeight");
      log.info("bottom  patientsWithnoWeight");
    } else if (programIdKey.equals("patientsWithNoHeight")) {
      log.info("top  patientsWithNoHeight");
      Concept concept = getConcept(getGlobalProperty("concept.height"));
      patients = getPatientWithoutAgivenConcept(concept);
      DataqualityFormController.setMsgToDisplay("tracdataquality.indicator.patientsWithNoHeight");
      log.info("bottom  patientsWithNoHeight");
    } else if (programIdKey.equals("patientWithNoHIVViralLoad")) {
      log.info("top  patientWithNoHIVViralLoad");
      List<Patient> patientsWithNoViralLoad = new ArrayList<Patient>();
      Concept viralLoadConcept = getConcept(getGlobalProperty("concept.viralLoad"));

      ProgramWorkflowService programService = Context.getProgramWorkflowService();
      Program hivProgram = programService.getProgram(getGlobalProperty("HIVProgramId"));
      patientsWithNoViralLoad = getPatientWithoutAgivenConcept(viralLoadConcept);

      patientsInHIVProgram = getPatientsCurrentlyInHIVProgram(hivProgram);
      for (Patient patient : patientsInHIVProgram) {
        if (patientsWithNoViralLoad.contains(patient)) {
          patients.add(patient);
        }
      }
      DataqualityFormController.setMsgToDisplay(
          "tracdataquality.indicator.patientWithNoHIVViralLoad");
      log.info("bottom  patientWithNoHIVViralLoad");
    } else if (programIdKey.equals("patientWithHIVPositiveAndNoCD4")) {
      log.info("top  patientWithHIVPositiveAndNoCD4");
      List<Patient> patientsWithNoCD4 = new ArrayList<Patient>();
      patientsInHIVProgram = new ArrayList<Patient>();
      Concept cd4 = getConcept(getGlobalProperty("concept.cd4_count"));
      ProgramWorkflowService programService = Context.getProgramWorkflowService();
      Program hivProgram = programService.getProgram(getGlobalProperty("HIVProgramId"));

      patientsWithNoCD4 = getPatientWithoutAgivenConcept(cd4);

      patientsInHIVProgram = getPatientsCurrentlyInHIVProgram(hivProgram);

      for (Patient patient : patientsInHIVProgram) {
        if (patientsWithNoCD4.contains(patient)) {
          patients.add(patient);
        }
      }
      DataqualityFormController.setMsgToDisplay(
          "tracdataquality.indicator.patientWithHIVPositiveAndNoCD4");
      log.info("bottom  patientWithHIVPositiveAndNoCD4");
    } else if (programIdKey.equals("patientWithNoWhoStage")) {
      log.info("top  patientWithNoWhoStage");
      Concept concept = getConcept(getGlobalProperty("concept.whoStage"));
      patients = getPatientWithoutAgivenConcept(concept);
      DataqualityFormController.setMsgToDisplay("tracdataquality.indicator.patientWithNoWhoStage");
      log.info("bottom  patientWithNoWhoStage");
    } else if (programIdKey.equals("patientWithMoreKgs")) {
      log.info("top  patientWithMoreKgs");
      // log.info("!!!!!!!!!!!!!!!!!!!!!!!! am getting in if statment");
      Concept concept = getConcept(getGlobalProperty("concept.weight"));
      // log.info("  !!!@@@@###$$%%^^&&**(())__++++++++++++++++  "+concept);
      double valueRange = Double.parseDouble(valueRangeType);
      // log.info("!!!!!!!!!!!!!!!!!!!!!!!  !!!@@@@###$$%%^^&&**(())__++++++++++++++++
      // "+valueRange);
      patients = getPatientsWithMoreValueOnConcept(concept, valueRange);
      DataqualityFormController.setMsgToDisplay(
          "Patients with more than " + valueRange + "   Weight");
      log.info("bottom  patientWithMoreKgs");
    } else if (programIdKey.equals("patientsWithMoreHeight")) {
      log.info("top  patientsWithMoreHeight");

      Concept concept = getConcept(getGlobalProperty("concept.height"));
      double valueRange = Double.parseDouble(valueRangeType);
      patients = getPatientsWithMoreValueOnConcept(concept, valueRange);
      DataqualityFormController.setMsgToDisplay(
          "Patients with more than " + valueRange + "   height");
      log.info("bottom  patientsWithMoreHeight");
    } else if (programIdKey.equals("patientsWithMoreBMI")) {
      log.info("top  patientsWithMoreBMI");
      Concept concept = getConcept(getGlobalProperty("concept.BMI"));
      double valueRange = Double.parseDouble(valueRangeType);
      patients = getPatientsWithMoreValueOnConcept(concept, valueRange);
      DataqualityFormController.setMsgToDisplay(
          "Patients with more than  " + valueRange + "   BMI");
      log.info("bottom  patientsWithMoreBMI");
    } else if (programIdKey.equals("patientsWithMoreBLOODOXYGENSATURATION")) {
      log.info("top  patientsWithMoreBLOODOXYGENSATURATION");
      double valueRange = Double.parseDouble(valueRangeType);
      patients =
          getPatientsWithMoreValueOnConcept(
              getConcept(getGlobalProperty("concept.bloodOxygenSaturation")), valueRange);
      DataqualityFormController.setMsgToDisplay(
          "Patients with more than " + valueRange + "  BLOODOXYGENSATURATION");
      log.info("bottom  patientsWithMoreBLOODOXYGENSATURATION");
    } else if (programIdKey.equals("patientsWithMoreDIASTOLICBLOODPRESSURE")) {
      log.info("top  patientsWithMoreDIASTOLICBLOODPRESSURE");
      double valueRange = Double.parseDouble(valueRangeType);
      patients =
          getPatientsWithMoreValueOnConcept(
              getConcept(getGlobalProperty("concept.diastolicBloodPressure")), valueRange);
      DataqualityFormController.setMsgToDisplay(
          "Patients with more than " + valueRange + "  of DIASTOLICBLOODPRESSURE");
      log.info("bottom  patientsWithMoreDIASTOLICBLOODPRESSURE");
    } else if (programIdKey.equals("patientsWithMoreHEADCIRCUMFERENCE")) {
      log.info("top  patientsWithMoreHEADCIRCUMFERENCE");
      double valueRange = Double.parseDouble(valueRangeType);
      patients =
          getPatientsWithMoreValueOnConcept(
              getConcept(getGlobalProperty("concept.headCircumference")), valueRange);
      DataqualityFormController.setMsgToDisplay(
          "Patients with more than " + valueRange + "   HEADCIRCUMFERENCE");
      log.info("bottom patientsWithMoreHEADCIRCUMFERENCE");
    } else if (programIdKey.equals("patientsWithMoreKARNOFSKYPERFORMANCESCORE")) {
      log.info("top  patientsWithMoreKARNOFSKYPERFORMANCESCORE");
      double valueRange = Double.parseDouble(valueRangeType);
      patients =
          getPatientsWithMoreValueOnConcept(
              getConcept(getGlobalProperty("concept.karnofskyPerformanceScore")), valueRange);
      DataqualityFormController.setMsgToDisplay(
          "Patients with more than " + valueRange + "  of KARNOFSKYPERFORMANCESCORE");
      log.info("bottom  patientsWithMoreKARNOFSKYPERFORMANCESCORE");
    } else if (programIdKey.equals("patientsWithMorePULSE")) {
      log.info("top  patientsWithMorePULSE");
      double valueRange = Double.parseDouble(valueRangeType);
      patients =
          getPatientsWithMoreValueOnConcept(
              getConcept(getGlobalProperty("concept.pulse")), valueRange);
      DataqualityFormController.setMsgToDisplay(
          "Patients with more than " + valueRange + "   PULSE");
      log.info("bottom  patientsWithMorePULSE");
    } else if (programIdKey.equals("patientsWithMoreRESPIRATORYRATE")) {
      log.info("top  patientsWithMoreRESPIRATORYRATE");
      double valueRange = Double.parseDouble(valueRangeType);
      patients =
          getPatientsWithMoreValueOnConcept(
              getConcept(getGlobalProperty("concept.respiratoryRate")), valueRange);
      DataqualityFormController.setMsgToDisplay(
          "Patients with more than " + valueRange + "   RESPIRATORYRATE");
      log.info("bottom  patientsWithMoreRESPIRATORYRATE");
    } else if (programIdKey.equals("patientsWithMoreSYSTOLICBLOODPRESSURE")) {
      log.info("top  patientsWithMoreSYSTOLICBLOODPRESSURE");
      double valueRange = Double.parseDouble(valueRangeType);
      patients =
          getPatientsWithMoreValueOnConcept(
              getConcept(getGlobalProperty("concept.systolicBloodPressure")), valueRange);
      DataqualityFormController.setMsgToDisplay(
          "Patients with more than " + valueRange + "   SYSTOLICBLOODPRESSURE");
      log.info("bottom  patientsWithMoreSYSTOLICBLOODPRESSURE");
    } else if (programIdKey.equals("patientsWithMoreTEMPERATURE")) {
      log.info("top  patientsWithMoreTEMPERATURE");
      double valueRange = Double.parseDouble(valueRangeType);
      patients =
          getPatientsWithMoreValueOnConcept(
              getConcept(getGlobalProperty("concept.temperature")), valueRange);
      DataqualityFormController.setMsgToDisplay(
          "Patients.With.More.Than" + valueRange + "  TEMPERATURE");
      log.info("bottom patientsWithMoreTEMPERATURE");
    } else if (programIdKey.equals("patientWithNoContactInformation")) {
      log.info("top  patientWithNoContactInformation");
      List<Patient> patientsWithoutPhoneNumber = new ArrayList<Patient>();
      List<Patient> patientsWithoutAlternativePhoneNumber = new ArrayList<Patient>();
      patientsWithoutPhoneNumber =
          getPatientWithoutAgivenConcept(
              getConcept(getGlobalProperty("concept.contactPhoneNumber")));
      patientsWithoutAlternativePhoneNumber =
          getPatientWithoutAgivenConcept(getConcept(getGlobalProperty("concept.phoneNumber")));
      for (Patient patient : patientsWithoutPhoneNumber) {
        if (patientsWithoutAlternativePhoneNumber.contains(patient)) {
          patients.add(patient);
        }
      }
      DataqualityFormController.setMsgToDisplay(
          "tracdataquality.indicator.patientWithNoContactInformation");
      log.info("bottom patientWithNoContactInformation");
    } else if (programIdKey.equals("patientWithNoTRACnet")) {
      log.info("top  patientWithNoTRACnet");
      // log.info("$$$$$$$$$$$$$$$$$$$$$$$$$ this is the tracnet
      // type"+getGlobalProperty("patientIdentifierType.TRACnetID"));
      patients =
          getPatientWithNoGivenIdentifier(getGlobalProperty("patientIdentifierType.TRACnetID"));
      DataqualityFormController.setMsgToDisplay(
          "tracdataquality.indicator.PatientsWithoutTRACnetID");
      log.info("bottom  patientWithNoTRACnet");
    } else if (programIdKey.equals("patientWithNoNID")) {
      log.info("top  patientWithNoNID");
      patients = getPatientWithNoGivenIdentifier(getGlobalProperty("patientIdentifierType.NID"));
      DataqualityFormController.setMsgToDisplay("tracdataquality.indicator.PatientsWithoutNID");
      log.info("bottom  patientWithNoNID");
    } else if (programIdKey.equals("exitedPatientWithProgram")) {
      log.info("top  exitedPatientWithProgram");
      List<Patient> patientsExitedFromCare = new ArrayList<Patient>();
      List<Patient> patientWithoutProgram = new ArrayList<Patient>();
      patientsExitedFromCare =
          getPatientWithAgivenConcept(getConcept(getGlobalProperty("concept.reasonExitedCare")));
      patientWithoutProgram = getPatientWithoutProgram();

      for (Patient patient : patientsExitedFromCare) {
        if (!patientWithoutProgram.contains(patient)) {
          patients.add(patient);
        }
      }
      DataqualityFormController.setMsgToDisplay(
          "tracdataquality.indicator.exitedPatientWithProgram");
      log.info("bottom  exitedPatientWithProgram");
    } else if (programIdKey.equals("patientInAnyHIVProgramWithNoHIVTestDate")) {
      log.info("top  patientInAnyHIVProgramWithNoHIVTestDate");
      //			List<Patient> patientsHIVProgram = new ArrayList<Patient>();
      List<Patient> patientsWithoutHIVTestDate = new ArrayList<Patient>();
      //			ProgramWorkflowService programService = Context.getProgramWorkflowService();
      patientsWithoutHIVTestDate =
          getPatientWithoutAdmitionModeConcept(
              getConcept(getGlobalProperty("concept.HIVTestDate")));
      log.info("number of patients with no hiv test date : " + patientsWithoutHIVTestDate.size());
      patients.addAll(patientsWithoutHIVTestDate);
      DataqualityFormController.setMsgToDisplay(
          "tracdataquality.indicator.patientInAnyHIVProgramWithNoHIVTestDate");
      log.info("bottom  patientInAnyHIVProgramWithNoHIVTestDate");
    } else if (programIdKey.equals("PatientsWhoStoppedRegimenAndReasonIsNotRecorded")) {
      log.info("top  PatientsWhoStoppedRegimenAndReasonIsNotRecorded");
      List<Integer> patientIds = new ArrayList<Integer>();

      DataQualityService serviceQualityCheck =
          ((DataQualityService) Context.getService(DataQualityService.class));
      patientIds = serviceQualityCheck.getPatientsWhoStoppedDrugWithoutDiscontinuedReason();

      for (Integer integer : patientIds) {
        Patient patient = getPatientById(integer);
        patients.add(patient);
      }
      DataqualityFormController.setMsgToDisplay(
          "tracdataquality.indicator.PatientsWhoStoppedRegimenAndReasonIsNotRecorded");
      log.info("bottom  PatientsWhoStoppedRegimenAndReasonIsNotRecorded");
    } else if (programIdKey.equals("PatientsPediatricsWhoHaveAdultWhoStage")) {
      log.info("top  PatientsPediatricsWhoHaveAdultWhoStage");
      patients = getPatientsPediatricsWhoHaveAdultWhoStage();
      DataqualityFormController.setMsgToDisplay(
          "tracdataquality.indicator.PatientsPediatricWhoHaveAdultWhoStage");
      /*log.info("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@bottom PatientsPediatricsWhoHaveAdultWhoStage"
      + patients);*/
    } else if (programIdKey.equals("PatientsAdultWhoHaveChildWhoStage")) {
      log.info("top  PatientsAdultWhoHaveChildWhoStage");
      patients = getPatientsAdultWhoHavePedsWhoStage();
      DataqualityFormController.setMsgToDisplay(
          "tracdataquality.indicator.PatientsAdultWhoHaveChildWhoStage");
      log.info("bottom  PatientsAdultWhoHaveChildWhoStage");
    } else if (programIdKey.equals("PatientsWhoAreInPMTCTWithNoCPNId")) {
      log.info("top  PatientsWhoAreInPMTCTWithNoCPNId");
      patients = getPatientsWhoAreInPMTCTWithNoCPNId();
      DataqualityFormController.setMsgToDisplay(
          "tracdataquality.indicator.PatientsInPMTCTWithNoCPNid");
      log.info("bottom  PatientsWhoAreInPMTCTWithNoCPNId");
    } else if (programIdKey.equals("PatientsWithNoReturnVisitDate")) {
      log.info("top  PatientsWithNoReturnVisitDate");
      patients =
          getPatientWithoutAgivenConcept(getConcept(getGlobalProperty("concept.returnVisitDate")));
      DataqualityFormController.setMsgToDisplay(
          "tracdataquality.indicator.PatientsWithNoReturnVisitDate");
      log.info("bottom  PatientsWithNoReturnVisitDate");
    }
    DataQualityService serviceQualityCheck =
        ((DataQualityService) Context.getService(DataQualityService.class));
    List<Integer> exitedPatient = serviceQualityCheck.getPatientsExitedFromCare();
    // log.info("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"+exitedPatient);
    // List<Integer> patientsExited = getPatientsExitedFromCare();
    for (Patient patient : patients) {
      // && !patientsExited.contains(patient.getPatientId())

      // = getPatientsExitedFromCare();
      if (!patient.isVoided() && !exitedPatient.contains(patient.getPatientId())) {

        activePatients.add(patient);
      }
    }

    Collections.sort(activePatients, new PatientSortByName());
    return activePatients;
  }
  /**
   * gets program by programId
   *
   * @param programId
   * @return
   */
  public Program getProgramByProgramId(int programId) {
    ProgramWorkflowService programService = Context.getProgramWorkflowService();
    Program program = programService.getProgram(programId);

    return program;
  }
 @Override
 public PatientState newObject() {
   return Context.getProgramWorkflowService().getPatientStateByUuid(getUuidProperty());
 }
Ejemplo n.º 25
0
  /**
   * This method produces a model containing the following mappings:
   *
   * <pre>
   *     (always)
   *          (java.util.Date) now
   *          (String) size
   *          (Locale) locale
   *          (String) portletUUID // unique for each instance of any portlet
   *          (other parameters)
   *     (if there's currently an authenticated user)
   *          (User) authenticatedUser
   *     (if the request has a patientId attribute)
   *          (Integer) patientId
   *          (Patient) patient
   *          (List<Obs>) patientObs
   *          (List<Encounter>) patientEncounters
   *          (List<DrugOrder>) patientDrugOrders
   *          (List<DrugOrder>) currentDrugOrders
   *          (List<DrugOrder>) completedDrugOrders
   *          (Obs) patientWeight // most recent weight obs
   *          (Obs) patientHeight // most recent height obs
   *          (Double) patientBmi // BMI derived from most recent weight and most recent height
   *          (String) patientBmiAsString // BMI rounded to one decimal place, or "?" if unknown
   *          (Integer) personId
   *          (if the patient has any obs for the concept in the global property 'concept.reasonExitedCare')
   *              (Obs) patientReasonForExit
   *     (if the request has a personId or patientId attribute)
   *          (Person) person
   *          (List<Relationship>) personRelationships
   *          (Map<RelationshipType, List<Relationship>>) personRelationshipsByType
   *     (if the request has an encounterId attribute)
   *          (Integer) encounterId
   *          (Encounter) encounter
   *          (Set<Obs>) encounterObs
   *     (if the request has a userId attribute)
   *          (Integer) userId
   *          (User) user
   *     (if the request has a patientIds attribute, which should be a (String) comma-separated list of patientIds)
   *          (PatientSet) patientSet
   *          (String) patientIds
   *     (if the request has a conceptIds attribute, which should be a (String) commas-separated list of conceptIds)
   *          (Map<Integer, Concept>) conceptMap
   *          (Map<String, Concept>) conceptMapByStringIds
   * </pre>
   *
   * @should calculate bmi into patientBmiAsString
   * @should not fail with empty height and weight properties
   */
  @SuppressWarnings("unchecked")
  public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    AdministrationService as = Context.getAdministrationService();
    ConceptService cs = Context.getConceptService();

    // find the portlet that was identified in the openmrs:portlet taglib
    Object uri = request.getAttribute("javax.servlet.include.servlet_path");
    String portletPath = "";
    Map<String, Object> model = null;
    {
      HttpSession session = request.getSession();
      String uniqueRequestId = (String) request.getAttribute(WebConstants.INIT_REQ_UNIQUE_ID);
      String lastRequestId =
          (String) session.getAttribute(WebConstants.OPENMRS_PORTLET_LAST_REQ_ID);
      if (uniqueRequestId.equals(lastRequestId)) {
        model =
            (Map<String, Object>) session.getAttribute(WebConstants.OPENMRS_PORTLET_CACHED_MODEL);

        // remove cached parameters
        List<String> parameterKeys = (List<String>) model.get("parameterKeys");
        for (String key : parameterKeys) {
          model.remove(key);
        }
      }
      if (model == null) {
        log.debug("creating new portlet model");
        model = new HashMap<String, Object>();
        session.setAttribute(WebConstants.OPENMRS_PORTLET_LAST_REQ_ID, uniqueRequestId);
        session.setAttribute(WebConstants.OPENMRS_PORTLET_CACHED_MODEL, model);
      }
    }

    if (uri != null) {
      long timeAtStart = System.currentTimeMillis();
      portletPath = uri.toString();

      // Allowable extensions are '' (no extension) and '.portlet'
      if (portletPath.endsWith("portlet")) portletPath = portletPath.replace(".portlet", "");
      else if (portletPath.endsWith("jsp"))
        throw new ServletException(
            "Illegal extension used for portlet: '.jsp'. Allowable extensions are '' (no extension) and '.portlet'");

      log.debug("Loading portlet: " + portletPath);

      String id = (String) request.getAttribute("org.openmrs.portlet.id");
      String size = (String) request.getAttribute("org.openmrs.portlet.size");
      Map<String, Object> params =
          (Map<String, Object>) request.getAttribute("org.openmrs.portlet.parameters");
      Map<String, Object> moreParams =
          (Map<String, Object>) request.getAttribute("org.openmrs.portlet.parameterMap");

      model.put("now", new Date());
      model.put("id", id);
      model.put("size", size);
      model.put("locale", Context.getLocale());
      model.put("portletUUID", UUID.randomUUID().toString().replace("-", ""));
      List<String> parameterKeys = new ArrayList<String>(params.keySet());
      model.putAll(params);
      if (moreParams != null) {
        model.putAll(moreParams);
        parameterKeys.addAll(moreParams.keySet());
      }
      model.put("parameterKeys", parameterKeys); // so we can clean these up in the next request

      // if there's an authenticated user, put them, and their patient set, in the model
      if (Context.getAuthenticatedUser() != null) {
        model.put("authenticatedUser", Context.getAuthenticatedUser());
      }

      Integer personId = null;

      // if a patient id is available, put patient data documented above in the model
      Object o = request.getAttribute("org.openmrs.portlet.patientId");
      if (o != null) {
        String patientVariation = "";
        Integer patientId = (Integer) o;
        if (!model.containsKey("patient")) {
          // we can't continue if the user can't view patients
          if (Context.hasPrivilege(PrivilegeConstants.VIEW_PATIENTS)) {
            Patient p = Context.getPatientService().getPatient(patientId);
            model.put("patient", p);

            // add encounters if this user can view them
            if (Context.hasPrivilege(PrivilegeConstants.VIEW_ENCOUNTERS))
              model.put(
                  "patientEncounters", Context.getEncounterService().getEncountersByPatient(p));

            if (Context.hasPrivilege(PrivilegeConstants.VIEW_OBS)) {
              List<Obs> patientObs = Context.getObsService().getObservationsByPerson(p);
              model.put("patientObs", patientObs);
              Obs latestWeight = null;
              Obs latestHeight = null;
              String bmiAsString = "?";
              try {
                String weightString = as.getGlobalProperty("concept.weight");
                ConceptNumeric weightConcept = null;
                if (StringUtils.hasLength(weightString))
                  weightConcept =
                      cs.getConceptNumeric(
                          cs.getConcept(Integer.valueOf(weightString)).getConceptId());
                String heightString = as.getGlobalProperty("concept.height");
                ConceptNumeric heightConcept = null;
                if (StringUtils.hasLength(heightString))
                  heightConcept =
                      cs.getConceptNumeric(
                          cs.getConcept(Integer.valueOf(heightString)).getConceptId());
                for (Obs obs : patientObs) {
                  if (obs.getConcept().equals(weightConcept)) {
                    if (latestWeight == null
                        || obs.getObsDatetime().compareTo(latestWeight.getObsDatetime()) > 0)
                      latestWeight = obs;
                  } else if (obs.getConcept().equals(heightConcept)) {
                    if (latestHeight == null
                        || obs.getObsDatetime().compareTo(latestHeight.getObsDatetime()) > 0)
                      latestHeight = obs;
                  }
                }
                if (latestWeight != null) model.put("patientWeight", latestWeight);
                if (latestHeight != null) model.put("patientHeight", latestHeight);
                if (latestWeight != null && latestHeight != null) {
                  double weightInKg;
                  double heightInM;
                  if (weightConcept.getUnits().equals("kg"))
                    weightInKg = latestWeight.getValueNumeric();
                  else if (weightConcept.getUnits().equals("lb"))
                    weightInKg = latestWeight.getValueNumeric() * 0.45359237;
                  else
                    throw new IllegalArgumentException(
                        "Can't handle units of weight concept: " + weightConcept.getUnits());
                  if (heightConcept.getUnits().equals("cm"))
                    heightInM = latestHeight.getValueNumeric() / 100;
                  else if (heightConcept.getUnits().equals("m"))
                    heightInM = latestHeight.getValueNumeric();
                  else if (heightConcept.getUnits().equals("in"))
                    heightInM = latestHeight.getValueNumeric() * 0.0254;
                  else
                    throw new IllegalArgumentException(
                        "Can't handle units of height concept: " + heightConcept.getUnits());
                  double bmi = weightInKg / (heightInM * heightInM);
                  model.put("patientBmi", bmi);
                  String temp = "" + bmi;
                  bmiAsString = temp.substring(0, temp.indexOf('.') + 2);
                }
              } catch (Exception ex) {
                if (latestWeight != null && latestHeight != null)
                  log.error(
                      "Failed to calculate BMI even though a weight and height were found", ex);
              }
              model.put("patientBmiAsString", bmiAsString);
            } else {
              model.put("patientObs", new HashSet<Obs>());
            }

            // information about whether or not the patient has exited care
            Obs reasonForExitObs = null;
            String reasonForExitConceptString = as.getGlobalProperty("concept.reasonExitedCare");
            if (StringUtils.hasLength(reasonForExitConceptString)) {
              Concept reasonForExitConcept = cs.getConcept(reasonForExitConceptString);
              if (reasonForExitConcept != null) {
                List<Obs> patientExitObs =
                    Context.getObsService()
                        .getObservationsByPersonAndConcept(p, reasonForExitConcept);
                if (patientExitObs != null) {
                  log.debug("Exit obs is size " + patientExitObs.size());
                  if (patientExitObs.size() == 1) {
                    reasonForExitObs = patientExitObs.iterator().next();
                    Concept exitReason = reasonForExitObs.getValueCoded();
                    Date exitDate = reasonForExitObs.getObsDatetime();
                    if (exitReason != null && exitDate != null) {
                      patientVariation = "Exited";
                    }
                  } else {
                    if (patientExitObs.size() == 0) {
                      log.debug("Patient has no reason for exit");
                    } else {
                      log.error("Too many reasons for exit - not putting data into model");
                    }
                  }
                }
              }
            }
            model.put("patientReasonForExit", reasonForExitObs);

            if (Context.hasPrivilege(PrivilegeConstants.VIEW_ORDERS)) {
              List<DrugOrder> drugOrderList = Context.getOrderService().getDrugOrdersByPatient(p);
              model.put("patientDrugOrders", drugOrderList);
              List<DrugOrder> currentDrugOrders = new ArrayList<DrugOrder>();
              List<DrugOrder> discontinuedDrugOrders = new ArrayList<DrugOrder>();
              Date rightNow = new Date();
              for (Iterator<DrugOrder> iter = drugOrderList.iterator(); iter.hasNext(); ) {
                DrugOrder next = iter.next();
                if (next.isCurrent() || next.isFuture()) currentDrugOrders.add(next);
                if (next.isDiscontinued(rightNow)) discontinuedDrugOrders.add(next);
              }
              model.put("currentDrugOrders", currentDrugOrders);
              model.put("completedDrugOrders", discontinuedDrugOrders);

              List<RegimenSuggestion> standardRegimens =
                  Context.getOrderService().getStandardRegimens();
              if (standardRegimens != null) model.put("standardRegimens", standardRegimens);
            }

            if (Context.hasPrivilege(PrivilegeConstants.VIEW_PROGRAMS)
                && Context.hasPrivilege(PrivilegeConstants.VIEW_PATIENT_PROGRAMS)) {
              model.put(
                  "patientPrograms",
                  Context.getProgramWorkflowService()
                      .getPatientPrograms(p, null, null, null, null, null, false));
              model.put(
                  "patientCurrentPrograms",
                  Context.getProgramWorkflowService()
                      .getPatientPrograms(p, null, null, new Date(), new Date(), null, false));
            }

            model.put("patientId", patientId);
            if (p != null) {
              personId = p.getPatientId();
              model.put("personId", personId);
            }

            model.put("patientVariation", patientVariation);
          }
        }
      }

      // if a person id is available, put person and relationships in the model
      if (personId == null) {
        o = request.getAttribute("org.openmrs.portlet.personId");
        if (o != null) {
          personId = (Integer) o;
          model.put("personId", personId);
        }
      }
      if (personId != null) {
        if (!model.containsKey("person")) {
          Person p = (Person) model.get("patient");
          if (p == null) p = Context.getPersonService().getPerson(personId);
          model.put("person", p);

          if (Context.hasPrivilege(PrivilegeConstants.VIEW_RELATIONSHIPS)) {
            List<Relationship> relationships = new ArrayList<Relationship>();
            relationships.addAll(Context.getPersonService().getRelationshipsByPerson(p));
            Map<RelationshipType, List<Relationship>> relationshipsByType =
                new HashMap<RelationshipType, List<Relationship>>();
            for (Relationship rel : relationships) {
              List<Relationship> list = relationshipsByType.get(rel.getRelationshipType());
              if (list == null) {
                list = new ArrayList<Relationship>();
                relationshipsByType.put(rel.getRelationshipType(), list);
              }
              list.add(rel);
            }

            model.put("personRelationships", relationships);
            model.put("personRelationshipsByType", relationshipsByType);
          }
        }
      }

      // if an encounter id is available, put "encounter" and "encounterObs" in the model
      o = request.getAttribute("org.openmrs.portlet.encounterId");
      if (o != null && !model.containsKey("encounterId")) {
        if (!model.containsKey("encounter")) {
          if (Context.hasPrivilege(PrivilegeConstants.VIEW_ENCOUNTERS)) {
            Encounter e = Context.getEncounterService().getEncounter((Integer) o);
            model.put("encounter", e);
            if (Context.hasPrivilege(PrivilegeConstants.VIEW_OBS))
              model.put("encounterObs", e.getObs());
          }
          model.put("encounterId", (Integer) o);
        }
      }

      // if a user id is available, put "user" in the model
      o = request.getAttribute("org.openmrs.portlet.userId");
      if (o != null) {
        if (!model.containsKey("user")) {
          if (Context.hasPrivilege(PrivilegeConstants.VIEW_USERS)) {
            User u = Context.getUserService().getUser((Integer) o);
            model.put("user", u);
          }
          model.put("userId", (Integer) o);
        }
      }

      // if a list of patient ids is available, make a patientset out of it
      o = request.getAttribute("org.openmrs.portlet.patientIds");
      if (o != null && !"".equals(o) && !model.containsKey("patientIds")) {
        if (!model.containsKey("patientSet")) {
          Cohort ps = new Cohort((String) o);
          model.put("patientSet", ps);
          model.put("patientIds", (String) o);
        }
      }

      o = model.get("conceptIds");
      if (o != null && !"".equals(o)) {
        if (!model.containsKey("conceptMap")) {
          log.debug("Found conceptIds parameter: " + o);
          Map<Integer, Concept> concepts = new HashMap<Integer, Concept>();
          Map<String, Concept> conceptsByStringIds = new HashMap<String, Concept>();
          String conceptIds = (String) o;
          String[] ids = conceptIds.split(",");
          for (String cId : ids) {
            try {
              Integer i = Integer.valueOf(cId);
              Concept c = cs.getConcept(i);
              concepts.put(i, c);
              conceptsByStringIds.put(i.toString(), c);
            } catch (Exception ex) {
            }
          }
          model.put("conceptMap", concepts);
          model.put("conceptMapByStringIds", conceptsByStringIds);
        }
      }

      populateModel(request, model);
      log.debug(portletPath + " took " + (System.currentTimeMillis() - timeAtStart) + " ms");
    }

    return new ModelAndView(portletPath, "model", model);
  }
  public int doStartTag() {

    records = null;

    Locale locale = Context.getLocale();

    if (name.equals("patientIdentifierType")) {
      PatientService ps = Context.getPatientService();
      records = ps.getAllPatientIdentifierTypes().iterator();
    } else if (name.equals("relationshipType")) {
      PersonService ps = Context.getPersonService();
      records = ps.getAllRelationshipTypes().iterator();
    } else if (name.equals("encounterType")) {
      EncounterService es = Context.getEncounterService();
      records = es.getAllEncounterTypes().iterator();
    } else if (name.equals("location")) {
      LocationService locServ = Context.getLocationService();
      records = locServ.getAllLocations().iterator();
    } else if (name.equals("locationHierarchy")) {
      List<LocationAndDepth> locationAndDepths = new ArrayList<LocationAndDepth>();
      List<Location> locations = Context.getLocationService().getRootLocations(true);
      populateLocationAndDepthList(locationAndDepths, locations, 0);
      records = locationAndDepths.iterator();
    } else if (name.equals("cohort")) {
      List<Cohort> cohorts = Context.getCohortService().getAllCohorts();
      records = cohorts.iterator();
    } else if (name.equals("conceptSource")) {
      List<ConceptSource> conceptSources = Context.getConceptService().getAllConceptSources(false);
      records = conceptSources.iterator();
    } else if (name.equals("form")) {
      List<Form> forms = Context.getFormService().getAllForms();
      records = forms.iterator();
    } else if (name.equals("role")) {
      List<Role> roles = Context.getUserService().getAllRoles();
      records = roles.iterator();
    } else if (name.equals("conceptMapType")) {
      List<ConceptMapType> mapTypes = Context.getConceptService().getActiveConceptMapTypes();
      records = mapTypes.iterator();
    } else if (name.equals("civilStatus")) {
      ConceptService cs = Context.getConceptService();
      Concept civilStatus = cs.getConcept(OpenmrsConstants.CIVIL_STATUS_CONCEPT_ID);
      if (civilStatus == null) {
        log.error("OpenmrsConstants.CIVIL_STATUS_CONCEPT_ID is defined incorrectly.");
      } else {
        records = civilStatus.getAnswers(false).iterator();

        Map<String, String> opts = new HashMap<String, String>();
        for (ConceptAnswer a : civilStatus.getAnswers(false)) {
          opts.put(
              a.getAnswerConcept().getConceptId().toString(),
              a.getAnswerConcept().getShortestName(locale, false).getName());
        }
        records = opts.entrySet().iterator();
        if (select != null) {
          select = select.toString() + "=" + opts.get(select);
        }
      }
    } else if (name.equals("gender")) {
      Map<String, String> opts = OpenmrsConstants.GENDER();
      records = opts.entrySet().iterator();
      if (select != null) {
        select = select.toString() + "=" + opts.get(select);
      }
    } else if (name.equals("workflowStatus")) {
      List<ProgramWorkflowState> ret = new ArrayList<ProgramWorkflowState>();
      records = ret.iterator();
    } else if (name.equals("workflowProgram")) {
      List<org.openmrs.Program> ret = Context.getProgramWorkflowService().getAllPrograms();
      records = ret.iterator();
    } else if (name.equals("role")) {
      List<Role> ret = Context.getUserService().getAllRoles();
      records = ret.iterator();
    } else if (name.equals("conceptSet")) {
      if (conceptSet == null) {
        throw new IllegalArgumentException("Must specify conceptSet");
      }
      Concept c = Context.getConceptService().getConcept(conceptSet);
      if (c == null) {
        throw new IllegalArgumentException("Can't find conceptSet " + conceptSet);
      }
      List<Concept> list = Context.getConceptService().getConceptsByConceptSet(c);
      records = list.iterator();
    } else if (name.equals("answer")) {
      if (concept == null) {
        throw new IllegalArgumentException("Must specify concept");
      }
      Concept c = Context.getConceptService().getConcept(concept);
      if (c == null) {
        log.error(
            "Can't find concept with name or id of: "
                + concept
                + " and so no answers will be returned");
        records = null;
      } else if (c.getAnswers(false) != null) {
        records = c.getAnswers(false).iterator();
      } else {
        records = new ArrayList<Concept>().iterator();
      }
    } else {
      try {
        Class<?> cls = Context.loadClass(name);
        Constructor<?> ct = cls.getConstructor();
        Iterable<?> iterable = (Iterable<?>) ct.newInstance();
        records = iterable.iterator();

      } catch (Exception e) {
        log.error(name + " not found in ForEachRecord list " + e);
      }
    }

    if (records == null || !records.hasNext()) {
      records = null;
      return SKIP_BODY;
    } else {
      return EVAL_BODY_BUFFERED;
    }
  }
Ejemplo n.º 27
0
  private static String replaceIdsWithUuidsHelper(
      String formXmlData, String attribute, String objectType) {
    // pattern to find the specified attribute and pull out its values; regex matches any characters
    // within quotes after an equals, i.e. ="a2-32" would match a232
    Pattern substitutionPattern =
        Pattern.compile(attribute + "=\"(.*?)\"", Pattern.CASE_INSENSITIVE);
    Matcher matcher = substitutionPattern.matcher(formXmlData);

    // list to keep track of any "repeat" keys we are going to have to substitute out as well
    Set<String> keysToReplace = new HashSet<String>();

    StringBuffer buffer = new StringBuffer();

    while (matcher.find()) {
      // split the group into the various ids
      String[] ids = matcher.group(1).split(",");

      StringBuffer idBuffer = new StringBuffer();
      // now loop through each id
      for (String id : ids) {
        // see if this is a concept id (i.e., is made up of one or more digits), as opposed to a
        // mapping id or a uuid, or a key used in a repeat template)
        if (id.matches("^\\d+$")) {
          // now we need to fetch the appropriate object for this id, and append the uuid to the
          // buffer
          if ("concept".equalsIgnoreCase(objectType)) {
            Concept concept = Context.getConceptService().getConcept(Integer.valueOf(id));
            idBuffer.append(concept.getUuid() + ",");
          } else if ("location".equalsIgnoreCase(objectType)) {
            Location location = Context.getLocationService().getLocation(Integer.valueOf(id));
            idBuffer.append(location.getUuid() + ",");
          } else if ("program".equalsIgnoreCase(objectType)) {
            Program program = Context.getProgramWorkflowService().getProgram(Integer.valueOf(id));
            idBuffer.append(program.getUuid() + ",");
          } else if ("person".equalsIgnoreCase(objectType)) {
            Person person = Context.getPersonService().getPerson(Integer.valueOf(id));
            idBuffer.append(person.getUuid() + ",");
          }
        } else {
          // otherwise, leave the id only
          idBuffer.append(id + ",");

          // also, if this id is a key (i.e., something in curly braces) we need to keep track of it
          // so that we can perform key substitutions
          // pattern matches one or more characters of any type within curly braces
          Matcher keyMatcher = Pattern.compile("\\{(.+)\\}").matcher(id);
          if (keyMatcher.find()) {
            keysToReplace.add(keyMatcher.group(1));
          }
        }
      }

      // trim off the trailing comma
      idBuffer.deleteCharAt(idBuffer.length() - 1);

      // now do the replacement
      // append to the buffer the matched sequence, substituting out group(1) with the updated ids
      matcher.appendReplacement(
          buffer,
          matcher.group().substring(0, matcher.start(1) - matcher.start())
              + idBuffer.toString()
              + "\"");
    }

    // append the rest of htmlform
    matcher.appendTail(buffer);

    formXmlData = buffer.toString();

    // now recursively handle any keys we have discovered during this substitution
    for (String key : keysToReplace) {
      formXmlData = replaceIdsWithUuidsHelper(formXmlData, key);
    }

    return formXmlData;
  }