Java Code Examples for ca.uhn.fhir.context.FhirContext

The following examples show how to use ca.uhn.fhir.context.FhirContext. These examples are extracted from open source projects. 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
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
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 3
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 4
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 Project: wildfly-camel   Source File: FhirXmlIntegrationTest.java    License: 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 6
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 7
@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 8
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 9
@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;
   }
 
Example 10
Source Project: camel-quarkus   Source File: FhirDataformatTest.java    License: 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 11
Source Project: cql_engine   Source File: R4FhirModelResolver.java    License: 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
@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 13
@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 14
@Override
public boolean populateResourceNarrative(FhirContext theFhirContext, IBaseResource theResource) {
	if (!myInitialized) {
		initialize();
	}
	super.populateResourceNarrative(theFhirContext, theResource);
	return false;
   }
 
Example 15
Source Project: cqf-ruler   Source File: FhirServerConfigDstu3.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public FhirContext fhirContextDstu3() {
	FhirContext retVal = FhirContext.forDstu3();

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

	return retVal;
}
 
Example 16
/**
 * 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 17
@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 18
Source Project: FHIR   Source File: FHIRPathEvaluatorBenchmark.java    License: 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 19
@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 20
@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 21
private DomainResource fetchCodeSystemOrValueSet(FhirContext theContext, String theSystem, boolean codeSystem) {
  synchronized (this) {
    logD("******* CareConnect fetchCodeSystemOrValueSet: system="+theSystem);

    Map<String, IBaseResource> codeSystems = cachedResource;

    return null;
  }
}
 
Example 22
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 23
Source Project: cql_engine   Source File: Dstu3FhirModelResolver.java    License: 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 24
@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 25
Source Project: cqf-ruler   Source File: FhirServerConfigR4.java    License: 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 Project: bunsen   Source File: UsCoreStu3ProfileProvider.java    License: 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 27
@Transactional
@Override
public void save(FhirContext ctx, PatientEntity patient)
{


    em.persist(patient);
}
 
Example 28
@Override
public Endpoint read(FhirContext ctx, IdType theId) {
    if (daoutils.isNumeric(theId.getIdPart())) {
        EndpointEntity endpoint = (EndpointEntity) em.find(EndpointEntity.class, Long.parseLong(theId.getIdPart()));

        return endpoint == null
                ? null
                : endpointEntityToFHIREndpointTransform.transform(endpoint);
    } else  {
        return null;
    }
}
 
Example 29
@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 30
@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;
    }
}