package com.malk.mcli.config;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.cxf.binding.soap.SoapMessage;
import org.apache.cxf.helpers.IOUtils;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.phase.AbstractPhaseInterceptor;

import java.io.ByteArrayInputStream;
import java.io.InputStream;

@Slf4j
public class WsInInterceptor extends AbstractPhaseInterceptor<SoapMessage> {

    public WsInInterceptor(String phase) {
        super(phase);
    }

    @Override
    public void handleMessage(SoapMessage message) throws Fault {
        try {
            // 从流中获取请求消息体并以字符串形式输出，注意IOUtils是cxf的包；
            String input = IOUtils.toString(message.getContent(InputStream.class), "UTF-8");
            // 如果内容不为空（第一次连接也会被拦截，此时input为空）
            if (StringUtils.isNotBlank(input)) {
                // 修改请求消息体为webservice服务要求的格式
                input = input.replace("<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\">", "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ser=\"http://server.dandelion.com\">")
                        .replace("<esb:getData xmlns:esb=\"mdm.stardand.com\">", "<ser:getData>")
                        .replace("</esb:getData>", "</ser:getData>").replace("ns2:InvokeResponse", "InvokeResponse");
                log.info("ns2:InvokeResponse, {}", input);
            }

            // 重新写入
            message.setContent(InputStream.class, new ByteArrayInputStream(input.getBytes()));
        } catch (Exception e) {
            System.out.println(String.format("解析报文异常: %s", e.getMessage()));
        }
    }
}
