Search in sources :

Example 16 with JsonParser

use of org.hl7.fhir.r5.elementmodel.JsonParser 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();
        Request cdsHooksRequest = new Request(service, parser.parse(request.getReader()).getAsJsonObject(), JsonHelper.getObjectRequired(getService(service), "prefetch"));
        logger.info(cdsHooksRequest.getRequestJson().toString());
        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.getTrigger().forEach(trigger -> {
                if (hookName.equals(trigger.getName())) {
                    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)));
        CanonicalType canonical = planDefinition.getLibrary().get(0);
        Library library = search(Library.class, Searches.byCanonical(canonical)).single();
        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);
        context.registerDataProvider("http://hl7.org/fhir", // TODO make sure tooling
        fhirRetrieveProviderFactory.create(requestDetails, serverTerminologyProvider));
        // handles remote
        context.registerTerminologyProvider(serverTerminologyProvider);
        context.registerLibraryLoader(libraryLoader);
        context.setContextValue("Patient", hook.getRequest().getContext().getPatientId().replace("Patient/", ""));
        context.setExpressionCaching(true);
        EvaluationContext<PlanDefinition> evaluationContext = new R4EvaluationContext(hook, FhirContext.forCached(FhirVersionEnum.R4).newRestfulGenericClient(baseUrl), context, elm, planDefinition, this.getProviderConfiguration(), this.modelResolver);
        this.setAccessControlHeaders(response);
        response.setHeader("Content-Type", ContentType.APPLICATION_JSON.getMimeType());
        R4HookEvaluator evaluator = new R4HookEvaluator(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);
    }
}
Also used : LibraryLoader(org.opencds.cqf.cql.engine.execution.LibraryLoader) CanonicalType(org.hl7.fhir.r4.model.CanonicalType) ServletException(javax.servlet.ServletException) VersionedIdentifier(org.cqframework.cql.elm.execution.VersionedIdentifier) SystemRequestDetails(ca.uhn.fhir.jpa.partition.SystemRequestDetails) DataProviderException(org.opencds.cqf.cql.engine.fhir.exception.DataProviderException) JsonParser(com.google.gson.JsonParser) FhirContext(ca.uhn.fhir.context.FhirContext) EvaluationContext(org.opencds.cqf.ruler.cdshooks.evaluation.EvaluationContext) Context(org.opencds.cqf.cql.engine.execution.Context) R4EvaluationContext(org.opencds.cqf.ruler.cdshooks.evaluation.R4EvaluationContext) Hook(org.opencds.cqf.ruler.cdshooks.hooks.Hook) Request(org.opencds.cqf.ruler.cdshooks.request.Request) HttpServletRequest(javax.servlet.http.HttpServletRequest) R4EvaluationContext(org.opencds.cqf.ruler.cdshooks.evaluation.R4EvaluationContext) BaseServerResponseException(ca.uhn.fhir.rest.server.exceptions.BaseServerResponseException) RequestDetails(ca.uhn.fhir.rest.api.server.RequestDetails) SystemRequestDetails(ca.uhn.fhir.jpa.partition.SystemRequestDetails) ServletException(javax.servlet.ServletException) CqlException(org.opencds.cqf.cql.engine.exception.CqlException) InvalidRequestException(ca.uhn.fhir.rest.server.exceptions.InvalidRequestException) DataProviderException(org.opencds.cqf.cql.engine.fhir.exception.DataProviderException) BaseServerResponseException(ca.uhn.fhir.rest.server.exceptions.BaseServerResponseException) IOException(java.io.IOException) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) TerminologyProvider(org.opencds.cqf.cql.engine.terminology.TerminologyProvider) PlanDefinition(org.hl7.fhir.r4.model.PlanDefinition) Library(org.hl7.fhir.r4.model.Library) R4HookEvaluator(org.opencds.cqf.ruler.cdshooks.hooks.R4HookEvaluator) CqlException(org.opencds.cqf.cql.engine.exception.CqlException)

Example 17 with JsonParser

use of org.hl7.fhir.r5.elementmodel.JsonParser in project cqf-ruler by DBCG.

the class R4CarePlanToCdsCard method convert.

private static List<CdsCard> convert(RequestGroup requestGroup) {
    List<CdsCard> cards = new ArrayList<>();
    // links
    List<CdsCard.Links> links = new ArrayList<>();
    if (requestGroup.hasExtension()) {
        for (Extension extension : requestGroup.getExtension()) {
            CdsCard.Links link = new CdsCard.Links();
            if (extension.getValue() instanceof Attachment) {
                Attachment attachment = (Attachment) extension.getValue();
                if (attachment.hasUrl()) {
                    link.setUrl(attachment.getUrl());
                }
                if (attachment.hasTitle()) {
                    link.setLabel(attachment.getTitle());
                }
                if (attachment.hasExtension()) {
                    link.setType(attachment.getExtensionFirstRep().getValue().primitiveValue());
                }
            } else {
                throw new RuntimeException("Invalid link extension type: " + extension.getValue().fhirType());
            }
            links.add(link);
        }
    }
    if (requestGroup.hasAction()) {
        for (RequestGroup.RequestGroupActionComponent action : requestGroup.getAction()) {
            IParser jsonParser = FhirContext.forCached(FhirVersionEnum.R4).newJsonParser().setPrettyPrint(true);
            CdsCard card = new CdsCard(jsonParser);
            // basic
            if (action.hasTitle()) {
                card.setSummary(action.getTitle());
            }
            if (action.hasDescription()) {
                card.setDetail(action.getDescription());
            }
            if (action.hasExtension()) {
                card.setIndicator(action.getExtensionFirstRep().getValue().toString());
            }
            // source
            if (action.hasDocumentation()) {
                // Assuming first related artifact has everything
                RelatedArtifact documentation = action.getDocumentationFirstRep();
                CdsCard.Source source = new CdsCard.Source();
                if (documentation.hasDisplay()) {
                    source.setLabel(documentation.getDisplay());
                }
                if (documentation.hasUrl()) {
                    source.setUrl(documentation.getUrl());
                }
                if (documentation.hasDocument() && documentation.getDocument().hasUrl()) {
                    source.setIcon(documentation.getDocument().getUrl());
                }
                card.setSource(source);
            }
            if (action.hasSelectionBehavior()) {
                card.setSelectionBehavior(action.getSelectionBehavior().toCode());
            }
            // suggestions
            // TODO - uuid
            boolean hasSuggestions = false;
            CdsCard.Suggestions suggestions = new CdsCard.Suggestions();
            CdsCard.Suggestions.Action actions = new CdsCard.Suggestions.Action();
            if (action.hasPrefix()) {
                suggestions.setLabel(action.getPrefix());
                hasSuggestions = true;
                if (action.hasDescription()) {
                    actions.setDescription(action.getDescription());
                }
                if (action.hasType() && !action.getType().getCodingFirstRep().getCode().equals("fire-event")) {
                    String code = action.getType().getCodingFirstRep().getCode();
                    actions.setType(CdsCard.Suggestions.Action.ActionType.valueOf(code.equals("remove") ? "delete" : code));
                }
                if (action.hasResource()) {
                    if (actions.getType().name().equalsIgnoreCase("create")) {
                        action.getResourceTarget().setId((String) null);
                    }
                    actions.setResource(action.getResourceTarget());
                }
            }
            if (hasSuggestions) {
                suggestions.addAction(actions);
                card.addSuggestion(suggestions);
            }
            if (!links.isEmpty()) {
                card.setLinks(links);
            }
            cards.add(card);
        }
    }
    return cards;
}
Also used : ArrayList(java.util.ArrayList) Attachment(org.hl7.fhir.r4.model.Attachment) RelatedArtifact(org.hl7.fhir.r4.model.RelatedArtifact) Extension(org.hl7.fhir.r4.model.Extension) RequestGroup(org.hl7.fhir.r4.model.RequestGroup) IParser(ca.uhn.fhir.parser.IParser)

Example 18 with JsonParser

use of org.hl7.fhir.r5.elementmodel.JsonParser in project Gravity-SDOH-Exchange-RI by FHIR.

the class TaskPollingService method demoRunQRThroughStructureMap.

/*
  A TEST polling service, implemented during January 2022 Connectathon, that automatically runs questionnaireResponse
  resources through a StructureMap. If any exception occurs - just ignore it.
   */
public void demoRunQRThroughStructureMap() {
    log.info("Looking for TOP 3 Patient QuestionnaireResponse resources without derived Observations...");
    // TODO use repository instead
    Bundle tasksBundle = openEhrClient.search().forResource(QuestionnaireResponse.class).where(new StringClientParam(Constants.PARAM_PROFILE).matches().value(SDOHProfiles.QUESTIONNAIRE_RESPONSE)).revInclude(Observation.INCLUDE_DERIVED_FROM.setRecurse(false)).sort().descending(QuestionnaireResponse.AUTHORED).count(3).returnBundle(Bundle.class).execute();
    List<QuestionnaireResponse> responses = FhirUtil.getFromBundle(tasksBundle, QuestionnaireResponse.class, Bundle.SearchEntryMode.MATCH);
    Set<String> derivedFrom = FhirUtil.getFromBundle(tasksBundle, Observation.class, Bundle.SearchEntryMode.INCLUDE).stream().map(o -> o.getDerivedFromFirstRep().getReferenceElement().getIdPart()).collect(Collectors.toSet());
    if (responses.size() != derivedFrom.size()) {
        log.info("Found " + (responses.size() - derivedFrom.size()) + " QuestionnaireResponse resources without observations.");
        List<QuestionnaireResponse> newResponses = responses.stream().filter(qr -> !derivedFrom.contains(qr.getIdElement().getIdPart())).collect(Collectors.toList());
        for (QuestionnaireResponse nr : newResponses) {
            log.info("Converting QuestionnaireResponse with id: " + nr.getIdElement().getIdPart());
            try {
                // TODO move parser logic within the convert service. Use resources instead
                JSONParser parser = new JSONParser(JSONParser.MODE_JSON_SIMPLE);
                Map<String, Object> result = convertService.convert((JSONObject) parser.parse(fhirContext.newJsonParser().encodeResourceToString(nr)));
                Bundle bundle = (Bundle) fhirContext.newJsonParser().parseResource(new JSONObject(result).toJSONString());
                bundle.getEntry().forEach(e -> e.setRequest(new Bundle.BundleEntryRequestComponent().setMethod(Bundle.HTTPVerb.POST).setUrl(e.getResource().getClass().getSimpleName())));
                openEhrClient.transaction().withBundle(bundle).execute();
            } catch (Exception exc) {
                // Just ignore this specific resource and go to the next one
                log.warn(exc.getMessage(), exc);
            }
        }
    }
    log.info("QuestionnaireResponse update process finished.");
}
Also used : Date(java.util.Date) TaskOutputComponent(org.hl7.fhir.r4.model.Task.TaskOutputComponent) Constants(ca.uhn.fhir.rest.api.Constants) RequiredArgsConstructor(lombok.RequiredArgsConstructor) LocalDateTime(java.time.LocalDateTime) CodeableConcept(org.hl7.fhir.r4.model.CodeableConcept) Autowired(org.springframework.beans.factory.annotation.Autowired) Endpoint(org.hl7.fhir.r4.model.Endpoint) Scheduled(org.springframework.scheduling.annotation.Scheduled) Reference(org.hl7.fhir.r4.model.Reference) TaskStatus(org.hl7.fhir.r4.model.Task.TaskStatus) Function(java.util.function.Function) ArrayList(java.util.ArrayList) JSONParser(net.minidev.json.parser.JSONParser) TasksPollingInfo(org.hl7.gravity.refimpl.sdohexchange.fhir.extract.TasksPollingBundleExtractor.TasksPollingInfo) Procedure(org.hl7.fhir.r4.model.Procedure) Task(org.hl7.fhir.r4.model.Task) FhirContext(ca.uhn.fhir.context.FhirContext) TaskInfoHolder(org.hl7.gravity.refimpl.sdohexchange.fhir.extract.TaskInfoBundleExtractor.TaskInfoHolder) Lists(com.google.common.collect.Lists) Service(org.springframework.stereotype.Service) Map(java.util.Map) BundleEntryComponent(org.hl7.fhir.r4.model.Bundle.BundleEntryComponent) IGenericClient(ca.uhn.fhir.rest.client.api.IGenericClient) StringClientParam(ca.uhn.fhir.rest.gclient.StringClientParam) SearchModifierCode(org.hl7.fhir.r4.model.codesystems.SearchModifierCode) Observation(org.hl7.fhir.r4.model.Observation) ServiceRequest(org.hl7.fhir.r4.model.ServiceRequest) SDOHProfiles(org.hl7.gravity.refimpl.sdohexchange.fhir.SDOHProfiles) TokenClientParam(ca.uhn.fhir.rest.gclient.TokenClientParam) Set(java.util.Set) TaskFailBundleFactory(org.hl7.gravity.refimpl.sdohexchange.fhir.factory.TaskFailBundleFactory) CpClientException(org.hl7.gravity.refimpl.sdohexchange.service.CpService.CpClientException) Collectors(java.util.stream.Collectors) IdType(org.hl7.fhir.r4.model.IdType) ZoneId(java.time.ZoneId) Organization(org.hl7.fhir.r4.model.Organization) Slf4j(lombok.extern.slf4j.Slf4j) QuestionnaireResponse(org.hl7.fhir.r4.model.QuestionnaireResponse) TaskPollingUpdateException(org.hl7.gravity.refimpl.sdohexchange.fhir.extract.TasksPollingBundleExtractor.TaskPollingUpdateException) List(java.util.List) TasksPollingBundleExtractor(org.hl7.gravity.refimpl.sdohexchange.fhir.extract.TasksPollingBundleExtractor) JSONObject(net.minidev.json.JSONObject) Bundle(org.hl7.fhir.r4.model.Bundle) OrganizationTypeCode(org.hl7.gravity.refimpl.sdohexchange.codes.OrganizationTypeCode) FhirUtil(org.hl7.gravity.refimpl.sdohexchange.util.FhirUtil) StringClientParam(ca.uhn.fhir.rest.gclient.StringClientParam) Bundle(org.hl7.fhir.r4.model.Bundle) QuestionnaireResponse(org.hl7.fhir.r4.model.QuestionnaireResponse) CpClientException(org.hl7.gravity.refimpl.sdohexchange.service.CpService.CpClientException) TaskPollingUpdateException(org.hl7.gravity.refimpl.sdohexchange.fhir.extract.TasksPollingBundleExtractor.TaskPollingUpdateException) JSONObject(net.minidev.json.JSONObject) Observation(org.hl7.fhir.r4.model.Observation) JSONParser(net.minidev.json.parser.JSONParser) JSONObject(net.minidev.json.JSONObject)

Example 19 with JsonParser

use of org.hl7.fhir.r5.elementmodel.JsonParser in project Gravity-SDOH-Exchange-RI by FHIR.

the class ConvertService method convertToBundle.

private String convertToBundle(JSONObject questionnaireResponse, String mapUri) {
    try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) {
        Element element = validationEngine.transform(questionnaireResponse.toString().getBytes(), Manager.FhirFormat.JSON, mapUri);
        new JsonParser(validationEngine.getContext()).compose(element, byteArrayOutputStream, org.hl7.fhir.r5.formats.IParser.OutputStyle.PRETTY, null);
        return byteArrayOutputStream.toString();
    } catch (IOException e) {
        throw new IllegalStateException("QuestionnaireResponse with id cannot be parsed.", e.getCause());
    }
}
Also used : Element(org.hl7.fhir.r5.elementmodel.Element) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) JsonParser(org.hl7.fhir.r5.elementmodel.JsonParser)

Example 20 with JsonParser

use of org.hl7.fhir.r5.elementmodel.JsonParser in project org.hl7.fhir.core by hapifhir.

the class ExtensionDefinitionGenerator method loadResource.

private Resource loadResource(InputStream inputStream, FHIRVersion v) throws IOException, FHIRException {
    if (v == FHIRVersion._3_0_1) {
        org.hl7.fhir.dstu3.model.Resource res = new org.hl7.fhir.dstu3.formats.JsonParser().parse(inputStream);
        return VersionConvertorFactory_30_40.convertResource(res, new BaseAdvisor_30_40(false));
    } else if (v == FHIRVersion._1_4_0) {
        org.hl7.fhir.dstu2016may.model.Resource res = new org.hl7.fhir.dstu2016may.formats.JsonParser().parse(inputStream);
        return VersionConvertorFactory_14_40.convertResource(res);
    } else if (v == FHIRVersion._1_0_2) {
        org.hl7.fhir.dstu2.model.Resource res = new org.hl7.fhir.dstu2.formats.JsonParser().parse(inputStream);
        BaseAdvisor_10_40 advisor = new IGR2ConvertorAdvisor();
        return VersionConvertorFactory_10_40.convertResource(res, advisor);
    } else if (v == FHIRVersion._4_0_0) {
        return new JsonParser().parse(inputStream);
    } else
        throw new Error("Unsupported version " + v);
}
Also used : Resource(org.hl7.fhir.r4.model.Resource) IGR2ConvertorAdvisor(org.hl7.fhir.convertors.misc.IGR2ConvertorAdvisor) BaseAdvisor_10_40(org.hl7.fhir.convertors.advisors.impl.BaseAdvisor_10_40) BaseAdvisor_30_40(org.hl7.fhir.convertors.advisors.impl.BaseAdvisor_30_40) JsonParser(org.hl7.fhir.r4.formats.JsonParser)

Aggregations

FileOutputStream (java.io.FileOutputStream)82 JsonParser (org.hl7.fhir.r5.formats.JsonParser)66 FHIRException (org.hl7.fhir.exceptions.FHIRException)58 FileInputStream (java.io.FileInputStream)53 IOException (java.io.IOException)49 XmlParser (org.hl7.fhir.r5.formats.XmlParser)44 ByteArrayOutputStream (java.io.ByteArrayOutputStream)41 File (java.io.File)36 JsonParser (org.hl7.fhir.r4.formats.JsonParser)35 CSFileInputStream (org.hl7.fhir.utilities.CSFileInputStream)29 JsonParser (org.hl7.fhir.dstu3.formats.JsonParser)26 JsonParser (org.hl7.fhir.r4b.formats.JsonParser)26 CSFile (org.hl7.fhir.utilities.CSFile)26 ArrayList (java.util.ArrayList)23 TextFile (org.hl7.fhir.utilities.TextFile)20 InputStream (java.io.InputStream)18 IParser (org.hl7.fhir.r5.formats.IParser)18 Resource (org.hl7.fhir.dstu3.model.Resource)17 FileNotFoundException (java.io.FileNotFoundException)16 Resource (org.hl7.fhir.r4.model.Resource)16