web stats
Mirth Tools: User defined functions - Page 3 - Mirth Community

Go Back   Mirth Community > Mirth Connect > Support

Reply
 
Thread Tools Display Modes
  #21  
Old 02-13-2013, 07:43 AM
narupley's Avatar
narupley narupley is online now
Mirth Employee
 
Join Date: Oct 2010
Posts: 7,050
narupley is on a distinguished road
Default

Just letting you guys know that I've updated getSegmentsAfter so that a regular expression (RegExp object) can be passed in for segName, allowing you to return more than one type of segment at once (e.g. IN1/IN2/IN3, Z-Segments, etc.).
__________________
Step 1: JAVA CACHE...DID YOU CLEAR ...wait, ding dong the witch is dead?

Nicholas Rupley
Work: 949-237-6069
Always include what Mirth Connect version you're working with. Also include (if applicable) the code you're using and full stacktraces for errors (use CODE tags). Posting your entire channel is helpful as well; make sure to scrub any PHI/passwords first.


- How do I foo?
- You just bar.
Reply With Quote
  #22  
Old 03-29-2013, 09:56 AM
narupley's Avatar
narupley narupley is online now
Mirth Employee
 
Join Date: Oct 2010
Posts: 7,050
narupley is on a distinguished road
Default Strip Empty Nodes from XML

Quote:
UPDATE: I've created a public GitHub repository to track these example channels, code templates, scripts, or whatever else!

https://github.com/nextgenhealthcare/connect-examples

To start with I only added the ones I wrote, because I didn't want to presume and add code from others without their explicit permission. Pull requests welcome!
stripEmptyNodes: Recursively iterates through all descendant nodes of an E4X XML object and removes those that are empty (or those whose children are all empty).

Parameters:
  • node: The node to iterate through. If node itself is empty, it will not be removed from its parent.

Examples:
  • Get rid of all empty nodes in the inbound XML structure (msg):
    Code:
    stripEmptyNodes(msg);

The code:

Code:
function stripEmptyNodes(node) {
	var name = '', index = -1;
	for each (child in node.children()) {
		index = (name != child.name() ? 0 : index+1);
		name = child.name();
		stripEmptyNodes(child);
		if (!child.toString())
			delete node[child.name()][index];
	}
}
Attached Files
File Type: xml stripEmptyNodes.xml (678 Bytes, 150 views)
__________________
Step 1: JAVA CACHE...DID YOU CLEAR ...wait, ding dong the witch is dead?

Nicholas Rupley
Work: 949-237-6069
Always include what Mirth Connect version you're working with. Also include (if applicable) the code you're using and full stacktraces for errors (use CODE tags). Posting your entire channel is helpful as well; make sure to scrub any PHI/passwords first.


- How do I foo?
- You just bar.

Last edited by narupley; 06-08-2018 at 10:35 AM.
Reply With Quote
  #23  
Old 04-24-2013, 03:47 PM
narupley's Avatar
narupley narupley is online now
Mirth Employee
 
Join Date: Oct 2010
Posts: 7,050
narupley is on a distinguished road
Default

Quote:
UPDATE: I've created a public GitHub repository to track these example channels, code templates, scripts, or whatever else!

https://github.com/nextgenhealthcare/connect-examples

To start with I only added the ones I wrote, because I didn't want to presume and add code from others without their explicit permission. Pull requests welcome!
Pursuant to a recent thread asking for this, I've expanded the stripEmptyNodes function to do more cool stuff.

stripEmptyNodes: Recursively iterates through all descendant nodes of an E4X XML object and removes those that are empty (or those whose children are all empty).

Parameters:
  • node: The node to iterate through. If node itself is empty, it will not be removed from its parent.
  • stripWhitespaceNodes: If true, nodes that are not empty but only contain whitespace will also be removed.
  • onlyDeleteTrailing: If true, only trailing nodes will actually be deleted. For example if a child set has five nodes at the end which are all empty, all five will be removed. However if the same five nodes are followed by a node which isn't empty, then those five nodes will not be removed. Instead, the nodes will simply have their inner text elements removed (if necessary).

Examples:
  • Get rid of all empty nodes in the inbound XML structure (msg):
    Code:
    stripEmptyNodes(msg);
  • Get rid of all blank (empty and whitespace-only) nodes in the inbound XML structure:
    Code:
    stripEmptyNodes(msg,true);
  • Delete any trailing blank nodes, and replace any non-trailing whitespace-only nodes with empty nodes:
    Code:
    stripEmptyNodes(msg,true,true);

The code:

Code:
function stripEmptyNodes(node, stripWhitespaceNodes, onlyDeleteTrailing) {
	var nonEmptyFound = false;
	for (var childIndex = node.children().length()-1; childIndex >= 0; childIndex--) {
		var child = node.children()[childIndex];
		stripEmptyNodes(child,stripWhitespaceNodes,onlyDeleteTrailing);
		if (stripWhitespaceNodes && !child.toString().trim() || !stripWhitespaceNodes && !child.toString())
			if (!nonEmptyFound || !onlyDeleteTrailing)
				delete node.children()[childIndex];
			else
				node.children()[childIndex] = new XML('<'+child.name().toString()+'/>');
		else
			nonEmptyFound = true;
	}
}
Attached Files
File Type: xml stripEmptyNodes (new 4-24-13).xml (1.0 KB, 173 views)
__________________
Step 1: JAVA CACHE...DID YOU CLEAR ...wait, ding dong the witch is dead?

Nicholas Rupley
Work: 949-237-6069
Always include what Mirth Connect version you're working with. Also include (if applicable) the code you're using and full stacktraces for errors (use CODE tags). Posting your entire channel is helpful as well; make sure to scrub any PHI/passwords first.


- How do I foo?
- You just bar.

Last edited by narupley; 06-08-2018 at 10:35 AM.
Reply With Quote
  #24  
Old 05-22-2013, 01:13 PM
ericb ericb is offline
Mirth Employee
 
Join Date: May 2009
Posts: 19
ericb is on a distinguished road
Default

Nick/Jake,

It seems like some of these functions would be universally useful. Have you guys considered adding them to the standard code templates for 3.x?
Reply With Quote
  #25  
Old 05-30-2013, 11:18 PM
adsseoalpha adsseoalpha is offline
What's HL7?
 
Join Date: May 2013
Location: delhi
Posts: 3
adsseoalpha is on a distinguished road
Default hi...here is some info for you

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.
__________________
signage

Last edited by narupley; 09-30-2013 at 06:35 AM.
Reply With Quote
  #26  
Old 05-30-2013, 11:24 PM
adsseoalpha adsseoalpha is offline
What's HL7?
 
Join Date: May 2013
Location: delhi
Posts: 3
adsseoalpha is on a distinguished road
Default hi...here is some info for you

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.
__________________
signage

Last edited by narupley; 09-30-2013 at 06:35 AM.
Reply With Quote
  #27  
Old 12-06-2013, 01:20 PM
narupley's Avatar
narupley narupley is online now
Mirth Employee
 
Join Date: Oct 2010
Posts: 7,050
narupley is on a distinguished road
Default Convert Date from Multiple Formats/Sources

Quote:
UPDATE: I've created a public GitHub repository to track these example channels, code templates, scripts, or whatever else!

https://github.com/nextgenhealthcare/connect-examples

To start with I only added the ones I wrote, because I didn't want to presume and add code from others without their explicit permission. Pull requests welcome!
convertDate: Parses a date (String, Date, DateTime, or Number) into a string using an array of possible input patterns and the specified output pattern.

This is useful if you want to convert/standardize an incoming date, but you don't know how it will be formatted. The code comes with an array of possible patterns, and if there is a pattern you encounter that isn't handled, you can simply add it to the list.

Parameters:
  • date: The object to convert. The object may be a String, Date, DateTime, or Number (or really any object, as long as its string representation is some formatted date).
  • outpattern: The pattern to use when converting the date to the output string.

Example:
  • Standardize the message date/time to a specific pattern, no matter what pattern it comes in as:
    Code:
    msg['MSH']['MSH.7']['MSH.7.1'] = convertDate(msg['MSH']['MSH.7']['MSH.7.1'].toString(), 'yyyyMMddHHmmss');

The Code:

Code:
var patterns = [
	'yyyy-MM-dd HH:mm:ss:SSS',
	'yyyy-MM-dd HH:mm:ss.SSS',
	'yyyy-MM-dd HH:mm:ss',
	'yyyy-MM-dd HH:mm',
	'EEE MMM dd HH:mm:ss:SSS zzz yyyy',
	'EEE MMM dd HH:mm:ss.SSS zzz yyyy',
	'EEE MMM dd HH:mm:ss zzz yyyy',
	'EEE MMM dd zzz yyyy',
	'dd-MMM-yyyy HH:mm:ss:SSS',
	'dd-MMM-yyyy HH:mm:ss.SSS',
	'dd-MMM-yyyy HH:mm:ss',
	'yyyy-MM-dd',
	'yyyy MM dd',
	'yyyy.MM.dd',
	'MM-dd-yyyy',
	'MM dd yyyy',
	'MM.dd.yyyy',
	'HH:mm:ss:SSS',
	'HH:mm:ss.SSS',
	'HH:mm:ss',
	'yyyyMMddHHmmssSSS',
	'yyyyMMddHHmmss',
	'yyyyMMddHHmm',
	'hh:mm aa'];

var formatters = [];
for each (pattern in patterns) {
	formatters.push(org.joda.time.format.DateTimeFormat.forPattern(pattern));
}

function convertDate(date, outpattern) {
	var instant = 0;
	if (typeof date == 'number' || date instanceof java.lang.Number)
		instant = new Number(date);
	else if (date instanceof Date || date instanceof java.util.Date)
		instant = date.getTime();
	else if (date instanceof org.joda.time.ReadableInstant)
		instant = date.getMillis();
	else {
		for each (formatter in formatters) {
			try {
				instant = formatter.parseMillis(new String(date));
				break;
			} catch(e) {}
		}
	}

	return org.joda.time.format.DateTimeFormat.forPattern(outpattern).print(instant);
}
Attached Files
File Type: xml convertDate.xml (1.8 KB, 223 views)
__________________
Step 1: JAVA CACHE...DID YOU CLEAR ...wait, ding dong the witch is dead?

Nicholas Rupley
Work: 949-237-6069
Always include what Mirth Connect version you're working with. Also include (if applicable) the code you're using and full stacktraces for errors (use CODE tags). Posting your entire channel is helpful as well; make sure to scrub any PHI/passwords first.


- How do I foo?
- You just bar.

Last edited by narupley; 06-08-2018 at 10:36 AM.
Reply With Quote
  #28  
Old 12-09-2013, 03:24 PM
mankowitz mankowitz is offline
Mirth Newb
 
Join Date: Oct 2013
Posts: 8
mankowitz is on a distinguished road
Smile javascript escape for sql, mysql

In some of my channels, I need to use javascript to apply changes to a MySQL database. The problem is that data needs to be esacaped. I have used the below functions which have saved me time.

Code:
function mq_escape(s) {
    if (s==null) return null;
	var str = s.toString() + "";
    return str.replace(/[\0\x08\x09\x1a\n\r"'\\\%]/g, function (char) {
        switch (char) {
            case "\0":
                return "\\0";
            case "\x08":
                return "\\b";
            case "\x09":
                return "\\t";
            case "\x1a":
                return "\\z";
            case "\n":
                return "\\n";
            case "\r":
                return "\\r";
            case "\"":
            case "'":
            case "\\":
            case "%":
                return "\\"+char; // prepends a backslash to backslash, percent,
                                  // and double/single quotes
        }
    });
}


function escaper(match, p) {
 // match is the whole string, p is the first parenthesized text
 // in this case, p is the text between the % signs.
 if ($(p)=="" || $(p)=="null" || $(p)==null) return "null";
 else return "'" + mq_escape($(p)) + "'"; 
}

function mq(db, sql) {
sql = sql.replace(/%([^%]+)%/g, escaper);
db.executeUpdate(sql); 
}
Which then allows you to do something like this:

Code:
var dbConn = DatabaseConnectionFactory.createDatabaseConnection('com.mysql.jdbc.Driver','jdbc:mysql://localhost:3306/documenter','hl7user','zzzzzzz');

mq(dbConn, "UPDATE documenter.tblmaster " + 
"SET FirstName = %pt_firstname%, " + 
"LastName = %pt_lastname%, " + 
"MRN = %pt_MRN%, " +
"ChiefComplaint = %visit_reason%, " + 
"MD = %PV1_md_id%, PMD = %PD1_pmd_id%, DOB = %pt_DOB%, " + 
"Sex = %pt_Sex%, " + 
"Weight = COALESCE(Weight, %weightKg%) " + 
"WHERE account = %pt_account%");
Reply With Quote
  #29  
Old 01-23-2014, 07:47 AM
narupley's Avatar
narupley narupley is online now
Mirth Employee
 
Join Date: Oct 2010
Posts: 7,050
narupley is on a distinguished road
Default Automatically overwrite the log4j categories used in user scripts

Quote:
UPDATE: I've created a public GitHub repository to track these example channels, code templates, scripts, or whatever else!

https://github.com/nextgenhealthcare/connect-examples

To start with I only added the ones I wrote, because I didn't want to presume and add code from others without their explicit permission. Pull requests welcome!
overwriteCategories: Overwrites the categories of Logger objects placed in JavaScript contexts.

When you call "logger.info('something');" in a user-defined script, you'll see something like this in the server log:

Code:
[2014-01-23 08:36:32,862]  INFO  (transformer:?): something
In a recent thread, someone was asking whether it's possible to change the category ("transformer") that shows up to something custom, without having to edit log4j.properties and restart the server. The answer is yes, it's definitely possible, and this code template can do that for you.

All you have to do is import the code template, redeploy your channels, and it'll start working, except for transformer scripts. Because of how we handle the filter/transformer, in order to get this to work in a transformer script you'll just have to add this line at the top of the first step in your transformer:

Code:
overwriteCategories();
Note that the above is only necessary for the regular transformer, not for response transformers, filters, deploy/shutdown/preprocessor/postprocessor scripts, Database/JavaScript connectors, or attachment/batch scripts.

The Code:

Code:
/* 
 * NOTE: This will work automatically for all contexts except for
 * the transformer. For transformers, you will need to manually
 * include "overwriteCategories();" at the beginning of your first step.
 */

function overwriteCategories() {
	logger = org.apache.log4j.Logger.getLogger({
		'transformer':		'custom-transformer',
		'preprocessor':		'custom-preprocessor',
		'postprocessor':	'custom-postprocessor',
		'deploy':		'custom-deploy',
		'shutdown':		'custom-shutdown',
		'filter':		'custom-filter',
		'db-connector':		'custom-db-connector',
		'js-connector':		'custom-js-connector',
		'attachment':		'custom-attachment',
		'batch':		'custom-batch',
		'response':		'custom-response'
	}[logger.getName()]);
	logger.setLevel(org.apache.log4j.Level.DEBUG);
}

overwriteCategories();
Obviously, you will want to switch out the "custom-*" strings for your own custom categories.
Attached Files
File Type: xml overwriteCategories.xml (1.3 KB, 75 views)
__________________
Step 1: JAVA CACHE...DID YOU CLEAR ...wait, ding dong the witch is dead?

Nicholas Rupley
Work: 949-237-6069
Always include what Mirth Connect version you're working with. Also include (if applicable) the code you're using and full stacktraces for errors (use CODE tags). Posting your entire channel is helpful as well; make sure to scrub any PHI/passwords first.


- How do I foo?
- You just bar.

Last edited by narupley; 06-08-2018 at 10:36 AM.
Reply With Quote
  #30  
Old 07-30-2014, 05:59 AM
cmcwhorter cmcwhorter is offline
OBX.2 Kenobi
 
Join Date: Apr 2008
Location: Texas
Posts: 89
cmcwhorter
Default

Version 3.0.3 of Mirth Connect. Function to Stop a channel if it reaches a particular error count. Also sends an alert message via another channel. Big Nod to Mirth Support for helping me figure out how to do this in version 3.0.3.

Code In Postprocessor of Scripts tab of Channel:

// will stop the current channel when errorcount greater than 10.

var numOfErrors = ChannelUtil.getErrorCount(channelId);

if(numOfErrors > 10)
{
ChannelUtil.stopChannel(channelId);
var channelName = ChannelUtil.getDeployedChannelName(channelId);
alert = 'channel ' + channelName + ' has been stopped with >10 errors';
router.routeMessage('email_Alerts', alert);
}
return;
__________________
cmc
Reply With Quote
Reply

Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT -8. The time now is 12:41 AM.


Powered by vBulletin® Version 3.8.7
Copyright ©2000 - 2018, vBulletin Solutions, Inc.
Mirth Corporation