Path: redb-route/redb.Route.IbmMq/IbmMqMessageHelper.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.IbmMq/IbmMqMessageHelper.cs
----
using System.Text;
using IBM.WMQ;
using redb.Route.Abstractions;
using RouteMessage = redb.Route.Core.Message;
namespace redb.Route.IbmMq;
///
/// Helpers for IBM MQ message body extraction, MQMD→headers mapping, and exchange→MQMessage building.
///
public static class IbmMqMessageHelper
{
///
/// Puts a dead letter header (MQDLH, version 1) in front of 's data, as IBM MQ does for a
/// message it moves to the dead letter queue: the reason, the queue and queue manager it was on, the encoding,
/// character set and format of the data behind it; the message's format becomes MQFMT_DEAD_LETTER_HEADER.
///
internal static void WrapInDeadLetterHeader(MQMessage msg, int reason, string queue, string queueManager)
{
msg.Seek(0);
var data = msg.ReadBytes(msg.MessageLength);
var format = msg.Format;
msg.ClearMessage();
msg.Write(Fixed("DLH ", 4));
msg.WriteInt4(MQC.MQDLH_VERSION_1);
msg.WriteInt4(reason);
msg.Write(Fixed(queue, 48));
msg.Write(Fixed(queueManager, 48));
msg.WriteInt4(msg.Encoding);
msg.WriteInt4(msg.CharacterSet);
msg.Write(Fixed(format, 8));
msg.WriteInt4(MQC.MQAT_DEFAULT);
msg.Write(Fixed("redb.Route", 28));
var now = DateTime.UtcNow;
msg.Write(Fixed(now.ToString("yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture), 8));
msg.Write(Fixed(now.ToString("HHmmssff", System.Globalization.CultureInfo.InvariantCulture), 8));
msg.Write(data);
msg.Format = MQC.MQFMT_DEAD_LETTER_HEADER;
static byte[] Fixed(string text, int length)
{
var bytes = System.Text.Encoding.ASCII.GetBytes((text ?? string.Empty).PadRight(length));
return bytes.Length == length ? bytes : bytes[..length];
}
}
///
/// Extracts the body from an as a string or byte[].
/// Uses Format and CCSID to decide encoding.
///
public static object ExtractBody(MQMessage msg)
{
var dataLength = msg.DataLength;
if (dataLength == 0) return string.Empty;
// MQFMT_STRING or MQFMT_RF_HEADER_2 → read as text
var fmt = msg.Format.Trim();
if (fmt == MQC.MQFMT_STRING.Trim() || fmt == MQC.MQFMT_RF_HEADER_2.Trim())
{
return msg.ReadString(dataLength);
}
// Binary payload
return msg.ReadBytes(dataLength);
}
///
/// Copies MQMD fields into redb.Route message headers with redbIbmMq.* prefix.
///
public static void CopyMqmdToHeaders(MQMessage mqMsg, RouteMessage routeMsg, string destination, string queueManager)
{
routeMsg.Headers[IbmMqHeaders.Destination] = destination;
routeMsg.Headers[IbmMqHeaders.QueueManager] = queueManager;
if (mqMsg.MessageId != null && mqMsg.MessageId.Length > 0)
routeMsg.Headers[IbmMqHeaders.MsgId] = BytesToHex(mqMsg.MessageId);
if (mqMsg.CorrelationId != null && mqMsg.CorrelationId.Length > 0)
routeMsg.Headers[IbmMqHeaders.CorrelId] = BytesToHex(mqMsg.CorrelationId);
routeMsg.Headers[IbmMqHeaders.Format] = mqMsg.Format.Trim();
routeMsg.Headers[IbmMqHeaders.CCSID] = mqMsg.CharacterSet;
routeMsg.Headers[IbmMqHeaders.Encoding] = mqMsg.Encoding;
routeMsg.Headers[IbmMqHeaders.Persistence] = mqMsg.Persistence;
routeMsg.Headers[IbmMqHeaders.Priority] = mqMsg.Priority;
routeMsg.Headers[IbmMqHeaders.Expiry] = mqMsg.Expiry;
routeMsg.Headers[IbmMqHeaders.MsgType] = mqMsg.MessageType;
routeMsg.Headers[IbmMqHeaders.Feedback] = mqMsg.Feedback;
routeMsg.Headers[IbmMqHeaders.ReportOptions] = mqMsg.Report;
routeMsg.Headers[IbmMqHeaders.BackoutCount] = mqMsg.BackoutCount;
if (!string.IsNullOrWhiteSpace(mqMsg.ReplyToQueueName))
routeMsg.Headers[IbmMqHeaders.ReplyToQueue] = mqMsg.ReplyToQueueName.Trim();
if (!string.IsNullOrWhiteSpace(mqMsg.ReplyToQueueManagerName))
routeMsg.Headers[IbmMqHeaders.ReplyToQueueManager] = mqMsg.ReplyToQueueManagerName.Trim();
if (!string.IsNullOrWhiteSpace(mqMsg.UserId))
routeMsg.Headers[IbmMqHeaders.UserIdentifier] = mqMsg.UserId.Trim();
if (!string.IsNullOrWhiteSpace(mqMsg.PutApplicationName))
routeMsg.Headers[IbmMqHeaders.PutApplName] = mqMsg.PutApplicationName.Trim();
routeMsg.Headers[IbmMqHeaders.PutApplType] = mqMsg.PutApplicationType;
if (mqMsg.GroupId != null && mqMsg.GroupId.Length > 0 && !IsEmptyBytes(mqMsg.GroupId))
routeMsg.Headers[IbmMqHeaders.GroupId] = BytesToHex(mqMsg.GroupId);
if (mqMsg.MessageSequenceNumber > 0)
routeMsg.Headers[IbmMqHeaders.MsgSeqNumber] = mqMsg.MessageSequenceNumber;
try
{
var putDate = mqMsg.PutDateTime;
routeMsg.Headers[IbmMqHeaders.PutDateTime] = putDate;
}
catch
{
// PutDateTime may throw if date fields are empty/invalid
}
}
///
/// Copies RFH2 user properties (if present) that lets in into exchange headers;
/// is the one they come into (for a request-reply's reply, the request's).
/// IBM MQ JMS messages carry user-defined properties in the MQRFH2 usr folder.
///
public static void CopyRfh2UserProperties(MQMessage mqMsg, RouteMessage routeMsg,
IHeaderFilterStrategy headerFilter, IExchange exchange)
{
string? json = null;
try { json = mqMsg.GetStringProperty(IbmMqHeaders.HeaderCatalogue); }
catch { /* property not present */ }
if (string.IsNullOrEmpty(json)) return;
try
{
var dict = System.Text.Json.JsonSerializer.Deserialize>(json);
if (dict is null) return;
foreach (var (key, value) in dict)
{
if (headerFilter.FilterIncoming(key, value, exchange)) continue;
routeMsg.Headers[key] = value;
}
}
catch { /* malformed JSON — skip */ }
}
///
/// Copies the headers of a route message that lets out into the MQ message's RFH2
/// user property folder (using the same JSON-encoded property as ).
///
public static void CopyHeadersToRfh2(MQMessage mqMsg, IMessage routeMsg,
IHeaderFilterStrategy headerFilter, IExchange exchange)
{
var customHeaders = new Dictionary();
foreach (var (key, value) in routeMsg.Headers)
{
if (value is null) continue;
if (headerFilter.FilterOutgoing(key, value, exchange)) continue;
customHeaders[key] = value.ToString()!;
}
if (customHeaders.Count == 0) return;
var json = System.Text.Json.JsonSerializer.Serialize(customHeaders);
mqMsg.SetStringProperty(IbmMqHeaders.HeaderCatalogue, json);
}
///
/// Builds an from an exchange for sending; decides which
/// exchange headers go into the header catalogue.
///
public static MQMessage BuildOutgoingMessage(
IExchange exchange,
IbmMqEndpointOptions options,
IHeaderFilterStrategy headerFilter)
{
var msg = new MQMessage
{
CharacterSet = options.CCSID,
Format = MQC.MQFMT_STRING,
};
// Persistence: header > expression > static
var persistence = options.Persistence;
if (options.PersistenceExpression is not null)
{
var resolved = options.ResolveOption(options.PersistenceExpression, exchange);
if (resolved is not null && Enum.TryParse(resolved, true, out var parsedPers))
persistence = parsedPers;
}
msg.Persistence = persistence switch
{
IbmMqPersistence.Persistent => MQC.MQPER_PERSISTENT,
IbmMqPersistence.NonPersistent => MQC.MQPER_NOT_PERSISTENT,
_ => MQC.MQPER_PERSISTENCE_AS_Q_DEF
};
// Priority: header > expression > static
var priority = options.Priority;
if (options.PriorityExpression is not null)
{
var resolved = options.ResolveOption(options.PriorityExpression, exchange);
if (resolved is not null && int.TryParse(resolved, out var parsedPrio))
priority = parsedPrio;
}
if (priority >= 0)
msg.Priority = priority;
// Expiry: header > expression > static
var expiry = options.Expiry;
if (options.ExpiryExpression is not null)
{
var resolved = options.ResolveOption(options.ExpiryExpression, exchange);
if (resolved is not null && int.TryParse(resolved, out var parsedExp))
expiry = parsedExp;
}
if (expiry >= 0)
msg.Expiry = expiry;
// Message type: header > expression > static
var messageType = (int)options.MessageType;
if (options.MessageTypeExpression is not null)
{
var resolved = options.ResolveOption(options.MessageTypeExpression, exchange);
if (resolved is not null && Enum.TryParse(resolved, true, out var parsedMt))
messageType = (int)parsedMt;
}
msg.MessageType = messageType;
// Body
var body = exchange.In.Body;
var contentType = exchange.In.ContentType;
switch (body)
{
case byte[] bytes:
msg.Write(bytes);
msg.Format = contentType is not null ? ContentTypeToFormat(contentType) : MQC.MQFMT_NONE;
break;
case string str:
msg.WriteString(str);
msg.Format = contentType is not null ? ContentTypeToFormat(contentType) : MQC.MQFMT_STRING;
break;
case null:
break;
default:
msg.WriteString(body.ToString() ?? string.Empty);
break;
}
// Copy exchange headers → single JSON-encoded MQ property
// (MQ property names forbid hyphens, so individual SetStringProperty won't
// work for standard HTTP-style headers like X-Custom-Id)
var customHeaders = new Dictionary();
foreach (var (key, value) in exchange.In.Headers)
{
if (value is null) continue;
if (headerFilter.FilterOutgoing(key, value, exchange)) continue;
customHeaders[key] = value.ToString()!;
}
// targetClient=Mq: a legacy MQ application expects raw MQMD+body. Message properties are
// what materializes as an MQRFH2 for property-aware paths, so in Mq mode none are written
// (the MQMD fields below are fine - they are descriptor, not properties). The option was
// declared and read by nothing until the options sweep.
if (customHeaders.Count > 0 && options.TargetClient != IbmMqTargetClient.Mq)
{
var json = System.Text.Json.JsonSerializer.Serialize(customHeaders);
msg.SetStringProperty(IbmMqHeaders.HeaderCatalogue, json);
}
// Standard, JMS-equivalent MQMD fields forward from headers BY DEFAULT (header wins over
// option/expression) — mirrors what a WMQ JMS client maps from JMSCorrelationID/JMSPriority/
// JMSExpiration/JMSDeliveryMode/JMSReplyTo, so a naive consume→produce round-trip preserves them.
ApplyStandardMqmdFromHeaders(msg, exchange, options.PreserveMessageQos);
// Advanced / raw MQMD fields (message type, format, grouping) only when explicitly enabled —
// mirrors IBM MQ JMS's WMQ_MQMD_WRITE_ENABLED, since these can alter message semantics.
if (options.MqmdWriteEnabled)
ApplyAdvancedMqmdFromHeaders(msg, exchange);
return msg;
}
///
/// Applies the standard, JMS-equivalent MQMD fields from exchange headers (header wins).
/// Always active: these are the fields a WMQ JMS client forwards by default.
///
private static void ApplyStandardMqmdFromHeaders(MQMessage msg, IExchange exchange, bool preserveReplyTo)
{
var headers = exchange.In.Headers;
if (headers.TryGetValue(IbmMqHeaders.CorrelId, out var cid) && cid is string cidStr)
msg.CorrelationId = HexToBytes(cidStr);
if (headers.TryGetValue(IbmMqHeaders.Priority, out var prio) && prio is int prioInt)
msg.Priority = prioInt;
if (headers.TryGetValue(IbmMqHeaders.Expiry, out var exp) && exp is int expInt)
msg.Expiry = expInt;
if (headers.TryGetValue(IbmMqHeaders.Persistence, out var pers) && pers is int persInt)
msg.Persistence = persInt;
// The reply-to only with preserveMessageQos, as Camel's JMS: a sender's reply-to forwarded here must not make another
// consumer answer into it. A request-reply put sets its own reply queue after this.
if (!preserveReplyTo)
return;
if (headers.TryGetValue(IbmMqHeaders.ReplyToQueue, out var rtq) && rtq is string rtqStr)
msg.ReplyToQueueName = rtqStr;
if (headers.TryGetValue(IbmMqHeaders.ReplyToQueueManager, out var rtqm) && rtqm is string rtqmStr)
msg.ReplyToQueueManagerName = rtqmStr;
}
///
/// Applies the advanced / raw MQMD fields from exchange headers — gated behind MqmdWriteEnabled
/// (mirrors IBM MQ JMS's WMQ_MQMD_WRITE_ENABLED) as these can change message semantics.
///
private static void ApplyAdvancedMqmdFromHeaders(MQMessage msg, IExchange exchange)
{
var headers = exchange.In.Headers;
if (headers.TryGetValue(IbmMqHeaders.MsgType, out var mt) && mt is int mtInt)
msg.MessageType = mtInt;
if (headers.TryGetValue(IbmMqHeaders.Format, out var fmt) && fmt is string fmtStr)
msg.Format = fmtStr;
if (headers.TryGetValue(IbmMqHeaders.GroupId, out var gid) && gid is string gidStr)
msg.GroupId = HexToBytes(gidStr);
if (headers.TryGetValue(IbmMqHeaders.MsgSeqNumber, out var seq) && seq is int seqInt)
msg.MessageSequenceNumber = seqInt;
}
// ── Format ↔ ContentType mapping ──
/// Maps MQMD Format to a MIME content type.
public static string? FormatToContentType(string? format)
{
if (format is null) return null;
var fmt = format.Trim();
if (fmt.Length == 0) return "application/octet-stream"; // MQFMT_NONE = 8 spaces
if (fmt == MQC.MQFMT_STRING.Trim()) return "text/plain";
if (fmt == MQC.MQFMT_RF_HEADER_2.Trim()) return "text/plain";
return null;
}
/// Maps a MIME content type to the best MQMD Format.
public static string ContentTypeToFormat(string? contentType)
{
if (string.IsNullOrWhiteSpace(contentType)) return MQC.MQFMT_STRING;
if (contentType.StartsWith("application/octet-stream", StringComparison.OrdinalIgnoreCase))
return MQC.MQFMT_NONE;
// text/*, application/json, application/xml etc. → string format
return MQC.MQFMT_STRING;
}
// ── Helpers ──
internal static string BytesToHex(byte[] bytes)
{
return Convert.ToHexString(bytes);
}
internal static byte[] HexToBytes(string hex)
{
return Convert.FromHexString(hex);
}
private static bool IsEmptyBytes(byte[] bytes)
{
foreach (var b in bytes)
if (b != 0) return false;
return true;
}
}