Search in sources :

Example 1 with ID

use of ca.uhn.hl7v2.model.v25.datatype.ID in project streamsx.health by IBMStreams.

the class AdtToModelMapper method messageToModel.

@SuppressWarnings("unchecked")
public <T> Iterable<T> messageToModel(Message message) {
    ArrayList<ADTEvent> adtEvents = new ArrayList<ADTEvent>();
    if (message instanceof ADT_AXX) {
        ADT_AXX superMsg = (ADT_AXX) message;
        MessageInfo msg = new MessageInfo();
        Patient patient = new Patient();
        try {
            MSH header = superMsg.getMSH();
            msg.setSendingApp(header.getSendingApplication().encode());
            msg.setSendingFacility(header.getSendingFacility().encode());
            msg.setReceivingApp(header.getReceivingApplication().encode());
            msg.setReceivingFacility(header.getReceivingFacility().encode());
            msg.setMessageTs(header.getDateTimeOfMessage().encode());
            msg.setMessageType(header.getMessageType().encode());
            PID pid = superMsg.getPID();
            patient.setId(pid.getPatientID().encode());
            XPN[] patientNames = pid.getPatientName();
            for (XPN name : patientNames) {
                if (patient.getName().equals(IInjestServicesConstants.EMPTYSTR)) {
                    patient.setName(getPatientFullName(name));
                } else {
                    patient.addAlternateName(getPatientFullName(name));
                }
            }
            patient.setGender(pid.getAdministrativeSex().encode());
            patient.setDateOfBirth(pid.getDateTimeOfBirth().encode());
            CX[] ids = pid.getAlternatePatientIDPID();
            if (ids.length > 0) {
                for (CX cx : ids) {
                    patient.addAlternativeId(cx.encode());
                }
            }
            EventDetails evt = new EventDetails();
            EVN evn = superMsg.getEVN();
            evt.setEventType(evn.getEventTypeCode().encode());
            evt.setEventTs(evn.getEvn6_EventOccurred().encode());
            evt.setRecordTs(evn.getEvn2_RecordedDateTime().encode());
            PV1 pv1 = superMsg.getPV1();
            PatientVisit patientVisit = new PatientVisit();
            patientVisit.setPatientClass(pv1.getPatientClass().encode());
            patientVisit.setLocation(pv1.getAssignedPatientLocation().encode());
            patientVisit.setPriorLocation(pv1.getPriorPatientLocation().encode());
            patientVisit.setVisitNumber(pv1.getVisitNumber().encode());
            patient.setStatus(pv1.getBedStatus().encode());
            XCN[] doctors = pv1.getAttendingDoctor();
            for (XCN xcn : doctors) {
                String id = xcn.getIDNumber().encode();
                String name = xcn.getFamilyName().encode() + " " + xcn.getGivenName().encode();
                Clinician clinician = new Clinician();
                clinician.setId(id);
                clinician.setName(name);
                patientVisit.addAttendingDoctor(clinician);
            }
            doctors = pv1.getConsultingDoctor();
            for (XCN xcn : doctors) {
                String id = xcn.getIDNumber().encode();
                String name = xcn.getFamilyName().encode() + " " + xcn.getGivenName().encode();
                Clinician clinician = new Clinician();
                clinician.setId(id);
                clinician.setName(name);
                patientVisit.addConsultingDoctor(clinician);
            }
            ADTEvent adtEvent = new ADTEvent();
            adtEvent.setEvt(evt);
            adtEvent.setPatient(patient);
            adtEvent.setMsg(msg);
            adtEvent.setPv(patientVisit);
            adtEvents.add(adtEvent);
        } catch (HL7Exception e) {
            TRACE.error("Unable to parse HL7 message", e);
        }
    }
    return (Iterable<T>) adtEvents;
}
Also used : PatientVisit(com.ibm.streamsx.health.ingest.types.model.PatientVisit) XCN(ca.uhn.hl7v2.model.v26.datatype.XCN) MSH(ca.uhn.hl7v2.model.v26.segment.MSH) ADTEvent(com.ibm.streamsx.health.ingest.types.model.ADTEvent) ArrayList(java.util.ArrayList) Patient(com.ibm.streamsx.health.ingest.types.model.Patient) PID(ca.uhn.hl7v2.model.v26.segment.PID) PV1(ca.uhn.hl7v2.model.v26.segment.PV1) MessageInfo(com.ibm.streamsx.health.ingest.types.model.MessageInfo) EventDetails(com.ibm.streamsx.health.ingest.types.model.EventDetails) Clinician(com.ibm.streamsx.health.ingest.types.model.Clinician) CX(ca.uhn.hl7v2.model.v26.datatype.CX) XPN(ca.uhn.hl7v2.model.v26.datatype.XPN) HL7Exception(ca.uhn.hl7v2.HL7Exception) ADT_AXX(ca.uhn.hl7v2.model.v26.message.ADT_AXX) EVN(ca.uhn.hl7v2.model.v26.segment.EVN)

Example 2 with ID

use of ca.uhn.hl7v2.model.v25.datatype.ID in project pentaho-kettle by pentaho.

the class HL7MLLPInput method execute.

public Result execute(Result previousResult, int nr) {
    Result result = previousResult;
    try {
        String serverName = environmentSubstitute(server);
        int portNumber = Integer.parseInt(environmentSubstitute(port));
        String messageVariable = environmentSubstitute(messageVariableName);
        String messageTypeVariable = environmentSubstitute(messageTypeVariableName);
        String versionVariable = environmentSubstitute(versionVariableName);
        MLLPSocketCacheEntry entry = MLLPSocketCache.getInstance().getServerSocketStreamSource(serverName, portNumber);
        if (entry.getJobListener() != null) {
            parentJob.addJobListener(entry.getJobListener());
        }
        MLLPTransport transport = entry.getTransport();
        // 
        synchronized (transport) {
            Transportable transportable = transport.doReceive();
            String message = transportable.getMessage();
            logDetailed("Received message: " + message);
            parentJob.setVariable(messageVariable, message);
            // Parse the message and extract the control ID.
            // 
            Parser parser = new GenericParser();
            ValidationContext validationContext = new NoValidation();
            parser.setValidationContext(validationContext);
            Message msg = parser.parse(message);
            Structure structure = msg.get("MSH");
            String messageType = null;
            String version = msg.getVersion();
            if (structure instanceof ca.uhn.hl7v2.model.v21.segment.MSH) {
                messageType = ((ca.uhn.hl7v2.model.v21.segment.MSH) structure).getMESSAGETYPE().encode();
            } else if (structure instanceof ca.uhn.hl7v2.model.v22.segment.MSH) {
                messageType = ((ca.uhn.hl7v2.model.v22.segment.MSH) structure).getMessageType().encode();
            } else if (structure instanceof ca.uhn.hl7v2.model.v23.segment.MSH) {
                messageType = ((ca.uhn.hl7v2.model.v23.segment.MSH) structure).getMessageType().encode();
            } else if (structure instanceof ca.uhn.hl7v2.model.v231.segment.MSH) {
                messageType = ((ca.uhn.hl7v2.model.v231.segment.MSH) structure).getMessageType().getMessageStructure().getValue();
            } else if (structure instanceof ca.uhn.hl7v2.model.v24.segment.MSH) {
                messageType = ((ca.uhn.hl7v2.model.v24.segment.MSH) structure).getMessageType().getMessageStructure().getValue();
            } else if (structure instanceof ca.uhn.hl7v2.model.v25.segment.MSH) {
                messageType = ((ca.uhn.hl7v2.model.v25.segment.MSH) structure).getMessageType().getMessageStructure().getValue();
            } else if (structure instanceof ca.uhn.hl7v2.model.v251.segment.MSH) {
                messageType = ((ca.uhn.hl7v2.model.v251.segment.MSH) structure).getMessageType().getMessageStructure().getValue();
            } else if (structure instanceof ca.uhn.hl7v2.model.v26.segment.MSH) {
                messageType = ((ca.uhn.hl7v2.model.v26.segment.MSH) structure).getMessageType().getMessageStructure().getValue();
            } else {
                logError("This job entry does not support the HL7 dialect used. Found MSH class: " + structure.getClass().getName());
            }
            if (!Utils.isEmpty(messageTypeVariable)) {
                parentJob.setVariable(messageTypeVariable, messageType);
            }
            if (!Utils.isEmpty(versionVariable)) {
                parentJob.setVariable(versionVariable, version);
            }
        }
        // All went well..
        // 
        result.setNrErrors(0);
        result.setResult(true);
    } catch (Exception e) {
        log.logError(BaseMessages.getString(PKG, "HL7MLLPInput.Exception.UnexpectedError"), e);
        result.setNrErrors(1);
        result.setResult(false);
    }
    return result;
}
Also used : Message(ca.uhn.hl7v2.model.Message) Result(org.pentaho.di.core.Result) MLLPSocketCacheEntry(org.pentaho.di.trans.steps.hl7input.common.MLLPSocketCacheEntry) Structure(ca.uhn.hl7v2.model.Structure) Transportable(ca.uhn.hl7v2.protocol.Transportable) KettleException(org.pentaho.di.core.exception.KettleException) KettleDatabaseException(org.pentaho.di.core.exception.KettleDatabaseException) KettleXMLException(org.pentaho.di.core.exception.KettleXMLException) Parser(ca.uhn.hl7v2.parser.Parser) GenericParser(ca.uhn.hl7v2.parser.GenericParser) GenericParser(ca.uhn.hl7v2.parser.GenericParser) ValidationContext(ca.uhn.hl7v2.validation.ValidationContext) MLLPTransport(ca.uhn.hl7v2.protocol.impl.MLLPTransport) NoValidation(ca.uhn.hl7v2.validation.impl.NoValidation)

Example 3 with ID

use of ca.uhn.hl7v2.model.v25.datatype.ID in project openmrs-core by openmrs.

the class ORUR01Handler method createEncounter.

/**
 * This method does not call the database to create the encounter row. The encounter is only
 * created after all obs have been attached to it Creates an encounter pojo to be attached
 * later. This method does not create an encounterId
 *
 * @param msh
 * @param patient
 * @param pv1
 * @param orc
 * @return
 * @throws HL7Exception
 */
private Encounter createEncounter(MSH msh, Patient patient, PV1 pv1, ORC orc) throws HL7Exception {
    // the encounter we will return
    Encounter encounter;
    // look for the encounter id in PV1-19
    CX visitNumber = pv1.getVisitNumber();
    Integer encounterId = null;
    try {
        encounterId = Integer.valueOf(visitNumber.getIDNumber().getValue());
    } catch (NumberFormatException e) {
    // pass
    }
    // the database
    if (encounterId != null) {
        encounter = Context.getEncounterService().getEncounter(encounterId);
    } else {
        // if no encounter_id was passed in, this is a new
        // encounter, create the object
        encounter = new Encounter();
        Date encounterDate = getEncounterDate(pv1);
        Provider provider = getProvider(pv1);
        Location location = getLocation(pv1);
        Form form = getForm(msh);
        EncounterType encounterType = getEncounterType(msh, form);
        User enterer = getEnterer(orc);
        // Date dateEntered = getDateEntered(orc); // ignore this since we have no place in the data model to store it
        encounter.setEncounterDatetime(encounterDate);
        if (unknownRole == null) {
            unknownRole = Context.getEncounterService().getEncounterRoleByUuid(EncounterRole.UNKNOWN_ENCOUNTER_ROLE_UUID);
        }
        encounter.setProvider(unknownRole, provider);
        encounter.setPatient(patient);
        encounter.setLocation(location);
        encounter.setForm(form);
        encounter.setEncounterType(encounterType);
        encounter.setCreator(enterer);
        encounter.setDateCreated(new Date());
    }
    return encounter;
}
Also used : User(org.openmrs.User) CX(ca.uhn.hl7v2.model.v25.datatype.CX) Form(org.openmrs.Form) Encounter(org.openmrs.Encounter) EncounterType(org.openmrs.EncounterType) Date(java.util.Date) Provider(org.openmrs.Provider) Location(org.openmrs.Location)

Example 4 with ID

use of ca.uhn.hl7v2.model.v25.datatype.ID in project openmrs-core by openmrs.

the class ORUR01Handler method getProvider.

private Provider getProvider(PV1 pv1) throws HL7Exception {
    XCN hl7Provider = pv1.getAttendingDoctor(0);
    Provider provider = null;
    String id = hl7Provider.getIDNumber().getValue();
    String assignAuth = hl7Provider.getAssigningAuthority().getUniversalID().getValue();
    String type = hl7Provider.getAssigningAuthority().getUniversalIDType().getValue();
    String errorMessage;
    if (StringUtils.hasText(id)) {
        String specificErrorMsg = "";
        if (OpenmrsUtil.nullSafeEquals("L", type)) {
            if (HL7Constants.PROVIDER_ASSIGNING_AUTH_PROV_ID.equalsIgnoreCase(assignAuth)) {
                try {
                    provider = Context.getProviderService().getProvider(Integer.valueOf(id));
                } catch (NumberFormatException e) {
                // ignore
                }
                specificErrorMsg = "with provider Id";
            } else if (HL7Constants.PROVIDER_ASSIGNING_AUTH_IDENTIFIER.equalsIgnoreCase(assignAuth)) {
                provider = Context.getProviderService().getProviderByIdentifier(id);
                specificErrorMsg = "with provider identifier";
            } else if (HL7Constants.PROVIDER_ASSIGNING_AUTH_PROV_UUID.equalsIgnoreCase(assignAuth)) {
                provider = Context.getProviderService().getProviderByUuid(id);
                specificErrorMsg = "with provider uuid";
            }
        } else {
            try {
                Person person = Context.getPersonService().getPerson(Integer.valueOf(id));
                Collection<Provider> providers = Context.getProviderService().getProvidersByPerson(person);
                if (!providers.isEmpty()) {
                    provider = providers.iterator().next();
                }
            } catch (NumberFormatException e) {
            // ignore
            }
            specificErrorMsg = "associated to a person with person id";
        }
        errorMessage = "Could not resolve provider " + specificErrorMsg + ":" + id;
    } else {
        errorMessage = "No unique identifier was found for the provider";
    }
    if (provider == null) {
        throw new HL7Exception(errorMessage);
    }
    return provider;
}
Also used : XCN(ca.uhn.hl7v2.model.v25.datatype.XCN) HL7Exception(ca.uhn.hl7v2.HL7Exception) Person(org.openmrs.Person) Provider(org.openmrs.Provider)

Example 5 with ID

use of ca.uhn.hl7v2.model.v25.datatype.ID in project openmrs-core by openmrs.

the class HL7ServiceImpl method resolvePersonFromIdentifiers.

/**
 * @param identifiers CX identifier list from an identifier (either PID or NK1)
 * @return The internal id number of the Patient based on one of the given identifiers, or null
 *         if the patient is not found
 * @throws HL7Exception
 */
@Override
@Transactional(readOnly = true)
public Person resolvePersonFromIdentifiers(CX[] identifiers) throws HL7Exception {
    // give up if no identifiers exist
    if (identifiers.length < 1) {
        throw new HL7Exception("Missing patient identifier in PID segment");
    }
    // Take the first uniquely matching identifier
    for (CX identifier : identifiers) {
        String hl7PersonId = identifier.getIDNumber().getValue();
        // TODO if 1st component is blank, check 2nd and 3rd of assigning
        // authority
        String assigningAuthority = identifier.getAssigningAuthority().getNamespaceID().getValue();
        if (StringUtils.isNotBlank(assigningAuthority)) {
            // Assigning authority defined
            try {
                PatientIdentifierType pit = Context.getPatientService().getPatientIdentifierTypeByName(assigningAuthority);
                if (pit == null) {
                    // there is no matching PatientIdentifierType
                    if (assigningAuthority.equals(HL7Constants.HL7_AUTHORITY_UUID)) {
                        // the identifier is a UUID
                        Person p = Context.getPersonService().getPersonByUuid(hl7PersonId);
                        if (p != null) {
                            return p;
                        }
                        log.warn("Can't find person for UUID '" + hl7PersonId + "'");
                        // skip identifiers with unknown type
                        continue;
                    } else if (assigningAuthority.equals(HL7Constants.HL7_AUTHORITY_LOCAL)) {
                        // the ID is internal (local)
                        String idType = identifier.getIdentifierTypeCode().getValue();
                        try {
                            if (idType.equals(HL7Constants.HL7_ID_PERSON)) {
                                Integer pid = Integer.parseInt(hl7PersonId);
                                // patient_id == person_id, so just look for
                                // the person
                                Person p = Context.getPersonService().getPerson(pid);
                                if (p != null) {
                                    return p;
                                }
                            } else if (idType.equals(HL7Constants.HL7_ID_PATIENT)) {
                                Integer pid = Integer.parseInt(hl7PersonId);
                                // patient_id == person_id, so just look for
                                // the person
                                Patient p = Context.getPatientService().getPatient(pid);
                                if (p != null) {
                                    return p;
                                }
                            }
                        } catch (NumberFormatException e) {
                        }
                        log.warn("Can't find Local identifier of '" + hl7PersonId + "'");
                        // skip identifiers with unknown type
                        continue;
                    }
                    log.warn("Can't find PatientIdentifierType named '" + assigningAuthority + "'");
                    // skip identifiers with unknown type
                    continue;
                }
                List<PatientIdentifier> matchingIds = Context.getPatientService().getPatientIdentifiers(hl7PersonId, Collections.singletonList(pit), null, null, null);
                if (matchingIds == null || matchingIds.isEmpty()) {
                    // no matches
                    log.warn("NO matches found for " + hl7PersonId);
                    // try next identifier
                    continue;
                } else if (matchingIds.size() == 1) {
                    // unique match -- we're done
                    return matchingIds.get(0).getPatient();
                } else {
                    // ambiguous identifier
                    log.debug("Ambiguous identifier in PID. " + matchingIds.size() + " matches for identifier '" + hl7PersonId + "' of type '" + pit + "'");
                    // try next identifier
                    continue;
                }
            } catch (Exception e) {
                log.error("Error resolving patient identifier '" + hl7PersonId + "' for assigning authority '" + assigningAuthority + "'", e);
                continue;
            }
        } else {
            try {
                log.debug("CX contains ID '" + hl7PersonId + "' without assigning authority -- assuming patient.patient_id");
                return Context.getPatientService().getPatient(Integer.parseInt(hl7PersonId));
            } catch (NumberFormatException e) {
                log.warn("Invalid patient ID '" + hl7PersonId + "'");
            }
        }
    }
    return null;
}
Also used : CX(ca.uhn.hl7v2.model.v25.datatype.CX) HL7Exception(ca.uhn.hl7v2.HL7Exception) Patient(org.openmrs.Patient) Person(org.openmrs.Person) PatientIdentifierType(org.openmrs.PatientIdentifierType) PatientIdentifier(org.openmrs.PatientIdentifier) URISyntaxException(java.net.URISyntaxException) DAOException(org.openmrs.api.db.DAOException) FileNotFoundException(java.io.FileNotFoundException) APIException(org.openmrs.api.APIException) HL7Exception(ca.uhn.hl7v2.HL7Exception) EncodingNotSupportedException(ca.uhn.hl7v2.parser.EncodingNotSupportedException) IOException(java.io.IOException) PatientIdentifierException(org.openmrs.api.PatientIdentifierException) ApplicationException(ca.uhn.hl7v2.app.ApplicationException) Transactional(org.springframework.transaction.annotation.Transactional)

Aggregations

HL7Exception (ca.uhn.hl7v2.HL7Exception)14 Message (ca.uhn.hl7v2.model.Message)10 ApplicationException (ca.uhn.hl7v2.app.ApplicationException)8 Test (org.junit.Test)7 Patient (org.openmrs.Patient)7 BaseContextSensitiveTest (org.openmrs.test.BaseContextSensitiveTest)7 PID (ca.uhn.hl7v2.model.v25.segment.PID)6 Person (org.openmrs.Person)6 PatientIdentifierException (org.openmrs.api.PatientIdentifierException)6 EncodingNotSupportedException (ca.uhn.hl7v2.parser.EncodingNotSupportedException)5 FileNotFoundException (java.io.FileNotFoundException)5 IOException (java.io.IOException)5 URISyntaxException (java.net.URISyntaxException)5 ArrayList (java.util.ArrayList)5 APIException (org.openmrs.api.APIException)5 DAOException (org.openmrs.api.db.DAOException)5 CX (ca.uhn.hl7v2.model.v25.datatype.CX)4 XCN (ca.uhn.hl7v2.model.v25.datatype.XCN)4 ORU_R01 (ca.uhn.hl7v2.model.v25.message.ORU_R01)4 ORC (ca.uhn.hl7v2.model.v25.segment.ORC)4