Function for – Fetching Complete System Specification

This blog provides the code with javascript function that will fetch all the system specification of the system upon which mirth is installed.

This function does not require any input parameter, it will fetch all the statistics of the system in complete real time scenario.

function fetchSystemConfigurations() {

var systemConfiguration = ”;

function memoryCalc(data) {
var kb = data / 1024;
var mb = kb / 1024;
var gb = mb / 1024;

var finalGb = Math.round(gb);
var finalMb = Math.round(mb);
var finalKb = Math.round(kb);

var finalValue;

if (finalGb == 0) {
finalValue = finalMb + ‘MB’;
} else if (finalMb == 0) {
finalValue = finalKb + ‘KB’;
} else if (finalKb == 0) {
finalValue = data + ‘Bytes’;
} else {
finalValue = finalGb + ‘GB’;
return finalValue;

var availableProcessors = “Available Processors : ” + new java.lang.Runtime.getRuntime().availableProcessors();
var freeMemory = “Free Memory : ” + memoryCalc(new java.lang.Runtime.getRuntime().freeMemory());
var osName = “OS Name : ” + new java.lang.System.getProperty(‘’);
var maximumMemory = “Maximum Memory : ” + memoryCalc(new java.lang.Runtime.getRuntime().maxMemory());
var totalJVMMemory = “Total JVM Memory : ” + memoryCalc(new java.lang.Runtime.getRuntime().totalMemory());
var javaVersion = “Java Version : ” + new java.lang.System.getProperty(‘java.version’);
var file = new‘c:’);
var diskFreeSpace = “Disck Free Space : ” + memoryCalc(file.getFreeSpace());
var diskTotalSpace = “Total Disk Space : ” + memoryCalc(file.getTotalSpace());
var hostNameAndIP =;
var splitData = hostNameAndIP.split(“/”);
var hostName = “Host Name : ” + splitData[0];
var IP = “IP : ” + splitData[1];
var processorIdentifier = “Processor Identifier : ” + java.lang.System.getenv(“PROCESSOR_IDENTIFIER”);
var processorArchitecture = “Processor Architecture : ” + java.lang.System.getenv(“PROCESSOR_ARCHITECTURE”);
var javaClassPath = “Java Class Path : ” + new java.lang.System.getProperty(“java.class.path”);

systemConfiguration = availableProcessors + “\n” + freeMemory + “\n” + osName + “\n” + maximumMemory + “\n” + totalJVMMemory + “\n” + javaVersion + “\n” + diskFreeSpace + “\n” + diskTotalSpace + “\n” + IP + “\n” + hostName + “\n” + processorIdentifier + “\n” + processorArchitecture;

return systemConfiguration;

Put the above code in the code template library and call this function anywhere either in transformer or connector or  anywhere.


The output of the code will be as follows:

Available Processors : 4
Free Memory : 116MB
OS Name : Windows 10
Maximum Memory : 228MB
Total JVM Memory : 201MB
Java Version : 1.8.0_151
Disck Free Space : 415GB
Total Disk Space : 465GB
IP :
Host Name : VIBV-BLR-02
Processor Identifier : Intel64 Family 6 Model 142 Stepping 9, GenuineIntel
Processor Architecture : AMD64

Happy Integration ………!!!!!!!!


Perform all File IO operations – Code Templates

In this post, I’m creating the code templates that will do one stop solution for all problems that we face in mirth while doing the File based IO operation.

Imagine a case where you need to move the file from one directory to another via Mirth instead of source or destination connector provided by tool.

In that case:
1. first we need to check if the file exists or not?
2. we have to use FileUtil.write function to write that file to destination location
3. we have to delete the file from the source location.

The performance time required to complete this process will be high. and we have to catch exceptions in correct places. To avoid all these troubles I have developed Mirth code template library that will be one stop solution for all these problem.

This library utilizes apache commons FileUtils library. Download that library from this link here. In that link under binaries select if you are using Windows and commons-io-2.6-bin.tar.gz if you are using linux systems.

apache commons fileutils library

Once downloaded navigate to commons-io-2.6 folder and copy the JAR file named commons-io-2.6 alone. You will also find other JAR files along with that, you can ignore them, you have to copy this and place it in your custom-lib folder of Mirth connect installed directory. Once  done, go to Mirth settings tab and click on Reload Resource.

Provide the following codes in your code template library:

Copy Directory To Directory:

function copyDirectoryToDirectory(sourceDirectory, destinationDirectory) {

var srcDirectory = new;

var destDirectory = new;

try {

var copyDirectoryToDirectory = new, destDirectory);

} catch (exp) {



call from Transformer:

copyDirectoryToDirectory(“C:/Projects/PROJECTS/TEST/Sample Message/PDF-tests/sourcedirectory”,”C:/Projects/PROJECTS/TEST/destinationDirectory”);

Move File To Directory:

function moveFileToDirectory(sourceFileName, destinationDirectoryName) {

var srcFile = new;

var destDir = new;

try {

var moveFileToDirectory = new, destDir, false);

} catch (exp) {



call from Transformer:

moveFileToDirectory(“C:/Projects/PROJECTS/TEST/Sample Message/PDF-tests/test2.pdf”, “C:/Projects/PROJECTS/TEST/Sample Message/”);

Move Directory To Directory:

function moveDirectoryToDirectory(sourceDirectory, destinationDirectory) {

var srcDirectory = new;

var destDirectory = new;

try {

var moveDirectoryToDirectory = new, destDirectory);

} catch (exp) {



call from Transformer:

moveDirectoryToDirectory(“C:/Projects/PROJECTS/TEST/Sample Message/PDF-tests/sourcedirectory”, “C:/Projects/PROJECTS/TEST/destinationDirectory”);

Copy File To Directory:

function copyFileToDirectory(sourceFileName, destinationDirectoryName) {

var srcFile = new;

var destDir = new;

try {

var copyFileToDirectory = new, destDir);

} catch (exp) {




call from Transformer:

copyFileToDirectory(“C:/Projects/PROJECTS/TEST/Sample Message/PDF-tests/test.pdf”, “C:/Projects/PROJECTS/TEST/Sample Message/”);

Integrating – AWS EC2 (MySQL) to Mirth Engine

For this post. I have purchased a personal EC2 instance in AWS environment (a free tier for one year). Specifically an Amazon-AMI Image AWS instance with Fedora Operating System.

In the remote EC2 system, MySQL is deployed and a database is created as test. Once the DB is created in the EC2 instance, you have to create a table with some sample patient demographics information.

How to Access AWS remote server?


Open the putty client and put the AWS amazon hostname in the Host Name or IP adress text box. Else you can put the elastic IP of your AWS instance there. It doesn’t always need to be a complete hostname.

  1. Then select SSH on the left side window of the putty and select on Auth. 
  2. Once you selected Auth on the right window pane click on the Browse button and select the private key you have downloaded from the amazon.
  3. This private key will be a .ppk file. This PPK file will be necessary to establish the SSH connectivity between your putty client and the AWS system.


  1. Once this is done click on the Open button on the bottom.
  2. Once you open you will be prompted to enter the username. If you purchased a Linux Ubuntu System the default user name will be ubuntu.
  3. If you have purchased a different system (say here I have purchased the Amazon AMI system). For the Amazon AMI system you need the password as ec2-user. 
  4. you can install MySQL linux distribution based the version you use. For Amazon AMI linux it uses the Fedora System. For Fedora use this command to install the MySQL. Before executing the below command do the command sudo yum update once.
dnf install mysql-community-server

For the Debian Ubuntu distribution use the below command for the MySQL installation

  • sudo apt-get update
  • sudo apt-get install mysql-server

Once installation is done. Log into your MySQL database on the AWS linux box. You can do this by typing the below command in the putty client box.

mysql -u root -p

Once it is done, you will enter into mysql> type show databases; initially you will not have a new database been created at your end. you have to create a new database for yourself. use the below command and create a new database.

create database test;

This will create a new database. Now we have to use this database and create the tables in it. Use the below command to use this database;

use test;

Here, test is the database name that i’m creating in the box. you can have the name of your choice. Then create a table with the following fields as provided in the screen shot below.


  1. Once you have created it, log on to your AWS web console. And open the port in the security groups on the web console.
  2. Click on Edit button after selecting the security group and then add the port 3306 on TCP.
  3. Only when we do this the inbound socket of your remote system will open, then only your local Mirth system can establish the communication to the system in AWS environment.

In case if you install any application server like the Apache or Tomcat you would initially want to open the specific ports which are specified in the httpd.conf or catalina.conf files. We want to go to the security group on the AWS console and then open enable those inbound ports, then only your (IP+Port) combination will work in the browser, this IP+Port combination is technically referred as Socket.

Create a channel in your local Mirth Connect. make the source to the javascript reader and keep the polling frequency of your interest to fetch the data from the DB. In the source connector area provide the following code.

var dbConn;
// AWS Mysql Credentials
var mySqlDriver = “com.mysql.jdbc.Driver”;
// – Server IP
// 3306 – Mysql Default Port number
// test – Database in Remote server
var mySqlConnectionTemplate = “jdbc:mysql://”;
var mySqlUserName = “root”;

// Create Parent Tag <PatientDemographics>
var patientDemographicsXml = new XML(‘<PatientDemographics></PatientDemographics>’);
// Create Parent for individual patient information <IndividualPatientInformation>
var individualPatientInfoXml = new XML(‘<IndividualPatientInformation></IndividualPatientInformation>’);

try {
// MySQL connection Template
dbConn = DatabaseConnectionFactory.createDatabaseConnection(mySqlDriver, mySqlConnectionTemplate, mySqlUserName, );
// Select statement
// patient_information – is the table name
result = dbConn.executeCachedQuery(“select * from patient_information“);

// Loop through the resultset value
while ( {
individualPatientInfoXml[‘PatientId’] = result.getInt(“pid”);
individualPatientInfoXml[‘PatientFirstName’] = result.getString(“patient_first_name”);
individualPatientInfoXml[‘PatientLastName’] = result.getString(“patient_last_name”);
individualPatientInfoXml[‘PatientMiddleName’] = result.getString(“patient_middle_ name”);
individualPatientInfoXml[‘PatientSuffixName’] = result.getString(“patient_suffix_name”);
individualPatientInfoXml[‘PatientDateOfBirth’] = result.getString(“patient_date_of_birth”);
individualPatientInfoXml[‘PatientGender’] = result.getString(“patient_gender”);
individualPatientInfoXml[‘PatientAge’] = result.getInt(“patient_age”);
individualPatientInfoXml[‘PatientAddress1’] = result.getString(“patient_address_1”);
individualPatientInfoXml[‘PatientAddress2’] = result.getString(“patient_address_2”);
individualPatientInfoXml[‘PatientEmailAddress’] = result.getString(“patient_emailAddress”);
individualPatientInfoXml[‘PatientTelecomNumber’] = result.getString(“patient_telecom_number”);
individualPatientInfoXml[‘PatientRace’] = result.getString(“patient_race”);
individualPatientInfoXml[‘PatientEthincity’] = result.getString(“patient_ethincity”);
individualPatientInfoXml[‘PatientMaritalStatus’] = result.getString(“patient_maritalstatus”);
individualPatientInfoXml[‘PatientLanguage’] = result.getString(“patient_language”);
individualPatientInfoXml[‘PatientCountry’] = result.getString(“patient_country”);
individualPatientInfoXml[‘PatientState’] = result.getString(“patient_state”);
individualPatientInfoXml[‘PatientCity’] = result.getString(“patient_city”);
individualPatientInfoXml[‘PatientZipCode’] = result.getString(“patient_zipcode”);
individualPatientInfoXml[‘PatientSSN’] = result.getString(“patient_ssn”);
individualPatientInfoXml[‘PatientDriverLicense’] = result.getString(“patient_driver_license”);

patientDemographicsXml[‘PatientDemographics’] += individualPatientInfoXml;

individualPatientInfoXml = new XML(‘<IndividualPatientInformation></IndividualPatientInformation>’);

msg = patientDemographicsXml;

return msg;

} finally {
if (dbConn) {

Once the connector code is created then you will be able to fetch all the data which are available in the database as a batch, instead of single row entries. You will be able to accumulate all the data from the database on each row as shown below:


These data will be accumulated inside mirth as a XML data created in batch and the output of your mirth data will be as shown below:

<PatientAddress1>No:8, washington, test drive</PatientAddress1>
<PatientAddress2>Oregan, detroit</PatientAddress2>
<PatientAddress1>4/12 Stevie Street, jj colony</PatientAddress1>
<PatientAddress2>Michigan, detroit</PatientAddress2>

Happy Integrations !!!!!


How to create Zip file with multiple files in Mirth?

var zipFile = “c:\\”;
var sourceFiles= new Array(${arrayOfFileNames});

try {

var buffer = java.lang.reflect.Array.newInstance(java.lang.Byte.TYPE, 5000);
var fileOutput = new;
var zos = new;

for (i = 0; i < sourceFiles.length; i++) {

var srcFile = new[i]);
var fis = new;

var length;

while ((length = > 0) {
zos.write(buffer, 0, length);

} catch (ioe) {
logger.debug(“Error creating zip file: ” + ioe);

Paste the above provided code in the destination Javascript Writer. It does not require any external Java libraries to achieve this task as well.


Happy Integrating……

Parse responses in response tab

Imagine that we are sending certain data to external sources and we are getting response from those source. Now the received response has to be parsed inside the response tab.


Imagine we are receiving an HTML response like this as provided below:

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN” “”&gt;
<html xmlns=””&gt;
<meta http-equiv=”Content-Type” content=”text/html; charset=iso-8859-1″/>
<title>401 – Unauthorized: Access is denied due to invalid credentials.</title>
<style type=”text/css”>
body{margin:0;font-size:.7em;font-family:Verdana, Arial, Helvetica, sans-serif;background:#EEEEEE;}
fieldset{padding:0 15px 10px 15px;}
h3{font-size:1.2em;margin:10px 0 0 0;color:#000000;}
#header{width:96%;margin:0 0 0 0;padding:6px 2% 6px 2%;font-family:”trebuchet MS”, Verdana, sans-serif;color:#FFF;
#content{margin:0 0 0 2%;position:relative;}

401 – Unauthorized: Access is denied due to invalid credentials.

You do not have permission to view this directory or page using the credentials that you supplied.


We need to get the status that we are receiving on this and make business logic accordingly. For example,  here on this HTML response we are supposed to parse the status value 401, and if it is 401 then we need to perform actions accordingly.

This can be achieved by using external library called JSOUP that is used for parsing HTML via JAVA. download the jsoup jar library and then test it in the JAVA first using any version of eclipse. Find the JAVA code below:

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

public class TestHtml {
public void htmlDataReader() {
String htmlData =””; // your html string
Document doc = Jsoup.parse(htmlData);
Document doc = Jsoup.parse(htmlData);
Elements tds = doc.getElementsByTag(“h2”);
String text = tds.text();
System.out.println(“Data : “+ text.substring(0,3));
public static void main (String args[]) {
TestHtml val =  new TestHtml();

Output : Data: 401

The corresponding Mirth code for the above JAVA code will be as follows:

var doc = Jsoup.parse(msg);
var tds = doc.getElementsByTag(“h2”);
var text = tds.text();
var responseStatusValue = text.substring(0,3);
logger.debug(“Data : “+ text.substring(0,3));
// Business logic below of your choice


If we are going to parse the HTML data through mirth itself without using any external library, then it is little challenging because the tag <!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN” “”> is expected to come in HTML, but ex4 will not be considering this element as a XML tag. So mirth will not take this data as a XML and allow us to parse the message as normal XML.

Make your source listener as RAW instead of XML then only it will be consumed inside Mirth. In the pre-processor of the mirth write the following code:

var pattern = $gc(‘pattern’);
if (!pattern) {
pattern = java.util.regex.Pattern.compile(‘^(\\s*(<\\?xml.*\\?>)?\\s*(<!DOCTYPE[^\\[>]*(\\[\\s*(<![^>]*>\\s*)*\\])?[^>]*>)?\\s*)’);
$gc(‘pattern’, pattern);
var prolog = ”;
var matcher = pattern.matcher(message);
if (matcher.find()) {
prolog =;
message = message.substring(0, matcher.start(1)) + message.substring(matcher.end(1));
$c(‘prolog’, prolog);
return message;

Inside the source transformer provide the following code. you can use ‘msg’ inside the source transformer since, those DOCTYPE! will be removed inside the pre-processor. Your pre-processor is the first place where your code reaches at first followed by other stages of mirth interface engine.

var responseData = msg[‘body’][‘div’][1][‘div’][‘fieldset’][‘h2’].toString();
var responseData = msg[‘body’][‘div’][1][‘div’][‘fieldset’][‘h2’].toString();
var responseDataStatus = responseData.substring(0,3);
logger.debug(“RESPONSE DATA : “+responseDataStatus);
// Your business Logic


You can also perform this activity in the summary of the channel. As shown in the picture below:

summary javascript

Click on the properties tab, and provide the following code. This code is basically the replace code that we will be using to remove the incoming namespace.

message.replace(‘<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN” “”>&#8217;,”);
return message;

Similar to the scripts tab, we should be using message here instead of msg. From 3.4 version mirth has made this javascript properties tab available in the summary of the channel, which will be executed at first instead of the pre-processor.

Inside transformer we can use the code that we have used for Approach 2 directly. it will work fine.


If we want the same to be achieved in response tab, then we cannot use approach 2 or approach 3. In that case we can use the inbuilt function $(‘responseStatusLine’) which will contain the corresponding HTTP responses such as 500,401 or 200.

We can call this function directly and use it in response transformer as provided below:

//Your business logic goes here…

Mirth – DB Reader

In the Mirth tool, often people face many issues when it comes to connecting to DB either fetching data or updating/inserting data. This blog post will help you understand what are functions used for what purposes.

Starting with the Database reader concept, there are multiple misconception that needs to be clarified. Not everything are understood as the name portrays, the tool has its own definition of most of the areas and buttons.

polling settings

The option Poll Once on Start means that the database channel will start to poll the database once it is deployed. In-case if NO is selected for this option then, the channel will start to fetch the data from the database in the specified interval of time.


The option Process Batch is used, when the data are coming in batches and there is a necessity to split the data into separate batches. You may wonder, how data will come in batch from the database?. Seems there is a option available to make such polling of data from the DB. In that case you will select YES for the Process Batch and the split the incoming. In usual case, the option NO has to be selected.


Please note that the URL tab for SQL Server will be different than other traditional relational databases. Instead of IP & port in the connection string we may need to use the SQL server name or the system name. When you assign the special or custom user (sa in this example) specific to certain database then your port number will not be the usual default SQL server database port (i.e 1443). To check the port number that you are accessing the data use the following query.

USE master
xp_readerrorlog 0, 1, N’Server is listening on’

Apart from this, the other major misconception is the usage of Javascript. This will be either YES or NO. But in either case we just have to remember one thing that, this will be the triggering action that will be performed on the database. Mirth will poll the database by using the query that we write in the below area.

sql javascript

You can either use this SQL javascript area just for triggering the database by using a query, and perform the logic inside the transformers. Else some people prefer to write logic in the connector area itself by pressing YES on the using Javascript radio button.

But, if you decide to write logic in the SQL javascript area in the source, you will have to face certain limitations. Like the following:

  1. The variable used inside the SQL javascript text area cannot be used in the next javascript text area (i.e  Post-processor javascript). So just in-case you have to update a data using the data fetched previously the SQL javascript area, it will not work well.
  2. You do not have the liberty of using channelMap variable inside the SQL javascript editor area, neither the globalMap. In both the cases it will throw error.
  3. Said that, the result set value will be returned to the source transformer which can be used to process the data of our interest.

Most, misconception of all is how can we fetch data (i.e process). Mirth will fetch data from the Database only in the one-by-one row manner. There is no such possibility available in mirth to fetch 10 or 15 or 100 rows in single stretch. It’s Mirth a tool, not hulk. 🙂

Hope it clarifies some questions.

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/&#8217;;
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 ↑