Search in sources :

Example 1 with ReferenceId

use of org.openehealth.ipf.commons.ihe.xds.core.metadata.ReferenceId in project MobileAccessGateway by i4mi.

the class Iti67RequestConverter method searchParameterIti67ToFindDocumentsQuery.

/**
 * convert ITI-67 request to ITI-18 request
 * @param searchParameter
 * @return
 */
public QueryRegistry searchParameterIti67ToFindDocumentsQuery(@Body Iti67SearchParameters searchParameter) {
    boolean getLeafClass = true;
    Query searchQuery = null;
    if (searchParameter.get_id() != null || searchParameter.getIdentifier() != null) {
        GetDocumentsQuery query = new GetDocumentsQuery();
        if (searchParameter.getIdentifier() != null) {
            String val = searchParameter.getIdentifier().getValue();
            if (val.startsWith("urn:oid:")) {
                query.setUniqueIds(Collections.singletonList(val.substring("urn:oid:".length())));
            } else if (val.startsWith("urn:uuid:")) {
                query.setUuids(Collections.singletonList(val.substring("urn:uuid:".length())));
            }
        } else {
            query.setUuids(Collections.singletonList(searchParameter.get_id().getValue()));
        }
        searchQuery = query;
    } else {
        FindDocumentsQuery query;
        // TODO   related Note 4                  -->  $XDSDocumentEntryReferenceIdList
        TokenOrListParam related = searchParameter.getRelated();
        if (related != null) {
            FindDocumentsByReferenceIdQuery referenceIdQuery = new FindDocumentsByReferenceIdQuery();
            ;
            QueryList<ReferenceId> outerReferences = new QueryList<ReferenceId>();
            List<ReferenceId> references = new ArrayList<ReferenceId>();
            for (TokenParam token : related.getValuesAsQueryTokens()) {
                references.add(new ReferenceId(token.getValue(), null, getScheme(token.getSystem())));
            }
            outerReferences.getOuterList().add(references);
            referenceIdQuery.setTypedReferenceIds(outerReferences);
            query = referenceIdQuery;
        } else
            query = new FindDocumentsQuery();
        // query.setMetadataLevel(metadataLevel);
        // status  -->  $XDSDocumentEntryStatus
        TokenOrListParam status = searchParameter.getStatus();
        if (status != null) {
            List<AvailabilityStatus> availabilites = new ArrayList<AvailabilityStatus>();
            for (TokenParam statusToken : status.getValuesAsQueryTokens()) {
                String tokenValue = statusToken.getValue();
                if (tokenValue.equals("current"))
                    availabilites.add(AvailabilityStatus.APPROVED);
                else if (tokenValue.equals("superseded"))
                    availabilites.add(AvailabilityStatus.DEPRECATED);
            }
            query.setStatus(availabilites);
        }
        // patient or patient.identifier  -->  $XDSDocumentEntryPatientId
        TokenParam tokenIdentifier = searchParameter.getPatientIdentifier();
        if (tokenIdentifier != null) {
            String system = getScheme(tokenIdentifier.getSystem());
            if (system == null)
                throw new InvalidRequestException("Missing OID for patient");
            query.setPatientId(new Identifiable(tokenIdentifier.getValue(), new AssigningAuthority(system)));
        }
        ReferenceParam patientRef = searchParameter.getPatientReference();
        if (patientRef != null) {
            Identifiable id = transformReference(patientRef.getValue());
            query.setPatientId(id);
        }
        // date Note 1 Note 5              -->  $DSDocumentEntryCreationTimeFrom
        // date Note 2 Note 5              -->  $XDSDocumentEntryCreationTimeTo
        DateRangeParam dateRange = searchParameter.getDate();
        if (dateRange != null) {
            DateParam creationTimeFrom = dateRange.getLowerBound();
            DateParam creationTimeTo = dateRange.getUpperBound();
            query.getCreationTime().setFrom(timestampFromDateParam(creationTimeFrom));
            query.getCreationTime().setTo(timestampFromDateParam(creationTimeTo));
        }
        // period Note 1                   -->  $XDSDocumentEntryServiceStartTimeFrom
        // period Note 2                   -->  $XDSDocumentEntryServiceStartTimeTo
        // period Note 1                   -->  $XDSDocumentEntryServiceStopTimeFrom
        // period Note 2                   -->  $XDSDocumentEntryServiceStopTimeTo
        DateRangeParam periodRange = searchParameter.getPeriod();
        if (periodRange != null) {
            DateParam periodFrom = periodRange.getLowerBound();
            DateParam periodTo = periodRange.getUpperBound();
            query.getServiceStopTime().setFrom(timestampFromDateParam(periodFrom));
            query.getServiceStartTime().setTo(timestampFromDateParam(periodTo));
        }
        // category                        -->  $XDSDocumentEntryClassCode
        TokenOrListParam categories = searchParameter.getCategory();
        query.setClassCodes(codesFromTokens(categories));
        // type                            -->  $XDSDocumentEntryTypeCode
        TokenOrListParam types = searchParameter.getType();
        query.setTypeCodes(codesFromTokens(types));
        // setting                         -->  $XDSDocumentEntryPracticeSettingCode
        TokenOrListParam settings = searchParameter.getSetting();
        query.setPracticeSettingCodes(codesFromTokens(settings));
        // facility                        -->  $XDSDocumentEntryHealthcareFacilityTypeCode
        TokenOrListParam facilities = searchParameter.getFacility();
        query.setHealthcareFacilityTypeCodes(codesFromTokens(facilities));
        // event                           -->  $XDSDocumentEntryEventCodeList
        TokenOrListParam events = searchParameter.getEvent();
        if (events != null) {
            QueryList<Code> eventCodeList = new QueryList<Code>();
            eventCodeList.getOuterList().add(codesFromTokens(events));
            query.setEventCodes(eventCodeList);
        }
        // security-label                  -->  $XDSDocumentEntryConfidentialityCode
        TokenOrListParam securityLabels = searchParameter.getSecurityLabel();
        if (securityLabels != null) {
            QueryList<Code> confidentialityCodes = new QueryList<Code>();
            confidentialityCodes.getOuterList().add(codesFromTokens(securityLabels));
            query.setConfidentialityCodes(confidentialityCodes);
        }
        // format                          -->  $XDSDocumentEntryFormatCode
        TokenOrListParam formats = searchParameter.getFormat();
        query.setFormatCodes(codesFromTokens(formats));
        // TODO   author.given / author.family    -->  $XDSDocumentEntryAuthorPerson
        StringParam authorGivenName = searchParameter.getAuthorGivenName();
        StringParam authorFamilyName = searchParameter.getAuthorFamilyName();
        if (authorGivenName != null || authorFamilyName != null) {
            Person person = new Person();
            XcnName name = new XcnName();
            if (authorFamilyName != null)
                name.setFamilyName(authorFamilyName.getValue());
            if (authorGivenName != null)
                name.setGivenName(authorGivenName.getValue());
            person.setName(name);
            // String author = (authorGivenName != null ? authorGivenName.getValue() : "%")+" "+(authorFamilyName != null ? authorFamilyName.getValue() : "%");
            List<Person> authorPersons = Collections.singletonList(person);
            query.setTypedAuthorPersons(authorPersons);
        }
        searchQuery = query;
    }
    final QueryRegistry queryRegistry = new QueryRegistry(searchQuery);
    queryRegistry.setReturnType((getLeafClass) ? QueryReturnType.LEAF_CLASS : QueryReturnType.OBJECT_REF);
    return queryRegistry;
}
Also used : FindDocumentsQuery(org.openehealth.ipf.commons.ihe.xds.core.requests.query.FindDocumentsQuery) FindDocumentsByReferenceIdQuery(org.openehealth.ipf.commons.ihe.xds.core.requests.query.FindDocumentsByReferenceIdQuery) Query(org.openehealth.ipf.commons.ihe.xds.core.requests.query.Query) GetDocumentsQuery(org.openehealth.ipf.commons.ihe.xds.core.requests.query.GetDocumentsQuery) ArrayList(java.util.ArrayList) ReferenceParam(ca.uhn.fhir.rest.param.ReferenceParam) FindDocumentsQuery(org.openehealth.ipf.commons.ihe.xds.core.requests.query.FindDocumentsQuery) GetDocumentsQuery(org.openehealth.ipf.commons.ihe.xds.core.requests.query.GetDocumentsQuery) ReferenceId(org.openehealth.ipf.commons.ihe.xds.core.metadata.ReferenceId) InvalidRequestException(ca.uhn.fhir.rest.server.exceptions.InvalidRequestException) StringParam(ca.uhn.fhir.rest.param.StringParam) QueryList(org.openehealth.ipf.commons.ihe.xds.core.requests.query.QueryList) DateParam(ca.uhn.fhir.rest.param.DateParam) QueryRegistry(org.openehealth.ipf.commons.ihe.xds.core.requests.QueryRegistry) FindDocumentsByReferenceIdQuery(org.openehealth.ipf.commons.ihe.xds.core.requests.query.FindDocumentsByReferenceIdQuery) XcnName(org.openehealth.ipf.commons.ihe.xds.core.metadata.XcnName) AssigningAuthority(org.openehealth.ipf.commons.ihe.xds.core.metadata.AssigningAuthority) Code(org.openehealth.ipf.commons.ihe.xds.core.metadata.Code) Identifiable(org.openehealth.ipf.commons.ihe.xds.core.metadata.Identifiable) DateRangeParam(ca.uhn.fhir.rest.param.DateRangeParam) TokenOrListParam(ca.uhn.fhir.rest.param.TokenOrListParam) AvailabilityStatus(org.openehealth.ipf.commons.ihe.xds.core.metadata.AvailabilityStatus) TokenParam(ca.uhn.fhir.rest.param.TokenParam) Person(org.openehealth.ipf.commons.ihe.xds.core.metadata.Person)

Example 2 with ReferenceId

use of org.openehealth.ipf.commons.ihe.xds.core.metadata.ReferenceId 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 3 with ReferenceId

use of org.openehealth.ipf.commons.ihe.xds.core.metadata.ReferenceId in project MobileAccessGateway by i4mi.

the class Iti65RequestConverter method processDocumentReference.

/**
 * ITI-65: process DocumentReference resource from Bundle
 * @param reference
 * @param entry
 */
private void processDocumentReference(DocumentReference reference, DocumentEntry entry) {
    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")));
        }
    }
    // 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)

Aggregations

Identifiable (org.openehealth.ipf.commons.ihe.xds.core.metadata.Identifiable)3 ReferenceId (org.openehealth.ipf.commons.ihe.xds.core.metadata.ReferenceId)3 InvalidRequestException (ca.uhn.fhir.rest.server.exceptions.InvalidRequestException)2 ArrayList (java.util.ArrayList)2 Attachment (org.hl7.fhir.r4.model.Attachment)2 DocumentReference (org.hl7.fhir.r4.model.DocumentReference)2 DocumentReferenceContentComponent (org.hl7.fhir.r4.model.DocumentReference.DocumentReferenceContentComponent)2 DocumentReferenceContextComponent (org.hl7.fhir.r4.model.DocumentReference.DocumentReferenceContextComponent)2 Identifier (org.hl7.fhir.r4.model.Identifier)2 Period (org.hl7.fhir.r4.model.Period)2 Practitioner (org.hl7.fhir.r4.model.Practitioner)2 Reference (org.hl7.fhir.r4.model.Reference)2 Person (org.openehealth.ipf.commons.ihe.xds.core.metadata.Person)2 DateParam (ca.uhn.fhir.rest.param.DateParam)1 DateRangeParam (ca.uhn.fhir.rest.param.DateRangeParam)1 ReferenceParam (ca.uhn.fhir.rest.param.ReferenceParam)1 StringParam (ca.uhn.fhir.rest.param.StringParam)1 TokenOrListParam (ca.uhn.fhir.rest.param.TokenOrListParam)1 TokenParam (ca.uhn.fhir.rest.param.TokenParam)1 HashMap (java.util.HashMap)1