package jnpf.base.service.impl; import cn.dev33.satoken.context.SaHolder; import cn.hutool.core.collection.CollectionUtil; import cn.hutool.core.util.BooleanUtil; import cn.hutool.core.util.ObjectUtil; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import jnpf.base.ActionResult; import jnpf.base.ActionResultCode; import jnpf.base.Pagination; import jnpf.base.UserInfo; import jnpf.base.entity.DataInterfaceEntity; import jnpf.base.entity.DataInterfaceVariateEntity; import jnpf.base.entity.InterfaceOauthEntity; import jnpf.base.mapper.DataInterfaceMapper; import jnpf.base.model.datainterface.*; import jnpf.base.service.*; import jnpf.base.util.DataInterfaceParamUtil; import jnpf.base.util.interfaceUtil.InterfaceUtil; import jnpf.base.vo.PaginationVO; import jnpf.config.ConfigValueUtil; import jnpf.constant.DataInterfaceVarConst; import jnpf.constant.MsgCode; import jnpf.database.model.dto.PrepSqlDTO; import jnpf.database.util.DataSourceUtil; import jnpf.database.util.JdbcUtil; import jnpf.exception.DataException; import jnpf.model.SystemParamModel; import jnpf.permission.model.authorize.AuthorizeConditionEnum; import jnpf.permission.service.OrganizeService; import jnpf.permission.service.UserService; import jnpf.util.*; import jnpf.util.wxutil.HttpUtil; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.ObjectUtils; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import javax.script.ScriptException; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.text.SimpleDateFormat; import java.time.LocalDateTime; import java.time.ZoneOffset; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; /** * @author JNPF开发平台组 * @version V3.1.0 * @copyright 引迈信息技术有限公司 * @date 2021/3/12 15:31 */ @Service @Slf4j public class DataInterfaceServiceImpl extends SuperServiceImpl implements DataInterfaceService { private static final Set MARKERS = Set.of( DataInterfaceVarConst.ORGANDSUB, DataInterfaceVarConst.ORGANIZEANDPROGENY, DataInterfaceVarConst.USERANDSUB, DataInterfaceVarConst.USERANDPROGENY, DataInterfaceVarConst.POSITIONANDSUB, DataInterfaceVarConst.POSITIONANDPROGENY, DataInterfaceVarConst.CHARORG, DataInterfaceVarConst.ORG, DataInterfaceVarConst.POSITIONID, DataInterfaceVarConst.USER ); @Autowired private UserService userApi; @Autowired private DbLinkService dblinkService; @Autowired private DataSourceUtil dataSourceUtils; @Autowired private DataInterfaceLogService dataInterfaceLogService; @Autowired private DataInterfaceVariateService dataInterfaceVariateService; @Autowired private InterfaceOauthService interfaceOauthService; @Autowired private OrganizeService organizeApi; @Autowired private DataInterfaceUserService dataInterfaceUserService; @Autowired private ConfigValueUtil configValueUtil; @Override public List getList(PaginationDataInterface pagination, Integer isSelector) { // 定义变量判断是否需要使用修改时间倒序 boolean flag = false; QueryWrapper queryWrapper = new QueryWrapper<>(); if (ObjectUtil.isNotEmpty(pagination.getEnabledMark())) { queryWrapper.lambda().eq(DataInterfaceEntity::getEnabledMark, pagination.getEnabledMark()); } //关键字 if (!StringUtil.isEmpty(pagination.getKeyword())) { flag = true; queryWrapper.lambda().and( t -> t.like(DataInterfaceEntity::getFullName, pagination.getKeyword()) .or().like(DataInterfaceEntity::getEnCode, pagination.getKeyword()) ); } // 是否分页 if (pagination.getHasPage() != null && pagination.getHasPage() == 0) { queryWrapper.lambda().eq(DataInterfaceEntity::getHasPage, pagination.getHasPage()); } if (isSelector == 1) { queryWrapper.lambda().eq(DataInterfaceEntity::getIsPostPosition, 0); if (ObjectUtil.isEmpty(pagination.getEnabledMark())) { queryWrapper.lambda().eq(DataInterfaceEntity::getEnabledMark, 1); } } //分类 queryWrapper.lambda().eq(DataInterfaceEntity::getCategory, pagination.getCategory()); // 类型 String type = pagination.getType(); if (StringUtil.isNotEmpty(type)) { if (type.contains(",")) { List collect = Arrays.stream(type.split(",")).map(Integer::valueOf).collect(Collectors.toList()); queryWrapper.lambda().in(DataInterfaceEntity::getType, collect); } else { queryWrapper.lambda().eq(DataInterfaceEntity::getType, Integer.valueOf(type)); } } //排序 queryWrapper.lambda().orderByAsc(DataInterfaceEntity::getSortCode) .orderByDesc(DataInterfaceEntity::getCreatorTime); if (flag) { queryWrapper.lambda().orderByDesc(DataInterfaceEntity::getLastModifyTime); } Page page = new Page<>(pagination.getCurrentPage(), pagination.getPageSize()); IPage iPage = this.page(page, queryWrapper); return pagination.setData(iPage.getRecords(), iPage.getTotal()); } @Override public List getList(PaginationDataInterfaceSelector pagination) { QueryWrapper queryWrapper = new QueryWrapper<>(); if (ObjectUtil.equal(pagination.getSourceType(), 1)) { queryWrapper.lambda().and(t -> t.ne(DataInterfaceEntity::getType, 1).ne(DataInterfaceEntity::getHasPage, 1).ne(DataInterfaceEntity::getIsPostPosition, 1) .or(tt -> tt.eq(DataInterfaceEntity::getType, 1).eq(DataInterfaceEntity::getAction, 3).ne(DataInterfaceEntity::getHasPage, 1).ne(DataInterfaceEntity::getIsPostPosition, 1)) ); } else if (ObjectUtil.equal(pagination.getSourceType(), 2)) { queryWrapper.lambda().and(t -> t.ne(DataInterfaceEntity::getType, 1).ne(DataInterfaceEntity::getIsPostPosition, 1) .or(tt -> tt.eq(DataInterfaceEntity::getType, 1).eq(DataInterfaceEntity::getAction, 3).ne(DataInterfaceEntity::getIsPostPosition, 1)) ); } else if (ObjectUtil.equal(pagination.getSourceType(), 3)) { queryWrapper.lambda().and(t -> t.ne(DataInterfaceEntity::getType, 1).ne(DataInterfaceEntity::getHasPage, 1).ne(DataInterfaceEntity::getIsPostPosition, 1) .or(tt -> tt.eq(DataInterfaceEntity::getType, 1).ne(DataInterfaceEntity::getAction, 3).ne(DataInterfaceEntity::getHasPage, 1).ne(DataInterfaceEntity::getIsPostPosition, 1)) ); } // 类型 String type = pagination.getType(); if (StringUtil.isNotEmpty(type)) { if (type.contains(",")) { List collect = Arrays.stream(type.split(",")).map(Integer::valueOf).collect(Collectors.toList()); queryWrapper.lambda().in(DataInterfaceEntity::getType, collect); } else { queryWrapper.lambda().eq(DataInterfaceEntity::getType, Integer.valueOf(type)); } } //分类 queryWrapper.lambda().eq(DataInterfaceEntity::getCategory, pagination.getCategory()); queryWrapper.lambda().eq(DataInterfaceEntity::getEnabledMark, 1); //关键字查询 if (StringUtil.isNotEmpty(pagination.getKeyword())) { queryWrapper.lambda().and(t -> { t.like(DataInterfaceEntity::getFullName, pagination.getKeyword()).or(); t.like(DataInterfaceEntity::getEnCode, pagination.getKeyword()); }); } //排序 queryWrapper.lambda().orderByAsc(DataInterfaceEntity::getSortCode) .orderByDesc(DataInterfaceEntity::getCreatorTime); queryWrapper.lambda().orderByDesc(DataInterfaceEntity::getLastModifyTime); Page page = new Page<>(pagination.getCurrentPage(), pagination.getPageSize()); IPage iPage = this.page(page, queryWrapper); return pagination.setData(iPage.getRecords(), iPage.getTotal()); } @Override public List getList(boolean filterPage) { QueryWrapper queryWrapper = new QueryWrapper<>(); if (filterPage) { queryWrapper.lambda().ne(DataInterfaceEntity::getHasPage, 1); } queryWrapper.lambda().eq(DataInterfaceEntity::getEnabledMark, 1) .orderByAsc(DataInterfaceEntity::getSortCode) .orderByDesc(DataInterfaceEntity::getCreatorTime); return baseMapper.selectList(queryWrapper); } @Override public DataInterfaceEntity getInfo(String id) { QueryWrapper queryWrapper = new QueryWrapper<>(); queryWrapper.lambda().eq(DataInterfaceEntity::getId, id); return this.getOne(queryWrapper); } @Override public void create(DataInterfaceEntity entity) { entity.setId(RandomUtil.uuId()); entity.setCreatorUserId(UserProvider.getUser().getUserId()); entity.setCreatorTime(DateUtil.getNowDate()); entity.setLastModifyTime(null); entity.setLastModifyUserId(null); this.setIgnoreLogicDelete().saveOrUpdate(entity); this.clearIgnoreLogicDelete(); } @Override public boolean update(DataInterfaceEntity entity, String id) throws DataException { entity.setId(id); entity.setLastModifyUserId(UserProvider.getUser().getUserId()); entity.setLastModifyTime(DateUtil.getNowDate()); return this.updateById(entity); } @Override public void delete(DataInterfaceEntity entity) { LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>(); wrapper.eq(DataInterfaceVariateEntity::getInterfaceId, entity.getId()); dataInterfaceVariateService.remove(wrapper); this.removeById(entity.getId()); } @Override public boolean isExistByFullNameOrEnCode(String id, String fullName, String enCode) { QueryWrapper queryWrapper = new QueryWrapper<>(); if (StringUtil.isNotEmpty(fullName)) { queryWrapper.lambda().eq(DataInterfaceEntity::getFullName, fullName); } if (StringUtil.isNotEmpty(enCode)) { queryWrapper.lambda().eq(DataInterfaceEntity::getEnCode, enCode); } if (StringUtil.isNotEmpty(id)) { queryWrapper.lambda().ne(DataInterfaceEntity::getId, id); } return this.count(queryWrapper) > 0; } @Override public ActionResult infoToIdPageList(String id, DataInterfacePage page) { DataInterfaceEntity entity = this.getInfo(id); if (entity == null) { return ActionResult.page(new ArrayList<>(), JsonUtil.getJsonToBean(new Pagination(), PaginationVO.class)); } if (entity.getHasPage() == 1) { Map map = null; if (page.getParamList() != null) { map = new HashMap<>(); List jsonToList = JsonUtil.getJsonToList(page.getParamList(), DataInterfaceModel.class); this.paramSourceTypeReplaceValue(jsonToList, map); // for (DataInterfaceModel dataInterfaceModel : jsonToList) { // String defaultValue = dataInterfaceModel.getDefaultValue(); // map.put(dataInterfaceModel.getField(), defaultValue); // } } Pagination pagination = new Pagination(); pagination.setPageSize(page.getPageSize()); pagination.setCurrentPage(page.getCurrentPage()); pagination.setKeyword(page.getKeyword()); return infoToId(id, null, map, null, null, null, pagination, null); } else { String dataProcessing = null; if (StringUtil.isNotEmpty(entity.getDataJsJson())) { dataProcessing = entity.getDataJsJson(); } List> dataList = new ArrayList<>(); int total = 0; Map map = null; if (page.getParamList() != null) { map = new HashMap<>(); List jsonToList = JsonUtil.getJsonToList(page.getParamList(), DataInterfaceModel.class); this.paramSourceTypeReplaceValue(jsonToList, map); // for (DataInterfaceModel dataInterfaceModel : jsonToList) { // String defaultValue = dataInterfaceModel.getDefaultValue(); // map.put(dataInterfaceModel.getField(), defaultValue); // } } ActionResult result = infoToId(id, null, map); if (result.getData() != null) { if (result.getData() instanceof List) { dataList = (List>) result.getData(); } } // if (StringUtil.isNotEmpty(page.getKeyword()) && StringUtil.isNotEmpty(page.getRelationField())) { // dataList = dataList.stream().filter(t -> String.valueOf(t.get(page.getRelationField())).contains(page.getKeyword())).collect(Collectors.toList()); // } PaginationVO pagination = new PaginationVO(); page.setTotal(dataList.size()); if (StringUtil.isNotEmpty(page.getKeyword()) && StringUtil.isNotEmpty(page.getColumnOptions())) { String[] colOptions = page.getColumnOptions().split(","); dataList = dataList.stream().filter(t -> { boolean isFit = false; for (String c : colOptions) { if (String.valueOf(t.get(c)).contains(page.getKeyword())) { isFit = true; break; } } return isFit; }).collect(Collectors.toList()); } page.setTotal(dataList.size()); dataList = PageUtil.getListPage((int) page.getCurrentPage(), (int) page.getPageSize(), dataList); pagination = JsonUtil.getJsonToBean(page, PaginationVO.class); return ActionResult.page(dataList, pagination, dataProcessing); } } @Override public List> infoToInfo(String id, DataInterfacePage page) { List> list = new ArrayList<>(); Map map = null; DataInterfaceEntity entity = this.getInfo(id); if (entity == null) { return new ArrayList<>(); } try { if (entity.getHasPage() == 1) { if (page.getParamList() != null) { map = new HashMap<>(); List jsonToList = JsonUtil.getJsonToList(page.getParamList(), DataInterfaceModel.class); this.paramSourceTypeReplaceValue(jsonToList, map); // for (DataInterfaceModel dataInterfaceModel : jsonToList) { // String defaultValue = dataInterfaceModel.getDefaultValue(); // map.put(dataInterfaceModel.getField(), defaultValue); // } } Map showMap = new HashMap<>(); if (page.getIds() instanceof List) { List ids = (List) page.getIds(); Map finalMap = map; ids.forEach(t -> { showMap.put(page.getPropsValue(), t); ActionResult result = infoToId(id, null, finalMap, null, null, null, null, showMap); if (result.getData() instanceof Map) { Map objectMap = (Map) result.getData(); if (!objectMap.isEmpty()) { List mapList = JsonUtil.getJsonToList(objectMap.get("list"), Map.class); if (mapList != null && !mapList.isEmpty()) { list.add(mapList.get(0)); } else { list.add(objectMap); } } } else if (result.getData() instanceof List) { List list1 = (List) result.getData(); if (!list1.isEmpty()) { list.add(list1.get(0)); } } else { } }); } } else { if (page.getIds() != null) { Map dataMap = new HashMap<>(); if (page.getParamList() != null) { map = new HashMap<>(); List jsonToList = JsonUtil.getJsonToList(page.getParamList(), DataInterfaceModel.class); this.paramSourceTypeReplaceValue(jsonToList, map); // for (DataInterfaceModel dataInterfaceModel : jsonToList) { // map.put(dataInterfaceModel.getField(), dataInterfaceModel.getDefaultValue()); // } } ActionResult result = infoToId(id, null, map); List> dataList = new ArrayList<>(); if (result.getData() instanceof List) { dataList = (List>) result.getData(); List ids = (List) page.getIds(); List> finalDataList = dataList; ids.forEach(t -> { list.add(finalDataList.stream().filter(data -> t.equals(data.get(page.getPropsValue()))).findFirst().orElse(new HashMap<>())); }); } } } } catch (Exception e) { e.printStackTrace(); return list; } return list; } @Override public ActionResult infoToId(String id, String tenantId, Map map) { return infoToId(id, tenantId, map, null, null, null, null, null); } @Override public ActionResult infoToId(String id, String tenantId, Map map, String token, String appId, String invokType, Pagination pagination, Map showMap) { DataInterfaceEntity entity = this.getInfo(id); if (entity == null) { return ActionResult.success(new ArrayList<>()); } // 开始调用的时间 LocalDateTime dateTime = LocalDateTime.now(); //调用时间 int invokWasteTime = 0; // 有设置默认值的直接赋值 replaceDefaultVale(entity.getParameterJson(), map); // 验证参数必填或类型 String checkRequestParams = checkRequestParams(entity.getParameterJson(), map, null); if (StringUtil.isNotEmpty(checkRequestParams)) { return ActionResult.fail(checkRequestParams); } Object callJs = null; try { if (pagination == null) { pagination = new Pagination(); } // 数据配置 String dataConfigJson = entity.getDataConfigJson(); DataConfigJsonModel configJsonModel = JsonUtil.getJsonToBean(dataConfigJson, DataConfigJsonModel.class); // 如果是静态数据 if (entity.getType() == 2) { String staticData = configJsonModel.getStaticData(); Object object = callStaticData(staticData); handlePostVariate(entity, object); return ActionResult.success(object); } else if (entity.getType() == 3) { // HTTP调用或HTTPS调用 JSONObject jsonObject = new JSONObject(); if (showMap == null) { if (entity.getHasPage() == 0) { pagination = null; } //HTTP调用或HTTPS调用 jsonObject = callHTTP(map, token, pagination, null, configJsonModel.getApiData()); } else { String echoJson = entity.getDataEchoJson(); DataConfigJsonModel echoJsonModel = JsonUtil.getJsonToBean(echoJson, DataConfigJsonModel.class); jsonObject = callHTTP(map, token, null, showMap, echoJsonModel.getApiData()); } if (Objects.nonNull(jsonObject) && "1".equals(jsonObject.get("errorCode"))) { return ActionResult.fail(MsgCode.SYS121.get()); } // 判断返回参数长度和key是否跟内置的一致 if (jsonObject == null) { return ActionResult.fail(MsgCode.SYS122.get()); } handlePostVariate(entity, jsonObject); Object js = JScriptUtil.callJs(entity.getDataExceptionJson(), jsonObject.get("data") == null ? new ArrayList<>() : jsonObject.get("data")); if ((js instanceof Boolean && !BooleanUtil.toBoolean(String.valueOf(js)))) { // 继续执行接口 if (showMap == null) { // 处理变量 handlerVariate(configJsonModel.getApiData()); jsonObject = callHTTP(map, token, pagination, null, configJsonModel.getApiData()); } else { String echoJson = entity.getDataEchoJson(); DataConfigJsonModel echoJsonModel = JsonUtil.getJsonToBean(echoJson, DataConfigJsonModel.class); // 处理变量 handlerVariate(echoJsonModel.getApiData()); jsonObject = callHTTP(map, token, null, showMap, echoJsonModel.getApiData()); } } if (isInternal(jsonObject)) { callJs = JScriptUtil.callJs(entity.getDataJsJson(), jsonObject.get("data") == null ? new ArrayList<>() : jsonObject.get("data")); } else { callJs = JScriptUtil.callJs(entity.getDataJsJson(), jsonObject); } } else if (entity.getType() == 1) { UserInfo oldUser = null; if (token != null) { oldUser = UserProvider.getUser(); UserInfo userInfo = UserProvider.getUser(token); UserProvider.setLocalLoginUser(userInfo); } try { if (showMap == null) { SqlDateModel sqlData = configJsonModel.getSqlData(); List> sqlMapList = executeSql(entity, 0, map, pagination, null, sqlData); handlePostVariate(entity, sqlMapList); if (entity.getHasPage() == 1) { DataConfigJsonModel pageJsonModel = JsonUtil.getJsonToBean(entity.getDataConfigJson(), DataConfigJsonModel.class); List> maps = executeSql(entity, 1, map, pagination, null, pageJsonModel.getSqlData()); if (maps.get(0) != null) { pagination.setTotal(Long.parseLong(String.valueOf(maps.get(0).values().iterator().next()))); } Map obj = new HashMap<>(); obj.put("list", sqlMapList); obj.put("pagination", JsonUtil.getJsonToBean(pagination, PaginationVO.class)); callJs = JScriptUtil.callJs(entity.getDataJsJson(), obj); return ActionResult.success(callJs); } else { callJs = JScriptUtil.callJs(entity.getDataJsJson(), sqlMapList == null ? new ArrayList<>() : sqlMapList); } } else { DataConfigJsonModel echoJsonModel = JsonUtil.getJsonToBean(entity.getDataEchoJson(), DataConfigJsonModel.class); List> sqlMapList = executeSql(entity, 2, map, pagination, showMap, echoJsonModel.getSqlData()); if (entity.getHasPage() == 1) { DataConfigJsonModel pageJsonModel = JsonUtil.getJsonToBean(entity.getDataConfigJson(), DataConfigJsonModel.class); List> maps = executeSql(entity, 1, map, pagination, null, pageJsonModel.getSqlData()); if (maps.get(0) != null) { pagination.setTotal(Long.parseLong(String.valueOf(maps.get(0).values().iterator().next()))); } Map obj = new HashMap<>(); obj.put("list", sqlMapList); obj.put("pagination", JsonUtil.getJsonToBean(pagination, PaginationVO.class)); callJs = JScriptUtil.callJs(entity.getDataJsJson(), obj); return ActionResult.success(callJs); } else { callJs = JScriptUtil.callJs(entity.getDataJsJson(), CollectionUtil.isEmpty(sqlMapList) ? new ArrayList<>() : sqlMapList.get(0)); } } } finally { if (oldUser != null) { UserProvider.setLocalLoginUser(oldUser); } } } if (callJs instanceof Exception) { return ActionResult.success(MsgCode.SYS123.get(((Exception) callJs).getMessage())); } return ActionResult.success(callJs); } catch (Exception e) { log.error("错误提示:" + e.getMessage()); // 本地调试时打印出问题 e.printStackTrace(); return ActionResult.fail(MsgCode.SYS122.get()); } finally { // 调用时间 invokWasteTime = invokTime(dateTime); // 添加调用日志 dataInterfaceLogService.create(id, invokWasteTime, appId, invokType); } } /** * 预览时赋值变量 * * @param entity * @param object */ private void handlePostVariate(DataInterfaceEntity entity, Object object) { // 如果是鉴权的话,需要赋值value if (entity.getIsPostPosition() == 1) { List list = dataInterfaceVariateService.getList(entity.getId(), null); list.forEach(t -> { try { Object o; if (object instanceof JSONObject && isInternal((JSONObject) object)) { o = JScriptUtil.callJs(t.getExpression(), ((JSONObject) object).get("data")); } else { o = JScriptUtil.callJs(t.getExpression(), object); } if (o != null) { t.setValue(o.toString()); dataInterfaceVariateService.update(t); } } catch (ScriptException e) { log.error(e.getMessage()); } }); } } @Override public List getList(List ids) { if (CollectionUtil.isEmpty(ids)) { return new ArrayList<>(); } QueryWrapper queryWrapper = new QueryWrapper<>(); queryWrapper.lambda().in(DataInterfaceEntity::getId, ids); return this.list(queryWrapper); } /** * 处理静态数据 */ private Object callStaticData(String staticData) { Object obj; try { Object parse = JSON.parse(staticData); if (parse instanceof JSONArray) { obj = JsonUtil.getJsonToListMap(staticData); } else { obj = JsonUtil.stringToMap(staticData); } } catch (Exception e) { obj = staticData; } if (ObjectUtils.isEmpty(obj)) { return new ArrayList<>(); } return obj; } /** * 有设置默认值的直接赋值 * * @param parameterJson * @param map */ private void replaceDefaultVale(String parameterJson, Map map) { List dataInterfaceModelList = JsonUtil.getJsonToList(parameterJson, DataInterfaceModel.class); if (ObjectUtils.isNotEmpty(dataInterfaceModelList)) { if (map == null) { map = new HashMap<>(16); } for (DataInterfaceModel dataInterfaceModel : dataInterfaceModelList) { String field = dataInterfaceModel.getField(); String defaultValue = dataInterfaceModel.getDefaultValue(); String dataType = dataInterfaceModel.getDataType(); if (!map.containsKey(field) || StringUtil.isEmpty(map.get(field))) { map.put(field, defaultValue == null ? "" : defaultValue); } // if (dataType.equals("int") && StringUtil.isEmpty(map.get(field))) { // map.put(field, "0"); // } } } } /** * 判断是不是内部接口 * * @param jsonObject * @return */ private boolean isInternal(JSONObject jsonObject) { if (jsonObject != null) { if (jsonObject.size() == 3 && jsonObject.get("code") != null && jsonObject.get("msg") != null && jsonObject.get("data") != null) { return true; } } return false; } /** * 检查参数是够必填或类型是否正确 * * @param parameterJson * @param map * @param sql 预留参数 */ private String checkRequestParams(String parameterJson, Map map, String sql) { if (map == null || StringUtil.isEmpty(parameterJson)) { return ""; } StringBuilder message = new StringBuilder(); List dataInterfaceModelList = JsonUtil.getJsonToList(parameterJson, DataInterfaceModel.class); dataInterfaceModelList.stream().anyMatch(model -> { // 验证是否必填 if (model.getRequired() == 1) { String value = map.get(model.getField()); if (StringUtil.isEmpty(value)) { message.append(model.getField()).append("不能为空"); } } if (message.length() == 0) { // 验证类型 if (model.getDataType() != null) { String value = map.get(model.getField()); // 判断是整形 if (StringUtil.isNotEmpty(value) && "int".equals(model.getDataType())) { try { Integer.parseInt(value); } catch (Exception e) { message.append(model.getField()).append("类型必须为整型"); } } else if (StringUtil.isNotEmpty(value) && "datetime".equals(model.getDataType())) { try { SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); map.put(model.getField(), DateUtil.dateFormat(formatter.parse(value))); } catch (Exception e) { try { map.put(model.getField(), DateUtil.dateFormat(new Date(Long.valueOf(value)))); } catch (Exception ex) { message.append(model.getField() + "类型必须为日期时间型"); } } } else if (StringUtil.isNotEmpty(value) && "decimal".equals(model.getDataType())) { try { Double.valueOf(value); } catch (Exception e) { message.append(model.getField()).append("类型必须为浮点型"); } } } } return message.length() > 0; }); return message.toString(); } @Override public ActionResult infoToIdNew(String id, String tenantId, DataInterfaceActionModel model) { //鉴权验证 // 获取token String authorSignature = ServletUtil.getRequest().getHeader(Constants.AUTHORIZATION); String[] authorSignatureArr = authorSignature.split(":"); if (authorSignatureArr.length != 3) { return ActionResult.fail(ActionResultCode.ValidateError.getMessage()); } String appId = authorSignatureArr[0]; String author = authorSignatureArr[2]; Map map = model.getMap(); String interfaceUserToken = null; InterfaceOauthEntity infoByAppId = interfaceOauthService.getInfoByAppId(appId); //未提供app相关,接口认证失效,接口不在授权列表时无权访问 if (infoByAppId == null || infoByAppId.getEnabledMark() == 0 || !infoByAppId.getDataInterfaceIds().contains(id)) { return ActionResult.fail(MsgCode.FA021.get()); } if (infoByAppId.getVerifySignature() == 1) {//验证开启 try { //验证请求有效期1分钟内 String ymdateStr = ServletUtil.getRequest().getHeader(InterfaceUtil.YMDATE); Date ymdate = new Date(Long.parseLong(ymdateStr)); Date time = DateUtil.dateAddMinutes(ymdate, 1); if (DateUtil.getNowDate().after(time)) { return ActionResult.fail(MsgCode.SYS124.get()); } //验证签名有效性 boolean flag = InterfaceUtil.verifySignature(infoByAppId.getAppSecret(), author); if (!flag) { return ActionResult.fail(ActionResultCode.ValidateError.getMessage()); } } catch (Exception e) { e.printStackTrace(); return ActionResult.fail(ActionResultCode.ValidateError.getMessage()); } } else {//验证未开启,直接使用秘钥进行验证 if (!infoByAppId.getAppSecret().equals(author)) { return ActionResult.fail(MsgCode.SYS125.get()); } } //验证使用期限 Date usefulLife = infoByAppId.getUsefulLife(); if (infoByAppId.getUsefulLife() != null && usefulLife.before(DateUtil.getNowDate())) {//空值无限期 return ActionResult.fail(MsgCode.SYS126.get()); } try { //用户秘钥获取token interfaceUserToken = dataInterfaceUserService.getInterfaceUserToken(model.getTenantId(), infoByAppId.getId(), ServletUtil.getRequest().getHeader(InterfaceUtil.USERKEY)); } catch (Exception e) { return ActionResult.fail(e.getMessage()); } //黑白名单验证 String ipwhiteList = StringUtil.isNotEmpty(infoByAppId.getWhiteList()) ? infoByAppId.getWhiteList() : "";//ip白名单 String ipwhiteBlackList = StringUtil.isNotEmpty(infoByAppId.getBlackList()) ? infoByAppId.getBlackList() : "";//ip黑名单 String ipAddr = IpUtil.getIpAddr(); if (StringUtil.isNotEmpty(ipwhiteList) && !ipwhiteList.contains(ipAddr)) {//不属于白名单 return ActionResult.fail(MsgCode.LOG010.get()); } // if (StringUtil.isNotEmpty(ipwhiteBlackList) && ipwhiteBlackList.contains(ipAddr)) {//属于黑名单 // return ActionResult.fail(ActionResultCode.ValidateError.getMessage()); // } //以下调用接口 return infoToId(id, null, map, interfaceUserToken, infoByAppId.getAppId(), model.getInvokType(), null, null); } @Override public DataInterfaceActionModel checkParams(Map map) { String ymDate = ServletUtil.getRequest().getHeader(InterfaceUtil.YMDATE); String authorSignature = ServletUtil.getRequest().getHeader(Constants.AUTHORIZATION); if (StringUtils.isEmpty(ymDate)) { throw new RuntimeException("header参数:YmDate未传值"); } if (StringUtils.isEmpty(authorSignature)) { throw new RuntimeException("header参数:" + Constants.AUTHORIZATION + "未传值"); } DataInterfaceActionModel entity = new DataInterfaceActionModel(); //判断是否多租户,取参数tenantId if (InterfaceUtil.checkParam(map, "tenantId")) { entity.setTenantId(map.get("tenantId")); } String tenantId = SaHolder.getRequest().getParam("tenantId"); if (StringUtil.isNotEmpty(tenantId)) { entity.setTenantId(tenantId); } entity.setMap(map); return entity; } /** * 执行SQL * * @param entity * @param sqlType * @param map * @return * @throws DataException */ private List> executeSql(DataInterfaceEntity entity, int sqlType, Map map, Pagination pagination, Map showMap, SqlDateModel sqlDateModel) throws Exception { Map mapData = new HashMap<>(); if (map != null) { for (String key : map.keySet()) { mapData.put(key, map.get(key)); } } DataSourceUtil linkEntity = dblinkService.getInfo(sqlDateModel.getDbLinkId()); String sql = sqlDateModel.getSql(); if (entity.getHasPage() == 1) { if (sqlType == 1) { DataConfigJsonModel dataConfigJsonModel = JsonUtil.getJsonToBean(entity.getDataCountJson(), DataConfigJsonModel.class); if (dataConfigJsonModel != null) { SqlDateModel countSqlDateModel = JsonUtil.getJsonToBean(dataConfigJsonModel.getSqlData(), SqlDateModel.class); sql = countSqlDateModel.getSql(); } } else if (sqlType == 2) { DataConfigJsonModel dataConfigJsonModel = JsonUtil.getJsonToBean(entity.getDataEchoJson(), DataConfigJsonModel.class); if (dataConfigJsonModel != null) { SqlDateModel countSqlDateModel = JsonUtil.getJsonToBean(dataConfigJsonModel.getSqlData(), SqlDateModel.class); sql = countSqlDateModel.getSql(); } } } UserInfo userInfo = UserProvider.getUser(); if (linkEntity == null) { linkEntity = dataSourceUtils; } // 系统内置参数替换 Map systemParameter = systemParameter(sql, userInfo, pagination, showMap); // 自定义参数替换 sql = customizationParameter(entity.getParameterJson(), sql, mapData, systemParameter); // 处理SQL List values = new ArrayList<>(systemParameter.size()); // 参数替换为占位符 sql = getHandleArraysSql(sql, values, systemParameter); if (showMap != null) { sql = sql.replace(DataInterfaceVarConst.SHOWKEY, showMap.keySet().iterator().next()); } //封装sql---视图查询 -重新封装sql if (StringUtil.isNotEmpty(sql) && Objects.nonNull(map) && StringUtil.isNotEmpty(map.get("searchSqlStr")) && Objects.equals(entity.getAction(), 3)) { if (sql.trim().endsWith(";")) { sql = sql.trim(); sql = sql.substring(0, sql.length() - 1); } sql = "select * from (" + sql + ") t where " + map.get("searchSqlStr"); } //封装sql结束--- log.info("当前执行SQL:{}", sql); if (entity.getHasPage() == 1 && (sql.contains(";") && sql.trim().indexOf(";") != sql.trim().length() - 1)) { return null; } if (entity.getAction() != null && entity.getAction() != 3) { JdbcUtil.creUpDe(new PrepSqlDTO(sql, values).withConn(linkEntity, null)); return null; } String objectToString = JsonUtil.getObjectToStringAsDate(JdbcUtil.queryList(new PrepSqlDTO(sql, values).withConn(linkEntity, null)).setIsAlias(true).get()); return JsonUtil.getJsonToListMap(objectToString); } /** * 自定义参数替换 * * @param parameterJson 参数配置 * @param sql sql * @param map 参数 * @param systemParameter 参数集合 */ @Override public String customizationParameter(String parameterJson, String sql, Map map, Map systemParameter) { List dataInterfaceModelList = StringUtil.isNotEmpty(parameterJson) ? JsonUtil.getJsonToList(parameterJson, DataInterfaceModel.class) : new ArrayList<>(); if (StringUtil.isNotEmpty(sql) && Objects.nonNull(map)) { Map placeholderMap = new HashMap<>(); for (String key : map.keySet()) { // 验证参数key对比 Object tmpValue = map.get(key); if (tmpValue != null) { //参数前方 上个参数后方的语句中是否有 in String sqlarr1 = sql.split("\\{" + key + "}")[0]; String[] sqlarr2 = sqlarr1.split("}"); String sql1 = sqlarr2.length > 1 ? sqlarr2[sqlarr2.length - 1] : sqlarr2[0]; boolean isInSql = sql1.toLowerCase().contains(" in "); List valueList = new ArrayList<>(); if (isInSql) { valueList = Arrays.asList(String.valueOf(tmpValue).split(",")); } else { valueList.add(tmpValue); } String placeholder = "?"; for (int i = 1; i < valueList.size(); i++) { placeholder += ",?"; } String finalSql = sql; valueList.forEach(t -> { Object b = t; for (DataInterfaceModel model : dataInterfaceModelList) { if (model.getField().equals(key) && model.getDataType() != null) { // 判断是整形 if ("int".equals(model.getDataType())) { b = ObjectUtil.isNull(t) ? null : Integer.parseInt(String.valueOf(t)); } else if ("decimal".equals(model.getDataType())) { b = ObjectUtil.isNull(t) ? null : Double.valueOf(String.valueOf(t)); } else if ("datetime".equals(model.getDataType()) && ObjectUtil.isNull(t)) { b = null; } } } DataInterfaceParamUtil.getParamModel(systemParameter, finalSql, "{" + key + "}", b); }); placeholderMap.put(key, placeholder); } else { DataInterfaceParamUtil.getParamModel(systemParameter, sql, "{" + key + "}", null); placeholderMap.put(key, "?"); } } for (String key : placeholderMap.keySet()) { sql = sql.replaceAll("\\{" + key + "}", placeholderMap.get(key)); } } return sql; } /** * 参数替换为占位符 */ public String getHandleArraysSql(String sql, List values, Map systemParameter) { if (StringUtil.isNotEmpty(sql)) { for (Double aDouble : systemParameter.keySet()) { Object value = systemParameter.get(aDouble).getValue(); values.add(value); } for (Double aDouble : systemParameter.keySet()) { DataInterfaceMarkModel dataInterfaceMarkModel = systemParameter.get(aDouble); List collect = MARKERS.stream().filter(t -> t.equals(dataInterfaceMarkModel.getMarkName())).collect(Collectors.toList()); if (collect.isEmpty()) continue; if (dataInterfaceMarkModel.getValue() instanceof List) { List list = (List) dataInterfaceMarkModel.getValue(); StringBuilder placeholder = new StringBuilder("?"); int index = 0; boolean addOrSet = false; for (Object obj : list) { if (!addOrSet) { // 得到下标 int i = values.indexOf(dataInterfaceMarkModel.getValue()); values.set(i, obj); addOrSet = true; index = i++; } else { placeholder.append(",?"); values.add(index, obj); } } sql = sql.replaceAll(collect.get(0), placeholder.toString()); } } sql = sql.replaceAll(DataInterfaceVarConst.KEYWORD, "?"); sql = sql.replaceAll(DataInterfaceVarConst.USER, "?"); sql = sql.replaceAll(DataInterfaceVarConst.ORG, "?"); sql = sql.replaceAll(DataInterfaceVarConst.POSITIONID, "?"); sql = sql.replaceAll(DataInterfaceVarConst.OFFSETSIZE, "?"); sql = sql.replaceAll(DataInterfaceVarConst.PAGESIZE, "?"); // sql = sql.replaceAll(DataInterfaceVarEnum.SHOWKEY, "?"); sql = sql.replaceAll(DataInterfaceVarConst.SHOWVALUE, "?"); sql = sql.replaceAll(DataInterfaceVarConst.ID, "?"); sql = sql.replaceAll(DataInterfaceVarConst.ID_LOT, "?"); sql = sql.replaceAll(DataInterfaceVarConst.FORM_ID, "?"); } return sql; } /** * HTTP调用 * * @return get */ private JSONObject callHTTP(Map map, String token, Pagination pagination, Map showMap, ApiDateModel apiDateModel) throws UnsupportedEncodingException { JSONObject get = new JSONObject(); StringBuilder path = new StringBuilder(apiDateModel.getUrl()); // 请求方法 String requestMethod = apiDateModel.getMethod() == 1 ? "GET" : "POST"; // 获取请求头参数 List header = apiDateModel.getHeader(); // 自定义参数 List query = apiDateModel.getQuery(); String body = apiDateModel.getBody(); int bodyType = apiDateModel.getBodyType() == 1 ? 0 : apiDateModel.getBodyType(); // Post请求拼接参数 JSONObject jsonObject = null; List jsonObjects1 = null; //判断是否为http或https if (StringUtil.isNotEmpty(path.toString()) && path.toString().startsWith("/")) { path.insert(0, configValueUtil.getApiDomain()); if (StringUtil.isEmpty(token)) { token = UserProvider.getUser().getToken(); } } else { token = null; } if (path.toString().startsWith("http")) { String showKey = null; Object showValue = null; if (showMap != null) { if (!showMap.isEmpty()) { showKey = showMap.keySet().iterator().next(); showValue = showMap.values().iterator().next(); } } // 替换url上的回显参数 path = new StringBuilder(path.toString().replace("{" + DataInterfaceVarConst.SHOWKEY.replaceAll("@", "") + "}", showKey != null ? showKey : "")); path = new StringBuilder(path.toString().replace("{" + DataInterfaceVarConst.SHOWVALUE.replaceAll("@", "") + "}", showValue != null ? URLEncoder.encode(String.valueOf(showValue), "UTF-8") : "")); //请求参数解析 if (query != null) { // 判断是否为get,get从url上拼接 path.append(!path.toString().contains("?") ? "?" : "&"); for (HeadModel headModel : query) { if ("1".equals(headModel.getSource())) { String value = map == null || StringUtil.isEmpty(headModel.getDefaultValue()) || StringUtil.isEmpty(map.get(headModel.getDefaultValue())) ? "" : map.get(headModel.getDefaultValue()); path.append(headModel.getField()).append("=").append(URLEncoder.encode(value, "UTF-8")).append("&"); } if ("2".equals(headModel.getSource())) { DataInterfaceVariateEntity variateEntity = dataInterfaceVariateService.getInfo(headModel.getDefaultValue()); path.append(headModel.getField()).append("=").append(variateEntity.getValue()).append("&"); } if ("3".equals(headModel.getSource())) { path.append(headModel.getField()).append("=").append(URLEncoder.encode(StringUtil.isNotEmpty(headModel.getDefaultValue()) ? headModel.getDefaultValue() : "" // .replaceAll("'", "") , "UTF-8")).append("&"); } // 分页参数 if ("4".equals(headModel.getSource())) { Map map1 = JsonUtil.entityToMap(pagination); Object urlValue = map1.get(headModel.getDefaultValue()); if (urlValue instanceof String && ObjectUtil.isNotNull(urlValue)) { path.append(headModel.getField()).append("=").append(URLEncoder.encode(String.valueOf(urlValue), "UTF-8")).append("&"); } else { path.append(headModel.getField()).append("=").append(urlValue).append("&"); } } // 回显参数 if ("5".equals(headModel.getSource())) { if (DataInterfaceVarConst.SHOWKEY.equals(headModel.getDefaultValue())) { if (showKey != null) { path.append(headModel.getField()).append("=").append(URLEncoder.encode(showKey, "UTF-8")).append("&"); } } else { if (showValue != null) { path.append(headModel.getField()).append("=").append(URLEncoder.encode(String.valueOf(showValue), "UTF-8")).append("&"); } else { path.append(headModel.getField()).append("&"); } } } } } String jsonObjects = ""; if (bodyType == 2) { StringJoiner bodyParam = new StringJoiner("&"); List bodyJson = JsonUtil.getJsonToList(body, HeadModel.class); for (HeadModel headModel : bodyJson) { if ("1".equals(headModel.getSource())) { String value = map == null || StringUtil.isEmpty(headModel.getDefaultValue()) || StringUtil.isEmpty(map.get(headModel.getDefaultValue())) ? "" : map.get(headModel.getDefaultValue()); bodyParam.add(headModel.getField() + "=" + URLEncoder.encode(value, "UTF-8")); } if ("2".equals(headModel.getSource())) { DataInterfaceVariateEntity variateEntity = dataInterfaceVariateService.getInfo(headModel.getDefaultValue()); bodyParam.add(headModel.getField() + "=" + variateEntity.getValue()); } if ("3".equals(headModel.getSource())) { bodyParam.add(headModel.getField() + "=" + headModel.getDefaultValue()); } } jsonObjects += bodyParam.toString(); } else if (bodyType == 3 || bodyType == 4) { // 优先替换变量 Pattern compile = Pattern.compile("\\{@\\w+}"); Matcher matcher = compile.matcher(body); while (matcher.find()) { // 得到参数 String group = matcher.group(); String variate = group.replace("{", "").replace("}", "").replace("@", ""); DataInterfaceVariateEntity dataInterfaceVariateEntity = dataInterfaceVariateService.getInfoByFullName(variate); if (dataInterfaceVariateEntity != null) { body = body.replace(group, dataInterfaceVariateEntity.getValue()); } } Pattern compile1 = Pattern.compile("\\{\\w+}"); Matcher matcher1 = compile1.matcher(body); while (matcher1.find()) { // 得到参数 String group = matcher1.group(); String param = group.replace("{", "").replace("}", ""); String value = map != null ? map.get(param) : null; if (pagination != null && DataInterfaceVarConst.KEYWORD.equals("@" + param)) { value = pagination.getKeyword(); } if (pagination != null && DataInterfaceVarConst.CURRENTPAGE.equals("@" + param)) { value = pagination.getCurrentPage() + ""; } if (pagination != null && DataInterfaceVarConst.PAGESIZE.equals("@" + param)) { value = pagination.getPageSize() + ""; } body = body.replace(group, value); } jsonObjects = body; } jsonObjects = StringUtil.isEmpty(jsonObjects) ? null : jsonObjects; if (apiDateModel.getMethod() == 1) { jsonObjects = ""; } JSONObject headerJson = new JSONObject(); // 请求头 for (HeadModel headModel : header) { if ("1".equals(headModel.getSource())) { if (map != null && map.containsKey(headModel.getDefaultValue())) { String value = map.get(headModel.getDefaultValue()); headerJson.put(headModel.getField(), value // .replaceAll("'", "") ); } else { headerJson.put(headModel.getField(), map.get(headModel.getDefaultValue())); } } if ("2".equals(headModel.getSource())) { DataInterfaceVariateEntity variateEntity = dataInterfaceVariateService.getInfo(headModel.getDefaultValue()); headerJson.put(headModel.getField(), variateEntity.getValue()); } if ("3".equals(headModel.getSource())) { headerJson.put(headModel.getField(), headModel.getDefaultValue()); } // 分页参数 if ("4".equals(headModel.getSource())) { Map map1 = JsonUtil.entityToMap(pagination); Object urlValue = map1.get(headModel.getDefaultValue()); headerJson.put(headModel.getField(), urlValue); } // 回显参数 if ("5".equals(headModel.getSource())) { if (DataInterfaceVarConst.SHOWKEY.equals(headModel.getDefaultValue())) { headerJson.put(headModel.getField(), showKey); } else { headerJson.put(headModel.getField(), showValue); } } } get = HttpUtil.httpRequest(path.toString(), requestMethod, jsonObjects, token, !headerJson.isEmpty() ? JsonUtil.getObjectToString(headerJson) : null, String.valueOf(bodyType)); return get; } else { get.put("errorCode", "1"); return get; } } /** * 处理变量 * * @param apiDateModel */ public void handlerVariate(ApiDateModel apiDateModel) { Set variate = new HashSet<>(); // 获取请求头参数 List header = apiDateModel.getHeader(); header.forEach(headModel -> { if ("2".equals(headModel.getSource())) { variate.add(headModel.getDefaultValue()); } }); // 自定义参数 List query = apiDateModel.getQuery(); query.forEach(headModel -> { if ("2".equals(headModel.getSource())) { variate.add(headModel.getDefaultValue()); } }); if (ObjectUtil.equal(apiDateModel.getBodyType(), 1) || ObjectUtil.equal(apiDateModel.getBodyType(), 2)) { List bodyJson = JsonUtil.getJsonToList(apiDateModel.getBody(), HeadModel.class); if (bodyJson != null) { bodyJson.forEach(headModel -> { if ("2".equals(headModel.getSource())) { variate.add(headModel.getDefaultValue()); } }); } } List variateEntities = dataInterfaceVariateService.getListByIds(new ArrayList<>(variate)); List collect = variateEntities.stream().map(DataInterfaceVariateEntity::getInterfaceId).distinct().collect(Collectors.toList()); List list = this.getList(collect); Map results = new HashMap<>(); Map updates = new HashMap<>(); list.forEach(t -> { try { DataConfigJsonModel dataConfigJsonModel = JsonUtil.getJsonToBean(t.getDataConfigJson(), DataConfigJsonModel.class); JSONObject jsonObject = callHTTP(null, UserProvider.getToken(), new Pagination(), null, JsonUtil.getJsonToBean(dataConfigJsonModel.getApiData(), ApiDateModel.class)); if (Objects.nonNull(jsonObject) && "1".equals(jsonObject.get("errorCode"))) { log.error("接口暂只支持HTTP和HTTPS方式"); return; } // 判断返回参数长度和key是否跟内置的一致 if (jsonObject == null) { log.error("接口请求失败"); return; } if (isInternal(jsonObject)) { results.put(t.getId(), JScriptUtil.callJs(t.getDataJsJson(), jsonObject.get("data") == null ? new ArrayList<>() : jsonObject.get("data"))); } else { results.put(t.getId(), JScriptUtil.callJs(t.getDataJsJson(), jsonObject)); } } catch (Exception e) { log.error(e.getMessage()); } }); variateEntities.forEach(t -> { if (results.containsKey(t.getInterfaceId())) { try { updates.put(t.getId(), String.valueOf(JScriptUtil.callJs(t.getExpression(), results.get(t.getInterfaceId())))); } catch (ScriptException e) { throw new RuntimeException(e); } } }); dataInterfaceVariateService.update(updates, variateEntities); } /** * 处理系统参数 * * @param sql * @return */ private Map systemParameter(String sql, UserInfo userInfo, Pagination pagination, Map showMap) { Map paramValue = new TreeMap<>(systemParameterOne(sql, userInfo)); //关键字 if (sql.contains(DataInterfaceVarConst.KEYWORD)) { DataInterfaceParamUtil.getParamModel(paramValue, sql, DataInterfaceVarConst.KEYWORD, pagination.getKeyword()); } // 当前页数 if (sql.contains(DataInterfaceVarConst.OFFSETSIZE)) { DataInterfaceParamUtil.getParamModel(paramValue, sql, DataInterfaceVarConst.OFFSETSIZE, pagination.getPageSize() * (pagination.getCurrentPage() - 1)); } // 每页行数 if (sql.contains(DataInterfaceVarConst.PAGESIZE)) { DataInterfaceParamUtil.getParamModel(paramValue, sql, DataInterfaceVarConst.PAGESIZE, pagination.getPageSize()); } // 每页行数 if (sql.contains(DataInterfaceVarConst.SHOWVALUE)) { DataInterfaceParamUtil.getParamModel(paramValue, sql, DataInterfaceVarConst.SHOWVALUE, showMap.values().iterator().next()); } return paramValue; } /** * 处理系统参数 * * @param sql * @param userInfo * @return */ public Map systemParameterOne(String sql, UserInfo userInfo) { Map paramValue = new TreeMap<>(); if (sql.contains(DataInterfaceVarConst.ID_LOT)) { DataInterfaceParamUtil.getParamModel(paramValue, sql, DataInterfaceVarConst.ID_LOT, null); } // 生成雪花id if (sql.contains(DataInterfaceVarConst.ID)) { DataInterfaceParamUtil.getParamModel(paramValue, sql, DataInterfaceVarConst.ID, RandomUtil.uuId()); } Map systemFieldValue = userApi.getSystemFieldValue(new SystemParamModel(sql)); //当前用户 if (hasCurrentUser(sql)) { String userId = userInfo.getUserId(); DataInterfaceParamUtil.getParamModel(paramValue, sql, DataInterfaceVarConst.USER, userId); } AuthorizeConditionEnum.getResListType().stream().forEach(t -> { List dataList = StringUtil.isNotEmpty(t) ? JsonUtil.getJsonToList(systemFieldValue.get(t), String.class) : Collections.EMPTY_LIST; DataInterfaceParamUtil.getParamModel(paramValue, sql, t, dataList); }); return paramValue; } /** * 是否包含当前用户 * (当前用户及下属key包含当前用户key,constains判断不准确) * * @param str * @return */ public static boolean hasCurrentUser(String str) { int index = 0; int count = 0; while ((index = str.indexOf(DataInterfaceVarConst.USERANDSUB, index)) != -1) { count++; index += DataInterfaceVarConst.USERANDSUB.length(); } int index2 = 0; int count2 = 0; while ((index2 = str.indexOf(DataInterfaceVarConst.USER, index2)) != -1) { count2++; index2 += DataInterfaceVarConst.USER.length(); } return count != count2; } /** * 计算执行时间 * * @param dateTime * @return */ public int invokTime(LocalDateTime dateTime) { //调用时间 return (int) (System.currentTimeMillis() - dateTime.toInstant(ZoneOffset.of("+8")).toEpochMilli()); } /** * 按sourceType替换数据接口参数 * * @param listJson * @param map */ @Override public void paramSourceTypeReplaceValue(List listJson, Map map) { Map systemFieldValue = userApi.getSystemFieldValue(new SystemParamModel(JsonUtil.getObjectToString(listJson))); for (DataInterfaceModel item : listJson) { if (item.getSourceType() != null) { switch (item.getSourceType()) { case 1://字段 map.put(item.getField(), item.getDefaultValue()); break; case 2://自定义 map.put(item.getField(), item.getRelationField()); break; case 3://为空 map.put(item.getField(), ""); break; case 4://系统参数 map.put(item.getField(), this.getSystemFieldValue(item, systemFieldValue)); break; default: map.put(item.getField(), item.getDefaultValue()); break; } } else { map.put(item.getField(), item.getDefaultValue()); } } } /** * 获取系统参数值 * * @param templateJsonModel * @return */ @Override public String getSystemFieldValue(DataInterfaceModel templateJsonModel, Map systemFieldValue) { String relationField = templateJsonModel.getRelationField(); String dataValue; if (AuthorizeConditionEnum.FORMID.getCondition().equals(relationField)) { dataValue = String.valueOf(templateJsonModel.getDefaultValue()); } else if (AuthorizeConditionEnum.getResListType().contains(relationField)) { List strings = StringUtil.isNotEmpty(systemFieldValue.get(relationField)) ? JsonUtil.getJsonToList(systemFieldValue.get(relationField), String.class) : Collections.EMPTY_LIST; dataValue = CollectionUtil.isEmpty(strings) ? "" : String.join(",", strings); } else if (systemFieldValue.containsKey(relationField)) { dataValue = systemFieldValue.get(relationField); } else { dataValue = templateJsonModel.getDefaultValue(); } return dataValue; } }