处理Base64加密的xml文件、Dom解析、提取数据,保存到MySQL

处理Base64加密的xml文件、解析、提取数据,保存到MySQL

Document、Element

 

public BaseRet addProductionDefine(ProductDefineBody body) {
    ProductDefineEntity entityProductCode = productDefineDAO.findFirstByOrderByProductCodeDesc();
    ProductDefineEntity entity = new ProductDefineEntity();
    Optional<ProductDefineEntity> optional = Optional.ofNullable(entity);
    if (!optional.isPresent()) {
        entity.setProductCode(1);
    } else {
        entity.setProductCode(entityProductCode.getProductCode() + 1);
    }
    // 处理specContent 前端传Base64加密过的xml文档
    String xmlContent = body.getSpecContent();
    if (StringUtils.isEmpty(xmlContent)) {
        return BaseRet.createFailureRet("内容不正确");
    }
    /** decode xmlContent */
    String xmlContentDecode = xmlDecode(xmlContent);
    BeanUtils.copyProperties(body, entity);
    Document document = null;
    try{
        document = DocumentHelper.parseText(xmlContentDecode);
    }catch (DocumentException e) {
        e.printStackTrace();
        log.info("文档内容不正确{}",e.getMessage());
        return BaseRet.createFailureRet("文档内容不正确");
        //throw new RuntimeException("文档内容不正确");

    }
    if (document == null) {
        log.info("Dom4j格式处理后空");
        return BaseRet.createFailureRet("文档内容不正确");
    }
    Element rootElement = document.getRootElement();
    int productCode = entity.getProductCode();
    String productName = "";
    if ("spec".equals(rootElement.getName())) {
        productName = rootElement.attribute("name").getValue();
        if (StringUtils.isEmpty(productName)) {
            log.info("缺少关键字段");
            return BaseRet.createFailureRet("文档内容不正确");
        }

        /**
         * 获取spec产品规格描述,如:
         <spec name="ecooker_2kw">
         **/
        entity.setProductName(productName);
        /** 保存产品资源列表并生成资源id字符串(每个资源id使用逗号分隔)  **/
        if (body.getResourceList() != null) {
            List<String> resIdList = sysResourceService.addSysResource(body.getResourceList());
            entity.setProductImage(resIds2ImagesString(resIdList));
        } else {
            entity.setProductImage(null);
        }
        productDefineDAO.save(entity);
        List<Element> list = rootElement.elements();
        for (Element e : list) {
            Element moduleElement = e.element("module");
            String reserveValue = moduleElement.element("reserve").getText();
            String moduletypeValue = moduleElement.element("moduletype").getText();

            /**     设备参数表只要模块含有以下节点,提取参数信息 **/
            drawParameterToDeviceFuncEntity(e, reserveValue, moduletypeValue, productCode, productName);

            /**     设备参数表只要模块含有以下节点,提取参数信息* **/
            drawParameterToDeviceVarEntity(e, reserveValue, moduletypeValue, productName);

        }

    } else if ("root".equals(rootElement.getName())) {
        productName = handleStandardXml(rootElement);
        if (StringUtils.isEmpty(productName)) {
            log.info("spec 缺少关键字");
            return BaseRet.createFailureRet("文档内容不正确");
        }
        entity.setProductName(productName);
        /** 保存产品资源列表并生成资源id字符串(每个资源id使用逗号分隔)  **/

        if (body.getResourceList() != null) {
            List<String> resIdList = sysResourceService.addSysResource(body.getResourceList());
            entity.setProductImage(resIds2ImagesString(resIdList));
        } else {
            entity.setProductImage(null);
        }
        productDefineDAO.save(entity);

        /**  提取xml中的参数、函数信息
         1、获取xml中的lua算法模块    ***/
        Element luaModule = rootElement.element("lua");
        if (StringUtils.isEmpty(luaModule.getText())) {
            log.info("lua模块空");
            return BaseRet.createFailureRet("文档内容不正确");
        }
        // 获取luaModule模块的一级子节点集
        List<Element> childElments = luaModule.elements();
        if (childElments.isEmpty()) {
            log.info("spec文本不存在算法集");
            return BaseRet.createFailureRet("文档内容不正确");
        }

        for (Element e : childElments) {

            /**  2、提取Lua算法模块中的设备函数相关信息    **/
            String reserveValue = e.element("module").element("reserve").getText();
            String moduleTypeValue = e.element("module").element("moduletype").getText();
            drawParameterToDeviceFuncEntity(e, reserveValue, moduleTypeValue, productCode, productName);

            /**   3、 模块含有以下节点,提取参数信息    **/
            drawParameterToDeviceVarEntity(e, reserveValue, moduleTypeValue, productName);

        }

    }
    drawDataToDeviceAbility(productName, productCode);

    return BaseRet.createSuccessRet();

}


    // 判断文件格式
    public Document dealXml(String xmlContentDecode) {
        Document document = null;
        // File Decode Recovery
        try {
            document = DocumentHelper.parseText(xmlContentDecode);
        } catch (DocumentException e) {
            e.printStackTrace();
            throw new RuntimeException("文本格式有误");
        }
        if (document == null) {
            throw new RuntimeException("文本内容空");
        }

        return document;

    }


public String handleStandardXml(Element rootElement) {
        // 处理标准xml文档(spec文档)
        List<Element> infoElementList = rootElement.element("specs").elements("info");
        if (infoElementList == null || infoElementList.isEmpty()) {
            return null;
        }
        Map<String, String> infoMap = new HashMap<>();
        for (Element info : infoElementList) {
            String nameKey = info.attribute("name").getValue();
            String valueValue = info.attribute("value").getValue();
            infoMap.put(nameKey, valueValue);
        }
        String productName = infoMap.get("KS_CODE");
        if (StringUtils.isEmpty(productName)) {
            log.info("缺少关键字段");
            return null;
        }
        return productName;
    }


public String getProductName(ProductDefineBody body) {
        String xmlContent = body.getSpecContent();
        if (StringUtils.isEmpty(xmlContent)) {
            return null;
        }
        String xmlContentDecode = xmlDecode(xmlContent);
        Document doc = null;
        try {
            doc = dealXml(xmlContentDecode);
        }catch (RuntimeException e){
            return null;
        }
        Element root = doc.getRootElement();
        // 需要进一步验证
        if ("spec".equals(root.getName())) {
            String productName = root.attribute("name").getValue();
            if (StringUtils.isEmpty(productName)) {
                log.info("缺少关键字段");
                return null;
            } else {
                return productName;
            }
        } else if ("root".equals(root.getName())) {
            return handleStandardXml(root);
        }
        return null;
    }

    public void drawParameterToDeviceFuncEntity(Element e, String reserveValue, String moduletypeValue, int productCode, String productName) {
        if ("0".equals(reserveValue) && "output".equals(moduletypeValue)) {
            DeviceFuncdefineEntity funcEntity = new DeviceFuncdefineEntity();
            String funcName = e.element("module").element("name").getText();
            funcEntity.setFunctionName(funcName);
            funcEntity.setFunctionNamedesc(e.element("module").element("desc").getText());
            String pardesc = e.element("module").element("pardesc").getText();

            funcEntity.setParameterList(getParameterString(pardesc));
            /** 函数码属性,获取表中同一设备下的最大的函数码值 **/
            Sort sort = new Sort(Sort.Direction.DESC, "functionCode");

            List<DeviceFuncdefineEntity> list = deviceFuncdefineDAO.findAllByProductCode(productCode, sort);
            if (!list.isEmpty()) {
                DeviceFuncdefineEntity deviceFuncdefineEntity = list.get(0);
                funcEntity.setFunctionCode(deviceFuncdefineEntity.getFunctionCode() + 1);
            } else {
                funcEntity.setFunctionCode(1);

            }

            int productCode0 = productDefineDAO.findFirstByProductName(productName).getProductCode();
            funcEntity.setProductCode(productCode0);
            System.out.println(funcEntity);

        }
    }


    private String getParameterString(String parameterString) {
        JSONArray jsonArray = new JSONArray();
        JSONObject jsonObject = JSONObject.parseObject(parameterString);
        Set<String> keys = jsonObject.keySet();
        for (String s : keys) {
            JSONObject childJosn = (JSONObject) JSONObject.parse(jsonObject.getString(s));
            Map jsponMap = new LinkedHashMap();
            jsponMap.put("name", s);
            String pardescString = "";
            if (!StringUtils.isEmpty(childJosn.getString("desc"))) {
                jsponMap.put("nameDescription", childJosn.getString("desc"));
                pardescString = childJosn.getString("desc");
            } else {
                jsponMap.put("nameDescription", childJosn.getString("displayname"));
                pardescString = childJosn.getString("displayname");
            }

            if (!StringUtils.isEmpty(pardescString)) {
                if (pardescString.contains("温度")) {
                    String dataType = "temperature";
                    String unit = "摄氏度";//摄氏度  ℃
                    dealDataTypeAndUnit(dataType, unit, jsponMap);
                } else if (pardescString.contains("功率")) {
                    String dataType = "power";
                    String unit = "瓦";
                    dealDataTypeAndUnit(dataType, unit, jsponMap);
                } else if (pardescString.contains("时间")) {
                    String dataType = "time";
                    String unit = "秒";
                    dealDataTypeAndUnit(dataType, unit, jsponMap);
                } else if (pardescString.contains("物料")) {
                    String dataType = "materiel-id";
                    String unit = "";
                    dealDataTypeAndUnit(dataType, unit, jsponMap);
                } else if (pardescString.contains("提示")) {
                    String dataType = "char";
                    String unit = "";
                    dealDataTypeAndUnit(dataType, unit, jsponMap);
                } else {
                    String dataType = "string";
                    String unit = "";
                    dealDataTypeAndUnit(dataType, unit, jsponMap);
                }
                if (!StringUtils.isEmpty(childJosn.getString("scope"))) {
                    jsponMap.put("scope", childJosn.getString("scope"));
                }else {
                    jsponMap.put("scope", null);
                }
                if (!StringUtils.isEmpty(childJosn.getString("select"))) {
                    jsponMap.put("select", childJosn.getString("select"));
                }else {
                    jsponMap.put("select", null);
                }
            }

            JSONObject json = new JSONObject(jsponMap);
            jsonArray.add(json);
        }

        return StringEscapeUtils.unescapeJavaScript(jsonArray.toJSONString());
    }

    private void dealDataTypeAndUnit(String dataType, String unit, Map jsonMap) {
        jsonMap.put("dataType", dataType);
        if(StringUtils.isEmpty(unit)){
            jsonMap.put("unit",null);
        }else{
            jsonMap.put("unit", unit);
        }

    }

    private void drawDataToDeviceAbility(String productName, int productCode){
        int startIndex = productName.lastIndexOf("_");
        String deviceAbility = productName.substring(startIndex+1,productName.length());
        deviceAbility = deviceAbility.toLowerCase();
        if (!StringUtils.isEmpty(deviceAbility) && deviceAbility.contains("kw")){
            DeviceAbilityEntity deviceAbilityEntity = new DeviceAbilityEntity();
            deviceAbilityEntity.setProductCode(productCode);
            deviceAbilityEntity.setAbilityName("MaxPower");
            deviceAbilityEntity.setAbilityDesc("最大功率");
            deviceAbilityEntity.setUnit("w");
            if (deviceAbility.contains(".")){
                deviceAbility = deviceAbility.replace(".","");
                deviceAbility =deviceAbility.substring(0,deviceAbility.indexOf("k"));
                int abilityValue = Integer.valueOf(deviceAbility)*100;
                deviceAbility = String.valueOf(abilityValue);
                deviceAbilityEntity.setAbilityValue(deviceAbility);
                deviceAbilityDAO.save(deviceAbilityEntity);
            } else {
                deviceAbility =deviceAbility.substring(0,deviceAbility.indexOf("k"));
                int abilityValue = Integer.valueOf(deviceAbility)*1000;
                deviceAbility = String.valueOf(abilityValue);
                deviceAbilityEntity.setAbilityValue(deviceAbility);
                deviceAbilityDAO.save(deviceAbilityEntity);
            }
        }
    }

    public void drawParameterToDeviceVarEntity(Element e, String reserveValue, String moduletypeValue, String productName) {
        String temperature = "温度";
        String pressure = "压力";
        String weight = "重量";
        String numberic = "数值";
        String power = "功率";
        String capacity = "容量";
        String time = "时间";
        if ((("0".equals(reserveValue)) && "metadata".equals(moduletypeValue)) ||
                ((("0".equals(reserveValue)) && "userinput".equals(moduletypeValue)))) {
            DeviceVardefineEntity varEntity = new DeviceVardefineEntity();
            varEntity.setVarName(e.element("module").element("name").getText());
            varEntity.setVarNamedesc(e.element("module").element("desc").getText());

            String srcStr = e.element("module").element("desc").getText();

            if (srcStr.contains(temperature) || srcStr.contains(pressure) || srcStr.contains(weight) || srcStr.contains(numberic)) {
                varEntity.setDatatype("double");
            } else if (srcStr.contains(power) || srcStr.contains(capacity) || srcStr.contains(time)) {
                varEntity.setDatatype("unit32");
            } else {
                varEntity.setDatatype("string");
            }
            // 处理数据类型

            String ref = e.element("module").element("ref").getText();
            // 获取<ref>{"Pwr":{"desc":"功率","unit":"瓦","scope":["0","3500"]}}</ref>
            JSONObject jsonObject = JSONObject.parseObject(ref);

            Set<String> keys = jsonObject.keySet();
            for (String s : keys) {
                JSONObject childJosn = (JSONObject) JSONObject.parse(jsonObject.getString(s));
                String scope = childJosn.getString("scope");
                String select = childJosn.getString("select");
                varEntity.setScope(scope);
                varEntity.setVarselect(select);
            }
            int productCode = productDefineDAO.findFirstByProductName(productName).getProductCode();
            varEntity.setProductCode(productCode);
            Sort sort = new Sort(Sort.Direction.DESC, "varCode");

            List<DeviceVardefineEntity> list = deviceVardefineDAO.findAllByProductCode(productCode, sort);
            if (!list.isEmpty()) {
                DeviceVardefineEntity deviceVardefineEntity = list.get(0);
                varEntity.setVarCode(deviceVardefineEntity.getVarCode() + 1);
            } else {
                varEntity.setVarCode(1);

            }
            varEntity.setEventPriority(1);
            
        }
    }


// 对Base64编码的数据进行解码
public String xmlDecode(String xmlContent) {
    String xmlContentDecode = null;
    xmlContentDecode = new String(Base64.getDecoder().decode(xmlContent));
    return xmlContentDecode;
}


 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值