We can now use this preprocess script to fix the message and send a response when the message is discarded:
//Convert bytesIn to a string
var messageToValidate = new java.lang.String(bytesIn, "UTF-8");
//Split the string up into a string array for each line. Note: newline characters are removed from the array
var sourceArray = messageToValidate.split('\\r?\\n|\\r');
// Create a valid HL7 message header used below to validate each line in the array
var testMSHSegment = 'MSH|^~\\&|ValidationHeader';
//Loop over the array and validate each line
var newLine = '\r\n';
var fixedMessageAsText = '';
for (var i=0 ; i < sourceArray.length ; i++) {
try {
//Try to validate each line by parsing it with a valid MSH segment
qie.parseHL7String(testMSHSegment + newLine + sourceArray[i]);
//If valid, add it to the new message as a new line or complete line
fixedMessageAsText += newLine + sourceArray[i];
} catch (err) {
//If it throws an exception parsing then add it to the new message as a partial line
fixedMessageAsText += sourceArray[i];
}
}
//Convert fixedMessageAsText to a message model
var fixedMessage = qie.parseHL7String(fixedMessageAsText);
//Filter out or discard any message types that are NOT a VXU
var newBytes = fixedMessage.getBytes();
if (!StringUtils.equalsIgnoreCase(fixedMessage.getNode('MSH-9.1'), 'VXU')) {
newBytes = null;
}
//If message was discarded send a response from this script. If the newBytes are not null then the reponse will be handled by the channel.
if (newBytes === null) {
var ackResponse = qie.parseHL7String('MSH|^~\\&|LinkLogic-Test|MHS|');
ackResponse.setNode('MSH-3', fixedMessage.getNode('MSH-5'));
ackResponse.setNode('MSH-4', fixedMessage.getNode('MSH-6'));
ackResponse.setNode('MSH-5', fixedMessage.getNode('MSH-3'));
ackResponse.setNode('MSH-6', fixedMessage.getNode('MSH-4'));
ackResponse.setNode('MSH-7', '20160912034734513');
ackResponse.setNode('MSH-8', fixedMessage.getNode('MSH-8'));
ackResponse.setNode('MSH-9', 'ACK');
ackResponse.setNode('MSH-10', '20160912034734513');
ackResponse.setNode('MSH-11', fixedMessage.getNode('MSH-11'));
ackResponse.setNode('MSH-12', fixedMessage.getNode('MSH-12'));
ackResponse.setNode('MSA-1', 'AA');
ackResponse.setNode('MSA-2', fixedMessage.getNode('MSH-10'));
responseBytes = ackResponse.getBytes();
}
//Set bytesOut to the modified bytes
bytesOut = newBytes;