At least for the FHIR2 version, something like this would work (please excuse the really hacky means of getting a reference to the ApplicationContext
):
public class SampleTask extends AbstractTask {
@Override
public void execute() {
ServiceContext serviceContext = (ServiceContext) ReflectionUtils.getField(ReflectionUtils.findField(Context.class, "serviceContext"), Context.class);
FhirPatientService patientService = serviceContext.getApplicationContext().getBean(FhirPatientService.class);
IParser parser = FhirContext.forR4().newJsonParser();
parser.encodeResourceToString(patientService.get("Some UUID"));
}
}
This will get the FHIR-formatted version of an OpenMRS patient and convert it into a JSON string. You can get an XML version by replacing newJsonParser()
with newXmlParser()
.
Things are a little more complicated if you need more than one resource at a time, which is usually done via a search operation. The FHIR2 service classes generally have a searchFor...()
method, but the parameters vary quite a bit and need to be encoded using the appropriate HAPI classes, so it’s quite a bit more fragile. But, you could, for instance, get all the patients named “Adam” like this:
IBundleProvider bundleProvider = patientService
.searchForPatients(null, new StringAndListParam().addAnd(new StringParam("Adam")), null, null, null, null,
null, null, null, null, null, null, null, null, null, null);
List<Patient> patients = bundleProvider.getResources(0, Integer.MAX_VALUE).stream().filter(r -> r instanceof Patient)
.map(r -> (Patient) r).collect(Collectors.toList());
and convert them to JSON or XML following a similar pattern.
I believe things are similar with the old FHIR module, except the services are actually normal OpenMRS services and can be gotten with Context.getService(...)
.