ca.uhn.fhir.context.FhirContext Java Examples

The following examples show how to use ca.uhn.fhir.context.FhirContext. 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: TestApplicationHints.java    From fhirstarters with BSD 3-Clause "New" or "Revised" License 7 votes vote down vote up
public static void step2_search_for_patients_named_test() {
	FhirContext ctx = FhirContext.forDstu3();
	IGenericClient client = ctx.newRestfulGenericClient("http://fhirtest.uhn.ca/baseDstu3");

	org.hl7.fhir.r4.model.Bundle results = client
		.search()
		.forResource(Patient.class)
		.where(Patient.NAME.matches().value("test"))
		.returnBundle(org.hl7.fhir.r4.model.Bundle.class)
		.execute();

	System.out.println("First page: ");
	System.out.println(ctx.newXmlParser().encodeResourceToString(results));

	// Load the next page
	org.hl7.fhir.r4.model.Bundle nextPage = client
		.loadPage()
		.next(results)
		.execute();

	System.out.println("Next page: ");
	System.out.println(ctx.newXmlParser().encodeResourceToString(nextPage));

}
 
Example #2
Source File: TestApplicationHints.java    From fhirstarters with BSD 3-Clause "New" or "Revised" License 7 votes vote down vote up
public static void step1_read_a_resource() {

		FhirContext ctx = FhirContext.forDstu3();
		IGenericClient client = ctx.newRestfulGenericClient("http://fhirtest.uhn.ca/baseDstu3");

		Patient patient;
		try {
			// Try changing the ID from 952975 to 999999999999
			patient = client.read().resource(Patient.class).withId("952975").execute();
		} catch (ResourceNotFoundException e) {
			System.out.println("Resource not found!");
			return;
		}

		String string = ctx.newXmlParser().setPrettyPrint(true).encodeResourceToString(patient);
		System.out.println(string);

	}
 
Example #3
Source File: PatientDao.java    From careconnect-reference-implementation with Apache License 2.0 6 votes vote down vote up
@Override
public Patient read(FhirContext ctx, IdType theId) {

    log.info("Looking for patient = "+theId.getIdPart());
    if (daoutils.isNumeric(theId.getIdPart())) {
        PatientEntity patientEntity = (PatientEntity) em.find(PatientEntity.class, Long.parseLong(theId.getIdPart()));

        Patient patient = null;
        if (patientEntity != null) {
            patient = patientEntityToFHIRPatientTransformer.transform(patientEntity);
            patientEntity.setResource(ctx.newJsonParser().encodeResourceToString(patient));
            em.persist(patientEntity);
        }
        return patient;
    } else {
        return null;
    }
}
 
Example #4
Source File: Example30_AddSomeExtensions.java    From fhirstarters with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public static void main(String[] theArgs) {
Patient pat = new Patient();
pat.addName().setFamily("Simpson").addGiven("Homer").addGiven("J");

// Add an extension on the resource
pat.addExtension()
		.setUrl("http://hl7.org/fhir/StructureDefinition/patient-importance")
		.setValue(new CodeableConcept().setText("Patient is a VIP"));

// Add an extension on a primitive
pat.getBirthDateElement().setValueAsString("1955-02-22");
pat.getBirthDateElement().addExtension()
		.setUrl("http://hl7.org/fhir/StructureDefinition/patient-birthTime")
		.setValue(new TimeType("23:30"));

    IParser parser = FhirContext.forDstu3().newJsonParser().setPrettyPrint(true);
    System.out.println(parser.encodeResourceToString(pat));
 }
 
Example #5
Source File: GraphDefinitionDao.java    From careconnect-reference-implementation with Apache License 2.0 6 votes vote down vote up
public List<GraphDefinition> search (FhirContext ctx,
                              @OptionalParam(name = GraphDefinition.SP_NAME) StringParam name,
                              @OptionalParam(name = GraphDefinition.SP_PUBLISHER) StringParam publisher,
                              @OptionalParam(name = GraphDefinition.SP_URL) UriParam url

) {
    List<GraphDefinition> results = new ArrayList<>();
    List<GraphDefinitionEntity> qryResults = searchEntity(ctx, name, publisher, url);

    for (GraphDefinitionEntity graphEntity : qryResults) {
        if (graphEntity.getResource() != null) {
            results.add((GraphDefinition) ctx.newJsonParser().parseResource(graphEntity.getResource()));
        } else {

            GraphDefinition graph = graphEntityToFHIRValuesetTransformer.transform(graphEntity);
            String resource = ctx.newJsonParser().encodeResourceToString(graph);
            if (resource.length() < 10000) {
                graphEntity.setResource(resource);
                em.persist(graphEntity);
            }
            results.add(graph);
        }
    }
    return results;
}
 
Example #6
Source File: EncounterRepository.java    From careconnect-reference-implementation with Apache License 2.0 6 votes vote down vote up
List<EncounterEntity> searchEntity(FhirContext ctx,
        @OptionalParam(name = Encounter.SP_PATIENT) ReferenceParam patient
        ,@OptionalParam(name = Encounter.SP_DATE) DateRangeParam date
        ,@OptionalParam(name = Encounter.SP_EPISODEOFCARE) ReferenceParam episode
        , @OptionalParam(name = Encounter.SP_IDENTIFIER) TokenParam identifier
        ,@OptionalParam(name= Encounter.SP_RES_ID) StringParam id
        , @IncludeParam(reverse=true, allow = {
        "Observation:context",
        "Encounter:part-of",
        "Procedure:context",
        "Condition:context",
        "MedicationRequest:context",
        "Immunization:encounter" ,
        "DocumentReference:context",
        "Composition:encounter",
        "ReferralRequest:encounter",
        "*"
}) Set<Include> reverseIncludes
        , @IncludeParam(allow = { "Encounter.participant" , "Encounter.subject", "Encounter.service-provider", "Encounter.location", "*"
}) Set<Include> includes
        , @OptionalParam(name = Encounter.SP_TYPE) TokenParam type
        , @OptionalParam(name = Encounter.SP_STATUS) TokenParam status
);
 
Example #7
Source File: Example06_ClientCreate.java    From fhirstarters with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public static void main(String[] theArgs) {

      Patient pat = new Patient();
      pat.addName().setFamily("Simpson").addGiven("Homer").addGiven("J");
      pat.addIdentifier().setSystem("http://acme.org/MRNs").setValue("7000135");
      pat.setGender(AdministrativeGender.MALE);

      // Create a context
      FhirContext ctx = FhirContext.forR4();

      // Create a client
      String serverBaseUrl = "http://hapi.fhir.org/baseR4";
      IGenericClient client = ctx.newRestfulGenericClient(serverBaseUrl);

      // Use the client to store a new resource instance
      MethodOutcome outcome = client
         .create()
         .resource(pat)
         .execute();

      // Print the ID of the newly created resource
      System.out.println(outcome.getId());
   }
 
Example #8
Source File: FhirXmlIntegrationTest.java    From wildfly-camel with Apache License 2.0 6 votes vote down vote up
@Test
public void testFhirJsonMarshal() throws Exception {
    CamelContext camelctx = new DefaultCamelContext();
    camelctx.addRoutes(new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            from("direct:start")
            .marshal().fhirXml();
        }
    });

    camelctx.start();
    try {
        Patient patient = createPatient();
        ProducerTemplate template = camelctx.createProducerTemplate();
        InputStream inputStream = template.requestBody("direct:start", patient, InputStream.class);
        IBaseResource result = FhirContext.forDstu3().newXmlParser().parseResource(new InputStreamReader(inputStream));
        Assert.assertTrue("Expected marshaled patient to be equal", patient.equalsDeep((Base)result));
    } finally {
        camelctx.close();
    }
}
 
Example #9
Source File: SlotDao.java    From careconnect-reference-implementation with Apache License 2.0 5 votes vote down vote up
@Override
public List<Slot> searchSlot(FhirContext ctx, TokenParam identifier, DateParam start, StringParam status, StringParam res_id, ReferenceParam schedule, ReferenceParam service) {
    List<SlotEntity> qryResults = searchSlotEntity(ctx,identifier,start,status,res_id,schedule, service);
    List<Slot> results = new ArrayList<>();

    for (SlotEntity slotEntity : qryResults) {
        Slot slot = slotEntityToFHIRSlotTransformer.transform(slotEntity);
        results.add(slot);
    }

    return results;
}
 
Example #10
Source File: EpisodeOfCareDao.java    From careconnect-reference-implementation with Apache License 2.0 5 votes vote down vote up
@Override
public EpisodeOfCare read(FhirContext ctx,IdType theId) {
    if (daoutils.isNumeric(theId.getIdPart())) {
        EpisodeOfCareEntity episode = (EpisodeOfCareEntity) em.find(EpisodeOfCareEntity.class, Long.parseLong(theId.getIdPart()));

        return episode == null
                ? null
                : episodeOfCareEntityToFHIREpisodeOfCareTransformer.transform(episode);
    } else {
        return null;
    }

}
 
Example #11
Source File: R4FhirModelResolver.java    From cql_engine with Apache License 2.0 5 votes vote down vote up
private R4FhirModelResolver(FhirContext fhirContext) {
    super(fhirContext);
    this.setPackageName("org.hl7.fhir.r4.model");
    if (fhirContext.getVersion().getVersion() != FhirVersionEnum.R4) {
        throw new IllegalArgumentException("The supplied context is not configured for R4");
    }
}
 
Example #12
Source File: CareConnectProfileValidationSupport.java    From careconnect-reference-implementation with Apache License 2.0 5 votes vote down vote up
/**
 * Method to fetch a CodeSystem based on a provided URL. Tries to fetch it
 * from remote server. If it succeeds, it caches it in our global cache.
 *
 * @param theContext FHIR Context
 * @param theSystem The CodeSystem URL
 * @return Returns the retrieved FHIR Resource object or null
 */
@Override
public final CodeSystem fetchCodeSystem(
        final FhirContext theContext, final String theSystem) {
    logD(
            "MyInstanceValidator asked to fetch Code System: %s%n",
            theSystem);


    if (!isSupported(theSystem)) {
        log.trace("  Returning null as it's an HL7 one");
        return null;
    }

    CodeSystem newCS;

    if (cachedResource.get(theSystem) == null) {
        log.trace(" Not cached");
        IBaseResource response = fetchURL(theSystem);
        if (response != null) {
            log.trace("  Retrieved");
            cachedResource.put(theSystem, (CodeSystem) response);
            log.trace("   Cached");
        }
    }
    if (cachedResource.get(theSystem) == null && cachedResource.get(theSystem) instanceof CodeSystem) {
        log.trace("  Couldn't fetch it, so returning null");
        return null;
    } else {
        log.trace(" Provided from cache");
        return newCS = (CodeSystem) cachedResource.get(theSystem);

    }
    //return newCS;
}
 
Example #13
Source File: ScheduleDao.java    From careconnect-reference-implementation with Apache License 2.0 5 votes vote down vote up
@Override
public ScheduleEntity readEntity(FhirContext ctx, IdType theId) {
    if (daoutils.isNumeric(theId.getIdPart())) {
        ScheduleEntity scheduleEntity = (ScheduleEntity) em.find(ScheduleEntity.class, Long.parseLong(theId.getIdPart()));

        return scheduleEntity;

    } else {
        return null;
    }
}
 
Example #14
Source File: FlagDao.java    From careconnect-reference-implementation with Apache License 2.0 5 votes vote down vote up
@Override
public List<Flag> searchFlag(FhirContext ctx, TokenParam identifier, StringParam id, ReferenceParam patient) {
    List<FlagEntity> qryResults = searchFlagEntity(ctx, identifier, id,  patient);
    List<Flag> results = new ArrayList<>();

    for (FlagEntity flag : qryResults)
    {
        // log.trace("HAPI Custom = "+doc.getId());
        Flag questionnaireResponse = flagEntityToFHIRFlagTransformer.transform(flag);
        results.add(questionnaireResponse);
    }

    return results;
}
 
Example #15
Source File: LibDao.java    From careconnect-reference-implementation with Apache License 2.0 5 votes vote down vote up
public PatientEntity findPatientEntity(FhirContext ctx, Reference ref) {
    PatientEntity patientEntity = null;
    if (ref.hasReference()) {
        log.trace(ref.getReference());
        patientEntity = patientDao.readEntity(ctx, new IdType(ref.getReference()));

    }
    if (ref.hasIdentifier()) {
        // This copes with reference.identifier param (a short cut?)
        log.trace(ref.getIdentifier().getSystem() + " " + ref.getIdentifier().getValue());
        patientEntity = patientDao.readEntity(ctx, new TokenParam().setSystem(ref.getIdentifier().getSystem()).setValue(ref.getIdentifier().getValue()));
    }
    return patientEntity;
}
 
Example #16
Source File: FhirDataformatTest.java    From camel-quarkus with Apache License 2.0 5 votes vote down vote up
@Test
@EnabledIf(FhirFlags.R4Enabled.class)
public void jsonR4() {
    LOG.info("Running R4 JSON test");

    final org.hl7.fhir.r4.model.Patient patient = getR4Patient();
    final String patientString = FhirContext.forR4().newJsonParser().encodeResourceToString(patient);

    RestAssured.given()
            .contentType(ContentType.JSON).body(patientString).post("/r4/fhir2json")
            .then().statusCode(201);
}
 
Example #17
Source File: AllergyIntoleranceDao.java    From careconnect-reference-implementation with Apache License 2.0 5 votes vote down vote up
@Override
public AllergyIntolerance read(FhirContext ctx,IdType theId) {
    if (daoutils.isNumeric(theId.getIdPart())) {
        AllergyIntoleranceEntity allergyIntolerance = (AllergyIntoleranceEntity) em.find(AllergyIntoleranceEntity.class, Long.parseLong(theId.getIdPart()));

        return allergyIntolerance == null
                ? null
                : allergyIntoleranceEntityToFHIRAllergyIntoleranceTransformer.transform(allergyIntolerance);
    } else {
        return null;
    }
}
 
Example #18
Source File: SNOMEDUKMockValidationSupport.java    From careconnect-reference-implementation with Apache License 2.0 5 votes vote down vote up
@Override
public List<IBaseResource> fetchAllConformanceResources(FhirContext theContext) {
  ArrayList<IBaseResource> retVal = new ArrayList<>();
  retVal.addAll(myCodeSystems.values());
  retVal.addAll(myStructureDefinitions.values());
  retVal.addAll(myValueSets.values());
  return retVal;
}
 
Example #19
Source File: PatientDao.java    From careconnect-reference-implementation with Apache License 2.0 5 votes vote down vote up
@Transactional
@Override
public void save(FhirContext ctx, PatientEntity patient)
{


    em.persist(patient);
}
 
Example #20
Source File: MedicationRequestDao.java    From careconnect-reference-implementation with Apache License 2.0 5 votes vote down vote up
@Override
public MedicationRequestEntity readEntity(FhirContext ctx, IdType theId) {
    if (daoutils.isNumeric(theId.getIdPart())) {
        MedicationRequestEntity medicationRequestEntity = em.find(MedicationRequestEntity.class, Long.parseLong(theId.getIdPart()));

        return medicationRequestEntity ;
    } else {
        return null;
    }
}
 
Example #21
Source File: UsCoreStu3ProfileProvider.java    From bunsen with Apache License 2.0 5 votes vote down vote up
private static void addUsCoreDefinitions(PrePopulatedValidationSupport support,
    FhirContext context) {

  IParser parser = context.newJsonParser();

  load(support, parser, "definitions/StructureDefinition-us-core-allergyintolerance.json");
  load(support, parser, "definitions/StructureDefinition-us-core-birthsex.json");
  load(support, parser, "definitions/StructureDefinition-us-core-careplan.json");
  load(support, parser, "definitions/StructureDefinition-us-core-careteam.json");
  load(support, parser, "definitions/StructureDefinition-us-core-condition.json");
  load(support, parser, "definitions/StructureDefinition-us-core-device.json");
  load(support, parser, "definitions/StructureDefinition-us-core-diagnosticreport.json");
  load(support, parser, "definitions/StructureDefinition-us-core-direct.json");
  load(support, parser, "definitions/StructureDefinition-us-core-documentreference.json");
  load(support, parser, "definitions/StructureDefinition-us-core-encounter.json");
  load(support, parser, "definitions/StructureDefinition-us-core-ethnicity.json");
  load(support, parser, "definitions/StructureDefinition-us-core-goal.json");
  load(support, parser, "definitions/StructureDefinition-us-core-immunization.json");
  load(support, parser, "definitions/StructureDefinition-us-core-location.json");
  load(support, parser, "definitions/StructureDefinition-us-core-medication.json");
  load(support, parser, "definitions/StructureDefinition-us-core-medicationrequest.json");
  load(support, parser, "definitions/StructureDefinition-us-core-medicationstatement.json");
  load(support, parser, "definitions/StructureDefinition-us-core-observationresults.json");
  load(support, parser, "definitions/StructureDefinition-us-core-organization.json");
  load(support, parser, "definitions/StructureDefinition-us-core-patient.json");
  load(support, parser, "definitions/StructureDefinition-us-core-practitioner.json");
  load(support, parser, "definitions/StructureDefinition-us-core-practitionerrole.json");
  load(support, parser, "definitions/StructureDefinition-us-core-procedure.json");
  load(support, parser, "definitions/StructureDefinition-us-core-profile-link.json");
  load(support, parser, "definitions/StructureDefinition-us-core-race.json");
  load(support, parser, "definitions/StructureDefinition-us-core-smokingstatus.json");

}
 
Example #22
Source File: FHIRPathEvaluatorBenchmark.java    From FHIR with Apache License 2.0 5 votes vote down vote up
@Setup
public void setUp() throws Exception {
    context = FhirContext.forR4();
    fluentPath = context.newFluentPath();
    resource = FHIRParser.parser(Format.JSON).parse(new StringReader(JSON_SPEC_EXAMPLE));
    evaluator = FHIRPathEvaluator.evaluator();
    evaluationContext = new EvaluationContext(resource);
    initialContext = singleton(evaluationContext.getTree().getRoot());
    baseResource = context.newJsonParser().parseResource(new StringReader(JSON_SPEC_EXAMPLE));
}
 
Example #23
Source File: DiagnosticReportDao.java    From careconnect-reference-implementation with Apache License 2.0 5 votes vote down vote up
@Override
public DiagnosticReportEntity readEntity(FhirContext ctx, IdType theId) {
    if (daoutils.isNumeric(theId.getIdPart())) {
        DiagnosticReportEntity diagnosticReport = em.find(DiagnosticReportEntity.class, Long.parseLong(theId.getIdPart()));

        return diagnosticReport;
    } else {
        return null;
    }
}
 
Example #24
Source File: FHIRParserValidatorGeneratorBenchmark.java    From FHIR with Apache License 2.0 5 votes vote down vote up
@Setup
public void setUp() {
    context = FhirContext.forR4();
    context.setParserErrorHandler(new StrictErrorHandler());
    fhirValidator = context.newValidator();
    validator = FHIRValidator.validator();
    jsonParser = FHIRParser.parser(Format.JSON);
    jsonGenerator = FHIRGenerator.generator(Format.JSON);
    xmlParser = FHIRParser.parser(Format.XML);
    xmlGenerator = FHIRGenerator.generator(Format.XML);
}
 
Example #25
Source File: FhirServerConfigR4.java    From cqf-ruler with Apache License 2.0 5 votes vote down vote up
@Override
public FhirContext fhirContextR4() {
	FhirContext retVal = FhirContext.forR4();

	// Don't strip versions in some places
	ParserOptions parserOptions = retVal.getParserOptions();
	parserOptions.setDontStripVersionsFromReferencesAtPaths("AuditEvent.entity.what");

	return retVal;
}
 
Example #26
Source File: CareConnectProfileValidationSupport.java    From careconnect-reference-implementation with Apache License 2.0 5 votes vote down vote up
private DomainResource fetchCodeSystemOrValueSet(FhirContext theContext, String theSystem, boolean codeSystem) {
  synchronized (this) {
    logD("******* CareConnect fetchCodeSystemOrValueSet: system="+theSystem);

    Map<String, IBaseResource> codeSystems = cachedResource;

    return null;
  }
}
 
Example #27
Source File: MedicationRequestRepository.java    From careconnect-reference-implementation with Apache License 2.0 5 votes vote down vote up
List<MedicationRequest> search(FhirContext ctx,

                                   @OptionalParam(name = MedicationRequest.SP_PATIENT) ReferenceParam patient
            , @OptionalParam(name = MedicationRequest.SP_CODE) TokenParam code
            , @OptionalParam(name = MedicationRequest.SP_AUTHOREDON) DateRangeParam dateWritten
            , @OptionalParam(name = MedicationRequest.SP_STATUS) TokenParam status
            , @OptionalParam(name = MedicationRequest.SP_IDENTIFIER) TokenParam identifier
            , @OptionalParam(name= MedicationRequest.SP_RES_ID) StringParam id
            , @OptionalParam(name= MedicationRequest.SP_MEDICATION) ReferenceParam medication
    );
 
Example #28
Source File: Dstu3FhirModelResolver.java    From cql_engine with Apache License 2.0 5 votes vote down vote up
private Dstu3FhirModelResolver(FhirContext fhirContext) {
    super(fhirContext);
    this.setPackageName("org.hl7.fhir.dstu3.model");
    if (fhirContext.getVersion().getVersion() != FhirVersionEnum.DSTU3) {
        throw new IllegalArgumentException("The supplied context is not configured for DSTU3");
    }
}
 
Example #29
Source File: CareConnectProfileDbValidationSupportR4.java    From careconnect-reference-implementation with Apache License 2.0 5 votes vote down vote up
@Override
public final <T extends IBaseResource> T fetchResource(
        final FhirContext theContext,
        final Class<T> theClass,
        final String theUrl) {



    if (!isSupported(theUrl)) {
        log.trace("  Returning null as it's an HL7 one");
        return null;
    }

    logT(
            "CareConnectValidator asked to fetch Resource: %s%n",
            theUrl);

    if (cachedResource.get(theUrl) == null) {
        IBaseResource response = fetchURL(theUrl);
        if (response != null) {

            cachedResource.put(theUrl, response);
            logD("  Resource added to cache: %s%n", theUrl);
        } else {
            logW("  No data returned from: %s%n", theUrl);
        }
    } else {
        logT( "  This URL was already loaded: %s%n", theUrl);
    }

    return (T) cachedResource.get(theUrl);
}
 
Example #30
Source File: ObservationDefinitionDao.java    From careconnect-reference-implementation with Apache License 2.0 5 votes vote down vote up
@Override
   public ObservationDefinitionEntity readEntity(FhirContext ctx, IdType theId) {

       System.out.println("the id is " + theId.getIdPart());

       ObservationDefinitionEntity observationDefinitionEntity = null;
       // Only look up if the id is numeric else need to do a search
/*        if (daoutils.isNumeric(theId.getIdPart())) {
            observationDefinitionEntity =(ObservationDefinitionEntity) em.find(ObservationDefinitionEntity.class, theId.getIdPart());
        } */
       ObservationDefinitionEntity.class.getName();
       // if null try a search on strId

       CriteriaBuilder builder = em.getCriteriaBuilder();

       if (daoutilsR4.isNumeric(theId.getIdPart())) {

           CriteriaQuery<ObservationDefinitionEntity> criteria = builder.createQuery(ObservationDefinitionEntity.class);
           Root<ObservationDefinitionEntity> root = criteria.from(ObservationDefinitionEntity.class);
           List<Predicate> predList = new LinkedList<Predicate>();
           Predicate p = builder.equal(root.<String>get("id"), theId.getIdPart());
           predList.add(p);
           Predicate[] predArray = new Predicate[predList.size()];
           predList.toArray(predArray);
           if (predList.size() > 0) {
               criteria.select(root).where(predArray);

               List<ObservationDefinitionEntity> qryResults = em.createQuery(criteria).getResultList();

               for (ObservationDefinitionEntity cme : qryResults) {
                   observationDefinitionEntity = cme;
                   break;
               }
           }
       }
       // }
       return observationDefinitionEntity;
   }