"Act as a programmer when you want to code your career. Act as a debugger when you want to refine your career." – Amarnath Krishnan

Posts tagged ‘mirth connect tutorial’

Mirth HL7 Creation- An Intro

In this tutorial, i am going to explain how to create an HL7 message by reading data values from database using Database Reader. I have used a simple table to demonstrate the worflow . Add more queries based on your requirements.

I am going to use the following database schema and data values in this tutorial

Image

ImageNow we are going to create a channel that reads data with status 0 from the patient table and create a HL7 ORM message  and update status to 1.

summary

Choose any Channel Name as you wish. Set the Datatypes here or you can do it inside transformer. Store the messages or prune it after specified period of time as you wish.

source_connector

In the Sorce Connector, select Connector Type as Database Reader. Provide the Driver info and insert the URL template. Modify the URL template configuring the host, port and Database name.   Provide the Database credentials and choose the polling ype.

Interval: Polls the database repeatedly after the specified polling frequency.

Time: Polls the database at the specified time.

Enable Use JavaScript if you want to do some manipulations over there other then database reading.  Here i have queried to read the patient table to get pid, pname, psex, pdob based on status flag. Enable Run On Update Statement if you wish to update something after reading data from table. Here i have updated the status flag to 1 such that those details will not be read again. You can now see the selected data values in the right side of On Update SQL. These selected values will be passed as an xml to the source inbound template.

source_trans

Write your custom code in the transformer. I have written the following code to create a simple HL7 messsage with single OBR Segment. You can create any number of Segments as per your requirements. Since your output to the desitnation is an HL7 message choose your Outbound Message Template Datatype to HL7 v2.x.

channelMap.put(“pid”,msg['patient_pid'].toString());
var currentdate=DateUtil.getCurrentDate(“yyyyMMddHHmmss”);

//Adding data to MSH Fields
tmp['MSH']['MSH.3']['MSH.3.1']=”XYZ”;
tmp['MSH']['MSH.4']['MSH.4.1']=”123″;
tmp['MSH']['MSH.5']['MSH.5.1']=”ABC”;
tmp['MSH']['MSH.6']['MSH.6.1']=”456″;
tmp['MSH']['MSH.7']['MSH.7.1']=currentdate;

//Adding data to PID Fields
tmp['PID']['PID.2']['PID.2.1']=1;
tmp['PID']['PID.3']['PID.3.1']=msg['patient_pid'].toString();
tmp['PID']['PID.5']['PID.5.1']=msg['patient_pname'].toString();
tmp['PID']['PID.7']['PID.7.1']=msg['patient_pdob'].toString();
tmp['PID']['PID.8']['PID.8.1']=msg['patient_psex'].toString();
tmp['PID']['PID.11']['PID.11.1']=”India”;
tmp['PID']['PID.15']['PID.15.1']=”English”;
tmp['PID']['PID.16']['PID.16.1']=”Single”;

//Adding data to ORC and OBR Fields
tmp['ORC']['ORC.2']['ORC.2.1']=100;
tmp['OBR']['OBR.2']['OBR.2.1']=100;
tmp['OBR']['OBR.4']['OBR.4.1']=”003038″;
tmp['OBR']['OBR.4']['OBR.4.2']=”Urinalysis”;
tmp['OBR']['OBR.4']['OBR.4.3']=”L”;
tmp['OBR']['OBR.6']['OBR.6.1']=currentdate;

I have mapped the pid in order to create a HL7 message with pid as a file name in destination. The code highlighted in red is the data values retrieved from database and other values are hard coded for simplicity. You can retrieve data from database and replace the hardcoded values.

dest_connector

Choose the Destination Connector Type as per your requirements. Here i have used File Writer in order to write the HL7 message. Choose Test Write to validate the existance of directory being selected. Choose any  File Name as you wish. I have used the pid(patient id) as the file name. The file will be saved with an extension(.hl7). Enable Append to File if you wish to create a batch file and choose File Type as ASCII, if you like to store the data values as ASCII characters. In the Template choose Encoded data.

User Defined Java Class in Mirth

In this tutorial we are going to see how to use an Userdefined Java class in Mirth. In this example, i have created a java class named Utility under org.amar.mirth package. My java class contains two userdefined functions.

UpperCase – To convert a String to UpperCase String

ConvertDOB – To convert date of birth to specified format (Ex: 19910518 to 18 May 1991)

Utility.java

package org.amar.mirth;

public class Utility
{
//Convert String to Upper Case
public String UpperCase(String str)
{
return str.toUpperCase();
}

//Convert DOB
//Example: 19910518 to 18 May 1991
public String ConvertDOB(String str)
{
String[] months={“Jan”,”Feb”,”Mar”,”Apr”,”May”,”Jun”,”Jul”,”Aug”,”Sep”,”Oct”,”Nov”,”Dec”};
String format;
int mon=Integer.parseInt(str.substring(4,6));
format=str.substring(6)+’ ‘+months[mon-1]+’ ‘+str.substring(0,4);
return format;
}
}

Create a jar file with the same class name(Utility.jar). Copy the Utility.jar file to $MIRTH_HOME/lib/ directory. Now restart the mirth server so that the jar file can be recognized as a valid file by mirth next time.

In the source transformer, create a new step with JavaScript type and use the userdefined functions wherever necessary.

//Import the package
var util = new Packages.org.amar.mirth.Utility();
//Message Modifications
msg['PID']['PID.5']['PID.5.2']=util.UpperCase(msg['PID']['PID.5']['PID.5.2'].toString());
msg['PID']['PID.7']['PID.7.1']=util.ConvertDOB(msg['PID']['PID.7']['PID.7.1'].toString());
msg['PID']['PID.5']['PID.5.1']=util.UpperCase(msg['PID']['PID.5']['PID.5.1'].toString());

The variable util is the object reference to the Utility Class. Using this object you can access the methods defined in that class. The above code converts the patient name to uppercase name,date of birth to userdefined format and replaces the old one.

INPUT HL7 MESSAGE:

MSH|^~\&|LAB|1111111111|HUB|abc34abc34|20001020135010||ORU^R01|msg-ctrl-id-here|D|2.3
PID|1|123456789|987654321|60|krishnan^amarnath||19910518|M|||3317 MERLIN CT^^CHESAPEAKE^VA^23323||(757)487-5034|||U|
NTE|1|99| PT. PHONE:
ORC|RE|123456789|123456789-LA|
OBR||||||||||||||||
OBR||||||||||||||||
 

OUTPUT HL7 MESSAGE:

MSH|^~\&|LAB|1111111111|HUB|abc34abc34|20001020135010||ORU^R01|msg-ctrl-id-here|D|2.3
PID|1|123456789|987654321|60|KRISHNAN^AMARNATH||18 May 1991|M|||3317 MERLIN CT^^CHESAPEAKE^VA^23323||(757)487-5034|||U|
NTE|1|99| PT. PHONE:
ORC|RE|123456789|123456789-LA|
OBR||||||||||||||||
OBR||||||||||||||||
 
 

XML TO PLAIN TEXT

How can we convert a xml file into text file using mirth.? Let us now discuss how it can be done. Consider a case where a xml file resides in the local folder. We need to read the file from a specific folder, convert it into text file and store the text file within a specific folder.

Assume that the input file contains the following data.

<xml>
<PatientList>
<Patient LastName=”Krishnan” FirstName=”Amarnath” Gender=”Male” BirthDate=”18/05/1991″ SSN=”987654321″>
<Address AddressLine1=”NO 9/11″ City=”Coimbatore” State=”TamilNadu” Zip=”641004″/>
</Patient>
<Patient LastName=”Krishnan” FirstName=”HariGanesh” Gender=”Male” BirthDate=”18/05/1991″ SSN=”123456789″>
<Address AddressLine1=”NO 24/11″ City=”Coimbatore” State=”TamilNadu” Zip=”641014″/>
</Patient>
</PatientList>
</xml>

So what should be the output? It has to be decided by the programmer. I have decided to go with following output.

Name: Krishnan Amarnath
Gender: Male
BirthDate: 18/05/1991
SSN: 987654321
Address: NO 9/11
City: Coimbatore
State: TamilNadu
Zip: 641004
————————————-
Name: Krishnan HariGanesh
Gender: Male
BirthDate: 18/05/1991
SSN: 123456789
Address: NO 24/11
City: Coimbatore
State: TamilNadu
Zip: 641014
————————————-

Let us now discuss how to convert the xml into plain text using Mirth.

Step 1: Create a channel with source connector as File Reader. Specify the path from where you have to read file. Choose Delete File After Read or Move-to Directory and specify the path in order to avoid reading the same file again and again. In this tutorial i have moved the file once its read.

source

 Step2: Create a new step with type JavaScript in the Source Transformer and write the user logic here. Inbound and Outbound template should be XML.

var i;
var file=””;
var delimiter=”————————————-”;
for(i=0;i<msg['PatientList']['Patient'].length();i++)
{
file+=”Name: “+msg['PatientList']['Patient'][i]['@LastName'].toString()+’ ‘+msg['PatientList']['Patient'][i]['@FirstName'].toString()+”\n”;
file+=”Gender: “+msg['PatientList']['Patient'][i]['@Gender'].toString()+”\n”;
file+=”BirthDate: “+msg['PatientList']['Patient'][i]['@BirthDate'].toString()+”\n”;
file+=”SSN: “+msg['PatientList']['Patient'][i]['@SSN'].toString()+”\n”;
file+=”Address: “+msg['PatientList']['Patient'][i]['Address']['@AddressLine1'].toString()+”\n”;
file+=”City: “+msg['PatientList']['Patient'][i]['Address']['@City'].toString()+”\n”;
file+=”State: “+msg['PatientList']['Patient'][i]['Address']['@State'].toString()+”\n”;
file+=”Zip: “+msg['PatientList']['Patient'][i]['Address']['@Zip'].toString()+”\n”;
file+=delimiter+”\n”;
}
channelMap.put(“FILE”,file);

Iterate over each node present in the xml file and store the data in the local variable(file) with linefeed and other constraints required. Copy the local variable(file) data to a channelmap variable (FILE) that can be used in the destination side.

source_transformer

Step 3: The destination connector is a File writer that writes the text file to the specified directory. Provide the directory path and file name. In the template field specify the channelmap variable(FILE) that holds the formatted data.

destination

Discard Data Info before “~”

How to discard data info before “~” symbol.?  I post this solution for one of my visitor. Hope it helps.

Consider the following case.

Raw PID3 =12345^^^TEST1~67890^^^TEST2
Result PID3 = 67890^^^TEST2

Try the Following Approach.. As per the requirements, there are two cases possible.

Case 1: “~” comes in the beginning of any field in PID.3
Case 2: “~” comes in the middle or end of any field in PID.3

You can certainly discard the data before ~ by simple replacement.

// Identifying the patient id and assigning authority

var temp=msg['PID']['PID.3']['PID.3.4'].toString();
var pid=msg['PID']['PID.3']['PID.3.4'].toString().split(“~”);
var patient_id=pid[1];
var assign =msg['PID']['PID.3']['PID.3.7'].toString();

// Discarding data after ~

temp=””;
pid=””;
temp=msg['PID']['PID.3'].toString();
pid=msg['PID']['PID.3'].toString().split(“~”);
if(temp.toString().charAt(temp.toString().indexOf( “~”)-1)==”>”)
{
substr=pid[0].toString().substring(0,pid[0].lastIndexOf(“<”));
substr+=”</PID.3>”;
}
else
{
substr=pid[1].toString().substring(pid[1].toString().indexOf(“<”),(pid[1].toString().indexOf(“>”)+1));
substr=pid[0].toString()+substr;
substr+=”</PID.3>”;
}

msg['PID']['PID.3']=new XML(substr);

//Replacing data

msg['PID']['PID.3']['PID.3.1']=patient_id;
msg['PID']['PID.3']['PID.3.4']=assign;

Handling Repeating OBX Segment

Just noticed that lots of people looking for a generalized code to handle repeating OBX Segments. I just taught of sharing the logic i posted in mirth forum with you all.

var len=msg['OBX'].length();
for(i=0;i<len;i++)
{
for(j=i+1;j<len;j++)
{
if(msg['OBX'][i]['OBX.3']['OBX.3.1'].toString()==msg['OBX'][j]['OBX.3']['OBX.3.1'].toString())
{
msg['OBX'][i]['OBX.5']['OBX.5.1']+=msg['OBX'][j]['OBX.5']['OBX.5.1'].toString();
delete msg['OBX'][j];
j=j-1;
}
len=msg['OBX'].length();
}
}

Post Reference: http://www.mirthcorp.com/community/forums/showpost.php?p=28261&postcount=2

Delete a file Using JavaScript in Mirth

How to delete a file using JavaScript in Mirth?

We cant directly use the inbuild delete() javascript function in mirth. It throws error due to the conflication. In order to delete a file we can use java.io.File Package. It can be done as follows.

The code specified below will delete a file in the coressponding directory.

var del=new java.io.File(‘/Directory/FileName.hl7′);
del["delete"]();

Discard Data Info after “~”

How to discard data info after “~” symbol. Consider the following case.

Raw PID3 = 09999999^^^ST01W^MR~09999999^^^ST01^PI|
Result PID3 = 09999999^^^ST01W^MR

Try the Following Approach.. As per the requirements, there are two cases possible.
Case 1: “~” comes in the beginning of any field in PID.3
Case 2: “~” comes in the middle or end of any field in PID.3

var temp=msg['PID']['PID.3'].toString();
var pid=msg['PID']['PID.3'].toString().split("~");
if(temp.toString().charAt(temp.toString().indexOf("~")-1)==">")
{
substr=pid[0].toString().substring(0,pid[0].lastIndexOf("<"));
substr+="</PID.3>";
}
else
{
substr=pid[1].toString().substring(pid[1].toString().indexOf("<"),(pid[1].toString().indexOf(">")+1));
substr=pid[0].toString()+substr;
substr+="</PID.3>";
}
msg['PID']['PID.3']=new XML(substr);

Using Prepared Statement in Mirth

DatabaseConnectionFactory cannot be used for employing prepared statements in mirth. 
So lets use DriverManager connection.

importPackage(java.sql);
new DatabaseDriver();
var dbConn=DriverManager.getConnection(‘url’,’username’,’password’);

Create Platform Independent LF

var outputStream = new java.io.FileOutputStream("/home/amarnath/samp/output/"+$('patientInternalId')+"(inbuilt).NVP");
var writer= new java.io.OutputStreamWriter(outputStream);
writer.write("MRN:"+$('patientInternalId'));
writer.write("\nLast Name:"+$('patientLastName'));    
// THE ABOVE CODE IS PLATFORM DEPENDENT AND VARIES IN DIFFERENT OS

var outputStream = new java.io.FileOutputStream("/home/amarnath/samp/output/"+$('patientInternalId')+"(direct).NVP");
var writer= new java.io.OutputStreamWriter(outputStream);
writer.write("MRN:"+$('patientInternalId')+"\n");
writer.write("Last Name:"+$('patientLastName')+"\n");
//THE ABOVE CODE IS PLATFORM INDEPENDENT AND LOOKS THE SAME IN ALL OS

Testing and Building Missing Segment

These are the two scenarios:

1.) If the NK1 Segment is there – ensure all text is Uppercase.
2.) If the NK1 Segment is missing – create it with null values.

if(msg['NK1'].length()!=0)
{
for each(seg in msg..NK1)
{
var index=seg.childIndex();
var string=seg.toString();
string=string.toUpperCase();
var xml=new XML(string);
msg.children()[index]=xml;
}
}
else
msg['NK1']=””;

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: