Code Templates in Mirth

Mirth is a wonderful tool which has provided options to use generalized functions in the form of code templates. This will improve the performance of the channels in the greater fashion. Code re-usability is a major success of Mirth which is the reason why Code Templates are used for.

Please see the example below.

code templates

Navigate to “Channels” tab in the Left pan of the Mirth navigation bar, create a new Channel or choose any existing channel. When a channel is selected, the options will expand on the left wing of the navigation bar. Select “Edit Code Templates” option there.

You will get a screen like showed below

create library

Note: You will not have any libraries listed at first. Unless you imported a channel from previous version of mirth that might have taken the libraries along with it.

On the right hand side you can see the list of channels that are available in the Mirth tool. You can select the channel that needs this code template to be used. In real time not all channels will use the generalized functions. It depends on the business needs of the channel creation.

Now create a new library to use in your channel by clicking the “New Library” on the left hand side navigation bar. This will list a new library on the dashboard. Please add the description for the library you have created. It is a good practice to write description where ever needed that includes writing the description for the channel even.

Now, be on the same library you have created and select “New Code Template” on the left hand side of the navigation panel. You will be provided with three options on the code template. They are as follows:

  1. Functions
  2. Drag-And-Drop code block
  3. Complied Code Block

I’m going to explain the code templates usage in here by using a simple function. I’m writing a function that will get the segment of the HL7 message and check if the length of the String in the segment is not empty. If the length of the string is 0 or empty then it should alert by saying “Length is irregular”. Below goes the code:

function checkStringLength(data) {
if (data.length != 0) {
data = data;
} else if (data.length == 0) {
data = “Length is irregular”;
return data;

Navigate to Save Changes on the left hand side of the navigation panel. Now The generalized function that has to be used again and again is successfully written in the code template. The purpose becomes meaningful only we know how to access this code, right?…

  1. To execute this. Navigate to the “Channels” tab, and double click on the channel you have created.
  2. Navigate to the Source Tab.
  3. Click on Edit Transformer on the left hand side of the navigation pan.
  4. Now you will see the source transformer dashboard area. Select the type as “Javascript”
  5. In the Right hand side  there will be three tabs available at the top. Reference, message Trees and Message Template. -> Select Message Template.
    Place the HL7 sample message provided below in the template area.

MSH|^~\&|EPICADT|DH|LABADT|DH|201301011226||ADT^A01|HL7MSG00001|P|2.3| EVN|A01|201301011223||
PID|||MRN12345^5^M11||^JOHN^A^III||19710101|M||C|1 DATICA STREET^^MADISON^WI^53005-1020|GL|(414)379-1212|(414)271-3434||S||MRN12345001^2^M10|123456789|987654^NC|

Whatever function we created in the code template will be available ready-made in the Reference tab. I have named the code template as “Check String Length“. As shown in the picture below


So I’m typing “Check String Length” in the Reference tab of the source transformer search area. You will get the function that you have created on the code template area in here directly as shown below

Poin check String length

You can drag and drop the function in your transformer Javascript area. I have just made a printing function that will get the value from the specific segments of the PID 5.1 field of the HL7 message which is basically patient’s first name. And call this function. The code is as below“check String length : “+checkStringLength(msg[‘PID’][‘PID.5’][‘PID.5.2’].toString()));

Now deploy the channel and send the HL7 message pasted above and send it via the dashboard channel by right clicking it. Observe the inferences on both stages when it has a value, it should display the name as it is, When it does not have value it should through the statement in the else part.

Hope it clarifies the question on how to use Code Templates.

Happy Coding & Integration …….

Don’t hesitate to reach out to me if there is any questions on the above part.


Mirth 3.5 Release Notes

Mirth Connect 3.5 introduces around a hundred new features, improvements, and bug fixes. Enhanced filtering for channel names / tags makes it even easier to manage and monitor your interfaces. Filter / Transformer Iterators allow you to loop through segments and fields and map / extract data without having to write any JavaScript. This version also includes enhancements to attachment handlers, destination set filtering, the REST API, and many other features designed to make Mirth Connect channels even more powerful, and at the same time easier to create and manage

Attachment Handler Improvements

Multiple regular expressions, each with their own MIME types, supported in the Regex attachment handler:

  • Regex and JavaScript attachment handlers now support binary data
  • Source map variable replacement supported for MIME types
  • Use attachments across multiple channels

Filter / Transformer Iterators

Iterating through repeating segments / fields has always been possible in Mirth Connect, but now in 3.5 it’s easier than ever, and doesn’t require any custom JavaScript code!

  • Drag-and-drop wizard dialog helps decide what parts of the message to iterate on
  • See the flow control of your transformer scripts at-a-glance, without having to step through code
  • Supports multiple nested iterations

Channel Tag / Filtering Enhancements

Channel tags are easier than ever to configure and use. Simply start typing, and available channels / tags will show up in an auto-completion dialog.

  • Filter by channel tags, partial matches on channel names, or both at the same time
  • Quickly filter down to a specific channel
  • Display colored tag icons next to the channel names on both the Dashboard and Channels views
  • Add / remove / modify multiple tags across multiple channels in just a few clicks

In 3.4 we added Channel Groups for hierarchical organization of channels. These can be used in tandem with channel tags to allow organization from multiple angles! Each channel is under one group, but tags can still apply to multiple channels at once, even across different groups

Destination Set Filtering Improvements

Destination Set Filtering was added back in 3.1, but now in 3.5 you can leverage this powerful feature without having to write any JavaScript!

  • New “Destination Set Filter” type available in the source transformer
  • Remove specific destinations, all except specific destinations, or all destinations

Other Features / Enhancements

  • REST API: Supports basic auth, CORS headers configurable in
  • DICOM Listener: A wide variety of source map variables are now available for use!
  • Database Reader: Now supports aggregating the results of a query into a single consolidated message, instead of dispatching multiple messages for each row
  • Reprocess / Remove Results: Additional confirmation / warnings added, so users cannot accidentally reprocess or remove multiple messages at once.
  • Channel Metadata: Changing pruning settings / tags or enabling / disabling a channel will no longer cause the channel revision to change
  • Password-protected ZIPs: When exporting or archiving messages to compressed ZIP files, you can now specify a password and encryption algorithm.
  • Easy List/Map Creation: New utility classes available in JavaScript contexts to create quick-and-easy Java Lists and Maps.
  • Security Updates: Updated cipher suites for SWEET32 vulnerability. Ephemeral Diffie-Hellman key size now 2048 to finish addressing Logjam. Added clickjack prevention headers to the REST API.

HTTP sender in Javascript

This blog post is about developing HTTP sender in Mirth, without having to send your data via destination.

Suppose, consider a situation when we need to loop through the incoming message and we have to send/post the message multiple time. Mirth do not have the capability to store the loop content variable and pass that to the destination end. So, if you want to loop through the incoming message and send them to HTTP sender, we need to write the Javascript code in the source transformer.

Imagine, that “output” is the variable that contains the looped contents of information in HL7v2 format, now use the below code to invoke HTTTP sender via javascript.

do {
try {
var data = output;
//Destination URL
destURL = ‘http://localhost:8088/’;
var url = new;
var conn = url.openConnection();
conn.setRequestProperty(“Content-length”, data.length());
conn.setRequestProperty(“Content-type”, “text/plain”);
var outStream = conn.getOutputStream();
var outWriter = new;
// Get response Code (200, 500 etc.)
var respCode = conn.getResponseCode();
// get response body
var response = new XML($(‘RESPONSE’)); // XML response message
var status = response[‘Status’].toString();

if (respCode != 200) {
// Write error to error folder
var stringData = response.toString() + ‘\n’;
FileUtil.write(‘C:/Outbox/Errors/’ + $(‘originalFilename’) + ‘.ERROR_RESPONSE’, false, stringData);
// Return Error to Mirth to move the file to the error folder
return ERROR;
errorCond = ‘false’;
catch(err) {
if(retry > 10) {
channelMap.put(‘RESPONSE’, err);
responseMap.put(‘WEBSVC’, ResponseFactory.getErrorResponse(err))
// Can return ERROR, QUEUED, SENT
// This re-queues the message on a fatal error. I’m doing this since any fatal message may be
// caused by HTTPS connect errors etc. The message will be re-queued
return QUEUED; // Re-queue the message
java.lang.Thread.sleep(6000); // 6 seconds * 10

errorCond = ‘true’;
while (errorCond == ‘true’);

Note : This code should be present inside the for loop or the while loop, so that the specific HL7v2 message will be sent/posted to the destination



Parse SOAP response & send HL7V2 ADT

This channel will explain how to parse the SOAP response which will be received from the webservice endpoint which will be a SOAP XML.

Mirth will fetch this XML, parse the SOAP data and convert it into HL7V2 ADT message and send it to the sender.

Mirth :

Have the below HL7v2 available in the POSTMAN of your system. This message will be received by the Mirth as HTTP listener.

MSH|^~\&|TEST|DH|ADT|DH|201301011226||ADT^A08|HG201001|P|2.3|EVN|A08|201301011223||PID|||MRN04160^7^M12||TEST^JACK^R^||19900903|M||2106-3|No5 AskVAsk Street^^Beta^WH^11136-1020|US|(414)222-9595^^^|(414)123-4597|EN|S||MRN27485987^2^M10|986410430|978974^NC||HIN1|Medicare|CD430677||1|||||||IN2|Medicaid|B025546788||1|||||||PD1|02997173|Data|Data2^20161011^20161111^Enrolled^Other||||02693680|Y|Enrolled|||

We will transform this data to the webservice specified format (XML), and the webservice will send a response like the below:

<S:Envelope xmlns:S=”; xmlns:SOAP-ENV=””&gt;
<ns1:addInformation xmlns:ns2=”http://Getdatawebservice/”&gt;
<ErrorReason>Patient deceased</ErrorReason>

Now, we wanted to take the error reason and send it to the sender as HL7V2 response. To do that, go the the Edit Response tab of this destination, and type as below:

var updateMsg= new XML (msg).toString().replace(/:/g,”)
var newMsg= new XML (updateMsg);

var checkError = newmsg[‘SBody’][‘ns1addInformation ‘][‘send’][‘isError’].toString();
var errorMessage = “Message Sent Successfully”;
var errorMessage = newmsg[‘SBody’][‘ns1addInformation ‘][‘send’][‘ErrorReason’].toString();

Now create another destination and create a MSA segment in the outbound template as follows:


Inside the transformer do the following:

tmp[‘MSH’] = $(‘MSH’);
tmp[‘MSA’][‘MSA.2’][‘MSA.2.1’] = $(‘errorMessage’);

Make the destination as Javascript Writer and copy the following code in the code area part

return connectorMessage.getEncodedData();

Deploy the channel, and send the message from the postman and you will get the response like this

MSA||Patient deceased|||


Happy Integrating !!!!!!!!!!!

Write HL7V2 Message to PDF

Scope :

To parse the incoming HL7V2.X message and write it to PDF.


  • MirthConnect : (latest version)

Channel setup :

  1. Create a New channel name it as your wish Here I have named HL7V2 to PDF
  2. Click on Set Data Types button set the source connector inbound to HL7V2.x
  3. Outbound and Destination 1 to Raw
     – that’s it the channel setup is done for it.

Source Transformer :

  • Go to the source transformer and right click to create a new step
  • Name the step as HL7V2 to PDF
  • Select the drop-down of  the step that you have created and select Javascript

Code : 

//MSH Data
var sender = msg[‘MSH’][‘MSH.3’][‘MSH.3.1’].toString();
var receiver = msg[‘MSH’][‘MSH.5’][‘MSH.5.1’].toString();
var messageType = msg[‘MSH’][‘MSH.9’][‘MSH.9.1’].toString();
var messageEvent = msg[‘MSH’][‘MSH.9’][‘MSH.9.2’].toString();
var uniqueId = msg[‘MSH’][‘MSH.10’][‘MSH.10.1’].toString();
//PID Data
var patientName = msg[‘PID’][‘PID.5’][‘PID.5.1’].toString()+” “+msg[‘PID’][‘PID.5’][‘PID.5.2’].toString();
//OBX data
var obxLen = msg[‘OBX’].length();
var obxSetId = msg[‘OBX’][obx][‘OBX.3’][‘OBX.3.1’].toString();

Destination :

  1. Select Document Writer as the destination setup
  2. Provide the directory to be written and the file name to be generated.

HTML Template : 

Design an HTML template with the following code below:


HL7 Message Patient Details

//quotes added to remove wordpress html way



//quotes added to remove wordpress html way
<li><u>Sending Facility</u> : ${sender}</li>
<li><u>Receiving Facility</u> : ${receiver}</li>
<li><u>Message Type </u> : ${messageType}</li>
<li><u>Message Event </u> : ${messageEvent}</li>
<li><u>Control-Id </u> : ${uniqueId}</li>


Destination Configuration :


Sample data for Source :

use the sample data provided here to pass it on to mirth




Status Monitor in Mirth

Consider this scenario,

You are having Mirth in your system. Which is actively running at-least 5 to 10 channels deployed. Each and every channel performs multiple operations within, and they are independent of each other.

Mirth allows a concept of setting alerts if there is a channel that is error, has messages filled in queue, has stopped due to heap space issues or halted. Mirth community edition will trigger an email to your personal mailing system if you run into any of these troubles.

Different Thought :

How about deploying a channel that will act as a tool, which will primarily monitor all the deployed channel and accumulates the status of those channels now and then and form that as an API.

How will it Help?

If you have a multiple mirth instances, which runs multiple channels, this channel can be deployed in each and every mirth instance and that will monitor  status of all the channels been deployed. Using this status accumulated API we can call it in a mobile or any web application to develop as a generalized reporting tool.


  • MirthConnect : (latest version)

Channel Setup:
Source : Javascript Reader

  1. Create a New channel name it as your wish Here I have named MirthMonitor
  2. Click on Set Data Types button set the source connector inbound to Raw
  3. Outbound and Destination 1 to Raw
     – that’s it the channel setup is done for it.

Destination : Channel Writer

Source Transformer Code:

/*Get Deployed Channel ID’s*/
var getDeployedChannelIds = ChannelUtil.getDeployedChannelIds();
var getDeployedChannelIdsCount=getDeployedChannelIds.size();
/*Initialize Array*/
var Totaldata=[];
var monitorObject={};
/*JSON Header*/
monitorObject.Date= DateUtil.getCurrentDate(“yyyyMMdd”);
for (var index = 0; index < getDeployedChannelIds.size(); index++) {
var ChannelID = getDeployedChannelIds.get(index);
var output= JSON.stringify(monitorObject);;

Let us consider that we have deployed three channels in the mirth and are actually running actively. We are now deploying this channel which will run and monitor the status of other channels and produce the outputs in the JSON format.

channel monitor

Output of this channel monitor will be a JSON data as shown below, Here I have deployed three channels and the outputs are monitored and produced below in real-time  for every 5 seconds.

“Date”: “20160831”,
“ClientKey”: “1792cdf1-1926-4438-9d4b-715ac3e45c63”,
“ChannelStats”: [{
“Id”: “f9d9d3ed-59ce-46dd-93cf-309adf0709bb”,
“ChannelName”: “JSON to HL7V2”,
“ReceivedCount”: 31,
“FilterCount”: 0,
“QueuedCount”: 0,
“ErrorCount”: 10,
“SentCount”: 21
}, {
“Id”: “97968dc3-78ba-40e9-960d-b4bee41e961e”,
“ChannelName”: “MirthMonitor-Version2”,
“ReceivedCount”: 4,
“FilterCount”: 0,
“QueuedCount”: 0,
“ErrorCount”: 3,
“SentCount”: 0
}, {
“Id”: “9c1bb1e3-6a4f-4213-b8de-49c16f7ae7e4”,
“ChannelName”: “QRDA – Generator”,
“ReceivedCount”: 25,
“FilterCount”: 0,
“QueuedCount”: 0,
“ErrorCount”: 3,
“SentCount”: 22




Blog at

Up ↑