Search in sources :

Example 1 with HL7FHIRResourceTemplate

use of io.github.linuxforhealth.hl7.message.HL7FHIRResourceTemplate in project hl7v2-fhir-converter by LinuxForHealth.

the class ResourceReader method getMessageModel.

private HL7MessageModel getMessageModel(String templateName) {
    // Allow for names that already have .yml extension
    String yamlizedTemplateName = templateName.endsWith(".yml") ? templateName : templateName + ".yml";
    String templateFileContent = getResourceInHl7Folder(Constants.MESSAGE_BASE_PATH + yamlizedTemplateName);
    if (StringUtils.isNotBlank(templateFileContent)) {
        try {
            JsonNode parent = ObjectMapperUtil.getYAMLInstance().readTree(templateFileContent);
            Preconditions.checkState(parent != null, "Parent node from template file cannot be null");
            JsonNode resourceNodes = parent.get("resources");
            Preconditions.checkState(resourceNodes != null && !resourceNodes.isEmpty(), "List of resources from Parent node from template file cannot be null or empty");
            List<HL7FHIRResourceTemplateAttributes> templateAttributes = ObjectMapperUtil.getYAMLInstance().convertValue(resourceNodes, new TypeReference<List<HL7FHIRResourceTemplateAttributes>>() {
            });
            List<HL7FHIRResourceTemplate> templates = new ArrayList<>();
            templateAttributes.forEach(t -> templates.add(new HL7FHIRResourceTemplate(t)));
            Preconditions.checkState(templateAttributes != null && !templateAttributes.isEmpty(), "TemplateAttributes generated from template file cannot be null or empty");
            return new HL7MessageModel(templateName, templates);
        } catch (IOException e) {
            throw new IllegalArgumentException("Error encountered in processing the template" + templateName, e);
        }
    } else {
        throw new IllegalArgumentException("File not present:" + templateName);
    }
}
Also used : HL7MessageModel(io.github.linuxforhealth.hl7.message.HL7MessageModel) HL7FHIRResourceTemplateAttributes(io.github.linuxforhealth.hl7.message.HL7FHIRResourceTemplateAttributes) HL7FHIRResourceTemplate(io.github.linuxforhealth.hl7.message.HL7FHIRResourceTemplate) ArrayList(java.util.ArrayList) JsonNode(com.fasterxml.jackson.databind.JsonNode) ArrayList(java.util.ArrayList) List(java.util.List) IOException(java.io.IOException)

Example 2 with HL7FHIRResourceTemplate

use of io.github.linuxforhealth.hl7.message.HL7FHIRResourceTemplate in project hl7v2-fhir-converter by LinuxForHealth.

the class HL7MessageEngine method generateResources.

private List<ResourceResult> generateResources(HL7MessageData hl7DataInput, HL7FHIRResourceTemplate template, Map<String, EvaluationResult> contextValues) {
    ResourceModel resourceModel = template.getResource();
    List<String> segmentGroup = template.getAttributes().getSegment().getGroup();
    String segment = template.getAttributes().getSegment().getSegment();
    List<ResourceResult> resourceResults = null;
    List<SegmentGroup> multipleSegments = getMultipleSegments(hl7DataInput, template, segmentGroup, segment);
    if (!multipleSegments.isEmpty()) {
        resourceResults = generateMultipleResources(hl7DataInput, resourceModel, contextValues, multipleSegments, template.isGenerateMultiple());
    }
    return resourceResults;
}
Also used : ResourceResult(io.github.linuxforhealth.core.resource.ResourceResult) ResourceModel(io.github.linuxforhealth.api.ResourceModel) SegmentGroup(io.github.linuxforhealth.hl7.message.util.SegmentGroup)

Example 3 with HL7FHIRResourceTemplate

use of io.github.linuxforhealth.hl7.message.HL7FHIRResourceTemplate in project hl7v2-fhir-converter by LinuxForHealth.

the class HL7MessageEngine method transform.

/**
 * Converts a HL7 message to a FHIR bundle with the list of resources specified
 *
 * @see io.github.linuxforhealth.api.MessageEngine#transform(io.github.linuxforhealth.api.InputDataExtractor,
 *      java.lang.Iterable, java.util.Map)
 */
@Override
public Bundle transform(final InputDataExtractor dataInput, final Iterable<FHIRResourceTemplate> resources, final Map<String, EvaluationResult> contextValues) {
    Preconditions.checkArgument(dataInput != null, "dataInput cannot be null");
    Preconditions.checkArgument(contextValues != null, "contextValues cannot be null");
    Preconditions.checkArgument(resources != null, "resources cannot be null");
    HL7MessageData hl7DataInput = (HL7MessageData) dataInput;
    Bundle bundle = initBundle();
    Map<String, EvaluationResult> localContextValues = new HashMap<>(contextValues);
    // Add run-time properties to localContextVariables
    for (Map.Entry<String, String> entry : getFHIRContext().getProperties().entrySet()) {
        localContextValues.put(entry.getKey(), new SimpleEvaluationResult<String>(entry.getValue()));
    }
    // Add the ZoneId runtime property to localContextVariables
    // If it is not passed in (null), use "" (empty) to satisfy parser null checks in .yml parsing
    String zoneIdText = getFHIRContext().getZoneIdText() != null ? getFHIRContext().getZoneIdText() : "";
    localContextValues.put("ZONEID", new SimpleEvaluationResult<String>(zoneIdText));
    List<ResourceResult> resourceResultsWithEvalLater = new ArrayList<>();
    for (FHIRResourceTemplate genericTemplate : resources) {
        HL7FHIRResourceTemplate hl7ResourceTemplate = (HL7FHIRResourceTemplate) genericTemplate;
        ResourceModel rs = genericTemplate.getResource();
        List<ResourceResult> resourceResults = new ArrayList<>();
        try {
            MDC.put(RESOURCE, rs.getName());
            List<ResourceResult> results = generateResources(hl7DataInput, hl7ResourceTemplate, localContextValues);
            if (results != null) {
                resourceResults.addAll(results);
                results.stream().filter(r -> (r.getPendingExpressions() != null && !r.getPendingExpressions().isEmpty())).forEach(re -> resourceResultsWithEvalLater.add(re));
                List<ResourceResult> resultsToAddToBundle = results.stream().filter(r -> (r.getPendingExpressions() == null || r.getPendingExpressions().isEmpty())).collect(Collectors.toList());
                addResourceToBundle(bundle, resultsToAddToBundle);
            }
            resourceResults.removeIf(isEmpty());
            Map<String, EvaluationResult> newContextValues = getContextValuesFromResource(hl7ResourceTemplate, resourceResults);
            localContextValues.putAll(newContextValues);
        } catch (IllegalArgumentException | IllegalStateException e) {
            LOGGER.error("Exception during resource {} generation", rs.getName());
            LOGGER.debug("Exception during resource {} generation", rs.getName(), e);
        } finally {
            MDC.remove(RESOURCE);
        }
    }
    for (ResourceResult r : resourceResultsWithEvalLater) {
        MDC.put(RESOURCE, "PendingExpressions");
        try {
            Map<String, EvaluationResult> primaryContextValues = new HashMap<>(localContextValues);
            r.getPendingExpressions().getContextValues().entrySet().forEach(e -> primaryContextValues.putIfAbsent(e.getKey(), e.getValue()));
            ResourceEvaluationResult res = ExpressionUtility.evaluate(hl7DataInput, primaryContextValues, r.getPendingExpressions().getExpressions());
            Map<String, Object> resolvedValues = new HashMap<>();
            resolvedValues.putAll(r.getValue().getResource());
            resolvedValues.putAll(res.getResolveValues());
            List<ResourceValue> additionalResources = new ArrayList<>();
            additionalResources.addAll(r.getAdditionalResources());
            additionalResources.addAll(res.getAdditionalResolveValues());
            ResourceResult updatedResourceResult = new ResourceResult(new SimpleResourceValue(resolvedValues, r.getValue().getFHIRResourceType()), additionalResources, r.getGroupId());
            addResourceToBundle(bundle, Lists.newArrayList(updatedResourceResult));
        } catch (IllegalArgumentException | IllegalStateException e) {
            LOGGER.error("Exception during resource PendingExpressions generation");
            LOGGER.debug("Exception during resource PendingExpressions generation", e);
        } finally {
            MDC.remove(RESOURCE);
        }
    }
    LOGGER.info("Successfully converted message");
    LOGGER.debug("Successfully converted Message: {} , Message Control Id: {} to FHIR bundle resource with id {}", dataInput.getName(), dataInput.getId(), bundle.getId());
    return bundle;
}
Also used : SegmentGroup(io.github.linuxforhealth.hl7.message.util.SegmentGroup) ResourceEvaluationResult(io.github.linuxforhealth.hl7.resource.ResourceEvaluationResult) Constants(io.github.linuxforhealth.core.Constants) LoggerFactory(org.slf4j.LoggerFactory) HashMap(java.util.HashMap) SimpleEvaluationResult(io.github.linuxforhealth.core.expression.SimpleEvaluationResult) FHIRResourceTemplate(io.github.linuxforhealth.api.FHIRResourceTemplate) ArrayList(java.util.ArrayList) Lists(com.google.common.collect.Lists) ExpressionUtility(io.github.linuxforhealth.hl7.util.ExpressionUtility) Map(java.util.Map) InputDataExtractor(io.github.linuxforhealth.api.InputDataExtractor) ResourceResult(io.github.linuxforhealth.core.resource.ResourceResult) Meta(org.hl7.fhir.r4.model.Meta) EvaluationResult(io.github.linuxforhealth.api.EvaluationResult) ObjectMapperUtil(io.github.linuxforhealth.core.ObjectMapperUtil) Logger(org.slf4j.Logger) ImmutableMap(com.google.common.collect.ImmutableMap) ResourceValue(io.github.linuxforhealth.api.ResourceValue) Predicate(java.util.function.Predicate) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) Structure(ca.uhn.hl7v2.model.Structure) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) UUID(java.util.UUID) LocalDateTime(org.joda.time.LocalDateTime) Collectors(java.util.stream.Collectors) SimpleResourceValue(io.github.linuxforhealth.core.resource.SimpleResourceValue) SegmentExtractorUtil(io.github.linuxforhealth.hl7.message.util.SegmentExtractorUtil) List(java.util.List) MDC(org.slf4j.MDC) EvaluationResultFactory(io.github.linuxforhealth.core.expression.EvaluationResultFactory) Entry(java.util.Map.Entry) Bundle(org.hl7.fhir.r4.model.Bundle) Preconditions(com.google.common.base.Preconditions) ResourceModel(io.github.linuxforhealth.api.ResourceModel) BundleType(org.hl7.fhir.r4.model.Bundle.BundleType) MessageEngine(io.github.linuxforhealth.api.MessageEngine) RequiredConstraintFailureException(io.github.linuxforhealth.core.exception.RequiredConstraintFailureException) FHIRContext(io.github.linuxforhealth.fhir.FHIRContext) FHIRResourceMapper(io.github.linuxforhealth.fhir.FHIRResourceMapper) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) SimpleResourceValue(io.github.linuxforhealth.core.resource.SimpleResourceValue) ResourceValue(io.github.linuxforhealth.api.ResourceValue) SimpleResourceValue(io.github.linuxforhealth.core.resource.SimpleResourceValue) ResourceModel(io.github.linuxforhealth.api.ResourceModel) FHIRResourceTemplate(io.github.linuxforhealth.api.FHIRResourceTemplate) Bundle(org.hl7.fhir.r4.model.Bundle) ResourceEvaluationResult(io.github.linuxforhealth.hl7.resource.ResourceEvaluationResult) SimpleEvaluationResult(io.github.linuxforhealth.core.expression.SimpleEvaluationResult) EvaluationResult(io.github.linuxforhealth.api.EvaluationResult) ResourceResult(io.github.linuxforhealth.core.resource.ResourceResult) ResourceEvaluationResult(io.github.linuxforhealth.hl7.resource.ResourceEvaluationResult) HashMap(java.util.HashMap) Map(java.util.Map) ImmutableMap(com.google.common.collect.ImmutableMap)

Example 4 with HL7FHIRResourceTemplate

use of io.github.linuxforhealth.hl7.message.HL7FHIRResourceTemplate in project hl7v2-fhir-converter by LinuxForHealth.

the class Hl7MessageTest method test_observation_condition.

@Test
void test_observation_condition() throws IOException {
    ResourceModel obsModel = ResourceReader.getInstance().generateResourceModel("resource/Observation");
    HL7FHIRResourceTemplateAttributes attributesObs = new HL7FHIRResourceTemplateAttributes.Builder().withResourceName("Observation").withResourceModel(obsModel).withSegment(".PROBLEM_OBSERVATION.OBX").withIsReferenced(true).withRepeats(true).withGroup("PROBLEM").build();
    HL7FHIRResourceTemplate obsTemplate = new HL7FHIRResourceTemplate(attributesObs);
    ResourceModel condModel = ResourceReader.getInstance().generateResourceModel("resource/Condition");
    HL7FHIRResourceTemplateAttributes attributesCond = new HL7FHIRResourceTemplateAttributes.Builder().withResourceName("Condition").withResourceModel(condModel).withSegment(".PRB").withIsReferenced(false).withRepeats(true).withGroup("PROBLEM").build();
    HL7FHIRResourceTemplate conditionTemplate = new HL7FHIRResourceTemplate(attributesCond);
    HL7MessageModel message = new HL7MessageModel("ADT", Lists.newArrayList(obsTemplate, conditionTemplate));
    String hl7message = "MSH|^~\\&|SendTest1|Sendfac1|Receiveapp1|Receivefac1|200603081747|security|PPR^PC1^PPR_PC1|1|P^I|2.6||||||ASCII||\r" + "PID|||555444222111^^^MPI&GenHosp&L^MR||james^anderson||19600614|M||C|99 Oakland #106^^qwerty^OH^44889||^^^^^626^5641111|^^^^^626^5647654|||||343132266|||N\r" + "PV1||I|6N^1234^A^GENHOS||||0100^ANDERSON^CARL|0148^ADDISON^JAMES||SUR|||||||0148^ANDERSON^CARL|S|1400|A|||||||||||||||||||SF|K||||199501102300\r" + "PRB|AD|200603150625|aortic stenosis|53692||2||200603150625\r" + "NTE|1|P|Problem Comments\r" + "VAR|varid1|200603150610\r" + // Two observation records
    "OBX|1|ST|0135-4^TotalProtein||6.4|gm/dl|5.9-8.4||||F|||||2740^Tsadok^Janetary~2913^Merrit^Darren^F|\r" + "OBX|2|ST|0135-4^TotalProtein||7.8|gm/dl|5.9-8.4||||F|||||2740^Tsadok^Janetary~2913^Merrit^Darren^F|\r";
    String json = message.convert(hl7message, engine);
    assertThat(json).isNotBlank();
    IBaseResource bundleResource = context.getParser().parseResource(json);
    assertThat(bundleResource).isNotNull();
    Bundle b = (Bundle) bundleResource;
    List<BundleEntryComponent> e = b.getEntry();
    List<Resource> observationResource = e.stream().filter(v -> ResourceType.Observation == v.getResource().getResourceType()).map(BundleEntryComponent::getResource).collect(Collectors.toList());
    assertThat(observationResource).hasSize(2);
    List<String> ids = observationResource.stream().map(m -> m.getId()).collect(Collectors.toList());
    List<Resource> conditionResource = e.stream().filter(v -> ResourceType.Condition == v.getResource().getResourceType()).map(BundleEntryComponent::getResource).collect(Collectors.toList());
    assertThat(conditionResource).hasSize(1);
    Condition cond = ResourceUtils.getResourceCondition(conditionResource.get(0), context);
    List<ConditionEvidenceComponent> evidences = cond.getEvidence();
    assertThat(evidences).hasSize(2);
    assertThat(evidences.get(0).hasDetail()).isTrue();
    assertThat(evidences.get(0).getDetail().get(0).getReference()).isIn(ids);
    assertThat(evidences.get(1).getDetail().get(0).getReference()).isIn(ids);
    assertThat(evidences.get(0).getDetail().get(0).getReference()).isNotEqualTo(evidences.get(1).getDetail().get(0).getReference());
}
Also used : Specimen(org.hl7.fhir.r4.model.Specimen) Logger(org.slf4j.Logger) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) LoggerFactory(org.slf4j.LoggerFactory) Resource(org.hl7.fhir.r4.model.Resource) IOException(java.io.IOException) Condition(org.hl7.fhir.r4.model.Condition) Reference(org.hl7.fhir.r4.model.Reference) Collectors(java.util.stream.Collectors) ResourceReader(io.github.linuxforhealth.hl7.resource.ResourceReader) Test(org.junit.jupiter.api.Test) Encounter(org.hl7.fhir.r4.model.Encounter) ResourceType(org.hl7.fhir.r4.model.ResourceType) List(java.util.List) Lists(com.google.common.collect.Lists) IBaseResource(org.hl7.fhir.instance.model.api.IBaseResource) BundleEntryComponent(org.hl7.fhir.r4.model.Bundle.BundleEntryComponent) ResourceUtils(io.github.linuxforhealth.hl7.segments.util.ResourceUtils) Bundle(org.hl7.fhir.r4.model.Bundle) ConditionEvidenceComponent(org.hl7.fhir.r4.model.Condition.ConditionEvidenceComponent) ResourceModel(io.github.linuxforhealth.api.ResourceModel) FHIRContext(io.github.linuxforhealth.fhir.FHIRContext) MessageHeader(org.hl7.fhir.r4.model.MessageHeader) Observation(org.hl7.fhir.r4.model.Observation) Condition(org.hl7.fhir.r4.model.Condition) ConditionEvidenceComponent(org.hl7.fhir.r4.model.Condition.ConditionEvidenceComponent) Bundle(org.hl7.fhir.r4.model.Bundle) Resource(org.hl7.fhir.r4.model.Resource) IBaseResource(org.hl7.fhir.instance.model.api.IBaseResource) BundleEntryComponent(org.hl7.fhir.r4.model.Bundle.BundleEntryComponent) ResourceModel(io.github.linuxforhealth.api.ResourceModel) IBaseResource(org.hl7.fhir.instance.model.api.IBaseResource) Test(org.junit.jupiter.api.Test)

Aggregations

ResourceModel (io.github.linuxforhealth.api.ResourceModel)3 List (java.util.List)3 Lists (com.google.common.collect.Lists)2 ResourceResult (io.github.linuxforhealth.core.resource.ResourceResult)2 FHIRContext (io.github.linuxforhealth.fhir.FHIRContext)2 SegmentGroup (io.github.linuxforhealth.hl7.message.util.SegmentGroup)2 IOException (java.io.IOException)2 ArrayList (java.util.ArrayList)2 Collectors (java.util.stream.Collectors)2 Bundle (org.hl7.fhir.r4.model.Bundle)2 Logger (org.slf4j.Logger)2 LoggerFactory (org.slf4j.LoggerFactory)2 Structure (ca.uhn.hl7v2.model.Structure)1 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)1 JsonNode (com.fasterxml.jackson.databind.JsonNode)1 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)1 Preconditions (com.google.common.base.Preconditions)1 ImmutableMap (com.google.common.collect.ImmutableMap)1 EvaluationResult (io.github.linuxforhealth.api.EvaluationResult)1 FHIRResourceTemplate (io.github.linuxforhealth.api.FHIRResourceTemplate)1