XmlUtil.java 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647
  1. package com.genersoft.iot.vmp.gb28181.utils;
  2. import com.alibaba.fastjson2.JSONArray;
  3. import com.alibaba.fastjson2.JSONObject;
  4. import com.genersoft.iot.vmp.common.CivilCodePo;
  5. import com.genersoft.iot.vmp.conf.CivilCodeFileConf;
  6. import com.genersoft.iot.vmp.gb28181.bean.Device;
  7. import com.genersoft.iot.vmp.gb28181.bean.DeviceChannel;
  8. import com.genersoft.iot.vmp.gb28181.event.subscribe.catalog.CatalogEvent;
  9. import com.genersoft.iot.vmp.utils.DateUtil;
  10. import org.apache.commons.lang3.math.NumberUtils;
  11. import org.dom4j.Attribute;
  12. import org.dom4j.Document;
  13. import org.dom4j.DocumentException;
  14. import org.dom4j.Element;
  15. import org.dom4j.io.SAXReader;
  16. import org.slf4j.Logger;
  17. import org.slf4j.LoggerFactory;
  18. import org.springframework.util.ObjectUtils;
  19. import org.springframework.util.ReflectionUtils;
  20. import javax.sip.RequestEvent;
  21. import javax.sip.message.Request;
  22. import java.io.ByteArrayInputStream;
  23. import java.io.StringReader;
  24. import java.lang.reflect.Field;
  25. import java.lang.reflect.InvocationTargetException;
  26. import java.lang.reflect.ParameterizedType;
  27. import java.lang.reflect.Type;
  28. import java.util.*;
  29. /**
  30. * 基于dom4j的工具包
  31. *
  32. *
  33. */
  34. public class XmlUtil {
  35. /**
  36. * 日志服务
  37. */
  38. private static Logger logger = LoggerFactory.getLogger(XmlUtil.class);
  39. /**
  40. * 解析XML为Document对象
  41. *
  42. * @param xml 被解析的XMl
  43. *
  44. * @return Document
  45. */
  46. public static Element parseXml(String xml) {
  47. Document document = null;
  48. //
  49. StringReader sr = new StringReader(xml);
  50. SAXReader saxReader = new SAXReader();
  51. try {
  52. document = saxReader.read(sr);
  53. } catch (DocumentException e) {
  54. logger.error("解析失败", e);
  55. }
  56. return null == document ? null : document.getRootElement();
  57. }
  58. /**
  59. * 获取element对象的text的值
  60. *
  61. * @param em 节点的对象
  62. * @param tag 节点的tag
  63. * @return 节点
  64. */
  65. public static String getText(Element em, String tag) {
  66. if (null == em) {
  67. return null;
  68. }
  69. Element e = em.element(tag);
  70. //
  71. return null == e ? null : e.getText().trim();
  72. }
  73. /**
  74. * 递归解析xml节点,适用于 多节点数据
  75. *
  76. * @param node node
  77. * @param nodeName nodeName
  78. * @return List<Map<String, Object>>
  79. */
  80. public static List<Map<String, Object>> listNodes(Element node, String nodeName) {
  81. if (null == node) {
  82. return null;
  83. }
  84. // 初始化返回
  85. List<Map<String, Object>> listMap = new ArrayList<Map<String, Object>>();
  86. // 首先获取当前节点的所有属性节点
  87. List<Attribute> list = node.attributes();
  88. Map<String, Object> map = null;
  89. // 遍历属性节点
  90. for (Attribute attribute : list) {
  91. if (nodeName.equals(node.getName())) {
  92. if (null == map) {
  93. map = new HashMap<String, Object>();
  94. listMap.add(map);
  95. }
  96. // 取到的节点属性放到map中
  97. map.put(attribute.getName(), attribute.getValue());
  98. }
  99. }
  100. // 遍历当前节点下的所有节点 ,nodeName 要解析的节点名称
  101. // 使用递归
  102. Iterator<Element> iterator = node.elementIterator();
  103. while (iterator.hasNext()) {
  104. Element e = iterator.next();
  105. listMap.addAll(listNodes(e, nodeName));
  106. }
  107. return listMap;
  108. }
  109. /**
  110. * xml转json
  111. *
  112. * @param element
  113. * @param json
  114. */
  115. public static void node2Json(Element element, JSONObject json) {
  116. // 如果是属性
  117. for (Object o : element.attributes()) {
  118. Attribute attr = (Attribute) o;
  119. if (!ObjectUtils.isEmpty(attr.getValue())) {
  120. json.put("@" + attr.getName(), attr.getValue());
  121. }
  122. }
  123. List<Element> chdEl = element.elements();
  124. if (chdEl.isEmpty() && !ObjectUtils.isEmpty(element.getText())) {// 如果没有子元素,只有一个值
  125. json.put(element.getName(), element.getText());
  126. }
  127. for (Element e : chdEl) { // 有子元素
  128. if (!e.elements().isEmpty()) { // 子元素也有子元素
  129. JSONObject chdjson = new JSONObject();
  130. node2Json(e, chdjson);
  131. Object o = json.get(e.getName());
  132. if (o != null) {
  133. JSONArray jsona = null;
  134. if (o instanceof JSONObject) { // 如果此元素已存在,则转为jsonArray
  135. JSONObject jsono = (JSONObject) o;
  136. json.remove(e.getName());
  137. jsona = new JSONArray();
  138. jsona.add(jsono);
  139. jsona.add(chdjson);
  140. }
  141. if (o instanceof JSONArray) {
  142. jsona = (JSONArray) o;
  143. jsona.add(chdjson);
  144. }
  145. json.put(e.getName(), jsona);
  146. } else {
  147. if (!chdjson.isEmpty()) {
  148. json.put(e.getName(), chdjson);
  149. }
  150. }
  151. } else { // 子元素没有子元素
  152. for (Object o : element.attributes()) {
  153. Attribute attr = (Attribute) o;
  154. if (!ObjectUtils.isEmpty(attr.getValue())) {
  155. json.put("@" + attr.getName(), attr.getValue());
  156. }
  157. }
  158. if (!e.getText().isEmpty()) {
  159. json.put(e.getName(), e.getText());
  160. }
  161. }
  162. }
  163. }
  164. public static Element getRootElement(RequestEvent evt) throws DocumentException {
  165. return getRootElement(evt, "gb2312");
  166. }
  167. public static Element getRootElement(RequestEvent evt, String charset) throws DocumentException {
  168. Request request = evt.getRequest();
  169. return getRootElement(request.getRawContent(), charset);
  170. }
  171. public static Element getRootElement(byte[] content, String charset) throws DocumentException {
  172. if (charset == null) {
  173. charset = "gb2312";
  174. }
  175. SAXReader reader = new SAXReader();
  176. reader.setEncoding(charset);
  177. Document xml = reader.read(new ByteArrayInputStream(content));
  178. return xml.getRootElement();
  179. }
  180. private enum ChannelType{
  181. CivilCode, BusinessGroup,VirtualOrganization,Other
  182. }
  183. public static DeviceChannel channelContentHandler(Element itemDevice, Device device, String event, CivilCodeFileConf civilCodeFileConf){
  184. DeviceChannel deviceChannel = new DeviceChannel();
  185. deviceChannel.setDeviceId(device.getDeviceId());
  186. Element channdelIdElement = itemDevice.element("DeviceID");
  187. if (channdelIdElement == null) {
  188. logger.warn("解析Catalog消息时发现缺少 DeviceID");
  189. return null;
  190. }
  191. String channelId = channdelIdElement.getTextTrim();
  192. if (ObjectUtils.isEmpty(channelId)) {
  193. logger.warn("解析Catalog消息时发现缺少 DeviceID");
  194. return null;
  195. }
  196. deviceChannel.setChannelId(channelId);
  197. if (event != null && !event.equals(CatalogEvent.ADD) && !event.equals(CatalogEvent.UPDATE)) {
  198. // 除了ADD和update情况下需要识别全部内容,
  199. return deviceChannel;
  200. }
  201. Element nameElement = itemDevice.element("Name");
  202. if (nameElement != null) {
  203. deviceChannel.setName(nameElement.getText());
  204. }
  205. if(channelId.length() <= 8) {
  206. deviceChannel.setHasAudio(false);
  207. CivilCodePo parentCode = civilCodeFileConf.getParentCode(channelId);
  208. if (parentCode != null) {
  209. deviceChannel.setParentId(parentCode.getCode());
  210. deviceChannel.setCivilCode(parentCode.getCode());
  211. }else {
  212. logger.warn("[xml解析] 无法确定行政区划{}的上级行政区划", channelId);
  213. }
  214. deviceChannel.setStatus(true);
  215. return deviceChannel;
  216. }else {
  217. if(channelId.length() != 20) {
  218. logger.warn("[xml解析] 失败,编号不符合国标28181定义: {}", channelId);
  219. return null;
  220. }
  221. int code = Integer.parseInt(channelId.substring(10, 13));
  222. if (code == 136 || code == 137 || code == 138) {
  223. deviceChannel.setHasAudio(true);
  224. }else {
  225. deviceChannel.setHasAudio(false);
  226. }
  227. // 设备厂商
  228. String manufacturer = getText(itemDevice, "Manufacturer");
  229. // 设备型号
  230. String model = getText(itemDevice, "Model");
  231. // 设备归属
  232. String owner = getText(itemDevice, "Owner");
  233. // 行政区域
  234. String civilCode = getText(itemDevice, "CivilCode");
  235. // 虚拟组织所属的业务分组ID,业务分组根据特定的业务需求制定,一个业务分组包含一组特定的虚拟组织
  236. String businessGroupID = getText(itemDevice, "BusinessGroupID");
  237. // 父设备/区域/系统ID
  238. String parentID = getText(itemDevice, "ParentID");
  239. if (parentID != null && parentID.equalsIgnoreCase("null")) {
  240. parentID = null;
  241. }
  242. // 注册方式(必选)缺省为1;1:符合IETFRFC3261标准的认证注册模式;2:基于口令的双向认证注册模式;3:基于数字证书的双向认证注册模式
  243. String registerWay = getText(itemDevice, "RegisterWay");
  244. // 保密属性(必选)缺省为0;0:不涉密,1:涉密
  245. String secrecy = getText(itemDevice, "Secrecy");
  246. // 安装地址
  247. String address = getText(itemDevice, "Address");
  248. switch (code){
  249. case 200:
  250. // 系统目录
  251. if (!ObjectUtils.isEmpty(manufacturer)) {
  252. deviceChannel.setManufacture(manufacturer);
  253. }
  254. if (!ObjectUtils.isEmpty(model)) {
  255. deviceChannel.setModel(model);
  256. }
  257. if (!ObjectUtils.isEmpty(owner)) {
  258. deviceChannel.setOwner(owner);
  259. }
  260. if (!ObjectUtils.isEmpty(civilCode)) {
  261. deviceChannel.setCivilCode(civilCode);
  262. deviceChannel.setParentId(civilCode);
  263. }else {
  264. if (!ObjectUtils.isEmpty(parentID)) {
  265. deviceChannel.setParentId(parentID);
  266. }
  267. }
  268. if (!ObjectUtils.isEmpty(address)) {
  269. deviceChannel.setAddress(address);
  270. }
  271. deviceChannel.setStatus(true);
  272. if (!ObjectUtils.isEmpty(registerWay)) {
  273. try {
  274. deviceChannel.setRegisterWay(Integer.parseInt(registerWay));
  275. }catch (NumberFormatException exception) {
  276. logger.warn("[xml解析] 从通道数据获取registerWay失败: {}", registerWay);
  277. }
  278. }
  279. if (!ObjectUtils.isEmpty(secrecy)) {
  280. deviceChannel.setSecrecy(secrecy);
  281. }
  282. return deviceChannel;
  283. case 215:
  284. // 业务分组
  285. deviceChannel.setStatus(true);
  286. if (!ObjectUtils.isEmpty(parentID)) {
  287. if (!parentID.trim().equalsIgnoreCase(device.getDeviceId())) {
  288. deviceChannel.setParentId(parentID);
  289. }
  290. }else {
  291. logger.warn("[xml解析] 业务分组数据中缺少关键信息->ParentId");
  292. if (!ObjectUtils.isEmpty(civilCode)) {
  293. deviceChannel.setCivilCode(civilCode);
  294. }
  295. }
  296. break;
  297. case 216:
  298. // 虚拟组织
  299. deviceChannel.setStatus(true);
  300. if (!ObjectUtils.isEmpty(businessGroupID)) {
  301. deviceChannel.setBusinessGroupId(businessGroupID);
  302. }
  303. if (!ObjectUtils.isEmpty(parentID)) {
  304. if (parentID.contains("/")) {
  305. String[] parentIdArray = parentID.split("/");
  306. parentID = parentIdArray[parentIdArray.length - 1];
  307. }
  308. deviceChannel.setParentId(parentID);
  309. }else {
  310. if (!ObjectUtils.isEmpty(businessGroupID)) {
  311. deviceChannel.setParentId(businessGroupID);
  312. }
  313. }
  314. break;
  315. default:
  316. // 设备目录
  317. if (!ObjectUtils.isEmpty(manufacturer)) {
  318. deviceChannel.setManufacture(manufacturer);
  319. }
  320. if (!ObjectUtils.isEmpty(model)) {
  321. deviceChannel.setModel(model);
  322. }
  323. if (!ObjectUtils.isEmpty(owner)) {
  324. deviceChannel.setOwner(owner);
  325. }
  326. if (!ObjectUtils.isEmpty(civilCode)
  327. && civilCode.length() <= 8
  328. && NumberUtils.isParsable(civilCode)
  329. && civilCode.length()%2 == 0
  330. ) {
  331. deviceChannel.setCivilCode(civilCode);
  332. }
  333. if (!ObjectUtils.isEmpty(businessGroupID)) {
  334. deviceChannel.setBusinessGroupId(businessGroupID);
  335. }
  336. // 警区
  337. String block = getText(itemDevice, "Block");
  338. if (!ObjectUtils.isEmpty(block)) {
  339. deviceChannel.setBlock(block);
  340. }
  341. if (!ObjectUtils.isEmpty(address)) {
  342. deviceChannel.setAddress(address);
  343. }
  344. if (!ObjectUtils.isEmpty(secrecy)) {
  345. deviceChannel.setSecrecy(secrecy);
  346. }
  347. // 当为设备时,是否有子设备(必选)1有,0没有
  348. String parental = getText(itemDevice, "Parental");
  349. if (!ObjectUtils.isEmpty(parental)) {
  350. try {
  351. // 由于海康会错误的发送65535作为这里的取值,所以这里除非是0否则认为是1
  352. if (!ObjectUtils.isEmpty(parental) && parental.length() == 1 && Integer.parseInt(parental) == 0) {
  353. deviceChannel.setParental(0);
  354. }else {
  355. deviceChannel.setParental(1);
  356. }
  357. }catch (NumberFormatException e) {
  358. logger.warn("[xml解析] 从通道数据获取 parental失败: {}", parental);
  359. }
  360. }
  361. // 父设备/区域/系统ID
  362. if (!ObjectUtils.isEmpty(parentID) ) {
  363. if (parentID.contains("/")) {
  364. String[] parentIdArray = parentID.split("/");
  365. deviceChannel.setParentId(parentIdArray[parentIdArray.length - 1]);
  366. }else {
  367. if (parentID.length()%2 == 0) {
  368. deviceChannel.setParentId(parentID);
  369. }else {
  370. logger.warn("[xml解析] 不规范的parentID:{}, 已舍弃", parentID);
  371. }
  372. }
  373. }else {
  374. if (!ObjectUtils.isEmpty(businessGroupID)) {
  375. deviceChannel.setParentId(businessGroupID);
  376. }else {
  377. if (!ObjectUtils.isEmpty(deviceChannel.getCivilCode())) {
  378. deviceChannel.setParentId(deviceChannel.getCivilCode());
  379. }
  380. }
  381. }
  382. // 注册方式
  383. if (!ObjectUtils.isEmpty(registerWay)) {
  384. try {
  385. int registerWayInt = Integer.parseInt(registerWay);
  386. deviceChannel.setRegisterWay(registerWayInt);
  387. }catch (NumberFormatException exception) {
  388. logger.warn("[xml解析] 从通道数据获取registerWay失败: {}", registerWay);
  389. deviceChannel.setRegisterWay(1);
  390. }
  391. }else {
  392. deviceChannel.setRegisterWay(1);
  393. }
  394. // 信令安全模式(可选)缺省为0; 0:不采用;2:S/MIME 签名方式;3:S/MIME加密签名同时采用方式;4:数字摘要方式
  395. String safetyWay = getText(itemDevice, "SafetyWay");
  396. if (!ObjectUtils.isEmpty(safetyWay)) {
  397. try {
  398. deviceChannel.setSafetyWay(Integer.parseInt(safetyWay));
  399. }catch (NumberFormatException e) {
  400. logger.warn("[xml解析] 从通道数据获取 safetyWay失败: {}", safetyWay);
  401. }
  402. }
  403. // 证书序列号(有证书的设备必选)
  404. String certNum = getText(itemDevice, "CertNum");
  405. if (!ObjectUtils.isEmpty(certNum)) {
  406. deviceChannel.setCertNum(certNum);
  407. }
  408. // 证书有效标识(有证书的设备必选)缺省为0;证书有效标识:0:无效 1:有效
  409. String certifiable = getText(itemDevice, "Certifiable");
  410. if (!ObjectUtils.isEmpty(certifiable)) {
  411. try {
  412. deviceChannel.setCertifiable(Integer.parseInt(certifiable));
  413. }catch (NumberFormatException e) {
  414. logger.warn("[xml解析] 从通道数据获取 Certifiable失败: {}", certifiable);
  415. }
  416. }
  417. // 无效原因码(有证书且证书无效的设备必选)
  418. String errCode = getText(itemDevice, "ErrCode");
  419. if (!ObjectUtils.isEmpty(errCode)) {
  420. try {
  421. deviceChannel.setErrCode(Integer.parseInt(errCode));
  422. }catch (NumberFormatException e) {
  423. logger.warn("[xml解析] 从通道数据获取 ErrCode失败: {}", errCode);
  424. }
  425. }
  426. // 证书终止有效期(有证书的设备必选)
  427. String endTime = getText(itemDevice, "EndTime");
  428. if (!ObjectUtils.isEmpty(endTime)) {
  429. deviceChannel.setEndTime(endTime);
  430. }
  431. // 设备/区域/系统IP地址
  432. String ipAddress = getText(itemDevice, "IPAddress");
  433. if (!ObjectUtils.isEmpty(ipAddress)) {
  434. deviceChannel.setIpAddress(ipAddress);
  435. }
  436. // 设备/区域/系统端口
  437. String port = getText(itemDevice, "Port");
  438. if (!ObjectUtils.isEmpty(port)) {
  439. try {
  440. deviceChannel.setPort(Integer.parseInt(port));
  441. }catch (NumberFormatException e) {
  442. logger.warn("[xml解析] 从通道数据获取 Port失败: {}", port);
  443. }
  444. }
  445. // 设备口令
  446. String password = getText(itemDevice, "Password");
  447. if (!ObjectUtils.isEmpty(password)) {
  448. deviceChannel.setPassword(password);
  449. }
  450. // 设备状态
  451. String status = getText(itemDevice, "Status");
  452. if (status != null) {
  453. // ONLINE OFFLINE HIKVISION DS-7716N-E4 NVR的兼容性处理
  454. if (status.equals("ON") || status.equals("On") || status.equals("ONLINE") || status.equals("OK")) {
  455. deviceChannel.setStatus(true);
  456. }
  457. if (status.equals("OFF") || status.equals("Off") || status.equals("OFFLINE")) {
  458. deviceChannel.setStatus(false);
  459. }
  460. }else {
  461. deviceChannel.setStatus(true);
  462. }
  463. // 经度
  464. String longitude = getText(itemDevice, "Longitude");
  465. if (NumericUtil.isDouble(longitude)) {
  466. deviceChannel.setLongitude(Double.parseDouble(longitude));
  467. } else {
  468. deviceChannel.setLongitude(0.00);
  469. }
  470. // 纬度
  471. String latitude = getText(itemDevice, "Latitude");
  472. if (NumericUtil.isDouble(latitude)) {
  473. deviceChannel.setLatitude(Double.parseDouble(latitude));
  474. } else {
  475. deviceChannel.setLatitude(0.00);
  476. }
  477. deviceChannel.setGpsTime(DateUtil.getNow());
  478. // -摄像机类型扩展,标识摄像机类型:1-球机;2-半球;3-固定枪机;4-遥控枪机。当目录项为摄像机时可选
  479. String ptzType = getText(itemDevice, "PTZType");
  480. if (ObjectUtils.isEmpty(ptzType)) {
  481. //兼容INFO中的信息
  482. Element info = itemDevice.element("Info");
  483. String ptzTypeFromInfo = XmlUtil.getText(info, "PTZType");
  484. if(!ObjectUtils.isEmpty(ptzTypeFromInfo)){
  485. try {
  486. deviceChannel.setPTZType(Integer.parseInt(ptzTypeFromInfo));
  487. }catch (NumberFormatException e){
  488. logger.warn("[xml解析] 从通道数据info中获取PTZType失败: {}", ptzTypeFromInfo);
  489. }
  490. }
  491. } else {
  492. try {
  493. deviceChannel.setPTZType(Integer.parseInt(ptzType));
  494. }catch (NumberFormatException e){
  495. logger.warn("[xml解析] 从通道数据中获取PTZType失败: {}", ptzType);
  496. }
  497. }
  498. // TODO 摄像机位置类型扩展。
  499. // 1-省际检查站、
  500. // 2-党政机关、
  501. // 3-车站码头、
  502. // 4-中心广场、
  503. // 5-体育场馆、
  504. // 6-商业中心、
  505. // 7-宗教场所、
  506. // 8-校园周边、
  507. // 9-治安复杂区域、
  508. // 10-交通干线。
  509. // String positionType = getText(itemDevice, "PositionType");
  510. // TODO 摄像机安装位置室外、室内属性。1-室外、2-室内。
  511. // String roomType = getText(itemDevice, "RoomType");
  512. // TODO 摄像机用途属性
  513. // String useType = getText(itemDevice, "UseType");
  514. // TODO 摄像机补光属性。1-无补光、2-红外补光、3-白光补光
  515. // String supplyLightType = getText(itemDevice, "SupplyLightType");
  516. // TODO 摄像机监视方位属性。1-东、2-西、3-南、4-北、5-东南、6-东北、7-西南、8-西北。
  517. // String directionType = getText(itemDevice, "DirectionType");
  518. // TODO 摄像机支持的分辨率,可有多个分辨率值,各个取值间以“/”分隔。分辨率取值参见附录 F中SDPf字段规定
  519. // String resolution = getText(itemDevice, "Resolution");
  520. // TODO 下载倍速范围(可选),各可选参数以“/”分隔,如设备支持1,2,4倍速下载则应写为“1/2/4
  521. // String downloadSpeed = getText(itemDevice, "DownloadSpeed");
  522. // TODO 空域编码能力,取值0:不支持;1:1级增强(1个增强层);2:2级增强(2个增强层);3:3级增强(3个增强层)
  523. // String svcSpaceSupportMode = getText(itemDevice, "SVCSpaceSupportMode");
  524. // TODO 时域编码能力,取值0:不支持;1:1级增强;2:2级增强;3:3级增强
  525. // String svcTimeSupportMode = getText(itemDevice, "SVCTimeSupportMode");
  526. deviceChannel.setSecrecy(secrecy);
  527. break;
  528. }
  529. }
  530. return deviceChannel;
  531. }
  532. /**
  533. * 新增方法支持内部嵌套
  534. *
  535. * @param element xmlElement
  536. * @param clazz 结果类
  537. * @param <T> 泛型
  538. * @return 结果对象
  539. * @throws NoSuchMethodException
  540. * @throws InvocationTargetException
  541. * @throws InstantiationException
  542. * @throws IllegalAccessException
  543. */
  544. public static <T> T loadElement(Element element, Class<T> clazz) throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
  545. Field[] fields = clazz.getDeclaredFields();
  546. T t = clazz.getDeclaredConstructor().newInstance();
  547. for (Field field : fields) {
  548. ReflectionUtils.makeAccessible(field);
  549. MessageElement annotation = field.getAnnotation(MessageElement.class);
  550. if (annotation == null) {
  551. continue;
  552. }
  553. String value = annotation.value();
  554. String subVal = annotation.subVal();
  555. Element element1 = element.element(value);
  556. if (element1 == null) {
  557. continue;
  558. }
  559. if ("".equals(subVal)) {
  560. // 无下级数据
  561. Object fieldVal = element1.isTextOnly() ? element1.getText() : loadElement(element1, field.getType());
  562. Object o = simpleTypeDeal(field.getType(), fieldVal);
  563. ReflectionUtils.setField(field, t, o);
  564. } else {
  565. // 存在下级数据
  566. ArrayList<Object> list = new ArrayList<>();
  567. Type genericType = field.getGenericType();
  568. if (!(genericType instanceof ParameterizedType)) {
  569. continue;
  570. }
  571. Class<?> aClass = (Class<?>) ((ParameterizedType) genericType).getActualTypeArguments()[0];
  572. for (Element element2 : element1.elements(subVal)) {
  573. list.add(loadElement(element2, aClass));
  574. }
  575. ReflectionUtils.setField(field, t, list);
  576. }
  577. }
  578. return t;
  579. }
  580. /**
  581. * 简单类型处理
  582. *
  583. * @param tClass
  584. * @param val
  585. * @return
  586. */
  587. private static Object simpleTypeDeal(Class<?> tClass, Object val) {
  588. if (tClass.equals(String.class)) {
  589. return val.toString();
  590. }
  591. if (tClass.equals(Integer.class)) {
  592. return Integer.valueOf(val.toString());
  593. }
  594. if (tClass.equals(Double.class)) {
  595. return Double.valueOf(val.toString());
  596. }
  597. if (tClass.equals(Long.class)) {
  598. return Long.valueOf(val.toString());
  599. }
  600. return val;
  601. }
  602. }