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

The following examples show how to use org.hl7.fhir.dstu3.model.Observation. 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: Example34_ContainedResources.java    From fhirstarters with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public static void main(String[] args) {

      // Create an Observation
      Observation obs = new Observation();
      obs.setStatus(Observation.ObservationStatus.FINAL);
      obs.setValue(new StringType("This is a value"));

      // Create a Patient
      Patient pat = new Patient();
      pat.addName().setFamily("Simpson").addGiven("Homer");

      // Assign the Patient to the Observation
      obs.getSubject().setResource(pat);

      FhirContext ctx = FhirContext.forDstu3();
      String output = ctx.newJsonParser().setPrettyPrint(true).encodeResourceToString(obs);
      System.out.println(output);

   }
 
Example #3
Source File: ObservationProvider.java    From careconnect-reference-implementation with Apache License 2.0 6 votes vote down vote up
@Update
public MethodOutcome update(HttpServletRequest theRequest, @ResourceParam Observation observation, @IdParam IdType theId,@ConditionalUrlParam String theConditional, RequestDetails theRequestDetails) {
	resourcePermissionProvider.checkPermission("update");
    MethodOutcome method = new MethodOutcome();
    method.setCreated(true);
    OperationOutcome opOutcome = new OperationOutcome();
    	
    method.setOperationOutcome(opOutcome);
    try {

        Observation newObservation = observationDao.save(ctx,observation,theId,theConditional);
        method.setId(newObservation.getIdElement());
        method.setResource(newObservation);
    } catch (BaseServerResponseException srv) {
        // HAPI Exceptions pass through
        throw srv;
    } catch(Exception ex) {
        ProviderResponseLibrary.handleException(method,ex);
    }

    return method;
}
 
Example #4
Source File: ObservationProvider.java    From careconnect-reference-implementation with Apache License 2.0 6 votes vote down vote up
@Create
public MethodOutcome create(HttpServletRequest theRequest, @ResourceParam Observation observation) {

	resourcePermissionProvider.checkPermission("create");
    MethodOutcome method = new MethodOutcome();
    method.setCreated(true);
    OperationOutcome opOutcome = new OperationOutcome();
    log.info(ctx.newXmlParser().setPrettyPrint(true).encodeResourceToString(observation));
    method.setOperationOutcome(opOutcome);
    try {

        Observation newObservation = observationDao.save(ctx, observation, null, null);
        method.setId(newObservation.getIdElement());
        method.setResource(newObservation);
    } catch (BaseServerResponseException srv) {
        // HAPI Exceptions pass through
        throw srv;
    } catch(Exception ex) {
        ProviderResponseLibrary.handleException(method,ex);
    }
    return method;
}
 
Example #5
Source File: TestData.java    From bunsen with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a FHIR Observation for testing purposes.
 */
public static Observation newObservation() {

  // Observation based on https://www.hl7.org/FHIR/observation-example-bloodpressure.json.html
  Observation observation = new Observation();

  observation.setId("blood-pressure");

  Identifier identifier = observation.addIdentifier();
  identifier.setSystem("urn:ietf:rfc:3986");
  identifier.setValue("urn:uuid:187e0c12-8dd2-67e2-99b2-bf273c878281");

  observation.setStatus(Observation.ObservationStatus.FINAL);

  Quantity quantity = new Quantity();
  quantity.setValue(new java.math.BigDecimal("123.45"));
  quantity.setUnit("mm[Hg]");
  observation.setValue(quantity);

  return observation;
}
 
Example #6
Source File: BundlesTest.java    From bunsen with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetResourcesAndContainedResourcesByClass() {

  List<Class> containedClasses = ImmutableList.of(Provenance.class);

  Dataset<Row> observations = bundles
      .extractEntry(spark, bundlesWithContainedRdd, Observation.class, containedClasses);

  SparkRowConverter rowConverter = SparkRowConverter
      .forResource(fhirContext, Observation.class.getSimpleName(),
          containedClasses.stream().map(c -> c.getSimpleName()).collect(Collectors.toList()));

  Observation observation = (Observation) rowConverter
      .rowToResource(observations.head());

  Assert.assertEquals(1, observations.count());
  Assert.assertEquals(ResourceType.Provenance,
      observation.getContained().get(0).getResourceType());

  // internal references prefixed with #
  String expectedId = "#" + "11000100-4";
  Assert.assertEquals(expectedId, observation.getContained().get(0).getId());
}
 
Example #7
Source File: CCDAConverter.java    From org.hl7.fhir.core with Apache License 2.0 6 votes vote down vote up
protected SectionComponent processProceduresSection(Element section) throws Exception {
	ListResource list = new ListResource();
	for (Element entry : cda.getChildren(section, "entry")) {
		Element procedure = cda.getlastChild(entry);

		if (cda.hasTemplateId(procedure, "2.16.840.1.113883.10.20.22.4.14")) {
			processProcedure(list, procedure, ProcedureType.Procedure);
		} else if (cda.hasTemplateId(procedure, "2.16.840.1.113883.10.20.22.4.13")) {
			processProcedure(list, procedure, ProcedureType.Observation);
		} else if (cda.hasTemplateId(procedure, "2.16.840.1.113883.10.20.22.4.12")) {
			processProcedure(list, procedure, ProcedureType.Act);
		} else
			throw new Exception("Unhandled Section template ids: "+cda.showTemplateIds(procedure));
	}

	// todo: text
	SectionComponent s = new Composition.SectionComponent();
	s.setCode(convert.makeCodeableConceptFromCD(cda.getChild(section,  "code")));
	// todo: check subject
	s.addEntry(Factory.makeReference(addReference(list, "Procedures", makeUUIDReference())));
	return s;

}
 
Example #8
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 #9
Source File: CCDAConverter.java    From org.hl7.fhir.core with Apache License 2.0 5 votes vote down vote up
protected String processVitalSignsObservation(Element comp, ListResource list) throws Exception {
	Element observation = cda.getChild(comp, "observation");
	cda.checkTemplateId(observation, "2.16.840.1.113883.10.20.22.4.27");
	checkNoNegationOrNullFlavor(observation, "Vital Signs Observation");
	checkNoSubject(observation, "Vital Signs Observation");

	Observation obs = new Observation();

	//	SHALL contain at least one [1..*] id (CONF:7300).
	for (Element e : cda.getChildren(observation, "id"))
		obs.getIdentifier().add(convert.makeIdentifierFromII(e));

	// SHALL contain exactly one [1..1] code, which SHOULD be selected from ValueSet Vital Sign Result Value Set 2.16.840.1.113883.3.88.12.80.62 DYNAMIC (CONF:7301).
	obs.setCode(convert.makeCodeableConceptFromCD(cda.getChild(observation, "code"))); // all loinc codes

	// SHOULD contain zero or one [0..1] text (CONF:7302).
	// The text, if present, SHOULD contain zero or one [0..1] reference (CONF:15943).
	// The reference, if present, SHOULD contain zero or one [0..1] @value (CONF:15944).
	// This reference/@value SHALL begin with a '#' and SHALL point to its corresponding narrative (using the approach defined in CDA Release 2, section 4.3.5.1) (CONF:15945).
	// todo: put this in narrative if it exists?


	// SHALL contain exactly one [1..1] statusCode (CONF:7303).	This statusCode SHALL contain exactly one [1..1] @code="completed" Completed (CodeSystem: ActStatus 2.16.840.1.113883.5.14 STATIC) (CONF:19119).
	// ignore

	// SHALL contain exactly one [1..1] effectiveTime (CONF:7304).
	obs.setEffective(convert.makeMatchingTypeFromIVL(cda.getChild(observation, "effectiveTime")));

	//	SHALL contain exactly one [1..1] value with @xsi:type="PQ" (CONF:7305).
	obs.setValue(convert.makeQuantityFromPQ(cda.getChild(observation, "value")));

	// MAY contain zero or one [0..1] interpretationCode (CONF:7307).
	obs.setInterpretation(convert.makeCodeableConceptFromCD(cda.getChild(observation, "interpretationCode")));

	//	MAY contain zero or one [0..1] methodCode (CONF:7308).
	obs.setMethod(convert.makeCodeableConceptFromCD(cda.getChild(observation, "methodCode")));

	// MAY contain zero or one [0..1] targetSiteCode (CONF:7309).
	obs.setBodySite(convert.makeCodeableConceptFromCD(cda.getChild(observation, "targetSiteCode")));

	// MAY contain zero or one [0..1] author (CONF:7310).
	if (cda.getChild(observation, "author") != null)
		obs.getPerformer().add(makeReferenceToPractitionerForAssignedEntity(cda.getChild(observation, "author"), composition));

	// make a contained practitioner
	String n = nextRef();
	obs.setId(n);
	list.getContained().add(obs);
	return n;
}
 
Example #10
Source File: ObservationEntityToFHIRObservationTransformerTest.java    From careconnect-reference-implementation with Apache License 2.0 5 votes vote down vote up
@Test
public void testTransformObservationEntity(){
    ObservationEntity observationEntity = new ObservationEntityBuilder()
            .build();
    Observation observation = transformer.transform(observationEntity);
    assertThat(observation, not(nullValue()));
    assertThat(observation.getId(), not(nullValue()));
    assertThat(observation.getId(), equalTo((new Long(ObservationEntityBuilder.DEFAULT_ID)).toString()));
    assertThat(observation.getSubject(), not(nullValue()));
    assertThat(observation.getSubject().getReference(), equalTo("Patient/100002"));
    assertThat(observation.getEffective(), not(nullValue()));
}
 
Example #11
Source File: TestData.java    From bunsen with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a new Observation for testing.
 *
 * @return a FHIR Observation for testing.
 */
public static Observation newObservation() {
  Observation observation = new Observation();

  observation.setId("blood-pressure");

  Identifier identifier = observation.addIdentifier();
  identifier.setSystem("urn:ietf:rfc:3986");
  identifier.setValue("urn:uuid:187e0c12-8dd2-67e2-99b2-bf273c878281");

  observation.setStatus(Observation.ObservationStatus.FINAL);

  CodeableConcept obsCode = new CodeableConcept();

  observation.setCode(obsCode);

  Quantity quantity = new Quantity();
  quantity.setValue(new java.math.BigDecimal("123.45"));
  quantity.setUnit("mm[Hg]");
  quantity.setSystem("http://unitsofmeasure.org");
  observation.setValue(quantity);

  ObservationComponentComponent component = observation.addComponent();

  CodeableConcept code = new CodeableConcept()
      .addCoding(new Coding()
          .setCode("abc")
          .setSystem("PLACEHOLDER"));

  component.setCode(code);

  return observation;
}
 
Example #12
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 #13
Source File: ObservationProvider.java    From careconnect-reference-implementation with Apache License 2.0 5 votes vote down vote up
@Search
public List<Resource> search(HttpServletRequest theRequest,

                             @OptionalParam(name= Observation.SP_CATEGORY) TokenParam category,
                             @OptionalParam(name= Observation.SP_CODE) TokenOrListParam codes,
                             @OptionalParam(name= Observation.SP_DATE) DateRangeParam effectiveDate,
                             @OptionalParam(name = Observation.SP_PATIENT) ReferenceParam patient,
                             @OptionalParam(name = Observation.SP_IDENTIFIER) TokenParam identifier
        , @OptionalParam(name = Observation.SP_RES_ID) StringParam resid
        , @OptionalParam(name = Observation.SP_SUBJECT) ReferenceParam subject
        , @IncludeParam(allow = { "Observation.related" ,  "*" }) Set<Include> includes
                                   ) {
    return observationDao.search(ctx,category, codes, effectiveDate,patient, identifier,resid,subject, includes);
}
 
Example #14
Source File: ObservationProvider.java    From careconnect-reference-implementation with Apache License 2.0 5 votes vote down vote up
@Read
public Observation get(@IdParam IdType internalId) {
	
	resourcePermissionProvider.checkPermission("read");
    Observation observation = observationDao.read(ctx,internalId);
    if (observation == null) {
        throw OperationOutcomeFactory.buildOperationOutcomeException(
                new ResourceNotFoundException("No observation found for ID: " + internalId.getIdPart()),
                OperationOutcome.IssueType.NOTFOUND);
    }
    return observation;
}
 
Example #15
Source File: ObservationStatsBuilder.java    From org.hl7.fhir.core with Apache License 2.0 5 votes vote down vote up
private static void vitals(Bundle b,  Calendar base, int minutes, int diastolic, int systolic, int sat, double temp) throws FHIRFormatError {
  Calendar when = (Calendar) base.clone();
  when.add(Calendar.MINUTE, minutes);
  
  baseVitals(b, when, minutes, "sat", "59408-5", "O2 Saturation").setValue(makeQty(sat, "%", "%"));
  baseVitals(b, when, minutes, "temp", "8310-5", "Body temperature").setValue(makeQty(temp, "\u00b0C", "Cel"));
  Observation obs = baseVitals(b, when, minutes, "bp", "85354-9", "Blood pressure");
  component(obs, "8480-6", "Systolic").setValue(makeQty(systolic, "mmhg", "mm[Hg]"));
  component(obs, "8462-4", "Diastolic").setValue(makeQty(diastolic, "mmhg", "mm[Hg]"));

}
 
Example #16
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;
}
 
Example #17
Source File: ObservationRepository.java    From careconnect-reference-implementation with Apache License 2.0 5 votes vote down vote up
List<ObservationEntity> searchEntity (FhirContext ctx,
                          @OptionalParam(name= Observation.SP_CATEGORY) TokenParam category,
                          @OptionalParam(name= Observation.SP_CODE) TokenOrListParam codes,
                          @OptionalParam(name= Observation.SP_DATE) DateRangeParam effectiveDate,
                          @OptionalParam(name = Observation.SP_PATIENT) ReferenceParam patient

        ,@OptionalParam(name = Observation.SP_IDENTIFIER) TokenParam identifier
        ,@OptionalParam(name= Observation.SP_RES_ID) StringParam id
        ,@OptionalParam(name = Observation.SP_SUBJECT) ReferenceParam subject

        , @IncludeParam(allow = { "Observation.related" ,  "*" }) Set<Include> includes
);
 
Example #18
Source File: ObservationRepository.java    From careconnect-reference-implementation with Apache License 2.0 5 votes vote down vote up
List<Resource> search (FhirContext ctx,
               @OptionalParam(name= Observation.SP_CATEGORY) TokenParam category,
               @OptionalParam(name= Observation.SP_CODE) TokenOrListParam codes,
               @OptionalParam(name= Observation.SP_DATE) DateRangeParam effectiveDate,
               @OptionalParam(name = Observation.SP_PATIENT) ReferenceParam patient
, @OptionalParam(name = Observation.SP_IDENTIFIER) TokenParam identifier
, @OptionalParam(name= Observation.SP_RES_ID) StringParam id
, @OptionalParam(name = Observation.SP_SUBJECT) ReferenceParam subject

, @IncludeParam(allow = { "Observation.related" ,  "*" }) Set<Include> includes
);
 
Example #19
Source File: FHIRSTU3ExporterTest.java    From synthea with Apache License 2.0 4 votes vote down vote up
@Test
public void testSampledDataExport() throws Exception {

  Person person = new Person(0L);
  person.attributes.put(Person.GENDER, "F");
  person.attributes.put(Person.FIRST_LANGUAGE, "spanish");
  person.attributes.put(Person.RACE, "other");
  person.attributes.put(Person.ETHNICITY, "hispanic");
  person.attributes.put(Person.INCOME, Integer.parseInt(Config
      .get("generate.demographics.socioeconomic.income.poverty")) * 2);
  person.attributes.put(Person.OCCUPATION_LEVEL, 1.0);

  person.history = new LinkedList<>();
  Provider mock = Mockito.mock(Provider.class);
  mock.uuid = "Mock-UUID";
  person.setProvider(EncounterType.AMBULATORY, mock);
  person.setProvider(EncounterType.WELLNESS, mock);
  person.setProvider(EncounterType.EMERGENCY, mock);
  person.setProvider(EncounterType.INPATIENT, mock);

  Long time = System.currentTimeMillis();
  long birthTime = time - Utilities.convertTime("years", 35);
  person.attributes.put(Person.BIRTHDATE, birthTime);

  Payer.loadNoInsurance();
  for (int i = 0; i < person.payerHistory.length; i++) {
    person.setPayerAtAge(i, Payer.noInsurance);
  }
  
  Module module = TestHelper.getFixture("observation.json");
  
  State encounter = module.getState("SomeEncounter");
  assertTrue(encounter.process(person, time));
  person.history.add(encounter);
  
  State physiology = module.getState("Simulate_CVS");
  assertTrue(physiology.process(person, time));
  person.history.add(physiology);
  
  State sampleObs = module.getState("SampledDataObservation");
  assertTrue(sampleObs.process(person, time));
  person.history.add(sampleObs);
  
  FhirContext ctx = FhirContext.forDstu3();
  IParser parser = ctx.newJsonParser().setPrettyPrint(true);
  String fhirJson = FhirStu3.convertToFHIRJson(person, System.currentTimeMillis());
  Bundle bundle = parser.parseResource(Bundle.class, fhirJson);
  
  for (BundleEntryComponent entry : bundle.getEntry()) {
    if (entry.getResource() instanceof Observation) {
      Observation obs = (Observation) entry.getResource();
      assertTrue(obs.getValue() instanceof SampledData);
      SampledData data = (SampledData) obs.getValue();
      assertEquals(10, data.getPeriod().doubleValue(), 0.001); // 0.01s == 10ms
      assertEquals(3, (int) data.getDimensions());
    }
  }
}
 
Example #20
Source File: ObservationProvider.java    From careconnect-reference-implementation with Apache License 2.0 4 votes vote down vote up
@Validate
public MethodOutcome testResource(HttpServletRequest theRequest, @ResourceParam Observation resource,
                              @Validate.Mode ValidationModeEnum theMode,
                              @Validate.Profile String theProfile) {
    return resourceTestProvider.testResource(resource,theMode,theProfile);
}
 
Example #21
Source File: ObservationEntity.java    From careconnect-reference-implementation with Apache License 2.0 4 votes vote down vote up
public ObservationEntity setStatus(Observation.ObservationStatus status) {
    this.status = status;
    return this;
}
 
Example #22
Source File: ObservationProvider.java    From careconnect-reference-implementation with Apache License 2.0 4 votes vote down vote up
@Override
public Class<Observation> getResourceType() {
    return Observation.class;
}
 
Example #23
Source File: ObservationRelated.java    From careconnect-reference-implementation with Apache License 2.0 4 votes vote down vote up
public void setType(Observation.ObservationRelationshipType type) {
    this.type = type;
}
 
Example #24
Source File: ObservationRelated.java    From careconnect-reference-implementation with Apache License 2.0 4 votes vote down vote up
public Observation.ObservationRelationshipType getType() {
    return type;
}
 
Example #25
Source File: ObservationEntity.java    From careconnect-reference-implementation with Apache License 2.0 4 votes vote down vote up
public Observation.ObservationStatus getStatus() {
    return status;
}
 
Example #26
Source File: ExampleServerDstu3IT.java    From hapi-fhir-jpaserver-starter with Apache License 2.0 4 votes vote down vote up
@Test
public void testWebsocketSubscription() throws Exception {
	/*
	 * Create subscription
	 */
	Subscription subscription = new Subscription();
	subscription.setReason("Monitor new neonatal function (note, age will be determined by the monitor)");
	subscription.setStatus(Subscription.SubscriptionStatus.REQUESTED);
	subscription.setCriteria("Observation?status=final");

	Subscription.SubscriptionChannelComponent channel = new Subscription.SubscriptionChannelComponent();
	channel.setType(Subscription.SubscriptionChannelType.WEBSOCKET);
	channel.setPayload("application/json");
	subscription.setChannel(channel);

	MethodOutcome methodOutcome = ourClient.create().resource(subscription).execute();
	IIdType mySubscriptionId = methodOutcome.getId();

	// Wait for the subscription to be activated
	waitForSize(1, () -> ourClient.search().forResource(Subscription.class).where(Subscription.STATUS.exactly().code("active")).cacheControl(new CacheControlDirective().setNoCache(true)).returnBundle(Bundle.class).execute().getEntry().size());

	/*
	 * Attach websocket
	 */

	WebSocketClient myWebSocketClient = new WebSocketClient();
	SocketImplementation mySocketImplementation = new SocketImplementation(mySubscriptionId.getIdPart(), EncodingEnum.JSON);

	myWebSocketClient.start();
	URI echoUri = new URI("ws://localhost:" + ourPort + "/hapi-fhir-jpaserver/websocket");
	ClientUpgradeRequest request = new ClientUpgradeRequest();
	ourLog.info("Connecting to : {}", echoUri);
	Future<Session> connection = myWebSocketClient.connect(mySocketImplementation, echoUri, request);
	Session session = connection.get(2, TimeUnit.SECONDS);

	ourLog.info("Connected to WS: {}", session.isOpen());

	/*
	 * Create a matching resource
	 */
	Observation obs = new Observation();
	obs.setStatus(Observation.ObservationStatus.FINAL);
	ourClient.create().resource(obs).execute();

	// Give some time for the subscription to deliver
	Thread.sleep(2000);

	/*
	 * Ensure that we receive a ping on the websocket
	 */
	waitForSize(1, () -> mySocketImplementation.myPingCount);

	/*
	 * Clean up
	 */
	ourClient.delete().resourceById(mySubscriptionId).execute();
}
 
Example #27
Source File: ArgonautConverter.java    From org.hl7.fhir.core with Apache License 2.0 4 votes vote down vote up
private void processVitalSignsSection(CDAUtilities cda, Convert convert, Element section, Context context) throws Exception {
	scanSection("Vital Signs", section);
	ListResource list = new ListResource();
	list.setId(context.baseId+"-list-vitalsigns");
	//. list.setUserData("profile", "http://hl7.org/fhir/StructureDefinition/list-daf-dafproblemlist"); no list
	list.setSubject(context.subjectRef);
	list.setCode(inspectCode(convert.makeCodeableConceptFromCD(cda.getChild(section, "code")), null));
	list.setTitle(cda.getChild(section, "title").getTextContent());
	list.setStatus(ListStatus.CURRENT);
	list.setMode(ListMode.SNAPSHOT);
	list.setDateElement(context.now);
	list.setSource(context.authorRef);
	buildNarrative(list, cda.getChild(section, "text"));

	int i = 0;
	for (Element c : cda.getChildren(section, "entry")) {
		Element org = cda.getChild(c, "organizer"); // problem concern act
		for (Element oc : cda.getChildren(org, "component")) {
			Element o = cda.getChild(oc, "observation"); // problem concern act
			Observation obs = new Observation();
			obs.setId(context.baseId+"-vitals-"+Integer.toString(i));
			obs.setUserData("profile", "http://hl7.org/fhir/StructureDefinition/observation-daf-vitalsigns-dafvitalsigns");
			i++;
			obs.setSubject(context.subjectRef);
			obs.setContext(new Reference().setReference("Encounter/"+context.encounter.getId()));
			obs.setCode(inspectCode(convert.makeCodeableConceptFromCD(cda.getChild(o, "code")), null));

			boolean found = false;
			for (Element e : cda.getChildren(o, "id")) {
				Identifier id = convert.makeIdentifierFromII(e);
				obs.getIdentifier().add(id);
			}

			if (!found) {
				list.addEntry().setItem(new Reference().setReference("Observation/"+obs.getId()));
				obs.setStatus(ObservationStatus.FINAL);
				obs.setEffective(convert.makeDateTimeFromTS(cda.getChild(o, "effectiveTime")));
				String v = cda.getChild(o, "value").getAttribute("value");
				if (!Utilities.isDecimal(v, true)) {
					obs.setDataAbsentReason(inspectCode(new CodeableConcept().setText(v), null));
				} else
					obs.setValue(convert.makeQuantityFromPQ(cda.getChild(o, "value")));
				saveResource(obs, "-vs");
			}
		}
	}
	saveResource(list, "-vs");
}
 
Example #28
Source File: ObservationStatsBuilder.java    From org.hl7.fhir.core with Apache License 2.0 4 votes vote down vote up
private static ObservationComponentComponent component(Observation obs, String lCode, String text) {
  ObservationComponentComponent comp = obs.addComponent();
  comp.getCode().setText(text).addCoding().setCode(lCode).setSystem("http://loinc.org");
  return comp;
}
 
Example #29
Source File: AvroConverterTest.java    From bunsen with Apache License 2.0 2 votes vote down vote up
/**
 * Initialize test data.
 */
@BeforeClass
public static void convertTestData() throws IOException {

  AvroConverter observationConverter = AvroConverter.forResource(FhirContexts.forStu3(),
      "Observation");

  avroObservation = (Record) observationConverter.resourceToAvro(testObservation);

  testObservationDecoded = (Observation) observationConverter.avroToResource(avroObservation);

  avroObservationNullStatus = (Record) observationConverter
      .resourceToAvro(testObservationNullStatus);

  testObservationDecodedNullStatus = (Observation) observationConverter
      .avroToResource(avroObservationNullStatus);

  AvroConverter patientConverter = AvroConverter.forResource(FhirContexts.forStu3(),
      TestData.US_CORE_PATIENT);

  avroPatient = (Record) patientConverter.resourceToAvro(testPatient);

  testPatientDecoded = (Patient) patientConverter.avroToResource(avroPatient);

  AvroConverter conditionConverter = AvroConverter.forResource(FhirContexts.forStu3(),
      TestData.US_CORE_CONDITION);

  avroCondition = (Record) conditionConverter.resourceToAvro(testCondition);

  testConditionDecoded = (Condition) conditionConverter.avroToResource(avroCondition);

  AvroConverter medicationConverter = AvroConverter.forResource(FhirContexts.forStu3(),
      TestData.US_CORE_MEDICATION);

  Record avroMedication = (Record) medicationConverter.resourceToAvro(testMedicationOne);

  testMedicationDecoded = (Medication) medicationConverter.avroToResource(avroMedication);

  AvroConverter medicationRequestConverter = AvroConverter.forResource(FhirContexts.forStu3(),
      TestData.US_CORE_MEDICATION_REQUEST,
      Arrays.asList(TestData.US_CORE_MEDICATION, TestData.PROVENANCE));

  avroMedicationRequest = (Record) medicationRequestConverter
      .resourceToAvro(testMedicationRequest);

  testMedicationRequestDecoded = (MedicationRequest) medicationRequestConverter
      .avroToResource(avroMedicationRequest);

  AvroConverter converterBunsenTestProfilePatient = AvroConverter
      .forResource(FhirContexts.forStu3(), TestData.BUNSEN_TEST_PATIENT);

  avroBunsenTestProfilePatient = (Record) converterBunsenTestProfilePatient
      .resourceToAvro(testBunsenTestProfilePatient);

  testBunsenTestProfilePatientDecoded = (Patient) converterBunsenTestProfilePatient
      .avroToResource(avroBunsenTestProfilePatient);
}
 
Example #30
Source File: SparkRowConverterTest.java    From bunsen with Apache License 2.0 2 votes vote down vote up
/**
 * Loads resource definitions used for testing.
 */
@BeforeClass
public static void loadDefinition() throws IOException {

  fhirContext = FhirContexts.forStu3();

  SparkRowConverter patientConverter = SparkRowConverter.forResource(fhirContext,
      TestData.US_CORE_PATIENT);

  Row testPatientRow = patientConverter.resourceToRow(testPatient);

  testPatientDataset = spark.createDataFrame(Collections.singletonList(testPatientRow),
      patientConverter.getSchema());

  testPatientDecoded = (Patient) patientConverter.rowToResource(testPatientDataset.head());

  SparkRowConverter observationConverter = SparkRowConverter.forResource(fhirContext,
      TestData.US_CORE_OBSERVATION);

  Row testObservationRow = observationConverter.resourceToRow(testObservation);

  testObservationDataset = spark.createDataFrame(Collections.singletonList(testObservationRow),
      observationConverter.getSchema());

  testObservationDecoded =
      (Observation) observationConverter.rowToResource(testObservationDataset.head());

  Row testObservationNullStatusRow = observationConverter
      .resourceToRow(testObservationNullStatus);

  testObservationNullStatusDataset = spark.createDataFrame(
      Collections.singletonList(testObservationNullStatusRow), observationConverter.getSchema());

  testObservationDecodedNullStatus = (Observation) observationConverter
      .rowToResource(testObservationNullStatusDataset.head());

  SparkRowConverter conditionConverter = SparkRowConverter.forResource(fhirContext,
      TestData.US_CORE_CONDITION);

  Row testConditionRow = conditionConverter.resourceToRow(testCondition);

  testConditionDataset = spark.createDataFrame(Collections.singletonList(testConditionRow),
      conditionConverter.getSchema());

  testConditionDecoded =
      (Condition) conditionConverter.rowToResource(testConditionDataset.head());

  SparkRowConverter medicationRequestConverter = SparkRowConverter.forResource(fhirContext,
      TestData.US_CORE_MEDICATION_REQUEST,
      Arrays.asList(TestData.US_CORE_MEDICATION, TestData.PROVENANCE));

  Row testMedicationRequestRow = medicationRequestConverter.resourceToRow(testMedicationRequest);

  testMedicationRequestDataset = spark.createDataFrame(
      Collections.singletonList(testMedicationRequestRow),
      medicationRequestConverter.getSchema());

  testMedicationRequestDecoded = (MedicationRequest) medicationRequestConverter
      .rowToResource(testMedicationRequestDataset.head());

  SparkRowConverter converterBunsenTestProfilePatient = SparkRowConverter
      .forResource(FhirContexts.forStu3(), TestData.BUNSEN_TEST_PATIENT);

  Row testBunsenTestProfilePatientRow = converterBunsenTestProfilePatient
      .resourceToRow(testBunsenTestProfilePatient);

  testBunsenTestProfilePatientDataset = spark
      .createDataFrame(Collections.singletonList(testBunsenTestProfilePatientRow),
          converterBunsenTestProfilePatient.getSchema());

  testBunsenTestProfilePatientDecoded = (Patient) converterBunsenTestProfilePatient
      .rowToResource(testBunsenTestProfilePatientRow);
}