java解析HL7协议报文工具 HAPI(SpringBoot版本)

Java通过HAPI解析HL7消息 Java通过HAPI解析HL7消息HL7([详情](https://baike.baidu.com/item/HL7))使用的HAPI([maven](https://mvnrepository.com/artifact/ca.uhn.hapi))解析解读MessageMessagenamesrequiredrepeatingstructures(重点)key:段落名value:段落内容fields:字段内容types:字段类型names:字段名剩下的字段大家自己消化 HL7(详情) Health Leve 阅读详情

java解析HL7协议报文工具 因为项目需要解析HL7协议报文,网上找到的工具都是解析成带位置信息的xml格式或者json格式,然后需要自己根据需要获取的位置来获取信息。而在生成的HL7协议报文的时候也是需要先生成xml或json格式再进行转换。想着希望找到一个直接解析生成类然后直接用的工具。 后来我找到了这个ca.uhn.hapi,能将HL7报文直接解析成相应的类,通过调用:PipeParser.parse(message, hl7str)来解析报文,将数据填充到message类里面,其中message是工具里面的继承Message类的子类,例如:QBP_Q11、RSP_K23等。而生成HL7报文的时候又可以调用message.encode()来生成,不过需要先设置MSH头

一、依赖:

        <dependency>
            <groupId>ca.uhn.hapi</groupId>
            <artifactId>hapi-base</artifactId>
            <version>2.2</version>
        </dependency>
        <dependency>
            <groupId>ca.uhn.hapi</groupId>
            <artifactId>hapi-structures-v24</artifactId>
            <version>2.3</version>
        </dependency>

因为我们是通过socket对接实现的,先实现socket代码

1.启动类

@SpringBootApplication
@EnableCaching
@Configuration
@EnableScheduling
@ServletComponentScan
@EnableTransactionManagement
public class Application extends SpringBootServletInitializer {

 public static void main(String[] args) {
        ApplicationContext context = SpringApplication.run(Application.class, args);
        SpringContextUtil.setApplicationContext(context);
        SocketServer demoServer = new SocketServer();
        try {
            demoServer.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

2.SocketServer(服务端)

@Component
public class SocketServer{

    private static final Logger logger = LoggerFactory.getLogger(SocketServer.class);

    public void start() throws IOException {
        ExecutorService newCacheThreadPool = new ThreadPoolExecutor(
                2,
                5,
                3,
                TimeUnit.SECONDS,
                new LinkedBlockingDeque<>(3),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.DiscardOldestPolicy()
        );
        ServerSocket server = new ServerSocket(SocketProperties.getSocketPort());
        logger.info("socket服务端启动....端口:{}",SocketProperties.getSocketPort());
        while (true) {
            final Socket socket = server.accept();
            logger.info("开始处理请求");
            newCacheThreadPool.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        handler(socket);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }

    private  void handler(Socket socket) throws Exception {
        byte[] bytes = null;
        InputStream inputStream = null;
        try {
            inputStream = socket.getInputStream();
            int bufflenth = inputStream.available();
            while (bufflenth != 0) {
                bytes = new byte[bufflenth];
                //读取数据(阻塞)
                inputStream.read(bytes);
                bufflenth = inputStream.available();
            }
            String result = new String(bytes);
            result =  new String(bytes).replaceAll("\n","\r")
                    .replaceAll("\u000B","").replaceAll("amp;","").replaceAll("\u001c","");
            logger.info("请求:{}" ,result);
            TestHL7.hl7Text2Obj(result,socket);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            logger.info("socket关闭");
            try {
                inputStream.close();
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

3.SocketClient

@Slf4j
public class SocketClient {
/**
     * 发送socket消息
     */
    public static String sendSocket(String message){
        Socket socket = null;
        String result = "";
        InputStream in = null;
        OutputStream out = null;
        try {
            socket = new Socket(SocketProperties.getSocketSendIp(),SocketProperties.getSocketSendPort());
            in = socket.getInputStream();
            out = socket.getOutputStream();
            log.info("----------开始发送 MESSAGE-----------{}",message);
            out.write(message.getBytes(SocketConstants.UTF_8));
            out.flush();
            socket.shutdownOutput();
            byte[] byteBuffer = new byte[8*1024];
            in.read(byteBuffer);
            result = new String(byteBuffer);
            log.info("Received from Server message: " + result);
            result =  result.replaceAll("\n","\r")
                    .replaceAll("\u000B","").replaceAll("amp;","").replaceAll("\u001c","");
            return result;
        }catch (Exception e){
            log.error("发送socket消息失败",e);
        }finally {
            if(socket!=null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if(in!=null) {
                try {
                    in.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if(out!=null) {
                try {
                    out.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        log.info("disconnected.");
        return result;
    }
    public static String handle(Socket socket,String message) throws IOException {
        InputStream in = socket.getInputStream();
        OutputStream out = socket.getOutputStream();
        log.info("----------开始发送 MESSAGE-----------{}",message);
        out.write(message.getBytes(SocketConstants.UTF_8));
        out.flush();
        socket.shutdownOutput();
        byte[] byteBuffer = new byte[8*1024];
        in.read(byteBuffer);
        String result = new String(byteBuffer);
        log.info("Received from Server message: " + result);
        return result;
    }

4.socket.properties

socket.server.port=30038
socket.send.server.ip=192.168.254.216
socket.send.server.p

后来因为接入的项目用到的协议和ca.uhn.hapi工具里面已经定义好的类所解析的报文结构不一致,所以需要自己去编写工具来自定义解析和生成相应的HL7报文,比如以下报文的RSP_ZP7在工具包里面没有相应的类结构对应(\r为回车): 下面我写了几个工具类来实现方便调用,HL7Helper类主要是设置数据和获取数据,UserDefineComposite类用于自定义数据类型,UserDefineMessage类用于自定义message类型:

HL7Helper类:

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import ca.uhn.hl7v2.HL7Exception;
import ca.uhn.hl7v2.model.AbstractComposite;
import ca.uhn.hl7v2.model.AbstractPrimitive;
import ca.uhn.hl7v2.model.AbstractSegment;
import ca.uhn.hl7v2.model.Message;
import ca.uhn.hl7v2.model.Type;
import ca.uhn.hl7v2.model.Varies;
import ca.uhn.hl7v2.parser.PipeParser;

/**
 * @author SamJoke
 */
public class HL7Helper {

    private static Method method = null;

    static {
        try {
            method = AbstractSegment.class.getDeclaredMethod("add", Class.class, boolean.class, int.class, int.class,
                    Object[].class, String.class);
            method.setAccessible(true);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (SecurityException e) {
            e.printStackTrace();
        }
    }

    /**
     * 自定义添加AbstractSegment类的字段类型,然后可以用getFeild方法进行赋值,例子参考:
     * testSegmentAddFeildRequest()
     * 
     * @param obj
     *            AbstractSegment对象
     * @param c
     *            数据类型
     * @param required
     *            是否必填
     * @param maxReps
     *            数组长度
     * @param length
     *            字节长度
     * @param constructorArgs
     *            构造器
     * @param name
     *            字段名
     * @throws IllegalAccessException
     * @throws IllegalArgumentException
     * @throws InvocationTargetException
     */
    public static void segmentAddFeild(AbstractSegment obj, Class<? extends Type> c, boolean required, int maxReps,
            int length, Object[] constructorArgs, String name)
            throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
        method.invoke(obj, c, required, maxReps, length, constructorArgs, name);
    }

    public static void segmentAddFeild(AbstractSegment obj, Class<? extends Type> c, int maxReps, int length,
            Message msg) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
        segmentAddFeild(obj, c, false, maxReps, length, new Object[] { msg }, "user define");
    }

    public static void segmentAddFeild(AbstractSegment obj, Class<? extends Type> c, int length, Message msg)
            throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
        segmentAddFeild(obj, c, false, 1, length, new Object[] { msg }, "user define");
    }

//    public static void segmentAddFeild(AbstractSegment obj, HL7DataType hl7DateType, Message msg)
//            throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
//        segmentAddFeild(obj, hl7DateType.getCls(), false, hl7DateType.getMaxReps(), hl7DateType.getLength(),
//                new Object[] { msg }, "user define");
//    }

    @SuppressWarnings("unchecked")
    public static <T> T getField(AbstractSegment obj, int pos, int index, Class<T> cls) throws HL7Exception {
        return (T) obj.getField(pos, index);
    }

    /**
     * 将hl7str协议报文转换为指定的Message类(可自定义),例子参考:testSegmentAddFeildResponse()
     * 
     * @param msg
     *            Message类型,如ADT_A01
     * @param hl7str
     *            HL7协议报文
     * @throws HL7Exception
     */
    public static void acceptResponse(Message msg, String hl7str) throws HL7Exception {
        PipeParser p = new PipeParser();
        p.parse(msg, hl7str);
    }

    public static String getMsgValue(Message msg, String segName, int... ints) throws HL7Exception {
        return getMsgValue(msg, 0, segName, ints);
    }

    public static String getMsgValue(Message msg, Class<? extends AbstractSegment> segCls, int... ints)
            throws HL7Exception {
        return getMsgValue(msg, 0, segCls.getSimpleName(), ints);
    }

    /**
     * 
     * 获取Message里面的数据,例子参考testGetMsgValue()
     * 
     * @param msg
     *            Message类型
     * @param struIndex
     *            AbstractSegment数组位,比如PID有重复多个的话需要自己设置位置,默认传0进去
     * @param segName
     *            AbstractSegment名,如PID、MSH等
     * @param ints
     *            具体位置,如new int[]{3,2,3}
     * @return
     * @throws HL7Exception
     */
    public static String getMsgValue(Message msg, int struIndex, String segName, int... ints) throws HL7Exception {
        AbstractSegment stru = (AbstractSegment) msg.get(segName, struIndex);

        int segPos = 0;

        int composIndex = 0;

        if (ints.length <= 0) {
            segPos = 0;
            composIndex = 0;
        } else if (ints.length == 1) {
            segPos = ints[0];
            composIndex = 0;
        } else {
            segPos = ints[0];
            composIndex = ints[1];
        }

        Type itetype = stru.getField(segPos, composIndex);

        for (int i = 2; i < ints.length; i++) {
            if (itetype instanceof AbstractPrimitive) {
                break;
            } else if (itetype instanceof AbstractComposite) {
                AbstractComposite coms = (AbstractComposite) itetype;
                itetype = coms.getComponent(ints[i]);
            }
        }

        return itetype.encode();
    }

    public static void setMsgValue(Message msg, String segName, String value, int... ints) throws HL7Exception {
        setMsgValue(msg, 0, segName, value, ints);
    }

    public static void setMsgValue(Message msg, Class<? extends AbstractSegment> segCls, String value, int... ints)
            throws HL7Exception {
        setMsgValue(msg, 0, segCls.getSimpleName(), value, ints);
    }

    public static void setMsgValue(Message msg, Object segCls, String value, int... ints)
            throws HL7Exception {
        setMsgValue(msg, 0, segCls.getClass().getSimpleName(), value, ints);
    }

    /**
     * 
     * 设置Message里面的数据,例子参考testSetMsgValue()
     * 
     * @param msg
     *            Message类型
     * @param struIndex
     *            AbstractSegment数组位,比如PID有重复多个的话需要自己设置位置,默认传0进去
     * @param segName
     *            AbstractSegment名,如PID、MSH等
     * @param value
     *            设置值
     * @param ints
     *            具体位置,如new
     *            int[]{3,2,3},需要注意这里的位置,要根据上面的segName类的init方法里面Type的排序和类型来确定,是否支持这样的定位(层级),若不支持则会抛异常,
     * @return
     * @throws HL7Exception
     */
    public static void setMsgValue(Message msg, int struIndex, String segName, String value, int... ints)
            throws HL7Exception {
        AbstractSegment stru = (AbstractSegment) msg.get(segName, struIndex);

        int segPos = 0;

        int composIndex = 0;

        if (ints.length <= 0) {
            segPos = 0;
            composIndex = 0;
        } else if (ints.length == 1) {
            segPos = ints[0];
            composIndex = 0;
        } else {
            segPos = ints[0];
            composIndex = ints[1];
        }

        Type itetype = stru.getField(segPos, composIndex);

        //用户自定义Type
        if(itetype instanceof Varies){
            itetype = ((Varies) itetype).getData();
        }

        if (ints.length == 2) {
            ((AbstractPrimitive) itetype).setValue(value);
        }

        for (int i = 2; i < ints.length; i++) {
            if (itetype instanceof AbstractPrimitive) {
                ((AbstractPrimitive) itetype).setValue(value);
            } else if (itetype instanceof AbstractComposite) {
                AbstractComposite coms = (AbstractComposite) itetype;
                itetype = coms.getComponent(ints[i]);
                if (i >= ints.length - 1) {
                    if (itetype instanceof AbstractComposite) {
                        coms = (AbstractComposite) itetype;
                        ((AbstractPrimitive) coms.getComponent(0)).setValue(value);
                    } else {
                        ((AbstractPrimitive) itetype).setValue(value);
                    }
                }
            }
        }
    }

}
复制代码

UserDefineComposite类:

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

import ca.uhn.hl7v2.model.AbstractComposite;
import ca.uhn.hl7v2.model.DataTypeException;
import ca.uhn.hl7v2.model.Message;
import ca.uhn.hl7v2.model.Type;
import ca.uhn.hl7v2.model.v24.datatype.ST;

/**
 * 用户自定义Type,根据传不同的长度和Types来构建
 * @author SamJoke
 */
public class UserDefineComposite extends AbstractComposite {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    private static Class<? extends Type> defalutclass = ST.class;

    Type[] data = null;

    public UserDefineComposite(Message message) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException {
        super(message);
        data = new Type[1];
        Constructor<? extends Type> cons = defalutclass.getConstructor(new Class[] { Message.class });
        data[0] = (Type) cons.newInstance(new Object[] { getMessage() });
    }

    public UserDefineComposite(Message message, Type... types) {
        super(message);
        init(types);
    }

    @SuppressWarnings("rawtypes")
    public UserDefineComposite(Message message, Class... clss) throws InstantiationException, IllegalAccessException,
            IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException {
        super(message);
        init(clss);
    }

    @SuppressWarnings("rawtypes")
    public UserDefineComposite(Message message, int typeCount) throws InstantiationException, IllegalAccessException,
            IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException {
        super(message);
        Class[] clss = new Class[typeCount];
        data = new Type[typeCount];
        Constructor<? extends Type> cons = defalutclass.getConstructor(new Class[] { Message.class });
        for (int i = 0; i < clss.length; i++) {
            data[i] = (Type) cons.newInstance(new Object[] { getMessage() });
        }
    }

    private void init(Type... types) {
        data = new Type[types.length];
        for (int i = 0; i < types.length; i++) {
            data[i] = types[i];
        }
    }

    @SuppressWarnings({ "rawtypes", "unchecked" })
    private void init(Class... clss) throws InstantiationException, IllegalAccessException, IllegalArgumentException,
            InvocationTargetException, NoSuchMethodException, SecurityException {
        data = new Type[clss.length];
        for (int i = 0; i < clss.length; i++) {
            Constructor<? extends Type> cons = clss[i].getConstructor(new Class[] { Message.class });
            data[i] = (Type) cons.newInstance(new Object[] { getMessage() });
        }
    }

    @Override
    public Type[] getComponents() {
        return data;
    }

    @Override
    public Type getComponent(int number) throws DataTypeException {
        try {
            return this.data[number];
        } catch (ArrayIndexOutOfBoundsException e) {
            throw new DataTypeException("Element " + number + " doesn't exist (Type " + getClass().getName()
                    + " has only " + this.data.length + " components)");
        }
    }

}
复制代码

UserDefineMessage类:

import ca.uhn.hl7v2.HL7Exception;
import ca.uhn.hl7v2.model.AbstractMessage;
import ca.uhn.hl7v2.model.DoNotCacheStructure;
import ca.uhn.hl7v2.model.Structure;
import ca.uhn.hl7v2.parser.DefaultModelClassFactory;
import ca.uhn.hl7v2.parser.ModelClassFactory;

/**
 * 用户自定义Message,@DoNotCacheStructure注解为了不进行缓存
 * @author SamJoke
 */
@DoNotCacheStructure
public class UserDefineMessage extends AbstractMessage {

    private static final long serialVersionUID = 1L;

    private static ASType[] types;

    private static ModelClassFactory fat = null;

    static {
        try {
            fat = new DefaultModelClassFactory();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public UserDefineMessage(ModelClassFactory factory) throws HL7Exception {
        super(factory);
        init(types);
    }

    public UserDefineMessage(ASType... types) throws HL7Exception {
        super(fat == null ? new DefaultModelClassFactory() : fat);
        setASTypes(types);
        init(types);
    }

    private void init(ASType... types) throws HL7Exception {
        for (int i = 0; i < types.length; i++) {
            this.add(types[i].c, types[i].required, types[i].repeating);
        }
    }

    public String getVersion() {
        return "2.4";
    }

    public Structure getAS(String asName, Class<? extends Structure> asCls) {
        return getTyped(asName, asCls);
    }

    @SuppressWarnings("unchecked")
    public <T extends Structure> T getAS(Class<T> asCls) throws HL7Exception {
        return (T) get(asCls.getSimpleName());
    }

    public static class ASType {
        Class<? extends Structure> c;
        boolean required;
        boolean repeating;

        public ASType(Class<? extends Structure> c, boolean required, boolean repeating) {
            this.c = c;
            this.required = required;
            this.repeating = repeating;
        }
    }

    private static void setASTypes(ASType... tys) {
        types = tys;
    }

}

测试类:

import ca.uhn.hl7v2.HL7Exception;
import ca.uhn.hl7v2.model.v24.datatype.CE;
import ca.uhn.hl7v2.model.v24.message.QBP_Q11;
import ca.uhn.hl7v2.model.v24.segment.DSC;
import ca.uhn.hl7v2.model.v24.segment.ERR;
import ca.uhn.hl7v2.model.v24.segment.IN1;
import ca.uhn.hl7v2.model.v24.segment.MSA;
import ca.uhn.hl7v2.model.v24.segment.MSH;
import ca.uhn.hl7v2.model.v24.segment.PID;
import ca.uhn.hl7v2.model.v24.segment.QAK;
import ca.uhn.hl7v2.model.v24.segment.QPD;
import ca.uhn.hl7v2.model.v24.segment.QRI;
import ca.uhn.hl7v2.model.v24.segment.RCP;

/**
 * @author SamJoke
 */
public class TestHL7 {

    static SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");

    public void setHeader(MSH msh) throws DataTypeException{
        String nowDate = sdf.format(new Date());
        msh.getFieldSeparator().setValue("|");// 分隔符
        msh.getEncodingCharacters().setValue("^~\\&");// MSH-2
        msh.getMsh3_SendingApplication().getHd1_NamespaceID().setValue("01");
        msh.getMsh5_ReceivingApplication().getHd1_NamespaceID().setValue("PMI");
        msh.getDateTimeOfMessage().getTimeOfAnEvent().setValue(nowDate);// MSH-7
        msh.getMsh10_MessageControlID().setValue(nowDate + new Random().nextInt(100));// MSH-10
        msh.getMsh11_ProcessingID().getProcessingID().setValue("P");
        msh.getMsh12_VersionID().getVersionID().setValue("2.4");
        msh.getMsh15_AcceptAcknowledgmentType().setValue("AL");
        msh.getMsh16_ApplicationAcknowledgmentType().setValue("AL");
        msh.getMsh17_CountryCode().setValue("CHN");
        msh.getMsh18_CharacterSet(0).setValue("UNICODE");
    }

    public String getHL7Text() {

        QBP_Q11 qbp_q11 = new QBP_Q11();
        MSH msh = qbp_q11.getMSH();

        String msg = null;
        try {
            //MSH设置
            HL7Helper.setMsgValue(qbp_q11, MSH.class,"QBP", 9,0,0);
            HL7Helper.setMsgValue(qbp_q11, MSH.class,"ZP7", 9,0,1);
            setHeader(msh);

            //QBP设置
            QPD qbp = qbp_q11.getQPD();

            HL7Helper.setMsgValue(qbp_q11, QPD.class, "ZP7", 1,0,0);
            HL7Helper.setMsgValue(qbp_q11, QPD.class, "Find Candidates", 1,0,1);
            HL7Helper.setMsgValue(qbp_q11, QPD.class, "HL7v2.4", 1,0,2);

            //设置用户自定义Type
            qbp.getQpd3_UserParametersInsuccessivefields().setData(new UserDefineComposite(qbp_q11, 3));

            //新增Type类型为CE的字段
            HL7Helper.segmentAddFeild(qbp, CE.class, 250, qbp_q11);

            HL7Helper.setMsgValue(qbp_q11, QPD.class, "0", 3,0,0);
            HL7Helper.setMsgValue(qbp_q11, QPD.class, "2558856", 3,0,1);
            HL7Helper.setMsgValue(qbp_q11, QPD.class, "0", 3,0,2);

            HL7Helper.segmentAddFeild(qbp, CE.class, 100, qbp_q11);
            HL7Helper.setMsgValue(qbp_q11, QPD.class, "SamJoke", 5,0,0);

            HL7Helper.segmentAddFeild(qbp, CE.class, 250, qbp_q11);
            SimpleDateFormat sdf01 = new SimpleDateFormat("yyyyMMddHHmmss");
            SimpleDateFormat sdf02 = new SimpleDateFormat("yyyy-MM-dd");
            HL7Helper.setMsgValue(qbp_q11, QPD.class, sdf01.format(sdf02.parse("1994-8-30")), 6,0,0);

            HL7Helper.segmentAddFeild(qbp, CE.class, 1, qbp_q11);
            HL7Helper.setMsgValue(qbp_q11, QPD.class, "M", 7,0,0);

            //RCP设置
            HL7Helper.setMsgValue(qbp_q11, RCP.class, "I", 1,0,0);
            HL7Helper.setMsgValue(qbp_q11, RCP.class, "20", 2,0,0);
            HL7Helper.setMsgValue(qbp_q11, RCP.class, "RD", 2,0,1);
            HL7Helper.setMsgValue(qbp_q11, RCP.class, "R", 3,0,0);

            msg = qbp_q11.encode();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return msg;
    }

    public void hl7Text2Obj(String responseStr) {

        try {
            ASType[] asTypes = new ASType[7];
            asTypes[0] = new ASType(MSH.class,true,true);
            asTypes[1] = new ASType(MSA.class,true,true);
            asTypes[2] = new ASType(QAK.class,true,true);
            asTypes[3] = new ASType(QPD.class,true,true);
            asTypes[4] = new ASType(PID.class,true,true);
            asTypes[5] = new ASType(IN1.class,false,true);
            asTypes[6] = new ASType(QRI.class,false,true);

            UserDefineMessage udm = new UserDefineMessage(asTypes);

            UserDefineMessage udm1 = new UserDefineMessage(asTypes);

            UserDefineMessage udm2 = new UserDefineMessage(asTypes);

            QPD qpd = udm2.getAS(QPD.class);

            HL7Helper.segmentAddFeild(qpd, CE.class, 250, udm2);

            // 添加一个长度为1的CE数组
            HL7Helper.segmentAddFeild(qpd, CE.class, 250, udm2);

            // 添加一个长度为2的CE数组
            HL7Helper.segmentAddFeild(qpd, CE.class, 2, 250, udm2);

            // 添加一个长度为1的CE数组
            HL7Helper.segmentAddFeild(qpd, CE.class, 250, udm2);

            HL7Helper.acceptResponse(udm2, responseStr);

            MSH msh = (MSH) udm2.get("MSH");
            System.out.println(msh.encode());
            System.out.println(msh.getDateTimeOfMessage().getTs1_TimeOfAnEvent().toString());

            QPD qpdt = (QPD) udm2.get("QPD");
            System.out.println(qpdt.encode());
            System.out.println(qpdt.getQpd1_MessageQueryName().getCe1_Identifier().getValue());

            System.out.println(HL7Helper.getMsgValue(udm2, "QRI", 1,0,0));

            System.out.println(udm2.encode());
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        TestHL7 co = new TestHL7();

        System.out.println(co.getHL7Text());

        String resStr = "MSH|^~\\&|HALO|Mediinfo|MediII|Mediinfo|20220829141621||ORM^O01^ORM_O01|bba39c9f0da54bd4b0aef102bba0685d|P|2.4\r" +
                "PID||7748577|7748577^^^JG01~330212SYB0000278595^^^JG06~~~~330212SYB0000278595^^^JG06~33020099000000000022700386^^^JG07~SYB0000278595^^^JG08~~16413536^^^JG10||ChenBinJun^陈斌均||19990522000000|1|||宁波骏潮信息技术有限公司^^330200^330000^^^H~^^^^^^W^宁波骏潮信息技术有限公司||^^01^^^^15057443642~^^02|||20^已婚||330283199905227218^^^01|330283199905227218|||01^汉族|浙江省宁波市|||90^农民||156^中国||||0\r" +
                "NTE|1|备注||^患者6月前可能因工作压力等失眠,表现为入睡困难、易醒,醒后难以入睡,日间疲劳、思睡,伴有担心多虑,有重复检查门窗,可达20余次,有间断情绪低落,兴趣减退,精力疲乏,悲观,无消极言行,否认打鼾,无安静状态下的双下肢不适。^^反复失眠  6月^神志清,定向力完整,接触主动,对答切题,记忆力下降,思维形式无异常,否认幻觉、妄想,情绪焦虑、低落,情感反应协调,意志行为减退,社会功能受损,自知力存在。\r" +
                "PV1|10|O||R|||10386^^杨璐|||12|||||0|||600|1205082153^10||SYB1101||||||||||||||||||1|||00812^1号楼2楼A区^^1&&1^1^宁波市第一医院(海曙)||20220829140706|||||||V\r" +
                "ORC|NW|2022082911621^^1038880068||2022082911621|IP||||20220829141347|||10386^^杨璐|00812^^^^^^^^心理门诊||||00812^心理门诊^1|||20^0^0^^^0\r" +
                "OBR|1|2022082911621||33918^JSWS-植物神经功能检查^^17^JSWS|0|||||||02020301^心理测试(海曙)^1|||0000033918&JSWS-植物神经功能检查||^^^^^^13957821050|周六下午休息,其余正常检查。|||||^20|17\r" +
                "DG1|1||^焦虑状态|焦虑状态\r" +
                "OBX|1|ST|OB01^既往病史||患者6月前可能因工作压力等失眠,表现为入睡困难、易醒,醒后难以入睡,日间疲劳、思睡,伴有担心多虑,有重复检查门窗,可达20余次,有间断情绪低落,兴趣减退,精力疲乏,悲观,无消极言行,否认打鼾,无安静状态下的双下肢不适。||||||F|||20220829141347\r" +
                "OBX|2|ST|OB02^主诉||反复失眠  6月||||||F|||20220829141347\r" +
                "OBX|3|ST|OB03^体格检查||神志清,定向力完整,接触主动,对答切题,记忆力下降,思维形式无异常,否认幻觉、妄想,情绪焦虑、低落,情感反应协调,意志行为减退,社会功能受损,自知力存在。||||||F|||20220829141347";

        co.hl7Text2Obj(resStr);
    }

}

注意:这里要注意 \n 换成 \r

一开始这个东西我也研究了好久,才发现根据节点去解析,一般都有文档

 

104报文解析工具 可选择包含报文的文本文件或日志文件进行解析,可选择按条数范围或时间范围,输出结果可以在报文解析显示区,也可以输出到文件。可以对文本内容的报文文件进行高级分析,包括遥信遥测等通讯数据的具体信息,通讯帧的统计,通讯次数的统计,各种错误的分析,报文的定位功能,传输的文件具体内容等。输入完成后点击工具栏的解析报文按钮或使用右键菜单的解析就可以对报文进行解析。在报文输入区输入待解析报文并解析后,解析结果就显示在报文解析显示区和报文定位展示区及报文定位条目区。当有多条报文解析后,可以通过报文列表树具体定位某条报文。 阅读详情

相关推荐

基于JAVA HAPI包以树形结构实现可配置式 HL7 V2消息接收与解析

一、背景 HL7 卫生信息交换标准(Health Level 7)

东南_bit的博客 1万+

java解析HL7协议报文工具(v24版)

java解析HL7协议报文工具因为项目需要解析HL7协议报文,网上找到的工具都是解析成带位置信息的xml格式或者json格式,然后需要自己根据需要获取的位置来获取信息。而在生成的HL7协议报文的时候也是需要先生成xml或json格式再进行转换。想着希望找到一个直接解析生成类然后直接用的工具。 后来我找到了这个ca.uhn.hapi,能将HL7报文直接解析成相应的类,通过调用:PipeParser.

u010781468的博客 1万+

基于SpringBoot与HAPI框架的迈瑞监护仪HL7 v2.6数据流实时解析实战

本文详细介绍了基于SpringBoot与HAPI框架的迈瑞监护仪HL7 v2.6数据流实时解析实战。通过环境搭建、消息处理核心实现、关键生理参数提取技巧等步骤,帮助开发者高效解析医疗设备数据,满足临床实时性需求。文章还提供了性能优化、数据可视化集成及生产环境部署建议,助力医疗信息化项目落地。

weixin_28728495的博客 323

springboot接收HL7协议报文 HAPI(SpringBoot版本)

3. MyHl7ExceptionHandler-异常消息回复。2.MyReceivingApplication 消息处理类。2.SocketApp-服务类。

qq_37996327的博客 3416

避坑指南:SpringBoot集成HAPI处理HL7消息时,你可能会遇到的编码与ACK回复问题

本文详细解析了SpringBoot集成HAPI处理HL7消息时常见的编码与ACK回复问题,提供了字符集设置、ACK响应规范和版本兼容性等实战解决方案。特别针对医疗行业常见的GB18030编码问题,给出了三重保障策略,帮助开发者避免常见陷阱,提升系统稳定性和兼容性。

weixin_28732953的博客 243

SpringBoot + HAPI实战:5步搞定迈瑞ePM监护仪HL7 v2.6数据接入

本文详细介绍了如何使用SpringBoot和HAPI库快速实现迈瑞ePM监护仪的HL7 v2.6数据接入。通过5个关键步骤,包括环境配置、HL7服务端实现、特殊字段解析、测试调试技巧以及生产环境优化,帮助开发者高效解决医疗协议数据解析的挑战,适用于医疗物联网项目中的实时数据采集需求。

weixin_29597551的博客 210

java通过TCP实现HL7医疗系统传输协议

java通过TCP实现HL7医疗系统传输协议时遇到的问题

小软的博客 4729

HL7 JAVA解析版本

HL7 2.X解析(JAVA版) Hl7引擎的目标主要是解决将数据按HL7协议的要求标准化,和标准业务的集成和不同系统间标准业务数据的同步。在多年的医院信息化过程中,HL7标准组织和解析最复杂了。本次公开JAVA的

迈瑞监护仪ePM系列HL7医疗协议数据解析

1.引入Jar包(v26指的我们使用的监护仪传输的数据是2.6版本的,选择版本视情况而定。NIBP_M:血压平均值,HR:心率,OBR_TIME:参数报告时间,Pleth:波形数据。(将监护仪发送的真实数据贴在这里,并配置上自己设置的ip+端口,便可以模拟发送数据。RR:呼吸率,PR:脉搏,SPO2:血氧,NIBP_S:收缩压,NIBP_D:舒张压。首先,我这里解析HL7协议数据选择用的是Java语言,框架是SpringBoot。4. 最后,我们就可以解析出来监护仪原文数据对应的生理参数与波形数据。

我是臭鱼阿祥 4103

OpenCV实战:从边缘检测到透视校正,打造智能文档扫描仪(Python代码详解)

本文详细介绍了如何使用OpenCV和Python从零开始构建一个智能文档扫描仪。通过边缘检测、透视校正和文字增强等核心技术,将倾斜、模糊的文档照片转换为清晰、方正的高质量扫描图像。文章提供了完整的代码实现和参数调优经验,帮助开发者打造稳定、高效的文档处理工具。

flower的专栏 700

扩展卡尔曼滤波(EKF)理论讲解与实例(matlab、python和C++代码)

扩展卡尔曼滤波(EKF)理论讲解与实例(matlab、python和C++代码) 文章目录扩展卡尔曼滤波(EKF)理论讲解与实例(matlab、python和C++代码)理论讲解KF和EKF模型对比雅可比矩阵计算计算实例应用实例线性模型CV模型:CA模型非线性模型CTRV模型:CTRV实例(python)small demo抛物线demo飞机高度demoC++实例参考文献 我们上篇提到的卡尔曼滤波是用于线性系统,预测(运动)模型和观测模型是在假设高斯和线性情况下进行的。简单的卡尔曼滤波必须应用在符合高斯分布

O_MMMM_O的博客 10万+

Spring Boot项目实战:用HAPI库搞定医疗设备HL7数据实时接收与解析(附完整代码)

本文详细介绍了如何在Spring Boot项目中使用HAPI库实现医疗设备HL7数据的实时接收与解析。通过构建高可用的HL7 Socket监听服务,结合WebSocket技术实现数据实时推送,帮助开发者快速掌握医疗信息化领域的关键技术。文章包含完整代码示例,涵盖协议解析、业务处理、性能优化等核心环节。

weixin_30700977的博客 246

【解决问题】‘vue‘ 不是内部或外部命令,也不是可运行的程序或批处理文件。

【解决问题】'vue' 不是内部或外部命令,也不是可运行的程序或批处理文件。

weixin_44566194的博客 4万+

从零到生产:Spring Boot整合HAPI实现HL7消息收发完整指南

本文详细介绍了如何使用Spring Boot整合HAPI实现HL7消息的收发,从环境准备、消息解析到生产级优化,提供完整实战指南。通过HAPI工具包,开发者可以高效处理医疗信息系统中的HL7标准消息,实现消息解析、构造及ACK响应等核心功能,适用于医院系统对接等医疗健康领域应用。

weixin_29234509的博客 266

华为EC6108V9E刷机实战:从U盘准备到开机优化的完整避坑指南

本文提供华为悦盒EC6108V9E刷机与优化的完整实战指南。针对搭载RK3228芯片和安卓4.4.4系统的设备,从型号确认、固件选择、U盘准备,到详细刷机步骤、常见故障排除,以及刷机后的深度性能优化,手把手帮助用户规避风险,让旧盒子焕发新生,成为流畅的全能媒体中心。

weixin_29324401的博客 1220

【计算机视觉】语义分割实战:FCN、U-Net与DeepLab系列详解

语义分割实战:FCN、U-Net与DeepLab系列详解,人工智能、大模型、AI深度学习在计算机视觉领域取得了令人瞩目的进展,语义分割作为计算机视觉领域的关键任务,旨在将图像中的每个像素都分配到特定的类别中,实现对图像内容的精细理解。与目标检测关注物体的类别与位置不同,语义分割能够对场景中的所有元素进行像素级别的分类,这在自动驾驶、医学图像分析、遥感图像解译等众多领域都有着至关重要的应用。例如,在自动驾驶中,准确的语义分割可以帮助车辆识别道路、行人、交通标志等,为安全行驶提供决策依据;在医学图像分析中……

不踩坑,不知道坑有多深;不总结,踩过的坑白踩。 9万+

【亲测免费】 HAPI FHIR 安装和配置指南

### 项目基础介绍 HAPI FHIR 是一个开源的 Java API,用于实现 HL7 FHIR 客户端和服务器。HL7 FHIR(Fast Healthcare Interoperability Resources)是一种用于医疗数据交换的标准,旨在提高不同系统之间的互操作性。HAPI FHIR 提供了一个完整的 FHIR 实现,支持多种 FHIR 版本,包括 DSTU2、DSTU3、R4、...

gitblog_07018的博客 1202

28、基于图像快速序列视觉呈现(RSVP)的脑机接口特征提取与分类算法综述

本文综述了基于图像快速序列视觉呈现(RSVP)的脑机接口(BCI)中的特征提取与分类算法。RSVP技术通过快速连续呈现图像序列,结合脑电图(EEG)信号分析,实现对目标图像的识别和标记。文章详细介绍了RSVP实验的设计、EEG数据的采集与预处理,并探讨了低信噪比、维度灾难、重叠epoch和不平衡数据集等挑战。针对特征提取,讨论了有监督空间滤波方法(如CSP、xDAWN、LDA波束形成器)的原理和应用。在分类策略部分,涵盖了线性分类技术(如LDA、BLR、LR、SVM)和非线性分类方法(如MLP、CNN)。文

hh234的博客 340

SpringBoot整合FHIR:手把手实现HIS与EMR的患者数据共享

本文详细介绍了如何使用SpringBoot整合FHIR标准,实现医院信息系统(HIS)与电子病历系统(EMR)之间的患者数据共享。通过FHIR的标准化资源模型和RESTful API设计,结合SpringBoot的高效开发框架,开发者可以构建安全、高效的医疗数据交换解决方案,有效打破医疗信息孤岛问题。

u5v6w7的博客 701

CDD那些事 - DID and SecurityAccess

本文介绍了SecurityAccessSID27的安全访问配置流程:1.通过StateGroups添加Level2群组;2.在Classes定义L2子功能;3.配置4步解锁流程,选择对应解锁等级;4.在DiagnosticInstance设置请求响应。同时说明了DID配置的两种方式:在DIDs页面定义或通过Identification页面创建,前者定义更全面。文章还提到ServiceList支持view/edit模式,其中edit模式可配置DID的多服务支持(如同时支持SID22读取和SID2E写入),但该

ziteng21的博客 261

96.在 Vue 3 中使用 OpenLayers 探究加载 Point、Polygon 的极限

在前端 GIS(地理信息系统)开发中,OpenLayers 作为一个功能强大的 Web 地图库,广泛用于加载地图、渲染矢量数据(点、线、面)、叠加图层等场景。然而,当涉及到。

小彭的博客 1159

FHIR、FAPI 初体验

FHIR、HAPI的简单应用和理解

S_p_carry的博客 1884

汉书HE8,好用的汇编代码编写工具

汉书HE8,好用的汇编代码编写工具早期编写汇编代码所用功能强大

SpringBoot+FHIR构建医疗数据共享平台:手把手实现HIS与EMR的患者信息互通

本文详细介绍了如何使用SpringBoot和FHIR标准构建医疗数据共享平台,实现医院信息系统(HIS)与电子病历(EMR)之间的患者信息互通。通过集成HAPI-FHIR库,开发者可以快速搭建符合国际标准的RESTful API服务,并探讨了OAuth2安全方案的实施,为打破医疗数据孤岛、提升诊疗效率提供了实战解决方案。

rrr55的博客 297

NTscan扫描工具

ntscan是一个扫描器,可以扫描没有密码和弱密码的共享,先到配置文件中填写猜测的用户名和密码,扫描过程中右侧出现的是扫描日志。

jre9下载 jdk9

(Java SE Runtime Environment 9.0) 9.0u175 官方最新版 【x86|x64】

SpringBoot+Java构建医疗陪诊系统的技术实践

医疗信息系统开发中,Java因其跨平台特性和强大的类型检查机制,成为处理医疗设备对接和敏感数据管理的首选语言。结合SpringBoot框架的快速开发优势,开发者可以高效构建包含安全认证、数据持久化等核心功能的RESTful服务。在医疗陪诊系统这类特殊场景下,技术选型需要兼顾HL7协议兼容性、复杂查询性能以及数据安全要求。通过分布式锁、TCC事务等机制,能够有效解决医疗场景下的并发预约和支付对账等典型问题。本文以实际项目为例,详解如何利用SpringBoot+Java技术栈应对医疗陪诊系统中的技术挑战,包括智

weixin_29268267的博客 156

大中型超市收银系统(可直接运行)

光步前台收银系统系统功能:商品销售、商品退货、挂单、收银员权限、会员销售、单品取消、整单取消、商品查询、脱机销售、脱机数据上传,基本资料下载,开钱箱、小票打印、收款结算,支持多币种付款方式(现金、储值卡、礼券、微信等),支持多种促销。运行环境:.net 4.0登陆信息用户名:1001 密码:123456内置商品信息,商品编码可输入00001000 - 00010000,测试效果相关功能键F5 结算 F9挂单 F11商品查询 F8退货 Insert单品取消 Del整单取消 F12开钱箱F2 会员 Ctrl+Z退出系统 Home 锁屏 相关源码待公开

上一篇: Spring5秘籍手册+架构导图看了吗?
下一篇: 阿里首席架构师讲解“双十一”亿级流量高并发的系统架构搭建方法
Java技术那些事儿
博客等级 码龄5年 2306粉丝 2584原创
评论 4
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
⌂ 换网址