WMS仓储系统对接奇门云网关Java接口实现

介绍:

基于spring框架 实现的奇门云网关 WMS端 通用API方法

编码思路:

1.接收ERP端xml类型的参数(request.getInputStream()),为方便取值转换为Json格式(xmlForJson(sb.toString()))

2.判断ERP端请求的奇门接口名称(request.getParameter("method"))走不同的业务实现方法(switch case注释部分),各接口返回数据均有差异,请参照淘宝奇门接口API文档

3.各实现方法返回Map格式数据,转换为xml格式返回,为防止乱码情况,我们转为byte数组返回(multilayerMapToXml(resultMap, false).getBytes("UTF-8"))

代码实现:

package org.tempuri;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.mingsoft.util.StringUtil;
import net.sf.json.JSONObject;
import net.sf.json.xml.XMLSerializer;

@Controller
@RequestMapping("api/open/qiMenApi")
public class QiMenTest {

    @ResponseBody
    @RequestMapping(value="/apiRealization",produces="text/xml;charset=UTF-8")
    public byte[] apiRealization(HttpServletRequest request, HttpServletResponse response) {
        // AppKey
        String appKeyVal = request.getParameter("app_key");
        // API接口名称
        String methodVal = request.getParameter("method");
        // 时间戳,格式:yyyy-MM-dd HH:mm:ss
        String timestampVal = request.getParameter("timestamp");
        // 请求签名
        String signVal = request.getParameter("sign");
        byte[] result = null;
        Map<String, Object> resultMap = new HashMap<>();
        InputStream inputStream;
        StringBuffer sb = new StringBuffer();
        try {
            // 解析xml参数
            inputStream = request.getInputStream();
            String s;
            BufferedReader in = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
            while ((s = in.readLine()) != null) {
                sb.append(s);
            }
            in.close();
            inputStream.close();
            if(sb.length() > 0) {
                // json格式的报文参数
                JSONObject xmlToJson = JSONObject.fromObject(xmlForJson(sb.toString()));
                if(!StringUtil.isBlank(methodVal)) {
                    switch (methodVal) {
                        case "deliveryorder.create":
                            // 发货单创建接口
                            //resultMap = ;
                            break;
                        case "entryorder.create":
                            // 入库单创建接口
                            //resultMap = ;
                            break;
                        case "stockout.create":
                            // 出库单创建接口
                            //resultMap = ;
                            break;
                        case "order.cancel":
                            // 单据取消接口
                            //resultMap = ;
                            break;
                        case "singleitem.synchronize":
                            // 商品同步接口
                            //resultMap = ;
                            break;
                        default:
                            resultMap.put("message", "接口名称method填写有误!");
                            resultMap.put("flag", "failure");
                            resultMap.put("code", "500");
                            break;
                    }
                }else {
                    resultMap.put("message", "接口名称method不能为空!");
                    resultMap.put("flag", "failure");
                    resultMap.put("code", "500");
                }
                result = multilayerMapToXml(resultMap, false).getBytes("UTF-8");
            }else {
                result = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>".getBytes("UTF-8");
            }
        } catch (Exception e) {
            resultMap.put("flag", "failure");
            resultMap.put("code", "500");
            resultMap.put("message", "操作失败,参数有误!");
            try {
                result = multilayerMapToXml(resultMap, false).getBytes("UTF-8");
            } catch (UnsupportedEncodingException e1) {
                return null;
            }
        }
        return result;
    }

    /**
     * xml字符串转json字符串
     * @param xml
     * @return
     */
    private Object xmlForJson(String xml) {
        XMLSerializer xmlSerializer = new XMLSerializer();
        String resutStr = xmlSerializer.read(xml).toString();
        return resutStr;
    }
    
    /**
     * (多层)map转换为xml格式字符串
     *
     * @param map 需要转换为xml的map
     * @param isCDATA 是否加入CDATA标识符 true:加入 false:不加入
     * @return xml字符串
     * @throws UnsupportedEncodingException 
     */
    public static String multilayerMapToXml(Map<String, Object> map, boolean isCDATA) throws UnsupportedEncodingException{
        String parentName = "response";
        Document doc = DocumentHelper.createDocument();
        doc.addElement(parentName);
        String xml = recursionMapToXml(doc.getRootElement(), parentName, map, isCDATA);
        return formatXML(xml);
    }

    /**
     * multilayerMapToXml核心方法,递归调用
     *
     * @param element 节点元素
     * @param parentName 根元素属性名
     * @param map 需要转换为xml的map
     * @param isCDATA 是否加入CDATA标识符 true:加入 false:不加入
     * @return xml字符串
     */
    @SuppressWarnings("unchecked")
    private static String recursionMapToXml(Element element, String parentName, Map<String, Object> map, boolean isCDATA) {
        Element xmlElement = element.addElement(parentName);
        map.keySet().forEach(key -> {
            Object obj = map.get(key);
            if (obj instanceof Map) {
                recursionMapToXml(xmlElement, key, (Map<String, Object>)obj, isCDATA);
            } else {
                String value = obj == null ? "" : obj.toString();
                if (isCDATA) {
                    xmlElement.addElement(key).addCDATA(value);
                } else {
                    xmlElement.addElement(key).addText(value);
                }
            }
        });
        return xmlElement.asXML();
    }
    
    /**
     * 格式化xml,显示为容易看的XML格式
     *
     * @param xml 需要格式化的xml字符串
     * @return
     */
    public static String formatXML(String xml) {
        String requestXML = null;
        try {
            // 拿取解析器
            SAXReader reader = new SAXReader();
            Document document = reader.read(new StringReader(xml));
            if (null != document) {
                StringWriter stringWriter = new StringWriter();
                // 格式化,每一级前的空格
                OutputFormat format = new OutputFormat("    ", true);
                // xml声明与内容是否添加空行
                format.setNewLineAfterDeclaration(false);
                // 是否设置xml声明头部
                format.setSuppressDeclaration(false);
                // 是否分行
                format.setNewlines(true);
                XMLWriter writer = new XMLWriter(stringWriter, format);
                writer.write(document);
                writer.flush();
                writer.close();
                requestXML = stringWriter.getBuffer().toString();
            }
            return requestXML;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    
}
上一篇:Mybatis中输入输出映射和动态Sql


下一篇:JavaEE权限管理系统的搭建(七)--------管理用户的增删改