From 2dbea71ba02bc0be533e4aaf1ca6e6632a117a5b Mon Sep 17 00:00:00 2001 From: ic_excellent <2570192571@qq.com> Date: Fri, 2 Jun 2023 11:00:00 +0800 Subject: [PATCH] =?UTF-8?q?=E4=B8=8A=E4=BC=A0=E6=96=87=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controller/ReportController.java | 55 ++++++ .../xiao/sh_bigdata/mapper/ReportMapper.java | 39 ++++ .../sh_bigdata/service/ReportService.java | 47 +++++ .../xiao/zhenn/controller/BankController.java | 30 +++- .../bokang/xiao/zhenn/mapper/BankMapper.java | 101 ++++++++++- .../xiao/zhenn/service/BankService.java | 148 +++++++++++++++- .../zenner/job/SyncAccountTradeInfoJob.java | 5 +- .../weaver/bokang/xiao/common/CommonUtil.java | 166 +++++++++++++++++- .../xiao/common/mapper/WorkflowMapper.java | 7 + .../process/ConditionWhereProcess.java | 130 ++++++++++++++ .../porsche/action/DateFieldUpdateAction.java | 3 + .../xiao/porsche/mapper/PorscheMapper.java | 4 +- .../schedule/CompanyWriteBackSchedule.java | 2 +- .../sh_bigdata/action/DataPushAction.java | 3 +- .../schedule/GenerateReportSchedule.java | 3 +- .../xiao/zscq/action/OneNetComAction.java | 11 +- src/test/java/bokang/xiao/NormalTest.java | 55 +++++- src/test/java/bokang/xiao/util/XmlParser.java | 94 ++++++++++ 18 files changed, 879 insertions(+), 24 deletions(-) create mode 100644 src/main/java/com/api/bokang/xiao/sh_bigdata/controller/ReportController.java create mode 100644 src/main/java/com/api/bokang/xiao/sh_bigdata/mapper/ReportMapper.java create mode 100644 src/main/java/com/api/bokang/xiao/sh_bigdata/service/ReportService.java create mode 100644 src/main/java/weaver/bokang/xiao/common/model_update/process/ConditionWhereProcess.java create mode 100644 src/test/java/bokang/xiao/util/XmlParser.java diff --git a/src/main/java/com/api/bokang/xiao/sh_bigdata/controller/ReportController.java b/src/main/java/com/api/bokang/xiao/sh_bigdata/controller/ReportController.java new file mode 100644 index 0000000..854970b --- /dev/null +++ b/src/main/java/com/api/bokang/xiao/sh_bigdata/controller/ReportController.java @@ -0,0 +1,55 @@ +package com.api.bokang.xiao.sh_bigdata.controller; + +import aiyh.utils.ApiResult; +import aiyh.utils.Util; +import com.api.bokang.xiao.sh_bigdata.service.ReportService; +import io.swagger.v3.oas.annotations.parameters.RequestBody; +import org.apache.log4j.Logger; +import weaver.hrm.HrmUserVarify; +import weaver.hrm.User; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import java.util.List; +import java.util.Map; + +/** + * @ClassName YearReviewController + * @Author 肖博亢 + * @Date 2023/2/14 17:00 + * @Description

保时捷年终总结相关接口

+ **/ +@Path("/xbk/sh_bigdata") +public class ReportController { + + private final Logger log = Util.getLogger(); + ReportService reportService = new ReportService(); + + /** + *

获取创建或处理流程的总数

+ * @param request 请求体 + * @param response 响应体 + * @param param 请求参数 + * @return 请求结果 + */ + @Path("/getReportData") + @POST + @Produces(MediaType.APPLICATION_JSON) + public String getReportData(@Context HttpServletRequest request, @Context HttpServletResponse response, @RequestBody Map param) { + try{ + log.info("into getReportData success params ==> "+param); + User loginUser = HrmUserVarify.getUser(request, response); + List> reportData = reportService.queryReportData(param, loginUser); + return ApiResult.success(reportData); + }catch (Exception e){ + log.error("getReportData error ==> "+Util.getErrString(e)); + return ApiResult.error(e.getMessage()); + } + } + +} diff --git a/src/main/java/com/api/bokang/xiao/sh_bigdata/mapper/ReportMapper.java b/src/main/java/com/api/bokang/xiao/sh_bigdata/mapper/ReportMapper.java new file mode 100644 index 0000000..716dd9b --- /dev/null +++ b/src/main/java/com/api/bokang/xiao/sh_bigdata/mapper/ReportMapper.java @@ -0,0 +1,39 @@ +package com.api.bokang.xiao.sh_bigdata.mapper; + +import aiyh.utils.annotation.recordset.*; + +import java.util.List; +import java.util.Map; + +/** + * @ClassName ReviewMapper + * @Author 肖博亢 + * @Date 2023/2/14 17:02 + * @Description

+ **/ +@SqlMapper +public interface ReportMapper { + + /** + *

查询日程报表信息

+ * @param uid 用户id + * @param param 参数信息 + * @return 前五条流程数据 + */ + @Select("select id, ysdx, hdlb, ysrq, ysclhjsy, hbcc, xcap, gzryhcl, zs, ykdhhgbs, " + + " dyjbr, (select lastname from hrmresource where id = dyjbr) dyjbr_span," + + " djr, (select lastname from hrmresource where id = djr) djr_span," + + " ldrlddw, rwzt, bz, ysjsy, ysrs, cfsj1, ddsj1, sfz, ddz, gzcl, gbs, lddw, lxr, lxrdh " + + " from $t{param.table} $t{param.whereSql} order by ysrq ") + @CaseConversion(value = false) + List> queryReportData(@ParamMapper("param") Map param,@ParamMapper("uid") int uid); + + @Select("select id,dlsk,yslx,hbcc,sfsj,ddsj,sfd,ddd,wdwcl,dwcljsy,wdwclqt,xcap,lxr,lxrdh,bz,gzcl,gzry,zs,dyjbr,djr,ldr,lddw,rwzt,ykdh,gbs, " + + " (select LISTAGG(wb, ',') WITHIN GROUP (ORDER BY wb) from uf_zwfwdjjmb_dt1 where mainid = main.id) ysdx, " + + " dyjbr, (select lastname from åhrmresource where id = dyjbr) dyjbr_span," + + " djr, (select lastname from hrmresource where id = djr) djr_span " + + " from uf_zwfwdjjmb main $t{param.whereSql} order by dlsk ") + @CaseConversion(value = false) + List> queryReportData2(@ParamMapper("param") Map param,@ParamMapper("uid") int uid); + +} diff --git a/src/main/java/com/api/bokang/xiao/sh_bigdata/service/ReportService.java b/src/main/java/com/api/bokang/xiao/sh_bigdata/service/ReportService.java new file mode 100644 index 0000000..4b70644 --- /dev/null +++ b/src/main/java/com/api/bokang/xiao/sh_bigdata/service/ReportService.java @@ -0,0 +1,47 @@ +package com.api.bokang.xiao.sh_bigdata.service; + +import aiyh.utils.Util; +import com.api.bokang.xiao.sh_bigdata.mapper.ReportMapper; +import weaver.general.TimeUtil; +import weaver.hrm.User; + +import java.util.List; +import java.util.Map; + +/** + * @ClassName ReviewService + * @Author 肖博亢 + * @Date 2023/2/14 17:01 + * @Description

+ **/ +public class ReportService { + + private final ReportMapper reportMapper = Util.getMapper(ReportMapper.class); + + /** + *

获取创建流程数量top5

+ * @param param 请求参数 + * @param user 用户信息 + * @return 前五条流程数据 + */ + public List> queryReportData(Map param, User user){ + String currentDate = Util.null2String(param.get("currentDate")); + String registrationPeople = Util.null2String(param.get("registrationPeople")); + String registrationPeopleSpan = Util.null2String(param.get("registrationPeopleSpan")); + param.put("whereSql",""); + String whereSql = ""; + if(!"".equals(currentDate)){ + whereSql += " and dlsk = #{param.currentDate} "; + }else { + param.put("today", TimeUtil.getCurrentDateString()); + whereSql += " and dlsk >= #{param.today} "; + } + if(!"".equals(registrationPeople)){ + whereSql += " and djr = #{param.registrationPeople} "; + } + whereSql = whereSql.replaceFirst(" and "," where "); + param.put("whereSql",whereSql); + return reportMapper.queryReportData2(param,user.getUID()); + } + +} diff --git a/src/main/java/com/api/bokang/xiao/zhenn/controller/BankController.java b/src/main/java/com/api/bokang/xiao/zhenn/controller/BankController.java index ba84d67..142abea 100644 --- a/src/main/java/com/api/bokang/xiao/zhenn/controller/BankController.java +++ b/src/main/java/com/api/bokang/xiao/zhenn/controller/BankController.java @@ -17,6 +17,7 @@ import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; +import java.util.List; import java.util.Map; /** @@ -30,7 +31,7 @@ public class BankController { private final Logger log = Util.getLogger(); - private final BankService reportService = new BankService(); + private final BankService bankService = new BankService(); /** *

获取搜索组件信息

@@ -46,11 +47,34 @@ public class BankController { log.info("====== into getBankData success ======="); log.info("param:"+param); User loginUser = HrmUserVarify.getUser(request, response); - Map reportData = reportService.getBankData(loginUser, param); - return ApiResult.success(reportData); + Map> bankData = bankService.getBankData(loginUser, param); + return ApiResult.success(bankData); }catch (Exception e){ log.error("getBankData error ==> "+Util.getErrString(e)); return ApiResult.error(e.getMessage()); } } + + /** + *

获取搜索组件信息

+ * @param request 请求体 + * @param response 响应体 + * @return 请求结果 + */ + @Path("/getCommonSelect") + @POST + @Produces(MediaType.APPLICATION_JSON) + public String getCommonSelect(@Context HttpServletRequest request, @Context HttpServletResponse response, @RequestBody Map param) { + try{ + log.info("====== into getCommonSelect success ======="); + log.info("param:"+param); + User loginUser = HrmUserVarify.getUser(request, response); + List> bankSelectInfo = bankService.getBankSelectInfo(loginUser, param); + return ApiResult.success(bankSelectInfo); + }catch (Exception e){ + log.error("getCommonSelect error ==> "+Util.getErrString(e)); + return ApiResult.error(e.getMessage()); + } + } + } diff --git a/src/main/java/com/api/bokang/xiao/zhenn/mapper/BankMapper.java b/src/main/java/com/api/bokang/xiao/zhenn/mapper/BankMapper.java index c9f1693..ef56c57 100644 --- a/src/main/java/com/api/bokang/xiao/zhenn/mapper/BankMapper.java +++ b/src/main/java/com/api/bokang/xiao/zhenn/mapper/BankMapper.java @@ -1,10 +1,109 @@ package com.api.bokang.xiao.zhenn.mapper; +import aiyh.utils.annotation.recordset.Select; +import aiyh.utils.annotation.recordset.SqlMapper; + +import java.util.List; +import java.util.Map; + /** * @ClassName ContractMapper * @Author 肖博亢 * @Date 2023/5/8 16:16 * @Description

**/ -public class BankMapper { +@SqlMapper +public interface BankMapper { + + /** + *

查询流程付款信息

+ * @param param 查询参数 + * @return 付款信息列表 + */ + @Select("SELECT t.requestid requestId,t.$t{amountField} amount,t.$t{amountField} outAmount," + + " $t{inCompany} inCompany,wb.lastoperatedate outDate," + + " (select top 1 xmlsend from workflowToFinanceUrl where wb.requestid = t.requestId and xmlsend IS NOT NULL order by id desc) xmlsend " + + "FROM $t{tableName} t " + + "INNER JOIN workflow_requestbase wb ON t.requestid = wb.requestid " + + "WHERE wb.currentnodetype = 3 " + + " AND wb.lastoperatedate BETWEEN #{beginDate} AND #{endDate} " + + " AND $t{currencyField} = #{currency}") + List> queryOaOutList(Map param); + + /** + *

查询流程付款信息

+ * @param param 查询参数 + * @return 付款信息列表 + */ + @Select("SELECT t.requestid requestId,t.$t{amountField} amount,t.$t{amountField} outAmount," + + " $t{inCompany} inCompany,wb.lastoperatedate outDate," + + " (select top 1 xmlsend from workflowToFinanceUrl where wb.requestid = t.requestId and xmlsend IS NOT NULL order by id desc) xmlsend " + + "FROM $t{tableName} t " + + "INNER JOIN workflow_requestbase wb ON t.requestid = wb.requestid " + + "WHERE wb.currentnodetype = 3 " + + " AND wb.lastoperatedate BETWEEN #{beginDate} AND #{endDate} " + + " AND $t{currencyField} = #{currency}" + + " AND t.$t{bankAccountField} = #{currentBankAccount}") + List> queryOaOutBank(Map param); + + /** + *

查询流程收款信息

+ * @param param 查询参数 + * @return 收款信息列表 + */ + @Select("SELECT t.requestid,t.$t{amountField} amount,t.$t{amountField} inAmount," + + " $t{inCompany} outCompany,wb.lastoperatedate inDate,wfu.xmlsend,t.$t{payInfoField} payInfo " + + "FROM $t{tableName} t " + + "INNER JOIN workflow_requestbase wb ON t.requestid = wb.requestid " + + "WHERE wb.currentnodetype = 3 " + + " AND wb.lastoperatedate BETWEEN #{beginDate} AND #{endDate} " + + " AND $t{currencyField} = #{currency}" + + " AND t.$t{bankAccountField} = #{currentBank}") + List> queryOaInBank(Map param); + + /** + *

查询银行付款信息

+ * @param param 查询参数 + * @return 付款信息列表 + */ + @Select("select id,txnamt amount,txnamt difAmount,txnamt outAmount,insid," + + " insid outFlowNo,txndate_time,actacn,tobank inCompany from uf_bank_trade_info " + + "where txndate_time BETWEEN #{beginDate} AND #{endDate} " + + " and trncur = #{currencySpan}" + + " and actacn = #{currentBankAccount}") + List> queryBankOutInfo(Map param); + + /** + *

查询银行收款信息

+ * @param param 查询参数 + * @return 收款信息列表 + */ + @Select("select id,id payInfo,txnamt amount,txnamt difAmount,txnamt inAmount,insid," + + " insid inFlowNo,txndate_time,actacn,ibkname outCompany from uf_bank_trade_info " + + "where txndate_time BETWEEN #{beginDate} AND #{endDate} " + + " and trncur = #{currencySpan}" + + " and actacn_receipt = #{currentBankAccount}") + List> queryBankInInfo(Map param); + + /** + *

银行存款日记账余额

+ * @param param 查询参数 + * @return 余额 + */ + @Select("select sum(avabal) from uf_bank_day_balance " + + "where actacn = #{currentBankAccount} and curcde = #{currencySpan} and baldat BETWEEN #{beginDate} AND #{endDate} ") + double queryBankDayAmount(Map param); + + /** + *

银行对账单余额

+ * @param param 查询参数 + * @return 余额 + */ + @Select("select sum(EvBalance) from uf_period_balance " + + "where glAccount = #{bankSubject} " + + " and EvCurrency = #{currencySpan} " + + " and IvFiscYear = YEAR(#{beginDate}) " + + " and IvFisPeriod = MONTH(#{beginDate})") + double queryBankStatementBalance(Map param); + } diff --git a/src/main/java/com/api/bokang/xiao/zhenn/service/BankService.java b/src/main/java/com/api/bokang/xiao/zhenn/service/BankService.java index 33ff78c..4af3a11 100644 --- a/src/main/java/com/api/bokang/xiao/zhenn/service/BankService.java +++ b/src/main/java/com/api/bokang/xiao/zhenn/service/BankService.java @@ -1,8 +1,18 @@ package com.api.bokang.xiao.zhenn.service; +import aiyh.utils.Util; +import com.alibaba.fastjson.JSON; +import com.api.bokang.xiao.zhenn.mapper.BankMapper; +import org.apache.log4j.Logger; +import weaver.bokang.xiao.common.CommonUtil; +import weaver.bokang.xiao.common.mapper.WorkflowMapper; import weaver.hrm.User; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; import java.util.Map; +import java.util.stream.Collectors; /** * @ClassName ContractService @@ -12,13 +22,147 @@ import java.util.Map; **/ public class BankService { + private final BankMapper bankMapper = Util.getMapper(BankMapper.class); + + private final WorkflowMapper workflowMapper = Util.getMapper(WorkflowMapper.class); + + private final Logger log = Util.getLogger(); + /** *

获取银行数据信息

+ * + *

+ * param{ + * currentBank:"当前银行下拉框索引", + * currentBankAccount:"当前银行下拉框账号", + * currentBankSpan:"当前银行名称", + * outParam:[{ + * table:"流程表名", + * workflowId:"流程id", + * amountField:"金额字段名", + * bankAccountField:"银行账号字段", + * queryTye:"1、付款账号固定;2、付款账号不固定" + * }]:"付款参数条件", + * inParam:[{ + * table:"流程表名", + * workflowId:"流程id", + * amountField:"金额字段名", + * bankAccountField:"银行账号字段", + * }]:"收款参数条件" + * } + *

getBankData(User loginUser, Map param) { - return null; + public Map> getBankData(User loginUser, Map param) { + Map> bankData = new HashMap<>(); + Map bankBaseInfo = new HashMap<>(); + String currentBankSpan = Util.null2String(param.get("currentBankSpan")); + String bankAccount = Util.null2String(param.get("currentBankAccount")); + List> outParam = (List>) param.get("outParam"); + List> inParam = (List>) param.get("inParam"); + //查询数据 + List> oaOutList = outParam.stream() + .flatMap(item -> { + String queryTye = Util.null2String(item.get("queryTye")); + item.put("currentBankAccount",bankAccount); + item.put("beginDate",Util.null2String(param.get("beginDate"))); + item.put("endDate",Util.null2String(param.get("endDate"))); + item.put("currency",Util.null2String(param.get("currency"))); + item.put("currencySpan",Util.null2String(param.get("endDate"))); + item.put("bankSubject",Util.null2String(param.get("bankSubject"))); + item.put("currentBank",Util.null2String(param.get("currentBank"))); + List> tempOutList = "1".equals(queryTye) ? bankMapper.queryOaOutList(item) : bankMapper.queryOaOutBank(item); + for (Map tempOut : tempOutList) { + String xmlSend = Util.null2String(tempOut.get("xmlsend")); + String insId = CommonUtil.getNodeValue(xmlSend, "insid"); + tempOut.put("insId",insId); + } + return tempOutList.stream(); + }) + .collect(Collectors.toList()); + List> oaInList = inParam.stream() + .flatMap(item -> { + item.put("currentBankAccount",bankAccount); + item.put("beginDate",Util.null2String(param.get("beginDate"))); + item.put("endDate",Util.null2String(param.get("endDate"))); + item.put("currency",Util.null2String(param.get("currency"))); + item.put("currencySpan",Util.null2String(param.get("endDate"))); + item.put("bankSubject",Util.null2String(param.get("bankSubject"))); + item.put("currentBank",Util.null2String(param.get("currentBank"))); + return bankMapper.queryOaInBank(item).stream(); + }) + .collect(Collectors.toList()); + List> bankOutList = bankMapper.queryBankOutInfo(param); + List> bankInList = bankMapper.queryBankInInfo(param); + //计算有差异的集合 + List> oaOutTable = CommonUtil.difference(oaOutList, bankOutList, map -> map.get("insid")); + List> bankOutTable = CommonUtil.difference(bankOutList,oaOutList, map -> map.get("insid")); + List> bankInTable = CommonUtil.difference(bankInList,oaInList, map -> map.get("payInfo")); + List> oaInTable = new ArrayList<>(); + //银行信息 + bankBaseInfo.put("bankName",currentBankSpan); + bankBaseInfo.put("bankAccount",bankAccount); + //求总和 + Map amountMap = new HashMap<>(); + double bankDayAmount = this.queryBankDayAmount(param); + double bankStatementBalance = this.queryBankStatementBalance(param); + double bankInDifference = bankInTable.stream().mapToDouble(item -> Double.parseDouble(item.get("amount").toString())).sum(); + double oaInDifference = 0; + double bankOutDifference = bankOutTable.stream().mapToDouble(item -> Double.parseDouble(item.get("amount").toString())).sum(); + double oaOutDifference = oaOutTable.stream().mapToDouble(item -> Double.parseDouble(item.get("amount").toString())).sum(); + double bankDayAmountUpdate = bankDayAmount + bankInDifference - bankOutDifference; + double bankStatementBalanceUpdate = bankStatementBalance + oaInDifference - oaOutDifference; + //返回数据组装 + amountMap.put("bankInDifference",bankInDifference); + amountMap.put("oaInDifference",oaInDifference); + amountMap.put("bankOutDifference",bankOutDifference); + amountMap.put("oaOutDifference",oaOutDifference); + amountMap.put("bankDayAmount",bankDayAmount); + amountMap.put("bankStatementBalance",bankStatementBalance); + amountMap.put("bankDayAmountUpdate",bankDayAmountUpdate); + amountMap.put("bankStatementBalanceUpdate",bankStatementBalanceUpdate); + Map bankTableListData = new HashMap<>(); + bankTableListData.put("oaOutTable",oaOutTable); + bankTableListData.put("bankOutTable",bankOutTable); + bankTableListData.put("bankInTable",bankInTable); + bankTableListData.put("oaInTable",oaInTable); + bankData.put("bankBaseData",bankBaseInfo); + bankData.put("bankAmountData",amountMap); + bankData.put("bankTableListData",bankTableListData); + log.info("getBankData bankData 对账单报表信息==>"+ JSON.toJSONString(bankData)); + return bankData; } + + /** + *

获取银行下拉框信息

+ * @param loginUser 登录用户 + * @param param 参数信息 + * @return 下拉框信息 + */ + public List> getBankSelectInfo(User loginUser, Map param){ + String fieldName = Util.null2String(param.get("fieldName")); + return workflowMapper.queryCommonSelect(fieldName); + } + + /** + *

银行存款日记账余额

+ * @param param 查询参数 + * @return 余额< + */ + private double queryBankDayAmount(Map param){ + return bankMapper.queryBankDayAmount(param); + } + + /** + *

银行对账单余额

+ * @param param 查询参数 + * @return 余额< + */ + private double queryBankStatementBalance(Map param){ + return bankMapper.queryBankStatementBalance(param); + } + } diff --git a/src/main/java/com/api/nonstandardext/zenner/job/SyncAccountTradeInfoJob.java b/src/main/java/com/api/nonstandardext/zenner/job/SyncAccountTradeInfoJob.java index 3d7106d..01f4496 100644 --- a/src/main/java/com/api/nonstandardext/zenner/job/SyncAccountTradeInfoJob.java +++ b/src/main/java/com/api/nonstandardext/zenner/job/SyncAccountTradeInfoJob.java @@ -100,10 +100,11 @@ public class SyncAccountTradeInfoJob extends BaseCronJob { xmlParams.put("type", "2002"); xmlParams.put("ibknum", ibknum); xmlParams.put("actacn", actacn); - xmlParams.put("from", "20220919"); + //xmlParams.put("from", "20220919"); Calendar cal = Calendar.getInstance(); cal.set(Calendar.DAY_OF_MONTH, -1); - xmlParams.put("to", ZennerUtil.parseToDateString(cal.getTime(), ZennerUtil.formatYYYYMMDD_NoSplit)); + xmlParams.put("from", ZennerUtil.parseToDateString(cal.getTime(), ZennerUtil.formatYYYYMMDD_NoSplit)); + xmlParams.put("to", ZennerUtil.parseToDateString(new Date(), ZennerUtil.formatYYYYMMDD_NoSplit)); xmlParams.put("amountFrom", "1"); xmlParams.put("amountTo", "100000"); xmlParams.put("begnum", start + ""); diff --git a/src/main/java/weaver/bokang/xiao/common/CommonUtil.java b/src/main/java/weaver/bokang/xiao/common/CommonUtil.java index c9cd911..1fa38bd 100644 --- a/src/main/java/weaver/bokang/xiao/common/CommonUtil.java +++ b/src/main/java/weaver/bokang/xiao/common/CommonUtil.java @@ -1,7 +1,14 @@ package weaver.bokang.xiao.common; -import java.util.Map; -import java.util.Set; +import org.jdom.Document; +import org.jdom.Element; +import org.jdom.input.SAXBuilder; + +import java.io.StringReader; +import java.lang.reflect.Field; +import java.util.*; +import java.util.function.BiPredicate; +import java.util.function.Function; /** * @ClassName CommonUtil @@ -68,4 +75,159 @@ public class CommonUtil { } return fixStr.substring(0, fixStr.length() - 1) + " "; } + + /** + * 获取 XML 字符串中指定节点的值 + * @param xml XML 字符串 + * @param nodeName 要获取值的节点名称 + * @return 节点的值,如果节点不存在则返回空字符串 + */ + public static String getNodeValue(String xml, String nodeName) { + try { + // 创建 SAXBuilder 对象 + SAXBuilder builder = new SAXBuilder(); + // 创建 StringReader 对象,并将 XML 字符串作为参数传入 + StringReader reader = new StringReader(xml); + // 使用 SAXBuilder 对象解析 XML,得到 Document 对象 + Document doc = builder.build(reader); + // 获取根节点 + Element root = doc.getRootElement(); + // 调用递归方法获取节点值 + String nodeValue = getNodeValue(root, nodeName); + // 如果节点值为空,则返回空字符串 + return nodeValue == null ? "" : nodeValue; + } catch (Exception e) { + // 如果解析 XML 异常,则返回空字符串 + return ""; + } + } + + /** + * 递归获取节点值 + * @param element 当前节点 + * @param nodeName 要获取值的节点名称 + * @return 节点的值,如果节点不存在则返回 null + */ + private static String getNodeValue(Element element, String nodeName) { + // 获取当前节点的子节点 + Element node = element.getChild(nodeName); + // 如果子节点中存在指定的节点,则返回节点的值 + if (node != null) { + return node.getValue(); + } else { + // 否则遍历子节点,递归调用 getNodeValue 方法,直到找到指定节点为止 + List children = element.getChildren(); + if (Objects.nonNull(children) && children.size() > 0) { + for (Element child : children) { + String value = getNodeValue(child, nodeName); + if (value != null) { + return value; + } + } + } + // 如果遍历完所有子节点都没有找到指定节点,则返回 null + return null; + } + } + + /** + * 求两个List的交集 + * + * @param list1 第一个List + * @param list2 第二个List + * @param fieldName 比较元素的属性名 + * @param 元素类型 + * @return 交集 + * @throws NoSuchFieldException 如果指定的属性不存在 + * @throws IllegalAccessException 如果访问指定的属性被拒绝 + */ + public static List intersection(List list1, List list2, String fieldName) throws NoSuchFieldException, IllegalAccessException { + return CommonUtil.intersection(list1, list2, (t1, t2) -> { + try { + Object fieldValue1 = getFieldValue(t1, fieldName); + Object fieldValue2 = getFieldValue(t2, fieldName); + return fieldValue1 != null && fieldValue1.equals(fieldValue2); + } catch (NoSuchFieldException | IllegalAccessException e) { + return false; + } + }); + } + + /** + * 求两个List的交集 + * + * @param list1 第一个List + * @param list2 第二个List + * @param matcher 元素比较器,返回true表示两个元素相等,false表示不相等 + * @param 元素类型 + * @return 交集 + */ + public static List intersection(List list1, List list2, BiPredicate matcher) { + Set set = new HashSet<>(list1); + List result = new ArrayList<>(); + for (T t2 : list2) { + if (set.contains(t2) && matcher.test(set.iterator().next(), t2)) { + result.add(t2); + } + } + return result; + } + + /** + * 求两个List的差集,即在第一个List中出现但没有在第二个List中出现的元素 + * + * @param list1 第一个List + * @param list2 第二个List + * @param matcher 元素比较器,返回true表示两个元素相等,false表示不相等 + * @param 元素类型 + * @return 差集 + */ + public static List difference(List list1, List list2, BiPredicate matcher) { + Set set2 = new HashSet<>(list2); + List result = new ArrayList<>(); + for (T t1 : list1) { + if (!set2.contains(t1) || !matcher.test(t1, set2.iterator().next())) { + result.add(t1); + } + } + return result; + } + + /** + * 求两个List的差集,即在第一个List中出现但没有在第二个List中出现的元素 + * + * @param list1 第一个List + * @param list2 第二个List + * @param keyFunc 提取元素的Key的函数 + * @param 元素类型 + * @param Key类型 + * @return 差集 + */ + public static List difference(List list1, List list2, Function keyFunc) { + BiPredicate matcher = (t1, t2) -> Objects.equals(keyFunc.apply(t1), keyFunc.apply(t2)); + return difference(list1, list2, matcher); + } + + private static Object getFieldValue(Object obj, String fieldName) throws NoSuchFieldException, IllegalAccessException { + if (obj instanceof Map) { + // 如果对象是Map类型,则直接返回指定键的值 + Map map = (Map) obj; + return map.get(fieldName); + } else { + // 如果对象是JavaBean类型,则通过反射获取指定属性的值 + Class clazz = obj.getClass(); + while (clazz != null) { + try { + Field field = clazz.getDeclaredField(fieldName); + field.setAccessible(true); + return field.get(obj); + } catch (NoSuchFieldException e) { + // 如果当前类没有指定的属性,则向上查找父类 + clazz = clazz.getSuperclass(); + } + } + // 如果所有父类都没有指定的属性,则抛出异常 + throw new NoSuchFieldException(fieldName); + } + } } diff --git a/src/main/java/weaver/bokang/xiao/common/mapper/WorkflowMapper.java b/src/main/java/weaver/bokang/xiao/common/mapper/WorkflowMapper.java index 257cf66..8a16306 100644 --- a/src/main/java/weaver/bokang/xiao/common/mapper/WorkflowMapper.java +++ b/src/main/java/weaver/bokang/xiao/common/mapper/WorkflowMapper.java @@ -2,6 +2,7 @@ package weaver.bokang.xiao.common.mapper; import aiyh.utils.annotation.recordset.*; +import java.util.List; import java.util.Map; import java.util.Set; @@ -37,6 +38,12 @@ public interface WorkflowMapper { @ParamMapper("fieldValue") String fieldValue, @ParamMapper("requestId") String requestId); + @Select("select detail.id as `key`,detail.name as showname " + + "from mode_selectitempage page " + + "inner join mode_selectitempagedetail detail on page.id = detail.mainid " + + "where page.selectitemname = #{fieldName}") + List> queryCommonSelect(@ParamMapper("fieldName")String fieldName); + /** *

执行自定义更新sql

* @param cusSql 自定义sql diff --git a/src/main/java/weaver/bokang/xiao/common/model_update/process/ConditionWhereProcess.java b/src/main/java/weaver/bokang/xiao/common/model_update/process/ConditionWhereProcess.java new file mode 100644 index 0000000..b383404 --- /dev/null +++ b/src/main/java/weaver/bokang/xiao/common/model_update/process/ConditionWhereProcess.java @@ -0,0 +1,130 @@ +package weaver.bokang.xiao.common.model_update.process; + +import aiyh.utils.Util; +import aiyh.utils.annotation.MethodRuleNo; +import org.apache.log4j.Logger; +import weaver.bokang.xiao.common.model_update.function.ConditionFunction; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.HashMap; +import java.util.Map; + +/** + * @ClassName ConditionWhereProcess + * @Author 肖博亢 + * @Date 2023/5/15 14:40 + * @Description

+ **/ +public class ConditionWhereProcess { + + public static final Map,Map,String>> MODE_METHOD_MAP = new HashMap<>(); + + public static final Logger logger = Util.getLogger(); + + static { + try { + Class valueRuleMethodClass = ConditionTargetProcess.class; + Method[] methods = valueRuleMethodClass.getDeclaredMethods(); + for (Method method : methods) { + if (method.isAnnotationPresent(MethodRuleNo.class)) { + MethodRuleNo annotation = method.getAnnotation(MethodRuleNo.class); + int value = annotation.value(); + MODE_METHOD_MAP.put(value, (whereParam,param,whereSql) -> { + try { + return (String) method.invoke(null,whereParam,param,whereSql); + } catch (IllegalAccessException | InvocationTargetException e) { + throw new RuntimeException(e); + } + }); + } + } + }catch (Exception exception){ + logger.error("ConditionTargetProcess init error !!! "+Util.getErrString(exception)); + } + } + + /** + *

目标建模等于处理方法

+ * @param whereParam 条件参数 + * @param param 参数信息 + * @param whereSql 条件sql + * @return 条件sql + */ + @MethodRuleNo(value = 0, desc = "等于") + public static String equals(Map whereParam,Map param,String whereSql) { + String conditionValue = Util.null2String(param.get("conditionValue")); + String targetFieldName = Util.null2String(param.get("targetFieldName")); + String targetStr = " and "+targetFieldName+" = #{whereParam."+targetFieldName+"}"; + whereSql += targetStr; + whereParam.put(targetFieldName,conditionValue); + return whereSql; + } + + /** + *

目标建模不等于处理方法

+ * @param whereParam 条件参数 + * @param param 参数信息 + * @param whereSql 条件sql + * @return 条件sql + */ + @MethodRuleNo(value = 1, desc = "不等于") + public static String noEquals(Map whereParam,Map param,String whereSql) { + String conditionValue = Util.null2String(param.get("conditionValue")); + String targetFieldName = Util.null2String(param.get("targetFieldName")); + String targetStr = " and "+targetFieldName+" <> #{whereParam."+targetFieldName+"}"; + whereSql += targetStr; + whereParam.put(targetFieldName,conditionValue); + return whereSql; + } + + /** + *

目标建模不等于处理方法

+ * @param whereParam 条件参数 + * @param param 参数信息 + * @param whereSql 条件sql + * @return 条件sql + */ + @MethodRuleNo(value = 6, desc = "in") + public static String in(Map whereParam,Map param,String whereSql) { + String conditionValue = Util.null2String(param.get("conditionValue")); + String targetFieldName = Util.null2String(param.get("targetFieldName")); + String targetStr = " and "+targetFieldName+" in ( $t{whereParam."+targetFieldName+"})"; + whereSql += targetStr; + whereParam.put(targetFieldName,conditionValue); + return whereSql; + } + + /** + *

目标建模不等于处理方法

+ * @param whereParam 条件参数 + * @param param 参数信息 + * @param whereSql 条件sql + * @return 条件sql + */ + @MethodRuleNo(value = 7, desc = "not in") + public static String notIn(Map whereParam,Map param,String whereSql) { + String conditionValue = Util.null2String(param.get("conditionValue")); + String targetFieldName = Util.null2String(param.get("targetFieldName")); + String targetStr = " and "+targetFieldName+" not in ( $t{whereParam."+targetFieldName+"})"; + whereSql += targetStr; + whereParam.put(targetFieldName,conditionValue); + return whereSql; + } + + /** + *

目标建模不等于处理方法

+ * @param whereParam 条件参数 + * @param param 参数信息 + * @param whereSql 条件sql + * @return 条件sql + */ + @MethodRuleNo(value = 8, desc = "自定义sql") + public static String cusSql(Map whereParam,Map param,String whereSql) { + String conditionValue = Util.null2String(param.get("conditionValue")); + String targetStr = " and "+Util.sbc2dbcCase(conditionValue); + whereSql += targetStr; + return whereSql; + } + +} diff --git a/src/main/java/weaver/bokang/xiao/porsche/action/DateFieldUpdateAction.java b/src/main/java/weaver/bokang/xiao/porsche/action/DateFieldUpdateAction.java index 87e649b..0106e72 100644 --- a/src/main/java/weaver/bokang/xiao/porsche/action/DateFieldUpdateAction.java +++ b/src/main/java/weaver/bokang/xiao/porsche/action/DateFieldUpdateAction.java @@ -7,6 +7,7 @@ import aiyh.utils.annotation.ActionOptionalParam; import aiyh.utils.annotation.PrintParamMark; import aiyh.utils.annotation.RequiredMark; import aiyh.utils.excention.CustomerException; +import com.alibaba.fastjson.JSON; import lombok.Setter; import weaver.bokang.xiao.common.CommonUtil; import weaver.bokang.xiao.common.mapper.WorkflowMapper; @@ -50,12 +51,14 @@ public class DateFieldUpdateAction extends SafeCusBaseAction { if(sourceDateFieldArray.length != targetDateFieldArray.length){ throw new CustomerException("请确保需要格式化的字段数量与存储字段数量一致"); } + log.info("workflowData ==>"+ JSON.toJSONString(workflowData)); Map dateFormat = new HashMap<>(); for (int i = 0; i < sourceDateFieldArray.length; i++) { String sourceDateField = sourceDateFieldArray[i]; String targetDateField = targetDateFieldArray[i]; String sourceDate = Util.null2String(workflowData.get(sourceDateField)); String targetDate = formatDate(sourceDate); + log.info(String.format("sourceDateField:[%s],targetDateField:[%s],sourceDate:[%s],targetDate:[%s]",sourceDateField,targetDateField,sourceDate,targetDate)); dateFormat.put(targetDateField,targetDate); } Map whereParam = new HashMap<>(); diff --git a/src/main/java/weaver/bokang/xiao/porsche/mapper/PorscheMapper.java b/src/main/java/weaver/bokang/xiao/porsche/mapper/PorscheMapper.java index ba0dd81..383bb37 100644 --- a/src/main/java/weaver/bokang/xiao/porsche/mapper/PorscheMapper.java +++ b/src/main/java/weaver/bokang/xiao/porsche/mapper/PorscheMapper.java @@ -18,7 +18,7 @@ public interface PorscheMapper { List> queryCompanyInfo(@ParamMapper("statusField")String statusField); @Update("update uf_zcgsxx set sfrz = #{authenticationStatus},fadadaid = #{contractId} where id = #{dataId}") - boolean updateAuthenticationStatus(@ParamMapper("authenticationField")String authenticationStatus, - @ParamMapper("authenticationStatus")String companyNo, + boolean updateAuthenticationStatus(@ParamMapper("authenticationStatus")String authenticationStatus, + @ParamMapper("contractId")String contractId, @ParamMapper("dataId")int dataId); } diff --git a/src/main/java/weaver/bokang/xiao/porsche/schedule/CompanyWriteBackSchedule.java b/src/main/java/weaver/bokang/xiao/porsche/schedule/CompanyWriteBackSchedule.java index c992fae..0354dd1 100644 --- a/src/main/java/weaver/bokang/xiao/porsche/schedule/CompanyWriteBackSchedule.java +++ b/src/main/java/weaver/bokang/xiao/porsche/schedule/CompanyWriteBackSchedule.java @@ -59,7 +59,7 @@ public class CompanyWriteBackSchedule extends CusBaseCronJob { Map certificationStatusResource = (Map) companyInfo.get("certificationStatusResource"); int dataId = Util.getIntValue(String.valueOf(map.get("id"))); String authenticationStatus = Util.null2String(certificationStatusResource.get("verifiedStatus")); - String companyNo = Util.null2String(companyInfo.get("companyInfo")); + String companyNo = Util.null2String(companyInfo.get("companyNo")); porscheMapper.updateAuthenticationStatus(authenticationStatus,companyNo,dataId); } } diff --git a/src/main/java/weaver/bokang/xiao/sh_bigdata/action/DataPushAction.java b/src/main/java/weaver/bokang/xiao/sh_bigdata/action/DataPushAction.java index 4345c18..6af0026 100644 --- a/src/main/java/weaver/bokang/xiao/sh_bigdata/action/DataPushAction.java +++ b/src/main/java/weaver/bokang/xiao/sh_bigdata/action/DataPushAction.java @@ -5,6 +5,7 @@ import aiyh.utils.action.SafeCusBaseAction; import aiyh.utils.annotation.ActionDesc; import aiyh.utils.annotation.ActionOptionalParam; import aiyh.utils.annotation.PrintParamMark; +import aiyh.utils.annotation.RequiredMark; import com.alibaba.fastjson.JSON; import lombok.Setter; import weaver.bokang.xiao.common.mapper.WorkflowMapper; @@ -31,7 +32,7 @@ public class DataPushAction extends SafeCusBaseAction { /** 数据推送接口唯一标识 */ @PrintParamMark - @ActionOptionalParam(value = "",desc = "数据推送接口唯一标识") + @RequiredMark(value = "",desc = "数据推送接口唯一标识") private String requestUnique; private final WorkflowMapper workflowMapper = Util.getMapper(WorkflowMapper.class); diff --git a/src/main/java/weaver/bokang/xiao/xhny_report/schedule/GenerateReportSchedule.java b/src/main/java/weaver/bokang/xiao/xhny_report/schedule/GenerateReportSchedule.java index ecec69c..8b2ede5 100644 --- a/src/main/java/weaver/bokang/xiao/xhny_report/schedule/GenerateReportSchedule.java +++ b/src/main/java/weaver/bokang/xiao/xhny_report/schedule/GenerateReportSchedule.java @@ -26,8 +26,7 @@ import java.util.stream.Collectors; * @Date 2023/3/17 19:58 * @Description

生成报表定时任务

**/ -@Data -@ActionDesc(value = "生成报表信息", author = "bokang.xiao") + public class GenerateReportSchedule extends CusBaseCronJob { diff --git a/src/main/java/weaver/bokang/xiao/zscq/action/OneNetComAction.java b/src/main/java/weaver/bokang/xiao/zscq/action/OneNetComAction.java index 4c1a331..2d6003c 100644 --- a/src/main/java/weaver/bokang/xiao/zscq/action/OneNetComAction.java +++ b/src/main/java/weaver/bokang/xiao/zscq/action/OneNetComAction.java @@ -71,6 +71,9 @@ public class OneNetComAction extends SafeCusBaseAction { @ActionOptionalParam(value = "",desc = "网关调用办理接口的apiId") private String handleApiName; + @ActionOptionalParam(value = "已办结办件不允许修改",desc = "错误信息不阻止流程") + private String continueError = "已办结办件不允许修改"; + private final WorkflowMapper workflowMapper = Util.getMapper(WorkflowMapper.class); private final DealWithMapping dealWithMapping = new DealWithMapping(); @@ -82,8 +85,10 @@ public class OneNetComAction extends SafeCusBaseAction { @Override public void doSubmit(String requestId, String billTable, int workflowId, User user, RequestInfo requestInfo) { log.info(String.format("=================== {%s} {requestId : %s} begin ======================", this.getClass().getName(),requestId)); - Map workflowMessage = workflowMapper.queryWorkflowByRequestId(requestId, billTable); + //Map workflowMessage = workflowMapper.queryWorkflowByRequestId(requestId, billTable); + Map workflowMessage = this.getObjMainTableValue(requestInfo); dealWithMapping.setMainTable(billTable); + log.info("workflowMessage ==>"+JSON.toJSONString(workflowMessage)); try{ if(StringUtils.isNotBlank(acceptUnique) && StringUtils.isNotBlank(acceptApiName)) { requestHandle(workflowMessage,acceptUnique,acceptApiName,requestId,billTable,"受理请求"); @@ -128,6 +133,10 @@ public class OneNetComAction extends SafeCusBaseAction { whereParam.put("requestid",requestId); sqlUtil.updateMode(billTable, updateMsg, whereParam); }else { + if(continueError.equals(message)){ + log.info("The error message for this request is related to whitelist content and will not block the submission of the action message:"+message ); + return; + } throw new CustomerException(desc+"请求失败 ==>"+message); } }else { diff --git a/src/test/java/bokang/xiao/NormalTest.java b/src/test/java/bokang/xiao/NormalTest.java index a6744bd..86ca4e0 100644 --- a/src/test/java/bokang/xiao/NormalTest.java +++ b/src/test/java/bokang/xiao/NormalTest.java @@ -8,8 +8,10 @@ import basetest.BaseTest; import bokang.xiao.entity.CourseEntity; import bokang.xiao.entity.StudentEntity; import bokang.xiao.entity.TeacherEntity; +import bokang.xiao.util.XmlParser; import cn.afterturn.easypoi.excel.ExcelExportUtil; import cn.afterturn.easypoi.excel.entity.ExportParams; +import com.alibaba.fastjson.JSON; import com.api.bokang.xiao.porsche_review.mapper.ReviewMapper; import com.api.bokang.xiao.wx_report.mapper.ReportMapper; @@ -20,10 +22,13 @@ import com.api.bokang.xiao.zscq.service.impl.ReserveServiceImpl; import org.apache.log4j.Logger; import org.apache.poi.ss.usermodel.Workbook; import org.junit.Test; +import weaver.bokang.xiao.common.CommonUtil; import weaver.bokang.xiao.common.mapper.ModeMapper; +import weaver.bokang.xiao.common.mapper.WorkflowMapper; import weaver.bokang.xiao.deg_repeat_check.action.RepeatCheckAction; import weaver.bokang.xiao.porsche.action.DateFieldUpdateAction; import weaver.bokang.xiao.porsche.schedule.CompanyWriteBackSchedule; +import weaver.bokang.xiao.porsche.schedule.SalaryUpdateSchedule; import weaver.bokang.xiao.sh_bigdata.action.DataPushAction; import weaver.bokang.xiao.xhny_mode.search.CustomSearchDepart; import weaver.bokang.xiao.xhny_report.entity.SourceTrackingData; @@ -33,6 +38,7 @@ import weaver.bokang.xiao.xhny_report.service.ScoreChainPattern; import weaver.bokang.xiao.zscq.action.OneNetComAction; import weaver.bokang.xiao.zscq.action.StatusChangeAction; import weaver.bokang.xiao.zscq.config.service.ModeChangeService; +import weaver.bokang.xiao.zscq.store.TableNameStore; import weaver.bokang.xiao.zxyh.RepeatSubmitAction; import weaver.conn.RecordSet; import weaver.general.StaticObj; @@ -61,16 +67,16 @@ public class NormalTest extends BaseTest { @Test public void testWord(){ - //GenerateFileUtil.createCronJobDocument(CompanyWriteBackSchedule.class); - GenerateFileUtil.createActionDocument(DataPushAction.class); + GenerateFileUtil.createCronJobDocument(SalaryUpdateSchedule.class); + //GenerateFileUtil.createActionDocument(DataPushAction.class); //GenerateFileUtil.createActionDocument(DateFieldUpdateAction.class); } @Test public void testChain(){ GenerateReportSchedule generateReportSchedule = new GenerateReportSchedule(); - generateReportSchedule.setReportModelId("-2915"); - generateReportSchedule.setDataSource("NCC"); + //generateReportSchedule.setReportModelId("-2915"); + //generateReportSchedule.setDataSource("NCC"); generateReportSchedule.runCode(); } @@ -347,9 +353,9 @@ public class NormalTest extends BaseTest { @Test public void testSub(){ - String sourceStr = ",0,1,2,"; - String value = ",0,"; - System.out.println(sourceStr.contains(value)); + WorkflowMapper workflowMapper = Util.getMapper(WorkflowMapper.class); + List> maps = workflowMapper.queryCommonSelect("付款银行"); + System.out.println(maps); } @Test @@ -360,4 +366,39 @@ public class NormalTest extends BaseTest { System.out.println("Formatted date: " + formattedDate); } + @Test + public void testXml() throws Exception { + //Map stringObjectMap = XmlParser.parseXml("\n" + + // "E192168000104220630083401387679060******b2e000922063008340100017220.02CNY0202206304559592253523132900300973101040160001226585上海昱锐科技有限公司杭州银行股份有限公司上海青浦支行"); + //System.out.println(JSON.toJSONString(stringObjectMap)); + String insid = XmlParser.getNodeValue("" + + "E192168000104220630083401387679060******b2e000922063008340100017220.02CNY0202206304559592253523132900300973101040160001226585上海昱锐科技有限公司杭州银行股份有限公司上海青浦支行","insid"); + System.out.println(insid); + } + + @Test + public void testDiffrentce() throws Exception { + Map map1 = new HashMap<>(); + map1.put("id", 1); + map1.put("name", "A"); + Map map2 = new HashMap<>(); + map2.put("id", 1); + map2.put("name", "B"); + Map map3 = new HashMap<>(); + map3.put("id", 2); + map3.put("name", "B"); + List> list1 = Arrays.asList(map1, map2); + List> list2 = Arrays.asList(map2, map3); + List> difference = CommonUtil.difference(list1, list2, map -> map.get("id")); + List> difference1 = CommonUtil.difference(list2, list1, map -> map.get("id")); + System.out.println(difference); // 输出 [{id=1, name=A}] + System.out.println(difference1); // 输出 [{id=1, name=A}] + + } + + @Test + public void testQuery1(){ + TableNameStore.getInstance().refresh(); + } + } diff --git a/src/test/java/bokang/xiao/util/XmlParser.java b/src/test/java/bokang/xiao/util/XmlParser.java new file mode 100644 index 0000000..357e3cf --- /dev/null +++ b/src/test/java/bokang/xiao/util/XmlParser.java @@ -0,0 +1,94 @@ +package bokang.xiao.util; + +import java.io.StringReader; +import java.util.*; + +import org.jdom.Document; +import org.jdom.Element; +import org.jdom.input.SAXBuilder; + +public class XmlParser { + + /** + * 将传入的 XML 字符串解析成 Map 对象 + * + * @param xml 要解析的 XML 字符串 + * @return 解析后的 Map 对象 + * @throws Exception 解析过程中出现的异常 + */ + public static Map parseXml(String xml) throws Exception { + Map map = new HashMap(); + // 创建 SAXBuilder 对象 + SAXBuilder builder = new SAXBuilder(); + // 解析 XML 字符串成 Document 对象 + Document document = builder.build(new StringReader(xml)); + // 获取根元素 + Element root = document.getRootElement(); + // 解析根元素 + parseElement(root, map); + return map; + } + + /** + * 解析指定的 Element 对象,并将解析结果存入指定的 Map 对象中 + * + * @param element 要解析的 Element 对象 + * @param map 存储解析结果的 Map 对象 + */ + private static void parseElement(Element element, Map map) { + // 获取子元素列表 + List childElements = element.getChildren(); + if (childElements.isEmpty()) { + // 如果没有子元素,则将当前元素的名称和值存入 Map 对象中 + map.put(element.getName(), element.getValue()); + } else { + Map childMap = new HashMap(); + for (Element childElement : childElements) { + // 如果有多个同名元素,则将这些元素解析成一个 List 对象,并将该 List 对象存入当前节点的 Map 对象中 + //if (childElement.getName().equals(childElements.get(0).getName())) { + // List> childList = new ArrayList>(); + // parseElement(childElement, childMap); + // childList.add(childMap); + // map.put(childElement.getName(), childList); + //} else { + // parseElement(childElement, childMap); + // map.put(childElement.getName(), childMap); + //} + parseElement(childElement, childMap); + map.put(childElement.getName(), childMap); + } + } + } + + public static String getNodeValue(String xml, String nodeName) throws Exception { + try { + SAXBuilder builder = new SAXBuilder(); + StringReader reader = new StringReader(xml); + Document doc = builder.build(reader); + Element root = doc.getRootElement(); + String nodeValue = getNodeValue(root, nodeName); + return nodeValue == null ? "" : nodeValue; + }catch (Exception e){ + return ""; + } + } + + private static String getNodeValue(Element element, String nodeName) { + Element node = element.getChild(nodeName); + if (node != null) { + return node.getValue(); + } else { + List children = element.getChildren(); + if(Objects.nonNull(children) && children.size() > 0){ + for (Element child : children) { + String value = getNodeValue(child, nodeName); + if (value != null) { + return value; + } + } + } + return null; + } + } + +} \ No newline at end of file