| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402 |
- 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<DataInterfaceMapper, DataInterfaceEntity> implements DataInterfaceService {
- private static final Set<String> 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<DataInterfaceEntity> getList(PaginationDataInterface pagination, Integer isSelector) {
- // 定义变量判断是否需要使用修改时间倒序
- boolean flag = false;
- QueryWrapper<DataInterfaceEntity> 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<Integer> 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<DataInterfaceEntity> page = new Page<>(pagination.getCurrentPage(), pagination.getPageSize());
- IPage<DataInterfaceEntity> iPage = this.page(page, queryWrapper);
- return pagination.setData(iPage.getRecords(), iPage.getTotal());
- }
- @Override
- public List<DataInterfaceEntity> getList(PaginationDataInterfaceSelector pagination) {
- QueryWrapper<DataInterfaceEntity> 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<Integer> 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<DataInterfaceEntity> page = new Page<>(pagination.getCurrentPage(), pagination.getPageSize());
- IPage<DataInterfaceEntity> iPage = this.page(page, queryWrapper);
- return pagination.setData(iPage.getRecords(), iPage.getTotal());
- }
- @Override
- public List<DataInterfaceEntity> getList(boolean filterPage) {
- QueryWrapper<DataInterfaceEntity> 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<DataInterfaceEntity> 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<DataInterfaceVariateEntity> 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<DataInterfaceEntity> 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<String, String> map = null;
- if (page.getParamList() != null) {
- map = new HashMap<>();
- List<DataInterfaceModel> 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<Map<String, Object>> dataList = new ArrayList<>();
- int total = 0;
- Map<String, String> map = null;
- if (page.getParamList() != null) {
- map = new HashMap<>();
- List<DataInterfaceModel> 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<Map<String, Object>>) 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<Map<String, Object>> infoToInfo(String id, DataInterfacePage page) {
- List<Map<String, Object>> list = new ArrayList<>();
- Map<String, String> 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<DataInterfaceModel> 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<String, Object> showMap = new HashMap<>();
- if (page.getIds() instanceof List) {
- List<Object> ids = (List<Object>) page.getIds();
- Map<String, String> 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<String, Object> objectMap = (Map<String, Object>) result.getData();
- if (!objectMap.isEmpty()) {
- List<Map> 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<Map> list1 = (List<Map>) result.getData();
- if (!list1.isEmpty()) {
- list.add(list1.get(0));
- }
- } else {
- }
- });
- }
- } else {
- if (page.getIds() != null) {
- Map<String, Object> dataMap = new HashMap<>();
- if (page.getParamList() != null) {
- map = new HashMap<>();
- List<DataInterfaceModel> 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<Map<String, Object>> dataList = new ArrayList<>();
- if (result.getData() instanceof List) {
- dataList = (List<Map<String, Object>>) result.getData();
- List<Object> ids = (List<Object>) page.getIds();
- List<Map<String, Object>> 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<String, String> map) {
- return infoToId(id, tenantId, map, null, null, null, null, null);
- }
- @Override
- public ActionResult infoToId(String id, String tenantId, Map<String, String> map, String token, String appId, String invokType, Pagination pagination, Map<String, Object> 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<Map<String, Object>> sqlMapList = executeSql(entity, 0, map, pagination, null, sqlData);
- handlePostVariate(entity, sqlMapList);
- if (entity.getHasPage() == 1) {
- DataConfigJsonModel pageJsonModel = JsonUtil.getJsonToBean(entity.getDataConfigJson(), DataConfigJsonModel.class);
- List<Map<String, Object>> 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<String, Object> 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<Map<String, Object>> sqlMapList = executeSql(entity, 2, map, pagination, showMap, echoJsonModel.getSqlData());
- if (entity.getHasPage() == 1) {
- DataConfigJsonModel pageJsonModel = JsonUtil.getJsonToBean(entity.getDataConfigJson(), DataConfigJsonModel.class);
- List<Map<String, Object>> 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<String, Object> 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<DataInterfaceVariateEntity> 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<DataInterfaceEntity> getList(List<String> ids) {
- if (CollectionUtil.isEmpty(ids)) {
- return new ArrayList<>();
- }
- QueryWrapper<DataInterfaceEntity> 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<String, String> map) {
- List<DataInterfaceModel> 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<String, String> map, String sql) {
- if (map == null || StringUtil.isEmpty(parameterJson)) {
- return "";
- }
- StringBuilder message = new StringBuilder();
- List<DataInterfaceModel> 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<String, String> 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<String, String> 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<Map<String, Object>> executeSql(DataInterfaceEntity entity, int sqlType, Map<String, String> map,
- Pagination pagination, Map<String, Object> showMap,
- SqlDateModel sqlDateModel) throws Exception {
- Map<String, Object> 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<Double, DataInterfaceMarkModel> systemParameter = systemParameter(sql, userInfo, pagination, showMap);
- // 自定义参数替换
- sql = customizationParameter(entity.getParameterJson(), sql, mapData, systemParameter);
- // 处理SQL
- List<Object> 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<String, Object> map,
- Map<Double, DataInterfaceMarkModel> systemParameter) {
- List<DataInterfaceModel> dataInterfaceModelList = StringUtil.isNotEmpty(parameterJson) ? JsonUtil.getJsonToList(parameterJson, DataInterfaceModel.class) : new ArrayList<>();
- if (StringUtil.isNotEmpty(sql) && Objects.nonNull(map)) {
- Map<String, String> 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<Object> 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<Object> values, Map<Double, DataInterfaceMarkModel> 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<String> 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<String, String> map,
- String token, Pagination pagination, Map<String, Object> showMap,
- ApiDateModel apiDateModel) throws UnsupportedEncodingException {
- JSONObject get = new JSONObject();
- StringBuilder path = new StringBuilder(apiDateModel.getUrl());
- // 请求方法
- String requestMethod = apiDateModel.getMethod() == 1 ? "GET" : "POST";
- // 获取请求头参数
- List<HeadModel> header = apiDateModel.getHeader();
- // 自定义参数
- List<HeadModel> query = apiDateModel.getQuery();
- String body = apiDateModel.getBody();
- int bodyType = apiDateModel.getBodyType() == 1 ? 0 : apiDateModel.getBodyType();
- // Post请求拼接参数
- JSONObject jsonObject = null;
- List<JSONObject> 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<String, Object> 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<HeadModel> 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<String, Object> 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<String> variate = new HashSet<>();
- // 获取请求头参数
- List<HeadModel> header = apiDateModel.getHeader();
- header.forEach(headModel -> {
- if ("2".equals(headModel.getSource())) {
- variate.add(headModel.getDefaultValue());
- }
- });
- // 自定义参数
- List<HeadModel> 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<HeadModel> bodyJson = JsonUtil.getJsonToList(apiDateModel.getBody(), HeadModel.class);
- if (bodyJson != null) {
- bodyJson.forEach(headModel -> {
- if ("2".equals(headModel.getSource())) {
- variate.add(headModel.getDefaultValue());
- }
- });
- }
- }
- List<DataInterfaceVariateEntity> variateEntities = dataInterfaceVariateService.getListByIds(new ArrayList<>(variate));
- List<String> collect = variateEntities.stream().map(DataInterfaceVariateEntity::getInterfaceId).distinct().collect(Collectors.toList());
- List<DataInterfaceEntity> list = this.getList(collect);
- Map<String, Object> results = new HashMap<>();
- Map<String, String> 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<Double, DataInterfaceMarkModel> systemParameter(String sql, UserInfo userInfo, Pagination pagination, Map<String, Object> showMap) {
- Map<Double, DataInterfaceMarkModel> 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<Double, DataInterfaceMarkModel> systemParameterOne(String sql, UserInfo userInfo) {
- Map<Double, DataInterfaceMarkModel> 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<String, String> 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<String> 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<DataInterfaceModel> listJson, Map<String, String> map) {
- Map<String, String> 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<String, String> 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<String> 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;
- }
- }
|