Search in sources :

Example 51 with Attachment

use of org.hl7.fhir.dstu2.model.Attachment in project nia-patient-switching-standard-adaptor by NHSDigital.

the class COPCMessageHandler method checkAndMergeFileParts.

public void checkAndMergeFileParts(InboundMessage inboundMessage, String conversationId) throws SAXException, AttachmentLogException, ValidationException, InlineAttachmentProcessingException {
    Document ebXmlDocument = xPathService.parseDocumentFromXml(inboundMessage.getEbXML());
    var inboundMessageId = xPathService.getNodeValue(ebXmlDocument, MESSAGE_ID_PATH);
    var currentAttachmentLog = patientAttachmentLogService.findAttachmentLog(inboundMessageId, conversationId);
    if (currentAttachmentLog == null) {
        throw new AttachmentLogException("Given COPC message is missing an attachment log");
    }
    // if a message has arrived early, it will not have a parent ID so we can cancel early.
    if (currentAttachmentLog.getParentMid() == null) {
        return;
    }
    var conversationAttachmentLogs = patientAttachmentLogService.findAttachmentLogs(conversationId);
    var attachmentLogFragments = conversationAttachmentLogs.stream().sorted(Comparator.comparingInt(PatientAttachmentLog::getOrderNum)).filter(log -> !(log.getParentMid() == null) && log.getParentMid().equals(currentAttachmentLog.getParentMid())).toList();
    var parentLogMessageId = attachmentLogFragments.size() == 1 ? currentAttachmentLog.getMid() : currentAttachmentLog.getParentMid();
    attachmentLogFragments = conversationAttachmentLogs.stream().sorted(Comparator.comparingInt(PatientAttachmentLog::getOrderNum)).filter(log -> !(log.getParentMid() == null) && log.getParentMid().equals(parentLogMessageId)).toList();
    var allFragmentsHaveUploaded = attachmentLogFragments.stream().allMatch(PatientAttachmentLog::getUploaded);
    if (allFragmentsHaveUploaded) {
        String payload = attachmentHandlerService.buildSingleFileStringFromPatientAttachmentLogs(attachmentLogFragments, conversationId);
        var parentLogFile = conversationAttachmentLogs.stream().filter(log -> log.getMid().equals(parentLogMessageId)).findAny().orElse(null);
        var mergedLargeAttachment = createNewLargeAttachmentInList(parentLogFile, payload);
        attachmentHandlerService.storeAttachments(mergedLargeAttachment, conversationId);
        var updatedLog = PatientAttachmentLog.builder().mid(parentLogFile.getMid()).uploaded(true).build();
        patientAttachmentLogService.updateAttachmentLog(updatedLog, conversationId);
        attachmentLogFragments.forEach((PatientAttachmentLog log) -> {
            attachmentHandlerService.removeAttachment(log.getFilename(), conversationId);
            patientAttachmentLogService.deleteAttachmentLog(log.getMid(), conversationId);
        });
    }
}
Also used : Arrays(java.util.Arrays) AttachmentNotFoundException(uk.nhs.adaptors.pss.translator.exception.AttachmentNotFoundException) RequiredArgsConstructor(lombok.RequiredArgsConstructor) Autowired(org.springframework.beans.factory.annotation.Autowired) NackAckPreparationService(uk.nhs.adaptors.pss.translator.service.NackAckPreparationService) XmlUnmarshallUtil.unmarshallString(uk.nhs.adaptors.pss.translator.util.XmlUnmarshallUtil.unmarshallString) PatientAttachmentLog(uk.nhs.adaptors.connector.model.PatientAttachmentLog) COPCIN000001UK01Message(org.hl7.v3.COPCIN000001UK01Message) ArrayList(java.util.ArrayList) BundleMappingException(uk.nhs.adaptors.pss.translator.exception.BundleMappingException) Document(org.w3c.dom.Document) ParseException(java.text.ParseException) PatientMigrationRequest(uk.nhs.adaptors.connector.model.PatientMigrationRequest) InboundMessageMergingService(uk.nhs.adaptors.pss.translator.service.InboundMessageMergingService) PatientAttachmentLogService(uk.nhs.adaptors.connector.service.PatientAttachmentLogService) EbxmlReference(uk.nhs.adaptors.pss.translator.model.EbxmlReference) AttachmentHandlerService(uk.nhs.adaptors.pss.translator.service.AttachmentHandlerService) XPathService(uk.nhs.adaptors.pss.translator.service.XPathService) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) AttachmentLogException(uk.nhs.adaptors.pss.translator.exception.AttachmentLogException) InboundMessage(uk.nhs.adaptors.pss.translator.mhs.model.InboundMessage) JAXBException(javax.xml.bind.JAXBException) List(java.util.List) Component(org.springframework.stereotype.Component) Slf4j(lombok.extern.slf4j.Slf4j) SAXException(org.xml.sax.SAXException) InlineAttachmentProcessingException(uk.nhs.adaptors.pss.translator.exception.InlineAttachmentProcessingException) EHR_EXTRACT_CANNOT_BE_PROCESSED(uk.nhs.adaptors.pss.translator.model.NACKReason.EHR_EXTRACT_CANNOT_BE_PROCESSED) ValidationException(javax.xml.bind.ValidationException) PatientMigrationRequestDao(uk.nhs.adaptors.connector.dao.PatientMigrationRequestDao) Comparator(java.util.Comparator) XmlParseUtilService(uk.nhs.adaptors.pss.translator.util.XmlParseUtilService) PatientAttachmentLog(uk.nhs.adaptors.connector.model.PatientAttachmentLog) XmlUnmarshallUtil.unmarshallString(uk.nhs.adaptors.pss.translator.util.XmlUnmarshallUtil.unmarshallString) Document(org.w3c.dom.Document) AttachmentLogException(uk.nhs.adaptors.pss.translator.exception.AttachmentLogException)

Example 52 with Attachment

use of org.hl7.fhir.dstu2.model.Attachment in project nia-patient-switching-standard-adaptor by NHSDigital.

the class EhrExtractMessageHandler method handleMessage.

public void handleMessage(InboundMessage inboundMessage, String conversationId) throws JAXBException, JsonProcessingException, InlineAttachmentProcessingException, BundleMappingException, AttachmentNotFoundException, ParseException, SAXException {
    RCMRIN030000UK06Message payload = unmarshallString(inboundMessage.getPayload(), RCMRIN030000UK06Message.class);
    PatientMigrationRequest migrationRequest = migrationRequestDao.getMigrationRequest(conversationId);
    MigrationStatusLog migrationStatusLog = migrationStatusLogService.getLatestMigrationStatusLog(conversationId);
    migrationStatusLogService.addMigrationStatusLog(EHR_EXTRACT_RECEIVED, conversationId);
    try {
        Document ebXmlDocument = getEbXmlDocument(inboundMessage);
        String messageId = xPathService.getNodeValue(ebXmlDocument, MESSAGE_ID_PATH);
        boolean hasExternalAttachment = !(inboundMessage.getExternalAttachments() == null || inboundMessage.getExternalAttachments().isEmpty());
        // Manage attachments against the EHR message
        var attachments = inboundMessage.getAttachments();
        if (attachments != null) {
            attachmentHandlerService.storeAttachments(attachments, conversationId);
            for (var i = 0; i < attachments.size(); i++) {
                var attachment = attachments.get(i);
                PatientAttachmentLog newAttachmentLog = buildPatientAttachmentLogFromAttachment(messageId, migrationRequest, attachment);
                patientAttachmentLogService.addAttachmentLog(newAttachmentLog);
            }
        }
        if (!hasExternalAttachment) {
            var fileUpdatedPayload = attachmentReferenceUpdaterService.updateReferenceToAttachment(inboundMessage.getAttachments(), conversationId, inboundMessage.getPayload());
            inboundMessage.setPayload(fileUpdatedPayload);
            payload = unmarshallString(inboundMessage.getPayload(), RCMRIN030000UK06Message.class);
            var bundle = bundleMapperService.mapToBundle(payload, migrationRequest.getLosingPracticeOdsCode());
            migrationStatusLogService.updatePatientMigrationRequestAndAddMigrationStatusLog(conversationId, fhirParser.encodeToJson(bundle), objectMapper.writeValueAsString(inboundMessage), EHR_EXTRACT_TRANSLATED);
            nackAckPreparationService.sendAckMessage(payload, conversationId);
        }
        // sending continue message
        if (hasExternalAttachment) {
            String patientNhsNumber = XmlParseUtilService.parseNhsNumber(payload);
            for (InboundMessage.ExternalAttachment externalAttachment : inboundMessage.getExternalAttachments()) {
                PatientAttachmentLog patientAttachmentLog;
                // save COPC_UK01 messages
                patientAttachmentLog = buildPatientAttachmentLogFromExternalAttachment(migrationRequest, externalAttachment);
                patientAttachmentLogService.addAttachmentLog(patientAttachmentLog);
            }
            migrationStatusLogService.updatePatientMigrationRequestAndAddMigrationStatusLog(conversationId, null, objectMapper.writeValueAsString(inboundMessage), EHR_EXTRACT_TRANSLATED);
            sendContinueRequest(payload, conversationId, patientNhsNumber, migrationRequest.getWinningPracticeOdsCode(), migrationStatusLog.getDate().toInstant());
        }
    } catch (BundleMappingException | DataFormatException | JsonProcessingException | InlineAttachmentProcessingException | AttachmentNotFoundException | SAXException | StorageException ex) {
        nackAckPreparationService.sendNackMessage(EHR_EXTRACT_CANNOT_BE_PROCESSED, payload, conversationId);
        throw ex;
    } catch (ParseException ex) {
        throw ex;
    }
}
Also used : AttachmentNotFoundException(uk.nhs.adaptors.pss.translator.exception.AttachmentNotFoundException) InboundMessage(uk.nhs.adaptors.pss.translator.mhs.model.InboundMessage) XmlUnmarshallUtil.unmarshallString(uk.nhs.adaptors.pss.translator.util.XmlUnmarshallUtil.unmarshallString) Document(org.w3c.dom.Document) SAXException(org.xml.sax.SAXException) PatientMigrationRequest(uk.nhs.adaptors.connector.model.PatientMigrationRequest) DataFormatException(ca.uhn.fhir.parser.DataFormatException) PatientAttachmentLog(uk.nhs.adaptors.connector.model.PatientAttachmentLog) MigrationStatusLog(uk.nhs.adaptors.connector.model.MigrationStatusLog) BundleMappingException(uk.nhs.adaptors.pss.translator.exception.BundleMappingException) ParseException(java.text.ParseException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) StorageException(uk.nhs.adaptors.pss.translator.storage.StorageException) RCMRIN030000UK06Message(org.hl7.v3.RCMRIN030000UK06Message) InlineAttachmentProcessingException(uk.nhs.adaptors.pss.translator.exception.InlineAttachmentProcessingException)

Example 53 with Attachment

use of org.hl7.fhir.dstu2.model.Attachment in project MobileAccessGateway by i4mi.

the class Iti67ResponseConverter method translateToFhir.

@Override
public List<DocumentReference> translateToFhir(QueryResponse input, Map<String, Object> parameters) {
    ArrayList<DocumentReference> list = new ArrayList<DocumentReference>();
    if (input != null && Status.SUCCESS.equals(input.getStatus())) {
        // process relationship association
        Map<String, List<DocumentReferenceRelatesToComponent>> relatesToMapping = new HashMap<String, List<DocumentReferenceRelatesToComponent>>();
        for (Association association : input.getAssociations()) {
            // Relationship type -> relatesTo.code code [1..1]
            // relationship reference -> relatesTo.target Reference(DocumentReference)
            String source = association.getSourceUuid();
            String target = association.getTargetUuid();
            AssociationType type = association.getAssociationType();
            DocumentReferenceRelatesToComponent relatesTo = new DocumentReferenceRelatesToComponent();
            if (type != null)
                switch(type) {
                    case APPEND:
                        relatesTo.setCode(DocumentRelationshipType.APPENDS);
                        break;
                    case REPLACE:
                        relatesTo.setCode(DocumentRelationshipType.REPLACES);
                        break;
                    case TRANSFORM:
                        relatesTo.setCode(DocumentRelationshipType.TRANSFORMS);
                        break;
                    case SIGNS:
                        relatesTo.setCode(DocumentRelationshipType.SIGNS);
                        break;
                }
            relatesTo.setTarget(new Reference().setReference("urn:oid:" + target));
            if (!relatesToMapping.containsKey(source))
                relatesToMapping.put(source, new ArrayList<DocumentReferenceRelatesToComponent>());
            relatesToMapping.get(source).add(relatesTo);
        }
        if (input.getDocumentEntries() != null) {
            for (DocumentEntry documentEntry : input.getDocumentEntries()) {
                DocumentReference documentReference = new DocumentReference();
                // FIXME do we need to cache this id in
                documentReference.setId(noUuidPrefix(documentEntry.getEntryUuid()));
                // relation to the DocumentManifest itself
                // for
                list.add(documentReference);
                // limitedMetadata -> meta.profile canonical [0..*]
                if (documentEntry.isLimitedMetadata()) {
                    documentReference.getMeta().addProfile("http://ihe.net/fhir/StructureDefinition/IHE_MHD_Query_Comprehensive_DocumentReference");
                } else {
                    documentReference.getMeta().addProfile("http://ihe.net/fhir/StructureDefinition/IHE_MHD_Comprehensive_DocumentManifest");
                }
                // uniqueId -> masterIdentifier Identifier [0..1] [1..1]
                if (documentEntry.getUniqueId() != null) {
                    documentReference.setMasterIdentifier((new Identifier().setValue("urn:oid:" + documentEntry.getUniqueId())));
                }
                // DocumentReference.identifier. use shall be ‘official’
                if (documentEntry.getEntryUuid() != null) {
                    documentReference.addIdentifier((new Identifier().setSystem("urn:ietf:rfc:3986").setValue(asUuid(documentEntry.getEntryUuid()))).setUse(IdentifierUse.OFFICIAL));
                }
                // Other status values are allowed but are not defined in this mapping to XDS.
                if (AvailabilityStatus.APPROVED.equals(documentEntry.getAvailabilityStatus())) {
                    documentReference.setStatus(DocumentReferenceStatus.CURRENT);
                }
                if (AvailabilityStatus.DEPRECATED.equals(documentEntry.getAvailabilityStatus())) {
                    documentReference.setStatus(DocumentReferenceStatus.SUPERSEDED);
                }
                // contentTypeCode -> type CodeableConcept [0..1]
                if (documentEntry.getTypeCode() != null) {
                    documentReference.setType(transform(documentEntry.getTypeCode()));
                }
                // classCode -> category CodeableConcept [0..*]
                if (documentEntry.getClassCode() != null) {
                    documentReference.addCategory((transform(documentEntry.getClassCode())));
                }
                // representing the XDS Affinity Domain Patient.
                if (documentEntry.getPatientId() != null) {
                    Identifiable patient = documentEntry.getPatientId();
                    documentReference.setSubject(transformPatient(patient));
                }
                // creationTime -> date instant [0..1]
                if (documentEntry.getCreationTime() != null) {
                    documentReference.setDate(Date.from(documentEntry.getCreationTime().getDateTime().toInstant()));
                }
                // PractitionerRole| Organization| Device| Patient| RelatedPerson) [0..*]
                if (documentEntry.getAuthors() != null) {
                    for (Author author : documentEntry.getAuthors()) {
                        documentReference.addAuthor(transformAuthor(author));
                    }
                }
                // legalAuthenticator -> authenticator Note 1
                // Reference(Practitioner|Practition erRole|Organization [0..1]
                Person person = documentEntry.getLegalAuthenticator();
                if (person != null) {
                    Practitioner practitioner = transformPractitioner(person);
                    documentReference.setAuthenticator((Reference) new Reference().setResource(practitioner));
                }
                // Relationship Association -> relatesTo [0..*]
                // [1..1]
                documentReference.setRelatesTo(relatesToMapping.get(documentEntry.getEntryUuid()));
                // title -> description string [0..1]
                if (documentEntry.getTitle() != null) {
                    documentReference.setDescription(documentEntry.getTitle().getValue());
                }
                // DocumentReference itself.
                if (documentEntry.getConfidentialityCodes() != null) {
                    documentReference.addSecurityLabel(transform(documentEntry.getConfidentialityCodes()));
                }
                DocumentReferenceContentComponent content = documentReference.addContent();
                Attachment attachment = new Attachment();
                content.setAttachment(attachment);
                // mimeType -> content.attachment.contentType [1..1] code [0..1]
                if (documentEntry.getMimeType() != null) {
                    attachment.setContentType(documentEntry.getMimeType());
                }
                // languageCode -> content.attachment.language code [0..1]
                if (documentEntry.getLanguageCode() != null) {
                    attachment.setLanguage(documentEntry.getLanguageCode());
                }
                // retrievable location of the document -> content.attachment.url uri
                // [0..1] [1..1
                // has to defined, for the PoC we define
                // $host:port/camel/$repositoryid/$uniqueid
                attachment.setUrl(config.getUriMagXdsRetrieve() + "?uniqueId=" + documentEntry.getUniqueId() + "&repositoryUniqueId=" + documentEntry.getRepositoryUniqueId());
                // size -> content.attachment.size integer [0..1] The size is calculated
                if (documentEntry.getSize() != null) {
                    attachment.setSize(documentEntry.getSize().intValue());
                }
                // on the data prior to base64 encoding, if the data is base64 encoded.
                if (documentEntry.getHash() != null) {
                    attachment.setHash(Hex.fromHex(documentEntry.getHash()));
                }
                // comments -> content.attachment.title string [0..1]
                if (documentEntry.getComments() != null) {
                    attachment.setTitle(documentEntry.getComments().getValue());
                }
                // TcreationTime -> content.attachment.creation dateTime [0..1]
                if (documentEntry.getCreationTime() != null) {
                    attachment.setCreation(Date.from(documentEntry.getCreationTime().getDateTime().toInstant()));
                }
                // formatCode -> content.format Coding [0..1]
                if (documentEntry.getFormatCode() != null) {
                    content.setFormat(transform(documentEntry.getFormatCode()).getCodingFirstRep());
                }
                DocumentReferenceContextComponent context = new DocumentReferenceContextComponent();
                documentReference.setContext(context);
                // referenceIdList -> context.encounter Reference(Encounter) [0..*] When
                // referenceIdList contains an encounter, and a FHIR Encounter is available, it
                // may be referenced.
                // Map to context.related
                List<ReferenceId> refIds = documentEntry.getReferenceIdList();
                if (refIds != null) {
                    for (ReferenceId refId : refIds) {
                        context.getRelated().add(transform(refId));
                    }
                }
                // eventCodeList -> context.event CodeableConcept [0..*]
                if (documentEntry.getEventCodeList() != null) {
                    documentReference.getContext().setEvent(transformMultiple(documentEntry.getEventCodeList()));
                }
                // serviceStartTime serviceStopTime -> context.period Period [0..1]
                if (documentEntry.getServiceStartTime() != null || documentEntry.getServiceStopTime() != null) {
                    Period period = new Period();
                    period.setStartElement(transform(documentEntry.getServiceStartTime()));
                    period.setEndElement(transform(documentEntry.getServiceStopTime()));
                    documentReference.getContext().setPeriod(period);
                }
                // [0..1]
                if (documentEntry.getHealthcareFacilityTypeCode() != null) {
                    context.setFacilityType(transform(documentEntry.getHealthcareFacilityTypeCode()));
                }
                // practiceSettingCode -> context.practiceSetting CodeableConcept [0..1]
                if (documentEntry.getPracticeSettingCode() != null) {
                    context.setPracticeSetting(transform(documentEntry.getPracticeSettingCode()));
                }
                // sourcePatientId and sourcePatientInfo -> context.sourcePatientInfo
                // Reference(Patient) [0..1] Contained Patient Resource with
                // Patient.identifier.use element set to ‘usual’.
                Identifiable sourcePatientId = documentEntry.getSourcePatientId();
                PatientInfo sourcePatientInfo = documentEntry.getSourcePatientInfo();
                Patient sourcePatient = new Patient();
                if (sourcePatientId != null) {
                    sourcePatient.addIdentifier((new Identifier().setSystem("urn:oid:" + sourcePatientId.getAssigningAuthority().getUniversalId()).setValue(sourcePatientId.getId())).setUse(IdentifierUse.OFFICIAL));
                }
                if (sourcePatientInfo != null) {
                    sourcePatient.setBirthDateElement(transformToDate(sourcePatientInfo.getDateOfBirth()));
                    String gender = sourcePatientInfo.getGender();
                    if (gender != null) {
                        switch(gender) {
                            case "F":
                                sourcePatient.setGender(Enumerations.AdministrativeGender.FEMALE);
                                break;
                            case "M":
                                sourcePatient.setGender(Enumerations.AdministrativeGender.MALE);
                                break;
                            case "U":
                                sourcePatient.setGender(Enumerations.AdministrativeGender.UNKNOWN);
                                break;
                            case "A":
                                sourcePatient.setGender(Enumerations.AdministrativeGender.OTHER);
                                break;
                        }
                    }
                    ListIterator<Name> names = sourcePatientInfo.getNames();
                    while (names.hasNext()) {
                        Name name = names.next();
                        sourcePatient.addName(transform(name));
                    }
                    ListIterator<Address> addresses = sourcePatientInfo.getAddresses();
                    while (addresses.hasNext()) {
                        Address address = addresses.next();
                        if (address != null)
                            sourcePatient.addAddress(transform(address));
                    }
                }
                if (sourcePatientId != null || sourcePatientInfo != null) {
                    context.getSourcePatientInfo().setResource(sourcePatient);
                }
            }
        }
    } else {
        processError(input);
    }
    return list;
}
Also used : DocumentReferenceRelatesToComponent(org.hl7.fhir.r4.model.DocumentReference.DocumentReferenceRelatesToComponent) DocumentReferenceContextComponent(org.hl7.fhir.r4.model.DocumentReference.DocumentReferenceContextComponent) Address(org.openehealth.ipf.commons.ihe.xds.core.metadata.Address) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) Attachment(org.hl7.fhir.r4.model.Attachment) PatientInfo(org.openehealth.ipf.commons.ihe.xds.core.metadata.PatientInfo) Name(org.openehealth.ipf.commons.ihe.xds.core.metadata.Name) Association(org.openehealth.ipf.commons.ihe.xds.core.metadata.Association) Identifier(org.hl7.fhir.r4.model.Identifier) ReferenceId(org.openehealth.ipf.commons.ihe.xds.core.metadata.ReferenceId) DocumentEntry(org.openehealth.ipf.commons.ihe.xds.core.metadata.DocumentEntry) ArrayList(java.util.ArrayList) List(java.util.List) DocumentReference(org.hl7.fhir.r4.model.DocumentReference) Reference(org.hl7.fhir.r4.model.Reference) DocumentReference(org.hl7.fhir.r4.model.DocumentReference) Period(org.hl7.fhir.r4.model.Period) Patient(org.hl7.fhir.r4.model.Patient) Identifiable(org.openehealth.ipf.commons.ihe.xds.core.metadata.Identifiable) Practitioner(org.hl7.fhir.r4.model.Practitioner) AssociationType(org.openehealth.ipf.commons.ihe.xds.core.metadata.AssociationType) Author(org.openehealth.ipf.commons.ihe.xds.core.metadata.Author) Person(org.openehealth.ipf.commons.ihe.xds.core.metadata.Person) DocumentReferenceContentComponent(org.hl7.fhir.r4.model.DocumentReference.DocumentReferenceContentComponent)

Example 54 with Attachment

use of org.hl7.fhir.dstu2.model.Attachment in project synthea by synthetichealth.

the class FhirR4 method convertToFHIR.

/**
 * Convert the given Person into a FHIR Bundle of the Patient and the
 * associated entries from their health record.
 *
 * @param person   Person to generate the FHIR JSON for
 * @param stopTime Time the simulation ended
 * @return FHIR Bundle containing the Person's health record
 */
public static Bundle convertToFHIR(Person person, long stopTime) {
    Bundle bundle = new Bundle();
    if (TRANSACTION_BUNDLE) {
        bundle.setType(BundleType.TRANSACTION);
    } else {
        bundle.setType(BundleType.COLLECTION);
    }
    BundleEntryComponent personEntry = basicInfo(person, bundle, stopTime);
    for (Encounter encounter : person.record.encounters) {
        BundleEntryComponent encounterEntry = encounter(person, personEntry, bundle, encounter);
        for (HealthRecord.Entry condition : encounter.conditions) {
            condition(person, personEntry, bundle, encounterEntry, condition);
        }
        for (HealthRecord.Allergy allergy : encounter.allergies) {
            allergy(person, personEntry, bundle, encounterEntry, allergy);
        }
        for (Observation observation : encounter.observations) {
            // Observation resources in v4 don't support Attachments
            if (observation.value instanceof Attachment) {
                media(person, personEntry, bundle, encounterEntry, observation);
            } else {
                observation(person, personEntry, bundle, encounterEntry, observation);
            }
        }
        for (Procedure procedure : encounter.procedures) {
            procedure(person, personEntry, bundle, encounterEntry, procedure);
        }
        for (HealthRecord.Device device : encounter.devices) {
            device(person, personEntry, bundle, device);
        }
        for (HealthRecord.Supply supply : encounter.supplies) {
            supplyDelivery(person, personEntry, bundle, supply, encounter);
        }
        for (Medication medication : encounter.medications) {
            medicationRequest(person, personEntry, bundle, encounterEntry, medication);
        }
        for (HealthRecord.Entry immunization : encounter.immunizations) {
            immunization(person, personEntry, bundle, encounterEntry, immunization);
        }
        for (Report report : encounter.reports) {
            report(person, personEntry, bundle, encounterEntry, report);
        }
        for (CarePlan careplan : encounter.careplans) {
            BundleEntryComponent careTeamEntry = careTeam(person, personEntry, bundle, encounterEntry, careplan);
            carePlan(person, personEntry, bundle, encounterEntry, encounter.provider, careTeamEntry, careplan);
        }
        for (ImagingStudy imagingStudy : encounter.imagingStudies) {
            imagingStudy(person, personEntry, bundle, encounterEntry, imagingStudy);
        }
        if (USE_US_CORE_IG) {
            String clinicalNoteText = ClinicalNoteExporter.export(person, encounter);
            boolean lastNote = (encounter == person.record.encounters.get(person.record.encounters.size() - 1));
            clinicalNote(person, personEntry, bundle, encounterEntry, clinicalNoteText, lastNote);
        }
        // one claim per encounter
        BundleEntryComponent encounterClaim = encounterClaim(person, personEntry, bundle, encounterEntry, encounter.claim);
        explanationOfBenefit(personEntry, bundle, encounterEntry, person, encounterClaim, encounter);
    }
    if (USE_US_CORE_IG) {
        // Add Provenance to the Bundle
        provenance(bundle, person, stopTime);
    }
    return bundle;
}
Also used : DiagnosticReport(org.hl7.fhir.r4.model.DiagnosticReport) Report(org.mitre.synthea.world.concepts.HealthRecord.Report) Bundle(org.hl7.fhir.r4.model.Bundle) ImagingStudy(org.mitre.synthea.world.concepts.HealthRecord.ImagingStudy) Attachment(org.mitre.synthea.engine.Components.Attachment) HealthRecord(org.mitre.synthea.world.concepts.HealthRecord) CarePlan(org.mitre.synthea.world.concepts.HealthRecord.CarePlan) BundleEntryComponent(org.hl7.fhir.r4.model.Bundle.BundleEntryComponent) Observation(org.mitre.synthea.world.concepts.HealthRecord.Observation) Medication(org.mitre.synthea.world.concepts.HealthRecord.Medication) Encounter(org.mitre.synthea.world.concepts.HealthRecord.Encounter) Procedure(org.mitre.synthea.world.concepts.HealthRecord.Procedure)

Example 55 with Attachment

use of org.hl7.fhir.dstu2.model.Attachment in project synthea by synthetichealth.

the class FhirR4 method media.

/**
 * Map the given Observation with attachment element to a FHIR Media resource, and add it to the
 * given Bundle.
 *
 * @param rand           Source of randomness to use when generating ids etc
 * @param personEntry    The Entry for the Person
 * @param bundle         Bundle to add the Media to
 * @param encounterEntry Current Encounter entry
 * @param obs   The Observation to map to FHIR and add to the bundle
 * @return The added Entry
 */
private static BundleEntryComponent media(RandomNumberGenerator rand, BundleEntryComponent personEntry, Bundle bundle, BundleEntryComponent encounterEntry, Observation obs) {
    org.hl7.fhir.r4.model.Media mediaResource = new org.hl7.fhir.r4.model.Media();
    // Hard code as Image since we don't anticipate using video or audio any time soon
    Code mediaType = new Code("http://terminology.hl7.org/CodeSystem/media-type", "image", "Image");
    if (obs.codes != null && obs.codes.size() > 0) {
        List<CodeableConcept> reasonList = obs.codes.stream().map(code -> mapCodeToCodeableConcept(code, SNOMED_URI)).collect(Collectors.toList());
        mediaResource.setReasonCode(reasonList);
    }
    mediaResource.setType(mapCodeToCodeableConcept(mediaType, MEDIA_TYPE_URI));
    mediaResource.setStatus(MediaStatus.COMPLETED);
    mediaResource.setSubject(new Reference(personEntry.getFullUrl()));
    mediaResource.setEncounter(new Reference(encounterEntry.getFullUrl()));
    Attachment content = (Attachment) obs.value;
    org.hl7.fhir.r4.model.Attachment contentResource = new org.hl7.fhir.r4.model.Attachment();
    contentResource.setContentType(content.contentType);
    contentResource.setLanguage(content.language);
    if (content.data != null) {
        contentResource.setDataElement(new org.hl7.fhir.r4.model.Base64BinaryType(content.data));
    } else {
        contentResource.setSize(content.size);
    }
    contentResource.setUrl(content.url);
    contentResource.setTitle(content.title);
    if (content.hash != null) {
        contentResource.setHashElement(new org.hl7.fhir.r4.model.Base64BinaryType(content.hash));
    }
    mediaResource.setWidth(content.width);
    mediaResource.setHeight(content.height);
    mediaResource.setContent(contentResource);
    return newEntry(rand, bundle, mediaResource);
}
Also used : Location(org.mitre.synthea.world.geography.Location) SimpleQuantity(org.hl7.fhir.r4.model.SimpleQuantity) SupplyDeliveryStatus(org.hl7.fhir.r4.model.SupplyDelivery.SupplyDeliveryStatus) Identifier(org.hl7.fhir.r4.model.Identifier) XhtmlNode(org.hl7.fhir.utilities.xhtml.XhtmlNode) HashBasedTable(com.google.common.collect.HashBasedTable) Condition(org.hl7.fhir.r4.model.Condition) CarePlanActivityComponent(org.hl7.fhir.r4.model.CarePlan.CarePlanActivityComponent) Reference(org.hl7.fhir.r4.model.Reference) SupplyDeliverySuppliedItemComponent(org.hl7.fhir.r4.model.SupplyDelivery.SupplyDeliverySuppliedItemComponent) HTTPVerb(org.hl7.fhir.r4.model.Bundle.HTTPVerb) Medication(org.mitre.synthea.world.concepts.HealthRecord.Medication) FhirContext(ca.uhn.fhir.context.FhirContext) Device(org.hl7.fhir.r4.model.Device) Person(org.mitre.synthea.world.agents.Person) ImmunizationStatus(org.hl7.fhir.r4.model.Immunization.ImmunizationStatus) Map(java.util.Map) Encounter(org.mitre.synthea.world.concepts.HealthRecord.Encounter) Coverage(org.hl7.fhir.r4.model.Coverage) IntegerType(org.hl7.fhir.r4.model.IntegerType) Meta(org.hl7.fhir.r4.model.Meta) Practitioner(org.hl7.fhir.r4.model.Practitioner) RandomNumberGenerator(org.mitre.synthea.helpers.RandomNumberGenerator) ProcedureStatus(org.hl7.fhir.r4.model.Procedure.ProcedureStatus) DocumentReference(org.hl7.fhir.r4.model.DocumentReference) CarePlanActivityStatus(org.hl7.fhir.r4.model.CarePlan.CarePlanActivityStatus) Goal(org.hl7.fhir.r4.model.Goal) EncounterHospitalizationComponent(org.hl7.fhir.r4.model.Encounter.EncounterHospitalizationComponent) Period(org.hl7.fhir.r4.model.Period) HealthRecord(org.mitre.synthea.world.concepts.HealthRecord) Provenance(org.hl7.fhir.r4.model.Provenance) ContactPoint(org.hl7.fhir.r4.model.ContactPoint) PractitionerRole(org.hl7.fhir.r4.model.PractitionerRole) Utilities(org.mitre.synthea.helpers.Utilities) BundleEntryRequestComponent(org.hl7.fhir.r4.model.Bundle.BundleEntryRequestComponent) BooleanType(org.hl7.fhir.r4.model.BooleanType) ObservationComponentComponent(org.hl7.fhir.r4.model.Observation.ObservationComponentComponent) Coding(org.hl7.fhir.r4.model.Coding) EncounterStatus(org.hl7.fhir.r4.model.Encounter.EncounterStatus) ImagingStudySeriesInstanceComponent(org.hl7.fhir.r4.model.ImagingStudy.ImagingStudySeriesInstanceComponent) BundleType(org.hl7.fhir.r4.model.Bundle.BundleType) EncounterType(org.mitre.synthea.world.concepts.HealthRecord.EncounterType) DeviceNameType(org.hl7.fhir.r4.model.Device.DeviceNameType) DateTimeType(org.hl7.fhir.r4.model.DateTimeType) AllergyIntoleranceType(org.hl7.fhir.r4.model.AllergyIntolerance.AllergyIntoleranceType) DocumentReferenceContextComponent(org.hl7.fhir.r4.model.DocumentReference.DocumentReferenceContextComponent) Use(org.hl7.fhir.r4.model.ExplanationOfBenefit.Use) DiagnosticReport(org.hl7.fhir.r4.model.DiagnosticReport) DosageDoseAndRateComponent(org.hl7.fhir.r4.model.Dosage.DosageDoseAndRateComponent) ProvenanceAgentComponent(org.hl7.fhir.r4.model.Provenance.ProvenanceAgentComponent) Money(org.hl7.fhir.r4.model.Money) ArrayList(java.util.ArrayList) LinkedHashMap(java.util.LinkedHashMap) Calendar(java.util.Calendar) ContactPointUse(org.hl7.fhir.r4.model.ContactPoint.ContactPointUse) LocationPhysicalType(org.hl7.fhir.r4.model.codesystems.LocationPhysicalType) DiagnosisComponent(org.hl7.fhir.r4.model.Claim.DiagnosisComponent) Quantity(org.hl7.fhir.r4.model.Quantity) DecimalType(org.hl7.fhir.r4.model.DecimalType) Procedure(org.mitre.synthea.world.concepts.HealthRecord.Procedure) ImagingStudySeriesComponent(org.hl7.fhir.r4.model.ImagingStudy.ImagingStudySeriesComponent) ImagingStudy(org.mitre.synthea.world.concepts.HealthRecord.ImagingStudy) IOException(java.io.IOException) NarrativeStatus(org.hl7.fhir.r4.model.Narrative.NarrativeStatus) FHIRDeviceStatus(org.hl7.fhir.r4.model.Device.FHIRDeviceStatus) Claim(org.mitre.synthea.world.concepts.Claim) ExplanationOfBenefit(org.hl7.fhir.r4.model.ExplanationOfBenefit) Bundle(org.hl7.fhir.r4.model.Bundle) CodeType(org.hl7.fhir.r4.model.CodeType) CarePlanIntent(org.hl7.fhir.r4.model.CarePlan.CarePlanIntent) DocumentReferenceStatus(org.hl7.fhir.r4.model.Enumerations.DocumentReferenceStatus) LocationStatus(org.hl7.fhir.r4.model.Location.LocationStatus) TotalComponent(org.hl7.fhir.r4.model.ExplanationOfBenefit.TotalComponent) ContactComponent(org.hl7.fhir.r4.model.Patient.ContactComponent) JsonObject(com.google.gson.JsonObject) Attachment(org.mitre.synthea.engine.Components.Attachment) NodeType(org.hl7.fhir.utilities.xhtml.NodeType) Point2D(java.awt.geom.Point2D) Date(java.util.Date) CoverageStatus(org.hl7.fhir.r4.model.Coverage.CoverageStatus) Costs(org.mitre.synthea.world.concepts.Costs) AllergyIntolerance(org.hl7.fhir.r4.model.AllergyIntolerance) LocationPositionComponent(org.hl7.fhir.r4.model.Location.LocationPositionComponent) ContactPointSystem(org.hl7.fhir.r4.model.ContactPoint.ContactPointSystem) HumanName(org.hl7.fhir.r4.model.HumanName) Gson(com.google.gson.Gson) StringType(org.hl7.fhir.r4.model.StringType) BundleEntryComponent(org.hl7.fhir.r4.model.Bundle.BundleEntryComponent) Components(org.mitre.synthea.engine.Components) Patient(org.hl7.fhir.r4.model.Patient) Timing(org.hl7.fhir.r4.model.Timing) GoalLifecycleStatus(org.hl7.fhir.r4.model.Goal.GoalLifecycleStatus) DateType(org.hl7.fhir.r4.model.DateType) CarePlanStatus(org.hl7.fhir.r4.model.CarePlan.CarePlanStatus) SupplyDelivery(org.hl7.fhir.r4.model.SupplyDelivery) Report(org.mitre.synthea.world.concepts.HealthRecord.Report) CareTeamStatus(org.hl7.fhir.r4.model.CareTeam.CareTeamStatus) MedicationAdministration(org.hl7.fhir.r4.model.MedicationAdministration) Resource(org.hl7.fhir.r4.model.Resource) MedicationRequestStatus(org.hl7.fhir.r4.model.MedicationRequest.MedicationRequestStatus) Collectors(java.util.stream.Collectors) SupportingInformationComponent(org.hl7.fhir.r4.model.Claim.SupportingInformationComponent) CarePlanActivityDetailComponent(org.hl7.fhir.r4.model.CarePlan.CarePlanActivityDetailComponent) InsuranceComponent(org.hl7.fhir.r4.model.Claim.InsuranceComponent) ProcedureComponent(org.hl7.fhir.r4.model.Claim.ProcedureComponent) Narrative(org.hl7.fhir.r4.model.Narrative) List(java.util.List) Immunization(org.hl7.fhir.r4.model.Immunization) Extension(org.hl7.fhir.r4.model.Extension) PositiveIntType(org.hl7.fhir.r4.model.PositiveIntType) ClaimStatus(org.hl7.fhir.r4.model.Claim.ClaimStatus) MedicationRequest(org.hl7.fhir.r4.model.MedicationRequest) SimpleCSV(org.mitre.synthea.helpers.SimpleCSV) Property(org.hl7.fhir.r4.model.Property) TimingRepeatComponent(org.hl7.fhir.r4.model.Timing.TimingRepeatComponent) Type(org.hl7.fhir.r4.model.Type) Clinician(org.mitre.synthea.world.agents.Clinician) AllergyIntoleranceCategory(org.hl7.fhir.r4.model.AllergyIntolerance.AllergyIntoleranceCategory) CodeableConcept(org.hl7.fhir.r4.model.CodeableConcept) HashMap(java.util.HashMap) AllergyIntoleranceCriticality(org.hl7.fhir.r4.model.AllergyIntolerance.AllergyIntoleranceCriticality) Dosage(org.hl7.fhir.r4.model.Dosage) CareTeam(org.hl7.fhir.r4.model.CareTeam) JsonElement(com.google.gson.JsonElement) Address(org.hl7.fhir.r4.model.Address) Code(org.mitre.synthea.world.concepts.HealthRecord.Code) CarePlan(org.mitre.synthea.world.concepts.HealthRecord.CarePlan) ItemComponent(org.hl7.fhir.r4.model.Claim.ItemComponent) PatientCommunicationComponent(org.hl7.fhir.r4.model.Patient.PatientCommunicationComponent) ImagingStudyStatus(org.hl7.fhir.r4.model.ImagingStudy.ImagingStudyStatus) ServiceRequest(org.hl7.fhir.r4.model.ServiceRequest) UnitsOfTime(org.hl7.fhir.r4.model.Timing.UnitsOfTime) ObservationStatus(org.hl7.fhir.r4.model.Observation.ObservationStatus) Config(org.mitre.synthea.helpers.Config) DoseRateType(org.hl7.fhir.r4.model.codesystems.DoseRateType) MedicationRequestIntent(org.hl7.fhir.r4.model.MedicationRequest.MedicationRequestIntent) MedicationStatus(org.hl7.fhir.r4.model.Medication.MedicationStatus) MedicationAdministrationDosageComponent(org.hl7.fhir.r4.model.MedicationAdministration.MedicationAdministrationDosageComponent) Payer(org.mitre.synthea.world.agents.Payer) MediaStatus(org.hl7.fhir.r4.model.Media.MediaStatus) Provider(org.mitre.synthea.world.agents.Provider) CareTeamParticipantComponent(org.hl7.fhir.r4.model.CareTeam.CareTeamParticipantComponent) Organization(org.hl7.fhir.r4.model.Organization) AdministrativeGender(org.hl7.fhir.r4.model.Enumerations.AdministrativeGender) RemittanceOutcome(org.hl7.fhir.r4.model.ExplanationOfBenefit.RemittanceOutcome) Observation(org.mitre.synthea.world.concepts.HealthRecord.Observation) IdentifierUse(org.hl7.fhir.r4.model.Identifier.IdentifierUse) DiagnosticReportStatus(org.hl7.fhir.r4.model.DiagnosticReport.DiagnosticReportStatus) Table(com.google.common.collect.Table) Reference(org.hl7.fhir.r4.model.Reference) DocumentReference(org.hl7.fhir.r4.model.DocumentReference) Attachment(org.mitre.synthea.engine.Components.Attachment) Code(org.mitre.synthea.world.concepts.HealthRecord.Code) CodeableConcept(org.hl7.fhir.r4.model.CodeableConcept)

Aggregations

Attachment (org.hl7.fhir.r4.model.Attachment)33 ArrayList (java.util.ArrayList)32 Attachment (com.ibm.cloud.cloudant.v1.model.Attachment)17 Reference (org.hl7.fhir.r4.model.Reference)17 Test (org.testng.annotations.Test)17 DocumentRevisionStatus (com.ibm.cloud.cloudant.v1.model.DocumentRevisionStatus)16 Revisions (com.ibm.cloud.cloudant.v1.model.Revisions)16 XhtmlNode (org.hl7.fhir.utilities.xhtml.XhtmlNode)16 NotImplementedException (org.apache.commons.lang3.NotImplementedException)14 HashMap (java.util.HashMap)12 Coding (org.hl7.fhir.r4.model.Coding)11 Document (com.ibm.cloud.cloudant.v1.model.Document)10 List (java.util.List)10 DiagnosticReport (org.hl7.fhir.r4.model.DiagnosticReport)10 BundleEntryComponent (org.hl7.fhir.r4.model.Bundle.BundleEntryComponent)9 DocumentReference (org.hl7.fhir.r4.model.DocumentReference)9 Observation (org.hl7.fhir.r4.model.Observation)9 IBaseResource (org.hl7.fhir.instance.model.api.IBaseResource)8 Resource (org.hl7.fhir.r4.model.Resource)8 DesignDocument (com.ibm.cloud.cloudant.v1.model.DesignDocument)7