Java HAPI 处理 HL7 V2 Inbound 事件

Java HL7 About 10,782 words

代码

HL7Server

import ca.uhn.hl7v2.HapiContext;
import ca.uhn.hl7v2.app.Connection;
import ca.uhn.hl7v2.app.ConnectionListener;
import ca.uhn.hl7v2.app.HL7Service;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * 入站端点:监听 8090,PACS 主动连进来推消息。
 * 这个端口只收不发(我方主动发给 PACS 走的是的另一条连接)。
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class Hl7Server {

    private final HapiContext context;
    private final InboundHandler inboundHandler;
    private final InboundExceptionHandler inboundExceptionHandler;

    @Value("${mllp.listen-port}")
    private int port;

    private HL7Service server;

    @PostConstruct
    public void start() {
        try {
            server = context.newServer(port, false);                  // false = 不用 TLS
            server.registerApplication("*", "*", inboundHandler);     // 所有消息类型都交给 InboundHandler
            server.setExceptionHandler(inboundExceptionHandler);
            server.registerConnectionListener(new ConnectionListener() {
                @Override
                public void connectionReceived(Connection connection) {
                    log.debug("EXA connected to port {}", port);
                }

                @Override
                public void connectionDiscarded(Connection connection) {
                    log.debug("EXA connection closed");
                }
            });
            server.startAndWait();
            log.info("MLLP server listening on port {}", port);
        } catch (Exception e) {
            throw new IllegalStateException("Failed to start MLLP server on port " + port, e);
        }
    }

    @PreDestroy
    public void stop() {
        if (server != null) {
            server.stopAndWait();
        }
    }
}

InboundHandler

import ca.uhn.hl7v2.HL7Exception;
import ca.uhn.hl7v2.model.Message;
import ca.uhn.hl7v2.protocol.ApplicationRouter;
import ca.uhn.hl7v2.protocol.ReceivingApplication;
import ca.uhn.hl7v2.protocol.ReceivingApplicationException;
import java.io.IOException;
import java.util.Map;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Component;

/**
 * HAPI 解析成功的消息走这里:落库 hl7_inbox,然后回 AA。
 * 解析失败的消息不会进来,走 InboundExceptionHandler。
 * 落库成功(含重复消息)→ AA;落库失败 → 抛 ReceivingApplicationException,
 * 由 InboundExceptionHandler 回 AE,PACS 重发。
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class InboundHandler implements ReceivingApplication<Message> {

    private final InboxDao inboxDao;

    @Override
    public Message processMessage(Message message, Map<String, Object> metadata)
            throws ReceivingApplicationException, HL7Exception {

        // HAPI 的 metadata 里没有原始字符串,只能重新编码:
        // 内容与原文一致,但可能去掉末尾空字段、改变转义
        String raw = message.encode();

        InboxMessage m = InboxMessage.from(raw, remoteAddress(metadata), null);
        try {
            if (m.getControlId() == null) {
                log.warn("HL7 message without MSH-10, duplicate detection disabled: type={}^{}, from={}",
                        m.getMessageCode(), m.getTriggerEvent(), m.getRemoteAddress());
            }
            if (inboxDao.insert(m)) {
                // 不打印原文:含 PHI
                log.info("HL7 stored: type={}^{}, controlId={}",
                        m.getMessageCode(), m.getTriggerEvent(), m.getControlId());
            }
        } catch (DataAccessException e) {
            log.error("Failed to store HL7 message: type={}^{}, controlId={}",
                    m.getMessageCode(), m.getTriggerEvent(), m.getControlId(), e);
            throw new ReceivingApplicationException("Failed to store inbound message", e);
        }

        try {
            return message.generateACK();   // MSA-1=AA,MSA-2=原消息 MSH-10
        } catch (IOException e) {
            throw new HL7Exception(e);
        }
    }

    @Override
    public boolean canProcess(Message message) {
        return true;
    }

    /** 对端地址,key 用 ApplicationRouter 的常量 */
    static String remoteAddress(Map<String, Object> metadata) {
        if (metadata == null) {
            return null;
        }
        Object ip = metadata.get(ApplicationRouter.METADATA_KEY_SENDING_IP);
        Object port = metadata.get(ApplicationRouter.METADATA_KEY_SENDING_PORT);
        return ip == null ? null : ip + (port == null ? "" : ":" + port);
    }
}

InboundExceptionHandler

import ca.uhn.hl7v2.protocol.ReceivingApplicationException;
import ca.uhn.hl7v2.protocol.ReceivingApplicationExceptionHandler;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicLong;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Component;

/**
 * HAPI 在解析 / 处理 / 编码入站消息失败时调用,返回值会替代 HAPI 默认的回复。
 * 规则:
 *  - InboundHandler 落库失败抛出的 ReceivingApplicationException → 回 AE,让 PACS 重发
 *  - 不以 MSH 开头(如原始文本)→ 不落库,打 WARN,回 AR
 *  - 以 MSH 开头但 HAPI 解析失败(如 SIU 的 MSH-12 为空)→ 原文落库:
 *        成功 → AA;落库失败 → AE
 * 注意:MSH-12 为空时 HAPI 拼不出 NAK,outgoingMessage 为 null,
 *       因此所有回复都在这里自己拼,永远不返回 null。
 *       HL7 段分隔符必须是 \r,不能用 Java text block(\n)。
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class InboundExceptionHandler implements ReceivingApplicationExceptionHandler {

    private static final DateTimeFormatter TS = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
    private static final AtomicLong SEQ = new AtomicLong();

    private final InboxDao inboxDao;
    private final RawDataInboxDao rawDataInboxDao;

    @Override
    public String processException(String incomingMessage, Map<String, Object> incomingMetadata,
                                   String outgoingMessage, Exception e) {

        String content = incomingMessage == null ? "" : incomingMessage.strip();

        // 0. 空内容:不落库
        if (content.isEmpty()) {
            log.warn("Empty content received over MLLP, ignored: from={}", InboundHandler.remoteAddress(incomingMetadata));
            return buildAck(null, "AA", null);
        }

        // 1. 非 HL7 内容:当作原始 数据 落库
        if (!content.startsWith("MSH")) {
            try {
                String preview = content.substring(0, Math.min(200, content.length())).replace('\r', '\n');
                log.warn("Non-HL7 content received over MLLP: length={}, from={}, preview=\n{}",
                        content.length(), InboundHandler.remoteAddress(incomingMetadata), preview);
                UUID id = rawDataInboxDao.insertRaw(incomingMessage, InboundHandler.remoteAddress(incomingMetadata));
                log.info("RAW data stored: csvInboxId={}, length={}", id, content.length());
                return buildAck(null, "AA", null);
            } catch (DataAccessException dae) {
                log.error("Failed to store RAW data content, length={}", content.length(), dae);
                return buildAck(null, "AE", "Temporary storage failure");
            }
        }

        InboxMessage m = InboxMessage.from(incomingMessage,
                InboundHandler.remoteAddress(incomingMetadata),
                e.getClass().getSimpleName() + ": " + e.getMessage());

        // 2. InboundHandler 自己落库失败(消息已解析成功,只是 DB 写不进去)→ AE
        if (e instanceof ReceivingApplicationException) {
            log.error("Inbound store failed, returning AE: type={}^{}, controlId={}",
                    m.getMessageCode(), m.getTriggerEvent(), m.getControlId());
            return buildAck(m, "AE", "Temporary storage failure");
        }

        // 3. HAPI 解析失败:原文落库后回 AA
        try {
            if (m.getControlId() == null) {
                log.warn("HL7 message without MSH-10, duplicate detection disabled: type={}^{}, from={}",
                        m.getMessageCode(), m.getTriggerEvent(), m.getRemoteAddress());
            }
            boolean inserted = inboxDao.insert(m);
            if (inserted) {
                log.info("HL7 parse failed but stored: type={}^{}, controlId={}, error={}",
                        m.getMessageCode(), m.getTriggerEvent(), m.getControlId(), m.getParseError());
            }
            return buildAck(m, "AA", null);
        } catch (DataAccessException dae) {
            log.error("Failed to store unparsable HL7 message: type={}^{}, controlId={}",
                    m.getMessageCode(), m.getTriggerEvent(), m.getControlId(), dae);
            return buildAck(m, "AE", "Temporary storage failure");
        }
    }

    /**
     * 手工拼 ACK:收发方对调;MSH-9 = ACK^<原 trigger>;MSA-2 = 原 MSH-10;版本号沿用原消息(为空则留空)。
     */
    private static String buildAck(InboxMessage m, String ackCode, String text) {
        String sendApp  = m == null ? "" : n(m.getReceivingApplication());
        String sendFac  = m == null ? "" : n(m.getReceivingFacility());
        String recvApp  = m == null ? "" : n(m.getSendingApplication());
        String recvFac  = m == null ? "" : n(m.getSendingFacility());
        String trigger  = m == null ? "" : n(m.getTriggerEvent());
        String procId   = m == null || m.getProcessingId() == null ? "P" : m.getProcessingId();
        String version  = m == null ? "" : n(m.getHl7Version());
        String ctrlId   = m == null ? "" : n(m.getControlId());
        String ackCtrl  = "ACK" + LocalDateTime.now().format(TS) + SEQ.incrementAndGet() % 1000;

        String msh = "MSH|^~\\&|" + sendApp + "|" + sendFac + "|" + recvApp + "|" + recvFac
                + "|" + LocalDateTime.now().format(TS) + "||ACK" + (trigger.isEmpty() ? "" : "^" + trigger)
                + "|" + ackCtrl + "|" + procId + "|" + version;
        String msa = "MSA|" + ackCode + "|" + ctrlId + (text == null ? "" : "|" + text);
        return msh + "\r" + msa + "\r";
    }

    private static String n(String s) {
        return s == null ? "" : s;
    }
}

pom.xml

<properties>
    <java.version>25</java.version>
    <hapi.version>2.6.0</hapi.version>
</properties>
    
<!-- HAPI HL7 v2:收发 + 解析 + ACK 全部用它 -->
<dependency>
    <groupId>ca.uhn.hapi</groupId>
    <artifactId>hapi-base</artifactId>
    <version>${hapi.version}</version>
</dependency>
<!-- 消息结构:我方发 2.3.1,PACS 发 2.5.1。PACS 以后用到别的版本,在这里加对应的 hapi-structures-vXX -->
<dependency>
    <groupId>ca.uhn.hapi</groupId>
    <artifactId>hapi-structures-v231</artifactId>
    <version>${hapi.version}</version>
</dependency>
<dependency>
    <groupId>ca.uhn.hapi</groupId>
    <artifactId>hapi-structures-v251</artifactId>
    <version>${hapi.version}</version>
</dependency>
Views: 12 · Posted: 2026-11-17

———         Thanks for Reading         ———

Give me a Star, Thanks:)

https://github.com/fendoudebb/LiteNote

扫描下方二维码关注公众号和小程序↓↓↓

扫描下方二维码关注公众号和小程序↓↓↓
Prev Post
Today In History
Browsing Refresh