org.hl7.fhir.dstu3.model.Reference Java Examples

The following examples show how to use org.hl7.fhir.dstu3.model.Reference. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ObservationStatsBuilder.java    From org.hl7.fhir.core with Apache License 2.0 7 votes vote down vote up
private static void addAge(Bundle b, int y, int m, String v) throws FHIRException {
  Observation obs = new Observation();
  obs.setId("obs-example-age-weight-"+Integer.toString(y)+"-"+Integer.toString(m));
  obs.setSubject(new Reference().setReference("Patient/123"));
  obs.setStatus(ObservationStatus.FINAL);
  Calendar when = Calendar.getInstance();
  when.add(Calendar.YEAR, -y);
  when.add(Calendar.MONTH, m);
  obs.setEffective(new DateTimeType(when));
  obs.getCode().addCoding().setCode("29463-7").setSystem("http://loinc.org");
  obs.setValue(new Quantity());
  obs.getValueQuantity().setCode("kg");
  obs.getValueQuantity().setSystem("http://unitsofmeasure.org");
  obs.getValueQuantity().setUnit("kg");
  obs.getValueQuantity().setValue(new BigDecimal(v));
  b.addEntry().setFullUrl("http://hl7.org/fhir/Observation/"+obs.getId()).setResource(obs);
}
 
Example #2
Source File: FindingsFormatUtilTest.java    From elexis-3-core with Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void convertProdcedureRequest20() throws IOException {
	// encounter format of HAPI FHIR 2.0
	String oldContent = AllTests.getResourceAsString("/rsc/json/ProcedureRequestFormat20.json");
	assertFalse(FindingsFormatUtil.isCurrentFindingsFormat(oldContent));

	Optional<String> newContent = FindingsFormatUtil.convertToCurrentFindingsFormat(oldContent);
	assertTrue(newContent.isPresent());

	IBaseResource resource = AllTests.getJsonParser().parseResource(newContent.get());
	assertTrue(resource instanceof ProcedureRequest);
	ProcedureRequest procedureRequest = (ProcedureRequest) resource;

	// encounter changed to context
	Reference encounterRef = procedureRequest.getContext();
	assertNotNull(encounterRef);
	assertTrue(encounterRef.getReference().contains("ENCOUNTERID"));
}
 
Example #3
Source File: ArgonautConverter.java    From org.hl7.fhir.core with Apache License 2.0 6 votes vote down vote up
private void processSocialHistorySection(CDAUtilities cda, Convert convert, Element section, Context context) throws Exception {
	scanSection("Social History", section);
	int i = 0;
	for (Element c : cda.getChildren(section, "entry")) {
		Element o = cda.getChild(c, "observation");
		Observation obs = new Observation();
		obs.setId(context.baseId+"-smoking-"+(i == 0 ? "" : Integer.toString(i)));
		obs.setUserData("profile", "http://hl7.org/fhir/StructureDefinition/observation-daf-smokingstatus-dafsmokingstatus");
		i++;
		obs.setSubject(context.subjectRef);
		obs.setContext(new Reference().setReference("Encounter/"+context.encounter.getId()));
		obs.setCode(inspectCode(convert.makeCodeableConceptFromCD(cda.getChild(o, "code")), new Coding().setSystem("http://loinc.org").setCode("72166-2")));

		boolean found = false;
		for (Element e : cda.getChildren(o, "id")) {
			Identifier id = convert.makeIdentifierFromII(e);
			obs.getIdentifier().add(convert.makeIdentifierFromII(e));
		}
		if (!found) {
			obs.setStatus(ObservationStatus.FINAL);
			obs.setEffective(convert.makeDateTimeFromTS(cda.getChild(o, "effectiveTime")));
			obs.setValue(inspectCode(convert.makeCodeableConceptFromCD(cda.getChild(o, "value")), null));
			saveResource(obs, "-sh");
		}
	}
}
 
Example #4
Source File: ArgonautConverter.java    From org.hl7.fhir.core with Apache License 2.0 6 votes vote down vote up
private void makeDocumentReference(CDAUtilities cda, Convert convert, Element doc, Context context) throws Exception {
	scanSection("document", doc);
	DocumentReference ref = new DocumentReference();
	ref.setId(context.baseId+"-document");
	ref.setMasterIdentifier(convert.makeIdentifierFromII(cda.getChild(doc, "id")));
	ref.setSubject(context.subjectRef);
	ref.setType(inspectCode(convert.makeCodeableConceptFromCD(cda.getChild(doc, "code")), null));
	ref.addAuthor(context.authorRef);
	ref.setCreatedElement(convert.makeDateTimeFromTS(cda.getChild(doc, "effectiveTime")));
	ref.setIndexedElement(InstantType.now());
	ref.setStatus(DocumentReferenceStatus.CURRENT);
	ref.addSecurityLabel(inspectCode(convert.makeCodeableConceptFromCD(cda.getChild(doc, "confidentialityCode")), null));
	DocumentReferenceContentComponent cnt = ref.addContent();
	cnt.getAttachment().setContentType("application/hl7-v3+xml").setUrl("Binary/"+context.baseId).setLanguage(convertLanguage(cda.getChild(doc, "language")));
	//		for (Element ti : cda.getChildren(doc, "templateId"))
	//			cnt.addFormat().setSystem("urn:oid:1.3.6.1.4.1.19376.1.2.3").setCode(value)("urn:oid:"+ti.getAttribute("root"));
	ref.setContext(new DocumentReferenceContextComponent());
	ref.getContext().setPeriod(convert.makePeriodFromIVL(cda.getChild(cda.getChild(doc, "serviceEvent"), "effectiveTime")));
	for (CodeableConcept cc : context.encounter.getType())
		ref.getContext().addEvent(cc);
	ref.setDescription(cda.getChild(doc, "title").getTextContent());
	ref.setCustodian(new Reference().setReference("Organization/"+processOrganization(cda.getDescendent(doc, "custodian/assignedCustodian/representedCustodianOrganization"), cda, convert, context).getId()));
	Practitioner p = processPerformer(cda, convert, context, cda.getChild(doc, "legalAuthenticator"), "assignedEntity", "assignedPerson");
	ref.setAuthenticator(new Reference().setReference("Practitioner/"+p.getId()).setDisplay(p.getUserString("display")));
	saveResource(ref);
}
 
Example #5
Source File: ProfileUtilities.java    From org.hl7.fhir.core with Apache License 2.0 6 votes vote down vote up
/**
 * Finds internal references in an Element's Binding and StructureDefinition references (in TypeRef) and bases them on the given url
 * @param url - the base url to use to turn internal references into absolute references
 * @param element - the Element to update
 * @return - the updated Element
 */
private ElementDefinition updateURLs(String url, ElementDefinition element) {
  if (element != null) {
    ElementDefinition defn = element;
    if (defn.hasBinding() && defn.getBinding().getValueSet() instanceof Reference && ((Reference)defn.getBinding().getValueSet()).getReference().startsWith("#"))
      ((Reference)defn.getBinding().getValueSet()).setReference(url+((Reference)defn.getBinding().getValueSet()).getReference());
    for (TypeRefComponent t : defn.getType()) {
      if (t.hasProfile()) {
        if (t.getProfile().startsWith("#"))
          t.setProfile(url+t.getProfile());
      }
      if (t.hasTargetProfile()) {
        if (t.getTargetProfile().startsWith("#"))
          t.setTargetProfile(url+t.getTargetProfile());
      }
    }
  }
  return element;
}
 
Example #6
Source File: ProfileComparer.java    From org.hl7.fhir.core with Apache License 2.0 6 votes vote down vote up
private ElementDefinitionBindingComponent unionBindings(ElementDefinition ed, ProfileComparison outcome, String path, ElementDefinitionBindingComponent left, ElementDefinitionBindingComponent right) throws FHIRFormatError {
  ElementDefinitionBindingComponent union = new ElementDefinitionBindingComponent();
  if (left.getStrength().compareTo(right.getStrength()) < 0)
    union.setStrength(left.getStrength());
  else
    union.setStrength(right.getStrength());
  union.setDescription(mergeText(ed, outcome, path, "binding.description", left.getDescription(), right.getDescription()));
  if (Base.compareDeep(left.getValueSet(), right.getValueSet(), false))
    union.setValueSet(left.getValueSet());
  else {
    ValueSet lvs = resolveVS(outcome.left, left.getValueSet());
    ValueSet rvs = resolveVS(outcome.left, right.getValueSet());
    if (lvs != null && rvs != null)
      union.setValueSet(new Reference().setReference("#"+addValueSet(unite(ed, outcome, path, lvs, rvs))));
    else if (lvs != null)
      union.setValueSet(new Reference().setReference("#"+addValueSet(lvs)));
    else if (rvs != null)
      union.setValueSet(new Reference().setReference("#"+addValueSet(rvs)));
  }
  return union;
}
 
Example #7
Source File: ShExGenerator.java    From org.hl7.fhir.core with Apache License 2.0 6 votes vote down vote up
private ValueSet resolveBindingReference(DomainResource ctxt, Type reference) {
  if (reference instanceof UriType) {
    return context.fetchResource(ValueSet.class, ((UriType) reference).getValue().toString());
  }
  else if (reference instanceof Reference) {
    String s = ((Reference) reference).getReference();
    if (s.startsWith("#")) {
      for (Resource c : ctxt.getContained()) {
        if (c.getId().equals(s.substring(1)) && (c instanceof ValueSet))
          return (ValueSet) c;
      }
      return null;
    } else {
      return context.fetchResource(ValueSet.class, ((Reference) reference).getReference());
    }
  }
  else
    return null;
}
 
Example #8
Source File: QuestionnaireBuilder.java    From org.hl7.fhir.core with Apache License 2.0 6 votes vote down vote up
private boolean instanceOf(TypeRefComponent t, Element obj) {
  if (t.getCode().equals("Reference")) {
    if (!(obj instanceof Reference)) {
      return false;
    } else {
      String url = ((Reference) obj).getReference();
      // there are several problems here around profile matching. This process is degenerative, and there's probably nothing we can do to solve it
      if (url.startsWith("http:") || url.startsWith("https:"))
          return true;
      else if (t.hasProfile() && t.getProfile().startsWith("http://hl7.org/fhir/StructureDefinition/")) 
        return url.startsWith(t.getProfile().substring(40)+'/');
      else
        return true;
    }
  } else if (t.getCode().equals("Quantity")) {
    return obj instanceof Quantity;
  } else
    throw new NotImplementedException("Not Done Yet");
}
 
Example #9
Source File: CqlExecutionProvider.java    From cqf-ruler with Apache License 2.0 6 votes vote down vote up
private String buildIncludes(Iterable<Reference> references) {
    StringBuilder builder = new StringBuilder();
    for (Reference reference : references) {

        if (builder.length() > 0) {
            builder.append(" ");
        }

        builder.append("include ");

        // TODO: This assumes the libraries resource id is the same as the library name,
        // need to work this out better
        builder.append(reference.getReferenceElement().getIdPart());

        if (reference.getReferenceElement().getVersionIdPart() != null) {
            builder.append(" version '");
            builder.append(reference.getReferenceElement().getVersionIdPart());
            builder.append("'");
        }

        builder.append(" called ");
        builder.append(reference.getReferenceElement().getIdPart());
    }

    return builder.toString();
}
 
Example #10
Source File: MeasureOperationsProvider.java    From cqf-ruler with Apache License 2.0 6 votes vote down vote up
private void resolveReferences(Resource resource, Parameters parameters, Map<String, Resource> resourceMap) {
    List<IBase> values;
    for (BaseRuntimeChildDefinition child : this.measureResourceProvider.getContext().getResourceDefinition(resource).getChildren()) {
        values = child.getAccessor().getValues(resource);
        if (values == null || values.isEmpty()) {
            continue;
        }

        else if (values.get(0) instanceof Reference
                && ((Reference) values.get(0)).getReferenceElement().hasResourceType()
                && ((Reference) values.get(0)).getReferenceElement().hasIdPart()) {
            Resource fetchedResource = (Resource) registry
                    .getResourceDao(((Reference) values.get(0)).getReferenceElement().getResourceType())
                    .read(new IdType(((Reference) values.get(0)).getReferenceElement().getIdPart()));

            if (!resourceMap.containsKey(fetchedResource.getIdElement().getValue())) {
                parameters.addParameter(new Parameters.ParametersParameterComponent().setName("resource")
                        .setResource(fetchedResource));

                resourceMap.put(fetchedResource.getIdElement().getValue(), fetchedResource);
            }
        }
    }
}
 
Example #11
Source File: ProcedureRequest.java    From elexis-3-core with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public void setEncounter(IEncounter encounter){
	Optional<IBaseResource> resource = loadResource();
	if (resource.isPresent()) {
		org.hl7.fhir.dstu3.model.ProcedureRequest fhirProcedureRequest =
			(org.hl7.fhir.dstu3.model.ProcedureRequest) resource.get();
		fhirProcedureRequest
			.setContext(new Reference(new IdDt("Encounter", encounter.getId())));
		
		saveResource(resource.get());
	}
	
	String patientId = encounter.getPatientId();
	if (patientId != null && !patientId.isEmpty() && getPatientId() == null) {
		setPatientId(patientId);
	}
	
	getEntity().setEncounterId(encounter.getId());
}
 
Example #12
Source File: Observation.java    From elexis-3-core with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public void setEncounter(IEncounter encounter){
	Optional<IBaseResource> resource = loadResource();
	if (resource.isPresent()) {
		org.hl7.fhir.dstu3.model.Observation fhirObservation =
			(org.hl7.fhir.dstu3.model.Observation) resource.get();
		fhirObservation.setContext(new Reference(new IdDt("Encounter", encounter.getId())));
		
		saveResource(resource.get());
	}
	
	String patientId = encounter.getPatientId();
	if (patientId != null && !patientId.isEmpty() && getPatientId() == null) {
		setPatientId(patientId);
	}
	
	getEntity().setEncounterId(encounter.getId());
}
 
Example #13
Source File: ClinicalImpression.java    From elexis-3-core with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public void setEncounter(IEncounter encounter){
	Optional<IBaseResource> resource = loadResource();
	if (resource.isPresent()) {
		org.hl7.fhir.dstu3.model.ClinicalImpression fhirClinicalImpression =
			(org.hl7.fhir.dstu3.model.ClinicalImpression) resource.get();
		fhirClinicalImpression
			.setContext(new Reference(new IdDt("Encounter", encounter.getId())));
		saveResource(resource.get());
	}
	
	String patientId = encounter.getPatientId();
	if (patientId != null && !patientId.isEmpty() && getPatientId() == null) {
		setPatientId(patientId);
	}
	
	getEntity().setEncounterid(encounter.getId());
}
 
Example #14
Source File: FindingsFormatUtilTest.java    From elexis-3-core with Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void convertEncounter20() throws IOException {
	// encounter format of HAPI FHIR 2.0
	String oldContent = AllTests.getResourceAsString("/rsc/json/EncounterFormat20.json");
	assertFalse(FindingsFormatUtil.isCurrentFindingsFormat(oldContent));

	Optional<String> newContent = FindingsFormatUtil.convertToCurrentFindingsFormat(oldContent);
	assertTrue(newContent.isPresent());

	IBaseResource resource = AllTests.getJsonParser().parseResource(newContent.get());
	assertTrue(resource instanceof Encounter);
	Encounter encounter = (Encounter) resource;

	// indication changed to diagnosis
	List<DiagnosisComponent> diagnosis = encounter.getDiagnosis();
	assertNotNull(diagnosis);
	assertFalse(diagnosis.isEmpty());
	DiagnosisComponent component = diagnosis.get(0);
	Reference conditionRef = component.getCondition();
	assertNotNull(conditionRef);
	assertTrue(conditionRef.getReference().contains("CONDITIONA"));
	// patient changed to subject
	Reference subjectRef = encounter.getSubject();
	assertNotNull(subjectRef);
	assertTrue(subjectRef.getReference().contains("PATIENTID"));
}
 
Example #15
Source File: TestData.java    From bunsen with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a new MedicationRequest for testing.
 *
 * @return a FHIR MedicationRequest for testing.
 */
public static MedicationRequest newMedicationRequest() {

  MedicationRequest medicationRequest = new MedicationRequest();

  medicationRequest.setId("test-medication-request");

  CodeableConcept itemCodeableConcept = new CodeableConcept();
  itemCodeableConcept.addCoding()
      .setSystem("http://www.nlm.nih.gov/research/umls/rxnorm")
      .setCode("103109")
      .setDisplay("Vitamin E 3 MG Oral Tablet [Ephynal]")
      .setUserSelected(true);

  medicationRequest.setMedication(itemCodeableConcept);

  medicationRequest
      .setSubject(new Reference("Patient/12345").setDisplay("Here is a display for you."));

  medicationRequest.setDosageInstruction(ImmutableList.of(
      new Dosage().setTiming(new Timing().setRepeat(new TimingRepeatComponent().setCount(10)))));

  medicationRequest
      .setSubstitution(new MedicationRequestSubstitutionComponent().setAllowed(true));

  return medicationRequest;
}
 
Example #16
Source File: NarrativeGenerator.java    From org.hl7.fhir.core with Apache License 2.0 5 votes vote down vote up
private boolean generateDefinition(XhtmlNode x, CodeSystem cs, boolean header) throws FHIRFormatError, DefinitionException, IOException {
    boolean hasExtensions = false;
    Map<ConceptMap, String> mymaps = new HashMap<ConceptMap, String>();
//    for (ConceptMap a : context.findMapsForSource(cs.getValueSet())) {
//      String url = "";
//      ValueSet vsr = context.fetchResource(ValueSet.class, ((Reference) a.getTarget()).getReference());
//      if (vsr != null)
//        url = (String) vsr.getUserData("filename");
//      mymaps.put(a, url);
//    }
    // also, look in the contained resources for a concept map
    for (Resource r : cs.getContained()) {
      if (r instanceof ConceptMap) {
        ConceptMap cm = (ConceptMap) r;
        if (((Reference) cm.getSource()).getReference().equals(cs.getValueSet())) {
          String url = "";
          ValueSet vsr = context.fetchResource(ValueSet.class, ((Reference) cm.getTarget()).getReference());
          if (vsr != null)
              url = (String) vsr.getUserData("filename");
        mymaps.put(cm, url);
        }
      }
    }
    List<String> langs = new ArrayList<String>();

    if (header) {
      XhtmlNode h = x.h2();
      h.addText(cs.hasTitle() ? cs.getTitle() : cs.getName());
      addMarkdown(x, cs.getDescription());
      if (cs.hasCopyright())
        generateCopyright(x, cs);
    }

    generateProperties(x, cs);
    generateFilters(x, cs);
    hasExtensions = generateCodeSystemContent(x, cs, hasExtensions, mymaps, langs);

    return hasExtensions;
  }
 
Example #17
Source File: FhirStu3.java    From synthea with Apache License 2.0 5 votes vote down vote up
/**
 * Create an entry for the given Claim, which references a Medication.
 *
 * @param personEntry Entry for the person
 * @param bundle The Bundle to add to
 * @param encounterEntry The current Encounter
 * @param claim the Claim object
 * @param medicationEntry The Entry for the Medication object, previously created
 * @return the added Entry
 */
private static BundleEntryComponent medicationClaim(BundleEntryComponent personEntry,
    Bundle bundle, BundleEntryComponent encounterEntry, Claim claim,
    BundleEntryComponent medicationEntry) {
  org.hl7.fhir.dstu3.model.Claim claimResource = new org.hl7.fhir.dstu3.model.Claim();
  org.hl7.fhir.dstu3.model.Encounter encounterResource =
      (org.hl7.fhir.dstu3.model.Encounter) encounterEntry.getResource();

  claimResource.setStatus(ClaimStatus.ACTIVE);
  claimResource.setUse(org.hl7.fhir.dstu3.model.Claim.Use.COMPLETE);

  // duration of encounter
  claimResource.setBillablePeriod(encounterResource.getPeriod());

  claimResource.setPatient(new Reference(personEntry.getFullUrl()));
  claimResource.setOrganization(encounterResource.getServiceProvider());

  // add item for encounter
  claimResource.addItem(new org.hl7.fhir.dstu3.model.Claim.ItemComponent(new PositiveIntType(1))
      .addEncounter(new Reference(encounterEntry.getFullUrl())));

  // add prescription.
  claimResource.setPrescription(new Reference(medicationEntry.getFullUrl()));

  Money moneyResource = new Money();
  moneyResource.setValue(claim.getTotalClaimCost());
  moneyResource.setCode("USD");
  moneyResource.setSystem("urn:iso:std:iso:4217");
  claimResource.setTotal(moneyResource);

  return newEntry(bundle, claimResource);
}
 
Example #18
Source File: FhirStu3.java    From synthea with Apache License 2.0 5 votes vote down vote up
/**
 * Map the given Media element to a FHIR Media resource, and add it to the given Bundle.
 *
 * @param personEntry    The Entry for the Person
 * @param bundle         Bundle to add the Media to
 * @param encounterEntry Current Encounter entry
 * @param obs   The Observation to map to FHIR and add to the bundle
 * @return The added Entry
 */
private static BundleEntryComponent media(BundleEntryComponent personEntry, Bundle bundle,
    BundleEntryComponent encounterEntry, Observation obs) {
  org.hl7.fhir.dstu3.model.Media mediaResource =
      new org.hl7.fhir.dstu3.model.Media();

  if (obs.codes != null && obs.codes.size() > 0) {
    List<CodeableConcept> reasonList = obs.codes.stream()
        .map(code -> mapCodeToCodeableConcept(code, SNOMED_URI)).collect(Collectors.toList());
    mediaResource.setReasonCode(reasonList);
  }
  
  // Hard code as an image
  mediaResource.setType(DigitalMediaType.PHOTO);
  mediaResource.setSubject(new Reference(personEntry.getFullUrl()));

  Attachment content = (Attachment) obs.value;
  org.hl7.fhir.dstu3.model.Attachment contentResource = new org.hl7.fhir.dstu3.model.Attachment();
  
  contentResource.setContentType(content.contentType);
  contentResource.setLanguage(content.language);
  if (content.data != null) {
    contentResource.setDataElement(new org.hl7.fhir.dstu3.model.Base64BinaryType(content.data));
  }
  contentResource.setUrl(content.url);
  contentResource.setSize(content.size);
  contentResource.setTitle(content.title);
  if (content.hash != null) {
    contentResource.setHashElement(new org.hl7.fhir.dstu3.model.Base64BinaryType(content.hash));
  }
  
  mediaResource.setWidth(content.width);
  mediaResource.setHeight(content.height);
  
  mediaResource.setContent(contentResource);

  return newEntry(bundle, mediaResource);
}
 
Example #19
Source File: FhirStu3.java    From synthea with Apache License 2.0 5 votes vote down vote up
/**
 * Map the JsonObject for a Supply into a FHIR SupplyDelivery and add it to the Bundle.
 *
 * @param personEntry    The Person entry.
 * @param bundle         Bundle to add to.
 * @param supply         The supplied object to add.
 * @param encounter      The encounter during which the supplies were delivered
 * @return The added Entry.
 */
private static BundleEntryComponent supplyDelivery(BundleEntryComponent personEntry, 
        Bundle bundle, HealthRecord.Supply supply, Encounter encounter) {
 
  SupplyDelivery supplyResource = new SupplyDelivery();
  supplyResource.setStatus(SupplyDeliveryStatus.COMPLETED);
  supplyResource.setPatient(new Reference(personEntry.getFullUrl()));
  
  CodeableConcept type = new CodeableConcept();
  type.addCoding()
    .setCode("device")
    .setDisplay("Device")
    .setSystem("http://hl7.org/fhir/supply-item-type");
  supplyResource.setType(type);
  
  SupplyDeliverySuppliedItemComponent suppliedItem = new SupplyDeliverySuppliedItemComponent();
  suppliedItem.setItem(mapCodeToCodeableConcept(supply.codes.get(0), SNOMED_URI));
  
  SimpleQuantity quantity = new SimpleQuantity();
  quantity.setValue(supply.quantity);
  suppliedItem.setQuantity(quantity);
  
  supplyResource.setSuppliedItem(suppliedItem);
  
  supplyResource.setOccurrence(convertFhirDateTime(supply.start, true));
  
  return newEntry(bundle, supplyResource);
}
 
Example #20
Source File: CqlExecutionProvider.java    From cqf-ruler with Apache License 2.0 5 votes vote down vote up
public Object evaluateInContext(DomainResource instance, String cql, String patientId) {
    Iterable<Reference> libraries = getLibraryReferences(instance);

    // Provide the instance as the value of the '%context' parameter, as well as the
    // value of a parameter named the same as the resource
    // This enables expressions to access the resource by root, as well as through
    // the %context attribute
    String source = String.format(
            "library LocalLibrary using FHIR version '3.0.0' include FHIRHelpers version '3.0.0' called FHIRHelpers %s parameter %s %s parameter \"%%context\" %s define Expression: %s",
            buildIncludes(libraries), instance.fhirType(), instance.fhirType(), instance.fhirType(), cql);
    // String source = String.format("library LocalLibrary using FHIR version '1.8'
    // include FHIRHelpers version '1.8' called FHIRHelpers %s parameter %s %s
    // parameter \"%%context\" %s define Expression: %s",
    // buildIncludes(libraries), instance.fhirType(), instance.fhirType(),
    // instance.fhirType(), cql);

    LibraryLoader libraryLoader = LibraryHelper.createLibraryLoader(this.libraryResolutionProvider);

    org.cqframework.cql.elm.execution.Library library = TranslatorHelper.translateLibrary(source,
            libraryLoader.getLibraryManager(), libraryLoader.getModelManager());
    Context context = new Context(library);
    context.setParameter(null, instance.fhirType(), instance);
    context.setParameter(null, "%context", instance);
    context.setExpressionCaching(true);
    context.registerLibraryLoader(libraryLoader);
    context.setContextValue("Patient", patientId);

    context.registerDataProvider("http://hl7.org/fhir", this.providerFactory.createDataProvider("FHIR", "3.0.0"));
    return context.resolveExpressionRef("Expression").evaluate(context);
}
 
Example #21
Source File: PlanDefinitionApplyProvider.java    From cqf-ruler with Apache License 2.0 5 votes vote down vote up
@Operation(name = "$apply", idempotent = true, type = PlanDefinition.class)
public CarePlan applyPlanDefinition(
        @IdParam IdType theId,
        @RequiredParam(name="patient") String patientId,
        @OptionalParam(name="encounter") String encounterId,
        @OptionalParam(name="practitioner") String practitionerId,
        @OptionalParam(name="organization") String organizationId,
        @OptionalParam(name="userType") String userType,
        @OptionalParam(name="userLanguage") String userLanguage,
        @OptionalParam(name="userTaskContext") String userTaskContext,
        @OptionalParam(name="setting") String setting,
        @OptionalParam(name="settingContext") String settingContext)
    throws IOException, JAXBException, FHIRException
{
    PlanDefinition planDefinition = this.planDefintionDao.read(theId);

    if (planDefinition == null) {
        throw new IllegalArgumentException("Couldn't find PlanDefinition " + theId);
    }

    logger.info("Performing $apply operation on PlanDefinition/" + theId);

    CarePlanBuilder builder = new CarePlanBuilder();

    builder
            .buildDefinition(new Reference(planDefinition.getIdElement().getIdPart()))
            .buildSubject(new Reference(patientId))
            .buildStatus(CarePlan.CarePlanStatus.DRAFT);

    if (encounterId != null) builder.buildContext(new Reference(encounterId));
    if (practitionerId != null) builder.buildAuthor(new Reference(practitionerId));
    if (organizationId != null) builder.buildAuthor(new Reference(organizationId));
    if (userLanguage != null) builder.buildLanguage(userLanguage);

    Session session =
            new Session(planDefinition, builder, patientId, encounterId, practitionerId,
                    organizationId, userType, userLanguage, userTaskContext, setting, settingContext);

    return resolveActions(session);
}
 
Example #22
Source File: EncounterAccessor.java    From elexis-3-core with Eclipse Public License 1.0 5 votes vote down vote up
public List<ICondition> getIndication(DomainResource resource){
	List<ICondition> indication = new ArrayList<>();
	org.hl7.fhir.dstu3.model.Encounter fhirEncounter =
		(org.hl7.fhir.dstu3.model.Encounter) resource;
	List<DiagnosisComponent> theIndication = fhirEncounter.getDiagnosis();
	for (DiagnosisComponent component : theIndication) {
		Reference reference = component.getCondition();
		if (reference.getReference() != null) {
			String idString = reference.getReferenceElement().getIdPart();
			ModelUtil.loadFinding(idString, ICondition.class)
				.ifPresent(condition -> indication.add((ICondition) condition));
		}
	}
	return indication;
}
 
Example #23
Source File: EncounterAccessor.java    From elexis-3-core with Eclipse Public License 1.0 5 votes vote down vote up
public void setIndication(DomainResource resource, List<ICondition> indication){
	org.hl7.fhir.dstu3.model.Encounter fhirEncounter =
		(org.hl7.fhir.dstu3.model.Encounter) resource;
	List<DiagnosisComponent> theIndication = new ArrayList<>();
	for (ICondition iCondition : indication) {
		theIndication.add(new DiagnosisComponent(new Reference(new IdDt("Condition", iCondition.getId()))));
	}
	fhirEncounter.setDiagnosis(theIndication);
}
 
Example #24
Source File: Encounter.java    From elexis-3-core with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void setPatientId(String patientId){
	Optional<IBaseResource> resource = loadResource();
	if (resource.isPresent()) {
		org.hl7.fhir.dstu3.model.Encounter fhirEncounter =
			(org.hl7.fhir.dstu3.model.Encounter) resource
				.get();
		fhirEncounter.setSubject(new Reference(new IdDt("Patient", patientId)));
		saveResource(resource.get());
	}
	
	getEntity().setPatientId(patientId);
}
 
Example #25
Source File: ProcedureRequest.java    From elexis-3-core with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void setPatientId(String patientId){
	Optional<IBaseResource> resource = loadResource();
	if (resource.isPresent()) {
		org.hl7.fhir.dstu3.model.ProcedureRequest fhirProcedureRequest =
			(org.hl7.fhir.dstu3.model.ProcedureRequest) resource.get();
		fhirProcedureRequest.setSubject(new Reference(new IdDt("Patient", patientId)));
		saveResource(resource.get());
	}
	getEntity().setPatientId(patientId);
}
 
Example #26
Source File: ArgonautConverter.java    From org.hl7.fhir.core with Apache License 2.0 5 votes vote down vote up
private Observation processObservation(CDAUtilities cda, Convert convert, Context context, Element o) throws Exception {
	Observation obs = new Observation();
	obs.setId(context.baseId+"-results-"+Integer.toString(context.obsId));
	context.obsId++;
	obs.setSubject(context.subjectRef);
	obs.setContext(new Reference().setReference("Encounter/"+context.encounter.getId()));
	obs.setStatus(ObservationStatus.FINAL);
	obs.setEffective(convert.makeDateTimeFromTS(cda.getChild(o, "effectiveTime")));
	obs.setCode(inspectCode(convert.makeCodeableConceptFromCD(cda.getChild(o, "code")), null));
	obs.setInterpretation(inspectCode(convert.makeCodeableConceptFromCD(cda.getChild(o, "interpretationCode")), null));
	Element rr = cda.getChild(o, "referenceRange");
	if (rr != null)
		obs.addReferenceRange().setText(cda.getChild(cda.getChild(rr, "observationRange"), "text").getTextContent());

	Element v = cda.getChild(o, "value");
	String type = v.getAttribute("xsi:type");
	if ("ST".equals(type)) {
		obs.setUserData("profile", "http://hl7.org/fhir/StructureDefinition/observation-daf-results-dafresultobsother");
		obs.setValue(new StringType(v.getTextContent()));
	} else if ("CD".equals(type)) {
		obs.setUserData("profile", "http://hl7.org/fhir/StructureDefinition/observation-daf-results-dafresultobscode");
		obs.setValue(inspectCode(convert.makeCodeableConceptFromCD(v), null));
	} else if ("PQ".equals(type)) {
		obs.setUserData("profile", "http://hl7.org/fhir/StructureDefinition/observation-daf-results-dafresultobsquantity");
		String va = cda.getChild(o, "value").getAttribute("value");
		if (!Utilities.isDecimal(va, true)) {
			obs.setDataAbsentReason(inspectCode(new CodeableConcept().setText(va), null));
		} else
			obs.setValue(convert.makeQuantityFromPQ(cda.getChild(o, "value"), null));
	} else
		throw new Exception("Unknown type '"+type+"'");

	for (Element e : cda.getChildren(o, "id")) {
		Identifier id = convert.makeIdentifierFromII(e);
		obs.getIdentifier().add(id);
	}
	saveResource(obs, "-gen");
	return obs;
}
 
Example #27
Source File: ClinicalImpression.java    From elexis-3-core with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void setPatientId(String patientId){
	Optional<IBaseResource> resource = loadResource();
	if (resource.isPresent()) {
		org.hl7.fhir.dstu3.model.ClinicalImpression fhirClinicalImpression = (org.hl7.fhir.dstu3.model.ClinicalImpression) resource
				.get();
		fhirClinicalImpression.setSubject(new Reference(new IdDt("Patient", patientId)));
		saveResource(resource.get());
	}
	
	getEntity().setPatientid(patientId);
}
 
Example #28
Source File: DocumentReference.java    From elexis-3-core with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void setPatientId(String patientId){
	Optional<IBaseResource> resource = loadResource();
	if (resource.isPresent()) {
		org.hl7.fhir.dstu3.model.DocumentReference fhirDocumentReference =
			(org.hl7.fhir.dstu3.model.DocumentReference) resource
				.get();
		fhirDocumentReference.setSubject(new Reference(new IdDt("Patient", patientId)));
		saveResource(resource.get());
	}
	
	getEntity().setPatientId(patientId);
}
 
Example #29
Source File: ArgonautConverter.java    From org.hl7.fhir.core with Apache License 2.0 5 votes vote down vote up
private Practitioner makeAuthor(CDAUtilities cda, Convert convert, Element doc, Context context, String id) throws Exception {
	Element a = cda.getChild(doc, "author");
	scanSection("Author", a);
	Practitioner author = processPerformer(cda, convert, context, a, "assignedAuthor", "assignedPerson");
	context.authorRef = new Reference().setDisplay(author.getUserString("display")).setReference("Practitioner/"+author.getId());
	return author;
}
 
Example #30
Source File: ObservationStatsBuilder.java    From org.hl7.fhir.core with Apache License 2.0 5 votes vote down vote up
private static Observation baseVitals(Bundle b, Calendar when, int min, String name, String lCode, String text) throws FHIRFormatError {
  Observation obs = new Observation();
  obs.setId("obs-vitals-"+name+"-"+Integer.toString(min));
  obs.setSubject(new Reference().setReference("Patient/123"));
  obs.setStatus(ObservationStatus.FINAL);
  obs.setEffective(new DateTimeType(when));
  obs.addCategory().setText("Vital Signs").addCoding().setSystem("http://hl7.org/fhir/observation-category").setCode("vital-signs").setDisplay("Vital Signs");
  obs.getCode().setText(text).addCoding().setCode(lCode).setSystem("http://loinc.org");
  b.addEntry().setFullUrl("http://hl7.org/fhir/Observation/"+obs.getId()).setResource(obs);
  return obs;
}