Search in sources :

Example 96 with Attachment

use of org.hl7.fhir.dstu2016may.model.Attachment in project org.hl7.fhir.core by hapifhir.

the class LibraryRenderer method render.

public boolean render(XhtmlNode x, ResourceWrapper lib) throws FHIRFormatError, DefinitionException, IOException {
    PropertyWrapper authors = lib.getChildByName("author");
    PropertyWrapper editors = lib.getChildByName("editor");
    PropertyWrapper reviewers = lib.getChildByName("reviewer");
    PropertyWrapper endorsers = lib.getChildByName("endorser");
    if ((authors != null && authors.hasValues()) || (editors != null && editors.hasValues()) || (reviewers != null && reviewers.hasValues()) || (endorsers != null && endorsers.hasValues())) {
        boolean email = hasCT(authors, "email") || hasCT(editors, "email") || hasCT(reviewers, "email") || hasCT(endorsers, "email");
        boolean phone = hasCT(authors, "phone") || hasCT(editors, "phone") || hasCT(reviewers, "phone") || hasCT(endorsers, "phone");
        boolean url = hasCT(authors, "url") || hasCT(editors, "url") || hasCT(reviewers, "url") || hasCT(endorsers, "url");
        x.h2().tx("Participants");
        XhtmlNode t = x.table("grid");
        if (authors != null) {
            for (BaseWrapper cd : authors.getValues()) {
                participantRow(t, "Author", cd, email, phone, url);
            }
        }
        if (authors != null) {
            for (BaseWrapper cd : editors.getValues()) {
                participantRow(t, "Editor", cd, email, phone, url);
            }
        }
        if (authors != null) {
            for (BaseWrapper cd : reviewers.getValues()) {
                participantRow(t, "Reviewer", cd, email, phone, url);
            }
        }
        if (authors != null) {
            for (BaseWrapper cd : endorsers.getValues()) {
                participantRow(t, "Endorser", cd, email, phone, url);
            }
        }
    }
    PropertyWrapper artifacts = lib.getChildByName("relatedArtifact");
    if (artifacts != null && artifacts.hasValues()) {
        x.h2().tx("Related Artifacts");
        XhtmlNode t = x.table("grid");
        boolean label = false;
        boolean display = false;
        boolean citation = false;
        for (BaseWrapper ra : artifacts.getValues()) {
            label = label || ra.has("label");
            display = display || ra.has("display");
            citation = citation || ra.has("citation");
        }
        for (BaseWrapper ra : artifacts.getValues()) {
            renderArtifact(t, ra, lib, label, display, citation);
        }
    }
    PropertyWrapper parameters = lib.getChildByName("parameter");
    if (parameters != null && parameters.hasValues()) {
        x.h2().tx("Parameters");
        XhtmlNode t = x.table("grid");
        boolean doco = false;
        for (BaseWrapper p : parameters.getValues()) {
            doco = doco || p.has("documentation");
        }
        for (BaseWrapper p : parameters.getValues()) {
            renderParameter(t, p, doco);
        }
    }
    PropertyWrapper dataRequirements = lib.getChildByName("dataRequirement");
    if (dataRequirements != null && dataRequirements.hasValues()) {
        x.h2().tx("Data Requirements");
        for (BaseWrapper p : dataRequirements.getValues()) {
            renderDataRequirement(x, (DataRequirement) p.getBase());
        }
    }
    PropertyWrapper contents = lib.getChildByName("content");
    if (contents != null) {
        x.h2().tx("Contents");
        boolean isCql = false;
        int counter = 0;
        for (BaseWrapper p : contents.getValues()) {
            Attachment att = (Attachment) p.getBase();
            renderAttachment(x, att, isCql, counter, lib.getId());
            isCql = isCql || (att.hasContentType() && att.getContentType().startsWith("text/cql"));
            counter++;
        }
    }
    return false;
}
Also used : PropertyWrapper(org.hl7.fhir.r4b.renderers.utils.BaseWrappers.PropertyWrapper) BaseWrapper(org.hl7.fhir.r4b.renderers.utils.BaseWrappers.BaseWrapper) Attachment(org.hl7.fhir.r4b.model.Attachment) ContactPoint(org.hl7.fhir.r4b.model.ContactPoint) XhtmlNode(org.hl7.fhir.utilities.xhtml.XhtmlNode)

Example 97 with Attachment

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

the class COPCMessageHandler method extractFragmentsAndLog.

private void extractFragmentsAndLog(PatientMigrationRequest migrationRequest, PatientAttachmentLog parentAttachmentLog, String conversationId, InboundMessage message) throws ParseException, SAXException, ValidationException, InlineAttachmentProcessingException {
    List<EbxmlReference> attachmentReferenceDescription = new ArrayList<>();
    attachmentReferenceDescription.addAll(xmlParseUtilService.getEbxmlAttachmentsData(message));
    // first item is always the message payload reference so skip it
    for (var index = 1; index < attachmentReferenceDescription.size(); index++) {
        var payloadReference = attachmentReferenceDescription.get(index);
        var descriptionString = "";
        var messageId = "";
        var fileUpload = false;
        // in this instance there should only ever be one CID on a fragment index file
        if (payloadReference.getHref().contains("cid:")) {
            messageId = payloadReference.getHref().substring(payloadReference.getHref().indexOf("cid:") + "cid:".length());
            descriptionString = message.getAttachments().get(0).getDescription();
            // upload the file
            attachmentHandlerService.storeAttachments(message.getAttachments(), conversationId);
            fileUpload = true;
        } else {
            var localMessageId = payloadReference.getHref().substring(payloadReference.getHref().indexOf("mid:") + "mid:".length());
            messageId = localMessageId;
            var externalAttachmentResult = message.getExternalAttachments().stream().filter(attachment -> attachment.getMessageId().equals(localMessageId)).findFirst();
            if (externalAttachmentResult == null || externalAttachmentResult.stream().count() != 1) {
                throw new ValidationException("External Attachment in payload header does not match a received External Attachment ID");
            }
            var externalAttachment = externalAttachmentResult.get();
            descriptionString = externalAttachment.getDescription();
        }
        PatientAttachmentLog fragmentLog = patientAttachmentLogService.findAttachmentLog(messageId, conversationId);
        if (fragmentLog != null) {
            updateFragmentLog(fragmentLog, parentAttachmentLog, descriptionString, index - 1, parentAttachmentLog.getLargeAttachment());
            patientAttachmentLogService.updateAttachmentLog(fragmentLog, conversationId);
        } else {
            PatientAttachmentLog newFragmentLog = buildPatientAttachmentLog(messageId, descriptionString, parentAttachmentLog.getMid(), migrationRequest.getId(), index - 1, fileUpload, parentAttachmentLog.getLargeAttachment());
            patientAttachmentLogService.addAttachmentLog(newFragmentLog);
        }
    }
}
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) ValidationException(javax.xml.bind.ValidationException) PatientAttachmentLog(uk.nhs.adaptors.connector.model.PatientAttachmentLog) ArrayList(java.util.ArrayList) EbxmlReference(uk.nhs.adaptors.pss.translator.model.EbxmlReference)

Example 98 with Attachment

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

the class LibraryContentProcessor method processResource.

/**
 * Processes the Library to have content pointing to CQL replaced with embedded base64 encoded CQL file.
 * Only supports relative paths to files being hosted on this server.
 */
@Override
protected Library processResource(Library inputResource, FileStore fileStore, String baseUrl) {
    Library output = inputResource.copy();
    List<Attachment> content = inputResource.getContent();
    logger.info("Attempt to embed CQL (ELM) into Requested Library");
    // if the first value in content is application/elm+json with a url, replace it with base64 encoded data
    if (content.size() > 0) {
        Attachment attachment = content.get(0);
        if (attachment.hasUrl()) {
            String url = attachment.getUrl();
            // make sure this is a relative path
            if (!url.toUpperCase().startsWith("HTTP")) {
                // grab the topic, fhir version, and filename from the url
                String[] urlParts = url.split("/");
                if (urlParts.length >= 4) {
                    if ((attachment.getContentType().equalsIgnoreCase("application/elm+json")) || (attachment.getContentType().equalsIgnoreCase("text/cql"))) {
                        // content is CQL (assuming elm/json is actually CQL)
                        String topic = urlParts[1];
                        String fhirVersion = urlParts[2].toUpperCase();
                        String fileName = urlParts[3];
                        List<Attachment> attachments = new ArrayList<>();
                        // get the CQL data and base64 encode
                        FileResource cqlFileResource = fileStore.getFile(topic, fileName, fhirVersion, false);
                        attachments.add(base64EncodeToAttachment(cqlFileResource, "text/cql"));
                        // get the ELM data and base64 encode
                        FileResource elmFileResource = fileStore.getFile(topic, fileName, fhirVersion, true);
                        attachments.add(base64EncodeToAttachment(elmFileResource, "application/elm+json"));
                        // insert back into the Library
                        output.setContent(attachments);
                    } else {
                        logger.info("Content is not xml or json elm");
                    }
                } else {
                    logger.info("URL doesn't split properly: " + url);
                }
            } else {
                logger.info("URL is NOT relative");
            }
        } else {
            logger.info("Content is not a url");
        }
    } else {
        logger.info("No content in library");
    }
    return output;
}
Also used : ArrayList(java.util.ArrayList) Attachment(org.hl7.fhir.r4.model.Attachment) Library(org.hl7.fhir.r4.model.Library)

Example 99 with Attachment

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

the class Iti65RequestConverter method processDocumentReference.

/**
 * ITI-65: process DocumentReference resource from Bundle
 * @param reference
 * @param entry
 */
public void processDocumentReference(DocumentReference reference, DocumentEntry entry) {
    if (reference.getIdElement() != null) {
        entry.setEntryUuid(reference.getIdElement().getIdPart());
    } else {
        entry.assignEntryUuid();
        reference.setId(entry.getEntryUuid());
    }
    Identifier masterIdentifier = reference.getMasterIdentifier();
    entry.setUniqueId(noPrefix(masterIdentifier.getValue()));
    // limitedMetadata -> meta.profile canonical [0..*]
    // No action
    // availabilityStatus -> status code {DocumentReferenceStatus} [1..1]
    // approved -> status=current
    // deprecated -> status=superseded
    // Other status values are allowed but are not defined in this mapping to XDS.
    DocumentReferenceStatus status = reference.getStatus();
    switch(status) {
        case CURRENT:
            entry.setAvailabilityStatus(AvailabilityStatus.APPROVED);
            break;
        case SUPERSEDED:
            entry.setAvailabilityStatus(AvailabilityStatus.DEPRECATED);
            break;
        default:
            throw new InvalidRequestException("Unknown document status");
    }
    // contentTypeCode -> type CodeableConcept [0..1]
    CodeableConcept type = reference.getType();
    entry.setTypeCode(transform(type));
    // classCode -> category CodeableConcept [0..*]
    List<CodeableConcept> category = reference.getCategory();
    entry.setClassCode(transform(category));
    // patientId -> subject Reference(Patient| Practitioner| Group| Device) [0..1],
    Reference subject = reference.getSubject();
    entry.setPatientId(transformReferenceToIdentifiable(subject, reference));
    // creationTime -> date instant [0..1]
    entry.setCreationTime(timestampFromDate(reference.getDateElement()));
    // PractitionerRole| Organization| Device| Patient| RelatedPerson) [0..*]
    for (Reference authorRef : reference.getAuthor()) {
        entry.getAuthors().add(transformAuthor(authorRef, reference.getContained(), null));
    }
    if (reference.hasAuthenticator()) {
        Reference authenticatorRef = reference.getAuthenticator();
        Resource authenticator = findResource(authenticatorRef, reference.getContained());
        if (authenticator instanceof Practitioner) {
            entry.setLegalAuthenticator(transform((Practitioner) authenticator));
        } else if (authenticator instanceof PractitionerRole) {
            Practitioner practitioner = (Practitioner) findResource(((PractitionerRole) authenticator).getPractitioner(), reference.getContained());
            if (practitioner != null)
                entry.setLegalAuthenticator(transform(practitioner));
        } else
            throw new InvalidRequestException("No authenticator of type Organization supported.");
    }
    // title -> description string [0..1]
    String title = reference.getDescription();
    if (title != null)
        entry.setTitle(localizedString(title));
    // confidentialityCode -> securityLabel CodeableConcept [0..*] Note: This
    // is NOT the DocumentReference.meta, as that holds the meta tags for the
    // DocumentReference itself.
    List<CodeableConcept> securityLabels = reference.getSecurityLabel();
    transformCodeableConcepts(securityLabels, entry.getConfidentialityCodes());
    // mimeType -> content.attachment.contentType [1..1] code [0..1]
    DocumentReferenceContentComponent content = reference.getContentFirstRep();
    if (content == null)
        throw new InvalidRequestException("Missing content field in DocumentReference");
    Attachment attachment = content.getAttachment();
    if (attachment == null)
        throw new InvalidRequestException("Missing attachment field in DocumentReference");
    entry.setMimeType(attachment.getContentType());
    // languageCode -> content.attachment.language code [0..1]
    entry.setLanguageCode(attachment.getLanguage());
    // size -> content.attachment.size integer [0..1] The size is calculated
    if (attachment.hasSize())
        entry.setSize((long) attachment.getSize());
    // on the data prior to base64 encoding, if the data is base64 encoded.
    // hash -> content.attachment.hash string [0..1]
    byte[] hash = attachment.getHash();
    if (hash != null)
        entry.setHash(Hex.encodeHexString(hash));
    // comments -> content.attachment.title string [0..1]
    String comments = attachment.getTitle();
    if (comments != null)
        entry.setComments(localizedString(comments));
    // creationTime -> content.attachment.creation dateTime [0..1]
    if (attachment.hasCreation()) {
        if (entry.getCreationTime() == null)
            entry.setCreationTime(timestampFromDate(attachment.getCreationElement()));
        else if (!timestampFromDate(attachment.getCreationElement()).equals(entry.getCreationTime()))
            throw new InvalidRequestException("DocumentReference.date does not match attachment.creation element");
    }
    // formatCode -> content.format Coding [0..1]
    Coding coding = content.getFormat();
    entry.setFormatCode(transform(coding));
    DocumentReferenceContextComponent context = reference.getContext();
    // Instead: referenceIdList -> related.identifier
    for (Reference ref : context.getRelated()) {
        Identifiable refId = transformReferenceToIdentifiable(ref, reference);
        if (refId != null) {
            ReferenceId referenceId = new ReferenceId();
            referenceId.setAssigningAuthority(new CXiAssigningAuthority(null, refId.getAssigningAuthority().getUniversalId(), refId.getAssigningAuthority().getUniversalIdType()));
            referenceId.setId(refId.getId());
            entry.getReferenceIdList().add(referenceId);
        }
    }
    // Currently not mapped
    /*for (Reference encounterRef : context.getEncounter()) {
        	ReferenceId referenceId = new ReferenceId();
        	Identifiable id = transformReferenceToIdentifiable(encounterRef, reference);
        	if (id != null) {
        	  referenceId.setIdTypeCode(ReferenceId.ID_TYPE_ENCOUNTER_ID);        	
        	  referenceId.setId(id.getId());
        	  //referenceId.setAssigningAuthority(new CXiAid.getAssigningAuthority().getUniversalId());
			  entry.getReferenceIdList().add(referenceId );
        }*/
    // eventCodeList -> context.event CodeableConcept [0..*]
    List<CodeableConcept> events = context.getEvent();
    transformCodeableConcepts(events, entry.getEventCodeList());
    // serviceStartTime serviceStopTime -> context.period Period [0..1]
    Period period = context.getPeriod();
    if (period != null) {
        entry.setServiceStartTime(timestampFromDate(period.getStartElement()));
        entry.setServiceStopTime(timestampFromDate(period.getEndElement()));
    }
    // healthcareFacilityTypeCode -> context.facilityType CodeableConcept
    // [0..1]
    entry.setHealthcareFacilityTypeCode(transformCodeableConcept(context.getFacilityType()));
    // practiceSettingCode -> context.practiceSetting CodeableConcept [0..1]
    entry.setPracticeSettingCode(transformCodeableConcept(context.getPracticeSetting()));
    Extension originalRole = reference.getExtensionByUrl("http://fhir.ch/ig/ch-epr-mhealth/StructureDefinition/ch-ext-author-authorrole");
    if (originalRole != null) {
        if (originalRole.getValue() instanceof Coding) {
            Coding value = (Coding) originalRole.getValue();
            String system = noPrefix(value.getSystem());
            String code = value.getCode();
            entry.setExtraMetadata(Collections.singletonMap("urn:e-health-suisse:2020:originalProviderRole", Collections.singletonList(code + "^^^&" + system + "&ISO")));
        }
    }
    Extension deletionStatus = reference.getExtensionByUrl("http://fhir.ch/ig/ch-epr-mhealth/StructureDefinition/ch-ext-deletionstatus");
    if (deletionStatus != null) {
        if (deletionStatus.getValue() instanceof Coding) {
            Coding value = (Coding) deletionStatus.getValue();
            String code = value.getCode();
            entry.setExtraMetadata(Collections.singletonMap("urn:e-health-suisse:2019:deletionStatus", Collections.singletonList("urn:e-health-suisse:2019:deletionStatus:" + code)));
        }
    }
    // Patient.identifier.use element set to ‘usual’.
    if (context.hasSourcePatientInfo()) {
        entry.setSourcePatientId(transformReferenceToIdentifiable(context.getSourcePatientInfo(), reference));
        entry.setSourcePatientInfo(transformReferenceToPatientInfo(context.getSourcePatientInfo(), reference));
    }
}
Also used : CXiAssigningAuthority(org.openehealth.ipf.commons.ihe.xds.core.metadata.CXiAssigningAuthority) DocumentReferenceContextComponent(org.hl7.fhir.r4.model.DocumentReference.DocumentReferenceContextComponent) Reference(org.hl7.fhir.r4.model.Reference) DocumentReference(org.hl7.fhir.r4.model.DocumentReference) Resource(org.hl7.fhir.r4.model.Resource) ListResource(org.hl7.fhir.r4.model.ListResource) DomainResource(org.hl7.fhir.r4.model.DomainResource) Period(org.hl7.fhir.r4.model.Period) Attachment(org.hl7.fhir.r4.model.Attachment) PractitionerRole(org.hl7.fhir.r4.model.PractitionerRole) LocalizedString(org.openehealth.ipf.commons.ihe.xds.core.metadata.LocalizedString) Identifiable(org.openehealth.ipf.commons.ihe.xds.core.metadata.Identifiable) Practitioner(org.hl7.fhir.r4.model.Practitioner) Extension(org.hl7.fhir.r4.model.Extension) Identifier(org.hl7.fhir.r4.model.Identifier) ReferenceId(org.openehealth.ipf.commons.ihe.xds.core.metadata.ReferenceId) Coding(org.hl7.fhir.r4.model.Coding) InvalidRequestException(ca.uhn.fhir.rest.server.exceptions.InvalidRequestException) DocumentReferenceStatus(org.hl7.fhir.r4.model.Enumerations.DocumentReferenceStatus) CodeableConcept(org.hl7.fhir.r4.model.CodeableConcept) DocumentReferenceContentComponent(org.hl7.fhir.r4.model.DocumentReference.DocumentReferenceContentComponent)

Example 100 with Attachment

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

the class Iti65RequestConverter method convert.

/**
 * convert ITI-65 to ITI-41 request
 * @param requestBundle
 * @return
 */
public ProvideAndRegisterDocumentSet convert(@Body Bundle requestBundle) {
    SubmissionSet submissionSet = new SubmissionSet();
    ProvideAndRegisterDocumentSetBuilder builder = new ProvideAndRegisterDocumentSetBuilder(true, submissionSet);
    // create mapping fullUrl -> resource for each resource in bundle
    Map<String, Resource> resources = new HashMap<String, Resource>();
    ListResource manifestNeu = null;
    for (Bundle.BundleEntryComponent requestEntry : requestBundle.getEntry()) {
        Resource resource = requestEntry.getResource();
        /*if (resource instanceof DocumentManifest) {
            	manifest = (DocumentManifest) resource;            	
            } else*/
        if (resource instanceof DocumentReference) {
            resources.put(requestEntry.getFullUrl(), resource);
        } else if (resource instanceof ListResource) {
            manifestNeu = (ListResource) resource;
        // resources.put(requestEntry.getFullUrl(), resource);
        } else if (resource instanceof Binary) {
            resources.put(requestEntry.getFullUrl(), resource);
        } else {
            throw new IllegalArgumentException(resource + " is not allowed here");
        }
    }
    /*if (manifest != null) {
		  processDocumentManifest(manifest, submissionSet);
	    } else {*/
    processDocumentManifest(manifestNeu, submissionSet);
    // set limited metadata
    for (CanonicalType profile : requestBundle.getMeta().getProfile()) {
        if ("http://ihe.net/fhir/StructureDefinition/IHE_MHD_Provide_Comprehensive_DocumentBundle".equals(profile.getValue())) {
            submissionSet.setLimitedMetadata(false);
        } else if ("http://ihe.net/fhir/StructureDefinition/IHE_MHD_Provide_Minimal_DocumentBundle".equals(profile.getValue())) {
            submissionSet.setLimitedMetadata(true);
        } else if ("http://profiles.ihe.net/ITI/MHD/StructureDefinition/IHE.MHD.Comprehensive.ProvideBundle".equals(profile.getValue())) {
            submissionSet.setLimitedMetadata(false);
        } else if ("http://profiles.ihe.net/ITI/MHD/StructureDefinition/IHE.MHD.Minimal.ProvideBundle".equals(profile.getValue())) {
            submissionSet.setLimitedMetadata(true);
        }
    }
    // process all resources referenced in DocumentManifest.content
    for (ListEntryComponent listEntry : manifestNeu.getEntry()) {
        Reference content = listEntry.getItem();
        String refTarget = content.getReference();
        Resource resource = resources.get(refTarget);
        if (resource instanceof DocumentReference) {
            DocumentReference documentReference = (DocumentReference) resource;
            Document doc = new Document();
            DocumentEntry entry = new DocumentEntry();
            processDocumentReference(documentReference, entry);
            doc.setDocumentEntry(entry);
            entry.setRepositoryUniqueId(config.getRepositoryUniqueId());
            // create associations
            for (DocumentReferenceRelatesToComponent relatesTo : documentReference.getRelatesTo()) {
                Reference target = relatesTo.getTarget();
                DocumentRelationshipType code = relatesTo.getCode();
                Association association = new Association();
                switch(code) {
                    case REPLACES:
                        association.setAssociationType(AssociationType.REPLACE);
                        break;
                    case TRANSFORMS:
                        association.setAssociationType(AssociationType.TRANSFORM);
                        break;
                    case SIGNS:
                        association.setAssociationType(AssociationType.SIGNS);
                        break;
                    case APPENDS:
                        association.setAssociationType(AssociationType.APPEND);
                        break;
                    default:
                }
                association.setSourceUuid(entry.getEntryUuid());
                association.setTargetUuid(transformUriFromReference(target));
                builder.withAssociation(association);
            }
            // get binary content from attachment.data or from referenced Binary resource
            Attachment attachment = documentReference.getContentFirstRep().getAttachment();
            if (attachment.hasData()) {
                doc.setDataHandler(new DataHandler(new ByteArrayDataSource(attachment.getData(), attachment.getContentType())));
                byte[] decoded = attachment.getData();
                entry.setSize((long) decoded.length);
                entry.setHash(SHAsum(decoded));
            } else if (attachment.hasUrl()) {
                String contentURL = attachment.getUrl();
                Resource binaryContent = resources.get(contentURL);
                if (binaryContent instanceof Binary) {
                    String contentType = attachment.getContentType();
                    Binary binary = (Binary) binaryContent;
                    if (binary.hasContentType() && !binary.getContentType().equals(contentType))
                        throw new InvalidRequestException("ContentType in Binary and in DocumentReference must match");
                    doc.setDataHandler(new DataHandler(new ByteArrayDataSource(binary.getData(), contentType)));
                    byte[] decoded = binary.getData();
                    entry.setSize((long) decoded.length);
                    entry.setHash(SHAsum(decoded));
                    Identifier masterIdentifier = documentReference.getMasterIdentifier();
                    binary.setUserData("masterIdentifier", noPrefix(masterIdentifier.getValue()));
                }
            }
            builder.withDocument(doc);
        }
    }
    return builder.build();
}
Also used : DocumentReferenceRelatesToComponent(org.hl7.fhir.r4.model.DocumentReference.DocumentReferenceRelatesToComponent) HashMap(java.util.HashMap) SubmissionSet(org.openehealth.ipf.commons.ihe.xds.core.metadata.SubmissionSet) Attachment(org.hl7.fhir.r4.model.Attachment) LocalizedString(org.openehealth.ipf.commons.ihe.xds.core.metadata.LocalizedString) DataHandler(javax.activation.DataHandler) Document(org.openehealth.ipf.commons.ihe.xds.core.metadata.Document) CanonicalType(org.hl7.fhir.r4.model.CanonicalType) Association(org.openehealth.ipf.commons.ihe.xds.core.metadata.Association) Identifier(org.hl7.fhir.r4.model.Identifier) ProvideAndRegisterDocumentSetBuilder(org.openehealth.ipf.commons.ihe.xds.core.requests.builder.ProvideAndRegisterDocumentSetBuilder) DocumentEntry(org.openehealth.ipf.commons.ihe.xds.core.metadata.DocumentEntry) ListEntryComponent(org.hl7.fhir.r4.model.ListResource.ListEntryComponent) InvalidRequestException(ca.uhn.fhir.rest.server.exceptions.InvalidRequestException) ByteArrayDataSource(com.sun.istack.ByteArrayDataSource) DocumentReference(org.hl7.fhir.r4.model.DocumentReference) DocumentRelationshipType(org.hl7.fhir.r4.model.DocumentReference.DocumentRelationshipType) Bundle(org.hl7.fhir.r4.model.Bundle) Reference(org.hl7.fhir.r4.model.Reference) DocumentReference(org.hl7.fhir.r4.model.DocumentReference) Resource(org.hl7.fhir.r4.model.Resource) ListResource(org.hl7.fhir.r4.model.ListResource) DomainResource(org.hl7.fhir.r4.model.DomainResource) Binary(org.hl7.fhir.r4.model.Binary) ListResource(org.hl7.fhir.r4.model.ListResource)

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