AbstractAdmBaseServiceImpl.java 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  1. package com.persagy.proxy.adm.service.impl;
  2. import java.io.IOException;
  3. import java.lang.reflect.Field;
  4. import java.lang.reflect.ParameterizedType;
  5. import java.util.ArrayList;
  6. import java.util.HashMap;
  7. import java.util.List;
  8. import java.util.Map;
  9. import java.util.Set;
  10. import org.springframework.beans.factory.annotation.Autowired;
  11. import com.alibaba.fastjson.JSONArray;
  12. import com.alibaba.fastjson.JSONObject;
  13. import com.fasterxml.jackson.databind.ObjectMapper;
  14. import com.fasterxml.jackson.databind.node.ArrayNode;
  15. import com.fasterxml.jackson.databind.node.JsonNodeFactory;
  16. import com.fasterxml.jackson.databind.node.ObjectNode;
  17. import com.persagy.dmp.basic.model.QueryCriteria;
  18. import com.persagy.dmp.common.constant.ValidEnum;
  19. import com.persagy.dmp.common.helper.SpringHelper;
  20. import com.persagy.dmp.common.model.entity.BaseEntity;
  21. import com.persagy.dmp.common.utils.JsonHelper;
  22. import com.persagy.dmp.digital.client.DigitalObjectFacade;
  23. import com.persagy.dmp.digital.entity.ObjectRelation;
  24. import com.persagy.proxy.adm.annotations.CascadeColumn;
  25. import com.persagy.proxy.adm.request.AdmQueryCriteria;
  26. import com.persagy.proxy.adm.request.AdmResponse;
  27. import com.persagy.proxy.adm.service.IAdmBaseService;
  28. import com.persagy.proxy.adm.service.IAdmRelationService;
  29. import com.persagy.proxy.adm.utils.AdmEntityTransferUtil;
  30. import com.persagy.proxy.adm.utils.AdmQueryCriteriaHelper;
  31. import com.persagy.proxy.common.client.DmpRwdClient;
  32. import com.persagy.proxy.common.entity.DmpResult;
  33. import com.persagy.proxy.common.entity.InstanceUrlParam;
  34. import cn.hutool.core.collection.CollUtil;
  35. import cn.hutool.core.map.MapUtil;
  36. import cn.hutool.core.util.ReflectUtil;
  37. import cn.hutool.core.util.StrUtil;
  38. import lombok.extern.slf4j.Slf4j;
  39. /**
  40. * ADM 抽象实现类
  41. * @author Charlie Yu
  42. * @date 2021-08-16
  43. */
  44. @Slf4j
  45. public class AbstractAdmBaseServiceImpl<T> implements IAdmBaseService<T> {
  46. @Autowired
  47. private DmpRwdClient rwdClient;
  48. @Autowired
  49. private ObjectMapper objectMapper;
  50. /**
  51. * 查询
  52. * @param request
  53. * @return
  54. */
  55. @Override
  56. public AdmResponse doQuery(InstanceUrlParam context, AdmQueryCriteria request, Class<T> clazz) {
  57. // 转换为数据中台查询条件
  58. QueryCriteria dmpRequest = AdmQueryCriteriaHelper.toDmpCriteria(request);
  59. // 提供一个钩子方法用于处理已封装好的中台查询参数(因传参有buildingId而处理)
  60. processDmpCriteria(dmpRequest);
  61. // 转换参数
  62. JSONObject para = null;
  63. try {
  64. para = JsonHelper.toJsonObject(dmpRequest);
  65. } catch (IOException e) {
  66. log.error(e.getMessage(), e);
  67. return AdmResponse.failure("参数格式有误");
  68. }
  69. log.info("param: {}", para.toString());
  70. // 调用中台查询
  71. DmpResult<JSONArray> dmpResult = rwdClient.queryObject(context, para);
  72. List<T> admVOs = AdmEntityTransferUtil.toAdmMultiEntity(dmpResult.getData(), request.getProjection(), clazz);
  73. //List<T> admVOs = AdmEntityTransferUtil.toAdmMultiEntityExtra(dmpResult.getData(), request.getProjection(), clazz);
  74. // 级联查询
  75. processCascade(context, admVOs, request.getName(), request.getCascade());
  76. // 设置返回值
  77. AdmResponse response = AdmResponse.success(admVOs);
  78. Long total = dmpResult.getCount() == null ? null : dmpResult.getCount().longValue();
  79. if(request.isOnlyCount()){
  80. response.setTotal(null);
  81. response.setCount(total);
  82. }else {
  83. response.setTotal(total);
  84. }
  85. response.setPageNumber(request.getPageNumber());
  86. response.setPageSize(request.getPageSize());
  87. return response;
  88. }
  89. /***
  90. * Description: 提供一个钩子方法用于处理已封装好的中台查询参数(因传参有buildingId而处理)
  91. * @param dmpRequest : 中台查询参数
  92. * @return : void
  93. * @author : lijie
  94. * @date :2021/10/28 20:23
  95. * Update By lijie 2021/10/28 20:23
  96. */
  97. protected void processDmpCriteria(QueryCriteria dmpRequest) {
  98. // 空方法,需要时子类重写
  99. }
  100. /**
  101. * 处理级联查询
  102. * @param context
  103. * @param admVOs
  104. * @param name
  105. * @param cascades
  106. */
  107. private void processCascade(InstanceUrlParam context, List admVOs, String name, List<AdmQueryCriteria> cascades) {
  108. if(CollUtil.isEmpty(admVOs) || CollUtil.isEmpty(cascades)) {
  109. return;
  110. }
  111. Map<String, Object> voMap = CollUtil.fieldValueMap(admVOs, BaseEntity.PROP_ID);
  112. Object simpleVO = admVOs.get(0);
  113. for(AdmQueryCriteria cascade:cascades) {
  114. if(StrUtil.isBlank(cascade.getName())){
  115. //处理 级联查询参数name首字母大写cascade": [ {"Name": "property"}]
  116. continue;
  117. }
  118. // 获取关联对象的Class
  119. Field casField = ReflectUtil.getField(simpleVO.getClass(), cascade.getName());
  120. if(casField == null) {
  121. continue;
  122. }
  123. // 获取级联信息
  124. CascadeColumn annotationInfo = casField.getAnnotation(CascadeColumn.class);
  125. if(annotationInfo == null) {
  126. continue;
  127. }
  128. Class clazz = getFieldRealClass(casField);
  129. // 获取关联对象的类型
  130. String objectType = getObjTypeByClass(clazz);
  131. if(StrUtil.isBlank(objectType)) {
  132. continue;
  133. }
  134. cascade.setName(objectType);
  135. // 转换为数据中台查询条件
  136. QueryCriteria dmpRequest = AdmQueryCriteriaHelper.toDmpCriteria(cascade);
  137. // 拼接关系条件,得到关系映射
  138. Map<String, List<String>> idMap = ensureRelationCond(context, dmpRequest.getCriteria(), voMap.keySet(), annotationInfo);
  139. if(MapUtil.isEmpty(idMap)) {
  140. continue;
  141. }
  142. // 查询结果
  143. List vos = queryByCondition(context, dmpRequest, cascade.getProjection(), clazz);
  144. if(CollUtil.isEmpty(vos)) {
  145. continue;
  146. }
  147. // 写回原对象中
  148. writeToVOs(voMap, idMap, vos, casField);
  149. // 递归继续处理
  150. processCascade(context, vos, objectType, cascade.getCascade());
  151. }
  152. }
  153. /**
  154. * 拼接关系条件
  155. * @param context
  156. * @param node
  157. * @param idList
  158. * @param annotationInfo
  159. * @return
  160. */
  161. private Map<String, List<String>> ensureRelationCond(InstanceUrlParam context, ObjectNode node, Set<String> idList, CascadeColumn annotationInfo) {
  162. if(CollUtil.isEmpty(idList)) {
  163. return null;
  164. }
  165. // 查询关系
  166. List<ObjectRelation> relations = queryRelations(context, idList, annotationInfo);
  167. ArrayNode array = node.putObject(BaseEntity.PROP_ID).putArray("$in");
  168. // 拼接查询条件
  169. if(CollUtil.isEmpty(relations)) {
  170. array.add("0");
  171. } else {
  172. List<String> relList = CollUtil.getFieldValues(relations, annotationInfo.selectToObj()?"objTo":"objFrom", String.class);
  173. relList.forEach(id -> array.add(id));
  174. }
  175. if(annotationInfo.selectToObj()){
  176. return groupMapList(relations, "objFrom", "objTo");
  177. }else{
  178. return groupMapList(relations, "objTo", "objFrom");
  179. }
  180. }
  181. /**
  182. * 将集合转换为Map
  183. * @param list 集合
  184. * @param keyField key属性名
  185. * @param valueField value属性名
  186. * @return
  187. */
  188. private static Map<String, List<String>> groupMapList(List<?> list, String keyField, String valueField) {
  189. if(CollUtil.isEmpty(list)) {
  190. return null;
  191. }
  192. Map<String, List<String>> groupMap = new HashMap<>();
  193. for(Object vo:list) {
  194. String key = (String) ReflectUtil.getFieldValue(vo, keyField);
  195. String value = (String) ReflectUtil.getFieldValue(vo, valueField);
  196. if(!StrUtil.isAllNotBlank(key, value)) {
  197. continue;
  198. }
  199. List<String> valueList = groupMap.get(key);
  200. if(CollUtil.isEmpty(valueList)) {
  201. valueList = new ArrayList<>();
  202. groupMap.put(key, valueList);
  203. }
  204. valueList.add(value);
  205. }
  206. return groupMap;
  207. }
  208. /**
  209. * 查询关系
  210. * @param context
  211. * @param idList
  212. * @param anno
  213. * @return
  214. */
  215. private List<ObjectRelation> queryRelations(InstanceUrlParam context, Set<String>idList, CascadeColumn anno) {
  216. // 如果没有任何配置,不处理
  217. if(StrUtil.isBlank(anno.graphCode()) && StrUtil.isBlank(anno.relCode()) &&
  218. StrUtil.isBlank(anno.relValue())) {
  219. return null;
  220. }
  221. // 查询关系
  222. QueryCriteria queryRequest = new QueryCriteria();
  223. ObjectNode criteria = JsonNodeFactory.instance.objectNode();
  224. queryRequest.setCriteria(criteria);
  225. boolean isSelectTo = anno.selectToObj();
  226. criteria.put(BaseEntity.PROP_VALID, ValidEnum.TRUE.getType());
  227. putString(criteria, "graphCode", anno.graphCode());
  228. putString(criteria, "relCode", anno.relCode());
  229. putString(criteria, "relValue", anno.relValue());
  230. ArrayNode array = criteria.putObject(isSelectTo?"objFrom":"objTo").putArray("$in");
  231. idList.forEach(id -> array.add(id));
  232. return SpringHelper.getBean(IAdmRelationService.class).queryByCondition(context, queryRequest);
  233. }
  234. /**
  235. * 添加字符串条件
  236. * @param node
  237. * @param key
  238. * @param value
  239. */
  240. private void putString(ObjectNode node, String key, String value) {
  241. if(StrUtil.isBlank(value)) {
  242. return;
  243. }
  244. node.put(key, value);
  245. }
  246. /**
  247. * 将子集写回到对象中
  248. * @param voMap 原始对象Map
  249. * @param idMap 主键映射<mainId, List<subId>>
  250. * @param vos 子对象
  251. * @param casField 子对象对应属性
  252. */
  253. private <V> void writeToVOs(Map<String, Object> voMap, Map<String, List<String>> idMap, List<V> vos, Field casField) {
  254. if(CollUtil.isEmpty(vos) || MapUtil.isEmpty(idMap)) {
  255. return;
  256. }
  257. // 转换为Map
  258. Map<String, V> subVOMap = CollUtil.fieldValueMap(vos, BaseEntity.PROP_ID);
  259. // 是否为集合
  260. boolean isList = List.class.isAssignableFrom(casField.getType());
  261. // 按对象循环
  262. for(String id:voMap.keySet()) {
  263. Object mainVO = voMap.get(id);
  264. List<String> subIdList = idMap.get(id);
  265. if(CollUtil.isEmpty(subIdList)) {
  266. continue;
  267. }
  268. // 如果是集合
  269. if(isList) {
  270. // 取出对应的对象集合
  271. Map<String, V> currVOMap = MapUtil.filter(subVOMap, subIdList.toArray(new String[0]));
  272. List<V> voList = CollUtil.newArrayList(currVOMap.values());
  273. ReflectUtil.setFieldValue(mainVO, casField, voList);
  274. } else {
  275. // 非集合取第一个即可
  276. String subId = subIdList.get(0);
  277. V vo = subVOMap.get(subId);
  278. ReflectUtil.setFieldValue(mainVO, casField, vo);
  279. }
  280. }
  281. }
  282. /**
  283. * 调用Client查询
  284. * @param context
  285. * @param criteria
  286. * @param projection
  287. * @param clazz
  288. * @return
  289. */
  290. private <V> List<V> queryByCondition(InstanceUrlParam context, QueryCriteria criteria, List<String> projection, Class<V> clazz) {
  291. // 转换参数
  292. if(criteria == null) {
  293. return null;
  294. }
  295. List<ObjectNode> objects = DigitalObjectFacade.query(context.getGroupCode(), context.getProjectId(),
  296. context.getAppId(), null, criteria);
  297. return AdmEntityTransferUtil.toAdmMultiEntity(objects, projection, clazz);
  298. }
  299. /**
  300. * 获取实际的Class
  301. * @param casField
  302. * @return
  303. */
  304. private Class getFieldRealClass(Field casField) {
  305. // 取到Field
  306. Class clazz = casField.getType();
  307. // 如果是集合,则取实际的对象
  308. if(List.class.isAssignableFrom(clazz)) {
  309. clazz = (Class) ((ParameterizedType) casField.getGenericType()).getActualTypeArguments()[0];
  310. }
  311. return clazz;
  312. }
  313. /**
  314. * 通过Class获取其对象类型
  315. * @param clazz
  316. * @return
  317. */
  318. private String getObjTypeByClass(Class clazz) {
  319. // 获取关联对象的类型
  320. String objectType = null;
  321. try {
  322. objectType = (String) ReflectUtil.getFieldValue(clazz.newInstance(), "objectType");
  323. } catch (Exception e) {
  324. log.error(e.getMessage(), e);
  325. }
  326. return objectType;
  327. }
  328. /**
  329. * 新增
  330. * @param context
  331. * @param clazz
  332. * @param voList
  333. * @return
  334. */
  335. @Override
  336. public List<T> doInsert(InstanceUrlParam context, Class<T> clazz, List<T> voList) {
  337. if(CollUtil.isEmpty(voList)) {
  338. return null;
  339. }
  340. ArrayNode vos = AdmEntityTransferUtil.toDmpMultiEntity(voList);
  341. // 调用中台新增
  342. DmpResult<JSONArray> response = rwdClient.createObject(context, JSONArray.parseArray(vos.toString()));
  343. if(!DmpResult.SUCCESS.equals(response.getResult())) {
  344. throw new RuntimeException("调用中台查询接口出错:" + response.getMessage());
  345. }
  346. // 转换为结果
  347. return AdmEntityTransferUtil.toAdmMultiEntity(response.getData(), null, clazz);
  348. }
  349. /**
  350. * 修改
  351. * @param context
  352. * @param clazz
  353. * @param voList
  354. * @return
  355. */
  356. @Override
  357. public List<T> doUpdate(InstanceUrlParam context, Class<T> clazz, List<T> voList) {
  358. if(CollUtil.isEmpty(voList)) {
  359. return null;
  360. }
  361. ArrayNode vos = AdmEntityTransferUtil.toDmpMultiEntity(voList);
  362. // 调用中台修改
  363. DmpResult<cn.hutool.json.JSONArray> response = rwdClient.updateObject(context, JSONArray.parseArray(vos.toString()));
  364. if(!DmpResult.SUCCESS.equals(response.getResult())) {
  365. throw new RuntimeException("调用中台查询接口出错:" + response.getMessage());
  366. }
  367. // 转换为结果
  368. return AdmEntityTransferUtil.toAdmMultiEntity(response.getData(), null, clazz);
  369. }
  370. /**
  371. * 删除
  372. * @param context
  373. * @param voList
  374. * @return
  375. */
  376. @Override
  377. public void doDelete(InstanceUrlParam context, List<T> voList) {
  378. if(CollUtil.isEmpty(voList)) {
  379. return;
  380. }
  381. List<String> idList = CollUtil.getFieldValues(voList, "id", String.class);
  382. // 调用中台修改
  383. DmpResult response = rwdClient.deleteObject(context, idList);
  384. if(!DmpResult.SUCCESS.equals(response.getResult())) {
  385. throw new RuntimeException("调用中台查询接口出错:" + response.getMessage());
  386. }
  387. }
  388. /**
  389. * 根据物理世界查询条件查询对象信息
  390. * @param context
  391. * @param dmpRequest
  392. * @param clazz
  393. * @return
  394. */
  395. @Override
  396. public AdmResponse doQuery(InstanceUrlParam context, QueryCriteria dmpRequest, Class<T> clazz) {
  397. // 转换参数
  398. JSONObject para = null;
  399. try {
  400. para = JsonHelper.toJsonObject(dmpRequest);
  401. } catch (IOException e) {
  402. log.error(e.getMessage(), e);
  403. return null;
  404. }
  405. // 调用中台查询
  406. DmpResult<JSONArray> dmpResult = rwdClient.queryObject(context, para);
  407. List<T> admVOs = AdmEntityTransferUtil.toAdmMultiEntity(dmpResult.getData(), null, clazz);
  408. // JSONArray data = dmpResult.getData();
  409. // List<T> admVOs = new ArrayList<>();
  410. // if(CollUtil.isNotEmpty(data)){
  411. // admVOs = data.toJavaList(clazz);
  412. // }
  413. // 设置返回值
  414. AdmResponse response = AdmResponse.success(admVOs);
  415. Long total = dmpResult.getCount() == null ? null : dmpResult.getCount().longValue();
  416. response.setTotal(total);
  417. return response;
  418. }
  419. /**
  420. * 查询标记计算关系
  421. * @param context
  422. * @param dmpRequest
  423. * @param clazz
  424. * @return
  425. */
  426. @Override
  427. public AdmResponse doQueryRelationProjectCal(InstanceUrlParam context, QueryCriteria dmpRequest, Class<T> clazz) {
  428. // 转换参数
  429. JSONObject para = null;
  430. try {
  431. para = JsonHelper.toJsonObject(dmpRequest);
  432. } catch (IOException e) {
  433. log.error(e.getMessage(), e);
  434. return null;
  435. }
  436. // 调用中台查询
  437. DmpResult<JSONArray> dmpResult = rwdClient.queryRelationProjectCal(context, para);
  438. List<T> admVOs = AdmEntityTransferUtil.toAdmMultiEntity(dmpResult.getData(), null, clazz);
  439. // 设置返回值
  440. AdmResponse response = AdmResponse.success(admVOs);
  441. Long total = dmpResult.getCount() == null ? null : dmpResult.getCount().longValue();
  442. response.setTotal(total);
  443. return response;
  444. }
  445. /**
  446. * 修改
  447. * @param context
  448. * @param clazz
  449. * @param voList
  450. * @return
  451. */
  452. @Override
  453. public List<T> doUpdateRelationProjectCal(InstanceUrlParam context, Class<T> clazz, List<T> voList) {
  454. if(CollUtil.isEmpty(voList)) {
  455. return null;
  456. }
  457. ArrayNode vos = AdmEntityTransferUtil.toDmpMultiEntity(voList);
  458. // 调用中台修改
  459. DmpResult<JSONArray> response = rwdClient.updateRelationProjectCal(context, JSONArray.parseArray(vos.toString()));
  460. if(!DmpResult.SUCCESS.equals(response.getResult())) {
  461. throw new RuntimeException("调用中台查询接口出错:" + response.getMessage());
  462. }
  463. // 转换为结果
  464. return AdmEntityTransferUtil.toAdmMultiEntity(response.getData(), null, clazz);
  465. }
  466. }