Search in sources :

Example 1 with R4HookEvaluator

use of org.opencds.cqf.ruler.cdshooks.hooks.R4HookEvaluator 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)

Aggregations

FhirContext (ca.uhn.fhir.context.FhirContext)1 SystemRequestDetails (ca.uhn.fhir.jpa.partition.SystemRequestDetails)1 RequestDetails (ca.uhn.fhir.rest.api.server.RequestDetails)1 BaseServerResponseException (ca.uhn.fhir.rest.server.exceptions.BaseServerResponseException)1 InvalidRequestException (ca.uhn.fhir.rest.server.exceptions.InvalidRequestException)1 JsonParser (com.google.gson.JsonParser)1 IOException (java.io.IOException)1 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)1 ServletException (javax.servlet.ServletException)1 HttpServletRequest (javax.servlet.http.HttpServletRequest)1 VersionedIdentifier (org.cqframework.cql.elm.execution.VersionedIdentifier)1 CanonicalType (org.hl7.fhir.r4.model.CanonicalType)1 Library (org.hl7.fhir.r4.model.Library)1 PlanDefinition (org.hl7.fhir.r4.model.PlanDefinition)1 CqlException (org.opencds.cqf.cql.engine.exception.CqlException)1 Context (org.opencds.cqf.cql.engine.execution.Context)1 LibraryLoader (org.opencds.cqf.cql.engine.execution.LibraryLoader)1 DataProviderException (org.opencds.cqf.cql.engine.fhir.exception.DataProviderException)1 TerminologyProvider (org.opencds.cqf.cql.engine.terminology.TerminologyProvider)1 EvaluationContext (org.opencds.cqf.ruler.cdshooks.evaluation.EvaluationContext)1