Friday, September 30, 2022
Home Integration/Interfaces Why You Must Learn Mirth Connect's User API Now

Why You Must Learn Mirth Connect’s User API Now

Prerequisites

  • Basic knowledge of Mirth Connect
  • Basic knowledge of JavaScript
  • Basic knowledge of software documentation and APIs
  • Basic knowledge of Java development

NextGen provides several different APIs (Application Programming Interfaces) that can be leveraged inside your Mirth channels. The main two APIs are:

  • User API
  • Client API

User vs Client API

Before we dive in, you should know the basic differences between the User and Client APIs. The User API is more utilitarian in the sense that it allows you to perform actions that are needed for your channel logic. This could be converting XML to JSON, connecting to a database, or something of that nature. The Client API is focused on more administrative functions. For example, the client API allows you to programmatically deploy a channel.

The other big difference you need to know is that the User and Client are not the same type of API. The Client API is RESTful while the User API is a classic object-oriented style API (Java in this case).

Introduction

This post will only focus on the User API. Interface Developers need to become familiar with the User API as it is fundamental to writing any meaningful code in Mirth. Every fundamental data transformation function, class, data structure, etc. is available in the User API. Mirth professionals must learn the User API well to be successful.

In this post, a few of the most common classes from the User API will be outlined. ChannelUtil, DateUtil, XmlUtil, JsonUtil, DatabaseConnectionFactory, and DatabaseConnection will be demonstrated with various examples.

ChannelUtil

Mirth’s ChannelUtil class provides static utility methods for the channels that you create. These methods allow the developer to programmatically do things that they would normally do manually. For example, if you want to route a message to all channels that have ‘PROD’ in the channel name, you can do the following:

var channelNames = ChannelUtil.getChannelNames();
for(var i = 0; i < channelNames.size(); i++) {
   cName = channelNames.get(i);
   if(cName.includes("PROD")) {
      router.routeMessage(cName,new RawMessage("my message"));
   }
}

First, the code starts by invoking the User API, calling getChannelNames to get a List of all channel names. The code then iterates through the list and sees if the channel name contains ‘PROD’. If it does, then it routes a new raw message to that channel. However, you can obviously build and send a message of any data type.

Another great use of ChannelUtil is to count the number of errors in a given channel. Consider the following code block.

var errCount = ChannelUtil.getErrorCount('My Channel Name');
// write error count to reporting database

First, the number of errors is fetched using ChannelUtil.getErrorCount. It takes a single String that is either the channel name or the channel ID. Once you get the error count, you can do anything with it. Maybe you want to write this value to a reporting database, for example. Maybe you want to trigger an email alert if the error count goes above a certain threshold.

Additionally, say you wanted to know if a specific channel was deployed or not. You could leverage ChannelUtil.getChannelState. This method takes a single String parameter which is either the channel name or the channel ID. This method returns an enumerated type that is one of the following:

  • DEPLOYING
  • PAUSED
  • PAUSING
  • STARTED
  • STARTING
  • STOPPED
  • STOPING
  • SYNCING
  • UNDEPLOYED
  • UNDEPLOYING
  • UNKNOWN

Below, you will see ChannelUtil.getChannelState in action.

var cState = ChannelUtil.getChannelState('My Channel Name')
if(cState == DeployedState.DEPLOYING) {
   // do something
}

The code first grabs the channel’s state. Afterward, it checks if the channel’s state is equal to the enumerated value DEPLOYING. If it is equal then you execute some code to do something.

XmlUtil

Mirth’s XmlUtil class allows developers to perform conversions from XML to other data formats, XML transformations, etc. This channel has fewer channels than ChannelUtil; however, developers will typically use these methods much more frequently.

XmlUtil allows you to pretty print your XML if you have it in String format using XmlUtil.prettyPrint. The method takes one String parameter which is the XML and returns a String that is pretty printed. See the following code.

var xml = "<patientRole><streetAddressLine>1357 Amber Dr</streetAddressLine><city>Beaverton</city></patientRole>";
var prettyXML = XmlUtil.prettyPrint(xml);
channelMap.put('prettyXML',prettyXML);

After running the above, you can view your pretty printed XML in your channel map for a message.

One of the most powerful methods in XmlUtil is toJson. Now, XmlUtil.toJson is actually an overloaded method. However, most of the time you will use XmlUtil.toJson by passing a single String parameter that represents the XML.

Converting XML to JSON is very relevant in Health Integration as the FHIR (Fast Healthcare Interoperability Resources) standard becomes more widely adopted in healthcare systems. You can see XmlUtil.toJson in action below.

var xml = "<Encounter><identifier>12345</identifier><status>arrived</status></Encounter>";
var json = XmlUtil.toJson(xml);
channelMap.put('json',json);

The code above builds an XML string that loosely resembles a FHIR Encounter resource and then invokes XmlUtil.toJson. When you view the json channel map variable, you should see JSON data, not XML data. You will use XmlUtil.toJson a lot if you are making web API calls in your Mirth connect channels because responses are most often delivered in JSON format.

DateUtil

Mirth’s DateUtil class allows developers to quickly create and format date objects. This channel comes in handy when you are trying to insert a date into a file’s name before writing the file or something of that nature. Consider the following example.

var today = DateUtil.getCurrentDate('YYYYMMDD');
channelMap.put('fileName','export_' + today);

The code above grabs today’s date and then builds the file name in the channel map. The file name can then be used in the File Writer destination. Many healthcare systems still read and write from delimited files so this is something that you should become familiar with as a Mirth developer if you are not already. Most often, DateUtil is used in this context.

Another similar method to DateUtil.getCurrentDate is DateUtil.getDate. This method takes two parameters. The first is the date pattern String and the second is the date itself as a String. Consider the following example.

var myDate = DateUtil.getDate('YYYYMMDD','19900101');
channelMap.put('first day of 1990', myDate);

This time, the code simply generates a date that is the first day of 1990 and puts it in the channel map.

DatabaseConnectionFactory and DatabaseConnection

DatabaseConnectionFactory and DatabaseConnection are probably the most important classes in the User API. Mirth developers can use the Database Reader and Database Writer connections to do basic reads and writes to a DBMS (Database Management System). However, there are times where many select, update and delete statements need to be executed from within your channel. This is where DatabaseConnectionFactory and DatabaseConnection come in.

First, Mirth developers must know how to instantiate a DatabaseConnection object using DatabaseConnectionFactory. Consider the following example.

var conn;
try {
    conn = DatabaseConnectionFactory.createDatabaseConnection('org.postgresql.Driver','jdbc:postgresql://servername:5432/dbname','myUser','pass123');
} finally {
   if(conn) {
      conn.close();
   }
}

There are several steps to instantiating a DatabaseConnection. Immediately, you will notice the try and finally blocks. This structure is used because the database connection needs to be closed if it was opened initially. To create a connection, DatabaseConnectionFactory.createDatabaseConnection is invoked.

This method takes four parameters. The first is the driver. In the above example, the driver for a PostgreSQL database driver is used for PostgreSQL. The second parameter is the full JDBC (Java Database Connectivity) connection string. Again, this example is for a PostgreSQL database so make sure you have the right connection string for your database. For example, your connection string would look something like the following if you were trying to connect to an Oracle database.

'jdbc:oracle:thin:@[host]:[port]:[dbname]'

Where [host], [port], and [dbname] are the Oracle database server, port number (1521 typically), and the database name, respectively. The third parameter is your database user and the fourth parameter is the password for that user.

If all of these parameters are correct and the necessary network infrastructure is in place, you will be able to connect to your database.

Now that you have created a DatabaseConnection object, you can create and execute queries. Consider the following:

var getPatientsSQL = "SELECT * "+ 
                     "FROM patients p "+
                     "WHERE p.gender = 'M' AND "+
                     "p.age < 10 ";
var getPatientRS = conn.executeCachedQuery(getPatientsSQL);
while(getPatientRS.next()) {
   // do something
}

The above code executes the query, which fetches all male patients less than 10 years old and then iterates through the result set. Mirth developers can also execute the update, insert, and delete statements using similar methods in the DatabaseConnection class.

Becoming familiar with databases is important to your success as a Mirth Developer. If you need a refresher on your SQL skills then click here to view an article that details SQL basics.

Accessing the Full User API

You may be wondering how you can access the full User API JavaDoc. Login to the Mirth Connect Administrator and simply click View User API at the bottom left-hand corner of the screen in the Other panel.

Your browser will open immediately; however, you will likely get a certificate error that you have to proceed through. If you cannot proceed through the certificate error, you can proceed by typing “thisisunsafe” or “badidea” after you browse to the website. Just start typing the phrase and it will let you proceed. Note: this is not recommended for any other site.

You can also open the JavaDoc via an html file that comes with your Mirth installation. To find this file, navigate to your Mirth Connect installation.

Go into the docs directory.

Go into javadocs > user-api.

Double-click on index.html to view your JavaDoc.

This is exactly how all JavaDoc looks. JavaDoc is the software documentation framework for Java. Since Mirth is Java-based and leverages Java code, all User API documentation is JavaDoc.

First, you should notice a list of packages in the top left-hand corner. Clicking All Classes will show all classes across all packages in the list. If you click a particular package then the JavaDoc will only show classes belonging to that package. In fact, when you click a package, the label ‘Classes’ will change to the name of the package you select.

Click on any class. Now, you should see the class details appear.

Note that any blue text on this page is clickable, allowing you to view the JavaDoc for that Java Class, method, etc.

In the beginning, you will see the inheritance structure for the class. In this instance, ChannelUtil is a child of Java’s Object. TutorialsPoint has a nice web module on Java inheritance if you would like to learn more about this important Object-oriented programming (OOP) concept. Immediately below, you will notice a list of methods. Click on any one of these methods to view the documentation on how to use the method.

The JavaDoc above shows that this is a public static method that returns a List of Strings. Specifically, the method returns every channel name in your Mirth Connect instance. The method takes no parameters.


Now that you understand JavaDoc a little bit better, take some time to explore the entire User API with all of its classes and their methods. Becoming intimately familiar with Mirth’s User API is an important step in becoming a master Interface Developer.

RELATED ARTICLES

Leverage Mirth’s Channel Scripts Now

Prerequisites Basic knowledge of Mirth ConnectBasic knowledge of JavaScript Each Mirth Connect channel gives you the ability to leverage four different scripts that have different triggers,...

Reference a Custom Jar File in Mirth Connect Now

Prerequisites Knowledge of Java developmentKnowledge of Eclipse or another Java IDEKnowledge of Mirth Connect Many Mirth professionals are unaware that they can write their own custom...

Get to Know Mirth’s Configuration Map Now

What exactly is Mirth's configuration map? And how should Mirth developers take advantage of it to create more maintainable channels? Before diving in, it should...

Most Popular

Mirth Connect Extensions: What You Need to Know

Prerequisistes Basic Knowledge of Mirth Connect Overview Users can navigate to Mirth Connect's Extensions screen by selecting Extensions on the left-hand side. You should now see the following...

Take a Tour of System Settings in Mirth Connect Now

Prerequisites Basic Knowledge of Mirth Connect Introduction Mirth Connect has a multitude of system settings that are available for configuration. In larger companies, there will often be...

Why You Must Master Mirth’s Message Template Tool Today

Prerequisuites Basic Knowledge of Mirth ConnectKnowledge of Programming in Mirth Connect Introduction When writing scripts in Mirth Connect, you have a message template tool that allows you...

Make Sense of HL7 v2 Messages Effortlessly Now

Prerequisites Beginner Knowledge of HL7 Introduction If you've been in Healthcare Information Technology for any period of time, you have definitely heard of HL7 (Health Level 7)....

Recent Comments