use of org.hl7.fhir.dstu2.model.Reference in project cqf-ruler by DBCG.
the class DetectedIssueBuilder method initializeDstu2_1.
@Override
protected void initializeDstu2_1(T theResource) {
super.initializeDstu2_1(theResource);
org.hl7.fhir.dstu2016may.model.DetectedIssue detectedIssue = (org.hl7.fhir.dstu2016may.model.DetectedIssue) theResource;
detectedIssue.setIdentifier(new Identifier().setSystem(getIdentifier().getKey()).setValue(getIdentifier().getValue())).setPatient(new Reference(myPatient));
getEvidenceDetails().forEach(detectedIssue::setReference);
}
use of org.hl7.fhir.dstu2.model.Reference in project cqf-ruler by DBCG.
the class ParameterUser method getPatientListFromGroup.
// TODO: replace this with version from the evaluator?
default List<Patient> getPatientListFromGroup(String subjectGroupId) {
List<Patient> patientList = new ArrayList<>();
Group group = read(newId(subjectGroupId));
if (group == null) {
throw new IllegalArgumentException("Could not find Group: " + subjectGroupId);
}
group.getMember().forEach(member -> {
Reference reference = member.getEntity();
if (reference.getReferenceElement().getResourceType().equals("Patient")) {
Patient patient = ensurePatient(reference.getReference());
patientList.add(patient);
} else if (reference.getReferenceElement().getResourceType().equals("Group")) {
patientList.addAll(getPatientListFromGroup(reference.getReference()));
} else {
ourLog.info("Group member was not a Patient or a Group, so skipping. \n{}", reference.getReference());
}
});
return patientList;
}
use of org.hl7.fhir.dstu2.model.Reference in project cqf-ruler by DBCG.
the class CdsHooksServlet method doPost.
@Override
@SuppressWarnings("deprecation")
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
logger.info(request.getRequestURI());
try {
// validate that we are dealing with JSON
if (request.getContentType() == null || !request.getContentType().startsWith("application/json")) {
throw new ServletException(String.format("Invalid content type %s. Please use application/json.", request.getContentType()));
}
String baseUrl = this.myAppProperties.getServer_address();
String service = request.getPathInfo().replace("/", "");
JsonParser parser = new JsonParser();
JsonObject requestJson = parser.parse(request.getReader()).getAsJsonObject();
logger.info(requestJson.toString());
Request cdsHooksRequest = new Request(service, requestJson, JsonHelper.getObjectRequired(getService(service), "prefetch"));
Hook hook = HookFactory.createHook(cdsHooksRequest);
String hookName = hook.getRequest().getHook();
logger.info("cds-hooks hook: {}", hookName);
logger.info("cds-hooks hook instance: {}", hook.getRequest().getHookInstance());
logger.info("cds-hooks maxCodesPerQuery: {}", this.getProviderConfiguration().getMaxCodesPerQuery());
logger.info("cds-hooks expandValueSets: {}", this.getProviderConfiguration().getExpandValueSets());
logger.info("cds-hooks searchStyle: {}", this.getProviderConfiguration().getSearchStyle());
logger.info("cds-hooks prefetch maxUriLength: {}", this.getProviderConfiguration().getMaxUriLength());
logger.info("cds-hooks local server address: {}", baseUrl);
logger.info("cds-hooks fhir server address: {}", hook.getRequest().getFhirServerUrl());
logger.info("cds-hooks cql_logging_enabled: {}", this.getProviderConfiguration().getCqlLoggingEnabled());
PlanDefinition planDefinition = read(Ids.newId(PlanDefinition.class, hook.getRequest().getServiceName()));
AtomicBoolean planDefinitionHookMatchesRequestHook = new AtomicBoolean(false);
planDefinition.getAction().forEach(action -> {
action.getTriggerDefinition().forEach(triggerDefn -> {
if (hookName.equals(triggerDefn.getEventName())) {
planDefinitionHookMatchesRequestHook.set(true);
return;
}
});
if (planDefinitionHookMatchesRequestHook.get()) {
return;
}
});
if (!planDefinitionHookMatchesRequestHook.get()) {
throw new ServletException("ERROR: Request hook does not match the service called.");
}
// No tenant information available, so create local system request
RequestDetails requestDetails = new SystemRequestDetails();
LibraryLoader libraryLoader = libraryLoaderFactory.create(Lists.newArrayList(jpaLibraryContentProviderFactory.create(requestDetails)));
Reference reference = planDefinition.getLibrary().get(0);
Library library = read(reference.getReferenceElement());
org.cqframework.cql.elm.execution.Library elm = libraryLoader.load(new VersionedIdentifier().withId(library.getName()).withVersion(library.getVersion()));
Context context = new Context(elm);
context.setDebugMap(this.getDebugMap());
// provider case
// No tenant information available for cds-hooks
TerminologyProvider serverTerminologyProvider = myJpaTerminologyProviderFactory.create(requestDetails);
// TODO make sure tooling handles remote
context.registerDataProvider("http://hl7.org/fhir", fhirRetrieveProviderFactory.create(requestDetails, serverTerminologyProvider));
context.registerTerminologyProvider(serverTerminologyProvider);
context.registerLibraryLoader(libraryLoader);
context.setContextValue("Patient", hook.getRequest().getContext().getPatientId().replace("Patient/", ""));
context.setExpressionCaching(true);
EvaluationContext<PlanDefinition> evaluationContext = new Stu3EvaluationContext(hook, FhirContext.forCached(FhirVersionEnum.DSTU3).newRestfulGenericClient(baseUrl), context, elm, planDefinition, this.getProviderConfiguration(), this.modelResolver);
this.setAccessControlHeaders(response);
response.setHeader("Content-Type", ContentType.APPLICATION_JSON.getMimeType());
Stu3HookEvaluator evaluator = new Stu3HookEvaluator(this.modelResolver);
String jsonResponse = toJsonResponse(evaluator.evaluate(evaluationContext));
logger.info(jsonResponse);
response.getWriter().println(jsonResponse);
} catch (BaseServerResponseException e) {
this.setAccessControlHeaders(response);
// This will be overwritten with the correct status code downstream if needed.
response.setStatus(500);
response.getWriter().println("ERROR: Exception connecting to remote server.");
this.printMessageAndCause(e, response);
this.handleServerResponseException(e, response);
this.printStackTrack(e, response);
logger.error(e.toString());
} catch (DataProviderException e) {
this.setAccessControlHeaders(response);
// This will be overwritten with the correct status code downstream if needed.
response.setStatus(500);
response.getWriter().println("ERROR: Exception in DataProvider.");
this.printMessageAndCause(e, response);
if (e.getCause() != null && (e.getCause() instanceof BaseServerResponseException)) {
this.handleServerResponseException((BaseServerResponseException) e.getCause(), response);
}
this.printStackTrack(e, response);
logger.error(e.toString());
} catch (CqlException e) {
this.setAccessControlHeaders(response);
// This will be overwritten with the correct status code downstream if needed.
response.setStatus(500);
response.getWriter().println("ERROR: Exception in CQL Execution.");
this.printMessageAndCause(e, response);
if (e.getCause() != null && (e.getCause() instanceof BaseServerResponseException)) {
this.handleServerResponseException((BaseServerResponseException) e.getCause(), response);
}
this.printStackTrack(e, response);
logger.error(e.toString());
} catch (Exception e) {
logger.error(e.toString());
throw new ServletException("ERROR: Exception in cds-hooks processing.", e);
}
}
use of org.hl7.fhir.dstu2.model.Reference in project cqf-ruler by DBCG.
the class MeasureDataProcessProvider method getSubjectResultsFromList.
private List<Reference> getSubjectResultsFromList(Reference subjectResults) {
List<Reference> results = new ArrayList<>();
if (subjectResults.getReference() == null) {
logger.debug("No subject results found.");
return results;
}
IBaseResource baseList = read(subjectResults.getReferenceElement());
if (!(baseList instanceof ListResource)) {
throw new IllegalArgumentException(String.format("Population subject reference was not a List, found: %s", baseList.fhirType()));
}
ListResource list = (ListResource) baseList;
list.getEntry().forEach(entry -> {
if (entry.getItemTarget().getResourceType() == ResourceType.Patient || entry.getItemTarget().getResourceType() == ResourceType.Group) {
results.add(entry.getItem());
}
});
return results;
}
use of org.hl7.fhir.dstu2.model.Reference in project cqf-ruler by DBCG.
the class ProcessMessageProvider method processMessageBundle.
@Operation(name = "$process-message-bundle", idempotent = false)
public Bundle processMessageBundle(HttpServletRequest theServletRequest, RequestDetails theRequestDetails, @OperationParam(name = "content", min = 1, max = 1) @Description(formalDefinition = "The message to process (or, if using asynchronous messaging, it may be a response message to accept)") Bundle theMessageToProcess) {
logger.info("Validating the Bundle");
Bundle bundle = theMessageToProcess;
Boolean errorExists = false;
OperationOutcome outcome = validateBundle(errorExists, bundle);
if (!errorExists) {
IVersionSpecificBundleFactory bundleFactory = this.getFhirContext().newBundleFactory();
bundle.setId(getUUID());
bundleFactory.initializeWithBundleResource(bundle);
Bundle dafBundle = (Bundle) bundleFactory.getResourceBundle();
dafBundle.setTimestamp(new Date());
this.getDaoRegistry().getResourceDao(Bundle.class).create(dafBundle);
MessageHeader messageHeader = null;
String patientId = null;
String commId = null;
List<MessageHeader> headers = BundleUtil.toListOfResourcesOfType(this.getFhirContext(), bundle, MessageHeader.class);
for (MessageHeader mh : headers) {
messageHeader = mh;
messageHeader.setId(getUUID());
Meta meta = messageHeader.getMeta();
meta.setLastUpdated(new Date());
messageHeader.setMeta(meta);
}
List<IBaseResource> resources = new ArrayList<>();
List<Patient> patients = BundleUtil.toListOfResourcesOfType(this.getFhirContext(), bundle, Patient.class);
for (Patient p : patients) {
patientId = p.getId();
p.setId(p.getIdElement().toVersionless());
resources.add(p);
}
List<Bundle> bundles = BundleUtil.toListOfResourcesOfType(this.getFhirContext(), bundle, Bundle.class);
for (Bundle b : bundles) {
patientId = this.processBundle(b, theRequestDetails);
b.setId(b.getIdElement().toVersionless());
resources.add(b);
}
for (BundleEntryComponent e : bundle.getEntry()) {
Resource r = e.getResource();
if (r == null) {
continue;
}
if (r.fhirType().equals("Bundle") || r.fhirType().equals("MessageHeader") || r.fhirType().equals("Patient")) {
continue;
}
r.setId(r.getIdElement().toVersionless());
resources.add(r);
}
if (patientId != null) {
commId = constructAndSaveCommunication(patientId);
}
if (messageHeader == null) {
messageHeader = constructMessageHeaderResource();
BundleEntryComponent entryComp = new BundleEntryComponent();
entryComp.setResource(messageHeader);
dafBundle.addEntry(entryComp);
}
if (commId != null) {
List<Reference> referenceList = new ArrayList<>();
Reference commRef = new Reference();
commRef.setReference("Communication/" + commId);
referenceList.add(commRef);
messageHeader.setFocus(referenceList);
}
IVersionSpecificBundleFactory newBundleFactory = this.getFhirContext().newBundleFactory();
newBundleFactory.addResourcesToBundle(resources, BundleTypeEnum.TRANSACTION, theRequestDetails.getFhirServerBase(), null, null);
Bundle transactionBundle = (Bundle) newBundleFactory.getResourceBundle();
for (BundleEntryComponent entry : transactionBundle.getEntry()) {
UriType uri = new UriType(theRequestDetails.getFhirServerBase() + "/" + entry.getResource().fhirType() + "/" + entry.getResource().getIdElement().getIdPart());
Enumeration<HTTPVerb> method = new Enumeration<>(new HTTPVerbEnumFactory());
method.setValue(HTTPVerb.PUT);
entry.setRequest(new BundleEntryRequestComponent(method, uri));
}
@SuppressWarnings("unchecked") IFhirSystemDao<Bundle, Meta> fhirSystemDao = this.getDaoRegistry().getSystemDao();
fhirSystemDao.transaction(theRequestDetails, transactionBundle);
return dafBundle;
} else {
BundleEntryComponent entryComp = new BundleEntryComponent();
entryComp.setResource(outcome);
bundle.addEntry(entryComp);
return bundle;
}
}
Aggregations