DataInterfaceServiceImpl.java 66 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402
  1. package jnpf.base.service.impl;
  2. import cn.dev33.satoken.context.SaHolder;
  3. import cn.hutool.core.collection.CollectionUtil;
  4. import cn.hutool.core.util.BooleanUtil;
  5. import cn.hutool.core.util.ObjectUtil;
  6. import com.alibaba.fastjson.JSON;
  7. import com.alibaba.fastjson.JSONArray;
  8. import com.alibaba.fastjson.JSONObject;
  9. import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
  10. import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
  11. import com.baomidou.mybatisplus.core.metadata.IPage;
  12. import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
  13. import jnpf.base.ActionResult;
  14. import jnpf.base.ActionResultCode;
  15. import jnpf.base.Pagination;
  16. import jnpf.base.UserInfo;
  17. import jnpf.base.entity.DataInterfaceEntity;
  18. import jnpf.base.entity.DataInterfaceVariateEntity;
  19. import jnpf.base.entity.InterfaceOauthEntity;
  20. import jnpf.base.mapper.DataInterfaceMapper;
  21. import jnpf.base.model.datainterface.*;
  22. import jnpf.base.service.*;
  23. import jnpf.base.util.DataInterfaceParamUtil;
  24. import jnpf.base.util.interfaceUtil.InterfaceUtil;
  25. import jnpf.base.vo.PaginationVO;
  26. import jnpf.config.ConfigValueUtil;
  27. import jnpf.constant.DataInterfaceVarConst;
  28. import jnpf.constant.MsgCode;
  29. import jnpf.database.model.dto.PrepSqlDTO;
  30. import jnpf.database.util.DataSourceUtil;
  31. import jnpf.database.util.JdbcUtil;
  32. import jnpf.exception.DataException;
  33. import jnpf.model.SystemParamModel;
  34. import jnpf.permission.model.authorize.AuthorizeConditionEnum;
  35. import jnpf.permission.service.OrganizeService;
  36. import jnpf.permission.service.UserService;
  37. import jnpf.util.*;
  38. import jnpf.util.wxutil.HttpUtil;
  39. import lombok.extern.slf4j.Slf4j;
  40. import org.apache.commons.lang3.ObjectUtils;
  41. import org.apache.commons.lang3.StringUtils;
  42. import org.springframework.beans.factory.annotation.Autowired;
  43. import org.springframework.stereotype.Service;
  44. import javax.script.ScriptException;
  45. import java.io.UnsupportedEncodingException;
  46. import java.net.URLEncoder;
  47. import java.text.SimpleDateFormat;
  48. import java.time.LocalDateTime;
  49. import java.time.ZoneOffset;
  50. import java.util.*;
  51. import java.util.regex.Matcher;
  52. import java.util.regex.Pattern;
  53. import java.util.stream.Collectors;
  54. /**
  55. * @author JNPF开发平台组
  56. * @version V3.1.0
  57. * @copyright 引迈信息技术有限公司
  58. * @date 2021/3/12 15:31
  59. */
  60. @Service
  61. @Slf4j
  62. public class DataInterfaceServiceImpl extends SuperServiceImpl<DataInterfaceMapper, DataInterfaceEntity> implements DataInterfaceService {
  63. private static final Set<String> MARKERS = Set.of(
  64. DataInterfaceVarConst.ORGANDSUB,
  65. DataInterfaceVarConst.ORGANIZEANDPROGENY,
  66. DataInterfaceVarConst.USERANDSUB,
  67. DataInterfaceVarConst.USERANDPROGENY,
  68. DataInterfaceVarConst.POSITIONANDSUB,
  69. DataInterfaceVarConst.POSITIONANDPROGENY,
  70. DataInterfaceVarConst.CHARORG,
  71. DataInterfaceVarConst.ORG,
  72. DataInterfaceVarConst.POSITIONID,
  73. DataInterfaceVarConst.USER
  74. );
  75. @Autowired
  76. private UserService userApi;
  77. @Autowired
  78. private DbLinkService dblinkService;
  79. @Autowired
  80. private DataSourceUtil dataSourceUtils;
  81. @Autowired
  82. private DataInterfaceLogService dataInterfaceLogService;
  83. @Autowired
  84. private DataInterfaceVariateService dataInterfaceVariateService;
  85. @Autowired
  86. private InterfaceOauthService interfaceOauthService;
  87. @Autowired
  88. private OrganizeService organizeApi;
  89. @Autowired
  90. private DataInterfaceUserService dataInterfaceUserService;
  91. @Autowired
  92. private ConfigValueUtil configValueUtil;
  93. @Override
  94. public List<DataInterfaceEntity> getList(PaginationDataInterface pagination, Integer isSelector) {
  95. // 定义变量判断是否需要使用修改时间倒序
  96. boolean flag = false;
  97. QueryWrapper<DataInterfaceEntity> queryWrapper = new QueryWrapper<>();
  98. if (ObjectUtil.isNotEmpty(pagination.getEnabledMark())) {
  99. queryWrapper.lambda().eq(DataInterfaceEntity::getEnabledMark, pagination.getEnabledMark());
  100. }
  101. //关键字
  102. if (!StringUtil.isEmpty(pagination.getKeyword())) {
  103. flag = true;
  104. queryWrapper.lambda().and(
  105. t -> t.like(DataInterfaceEntity::getFullName, pagination.getKeyword())
  106. .or().like(DataInterfaceEntity::getEnCode, pagination.getKeyword())
  107. );
  108. }
  109. // 是否分页
  110. if (pagination.getHasPage() != null && pagination.getHasPage() == 0) {
  111. queryWrapper.lambda().eq(DataInterfaceEntity::getHasPage, pagination.getHasPage());
  112. }
  113. if (isSelector == 1) {
  114. queryWrapper.lambda().eq(DataInterfaceEntity::getIsPostPosition, 0);
  115. if (ObjectUtil.isEmpty(pagination.getEnabledMark())) {
  116. queryWrapper.lambda().eq(DataInterfaceEntity::getEnabledMark, 1);
  117. }
  118. }
  119. //分类
  120. queryWrapper.lambda().eq(DataInterfaceEntity::getCategory, pagination.getCategory());
  121. // 类型
  122. String type = pagination.getType();
  123. if (StringUtil.isNotEmpty(type)) {
  124. if (type.contains(",")) {
  125. List<Integer> collect = Arrays.stream(type.split(",")).map(Integer::valueOf).collect(Collectors.toList());
  126. queryWrapper.lambda().in(DataInterfaceEntity::getType, collect);
  127. } else {
  128. queryWrapper.lambda().eq(DataInterfaceEntity::getType, Integer.valueOf(type));
  129. }
  130. }
  131. //排序
  132. queryWrapper.lambda().orderByAsc(DataInterfaceEntity::getSortCode)
  133. .orderByDesc(DataInterfaceEntity::getCreatorTime);
  134. if (flag) {
  135. queryWrapper.lambda().orderByDesc(DataInterfaceEntity::getLastModifyTime);
  136. }
  137. Page<DataInterfaceEntity> page = new Page<>(pagination.getCurrentPage(), pagination.getPageSize());
  138. IPage<DataInterfaceEntity> iPage = this.page(page, queryWrapper);
  139. return pagination.setData(iPage.getRecords(), iPage.getTotal());
  140. }
  141. @Override
  142. public List<DataInterfaceEntity> getList(PaginationDataInterfaceSelector pagination) {
  143. QueryWrapper<DataInterfaceEntity> queryWrapper = new QueryWrapper<>();
  144. if (ObjectUtil.equal(pagination.getSourceType(), 1)) {
  145. queryWrapper.lambda().and(t -> t.ne(DataInterfaceEntity::getType, 1).ne(DataInterfaceEntity::getHasPage, 1).ne(DataInterfaceEntity::getIsPostPosition, 1)
  146. .or(tt -> tt.eq(DataInterfaceEntity::getType, 1).eq(DataInterfaceEntity::getAction, 3).ne(DataInterfaceEntity::getHasPage, 1).ne(DataInterfaceEntity::getIsPostPosition, 1))
  147. );
  148. } else if (ObjectUtil.equal(pagination.getSourceType(), 2)) {
  149. queryWrapper.lambda().and(t -> t.ne(DataInterfaceEntity::getType, 1).ne(DataInterfaceEntity::getIsPostPosition, 1)
  150. .or(tt -> tt.eq(DataInterfaceEntity::getType, 1).eq(DataInterfaceEntity::getAction, 3).ne(DataInterfaceEntity::getIsPostPosition, 1))
  151. );
  152. } else if (ObjectUtil.equal(pagination.getSourceType(), 3)) {
  153. queryWrapper.lambda().and(t -> t.ne(DataInterfaceEntity::getType, 1).ne(DataInterfaceEntity::getHasPage, 1).ne(DataInterfaceEntity::getIsPostPosition, 1)
  154. .or(tt -> tt.eq(DataInterfaceEntity::getType, 1).ne(DataInterfaceEntity::getAction, 3).ne(DataInterfaceEntity::getHasPage, 1).ne(DataInterfaceEntity::getIsPostPosition, 1))
  155. );
  156. }
  157. // 类型
  158. String type = pagination.getType();
  159. if (StringUtil.isNotEmpty(type)) {
  160. if (type.contains(",")) {
  161. List<Integer> collect = Arrays.stream(type.split(",")).map(Integer::valueOf).collect(Collectors.toList());
  162. queryWrapper.lambda().in(DataInterfaceEntity::getType, collect);
  163. } else {
  164. queryWrapper.lambda().eq(DataInterfaceEntity::getType, Integer.valueOf(type));
  165. }
  166. }
  167. //分类
  168. queryWrapper.lambda().eq(DataInterfaceEntity::getCategory, pagination.getCategory());
  169. queryWrapper.lambda().eq(DataInterfaceEntity::getEnabledMark, 1);
  170. //关键字查询
  171. if (StringUtil.isNotEmpty(pagination.getKeyword())) {
  172. queryWrapper.lambda().and(t -> {
  173. t.like(DataInterfaceEntity::getFullName, pagination.getKeyword()).or();
  174. t.like(DataInterfaceEntity::getEnCode, pagination.getKeyword());
  175. });
  176. }
  177. //排序
  178. queryWrapper.lambda().orderByAsc(DataInterfaceEntity::getSortCode)
  179. .orderByDesc(DataInterfaceEntity::getCreatorTime);
  180. queryWrapper.lambda().orderByDesc(DataInterfaceEntity::getLastModifyTime);
  181. Page<DataInterfaceEntity> page = new Page<>(pagination.getCurrentPage(), pagination.getPageSize());
  182. IPage<DataInterfaceEntity> iPage = this.page(page, queryWrapper);
  183. return pagination.setData(iPage.getRecords(), iPage.getTotal());
  184. }
  185. @Override
  186. public List<DataInterfaceEntity> getList(boolean filterPage) {
  187. QueryWrapper<DataInterfaceEntity> queryWrapper = new QueryWrapper<>();
  188. if (filterPage) {
  189. queryWrapper.lambda().ne(DataInterfaceEntity::getHasPage, 1);
  190. }
  191. queryWrapper.lambda().eq(DataInterfaceEntity::getEnabledMark, 1)
  192. .orderByAsc(DataInterfaceEntity::getSortCode)
  193. .orderByDesc(DataInterfaceEntity::getCreatorTime);
  194. return baseMapper.selectList(queryWrapper);
  195. }
  196. @Override
  197. public DataInterfaceEntity getInfo(String id) {
  198. QueryWrapper<DataInterfaceEntity> queryWrapper = new QueryWrapper<>();
  199. queryWrapper.lambda().eq(DataInterfaceEntity::getId, id);
  200. return this.getOne(queryWrapper);
  201. }
  202. @Override
  203. public void create(DataInterfaceEntity entity) {
  204. entity.setId(RandomUtil.uuId());
  205. entity.setCreatorUserId(UserProvider.getUser().getUserId());
  206. entity.setCreatorTime(DateUtil.getNowDate());
  207. entity.setLastModifyTime(null);
  208. entity.setLastModifyUserId(null);
  209. this.setIgnoreLogicDelete().saveOrUpdate(entity);
  210. this.clearIgnoreLogicDelete();
  211. }
  212. @Override
  213. public boolean update(DataInterfaceEntity entity, String id) throws DataException {
  214. entity.setId(id);
  215. entity.setLastModifyUserId(UserProvider.getUser().getUserId());
  216. entity.setLastModifyTime(DateUtil.getNowDate());
  217. return this.updateById(entity);
  218. }
  219. @Override
  220. public void delete(DataInterfaceEntity entity) {
  221. LambdaQueryWrapper<DataInterfaceVariateEntity> wrapper = new LambdaQueryWrapper<>();
  222. wrapper.eq(DataInterfaceVariateEntity::getInterfaceId, entity.getId());
  223. dataInterfaceVariateService.remove(wrapper);
  224. this.removeById(entity.getId());
  225. }
  226. @Override
  227. public boolean isExistByFullNameOrEnCode(String id, String fullName, String enCode) {
  228. QueryWrapper<DataInterfaceEntity> queryWrapper = new QueryWrapper<>();
  229. if (StringUtil.isNotEmpty(fullName)) {
  230. queryWrapper.lambda().eq(DataInterfaceEntity::getFullName, fullName);
  231. }
  232. if (StringUtil.isNotEmpty(enCode)) {
  233. queryWrapper.lambda().eq(DataInterfaceEntity::getEnCode, enCode);
  234. }
  235. if (StringUtil.isNotEmpty(id)) {
  236. queryWrapper.lambda().ne(DataInterfaceEntity::getId, id);
  237. }
  238. return this.count(queryWrapper) > 0;
  239. }
  240. @Override
  241. public ActionResult infoToIdPageList(String id, DataInterfacePage page) {
  242. DataInterfaceEntity entity = this.getInfo(id);
  243. if (entity == null) {
  244. return ActionResult.page(new ArrayList<>(), JsonUtil.getJsonToBean(new Pagination(), PaginationVO.class));
  245. }
  246. if (entity.getHasPage() == 1) {
  247. Map<String, String> map = null;
  248. if (page.getParamList() != null) {
  249. map = new HashMap<>();
  250. List<DataInterfaceModel> jsonToList = JsonUtil.getJsonToList(page.getParamList(), DataInterfaceModel.class);
  251. this.paramSourceTypeReplaceValue(jsonToList, map);
  252. // for (DataInterfaceModel dataInterfaceModel : jsonToList) {
  253. // String defaultValue = dataInterfaceModel.getDefaultValue();
  254. // map.put(dataInterfaceModel.getField(), defaultValue);
  255. // }
  256. }
  257. Pagination pagination = new Pagination();
  258. pagination.setPageSize(page.getPageSize());
  259. pagination.setCurrentPage(page.getCurrentPage());
  260. pagination.setKeyword(page.getKeyword());
  261. return infoToId(id, null, map, null, null, null, pagination, null);
  262. } else {
  263. String dataProcessing = null;
  264. if (StringUtil.isNotEmpty(entity.getDataJsJson())) {
  265. dataProcessing = entity.getDataJsJson();
  266. }
  267. List<Map<String, Object>> dataList = new ArrayList<>();
  268. int total = 0;
  269. Map<String, String> map = null;
  270. if (page.getParamList() != null) {
  271. map = new HashMap<>();
  272. List<DataInterfaceModel> jsonToList = JsonUtil.getJsonToList(page.getParamList(), DataInterfaceModel.class);
  273. this.paramSourceTypeReplaceValue(jsonToList, map);
  274. // for (DataInterfaceModel dataInterfaceModel : jsonToList) {
  275. // String defaultValue = dataInterfaceModel.getDefaultValue();
  276. // map.put(dataInterfaceModel.getField(), defaultValue);
  277. // }
  278. }
  279. ActionResult result = infoToId(id, null, map);
  280. if (result.getData() != null) {
  281. if (result.getData() instanceof List) {
  282. dataList = (List<Map<String, Object>>) result.getData();
  283. }
  284. }
  285. // if (StringUtil.isNotEmpty(page.getKeyword()) && StringUtil.isNotEmpty(page.getRelationField())) {
  286. // dataList = dataList.stream().filter(t -> String.valueOf(t.get(page.getRelationField())).contains(page.getKeyword())).collect(Collectors.toList());
  287. // }
  288. PaginationVO pagination = new PaginationVO();
  289. page.setTotal(dataList.size());
  290. if (StringUtil.isNotEmpty(page.getKeyword()) && StringUtil.isNotEmpty(page.getColumnOptions())) {
  291. String[] colOptions = page.getColumnOptions().split(",");
  292. dataList = dataList.stream().filter(t -> {
  293. boolean isFit = false;
  294. for (String c : colOptions) {
  295. if (String.valueOf(t.get(c)).contains(page.getKeyword())) {
  296. isFit = true;
  297. break;
  298. }
  299. }
  300. return isFit;
  301. }).collect(Collectors.toList());
  302. }
  303. page.setTotal(dataList.size());
  304. dataList = PageUtil.getListPage((int) page.getCurrentPage(), (int) page.getPageSize(), dataList);
  305. pagination = JsonUtil.getJsonToBean(page, PaginationVO.class);
  306. return ActionResult.page(dataList, pagination, dataProcessing);
  307. }
  308. }
  309. @Override
  310. public List<Map<String, Object>> infoToInfo(String id, DataInterfacePage page) {
  311. List<Map<String, Object>> list = new ArrayList<>();
  312. Map<String, String> map = null;
  313. DataInterfaceEntity entity = this.getInfo(id);
  314. if (entity == null) {
  315. return new ArrayList<>();
  316. }
  317. try {
  318. if (entity.getHasPage() == 1) {
  319. if (page.getParamList() != null) {
  320. map = new HashMap<>();
  321. List<DataInterfaceModel> jsonToList = JsonUtil.getJsonToList(page.getParamList(), DataInterfaceModel.class);
  322. this.paramSourceTypeReplaceValue(jsonToList, map);
  323. // for (DataInterfaceModel dataInterfaceModel : jsonToList) {
  324. // String defaultValue = dataInterfaceModel.getDefaultValue();
  325. // map.put(dataInterfaceModel.getField(), defaultValue);
  326. // }
  327. }
  328. Map<String, Object> showMap = new HashMap<>();
  329. if (page.getIds() instanceof List) {
  330. List<Object> ids = (List<Object>) page.getIds();
  331. Map<String, String> finalMap = map;
  332. ids.forEach(t -> {
  333. showMap.put(page.getPropsValue(), t);
  334. ActionResult result = infoToId(id, null, finalMap, null, null, null, null, showMap);
  335. if (result.getData() instanceof Map) {
  336. Map<String, Object> objectMap = (Map<String, Object>) result.getData();
  337. if (!objectMap.isEmpty()) {
  338. List<Map> mapList = JsonUtil.getJsonToList(objectMap.get("list"), Map.class);
  339. if (mapList != null && !mapList.isEmpty()) {
  340. list.add(mapList.get(0));
  341. } else {
  342. list.add(objectMap);
  343. }
  344. }
  345. } else if (result.getData() instanceof List) {
  346. List<Map> list1 = (List<Map>) result.getData();
  347. if (!list1.isEmpty()) {
  348. list.add(list1.get(0));
  349. }
  350. } else {
  351. }
  352. });
  353. }
  354. } else {
  355. if (page.getIds() != null) {
  356. Map<String, Object> dataMap = new HashMap<>();
  357. if (page.getParamList() != null) {
  358. map = new HashMap<>();
  359. List<DataInterfaceModel> jsonToList = JsonUtil.getJsonToList(page.getParamList(), DataInterfaceModel.class);
  360. this.paramSourceTypeReplaceValue(jsonToList, map);
  361. // for (DataInterfaceModel dataInterfaceModel : jsonToList) {
  362. // map.put(dataInterfaceModel.getField(), dataInterfaceModel.getDefaultValue());
  363. // }
  364. }
  365. ActionResult result = infoToId(id, null, map);
  366. List<Map<String, Object>> dataList = new ArrayList<>();
  367. if (result.getData() instanceof List) {
  368. dataList = (List<Map<String, Object>>) result.getData();
  369. List<Object> ids = (List<Object>) page.getIds();
  370. List<Map<String, Object>> finalDataList = dataList;
  371. ids.forEach(t -> {
  372. list.add(finalDataList.stream().filter(data -> t.equals(data.get(page.getPropsValue()))).findFirst().orElse(new HashMap<>()));
  373. });
  374. }
  375. }
  376. }
  377. } catch (Exception e) {
  378. e.printStackTrace();
  379. return list;
  380. }
  381. return list;
  382. }
  383. @Override
  384. public ActionResult infoToId(String id, String tenantId, Map<String, String> map) {
  385. return infoToId(id, tenantId, map, null, null, null, null, null);
  386. }
  387. @Override
  388. public ActionResult infoToId(String id, String tenantId, Map<String, String> map, String token, String appId, String invokType, Pagination pagination, Map<String, Object> showMap) {
  389. DataInterfaceEntity entity = this.getInfo(id);
  390. if (entity == null) {
  391. return ActionResult.success(new ArrayList<>());
  392. }
  393. // 开始调用的时间
  394. LocalDateTime dateTime = LocalDateTime.now();
  395. //调用时间
  396. int invokWasteTime = 0;
  397. // 有设置默认值的直接赋值
  398. replaceDefaultVale(entity.getParameterJson(), map);
  399. // 验证参数必填或类型
  400. String checkRequestParams = checkRequestParams(entity.getParameterJson(), map, null);
  401. if (StringUtil.isNotEmpty(checkRequestParams)) {
  402. return ActionResult.fail(checkRequestParams);
  403. }
  404. Object callJs = null;
  405. try {
  406. if (pagination == null) {
  407. pagination = new Pagination();
  408. }
  409. // 数据配置
  410. String dataConfigJson = entity.getDataConfigJson();
  411. DataConfigJsonModel configJsonModel = JsonUtil.getJsonToBean(dataConfigJson, DataConfigJsonModel.class);
  412. // 如果是静态数据
  413. if (entity.getType() == 2) {
  414. String staticData = configJsonModel.getStaticData();
  415. Object object = callStaticData(staticData);
  416. handlePostVariate(entity, object);
  417. return ActionResult.success(object);
  418. } else if (entity.getType() == 3) {
  419. // HTTP调用或HTTPS调用
  420. JSONObject jsonObject = new JSONObject();
  421. if (showMap == null) {
  422. if (entity.getHasPage() == 0) {
  423. pagination = null;
  424. }
  425. //HTTP调用或HTTPS调用
  426. jsonObject = callHTTP(map, token, pagination, null, configJsonModel.getApiData());
  427. } else {
  428. String echoJson = entity.getDataEchoJson();
  429. DataConfigJsonModel echoJsonModel = JsonUtil.getJsonToBean(echoJson, DataConfigJsonModel.class);
  430. jsonObject = callHTTP(map, token, null, showMap, echoJsonModel.getApiData());
  431. }
  432. if (Objects.nonNull(jsonObject) && "1".equals(jsonObject.get("errorCode"))) {
  433. return ActionResult.fail(MsgCode.SYS121.get());
  434. }
  435. // 判断返回参数长度和key是否跟内置的一致
  436. if (jsonObject == null) {
  437. return ActionResult.fail(MsgCode.SYS122.get());
  438. }
  439. handlePostVariate(entity, jsonObject);
  440. Object js = JScriptUtil.callJs(entity.getDataExceptionJson(), jsonObject.get("data") == null ? new ArrayList<>() : jsonObject.get("data"));
  441. if ((js instanceof Boolean && !BooleanUtil.toBoolean(String.valueOf(js)))) {
  442. // 继续执行接口
  443. if (showMap == null) {
  444. // 处理变量
  445. handlerVariate(configJsonModel.getApiData());
  446. jsonObject = callHTTP(map, token, pagination, null, configJsonModel.getApiData());
  447. } else {
  448. String echoJson = entity.getDataEchoJson();
  449. DataConfigJsonModel echoJsonModel = JsonUtil.getJsonToBean(echoJson, DataConfigJsonModel.class);
  450. // 处理变量
  451. handlerVariate(echoJsonModel.getApiData());
  452. jsonObject = callHTTP(map, token, null, showMap, echoJsonModel.getApiData());
  453. }
  454. }
  455. if (isInternal(jsonObject)) {
  456. callJs = JScriptUtil.callJs(entity.getDataJsJson(), jsonObject.get("data") == null ? new ArrayList<>() : jsonObject.get("data"));
  457. } else {
  458. callJs = JScriptUtil.callJs(entity.getDataJsJson(), jsonObject);
  459. }
  460. } else if (entity.getType() == 1) {
  461. UserInfo oldUser = null;
  462. if (token != null) {
  463. oldUser = UserProvider.getUser();
  464. UserInfo userInfo = UserProvider.getUser(token);
  465. UserProvider.setLocalLoginUser(userInfo);
  466. }
  467. try {
  468. if (showMap == null) {
  469. SqlDateModel sqlData = configJsonModel.getSqlData();
  470. List<Map<String, Object>> sqlMapList = executeSql(entity, 0, map, pagination, null, sqlData);
  471. handlePostVariate(entity, sqlMapList);
  472. if (entity.getHasPage() == 1) {
  473. DataConfigJsonModel pageJsonModel = JsonUtil.getJsonToBean(entity.getDataConfigJson(), DataConfigJsonModel.class);
  474. List<Map<String, Object>> maps = executeSql(entity, 1, map, pagination, null, pageJsonModel.getSqlData());
  475. if (maps.get(0) != null) {
  476. pagination.setTotal(Long.parseLong(String.valueOf(maps.get(0).values().iterator().next())));
  477. }
  478. Map<String, Object> obj = new HashMap<>();
  479. obj.put("list", sqlMapList);
  480. obj.put("pagination", JsonUtil.getJsonToBean(pagination, PaginationVO.class));
  481. callJs = JScriptUtil.callJs(entity.getDataJsJson(), obj);
  482. return ActionResult.success(callJs);
  483. } else {
  484. callJs = JScriptUtil.callJs(entity.getDataJsJson(), sqlMapList == null ? new ArrayList<>() : sqlMapList);
  485. }
  486. } else {
  487. DataConfigJsonModel echoJsonModel = JsonUtil.getJsonToBean(entity.getDataEchoJson(), DataConfigJsonModel.class);
  488. List<Map<String, Object>> sqlMapList = executeSql(entity, 2, map, pagination, showMap, echoJsonModel.getSqlData());
  489. if (entity.getHasPage() == 1) {
  490. DataConfigJsonModel pageJsonModel = JsonUtil.getJsonToBean(entity.getDataConfigJson(), DataConfigJsonModel.class);
  491. List<Map<String, Object>> maps = executeSql(entity, 1, map, pagination, null, pageJsonModel.getSqlData());
  492. if (maps.get(0) != null) {
  493. pagination.setTotal(Long.parseLong(String.valueOf(maps.get(0).values().iterator().next())));
  494. }
  495. Map<String, Object> obj = new HashMap<>();
  496. obj.put("list", sqlMapList);
  497. obj.put("pagination", JsonUtil.getJsonToBean(pagination, PaginationVO.class));
  498. callJs = JScriptUtil.callJs(entity.getDataJsJson(), obj);
  499. return ActionResult.success(callJs);
  500. } else {
  501. callJs = JScriptUtil.callJs(entity.getDataJsJson(), CollectionUtil.isEmpty(sqlMapList) ? new ArrayList<>() : sqlMapList.get(0));
  502. }
  503. }
  504. } finally {
  505. if (oldUser != null) {
  506. UserProvider.setLocalLoginUser(oldUser);
  507. }
  508. }
  509. }
  510. if (callJs instanceof Exception) {
  511. return ActionResult.success(MsgCode.SYS123.get(((Exception) callJs).getMessage()));
  512. }
  513. return ActionResult.success(callJs);
  514. } catch (Exception e) {
  515. log.error("错误提示:" + e.getMessage());
  516. // 本地调试时打印出问题
  517. e.printStackTrace();
  518. return ActionResult.fail(MsgCode.SYS122.get());
  519. } finally {
  520. // 调用时间
  521. invokWasteTime = invokTime(dateTime);
  522. // 添加调用日志
  523. dataInterfaceLogService.create(id, invokWasteTime, appId, invokType);
  524. }
  525. }
  526. /**
  527. * 预览时赋值变量
  528. *
  529. * @param entity
  530. * @param object
  531. */
  532. private void handlePostVariate(DataInterfaceEntity entity, Object object) {
  533. // 如果是鉴权的话,需要赋值value
  534. if (entity.getIsPostPosition() == 1) {
  535. List<DataInterfaceVariateEntity> list = dataInterfaceVariateService.getList(entity.getId(), null);
  536. list.forEach(t -> {
  537. try {
  538. Object o;
  539. if (object instanceof JSONObject && isInternal((JSONObject) object)) {
  540. o = JScriptUtil.callJs(t.getExpression(), ((JSONObject) object).get("data"));
  541. } else {
  542. o = JScriptUtil.callJs(t.getExpression(), object);
  543. }
  544. if (o != null) {
  545. t.setValue(o.toString());
  546. dataInterfaceVariateService.update(t);
  547. }
  548. } catch (ScriptException e) {
  549. log.error(e.getMessage());
  550. }
  551. });
  552. }
  553. }
  554. @Override
  555. public List<DataInterfaceEntity> getList(List<String> ids) {
  556. if (CollectionUtil.isEmpty(ids)) {
  557. return new ArrayList<>();
  558. }
  559. QueryWrapper<DataInterfaceEntity> queryWrapper = new QueryWrapper<>();
  560. queryWrapper.lambda().in(DataInterfaceEntity::getId, ids);
  561. return this.list(queryWrapper);
  562. }
  563. /**
  564. * 处理静态数据
  565. */
  566. private Object callStaticData(String staticData) {
  567. Object obj;
  568. try {
  569. Object parse = JSON.parse(staticData);
  570. if (parse instanceof JSONArray) {
  571. obj = JsonUtil.getJsonToListMap(staticData);
  572. } else {
  573. obj = JsonUtil.stringToMap(staticData);
  574. }
  575. } catch (Exception e) {
  576. obj = staticData;
  577. }
  578. if (ObjectUtils.isEmpty(obj)) {
  579. return new ArrayList<>();
  580. }
  581. return obj;
  582. }
  583. /**
  584. * 有设置默认值的直接赋值
  585. *
  586. * @param parameterJson
  587. * @param map
  588. */
  589. private void replaceDefaultVale(String parameterJson, Map<String, String> map) {
  590. List<DataInterfaceModel> dataInterfaceModelList = JsonUtil.getJsonToList(parameterJson, DataInterfaceModel.class);
  591. if (ObjectUtils.isNotEmpty(dataInterfaceModelList)) {
  592. if (map == null) {
  593. map = new HashMap<>(16);
  594. }
  595. for (DataInterfaceModel dataInterfaceModel : dataInterfaceModelList) {
  596. String field = dataInterfaceModel.getField();
  597. String defaultValue = dataInterfaceModel.getDefaultValue();
  598. String dataType = dataInterfaceModel.getDataType();
  599. if (!map.containsKey(field) || StringUtil.isEmpty(map.get(field))) {
  600. map.put(field, defaultValue == null ? "" : defaultValue);
  601. }
  602. // if (dataType.equals("int") && StringUtil.isEmpty(map.get(field))) {
  603. // map.put(field, "0");
  604. // }
  605. }
  606. }
  607. }
  608. /**
  609. * 判断是不是内部接口
  610. *
  611. * @param jsonObject
  612. * @return
  613. */
  614. private boolean isInternal(JSONObject jsonObject) {
  615. if (jsonObject != null) {
  616. if (jsonObject.size() == 3 && jsonObject.get("code") != null && jsonObject.get("msg") != null && jsonObject.get("data") != null) {
  617. return true;
  618. }
  619. }
  620. return false;
  621. }
  622. /**
  623. * 检查参数是够必填或类型是否正确
  624. *
  625. * @param parameterJson
  626. * @param map
  627. * @param sql 预留参数
  628. */
  629. private String checkRequestParams(String parameterJson, Map<String, String> map, String sql) {
  630. if (map == null || StringUtil.isEmpty(parameterJson)) {
  631. return "";
  632. }
  633. StringBuilder message = new StringBuilder();
  634. List<DataInterfaceModel> dataInterfaceModelList = JsonUtil.getJsonToList(parameterJson, DataInterfaceModel.class);
  635. dataInterfaceModelList.stream().anyMatch(model -> {
  636. // 验证是否必填
  637. if (model.getRequired() == 1) {
  638. String value = map.get(model.getField());
  639. if (StringUtil.isEmpty(value)) {
  640. message.append(model.getField()).append("不能为空");
  641. }
  642. }
  643. if (message.length() == 0) {
  644. // 验证类型
  645. if (model.getDataType() != null) {
  646. String value = map.get(model.getField());
  647. // 判断是整形
  648. if (StringUtil.isNotEmpty(value) && "int".equals(model.getDataType())) {
  649. try {
  650. Integer.parseInt(value);
  651. } catch (Exception e) {
  652. message.append(model.getField()).append("类型必须为整型");
  653. }
  654. } else if (StringUtil.isNotEmpty(value) && "datetime".equals(model.getDataType())) {
  655. try {
  656. SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  657. map.put(model.getField(), DateUtil.dateFormat(formatter.parse(value)));
  658. } catch (Exception e) {
  659. try {
  660. map.put(model.getField(), DateUtil.dateFormat(new Date(Long.valueOf(value))));
  661. } catch (Exception ex) {
  662. message.append(model.getField() + "类型必须为日期时间型");
  663. }
  664. }
  665. } else if (StringUtil.isNotEmpty(value) && "decimal".equals(model.getDataType())) {
  666. try {
  667. Double.valueOf(value);
  668. } catch (Exception e) {
  669. message.append(model.getField()).append("类型必须为浮点型");
  670. }
  671. }
  672. }
  673. }
  674. return message.length() > 0;
  675. });
  676. return message.toString();
  677. }
  678. @Override
  679. public ActionResult infoToIdNew(String id, String tenantId, DataInterfaceActionModel model) {
  680. //鉴权验证
  681. // 获取token
  682. String authorSignature = ServletUtil.getRequest().getHeader(Constants.AUTHORIZATION);
  683. String[] authorSignatureArr = authorSignature.split(":");
  684. if (authorSignatureArr.length != 3) {
  685. return ActionResult.fail(ActionResultCode.ValidateError.getMessage());
  686. }
  687. String appId = authorSignatureArr[0];
  688. String author = authorSignatureArr[2];
  689. Map<String, String> map = model.getMap();
  690. String interfaceUserToken = null;
  691. InterfaceOauthEntity infoByAppId = interfaceOauthService.getInfoByAppId(appId);
  692. //未提供app相关,接口认证失效,接口不在授权列表时无权访问
  693. if (infoByAppId == null || infoByAppId.getEnabledMark() == 0 || !infoByAppId.getDataInterfaceIds().contains(id)) {
  694. return ActionResult.fail(MsgCode.FA021.get());
  695. }
  696. if (infoByAppId.getVerifySignature() == 1) {//验证开启
  697. try {
  698. //验证请求有效期1分钟内
  699. String ymdateStr = ServletUtil.getRequest().getHeader(InterfaceUtil.YMDATE);
  700. Date ymdate = new Date(Long.parseLong(ymdateStr));
  701. Date time = DateUtil.dateAddMinutes(ymdate, 1);
  702. if (DateUtil.getNowDate().after(time)) {
  703. return ActionResult.fail(MsgCode.SYS124.get());
  704. }
  705. //验证签名有效性
  706. boolean flag = InterfaceUtil.verifySignature(infoByAppId.getAppSecret(), author);
  707. if (!flag) {
  708. return ActionResult.fail(ActionResultCode.ValidateError.getMessage());
  709. }
  710. } catch (Exception e) {
  711. e.printStackTrace();
  712. return ActionResult.fail(ActionResultCode.ValidateError.getMessage());
  713. }
  714. } else {//验证未开启,直接使用秘钥进行验证
  715. if (!infoByAppId.getAppSecret().equals(author)) {
  716. return ActionResult.fail(MsgCode.SYS125.get());
  717. }
  718. }
  719. //验证使用期限
  720. Date usefulLife = infoByAppId.getUsefulLife();
  721. if (infoByAppId.getUsefulLife() != null && usefulLife.before(DateUtil.getNowDate())) {//空值无限期
  722. return ActionResult.fail(MsgCode.SYS126.get());
  723. }
  724. try {
  725. //用户秘钥获取token
  726. interfaceUserToken = dataInterfaceUserService.getInterfaceUserToken(model.getTenantId(), infoByAppId.getId(), ServletUtil.getRequest().getHeader(InterfaceUtil.USERKEY));
  727. } catch (Exception e) {
  728. return ActionResult.fail(e.getMessage());
  729. }
  730. //黑白名单验证
  731. String ipwhiteList = StringUtil.isNotEmpty(infoByAppId.getWhiteList()) ? infoByAppId.getWhiteList() : "";//ip白名单
  732. String ipwhiteBlackList = StringUtil.isNotEmpty(infoByAppId.getBlackList()) ? infoByAppId.getBlackList() : "";//ip黑名单
  733. String ipAddr = IpUtil.getIpAddr();
  734. if (StringUtil.isNotEmpty(ipwhiteList) && !ipwhiteList.contains(ipAddr)) {//不属于白名单
  735. return ActionResult.fail(MsgCode.LOG010.get());
  736. }
  737. // if (StringUtil.isNotEmpty(ipwhiteBlackList) && ipwhiteBlackList.contains(ipAddr)) {//属于黑名单
  738. // return ActionResult.fail(ActionResultCode.ValidateError.getMessage());
  739. // }
  740. //以下调用接口
  741. return infoToId(id, null, map, interfaceUserToken, infoByAppId.getAppId(), model.getInvokType(), null, null);
  742. }
  743. @Override
  744. public DataInterfaceActionModel checkParams(Map<String, String> map) {
  745. String ymDate = ServletUtil.getRequest().getHeader(InterfaceUtil.YMDATE);
  746. String authorSignature = ServletUtil.getRequest().getHeader(Constants.AUTHORIZATION);
  747. if (StringUtils.isEmpty(ymDate)) {
  748. throw new RuntimeException("header参数:YmDate未传值");
  749. }
  750. if (StringUtils.isEmpty(authorSignature)) {
  751. throw new RuntimeException("header参数:" + Constants.AUTHORIZATION + "未传值");
  752. }
  753. DataInterfaceActionModel entity = new DataInterfaceActionModel();
  754. //判断是否多租户,取参数tenantId
  755. if (InterfaceUtil.checkParam(map, "tenantId")) {
  756. entity.setTenantId(map.get("tenantId"));
  757. }
  758. String tenantId = SaHolder.getRequest().getParam("tenantId");
  759. if (StringUtil.isNotEmpty(tenantId)) {
  760. entity.setTenantId(tenantId);
  761. }
  762. entity.setMap(map);
  763. return entity;
  764. }
  765. /**
  766. * 执行SQL
  767. *
  768. * @param entity
  769. * @param sqlType
  770. * @param map
  771. * @return
  772. * @throws DataException
  773. */
  774. private List<Map<String, Object>> executeSql(DataInterfaceEntity entity, int sqlType, Map<String, String> map,
  775. Pagination pagination, Map<String, Object> showMap,
  776. SqlDateModel sqlDateModel) throws Exception {
  777. Map<String, Object> mapData = new HashMap<>();
  778. if (map != null) {
  779. for (String key : map.keySet()) {
  780. mapData.put(key, map.get(key));
  781. }
  782. }
  783. DataSourceUtil linkEntity = dblinkService.getInfo(sqlDateModel.getDbLinkId());
  784. String sql = sqlDateModel.getSql();
  785. if (entity.getHasPage() == 1) {
  786. if (sqlType == 1) {
  787. DataConfigJsonModel dataConfigJsonModel = JsonUtil.getJsonToBean(entity.getDataCountJson(), DataConfigJsonModel.class);
  788. if (dataConfigJsonModel != null) {
  789. SqlDateModel countSqlDateModel = JsonUtil.getJsonToBean(dataConfigJsonModel.getSqlData(), SqlDateModel.class);
  790. sql = countSqlDateModel.getSql();
  791. }
  792. } else if (sqlType == 2) {
  793. DataConfigJsonModel dataConfigJsonModel = JsonUtil.getJsonToBean(entity.getDataEchoJson(), DataConfigJsonModel.class);
  794. if (dataConfigJsonModel != null) {
  795. SqlDateModel countSqlDateModel = JsonUtil.getJsonToBean(dataConfigJsonModel.getSqlData(), SqlDateModel.class);
  796. sql = countSqlDateModel.getSql();
  797. }
  798. }
  799. }
  800. UserInfo userInfo = UserProvider.getUser();
  801. if (linkEntity == null) {
  802. linkEntity = dataSourceUtils;
  803. }
  804. // 系统内置参数替换
  805. Map<Double, DataInterfaceMarkModel> systemParameter = systemParameter(sql, userInfo, pagination, showMap);
  806. // 自定义参数替换
  807. sql = customizationParameter(entity.getParameterJson(), sql, mapData, systemParameter);
  808. // 处理SQL
  809. List<Object> values = new ArrayList<>(systemParameter.size());
  810. // 参数替换为占位符
  811. sql = getHandleArraysSql(sql, values, systemParameter);
  812. if (showMap != null) {
  813. sql = sql.replace(DataInterfaceVarConst.SHOWKEY, showMap.keySet().iterator().next());
  814. }
  815. //封装sql---视图查询 -重新封装sql
  816. if (StringUtil.isNotEmpty(sql) && Objects.nonNull(map)
  817. && StringUtil.isNotEmpty(map.get("searchSqlStr")) && Objects.equals(entity.getAction(), 3)) {
  818. if (sql.trim().endsWith(";")) {
  819. sql = sql.trim();
  820. sql = sql.substring(0, sql.length() - 1);
  821. }
  822. sql = "select * from (" + sql + ") t where " + map.get("searchSqlStr");
  823. }
  824. //封装sql结束---
  825. log.info("当前执行SQL:{}", sql);
  826. if (entity.getHasPage() == 1 && (sql.contains(";") && sql.trim().indexOf(";") != sql.trim().length() - 1)) {
  827. return null;
  828. }
  829. if (entity.getAction() != null && entity.getAction() != 3) {
  830. JdbcUtil.creUpDe(new PrepSqlDTO(sql, values).withConn(linkEntity, null));
  831. return null;
  832. }
  833. String objectToString = JsonUtil.getObjectToStringAsDate(JdbcUtil.queryList(new PrepSqlDTO(sql, values).withConn(linkEntity, null)).setIsAlias(true).get());
  834. return JsonUtil.getJsonToListMap(objectToString);
  835. }
  836. /**
  837. * 自定义参数替换
  838. *
  839. * @param parameterJson 参数配置
  840. * @param sql sql
  841. * @param map 参数
  842. * @param systemParameter 参数集合
  843. */
  844. @Override
  845. public String customizationParameter(String parameterJson, String sql, Map<String, Object> map,
  846. Map<Double, DataInterfaceMarkModel> systemParameter) {
  847. List<DataInterfaceModel> dataInterfaceModelList = StringUtil.isNotEmpty(parameterJson) ? JsonUtil.getJsonToList(parameterJson, DataInterfaceModel.class) : new ArrayList<>();
  848. if (StringUtil.isNotEmpty(sql) && Objects.nonNull(map)) {
  849. Map<String, String> placeholderMap = new HashMap<>();
  850. for (String key : map.keySet()) {
  851. // 验证参数key对比
  852. Object tmpValue = map.get(key);
  853. if (tmpValue != null) {
  854. //参数前方 上个参数后方的语句中是否有 in
  855. String sqlarr1 = sql.split("\\{" + key + "}")[0];
  856. String[] sqlarr2 = sqlarr1.split("}");
  857. String sql1 = sqlarr2.length > 1 ? sqlarr2[sqlarr2.length - 1] : sqlarr2[0];
  858. boolean isInSql = sql1.toLowerCase().contains(" in ");
  859. List<Object> valueList = new ArrayList<>();
  860. if (isInSql) {
  861. valueList = Arrays.asList(String.valueOf(tmpValue).split(","));
  862. } else {
  863. valueList.add(tmpValue);
  864. }
  865. String placeholder = "?";
  866. for (int i = 1; i < valueList.size(); i++) {
  867. placeholder += ",?";
  868. }
  869. String finalSql = sql;
  870. valueList.forEach(t -> {
  871. Object b = t;
  872. for (DataInterfaceModel model : dataInterfaceModelList) {
  873. if (model.getField().equals(key) && model.getDataType() != null) {
  874. // 判断是整形
  875. if ("int".equals(model.getDataType())) {
  876. b = ObjectUtil.isNull(t) ? null : Integer.parseInt(String.valueOf(t));
  877. } else if ("decimal".equals(model.getDataType())) {
  878. b = ObjectUtil.isNull(t) ? null : Double.valueOf(String.valueOf(t));
  879. } else if ("datetime".equals(model.getDataType()) && ObjectUtil.isNull(t)) {
  880. b = null;
  881. }
  882. }
  883. }
  884. DataInterfaceParamUtil.getParamModel(systemParameter, finalSql, "{" + key + "}", b);
  885. });
  886. placeholderMap.put(key, placeholder);
  887. } else {
  888. DataInterfaceParamUtil.getParamModel(systemParameter, sql, "{" + key + "}", null);
  889. placeholderMap.put(key, "?");
  890. }
  891. }
  892. for (String key : placeholderMap.keySet()) {
  893. sql = sql.replaceAll("\\{" + key + "}", placeholderMap.get(key));
  894. }
  895. }
  896. return sql;
  897. }
  898. /**
  899. * 参数替换为占位符
  900. */
  901. public String getHandleArraysSql(String sql, List<Object> values, Map<Double, DataInterfaceMarkModel> systemParameter) {
  902. if (StringUtil.isNotEmpty(sql)) {
  903. for (Double aDouble : systemParameter.keySet()) {
  904. Object value = systemParameter.get(aDouble).getValue();
  905. values.add(value);
  906. }
  907. for (Double aDouble : systemParameter.keySet()) {
  908. DataInterfaceMarkModel dataInterfaceMarkModel = systemParameter.get(aDouble);
  909. List<String> collect = MARKERS.stream().filter(t -> t.equals(dataInterfaceMarkModel.getMarkName())).collect(Collectors.toList());
  910. if (collect.isEmpty()) continue;
  911. if (dataInterfaceMarkModel.getValue() instanceof List) {
  912. List list = (List) dataInterfaceMarkModel.getValue();
  913. StringBuilder placeholder = new StringBuilder("?");
  914. int index = 0;
  915. boolean addOrSet = false;
  916. for (Object obj : list) {
  917. if (!addOrSet) {
  918. // 得到下标
  919. int i = values.indexOf(dataInterfaceMarkModel.getValue());
  920. values.set(i, obj);
  921. addOrSet = true;
  922. index = i++;
  923. } else {
  924. placeholder.append(",?");
  925. values.add(index, obj);
  926. }
  927. }
  928. sql = sql.replaceAll(collect.get(0), placeholder.toString());
  929. }
  930. }
  931. sql = sql.replaceAll(DataInterfaceVarConst.KEYWORD, "?");
  932. sql = sql.replaceAll(DataInterfaceVarConst.USER, "?");
  933. sql = sql.replaceAll(DataInterfaceVarConst.ORG, "?");
  934. sql = sql.replaceAll(DataInterfaceVarConst.POSITIONID, "?");
  935. sql = sql.replaceAll(DataInterfaceVarConst.OFFSETSIZE, "?");
  936. sql = sql.replaceAll(DataInterfaceVarConst.PAGESIZE, "?");
  937. // sql = sql.replaceAll(DataInterfaceVarEnum.SHOWKEY, "?");
  938. sql = sql.replaceAll(DataInterfaceVarConst.SHOWVALUE, "?");
  939. sql = sql.replaceAll(DataInterfaceVarConst.ID, "?");
  940. sql = sql.replaceAll(DataInterfaceVarConst.ID_LOT, "?");
  941. sql = sql.replaceAll(DataInterfaceVarConst.FORM_ID, "?");
  942. }
  943. return sql;
  944. }
  945. /**
  946. * HTTP调用
  947. *
  948. * @return get
  949. */
  950. private JSONObject callHTTP(Map<String, String> map,
  951. String token, Pagination pagination, Map<String, Object> showMap,
  952. ApiDateModel apiDateModel) throws UnsupportedEncodingException {
  953. JSONObject get = new JSONObject();
  954. StringBuilder path = new StringBuilder(apiDateModel.getUrl());
  955. // 请求方法
  956. String requestMethod = apiDateModel.getMethod() == 1 ? "GET" : "POST";
  957. // 获取请求头参数
  958. List<HeadModel> header = apiDateModel.getHeader();
  959. // 自定义参数
  960. List<HeadModel> query = apiDateModel.getQuery();
  961. String body = apiDateModel.getBody();
  962. int bodyType = apiDateModel.getBodyType() == 1 ? 0 : apiDateModel.getBodyType();
  963. // Post请求拼接参数
  964. JSONObject jsonObject = null;
  965. List<JSONObject> jsonObjects1 = null;
  966. //判断是否为http或https
  967. if (StringUtil.isNotEmpty(path.toString()) && path.toString().startsWith("/")) {
  968. path.insert(0, configValueUtil.getApiDomain());
  969. if (StringUtil.isEmpty(token)) {
  970. token = UserProvider.getUser().getToken();
  971. }
  972. } else {
  973. token = null;
  974. }
  975. if (path.toString().startsWith("http")) {
  976. String showKey = null;
  977. Object showValue = null;
  978. if (showMap != null) {
  979. if (!showMap.isEmpty()) {
  980. showKey = showMap.keySet().iterator().next();
  981. showValue = showMap.values().iterator().next();
  982. }
  983. }
  984. // 替换url上的回显参数
  985. path = new StringBuilder(path.toString().replace("{" + DataInterfaceVarConst.SHOWKEY.replaceAll("@", "") + "}", showKey != null ? showKey : ""));
  986. path = new StringBuilder(path.toString().replace("{" + DataInterfaceVarConst.SHOWVALUE.replaceAll("@", "") + "}", showValue != null ? URLEncoder.encode(String.valueOf(showValue), "UTF-8") : ""));
  987. //请求参数解析
  988. if (query != null) {
  989. // 判断是否为get,get从url上拼接
  990. path.append(!path.toString().contains("?") ? "?" : "&");
  991. for (HeadModel headModel : query) {
  992. if ("1".equals(headModel.getSource())) {
  993. String value = map == null || StringUtil.isEmpty(headModel.getDefaultValue()) || StringUtil.isEmpty(map.get(headModel.getDefaultValue()))
  994. ? "" : map.get(headModel.getDefaultValue());
  995. path.append(headModel.getField()).append("=").append(URLEncoder.encode(value, "UTF-8")).append("&");
  996. }
  997. if ("2".equals(headModel.getSource())) {
  998. DataInterfaceVariateEntity variateEntity = dataInterfaceVariateService.getInfo(headModel.getDefaultValue());
  999. path.append(headModel.getField()).append("=").append(variateEntity.getValue()).append("&");
  1000. }
  1001. if ("3".equals(headModel.getSource())) {
  1002. path.append(headModel.getField()).append("=").append(URLEncoder.encode(StringUtil.isNotEmpty(headModel.getDefaultValue()) ? headModel.getDefaultValue() : ""
  1003. // .replaceAll("'", "")
  1004. , "UTF-8")).append("&");
  1005. }
  1006. // 分页参数
  1007. if ("4".equals(headModel.getSource())) {
  1008. Map<String, Object> map1 = JsonUtil.entityToMap(pagination);
  1009. Object urlValue = map1.get(headModel.getDefaultValue());
  1010. if (urlValue instanceof String && ObjectUtil.isNotNull(urlValue)) {
  1011. path.append(headModel.getField()).append("=").append(URLEncoder.encode(String.valueOf(urlValue), "UTF-8")).append("&");
  1012. } else {
  1013. path.append(headModel.getField()).append("=").append(urlValue).append("&");
  1014. }
  1015. }
  1016. // 回显参数
  1017. if ("5".equals(headModel.getSource())) {
  1018. if (DataInterfaceVarConst.SHOWKEY.equals(headModel.getDefaultValue())) {
  1019. if (showKey != null) {
  1020. path.append(headModel.getField()).append("=").append(URLEncoder.encode(showKey, "UTF-8")).append("&");
  1021. }
  1022. } else {
  1023. if (showValue != null) {
  1024. path.append(headModel.getField()).append("=").append(URLEncoder.encode(String.valueOf(showValue), "UTF-8")).append("&");
  1025. } else {
  1026. path.append(headModel.getField()).append("&");
  1027. }
  1028. }
  1029. }
  1030. }
  1031. }
  1032. String jsonObjects = "";
  1033. if (bodyType == 2) {
  1034. StringJoiner bodyParam = new StringJoiner("&");
  1035. List<HeadModel> bodyJson = JsonUtil.getJsonToList(body, HeadModel.class);
  1036. for (HeadModel headModel : bodyJson) {
  1037. if ("1".equals(headModel.getSource())) {
  1038. String value = map == null || StringUtil.isEmpty(headModel.getDefaultValue()) || StringUtil.isEmpty(map.get(headModel.getDefaultValue()))
  1039. ? "" : map.get(headModel.getDefaultValue());
  1040. bodyParam.add(headModel.getField() + "=" + URLEncoder.encode(value, "UTF-8"));
  1041. }
  1042. if ("2".equals(headModel.getSource())) {
  1043. DataInterfaceVariateEntity variateEntity = dataInterfaceVariateService.getInfo(headModel.getDefaultValue());
  1044. bodyParam.add(headModel.getField() + "=" + variateEntity.getValue());
  1045. }
  1046. if ("3".equals(headModel.getSource())) {
  1047. bodyParam.add(headModel.getField() + "=" + headModel.getDefaultValue());
  1048. }
  1049. }
  1050. jsonObjects += bodyParam.toString();
  1051. } else if (bodyType == 3 || bodyType == 4) {
  1052. // 优先替换变量
  1053. Pattern compile = Pattern.compile("\\{@\\w+}");
  1054. Matcher matcher = compile.matcher(body);
  1055. while (matcher.find()) {
  1056. // 得到参数
  1057. String group = matcher.group();
  1058. String variate = group.replace("{", "").replace("}", "").replace("@", "");
  1059. DataInterfaceVariateEntity dataInterfaceVariateEntity = dataInterfaceVariateService.getInfoByFullName(variate);
  1060. if (dataInterfaceVariateEntity != null) {
  1061. body = body.replace(group, dataInterfaceVariateEntity.getValue());
  1062. }
  1063. }
  1064. Pattern compile1 = Pattern.compile("\\{\\w+}");
  1065. Matcher matcher1 = compile1.matcher(body);
  1066. while (matcher1.find()) {
  1067. // 得到参数
  1068. String group = matcher1.group();
  1069. String param = group.replace("{", "").replace("}", "");
  1070. String value = map != null ? map.get(param) : null;
  1071. if (pagination != null && DataInterfaceVarConst.KEYWORD.equals("@" + param)) {
  1072. value = pagination.getKeyword();
  1073. }
  1074. if (pagination != null && DataInterfaceVarConst.CURRENTPAGE.equals("@" + param)) {
  1075. value = pagination.getCurrentPage() + "";
  1076. }
  1077. if (pagination != null && DataInterfaceVarConst.PAGESIZE.equals("@" + param)) {
  1078. value = pagination.getPageSize() + "";
  1079. }
  1080. body = body.replace(group, value);
  1081. }
  1082. jsonObjects = body;
  1083. }
  1084. jsonObjects = StringUtil.isEmpty(jsonObjects) ? null : jsonObjects;
  1085. if (apiDateModel.getMethod() == 1) {
  1086. jsonObjects = "";
  1087. }
  1088. JSONObject headerJson = new JSONObject();
  1089. // 请求头
  1090. for (HeadModel headModel : header) {
  1091. if ("1".equals(headModel.getSource())) {
  1092. if (map != null && map.containsKey(headModel.getDefaultValue())) {
  1093. String value = map.get(headModel.getDefaultValue());
  1094. headerJson.put(headModel.getField(), value
  1095. // .replaceAll("'", "")
  1096. );
  1097. } else {
  1098. headerJson.put(headModel.getField(), map.get(headModel.getDefaultValue()));
  1099. }
  1100. }
  1101. if ("2".equals(headModel.getSource())) {
  1102. DataInterfaceVariateEntity variateEntity = dataInterfaceVariateService.getInfo(headModel.getDefaultValue());
  1103. headerJson.put(headModel.getField(), variateEntity.getValue());
  1104. }
  1105. if ("3".equals(headModel.getSource())) {
  1106. headerJson.put(headModel.getField(), headModel.getDefaultValue());
  1107. }
  1108. // 分页参数
  1109. if ("4".equals(headModel.getSource())) {
  1110. Map<String, Object> map1 = JsonUtil.entityToMap(pagination);
  1111. Object urlValue = map1.get(headModel.getDefaultValue());
  1112. headerJson.put(headModel.getField(), urlValue);
  1113. }
  1114. // 回显参数
  1115. if ("5".equals(headModel.getSource())) {
  1116. if (DataInterfaceVarConst.SHOWKEY.equals(headModel.getDefaultValue())) {
  1117. headerJson.put(headModel.getField(), showKey);
  1118. } else {
  1119. headerJson.put(headModel.getField(), showValue);
  1120. }
  1121. }
  1122. }
  1123. get = HttpUtil.httpRequest(path.toString(), requestMethod, jsonObjects, token, !headerJson.isEmpty() ? JsonUtil.getObjectToString(headerJson) : null, String.valueOf(bodyType));
  1124. return get;
  1125. } else {
  1126. get.put("errorCode", "1");
  1127. return get;
  1128. }
  1129. }
  1130. /**
  1131. * 处理变量
  1132. *
  1133. * @param apiDateModel
  1134. */
  1135. public void handlerVariate(ApiDateModel apiDateModel) {
  1136. Set<String> variate = new HashSet<>();
  1137. // 获取请求头参数
  1138. List<HeadModel> header = apiDateModel.getHeader();
  1139. header.forEach(headModel -> {
  1140. if ("2".equals(headModel.getSource())) {
  1141. variate.add(headModel.getDefaultValue());
  1142. }
  1143. });
  1144. // 自定义参数
  1145. List<HeadModel> query = apiDateModel.getQuery();
  1146. query.forEach(headModel -> {
  1147. if ("2".equals(headModel.getSource())) {
  1148. variate.add(headModel.getDefaultValue());
  1149. }
  1150. });
  1151. if (ObjectUtil.equal(apiDateModel.getBodyType(), 1) || ObjectUtil.equal(apiDateModel.getBodyType(), 2)) {
  1152. List<HeadModel> bodyJson = JsonUtil.getJsonToList(apiDateModel.getBody(), HeadModel.class);
  1153. if (bodyJson != null) {
  1154. bodyJson.forEach(headModel -> {
  1155. if ("2".equals(headModel.getSource())) {
  1156. variate.add(headModel.getDefaultValue());
  1157. }
  1158. });
  1159. }
  1160. }
  1161. List<DataInterfaceVariateEntity> variateEntities = dataInterfaceVariateService.getListByIds(new ArrayList<>(variate));
  1162. List<String> collect = variateEntities.stream().map(DataInterfaceVariateEntity::getInterfaceId).distinct().collect(Collectors.toList());
  1163. List<DataInterfaceEntity> list = this.getList(collect);
  1164. Map<String, Object> results = new HashMap<>();
  1165. Map<String, String> updates = new HashMap<>();
  1166. list.forEach(t -> {
  1167. try {
  1168. DataConfigJsonModel dataConfigJsonModel = JsonUtil.getJsonToBean(t.getDataConfigJson(), DataConfigJsonModel.class);
  1169. JSONObject jsonObject = callHTTP(null, UserProvider.getToken(), new Pagination(), null, JsonUtil.getJsonToBean(dataConfigJsonModel.getApiData(), ApiDateModel.class));
  1170. if (Objects.nonNull(jsonObject) && "1".equals(jsonObject.get("errorCode"))) {
  1171. log.error("接口暂只支持HTTP和HTTPS方式");
  1172. return;
  1173. }
  1174. // 判断返回参数长度和key是否跟内置的一致
  1175. if (jsonObject == null) {
  1176. log.error("接口请求失败");
  1177. return;
  1178. }
  1179. if (isInternal(jsonObject)) {
  1180. results.put(t.getId(), JScriptUtil.callJs(t.getDataJsJson(), jsonObject.get("data") == null ? new ArrayList<>() : jsonObject.get("data")));
  1181. } else {
  1182. results.put(t.getId(), JScriptUtil.callJs(t.getDataJsJson(), jsonObject));
  1183. }
  1184. } catch (Exception e) {
  1185. log.error(e.getMessage());
  1186. }
  1187. });
  1188. variateEntities.forEach(t -> {
  1189. if (results.containsKey(t.getInterfaceId())) {
  1190. try {
  1191. updates.put(t.getId(), String.valueOf(JScriptUtil.callJs(t.getExpression(), results.get(t.getInterfaceId()))));
  1192. } catch (ScriptException e) {
  1193. throw new RuntimeException(e);
  1194. }
  1195. }
  1196. });
  1197. dataInterfaceVariateService.update(updates, variateEntities);
  1198. }
  1199. /**
  1200. * 处理系统参数
  1201. *
  1202. * @param sql
  1203. * @return
  1204. */
  1205. private Map<Double, DataInterfaceMarkModel> systemParameter(String sql, UserInfo userInfo, Pagination pagination, Map<String, Object> showMap) {
  1206. Map<Double, DataInterfaceMarkModel> paramValue = new TreeMap<>(systemParameterOne(sql, userInfo));
  1207. //关键字
  1208. if (sql.contains(DataInterfaceVarConst.KEYWORD)) {
  1209. DataInterfaceParamUtil.getParamModel(paramValue, sql, DataInterfaceVarConst.KEYWORD, pagination.getKeyword());
  1210. }
  1211. // 当前页数
  1212. if (sql.contains(DataInterfaceVarConst.OFFSETSIZE)) {
  1213. DataInterfaceParamUtil.getParamModel(paramValue, sql, DataInterfaceVarConst.OFFSETSIZE, pagination.getPageSize() * (pagination.getCurrentPage() - 1));
  1214. }
  1215. // 每页行数
  1216. if (sql.contains(DataInterfaceVarConst.PAGESIZE)) {
  1217. DataInterfaceParamUtil.getParamModel(paramValue, sql, DataInterfaceVarConst.PAGESIZE, pagination.getPageSize());
  1218. }
  1219. // 每页行数
  1220. if (sql.contains(DataInterfaceVarConst.SHOWVALUE)) {
  1221. DataInterfaceParamUtil.getParamModel(paramValue, sql, DataInterfaceVarConst.SHOWVALUE, showMap.values().iterator().next());
  1222. }
  1223. return paramValue;
  1224. }
  1225. /**
  1226. * 处理系统参数
  1227. *
  1228. * @param sql
  1229. * @param userInfo
  1230. * @return
  1231. */
  1232. public Map<Double, DataInterfaceMarkModel> systemParameterOne(String sql, UserInfo userInfo) {
  1233. Map<Double, DataInterfaceMarkModel> paramValue = new TreeMap<>();
  1234. if (sql.contains(DataInterfaceVarConst.ID_LOT)) {
  1235. DataInterfaceParamUtil.getParamModel(paramValue, sql, DataInterfaceVarConst.ID_LOT, null);
  1236. }
  1237. // 生成雪花id
  1238. if (sql.contains(DataInterfaceVarConst.ID)) {
  1239. DataInterfaceParamUtil.getParamModel(paramValue, sql, DataInterfaceVarConst.ID, RandomUtil.uuId());
  1240. }
  1241. Map<String, String> systemFieldValue = userApi.getSystemFieldValue(new SystemParamModel(sql));
  1242. //当前用户
  1243. if (hasCurrentUser(sql)) {
  1244. String userId = userInfo.getUserId();
  1245. DataInterfaceParamUtil.getParamModel(paramValue, sql, DataInterfaceVarConst.USER, userId);
  1246. }
  1247. AuthorizeConditionEnum.getResListType().stream().forEach(t -> {
  1248. List<String> dataList = StringUtil.isNotEmpty(t) ?
  1249. JsonUtil.getJsonToList(systemFieldValue.get(t), String.class) : Collections.EMPTY_LIST;
  1250. DataInterfaceParamUtil.getParamModel(paramValue, sql, t, dataList);
  1251. });
  1252. return paramValue;
  1253. }
  1254. /**
  1255. * 是否包含当前用户
  1256. * (当前用户及下属key包含当前用户key,constains判断不准确)
  1257. *
  1258. * @param str
  1259. * @return
  1260. */
  1261. public static boolean hasCurrentUser(String str) {
  1262. int index = 0;
  1263. int count = 0;
  1264. while ((index = str.indexOf(DataInterfaceVarConst.USERANDSUB, index)) != -1) {
  1265. count++;
  1266. index += DataInterfaceVarConst.USERANDSUB.length();
  1267. }
  1268. int index2 = 0;
  1269. int count2 = 0;
  1270. while ((index2 = str.indexOf(DataInterfaceVarConst.USER, index2)) != -1) {
  1271. count2++;
  1272. index2 += DataInterfaceVarConst.USER.length();
  1273. }
  1274. return count != count2;
  1275. }
  1276. /**
  1277. * 计算执行时间
  1278. *
  1279. * @param dateTime
  1280. * @return
  1281. */
  1282. public int invokTime(LocalDateTime dateTime) {
  1283. //调用时间
  1284. return (int) (System.currentTimeMillis() - dateTime.toInstant(ZoneOffset.of("+8")).toEpochMilli());
  1285. }
  1286. /**
  1287. * 按sourceType替换数据接口参数
  1288. *
  1289. * @param listJson
  1290. * @param map
  1291. */
  1292. @Override
  1293. public void paramSourceTypeReplaceValue(List<DataInterfaceModel> listJson, Map<String, String> map) {
  1294. Map<String, String> systemFieldValue = userApi.getSystemFieldValue(new SystemParamModel(JsonUtil.getObjectToString(listJson)));
  1295. for (DataInterfaceModel item : listJson) {
  1296. if (item.getSourceType() != null) {
  1297. switch (item.getSourceType()) {
  1298. case 1://字段
  1299. map.put(item.getField(), item.getDefaultValue());
  1300. break;
  1301. case 2://自定义
  1302. map.put(item.getField(), item.getRelationField());
  1303. break;
  1304. case 3://为空
  1305. map.put(item.getField(), "");
  1306. break;
  1307. case 4://系统参数
  1308. map.put(item.getField(), this.getSystemFieldValue(item, systemFieldValue));
  1309. break;
  1310. default:
  1311. map.put(item.getField(), item.getDefaultValue());
  1312. break;
  1313. }
  1314. } else {
  1315. map.put(item.getField(), item.getDefaultValue());
  1316. }
  1317. }
  1318. }
  1319. /**
  1320. * 获取系统参数值
  1321. *
  1322. * @param templateJsonModel
  1323. * @return
  1324. */
  1325. @Override
  1326. public String getSystemFieldValue(DataInterfaceModel templateJsonModel, Map<String, String> systemFieldValue) {
  1327. String relationField = templateJsonModel.getRelationField();
  1328. String dataValue;
  1329. if (AuthorizeConditionEnum.FORMID.getCondition().equals(relationField)) {
  1330. dataValue = String.valueOf(templateJsonModel.getDefaultValue());
  1331. } else if (AuthorizeConditionEnum.getResListType().contains(relationField)) {
  1332. List<String> strings = StringUtil.isNotEmpty(systemFieldValue.get(relationField)) ?
  1333. JsonUtil.getJsonToList(systemFieldValue.get(relationField), String.class) : Collections.EMPTY_LIST;
  1334. dataValue = CollectionUtil.isEmpty(strings) ? "" : String.join(",", strings);
  1335. } else if (systemFieldValue.containsKey(relationField)) {
  1336. dataValue = systemFieldValue.get(relationField);
  1337. } else {
  1338. dataValue = templateJsonModel.getDefaultValue();
  1339. }
  1340. return dataValue;
  1341. }
  1342. }