Search in sources :

Example 41 with Attachment

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

the class EhrExtractMessageHandlerTest method When_HandleLargeMessageWithValidDataIsCalled_Expect_AddAttachmentExactNumerOfTimesAsExternalAttachmentsList.

// We are no longer storing the payload as an attachment in the case of a Skelton message.
// @Test
// public void When_HandleLargeMessageWithValidDataIsCalled_Expect_StoreMessagePayload()
// throws
// JsonProcessingException,
// JAXBException,
// InlineAttachmentProcessingException,
// BundleMappingException,
// AttachmentNotFoundException,
// ParseException,
// SAXException  {
// 
// Bundle bundle = new Bundle();
// bundle.setId("Test");
// 
// InboundMessage inboundMessage = new InboundMessage();
// List<InboundMessage.ExternalAttachment> externalAttachmentsTestList = new ArrayList<>();
// externalAttachmentsTestList.add(
// new InboundMessage.ExternalAttachment(
// "68E2A39F-7A24-449D-83CC-1B7CF1A9DAD7spine.nhs",
// "66B41202-C358-4B4C-93C6-7A10803F9584",
// "68E2A39F-7A24-449D-83CC-1B7CF1A9DAD7spine.nhs.ukExample1",
// "Filename=\"68E2A39F-7A24-449D-83CC-1B7CF1A9DAD7spine.nhs.ukExample1.gzip\" "
// + "ContentType=text/xml Compressed=Yes LargeAttachment=No OriginalBase64=Yes "
// + "DomainData=\"X-GP2GP-Skeleton: Yes\"")
// );
// 
// inboundMessage.setPayload(readLargeInboundMessagePayloadFromFile());
// inboundMessage.setEbXML(readLargeInboundMessageEbXmlFromFile());
// inboundMessage.setExternalAttachments(externalAttachmentsTestList);
// 
// prepareMigrationRequestAndMigrationStatusMocks();
// 
// ehrExtractMessageHandler.handleMessage(inboundMessage, CONVERSATION_ID);
// verify(attachmentHandlerService, times(1)).storeAttachementWithoutProcessing(any(), any(), any(), any());
// }
@Test
public void When_HandleLargeMessageWithValidDataIsCalled_Expect_AddAttachmentExactNumerOfTimesAsExternalAttachmentsList() throws JsonProcessingException, JAXBException, InlineAttachmentProcessingException, BundleMappingException, AttachmentNotFoundException, ParseException, SAXException {
    Bundle bundle = new Bundle();
    bundle.setId("Test");
    InboundMessage inboundMessage = new InboundMessage();
    List<InboundMessage.ExternalAttachment> externalAttachmentsTestList = new ArrayList<>();
    externalAttachmentsTestList.add(new InboundMessage.ExternalAttachment("68E2A39F-7A24-449D-83CC-1B7CF1A9DAD7spine.nhs", "66B41202-C358-4B4C-93C6-7A10803F9584", "68E2A39F-7A24-449D-83CC-1B7CF1A9DAD7spine.nhs.ukExample1", "Filename=\"68E2A39F-7A24-449D-83CC-1B7CF1A9DAD7spine.nhs.ukExample1.gzip\" " + "ContentType=text/xml Compressed=Yes LargeAttachment=No OriginalBase64=Yes " + "DomainData=\"X-GP2GP-Skeleton: Yes\""));
    externalAttachmentsTestList.add(new InboundMessage.ExternalAttachment("68E2A39F-7A24-449D-83CC-1B7CF1A9DAD7spine.nhs", "66B41202-C358-4B4C-93C6-7A10803F9584", "68E2A39F-7A24-449D-83CC-1B7CF1A9DAD7spine.nhs.ukExample1", "Filename=\"68E2A39F-7A24-449D-83CC-1B7CF1A9DAD7spine.nhs.ukExample1.gzip\" " + "ContentType=text/xml Compressed=Yes LargeAttachment=No OriginalBase64=Yes " + "DomainData=\"X-GP2GP-Skeleton: Yes\""));
    externalAttachmentsTestList.add(new InboundMessage.ExternalAttachment("68E2A39F-7A24-449D-83CC-1B7CF1A9DAD7spine.nhs", "66B41202-C358-4B4C-93C6-7A10803F9584", "68E2A39F-7A24-449D-83CC-1B7CF1A9DAD7spine.nhs.ukExample1", "Filename=\"68E2A39F-7A24-449D-83CC-1B7CF1A9DAD7spine.nhs.ukExample1.gzip\" " + "ContentType=text/xml Compressed=Yes LargeAttachment=No OriginalBase64=Yes"));
    externalAttachmentsTestList.add(new InboundMessage.ExternalAttachment("68E2A39F-7A24-449D-83CC-1B7CF1A9DAD7spine.nhs", "66B41202-C358-4B4C-93C6-7A10803F9584", "68E2A39F-7A24-449D-83CC-1B7CF1A9DAD7spine.nhs.ukExample1", "Filename=\"68E2A39F-7A24-449D-83CC-1B7CF1A9DAD7spine.nhs.ukExample1.gzip\" " + "ContentType=text/xml Compressed=Yes LargeAttachment=No OriginalBase64=Yes"));
    inboundMessage.setPayload(readLargeInboundMessagePayloadFromFile());
    inboundMessage.setEbXML(readLargeInboundMessageEbXmlFromFile());
    inboundMessage.setExternalAttachments(externalAttachmentsTestList);
    prepareMigrationRequestAndMigrationStatusMocks();
    ehrExtractMessageHandler.handleMessage(inboundMessage, CONVERSATION_ID);
    verify(patientAttachmentLogService, times(externalAttachmentsTestList.size())).addAttachmentLog(any());
}
Also used : Bundle(org.hl7.fhir.dstu3.model.Bundle) ArrayList(java.util.ArrayList) InboundMessage(uk.nhs.adaptors.pss.translator.mhs.model.InboundMessage) Test(org.junit.jupiter.api.Test)

Example 42 with Attachment

use of org.hl7.fhir.dstu2016may.model.Attachment in project CRD by HL7-DaVinci.

the class LibraryContentProcessor method base64EncodeToAttachment.

private Attachment base64EncodeToAttachment(FileResource fileResource, String mimeType) {
    Attachment attachment = new Attachment();
    try {
        // base64 encode
        InputStream inputStream = fileResource.getResource().getInputStream();
        byte[] byteData = new byte[inputStream.available()];
        inputStream.read(byteData);
        String encodedData = Base64.encodeBase64String(byteData);
        attachment.setContentType(mimeType);
        Base64BinaryType b64bType = new Base64BinaryType();
        b64bType.setValueAsString(encodedData);
        attachment.setDataElement(b64bType);
    } catch (IOException e) {
        logger.warn("failed to read the data: " + mimeType);
    }
    return attachment;
}
Also used : InputStream(java.io.InputStream) Attachment(org.hl7.fhir.r4.model.Attachment) IOException(java.io.IOException) Base64BinaryType(org.hl7.fhir.r4.model.Base64BinaryType)

Example 43 with Attachment

use of org.hl7.fhir.dstu2016may.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 44 with Attachment

use of org.hl7.fhir.dstu2016may.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 45 with Attachment

use of org.hl7.fhir.dstu2016may.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)

Aggregations

Attachment (org.hl7.fhir.r4.model.Attachment)33 Reference (org.hl7.fhir.r4.model.Reference)17 ArrayList (java.util.ArrayList)16 XhtmlNode (org.hl7.fhir.utilities.xhtml.XhtmlNode)16 NotImplementedException (org.apache.commons.lang3.NotImplementedException)14 Coding (org.hl7.fhir.r4.model.Coding)11 DiagnosticReport (org.hl7.fhir.r4.model.DiagnosticReport)10 List (java.util.List)9 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 Test (org.junit.jupiter.api.Test)9 IBaseResource (org.hl7.fhir.instance.model.api.IBaseResource)8 Resource (org.hl7.fhir.r4.model.Resource)8 FhirContext (ca.uhn.fhir.context.FhirContext)5 HashMap (java.util.HashMap)5 Base64 (org.apache.commons.codec.binary.Base64)5 CodeableConcept (org.hl7.fhir.r4.model.CodeableConcept)5 Extension (org.hl7.fhir.r4.model.Extension)5 Library (org.hl7.fhir.r4.model.Library)5