private List<String> getRefTermAncestors(
      UiSessionContext context, String id, Locale locale, ConceptSource conceptSource)
      throws Exception {

    ConceptService conceptService = (ConceptService) Context.getService(ConceptService.class);

    ConceptManagementAppsService conceptManagementAppsService =
        (ConceptManagementAppsService) Context.getService(ConceptManagementAppsService.class);

    // there are no mappings so we need to send it through blank and let the user know
    if (StringUtils.isEmpty(id) || StringUtils.isBlank(id) || id.contains("empty")) {

      id = "0";
      Set<ConceptReferenceTerm> parentTerms = new HashSet<ConceptReferenceTerm>();
      Set<ConceptReferenceTerm> childTerms = new HashSet<ConceptReferenceTerm>();
      return formatByRefTermForUIWithGson(conceptService, id, childTerms, parentTerms, locale);
    }

    Set<ConceptReferenceTerm> parentTerms =
        conceptManagementAppsService.getRefTermParentReferenceTerms(
            conceptService.getConceptReferenceTerm(Integer.parseInt(id)), conceptSource);

    Set<ConceptReferenceTerm> childTerms =
        conceptManagementAppsService.getRefTermChildReferenceTerms(
            conceptService.getConceptReferenceTerm(Integer.parseInt(id)), conceptSource);

    return formatByRefTermForUIWithGson(conceptService, id, childTerms, parentTerms, locale);
  }
  @Test
  public void shouldAddNewDrugOrderWhenPrnIsTrueWIthNoDosageFrequencyOrDosageInstruction() {

    EncounterTransaction.DrugOrder drugOrder =
        new DrugOrderBuilder()
            .withBasicValues("drug-uuid", "test-concept-uuid", today, today, 3, "", "")
            .withPrn(true)
            .build();
    Concept drugConcept = new Concept(3);
    OrderType drugOrderType = new OrderType("Drug Order", "this is a drug order type");

    when(orderService.getAllOrderTypes()).thenReturn(asList(drugOrderType));
    when(conceptService.getConceptByUuid("test-concept-uuid")).thenReturn(drugConcept);
    Drug drug = new Drug();
    drug.setName("test drug");
    when(conceptService.getDrugByUuid("drug-uuid")).thenReturn(drug);

    encounterDrugOrderServiceHelper.update(encounter, asList(drugOrder));

    assertThat(encounter.getOrders().size(), is(1));
    org.openmrs.DrugOrder order = (org.openmrs.DrugOrder) encounter.getOrders().iterator().next();
    assertEquals(drugConcept, order.getConcept());
    assertEquals(drugOrderType, order.getOrderType());
    assertEquals(patient, order.getPatient());
    assertEquals(encounter, order.getEncounter());
    assertEquals(today, order.getStartDate());
    assertEquals(today, order.getAutoExpireDate());
    assertEquals(drug.getDisplayName(), order.getDrug().getDisplayName());
    assertEquals(Double.valueOf(3), order.getDose());

    assertEquals(true, order.getPrn());
    assertEquals(null, order.getFrequency());
    assertEquals(null, order.getUnits());
  }
  @Test
  public void testParsingDispositions() throws Exception {
    Concept admit =
        new ConceptBuilder(
                null,
                conceptService.getConceptDatatypeByName("N/A"),
                conceptService.getConceptClassByName("Misc"))
            .addName("Admit")
            .get();
    when(emrConceptService.getConcept("test:admit")).thenReturn(admit);
    Obs dispositionObs =
        dispositionDescriptor.buildObsGroup(
            new Disposition(
                "emrapi.admit",
                "Admit",
                "test:admit",
                Collections.<String>emptyList(),
                Collections.<DispositionObs>emptyList()),
            emrConceptService);
    encounter.addObs(doNotGoToServiceToFormatMembers(dispositionObs));
    ParsedObs parsed = parser.parseObservations(Locale.ENGLISH);

    assertThat(parsed.getDiagnoses().size(), is(0));
    assertThat(parsed.getDispositions().size(), is(1));
    assertThat(parsed.getObs().size(), is(0));
    assertThat(path(parsed.getDispositions(), 0, "disposition"), is((Object) "Admit"));
    assertThat(
        path(parsed.getDispositions(), 0, "additionalObs"), is((Object) Collections.emptyList()));
  }
 @Test
 public void shouldPurgeAConceptSource() throws Exception {
   Assert.assertNotNull(service.getConceptSourceByUuid(getUuid()));
   MockHttpServletRequest req = request(RequestMethod.DELETE, getURI() + "/" + getUuid());
   req.addParameter("purge", "");
   handle(req);
   Assert.assertNull(service.getConceptSourceByUuid(getUuid()));
 }
  /**
   * Processes requests to display a list of the current concept map types in the database
   *
   * @param model the {@link ModelMap} object
   * @param request the {@link WebRequest} object
   */
  @RequestMapping(method = RequestMethod.GET, value = CONCEPT_MAP_TYPE_LIST_URL)
  public void showConceptMapTypeList(ModelMap model, WebRequest request) {
    ConceptService conceptService = Context.getConceptService();
    List<ConceptMapType> conceptMapTypeList = null;
    conceptMapTypeList = conceptService.getConceptMapTypes(true, true);

    model.addAttribute("conceptMapTypeList", conceptMapTypeList);
  }
 @Test
 public void shouldRetireAConceptSource() throws Exception {
   Assert.assertEquals(false, service.getConceptSourceByUuid(getUuid()).isRetired());
   MockHttpServletRequest req = request(RequestMethod.DELETE, getURI() + "/" + getUuid());
   req.addParameter("!purge", "");
   final String reason = "none";
   req.addParameter("reason", reason);
   handle(req);
   Assert.assertEquals(true, service.getConceptSourceByUuid(getUuid()).isRetired());
   Assert.assertEquals(reason, service.getConceptSourceByUuid(getUuid()).getRetireReason());
 }
Esempio n. 7
0
 /** Gets or creates a Concept with a given UUID and name. */
 public static Concept getConcept(String name, String uuid, String typeUuid) {
   ConceptService conceptService = Context.getConceptService();
   Concept concept = conceptService.getConceptByUuid(uuid);
   if (concept == null) {
     concept = new Concept();
     concept.setUuid(uuid);
     concept.setShortName(new ConceptName(name, new Locale("en")));
     concept.setDatatype(conceptService.getConceptDatatypeByUuid(typeUuid));
     concept.setConceptClass(conceptService.getConceptClassByUuid(ConceptClass.MISC_UUID));
     conceptService.saveConcept(concept);
   }
   return concept;
 }
  /**
   * This is called prior to displaying a form for the first time. It tells Spring the form/command
   * object to load into the request
   *
   * @see
   *     org.springframework.web.servlet.mvc.AbstractFormController#formBackingObject(javax.servlet.http.HttpServletRequest)
   */
  protected Object formBackingObject(HttpServletRequest request) throws ServletException {

    // default empty Object
    List<ConceptClass> conceptClassList = new Vector<ConceptClass>();

    // only fill the Object if the user has authenticated properly
    if (Context.isAuthenticated()) {
      ConceptService cs = Context.getConceptService();
      conceptClassList = cs.getAllConceptClasses();
    }

    return conceptClassList;
  }
  /**
   * 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);
    }
  }
  private void verifySentinelData() {
    // Verify a few pieces of sentinel data that should have been in the packages
    assertNotNull(userService.getRole("Organizational: Doctor"));
    MetadataUtils.existing(Role.class, RolePrivilegeMetadata._Role.ORGANIZATIONAL_DOCTOR);
    MetadataUtils.existing(
        Privilege.class, RolePrivilegeMetadata._Privilege.APP_COREAPPS_FIND_PATIENT);

    assertThat(
        conceptService.getConcept(5085).getUuid(), is("5085AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"));
    assertThat(
        conceptService.getConcept(159947).getUuid(), is("159947AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"));

    assertThat(conceptService.getAllConcepts().size(), is(435));
  }
  @Test
  public void testParsingDispositionWithTransferLocation() throws Exception {
    Concept admit =
        new ConceptBuilder(
                null,
                conceptService.getConceptDatatypeByName("N/A"),
                conceptService.getConceptClassByName("Misc"))
            .addName("Transfer")
            .get();
    when(emrConceptService.getConcept("test:transfer")).thenReturn(admit);

    Obs dispositionObs =
        dispositionDescriptor.buildObsGroup(
            new Disposition(
                "emrapi.transfer",
                "Transfer",
                "test:transfer",
                Collections.<String>emptyList(),
                Collections.<DispositionObs>emptyList()),
            emrConceptService);

    Obs transferLocationObs = new Obs();
    transferLocationObs.setObsId(100);
    transferLocationObs.setConcept(dispositionDescriptor.getInternalTransferLocationConcept());
    transferLocationObs.setValueText("3");
    dispositionObs.addGroupMember(transferLocationObs);

    Location transferLocation = new Location();
    transferLocation.setName("Outpatient clinic");
    when(locationService.getLocation(3)).thenReturn(transferLocation);

    encounter.addObs(doNotGoToServiceToFormatMembers(dispositionObs));
    ParsedObs parsed = parser.parseObservations(Locale.ENGLISH);

    SimpleObject expectedTransferLocationObject =
        SimpleObject.create("obsId", transferLocationObs.getObsId());
    expectedTransferLocationObject.put("question", "Transfer location");
    expectedTransferLocationObject.put("answer", "Outpatient clinic");

    List<SimpleObject> expectedAdditionalObsList = new ArrayList<SimpleObject>();
    expectedAdditionalObsList.add(expectedTransferLocationObject);

    assertThat(parsed.getDiagnoses().size(), is(0));
    assertThat(parsed.getDispositions().size(), is(1));
    assertThat(parsed.getObs().size(), is(0));
    assertThat(path(parsed.getDispositions(), 0, "disposition"), is((Object) "Transfer"));
    assertThat(
        path(parsed.getDispositions(), 0, "additionalObs"), is((Object) expectedAdditionalObsList));
  }
  @Test
  public void addSetMembers() throws Exception {
    ConceptSetRow conceptRow = new ConceptSetRow();
    conceptRow.name = "New concept";
    conceptRow.conceptClass = "New Class";
    conceptRow.description = "some description";

    List<KeyValue> children = new ArrayList<>();
    children.add(new KeyValue("1", "Child1"));
    children.add(new KeyValue("2", "Child2"));
    conceptRow.children = children;
    Messages persistErrorMessages = conceptSetPersister.persist(conceptRow);
    assertTrue(persistErrorMessages.isEmpty());
    Context.openSession();
    Context.authenticate("admin", "test");
    Concept persistedConcept = conceptService.getConceptByName(conceptRow.name);
    assertNotNull(persistedConcept);
    assertEquals(conceptRow.name, persistedConcept.getName(Context.getLocale()).getName());
    assertEquals(conceptRow.conceptClass, persistedConcept.getConceptClass().getName());
    assertEquals("some description", persistedConcept.getDescription().getDescription());

    assertEquals(2, persistedConcept.getSetMembers().size());
    assertEquals("some description", persistedConcept.getDescription().getDescription());
    assertEquals(0, persistedConcept.getSynonyms().size());
    assertTrue(persistedConcept.isSet());
    Context.flushSession();
    Context.closeSession();
  }
  @Test
  public void should_fail_to_persist_if_conceptSetRow_introduces_cycle() throws Exception {
    ConceptSetRow row1 = new ConceptSetRow();
    row1.name = "ConceptA";
    row1.conceptClass = "New Class";
    row1.description = "some description";
    List<KeyValue> children = new ArrayList<>();
    children.add(new KeyValue("1", "Child1"));
    children.add(new KeyValue("2", "Child2"));
    row1.children = children;

    Messages persistErrorMessages = conceptSetPersister.persist(row1);
    assertTrue(persistErrorMessages.isEmpty());
    Context.openSession();
    Context.authenticate("admin", "test");
    Concept persistedConcept = conceptService.getConceptByName(row1.name);
    assertNotNull(persistedConcept);

    ConceptSetRow row2 = new ConceptSetRow();
    row2.name = "Child2";
    row2.conceptClass = "New Class";
    row2.description = "some description";
    List<KeyValue> children1 = new ArrayList<>();
    children1.add(new KeyValue("1", "ConceptA"));
    children1.add(new KeyValue("2", "Child3"));
    row2.children = children1;

    Messages persistErrorMessages1 = conceptSetPersister.persist(row2);
    assertFalse(persistErrorMessages1.isEmpty());

    Context.flushSession();
    Context.closeSession();
  }
  // loading MDS packages is expensive, so we do everything in a single test. This is typically not
  // best practice, but it speeds the build significantly.
  @Test
  public void testEverything() throws Exception {
    initializeInMemoryDatabase();
    executeDataSet("requiredDataTestDataset.xml");
    authenticate();

    // we need to make sure that if emrapi has already created its concept source, we don't
    // duplicate it
    ConceptSource emrapiSource = new EmrApiActivator().createConceptSource(conceptService);

    activator = new ReferenceMetadataActivator();
    activator.willRefreshContext();
    activator.contextRefreshed();
    activator.willStart();
    activator.started();

    verifyMetadataPackagesConfigured();

    verifySentinelData();

    // verify there's only one concept source representing the emrapi module (and we haven't
    // duplicated it)
    int count = 0;
    for (ConceptSource candidate : conceptService.getAllConceptSources()) {
      if (candidate.getName().equals(emrapiSource.getName())) {
        ++count;
      }
    }
    assertThat(count, is(1));
  }
  @Test
  public void createNewOrderFromEtOrder() throws Exception {
    Provider provider = mock(Provider.class);
    handleEncounterProvider(provider);

    Concept mrsBloodConcept = mock(Concept.class);
    when(conceptService.getConceptByUuid("bloodConceptUuid")).thenReturn(mrsBloodConcept);

    Date currentDate = new Date();

    EncounterTransaction.Concept blood =
        new EncounterTransaction.Concept("bloodConceptUuid", "blood");

    EncounterTransaction.Order etOrder = new EncounterTransaction.Order();
    etOrder.setConcept(blood);
    etOrder.setDateCreated(currentDate);

    OpenMRSOrderMapper orderMapper = new OpenMRSOrderMapper(orderService, conceptService);

    Order order = orderMapper.map(etOrder, encounter);

    Assert.assertEquals(encounter, order.getEncounter());
    Assert.assertEquals(mrsBloodConcept, order.getConcept());
    Assert.assertEquals(provider, order.getOrderer());
  }
  /**
   * This is called prior to displaying a form for the first time. It tells Spring the form/command
   * object to load into the request
   *
   * @see
   *     org.springframework.web.servlet.mvc.AbstractFormController#formBackingObject(javax.servlet.http.HttpServletRequest)
   */
  protected Object formBackingObject(HttpServletRequest request) throws ServletException {

    Drug drug = null;

    if (Context.isAuthenticated()) {
      ConceptService cs = Context.getConceptService();
      String id = request.getParameter("drugId");
      if (id != null) {
        drug = cs.getDrug(Integer.valueOf(id));
      }
    }

    if (drug == null) drug = new Drug();

    return drug;
  }
 private Concept newConcept(ConceptDatatype conceptDatatype, String conceptUuid) {
   Concept concept = new Concept();
   concept.setDatatype(conceptDatatype);
   concept.setUuid(conceptUuid);
   when(conceptService.getConceptByUuid(conceptUuid)).thenReturn(concept);
   return concept;
 }
  private HashMap<ConceptReferenceTerm, List<Concept>> getAssociatedConceptsToRefTerms(
      Set<ConceptReferenceTerm> terms) {

    ConceptService conceptService = (ConceptService) Context.getService(ConceptService.class);
    HashMap<ConceptReferenceTerm, List<Concept>> hmconceptsToRefTerms =
        new HashMap<ConceptReferenceTerm, List<Concept>>();

    for (ConceptReferenceTerm refTerm : terms) {

      List<Concept> mappedConcept =
          conceptService.getConceptsByMapping(
              refTerm.getCode(), refTerm.getConceptSource().getName(), false);
      hmconceptsToRefTerms.put(refTerm, mappedConcept);
    }
    return hmconceptsToRefTerms;
  }
 @Test
 public void testStarted() throws Exception {
   new EbolaExampleActivator().started();
   assertThat(
       conceptService.getConceptByUuid("162599AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA").getConceptId(),
       is(162599));
 }
  @Test
  public void testParsingDispositionWithDateOfDeath() throws Exception {
    Concept admit =
        new ConceptBuilder(
                null,
                conceptService.getConceptDatatypeByName("N/A"),
                conceptService.getConceptClassByName("Misc"))
            .addName("Death")
            .get();
    when(emrConceptService.getConcept("test:death")).thenReturn(admit);

    Obs dispositionObs =
        dispositionDescriptor.buildObsGroup(
            new Disposition(
                "emrapi.death",
                "Death",
                "test:death",
                Collections.<String>emptyList(),
                Collections.<DispositionObs>emptyList()),
            emrConceptService);

    Date dateOfDeath = new DateTime(2012, 2, 20, 10, 10, 10).toDate();
    Obs dateOfDeathObs = new Obs();
    dateOfDeathObs.setObsId(100);
    dateOfDeathObs.setConcept(dispositionDescriptor.getDateOfDeathConcept());
    dateOfDeathObs.setValueDate(dateOfDeath);
    dispositionObs.addGroupMember(dateOfDeathObs);

    encounter.addObs(doNotGoToServiceToFormatMembers(dispositionObs));
    ParsedObs parsed = parser.parseObservations(Locale.ENGLISH);

    SimpleObject expectedAdmissionLocationObject =
        SimpleObject.create("obsId", dateOfDeathObs.getObsId());
    expectedAdmissionLocationObject.put("question", "Date of death");
    expectedAdmissionLocationObject.put("answer", "20 Feb 2012 10:10 AM");

    List<SimpleObject> expectedAdditionalObsList = new ArrayList<SimpleObject>();
    expectedAdditionalObsList.add(expectedAdmissionLocationObject);

    assertThat(parsed.getDiagnoses().size(), is(0));
    assertThat(parsed.getDispositions().size(), is(1));
    assertThat(parsed.getObs().size(), is(0));
    assertThat(path(parsed.getDispositions(), 0, "disposition"), is((Object) "Death"));
    assertThat(
        path(parsed.getDispositions(), 0, "additionalObs"), is((Object) expectedAdditionalObsList));
  }
  private List<String> formatByRefTermForUIWithGson(
      ConceptService conceptService,
      String id,
      Set<ConceptReferenceTerm> childTerms,
      Set<ConceptReferenceTerm> parentTerms,
      Locale locale) {

    List<String> data = new ArrayList<String>();
    try {

      Gson gson = new Gson();

      ConceptReferenceTerm currentRefTerm =
          conceptService.getConceptReferenceTerm(Integer.parseInt(id));
      HashMap<ConceptReferenceTerm, List<Concept>> parentMappings =
          getAssociatedConceptsToRefTerms(parentTerms);
      HashMap<ConceptReferenceTerm, List<Concept>> childMappings =
          getAssociatedConceptsToRefTerms(childTerms);

      List<String> parents = new ArrayList<String>();
      for (ConceptReferenceTerm term : parentTerms) {

        List<Concept> mappedConcepts = parentMappings.get(term);
        List<DataObject> mappedConceptsDOList = new ArrayList<DataObject>();

        for (Concept concept : mappedConcepts) {

          DataObject mappedConceptDataObject = simplifyConcept(concept, locale);
          mappedConceptsDOList.add(mappedConceptDataObject);
        }
        DataObject refTermDataObject = simplifyReferenceTerm(term);
        parents.add(gson.toJson(simplifyMapping(mappedConceptsDOList, refTermDataObject)));
      }
      List<String> children = new ArrayList<String>();
      for (ConceptReferenceTerm term : childTerms) {

        List<Concept> mappedConcepts = childMappings.get(term);
        List<DataObject> mappedConceptsDOList = new ArrayList<DataObject>();

        for (Concept concept : mappedConcepts) {

          DataObject mappedConceptDataObject = simplifyConcept(concept, locale);
          mappedConceptsDOList.add(mappedConceptDataObject);
        }
        DataObject refTermDataObject = simplifyReferenceTerm(term);
        children.add(gson.toJson(simplifyMapping(mappedConceptsDOList, refTermDataObject)));
      }
      String currentTerm = gson.toJson(simplifyReferenceTerm(currentRefTerm));

      DataObject ancestorsDataObject = simplifyAncestors(parents, children, currentTerm);

      data.add(gson.toJson(ancestorsDataObject));

    } catch (Exception e) {
      log.error("Error generated", e);
    }
    return data;
  }
 private Concept setupConcept(ConceptService mockConceptService, String name, String mappingCode) {
   Concept concept = new Concept();
   concept.addName(new ConceptName(name, Locale.ENGLISH));
   concept.addConceptMapping(
       new ConceptMap(new ConceptReferenceTerm(emrConceptSource, mappingCode, null), sameAs));
   when(mockConceptService.getConceptByMapping(mappingCode, emrConceptSource.getName()))
       .thenReturn(concept);
   return concept;
 }
  @Test
  public void setPreferredConceptName_shouldTagShortName() throws Exception {
    metadataDeployService.installBundles(Arrays.<MetadataBundle>asList(ebolaMetadata));
    ConceptNameTag nameTag =
        MetadataUtils.existing(ConceptNameTag.class, EbolaMetadata._ConceptNameTag.PREFERRED);

    String uuid = "c607c80f-1ea9-4da3-bb88-6276ce8868dd";
    assertThat(
        conceptService.getConceptByUuid(uuid).getPreferredName(Locale.ENGLISH).getName(),
        is("WEIGHT (KG)"));

    new EbolaExampleActivator().setPreferredConceptName(conceptService, uuid, "WT");
    assertThat(
        conceptService.getConceptByUuid(uuid).getPreferredName(Locale.ENGLISH).getName(),
        is("WEIGHT (KG)"));
    assertThat(
        conceptService.getConceptByUuid(uuid).findNameTaggedWith(nameTag).getName(), is("WT"));
  }
  private void verifyMetadataPackagesConfigured() throws Exception {
    MetadataPackagesConfig config;
    {
      InputStream inputStream =
          activator.getClass().getClassLoader().getResourceAsStream(MetadataUtil.PACKAGES_FILENAME);
      String xml = IOUtils.toString(inputStream);
      config =
          Context.getSerializationService()
              .getDefaultSerializer()
              .deserialize(xml, MetadataPackagesConfig.class);
    }

    MetadataSharingService metadataSharingService =
        Context.getService(MetadataSharingService.class);

    // To catch the (common) case where someone gets the groupUuid wrong, we look for any installed
    // packages that
    // we are not expecting

    List<String> groupUuids = new ArrayList<String>();

    for (MetadataPackageConfig metadataPackage : config.getPackages()) {
      groupUuids.add(metadataPackage.getGroupUuid());
    }

    for (ImportedPackage importedPackage : metadataSharingService.getAllImportedPackages()) {
      if (!groupUuids.contains(importedPackage.getGroupUuid())) {
        fail(
            "Found a package with an unexpected groupUuid. Name: "
                + importedPackage.getName()
                + " , groupUuid: "
                + importedPackage.getGroupUuid());
      }
    }

    for (MetadataPackageConfig metadataPackage : config.getPackages()) {
      ImportedPackage installedPackage =
          metadataSharingService.getImportedPackageByGroup(metadataPackage.getGroupUuid());
      Integer actualVersion = installedPackage == null ? null : installedPackage.getVersion();
      assertEquals(
          "Failed to install "
              + metadataPackage.getFilenameBase()
              + ". Expected version: "
              + metadataPackage.getVersion()
              + " Actual version: "
              + actualVersion,
          metadataPackage.getVersion(),
          actualVersion);
    }

    // this doesn't strictly belong here, but we include it as an extra sanity check on the MDS
    // module
    for (Concept concept : conceptService.getAllConcepts()) {
      ValidateUtil.validate(concept);
    }
  }
  @Test
  public void shouldGetAConceptSourceByName() throws Exception {
    final String name = "SNOMED CT";
    MockHttpServletRequest req = request(RequestMethod.GET, getURI() + "/" + name);
    SimpleObject result = deserialize(handle(req));

    ConceptSource conceptSource = service.getConceptSourceByName(name);
    Assert.assertEquals(conceptSource.getUuid(), PropertyUtils.getProperty(result, "uuid"));
    Assert.assertEquals(conceptSource.getName(), PropertyUtils.getProperty(result, "name"));
  }
 void updateDiagnosisStatus(
     Obs diagnosisObs, BahmniDiagnosis bahmniDiagnosis, Concept bahmniDiagnosisStatusConcept) {
   Obs obs = findOrCreateObs(diagnosisObs, bahmniDiagnosisStatusConcept);
   if (bahmniDiagnosis.getDiagnosisStatusConcept() != null) {
     Concept statusConcept =
         conceptService.getConcept(bahmniDiagnosis.getDiagnosisStatusConcept().getName());
     obs.setValueCoded(statusConcept);
     addToObsGroup(diagnosisObs, obs);
   }
 }
  @RequestMapping("/module/htmlformentry/drugSearch")
  public void localizedMessage(@RequestParam("term") String query, HttpServletResponse response)
      throws IOException {

    List<Drug> drugs;

    // we want to use a later API method from 1.8+ if it is available, so we need to access it via
    // reflection
    if (OpenmrsConstants.OPENMRS_VERSION_SHORT.startsWith("1.6")
        || OpenmrsConstants.OPENMRS_VERSION_SHORT.startsWith("1.7")) {
      drugs =
          conceptService.getDrugs(query); // this method returns retired drugs, so it is not ideal
    } else {
      try {
        Object conceptService =
            Context.getService(Context.loadClass("org.openmrs.api.ConceptService"));
        Method getDrugsMethod =
            conceptService
                .getClass()
                .getMethod(
                    "getDrugs",
                    String.class,
                    Concept.class,
                    boolean.class,
                    boolean.class,
                    boolean.class,
                    Integer.class,
                    Integer.class);

        drugs =
            (List<Drug>)
                getDrugsMethod.invoke(
                    conceptService,
                    query,
                    null,
                    true,
                    false,
                    false,
                    0,
                    100); // this method excludes retired drugs

      } catch (Exception ex) {
        throw new RuntimeException(
            "Unable to access ConceptService getDrugs method via reflection", ex);
      }
    }

    List<Map<String, Object>> simplified = drugCompatibility.simplify(drugs);

    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");
    PrintWriter out = response.getWriter();

    new ObjectMapper().writeValue(out, simplified);
  }
Esempio n. 28
0
 static Obs jsonObservationToObs(
     Object jsonObservation, Patient patient, Date encounterTime, Location location) {
   Map observationObject = (Map) jsonObservation;
   String questionUuid = (String) observationObject.get(QUESTION_UUID);
   ConceptService conceptService = Context.getConceptService();
   Concept questionConcept = conceptService.getConceptByUuid(questionUuid);
   if (questionConcept == null) {
     log.warn("Question concept not found: " + questionUuid);
     return null;
   }
   Obs obs = new Obs(patient, questionConcept, encounterTime, location);
   String answerUuid = (String) observationObject.get(ANSWER_UUID);
   String answerDate = (String) observationObject.get(ANSWER_DATE);
   String answerNumber = (String) observationObject.get(ANSWER_NUMBER);
   if (answerUuid != null) {
     Concept answerConcept = conceptService.getConceptByUuid(answerUuid);
     if (answerConcept == null) {
       log.warn("Answer concept not found: " + answerUuid);
       return null;
     }
     obs.setValueCoded(answerConcept);
   } else if (answerDate != null) {
     try {
       obs.setValueDate(Utils.YYYYMMDD_UTC_FORMAT.parse(answerDate));
     } catch (ParseException e) {
       log.warn("Invalid date answer: " + answerDate);
       return null;
     }
   } else if (observationObject.containsKey(ANSWER_NUMBER)) {
     try {
       obs.setValueNumeric(Double.parseDouble(answerNumber));
     } catch (IllegalArgumentException e) {
       log.warn("Invalid numeric answer: " + answerUuid);
       return null;
     }
   } else {
     log.warn("Invalid answer type: " + observationObject);
     return null;
   }
   return obs;
 }
  @Test
  public void shouldEditAConceptSource() throws Exception {
    final String newName = "updated name";
    SimpleObject conceptSource = new SimpleObject();
    conceptSource.add("name", newName);

    String json = new ObjectMapper().writeValueAsString(conceptSource);

    MockHttpServletRequest req = request(RequestMethod.POST, getURI() + "/" + getUuid());
    req.setContent(json.getBytes());
    handle(req);
    Assert.assertEquals(newName, service.getConceptSourceByUuid(getUuid()).getName());
  }
  @Test
  public void shouldGetAConceptSourceByUuid() throws Exception {

    MockHttpServletRequest req = request(RequestMethod.GET, getURI() + "/" + getUuid());
    SimpleObject result = deserialize(handle(req));

    ConceptSource conceptSource = service.getConceptSourceByUuid(getUuid());
    Assert.assertEquals(conceptSource.getUuid(), PropertyUtils.getProperty(result, "uuid"));
    Assert.assertEquals(conceptSource.getName(), PropertyUtils.getProperty(result, "name"));
    Assert.assertEquals(conceptSource.getHl7Code(), PropertyUtils.getProperty(result, "hl7Code"));
    Assert.assertEquals(
        conceptSource.getDescription(), PropertyUtils.getProperty(result, "description"));
  }