/** @see org.openmrs.api.EncounterService#getEncountersByPatientIdentifier(java.lang.String) */
  @Transactional(readOnly = true)
  public List<Encounter> getEncountersByPatientIdentifier(String identifier) throws APIException {
    if (identifier == null) {
      throw new IllegalArgumentException(
          "The 'identifier' parameter is required and cannot be null");
    }

    List<Encounter> encs = new Vector<Encounter>();
    for (Patient p : Context.getPatientService().getPatients(null, identifier, null, false)) {
      encs.addAll(Context.getEncounterService().getEncountersByPatientId(p.getPatientId()));
    }
    return Context.getEncounterService().filterEncountersByViewPermissions(encs, null);
  }
  /** @see org.openmrs.api.EncounterService#retireEncounterType(EncounterType, String) */
  public EncounterType retireEncounterType(EncounterType encounterType, String reason)
      throws APIException {
    if (reason == null) {
      throw new IllegalArgumentException("The 'reason' for retiring is required");
    }

    // make sure the user has not turned off encounter types editing
    Context.getEncounterService().checkIfEncounterTypesAreLocked();

    encounterType.setRetired(true);
    encounterType.setRetireReason(reason);
    return Context.getEncounterService().saveEncounterType(encounterType);
  }
  /** @see org.openmrs.api.EncounterService#purgeEncounter(Encounter, boolean) */
  public void purgeEncounter(Encounter encounter, boolean cascade) throws APIException {

    // if authenticated user is not supposed to edit encounter of certain type
    if (!canEditEncounter(encounter, null)) {
      throw new APIException(
          "Encounter.error.privilege.required.purge",
          new Object[] {encounter.getEncounterType().getEditPrivilege()});
    }

    if (cascade) {
      ObsService obsService = Context.getObsService();
      List<Encounter> justThisEncounter = new ArrayList<Encounter>();
      justThisEncounter.add(encounter);
      List<Obs> observations = new Vector<Obs>();
      observations.addAll(
          obsService.getObservations(
              null, justThisEncounter, null, null, null, null, null, null, null, null, null, true));
      for (Obs o : observations) {
        obsService.purgeObs(o);
      }
      Set<Order> orders = encounter.getOrders();
      for (Order o : orders) {
        Context.getOrderService().purgeOrder(o);
      }
    }
    Context.getEncounterService().purgeEncounter(encounter);
  }
  /** @see org.openmrs.api.EncounterService#saveEncounterType(org.openmrs.EncounterType) */
  public EncounterType saveEncounterType(EncounterType encounterType) {
    // make sure the user has not turned off encounter types editing
    Context.getEncounterService().checkIfEncounterTypesAreLocked();

    dao.saveEncounterType(encounterType);
    return encounterType;
  }
 /**
  * @see org.openmrs.api.EncounterService#getEncounters(org.openmrs.Patient, org.openmrs.Location,
  *     java.util.Date, java.util.Date, java.util.Collection, java.util.Collection,
  *     java.util.Collection, boolean)
  */
 @Override
 @Transactional(readOnly = true)
 public List<Encounter> getEncounters(
     Patient who,
     Location loc,
     Date fromDate,
     Date toDate,
     Collection<Form> enteredViaForms,
     Collection<EncounterType> encounterTypes,
     Collection<Provider> providers,
     Collection<VisitType> visitTypes,
     Collection<Visit> visits,
     boolean includeVoided) {
   return Context.getEncounterService()
       .filterEncountersByViewPermissions(
           dao.getEncounters(
               who,
               loc,
               fromDate,
               toDate,
               enteredViaForms,
               encounterTypes,
               providers,
               visitTypes,
               visits,
               includeVoided),
           null);
 }
 /**
  * Gets the specified encounter type
  *
  * @param uuid the uuid
  * @return the encounter type
  * @throws IllegalArgumentException if no such encounter type exists
  */
 public static EncounterType getEncounterType(String uuid) {
   EncounterType ret = Context.getEncounterService().getEncounterTypeByUuid(uuid);
   if (ret == null) {
     throw new IllegalArgumentException("No such encounter type with identifier " + uuid);
   }
   return ret;
 }
  /** @see {@link ExistingOrNewVisitAssignmentHandler#beforeCreateEncounter(Encounter)} */
  @Test
  @Verifies(
      value = "should resolve encounter and visit type uuids as global property values",
      method = "beforeCreateEncounter(Encounter)")
  public void beforeCreateEncounter_shouldResolveEncounterAndVisitTypeUuidsAsGlobalPropertyValues()
      throws Exception {
    final String encounterTypeUuid = "759799ab-c9a5-435e-b671-77773ada74e4";
    final String visitTypeUuid = "c0c579b0-8e59-401d-8a4a-976a0b183519";
    Encounter encounter = Context.getEncounterService().getEncounter(1);
    Assert.assertNull(encounter.getVisit());
    Assert.assertEquals(encounterTypeUuid, encounter.getEncounterType().getUuid());

    Calendar calendar = Calendar.getInstance();
    calendar.setTime(encounter.getEncounterDatetime());
    calendar.set(Calendar.YEAR, 1900);

    encounter.setEncounterDatetime(calendar.getTime());

    GlobalProperty gp =
        new GlobalProperty(
            OpenmrsConstants.GP_ENCOUNTER_TYPE_TO_VISIT_TYPE_MAPPING,
            encounterTypeUuid + ":" + visitTypeUuid);
    Context.getAdministrationService().saveGlobalProperty(gp);

    new ExistingOrNewVisitAssignmentHandler().beforeCreateEncounter(encounter);

    Assert.assertNotNull(encounter.getVisit());

    // should be set according toencounterTypeUuid:visitTypeUuid
    Assert.assertEquals(1, encounter.getEncounterType().getEncounterTypeId().intValue());
    Assert.assertEquals(
        Context.getVisitService().getVisitTypeByUuid(visitTypeUuid),
        encounter.getVisit().getVisitType());
  }
  /** @see {@link ExistingVisitAssignmentHandler#beforeCreateEncounter(Encounter)} */
  @Test
  @Verifies(
      value = "should assign mapping global property visit type",
      method = "beforeCreateEncounter(Encounter)")
  public void beforeCreateEncounter_shouldAssignMappingGlobalPropertyVisitType() throws Exception {
    Encounter encounter = Context.getEncounterService().getEncounter(1);
    Assert.assertNull(encounter.getVisit());

    Calendar calendar = Calendar.getInstance();
    calendar.setTime(encounter.getEncounterDatetime());
    calendar.set(Calendar.YEAR, 1900);

    encounter.setEncounterDatetime(calendar.getTime());

    GlobalProperty gp =
        new GlobalProperty(
            OpenmrsConstants.GP_ENCOUNTER_TYPE_TO_VISIT_TYPE_MAPPING, "3:4, 5:2, 1:2, 2:2");
    Context.getAdministrationService().saveGlobalProperty(gp);

    new ExistingOrNewVisitAssignmentHandler().beforeCreateEncounter(encounter);

    Assert.assertNotNull(encounter.getVisit());

    // should be set according to: 1:2 encounterTypeId:visitTypeId
    Assert.assertEquals(1, encounter.getEncounterType().getEncounterTypeId().intValue());
    Assert.assertEquals(
        Context.getVisitService().getVisitType(2), encounter.getVisit().getVisitType());
  }
  public void saveAndTransferFileComplexObs() {

    try {
      List<Encounter> encounters =
          Context.getEncounterService().getEncounters(null, null, null, null, null, null, true);
      Encounter lastEncounter = encounters.get(encounters.size() - 1);

      Person patient = lastEncounter.getPatient();
      ConceptComplex conceptComplex = Context.getConceptService().getConceptComplex(17);
      Location location = Context.getLocationService().getDefaultLocation();
      Obs obs = new Obs(patient, conceptComplex, new Date(), location);

      String mergedUrl = tempFile.getCanonicalPath();
      InputStream out1 = new FileInputStream(new File(mergedUrl));

      ComplexData complexData = new ComplexData(tempFile.getName(), out1);
      obs.setComplexData(complexData);
      obs.setEncounter(lastEncounter);

      Context.getObsService().saveObs(obs, null);
      tempFile.delete();

    } catch (Exception e) {
      log.error(e);
    }
  }
  /** @see org.openmrs.api.EncounterService#unvoidEncounter(org.openmrs.Encounter) */
  public Encounter unvoidEncounter(Encounter encounter) throws APIException {

    // if authenticated user is not supposed to edit encounter of certain type
    if (!canEditEncounter(encounter, null)) {
      throw new APIException(
          "Encounter.error.privilege.required.unvoid",
          new Object[] {encounter.getEncounterType().getEditPrivilege()});
    }

    String voidReason = encounter.getVoidReason();
    if (voidReason == null) {
      voidReason = "";
    }

    ObsService os = Context.getObsService();
    for (Obs o : encounter.getObsAtTopLevel(true)) {
      if (voidReason.equals(o.getVoidReason())) {
        os.unvoidObs(o);
      }
    }

    OrderService orderService = Context.getOrderService();
    for (Order o : encounter.getOrders()) {
      if (voidReason.equals(o.getVoidReason())) {
        orderService.unvoidOrder(o);
      }
    }

    encounter.setVoided(false);
    encounter.setVoidedBy(null);
    encounter.setDateVoided(null);
    encounter.setVoidReason(null);
    Context.getEncounterService().saveEncounter(encounter);
    return encounter;
  }
 /** @see org.openmrs.api.EncounterService#getEncountersByPatientId(java.lang.Integer) */
 @Transactional(readOnly = true)
 public List<Encounter> getEncountersByPatientId(Integer patientId) throws APIException {
   if (patientId == null) {
     throw new IllegalArgumentException("The 'patientId' parameter is requred and cannot be null");
   }
   return Context.getEncounterService()
       .filterEncountersByViewPermissions(dao.getEncountersByPatientId(patientId), null);
 }
 /** @see org.openmrs.api.EncounterService#getEncountersByPatient(org.openmrs.Patient) */
 @Transactional(readOnly = true)
 public List<Encounter> getEncountersByPatient(Patient patient) throws APIException {
   if (patient == null) {
     throw new IllegalArgumentException("The 'patient' parameter is requred and cannot be null");
   }
   return Context.getEncounterService()
       .getEncounters(patient, null, null, null, null, null, null, false);
 }
 /**
  * @see org.openmrs.api.EncounterService#getEncounters(java.lang.String, java.lang.Integer,
  *     java.lang.Integer, boolean)
  */
 @Override
 @Transactional(readOnly = true)
 public List<Encounter> getEncounters(
     String query, Integer start, Integer length, boolean includeVoided) throws APIException {
   return Context.getEncounterService()
       .filterEncountersByViewPermissions(
           dao.getEncounters(query, null, start, length, includeVoided), null);
 }
 /**
  * @see org.openmrs.api.EncounterService#retireEncounterRole(org.openmrs.EncounterRole, String)
  */
 @Override
 public EncounterRole retireEncounterRole(EncounterRole encounterRole, String reason)
     throws APIException {
   if (reason == null) {
     throw new IllegalArgumentException("The 'reason' for retiring is required");
   }
   return Context.getEncounterService().saveEncounterRole(encounterRole);
 }
  public static Set<Encounter> generateEncountersFromSearchResults() {
    SearchAPI searchAPI = SearchAPI.getInstance();
    Set<Encounter> encounters = new HashSet<Encounter>();
    List<ChartListItem> searchResultsList = searchAPI.getResults();
    for (ChartListItem item : searchResultsList) {
      if (item != null
          && item instanceof EncounterItem
          && ((EncounterItem) item).getEncounterId() != null) {
        int itemEncounterId = ((EncounterItem) item).getEncounterId();

        Encounter encounter = Context.getEncounterService().getEncounter(itemEncounterId);
        if (encounter != null) {
          encounters.add(Context.getEncounterService().getEncounter(itemEncounterId));
        }
      }
    }
    return encounters;
  }
 public static List<Encounter> getEncountersByTreatment(Patient patient, String treatmentType) {
   List<Encounter> encounters = Context.getEncounterService().getEncountersByPatient(patient);
   List<Encounter> treatmentEncounters = new ArrayList<Encounter>();
   for (Encounter encounter : encounters) {
     if (!encounter.isVoided() && treatmentType.equals(encounter.getEncounterType().getName())) {
       treatmentEncounters.add(encounter);
     }
   }
   return treatmentEncounters;
 }
 /**
  * @see org.openmrs.api.EncounterService#getEncountersByVisitsAndPatient(org.openmrs.Patient,
  *     boolean, java.lang.String, java.lang.Integer, java.lang.Integer)
  */
 @Override
 @Transactional(readOnly = true)
 public List<Encounter> getEncountersByVisitsAndPatient(
     Patient patient, boolean includeVoided, String query, Integer start, Integer length)
     throws APIException {
   return Context.getEncounterService()
       .filterEncountersByViewPermissions(
           dao.getEncountersByVisitsAndPatient(patient, includeVoided, query, start, length),
           null);
 }
  @RequestMapping("/module/hirifxray/deleteXray.form")
  public String deleteXray(
      ModelMap model, @RequestParam(value = "xrayId", required = true) Encounter encounter)
      throws Exception {

    Integer pId = encounter.getPatient().getPatientId();
    Context.getEncounterService().voidEncounter(encounter, "Deleting xray");

    return "redirect:/module/hirifxray/participant.form?id=" + pId;
  }
  @Test
  @Verifies(
      value = "should return encounter with all child objects voided according to schema",
      method = "voidEncounterByHtmlFormSchema")
  public void testVoidEncounterByHtmlFormSchema_shouldHandleDrugOrderCorrectly() throws Exception {
    executeDataSet(
        XML_DATASET_PATH + new TestUtil().getTestDatasetFilename(XML_REGRESSION_TEST_DATASET));
    Encounter e = new Encounter();
    e.setPatient(Context.getPatientService().getPatient(2));
    Date date = Context.getDateFormat().parse("01/02/2003");
    e.setDateCreated(new Date());
    e.setEncounterDatetime(date);
    e.setLocation(Context.getLocationService().getLocation(2));
    e.setProvider(Context.getPersonService().getPerson(502));
    TestUtil.addObs(e, 1, 5000, date); // a matching obs

    DrugOrder dor = new DrugOrder();
    dor.setVoided(false);
    dor.setConcept(Context.getConceptService().getConcept(792));
    dor.setCreator(Context.getUserService().getUser(1));
    dor.setDateCreated(new Date());
    dor.setDiscontinued(false);
    dor.setDrug(Context.getConceptService().getDrug(2));
    dor.setOrderType(Context.getOrderService().getOrderType(1));
    dor.setPatient(Context.getPatientService().getPatient(2));
    dor.setStartDate(new Date());
    e.addOrder(dor);

    Context.getEncounterService().saveEncounter(e);

    Form form = new Form();
    HtmlForm htmlform = new HtmlForm();
    htmlform.setForm(form);
    form.setEncounterType(new EncounterType());
    htmlform.setDateChanged(new Date());
    htmlform.setXmlData(
        new TestUtil()
            .loadXmlFromFile(
                XML_DATASET_PATH + "returnSectionsAndConceptsInSectionsTestFormWithGroups.xml"));

    HtmlFormEntryUtil.voidEncounterByHtmlFormSchema(e, htmlform, "test void reason");

    // this is going to test out the voided state of the obs in the encounter after processing:
    // order was matched, so order was voided, and because that's the only thing in the encounter,
    // encounter was voided too.
    Assert.assertTrue(e.isVoided());
    Assert.assertTrue(e.getVoidReason().equals("test void reason"));
    for (Order o : e.getOrders()) {
      Assert.assertTrue(o.isVoided());
      Assert.assertTrue(o.getVoidReason().equals("test void reason"));
    }
    for (Obs o : e.getAllObs(true)) {
      Assert.assertTrue(o.getVoidReason().equals("test void reason"));
    }
  }
 @Override
 public Encounter save(Encounter delegate) {
   // This is a hack to save encounterProviders correctly. Without this they are created without
   // encounter_id in
   // the database.
   for (EncounterProvider ep : delegate.getEncounterProviders()) {
     ep.setEncounter(delegate);
   }
   Context.getEncounterService().saveEncounter(delegate);
   return delegate;
 }
  @Test
  @Verifies(value = "should delete encounter correctly", method = "voidEncounterByHtmlFormSchema")
  public void testVoidEncounterByHtmlFormSchema_shouldDeleteEncounter() throws Exception {
    executeDataSet(
        XML_DATASET_PATH + new TestUtil().getTestDatasetFilename(XML_REGRESSION_TEST_DATASET));
    Encounter e = new Encounter();
    e.setPatient(Context.getPatientService().getPatient(2));
    Date date = Context.getDateFormat().parse("01/02/2003");
    e.setDateCreated(new Date());
    e.setEncounterDatetime(date);
    e.setLocation(Context.getLocationService().getLocation(2));
    e.setProvider(Context.getPersonService().getPerson(502));
    TestUtil.addObs(e, 3, 5000, date); // adding an un-matched, voided Obs
    for (Obs o : e.getAllObs(true)) {
      o.setVoided(true);
      o.setVoidedBy(Context.getUserService().getUser(1));
      o.setVoidReason("blah");
      o.setDateVoided(new Date());
    }

    // and adding a voided drug order
    DrugOrder dor = new DrugOrder();
    dor.setVoided(false);
    dor.setConcept(Context.getConceptService().getConcept(792));
    dor.setCreator(Context.getUserService().getUser(1));
    dor.setDateCreated(new Date());
    dor.setDiscontinued(false);
    dor.setDrug(Context.getConceptService().getDrug(2));
    dor.setOrderType(Context.getOrderService().getOrderType(1));
    dor.setPatient(Context.getPatientService().getPatient(2));
    dor.setVoided(true);
    dor.setVoidedBy(Context.getUserService().getUser(1));
    dor.setVoidReason("blah");
    dor.setDateVoided(new Date());
    dor.setStartDate(new Date());
    e.addOrder(dor);

    Context.getEncounterService().saveEncounter(e);

    Form form = new Form();
    HtmlForm htmlform = new HtmlForm();
    htmlform.setForm(form);
    form.setEncounterType(new EncounterType());
    htmlform.setDateChanged(new Date());
    htmlform.setXmlData(
        new TestUtil()
            .loadXmlFromFile(
                XML_DATASET_PATH + "returnSectionsAndConceptsInSectionsTestFormWithGroups.xml"));

    HtmlFormEntryUtil.voidEncounterByHtmlFormSchema(e, htmlform, null);

    // encounter had no non-voided objects, should be voided
    Assert.assertTrue(e.isVoided());
  }
 public static Encounter getLatestEncounterByTreatment(Patient patient, String treatmentType) {
   List<Encounter> encounters = Context.getEncounterService().getEncountersByPatient(patient);
   Encounter treatmentEncounter = null;
   for (Encounter encounter : encounters) {
     if (!encounter.isVoided() && treatmentType.equals(encounter.getEncounterType().getName())) {
       if (treatmentEncounter == null) treatmentEncounter = encounter;
       else if (treatmentEncounter.getDateCreated().before(encounter.getDateCreated()))
         treatmentEncounter = encounter;
     }
   }
   return treatmentEncounter;
 }
 /** @see org.openmrs.api.EncounterService#canEditAllEncounterTypes(org.openmrs.User) */
 @Override
 @Transactional(readOnly = true)
 public boolean canEditAllEncounterTypes(User subject) {
   boolean canEdit = Boolean.TRUE;
   for (EncounterType et : Context.getEncounterService().getAllEncounterTypes()) {
     if (!userHasEncounterPrivilege(et.getEditPrivilege(), subject)) {
       canEdit = Boolean.FALSE;
       break;
     }
   }
   return canEdit;
 }
  /** @see {@link ExistingVisitAssignmentHandler#beforeCreateEncounter(Encounter)} */
  @Test
  @Verifies(
      value = "should assign existing visit if match found",
      method = "beforeCreateEncounter(Encounter)")
  public void beforeCreateEncounter_shouldAssignExistingVisitIfMatchFound() throws Exception {
    Encounter encounter = Context.getEncounterService().getEncounter(1);
    Assert.assertNull(encounter.getVisit());

    new ExistingOrNewVisitAssignmentHandler().beforeCreateEncounter(encounter);

    Assert.assertNotNull(encounter.getVisit());
  }
  /** @see org.openmrs.api.EncounterService#getEncountersByPatient(java.lang.String, boolean) */
  @Override
  @Transactional(readOnly = true)
  public List<Encounter> getEncountersByPatient(String query, boolean includeVoided)
      throws APIException {
    if (query == null) {
      throw new IllegalArgumentException("The 'query' parameter is required and cannot be null");
    }

    return Context.getEncounterService()
        .filterEncountersByViewPermissions(
            dao.getEncounters(query, null, null, null, includeVoided), null);
  }
  /**
   * Adds a new encounter with the given observations and orders.
   *
   * @param observations a list of observations
   * @param orderUuids a list of order UUIDs
   * @param patient the patient for whom to add the encounter
   * @param encounterTime the time of the encounter
   * @param changeMessage a message to be recorded with the observation
   * @param encounterTypeName the OpenMRS name for the encounter type, configured in OpenMRS
   * @param locationUuid the UUID of the location where the encounter happened
   */
  public static Encounter addEncounter(
      List observations,
      List orderUuids,
      Patient patient,
      Date encounterTime,
      String changeMessage,
      String encounterTypeName,
      String locationUuid) {
    // OpenMRS will reject the encounter if the time is in the past, even if
    // the client's clock is off by only one millisecond; work around this.
    encounterTime = Utils.fixEncounterDateTime(encounterTime);

    EncounterService encounterService = Context.getEncounterService();
    final Location location = Context.getLocationService().getLocationByUuid(locationUuid);
    if (location == null) {
      throw new InvalidObjectDataException("Location not found: " + locationUuid);
    }
    EncounterType encounterType = encounterService.getEncounterType(encounterTypeName);
    if (encounterType == null) {
      throw new InvalidObjectDataException("Encounter type not found: " + encounterTypeName);
    }

    List<Obs> obsList = new ArrayList<>();
    if (observations != null) {
      for (Object observation : observations) {
        obsList.add(jsonObservationToObs(observation, patient, encounterTime, location));
      }
    }

    if (orderUuids != null) {
      for (Object item : orderUuids) {
        obsList.add(orderUuidToObs((String) item, patient, encounterTime, location));
      }
    }

    // Write the encounter and all the observations to the database.
    Encounter encounter = new Encounter();
    encounter.setEncounterDatetime(encounterTime);
    encounter.setPatient(patient);
    encounter.setLocation(location);
    encounter.setEncounterType(encounterType);
    encounter = encounterService.saveEncounter(encounter);

    ObsService obsService = Context.getObsService();
    for (Obs obs : obsList) {
      if (obs != null) {
        encounter.addObs(obs);
        obsService.saveObs(obs, changeMessage);
      }
    }
    return encounter;
  }
  @Test
  @Verifies(
      value = "should return encounter with all child objects voided according to schema",
      method = "voidEncounterByHtmlFormSchema")
  public void testVoidEncounterByHtmlFormSchema_shouldHandleDrugOrderAndObsCorrectly()
      throws Exception {
    executeDataSet(
        XML_DATASET_PATH + new TestUtil().getTestDatasetFilename(XML_REGRESSION_TEST_DATASET));
    Encounter e = new Encounter();
    e.setPatient(Context.getPatientService().getPatient(2));
    Date date = Context.getDateFormat().parse("01/02/2003");
    e.setDateCreated(new Date());
    e.setEncounterDatetime(date);
    e.setLocation(Context.getLocationService().getLocation(2));
    e.setProvider(Context.getPersonService().getPerson(502));
    TestUtil.addObs(e, 3, 5000, date); // adding an un-matched Obs

    DrugOrder dor = new DrugOrder();
    dor.setVoided(false);
    dor.setConcept(Context.getConceptService().getConcept(792));
    dor.setCreator(Context.getUserService().getUser(1));
    dor.setDateCreated(new Date());
    dor.setDiscontinued(false);
    dor.setDrug(Context.getConceptService().getDrug(2));
    dor.setOrderType(Context.getOrderService().getOrderType(1));
    dor.setPatient(Context.getPatientService().getPatient(2));
    dor.setStartDate(new Date());
    e.addOrder(dor);

    Context.getEncounterService().saveEncounter(e);

    Form form = new Form();
    HtmlForm htmlform = new HtmlForm();
    htmlform.setForm(form);
    form.setEncounterType(new EncounterType());
    htmlform.setDateChanged(new Date());
    htmlform.setXmlData(
        new TestUtil()
            .loadXmlFromFile(
                XML_DATASET_PATH + "returnSectionsAndConceptsInSectionsTestFormWithGroups.xml"));

    HtmlFormEntryUtil.voidEncounterByHtmlFormSchema(e, htmlform, null);

    // order was matched, obs was not, so order should be voided, obs not, encounter not.
    Assert.assertTrue(!e.isVoided());
    for (Order o : e.getOrders()) {
      Assert.assertTrue(o.isVoided());
    }
    for (Obs o : e.getObs()) {
      Assert.assertTrue(!o.isVoided());
    }
  }
  public final void run() {

    EncounterService es = null;
    UserService us = null;
    try {
      while (es == null || us == null) {
        Thread.sleep(30000);
        if (RwandaPrimaryCareContextAware.getApplicationContext() != null) {
          try {
            log.warn("RwandaPrimaryCare still waiting for app context and services to load...");
            es = Context.getEncounterService();
            us = Context.getUserService();
          } catch (APIException apiEx) {
            apiEx.printStackTrace();
          }
        }
      }
    } catch (InterruptedException ex) {
      ex.printStackTrace();
    }
    try {
      Thread.sleep(10000);
      // Start new OpenMRS session on this thread
      Context.openSession();
      Context.addProxyPrivilege(OpenmrsConstants.PRIV_VIEW_ENCOUNTER_TYPES);
      Context.addProxyPrivilege(OpenmrsConstants.PRIV_MANAGE_ENCOUNTER_TYPES);
      Context.addProxyPrivilege(OpenmrsConstants.PRIV_MANAGE_PRIVILEGES);
      Context.addProxyPrivilege(OpenmrsConstants.PRIV_VIEW_PRIVILEGES);
      Context.addProxyPrivilege("Manage Encounter Roles");
      Context.addProxyPrivilege("View Visit Types");
      Context.addProxyPrivilege("Manage Visit Types");
      addMetadata();
    } catch (Exception ex) {
      ex.printStackTrace();
      throw new RuntimeException(
          "Could not pre-load rwanda primary care encounter types and privileges " + ex);
    } finally {
      Context.removeProxyPrivilege(OpenmrsConstants.PRIV_VIEW_ENCOUNTER_TYPES);
      Context.removeProxyPrivilege(OpenmrsConstants.PRIV_MANAGE_ENCOUNTER_TYPES);
      Context.removeProxyPrivilege(OpenmrsConstants.PRIV_MANAGE_PRIVILEGES);
      Context.removeProxyPrivilege(OpenmrsConstants.PRIV_VIEW_PRIVILEGES);
      Context.removeProxyPrivilege("Manage Encounter Roles");
      Context.removeProxyPrivilege("View Visit Types");
      Context.removeProxyPrivilege("Manage Visit Types");
      es = null;
      us = null;
      Context.closeSession();
      log.info("RwandaPrimaryCare loaded  metadata successfully.");
    }
  }
 @Test
 public void shouldAssignPatientToBed() throws Exception {
   PatientService patientService = Context.getPatientService();
   Patient patient = patientService.getPatient(5);
   BedDetails bedDetails = bedManagementService.getBedAssignmentDetailsByPatient(patient);
   assertNull(bedDetails);
   EncounterService encounterService = Context.getEncounterService();
   List<Encounter> encountersByPatient = encounterService.getEncountersByPatient(patient);
   bedManagementService.assignPatientToBed(patient, encountersByPatient.get(0), "10");
   BedDetails assigned = bedManagementService.getBedAssignmentDetailsByPatient(patient);
   assertNotNull(assigned);
   assertNotNull(assigned.getCurrentAssignments());
   assertNull(assigned.getLastAssignment());
 }
 /**
  * @see org.openmrs.api.EncounterService#getEncounters(org.openmrs.Patient, org.openmrs.Location,
  *     java.util.Date, java.util.Date, java.util.Collection, java.util.Collection, boolean)
  * @deprecated replaced by {@link #getEncounters(Patient, Location, Date, Date, Collection,
  *     Collection, Collection, boolean)}
  */
 @Deprecated
 @Transactional(readOnly = true)
 public List<Encounter> getEncounters(
     Patient who,
     Location loc,
     Date fromDate,
     Date toDate,
     Collection<Form> enteredViaForms,
     Collection<EncounterType> encounterTypes,
     boolean includeVoided) {
   return Context.getEncounterService()
       .getEncounters(
           who, loc, fromDate, toDate, enteredViaForms, encounterTypes, null, includeVoided);
 }