How stop execution and send ack/nack with error message in mirth 3.4? - mirth

I'm new in mirth so sorry if my question may seems naive.
I've a mirth channel that recives hl7 messages, and this is fine, also I've some filters and transformers both in Source and Destination.
When all is fine at the end of destination I send an ACK with a message, for this for this purpose I've made this function in code Templates:
function getAck(success, detailMessage, statusMessage) {
if (!detailMessage)
detailMessage = success ? "Operation completed successfully" : "Some error occours";
if(!statusMessage)
statusMessage = detailMessage;
if (success) {
ack = ACKGenerator.generateAckResponse(connectorMessage.getRawData(), "AA", detailMessage);
resp = new Response(com.mirth.connect.userutil.Status.SENT, ack, statusMessage);
} else {
ack = ACKGenerator.generateAckResponse(connectorMessage.getRawData(), "AE", detailMessage);
resp = new Response(com.mirth.connect.userutil.Status.ERROR, ack, statusMessage, detailMessage);
}
return resp;
}
So I use ACKGenerator.generateAckResponse for creating an Ack and Response for send response at client. This work but only in destination and that's my problem.
If I get an error before destination (e.g. in filters, transformer, ...) I don't be able to stop execution and send an NACK with an explaination of the error and this is what I would like to do.
Am I wrong doing things in this way?

You can store a Response in the responseMap in any filters or transformers. Once you define a key in the responseMap, it should be available as a selection in the response drop down on the source tab of your channel (instead of picking a destination.)
Your current connector should stop processing a message with an ERROR status if you manually throw an exception after setting the desired value in the responseMap. If you are in a filter, you could also filter the message instead of throwing the exception.
If you are worried about an uncaught exception, you could initialize the responseMap variable with an "Unknown Error" message at the first point in the channel where your custom code is defined that affects messages directly (likely the source filter from your description, but could possibly be the pre-processor or attachment handler if you use those.) The expectation is that this would be replaced with a more descriptive error or a success if the message makes it all the way through to the end, but the channel will always have something to return.

There are filter and transformer in the "Source" tab. If your expecting an error there or on other destinations, you could try:
Adding a try-catch code block in your filter and transformer.
Use your custom code template function in your filter and transformer to catch the error or issue.
Create a separate channel that will receive the ACK/NACK which will be responsible in forwarding that message to the client.
In your try-catch code block or custom code template, use the method router.routeMessageByChannelId to forward the ACK/NACK to the other channel (step 3).
Note: You'll need to disable the default response in your original channel since you have the other channel that'll forward the ACK/NACK. You'll also need to consider if the client's machine expects a valid ACK/NACK immediately when they sent the HL7 message, depends on their setup.

Related

Azure Service Bus Queue gives control characters in fetched message

I am using BizTalk Server SB-Messaging adapter to retreive messages from Azure Service Bus Queue. I have successfully managed to send message to queue myself (using same adapter), and retreive message from queue and do further processing.
Problem arises when a 3rd party software supplier is sending messages to the queue, and for BizTalk Server to retreive and process message. I then receive the following additional "header"-information and control characters in the beginning of the message:
In text: #ACKstringBShttp://schemas.microsoft.com/2003/10/Serialization/?$SOH
Seems like there is some sort of enveloped message, including headers to handle ACKnowledgement of the message to the queue.
SB-Messaging adapter gave following initial error message:
"The WCF service host at address has faulted and as a result no
more messages can be received on the corresponding receive location.
To fix the issue, BizTalk Server will automatically attempt to restart
the service host."
And, another error message:
"No Disassemble stage components can recognize the data."
Did anyone hit this problem before, and, what can be the cause of the problem? Can character encoding be a possible cause of this problem?
Here comes the feedback!
Turned out 3rd party software supplier had a setting to send message as stream, instead of string. Turns out it is a .Net application using BrokeredMessage object. Using string makes message serialized, and meta-data is added to the message. Using stream, no such serialization takes place, and message is kept untouched.
So, problem was using string and automatic serialization when sending to Service Bus Queue.
I have legacy Microsoft.ServiceBus.Messaging clients sending BrokeredMessage Xml content as <string> and I want to receive using the latest Microsoft.Azure.ServiceBus library and Message type.
Using Encoding.UTF8.GetString(message.Body) I get a unusable string prefaced with
#\u0006string\b3http://schemas.microsoft.com/2003/10/Serialization/��#
My approach is to explicitly use XmlDictionaryReader binary deserialization to undo the hidden serialization magic from the legacy library
private static string GetMessageBodyHandlingLegacyBrokeredMessage(Message message)
{
string str = null;
if (message.ContentType == null)
{
using (var reader = XmlDictionaryReader.CreateBinaryReader(
new MemoryStream(message.Body),
null,
XmlDictionaryReaderQuotas.Max))
{
var doc = new XmlDocument();
doc.Load(reader);
str = doc.InnerText;
}
}
else
throw new NotImplementedException("Unhandled Service Bus ContentType " + message.ContentType);
return str;
}
References
https://learn.microsoft.com/en-us/azure/service-bus-messaging/service-bus-messages-payloads#payload-serialization
https://carlos.mendible.com/2016/07/17/step-by-step-net-core-azure-service-bus-and-amqp/

Debugging Transformer Errors in Mirth Connect Server Log

Fairly new to Mirth, so looking for advice in regards to debugging/getting more information from errors reported in the Server Log in Mirth Connect. I know what channel this is originating from, but that's about it. This error is received 10 times for each message coming through. It should be noted that the channel is working properly except for this error cluttering up the logs.
The Error:
ERROR (transformer:?): TypeError: undefined is not an xml object.
What I've Tried:
Ruled out Channel Map variables (mappers), they don't have null default values, they match up with vars in the incoming xml message, even changed to Javascript transformers to modify the catch to try to narrow down the issue, but no luck.
Modified external javascript source files to include more error handling (wrapped each file in a try/catch that would log with identifying info) but this didn't change the result at all.
Added a new Alert to send info if errors are received, but this alert never fired.
Anything else to try? Thanks for any/all help!
This is a Rhino message that happens when you use an e4x operator on a variable that isn't an xml object. The following two samples will both throw the same error you are seeing when obj is undefined. Otherwise, 'undefined' in your error will be replaced with obj.toString();
// Putting a dot between the variable and () indicates an xml filter
// instead of a function call
obj.('test');
// Two consecutive dots returns all xml descendant elements of obj
// named test instead of retrieving a property named test from obj.
obj..test;

Intercept/Callback for QuickFIX message

I am using a FIX protocol to communicate with one of our counterparties. I have used Camel with Spring to build my communication routes.
I have a requirement where in my counterparty is expecting an ACK for every request it sends to me.
For example:
TradeCaptureRequestAck in response to TradeCaptureRequest
AllocationReportAck in response to AllocationReport
Confirmation_Ack in response to Confirmation
They are expecting a response irrespective of what happens at our end (even if something fails or exception occurs).
One way I know we can intercept the incoming message via MessageFactory. We can create a custom messagefactory and inject it in while creating QuickFixJComponent bean.
Problem with this approach is at factory level I will just be able to get the message type like TradeCaptureReport, AllocationReport etc. but not the content because factory only creates (and returns) the appropriate Message object. Actual work of populating this message object with incoming message data happens in Session class I guess (not sure about this).
Can someone please tell me if there is a way I can get or intercept the request message as soon as it reaches the route so that I can send the appropriate ACK to counterparty?

HTTP Sender and REST conventions

I'm writing a C# Web API server application, and will send JSON to it via a Mirth HTTP Sender destination. This post is about how to handle error conditions. Specifically, there are three scenarios I want to handle:
Sometimes we take the C# application server offline for a short period for system upgrade or maintenance, and Mirth is unable to connect at all. I want Mirth to queue all messages in order, and when the server is available, process them in the order they were received.
The server receives the request, but rejects it due to a problem with the content of the request, e.g., missing a required field. In accordance with REST conventions, the server will return a 400-level HTTP response. This message would be rejected every time it's submitted, so it should not be re-sent; just log the failure and move on to the next message.
The server receives the request, but something goes wrong on the server, and the server returns an HTTP 500 Server Error response. This would be the appropriate response, for example, when something in the server environment has gone wrong. One real-world example was the time the Web API server was running, but somebody rebooted the database server. REST conventions would suggest we continue to resend the message until the transient problem has been resolved.
For #1, initially I had it queue on failure/always, but it appears the response transformer never runs for messages that were queued (at least, the debug statements never showed in the log). I have turned queueing off, and set it to retry every ten seconds for an hour, and that seems to give the desired behavior. Am I on the right track here, or missing something?
For #2 and #3, returning any HTTP 400 or 500 error invokes the 1-hour retries. What I want is to apply the 1-hour retries for the 500 errors, but not the 400 errors. I’ve tried responseStatus = SENT in the response transformer, but the response transformer only runs once, after the hour has expired, and not for each retry.
This seems like a common problem, yet I’m not finding a solution. How are the rest of you handling this?
You're close!
So by default, the response transformer will only run if there's a response payload to transform. For connection problems, or possibly for 4xx/5xx responses that contain no payload, the response transformer won't execute.
However, if you set your response data types (From the Summary -> Set Data Types dialog, or from the Destinations -> Edit Response, Message Templates tab) to Raw, then the response transformer will execute all the time. The reason being that the Raw data type considers even an empty payload to be "transformable".
So turn queuing back on, and set your response data types to Raw. Then in the response transformer, if you look at the Reference tab there's a category for HTTP Sender:
You'll want the "response status line", that's the "HTTP/1.1 200 OK" line of the response that contains the response code. Here's a response transformer script that forces 4xx responses to error:
if (responseStatus == QUEUED) {
var statusLine = $('responseStatusLine');
if (statusLine) {
var parts = statusLine.split(' ');
if (parts.length >= 2) {
var responseCode = parseInt(parts[1], 10);
// Force 4xx responses to error
if (responseCode >= 400 && responseCode < 500) {
responseStatus = ERROR;
responseStatusMessage = statusLine;
}
}
}
}

NETTY 4.1.4: TCP Socket Server which replies back towards clients after processing requests

i'm new to Netty and intend to create a tcp socket server which reads the info of each client and replies back towards client before processing requests immediately ,i.e. sort of an acknowledgement towards client as and when the message enters overriden channelRead method of ChannelInboundHandlerAdapter class.
Please guide me in the above specified objective.
i'm currently trying the basic netty 4.1.4 echo server example however i wanted server to send back acknowledgement to the client so i updated channelread method as follows :
#Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
ctx.write(msg);
ChannelFuture cf = ctx.channel().write("FROM SERVER");
System.out.println("Channelfuture is "+cf);
}
and the output obtained was as follows:
Channelfuture is DefaultChannelPromise#3f4ee9dd(failure: java.lang.UnsupportedOperationException: unsupported message type: String (expected: ByteBuf, FileRegion))
I understand the error that it is expecting bytebuf but how do i achieve it? also, whether this method would be able to send out acknowledgement towards client
You can use String.getBytes(Charset) and Unpooled.wrappedBuffer(byte[]) to convert to ByteBuf.
ChannelFuture cf = ctx.channel()
.write(Unpooled.wrappedBuffer("FROM SERVER".getBytes(CharsetUtil.UTF_8)));
Also note that ctx.channel().write(...); may not be what you want. Consider ctx.write(...); instead. The difference is that if your handler is a ChannelDuplexHandler it would receive a write event when you do channel().write(). Using ctx instead of channel will send the write out from your handlers point in the pipeline instead of from the end of the pipeline, which is usually what you want.