Search in sources :

Example 6 with DataType

use of org.hl7.fhir.r5.model.DataType in project kindling by HL7.

the class DictHTMLGenerator method encodeValue.

private String encodeValue(DataType value) throws Exception {
    if (value == null || value.isEmpty())
        return null;
    if (value instanceof PrimitiveType)
        return Utilities.escapeXml(((PrimitiveType) value).asStringValue());
    ByteArrayOutputStream bs = new ByteArrayOutputStream();
    XmlParser parser = new XmlParser();
    parser.setOutputStyle(OutputStyle.PRETTY);
    parser.compose(bs, null, value);
    String[] lines = bs.toString().split("\\r?\\n");
    StringBuilder b = new StringBuilder();
    for (String s : lines) {
        if (!Utilities.noString(s) && !s.startsWith("<?")) {
            // eliminate the xml header
            b.append(Utilities.escapeXml(s).replace(" ", "&nbsp;") + "<br/>");
        }
    }
    return b.toString();
}
Also used : XmlParser(org.hl7.fhir.r5.formats.XmlParser) CommaSeparatedStringBuilder(org.hl7.fhir.utilities.CommaSeparatedStringBuilder) PrimitiveType(org.hl7.fhir.r5.model.PrimitiveType) ByteArrayOutputStream(java.io.ByteArrayOutputStream)

Example 7 with DataType

use of org.hl7.fhir.r5.model.DataType in project quality-measure-and-cohort-service by Alvearie.

the class CohortEngineRestHandler method evaluateMeasure.

@POST
@Path("/evaluation")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces({ MediaType.APPLICATION_JSON })
@ApiOperation(value = "Evaluates a measure bundle for a single patient", notes = EVALUATION_API_NOTES, response = String.class, tags = { "Measure Evaluation" }, nickname = "evaluate_measure", extensions = { @Extension(properties = { @ExtensionProperty(name = DarkFeatureSwaggerFilter.DARK_FEATURE_NAME, value = CohortEngineRestConstants.DARK_LAUNCHED_MEASURE_EVALUATION) }) })
@ApiImplicitParams({ // This is necessary for the dark launch feature
@ApiImplicitParam(access = DarkFeatureSwaggerFilter.DARK_FEATURE_CONTROLLED, paramType = "header", dataType = "string"), // These are necessary to create a proper view of the request body that is all wrapped up in the Liberty IMultipartBody parameter
@ApiImplicitParam(name = REQUEST_DATA_PART, value = EXAMPLE_REQUEST_DATA_JSON, dataTypeClass = MeasureEvaluation.class, required = true, paramType = "form", type = "file"), @ApiImplicitParam(name = MEASURE_PART, value = EXAMPLE_MEASURE_ZIP, dataTypeClass = File.class, required = true, paramType = "form", type = "file") })
@ApiResponses(value = { @ApiResponse(code = 200, message = "Successful Operation: This API returns the JSON representation of a FHIR MeasureReport. A full example can be found at https://www.hl7.org/fhir/measurereport-cms146-cat1-example.html"), @ApiResponse(code = 400, message = "Bad Request", response = ServiceErrorList.class), @ApiResponse(code = 500, message = "Server Error", response = ServiceErrorList.class) })
public Response evaluateMeasure(@Context HttpServletRequest request, @ApiParam(value = ServiceBaseConstants.MINOR_VERSION_DESCRIPTION, required = true, defaultValue = ServiceBuildConstants.DATE) @QueryParam(CohortEngineRestHandler.VERSION) String version, @ApiParam(hidden = true, type = "file", required = true) IMultipartBody multipartBody) {
    final String methodName = MethodNames.EVALUATE_MEASURE.getName();
    Response response = null;
    // Error out if feature is not enabled
    ServiceBaseUtility.isDarkFeatureEnabled(CohortEngineRestConstants.DARK_LAUNCHED_MEASURE_EVALUATION);
    try {
        // Perform api setup
        Response errorResponse = ServiceBaseUtility.apiSetup(version, logger, methodName);
        if (errorResponse != null) {
            return errorResponse;
        }
        if (multipartBody == null) {
            throw new IllegalArgumentException("A multipart/form-data body is required");
        }
        IAttachment metadataAttachment = multipartBody.getAttachment(REQUEST_DATA_PART);
        if (metadataAttachment == null) {
            throw new IllegalArgumentException(String.format("Missing '%s' MIME attachment", REQUEST_DATA_PART));
        }
        IAttachment measureAttachment = multipartBody.getAttachment(MEASURE_PART);
        if (measureAttachment == null) {
            throw new IllegalArgumentException(String.format("Missing '%s' MIME attachment", MEASURE_PART));
        }
        // deserialize the MeasuresEvaluation request
        ObjectMapper om = new ObjectMapper();
        MeasureEvaluation evaluationRequest = om.readValue(metadataAttachment.getDataHandler().getInputStream(), MeasureEvaluation.class);
        // validate the contents of the evaluationRequest
        validateBean(evaluationRequest);
        FhirContext fhirContext = FhirContext.forR4();
        try (InputStream is = measureAttachment.getDataHandler().getInputStream();
            RetrieveCacheContext retrieveCacheContext = new DefaultRetrieveCacheContext()) {
            MeasureEvaluator evaluator = createMeasureEvaluator(is, evaluationRequest.getDataServerConfig(), evaluationRequest.getTerminologyServerConfig(), evaluationRequest.isExpandValueSets(), evaluationRequest.getSearchPageSize(), retrieveCacheContext, fhirContext);
            MeasureReport report = evaluator.evaluatePatientMeasure(evaluationRequest.getPatientId(), evaluationRequest.getMeasureContext(), evaluationRequest.getEvidenceOptions());
            // The default serializer gets into an infinite loop when trying to serialize MeasureReport, so we use the
            // HAPI encoder instead.
            IParser parser = fhirContext.newJsonParser();
            ResponseBuilder responseBuilder = Response.status(Response.Status.OK).header("Content-Type", "application/json").entity(parser.encodeResourceToString(report));
            response = responseBuilder.build();
        }
    } catch (Throwable e) {
        // map any exceptions caught into the proper REST error response objects
        response = new CohortServiceExceptionMapper().toResponse(e);
    } finally {
        // Perform api cleanup
        Response errorResponse = ServiceBaseUtility.apiCleanup(logger, methodName);
        if (errorResponse != null) {
            response = errorResponse;
        }
    }
    return response;
}
Also used : FhirContext(ca.uhn.fhir.context.FhirContext) MeasureEvaluation(com.ibm.cohort.engine.api.service.model.MeasureEvaluation) PatientListMeasureEvaluation(com.ibm.cohort.engine.api.service.model.PatientListMeasureEvaluation) ZipInputStream(java.util.zip.ZipInputStream) InputStream(java.io.InputStream) DefaultRetrieveCacheContext(com.ibm.cohort.engine.measure.cache.DefaultRetrieveCacheContext) RetrieveCacheContext(com.ibm.cohort.engine.measure.cache.RetrieveCacheContext) MeasureReport(org.hl7.fhir.r4.model.MeasureReport) DefaultRetrieveCacheContext(com.ibm.cohort.engine.measure.cache.DefaultRetrieveCacheContext) MeasureEvaluator(com.ibm.cohort.engine.measure.MeasureEvaluator) IAttachment(com.ibm.websphere.jaxrs20.multipart.IAttachment) Response(javax.ws.rs.core.Response) ApiResponse(io.swagger.annotations.ApiResponse) ResponseBuilder(javax.ws.rs.core.Response.ResponseBuilder) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) IParser(ca.uhn.fhir.parser.IParser) Path(javax.ws.rs.Path) ApiImplicitParams(io.swagger.annotations.ApiImplicitParams) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces) ApiOperation(io.swagger.annotations.ApiOperation) ApiResponses(io.swagger.annotations.ApiResponses)

Example 8 with DataType

use of org.hl7.fhir.r5.model.DataType in project quality-measure-and-cohort-service by Alvearie.

the class SparkCqlEvaluator method createDataTypeAliases.

private Map<String, String> createDataTypeAliases(List<ContextDefinition> filteredContexts, CqlToElmTranslator translator) {
    Set<String> dataTypes = filteredContexts.stream().map(ContextDefinition::getPrimaryDataType).collect(Collectors.toSet());
    Collection<ModelInfo> modelInfos = translator.getRegisteredModelInfos().values();
    Map<String, String> dataTypeAliases = new HashMap<>();
    for (ModelInfo modelInfo : modelInfos) {
        modelInfo.getTypeInfo().stream().filter(ClassInfo.class::isInstance).map(ClassInfo.class::cast).filter(classInfo -> dataTypes.contains(classInfo.getName())).forEach(info -> {
            String dataType = info.getName();
            QName baseType = ModelUtils.getBaseTypeName(modelInfo, info);
            if (baseType != null) {
                // for inheritance types
                dataTypeAliases.put(dataType, baseType.getLocalPart());
            }
            Collection<String> choiceTypes = ModelUtils.getChoiceTypeNames(info);
            // for choice types
            choiceTypes.forEach(choiceType -> dataTypeAliases.put(dataType, choiceType));
        });
    }
    return dataTypeAliases;
}
Also used : ModelInfo(org.hl7.elm_modelinfo.r1.ModelInfo) Arrays(java.util.Arrays) CqlDataProvider(com.ibm.cohort.cql.data.CqlDataProvider) CqlToElmTranslator(com.ibm.cohort.cql.translation.CqlToElmTranslator) FileSystem(org.apache.hadoop.fs.FileSystem) ZonedDateTime(java.time.ZonedDateTime) LoggerFactory(org.slf4j.LoggerFactory) EncodedParametersCache(com.ibm.cohort.cql.spark.util.EncodedParametersCache) DataRowDataProvider(com.ibm.cohort.datarow.engine.DataRowDataProvider) Format(com.ibm.cohort.cql.library.Format) ClassInfo(org.hl7.elm_modelinfo.r1.ClassInfo) ColumnRuleCreator(com.ibm.cohort.cql.spark.aggregation.ColumnRuleCreator) ConfigurableOutputColumnNameEncoder(com.ibm.cohort.cql.spark.data.ConfigurableOutputColumnNameEncoder) DefaultDatasetRetriever(com.ibm.cohort.cql.spark.data.DefaultDatasetRetriever) SparkSchemaCreator(com.ibm.cohort.cql.spark.data.SparkSchemaCreator) ContextDefinition(com.ibm.cohort.cql.spark.aggregation.ContextDefinition) Map(java.util.Map) Path(org.apache.hadoop.fs.Path) CqlEvaluationRequest(com.ibm.cohort.cql.evaluation.CqlEvaluationRequest) ModelUtils(com.ibm.cohort.cql.spark.optimizer.ModelUtils) ConstraintViolation(javax.validation.ConstraintViolation) StructType(org.apache.spark.sql.types.StructType) HadoopPathOutputMetadataWriter(com.ibm.cohort.cql.spark.metadata.HadoopPathOutputMetadataWriter) Collection(java.util.Collection) Set(java.util.Set) Validator(javax.validation.Validator) CqlLibraryProvider(com.ibm.cohort.cql.library.CqlLibraryProvider) Reader(java.io.Reader) Tuple2(scala.Tuple2) Collectors(java.util.stream.Collectors) FileNotFoundException(java.io.FileNotFoundException) Serializable(java.io.Serializable) ContextRetriever(com.ibm.cohort.cql.spark.aggregation.ContextRetriever) List(java.util.List) CqlEvaluationRequests(com.ibm.cohort.cql.evaluation.CqlEvaluationRequests) CqlTerminologyProvider(com.ibm.cohort.cql.terminology.CqlTerminologyProvider) QName(javax.xml.namespace.QName) SparkOutputColumnEncoder(com.ibm.cohort.cql.spark.data.SparkOutputColumnEncoder) Parameter(com.ibm.cohort.cql.evaluation.parameters.Parameter) MapUtils(com.ibm.cohort.cql.util.MapUtils) ExternalFunctionProvider(org.opencds.cqf.cql.engine.data.ExternalFunctionProvider) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Dataset(org.apache.spark.sql.Dataset) SerializableConfiguration(org.apache.spark.util.SerializableConfiguration) CqlEvaluationResult(com.ibm.cohort.cql.evaluation.CqlEvaluationResult) SparkDataRow(com.ibm.cohort.cql.spark.data.SparkDataRow) PriorityCqlLibraryProvider(com.ibm.cohort.cql.library.PriorityCqlLibraryProvider) R4FileSystemFhirTerminologyProvider(com.ibm.cohort.cql.terminology.R4FileSystemFhirTerminologyProvider) HashMap(java.util.HashMap) ValidatorFactory(javax.validation.ValidatorFactory) HadoopBasedCqlLibraryProvider(com.ibm.cohort.cql.library.HadoopBasedCqlLibraryProvider) SparkTypeConverter(com.ibm.cohort.cql.spark.data.SparkTypeConverter) Function(java.util.function.Function) ArrayList(java.util.ArrayList) CustomMetricSparkPlugin(com.ibm.cohort.cql.spark.metrics.CustomMetricSparkPlugin) CollectionUtils(org.apache.commons.collections.CollectionUtils) EvaluationError(com.ibm.cohort.cql.spark.errors.EvaluationError) DataRowRetrieveProvider(com.ibm.cohort.datarow.engine.DataRowRetrieveProvider) Validation(javax.validation.Validation) TranslatingCqlLibraryProvider(com.ibm.cohort.cql.translation.TranslatingCqlLibraryProvider) NoSuchElementException(java.util.NoSuchElementException) EvaluationSummary(com.ibm.cohort.cql.spark.metadata.EvaluationSummary) DataRow(com.ibm.cohort.datarow.model.DataRow) SparkSession(org.apache.spark.sql.SparkSession) PrintStream(java.io.PrintStream) CqlEvaluator(com.ibm.cohort.cql.evaluation.CqlEvaluator) ClasspathCqlLibraryProvider(com.ibm.cohort.cql.library.ClasspathCqlLibraryProvider) SaveMode(org.apache.spark.sql.SaveMode) Logger(org.slf4j.Logger) CqlDebug(com.ibm.cohort.cql.evaluation.CqlDebug) Iterator(java.util.Iterator) RowFactory(org.apache.spark.sql.RowFactory) JCommander(com.beust.jcommander.JCommander) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) IOException(java.io.IOException) Row(org.apache.spark.sql.Row) CollectionAccumulator(org.apache.spark.util.CollectionAccumulator) InputStreamReader(java.io.InputStreamReader) JavaPairRDD(org.apache.spark.api.java.JavaPairRDD) LongAccumulator(org.apache.spark.util.LongAccumulator) CqlExpressionConfiguration(com.ibm.cohort.cql.evaluation.CqlExpressionConfiguration) AnyColumnFunctions(com.ibm.cohort.cql.functions.AnyColumnFunctions) MDC(org.slf4j.MDC) UnsupportedTerminologyProvider(com.ibm.cohort.cql.terminology.UnsupportedTerminologyProvider) CohortExternalFunctionProvider(com.ibm.cohort.cql.functions.CohortExternalFunctionProvider) ContextDefinitions(com.ibm.cohort.cql.spark.aggregation.ContextDefinitions) Collections(java.util.Collections) OutputMetadataWriter(com.ibm.cohort.cql.spark.metadata.OutputMetadataWriter) ModelInfo(org.hl7.elm_modelinfo.r1.ModelInfo) HashMap(java.util.HashMap) QName(javax.xml.namespace.QName) ClassInfo(org.hl7.elm_modelinfo.r1.ClassInfo)

Example 9 with DataType

use of org.hl7.fhir.r5.model.DataType in project drug-formulary-ri by HL7-DaVinci.

the class PatientAuthorizationInterceptor method verify.

/**
 * Helper method to verify and decode the access token
 *
 * @param token       - the access token
 * @param fhirBaseUrl - the base url of this FHIR server
 * @return the base interface Patient ID datatype if the jwt token is verified
 *         and contains a patient ID in it claim, otherwise null.
 * @throws SignatureVerificationException
 * @throws TokenExpiredException
 * @throws JWTVerificationException
 */
private IIdType verify(String token, String fhirBaseUrl) throws SignatureVerificationException, TokenExpiredException, JWTVerificationException {
    Algorithm algorithm = Algorithm.RSA256(OauthEndpointController.getPublicKey(), null);
    logger.fine("Verifying JWT token iss and aud is " + fhirBaseUrl);
    JWTVerifier verifier = JWT.require(algorithm).withIssuer(fhirBaseUrl).withAudience(fhirBaseUrl).build();
    DecodedJWT jwt = verifier.verify(token);
    String patientId = jwt.getClaim("patient_id").asString();
    if (patientId != null)
        return new IdType("Patient", patientId);
    return null;
}
Also used : Algorithm(com.auth0.jwt.algorithms.Algorithm) JWTVerifier(com.auth0.jwt.JWTVerifier) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT) IIdType(org.hl7.fhir.instance.model.api.IIdType) IdType(org.hl7.fhir.r4.model.IdType)

Example 10 with DataType

use of org.hl7.fhir.r5.model.DataType in project org.hl7.fhir.core by hapifhir.

the class ElementDefinition30_50 method convertElementDefinitionBindingComponent.

public static ElementDefinition.ElementDefinitionBindingComponent convertElementDefinitionBindingComponent(org.hl7.fhir.dstu3.model.ElementDefinition.ElementDefinitionBindingComponent src) throws FHIRException {
    if (src == null)
        return null;
    ElementDefinition.ElementDefinitionBindingComponent tgt = new ElementDefinition.ElementDefinitionBindingComponent();
    ConversionContext30_50.INSTANCE.getVersionConvertor_30_50().copyElement(src, tgt, VersionConvertor_30_50.EXT_SRC_TYPE);
    if (src.hasStrength())
        tgt.setStrengthElement(Enumerations30_50.convertBindingStrength(src.getStrengthElement()));
    if (src.hasDescription())
        tgt.setDescriptionElement(String30_50.convertString(src.getDescriptionElement()));
    if (src.hasValueSet()) {
        DataType t = ConversionContext30_50.INSTANCE.getVersionConvertor_30_50().convertType(src.getValueSet());
        if (t instanceof org.hl7.fhir.r5.model.Reference) {
            tgt.setValueSet(((org.hl7.fhir.r5.model.Reference) t).getReference());
            tgt.getValueSetElement().addExtension(VersionConvertor_30_50.EXT_SRC_TYPE, new org.hl7.fhir.r5.model.UrlType("Reference"));
        } else {
            tgt.setValueSet(t.primitiveValue());
            tgt.getValueSetElement().addExtension(VersionConvertor_30_50.EXT_SRC_TYPE, new org.hl7.fhir.r5.model.UrlType("uri"));
        }
        tgt.setValueSet(VersionConvertorConstants.refToVS(tgt.getValueSet()));
    }
    return tgt;
}
Also used : DataType(org.hl7.fhir.r5.model.DataType) ElementDefinition(org.hl7.fhir.r5.model.ElementDefinition)

Aggregations

DataType (org.hl7.fhir.r5.model.DataType)14 FHIRException (org.hl7.fhir.exceptions.FHIRException)11 XhtmlNode (org.hl7.fhir.utilities.xhtml.XhtmlNode)11 DefinitionException (org.hl7.fhir.exceptions.DefinitionException)8 HashMap (java.util.HashMap)7 List (java.util.List)7 Map (java.util.Map)7 FHIRFormatError (org.hl7.fhir.exceptions.FHIRFormatError)7 Collectors (java.util.stream.Collectors)6 DataType (org.hl7.cql.model.DataType)6 ModelInfo (org.hl7.elm_modelinfo.r1.ModelInfo)6 Piece (org.hl7.fhir.utilities.xhtml.HierarchicalTableGenerator.Piece)6 ArrayList (java.util.ArrayList)5 StructType (org.apache.spark.sql.types.StructType)5 BooleanType (org.hl7.fhir.r5.model.BooleanType)5 ValueSet (org.hl7.fhir.r5.model.ValueSet)5 Arrays (java.util.Arrays)4 QName (javax.xml.namespace.QName)4 DataType (org.hl7.fhir.r4b.model.DataType)4 ByteArrayOutputStream (java.io.ByteArrayOutputStream)3