Commit 0a7b743c authored by zhangc's avatar zhangc

优化gateway部分代码

parent 78e8094b
...@@ -8,18 +8,18 @@ CREATE TABLE `t_api_interface` ( ...@@ -8,18 +8,18 @@ CREATE TABLE `t_api_interface` (
`api_protocl` varchar(32) DEFAULT NULL COMMENT 'api请求协议:http,https', `api_protocl` varchar(32) DEFAULT NULL COMMENT 'api请求协议:http,https',
`api_path` varchar(100) DEFAULT NULL COMMENT '请求地址', `api_path` varchar(100) DEFAULT NULL COMMENT '请求地址',
`target_url` varchar(100) DEFAULT NULL COMMENT '目标url', `target_url` varchar(100) DEFAULT NULL COMMENT '目标url',
`api_type` varchar(50) NULL DEFAULT '' COMMENT 'api类型:1 数据银行制作API 2 数据银行制作数据包, 3 API实时接入 6 标签查询 9自定义', `api_type` varchar(50) NULL DEFAULT '' COMMENT 'api类型:1 数据银行制作大数据表 2 数据银行制作数据包,3,数据银行制作自定义API 4 API实时接入 6 标签查询 9自定义',
`api_function` varchar(200) DEFAULT NULL COMMENT '接口功能', `api_function` varchar(200) DEFAULT NULL COMMENT '接口功能',
`join_type` varchar(50) NULL DEFAULT NULL COMMENT '接入类型:字典表对应key值', `join_type` varchar(50) NULL DEFAULT NULL COMMENT '接入类型:字典表对应key值',
`test_example` varchar(255) NULL DEFAULT NULL COMMENT '测试实例', `test_example` varchar(255) NULL DEFAULT NULL COMMENT '测试实例',
`status` varchar(50) NOT NULL COMMENT '状态(DRAFT-草稿 ISSUE-发布 OUTMODED-过时 4FREEZE-冻结 EXPIRY-失效)', `status` varchar(50) NOT NULL COMMENT '状态(DRAFT-草稿 ISSUE-发布 OUTMODED-过时 4FREEZE-冻结 EXPIRY-失效)',
`output_type` varchar(50) NULL DEFAULT 'JSON' COMMENT '输出类型:flow 流形式输出, json格式输出', `output_type` varchar(50) NULL DEFAULT 'JSON' COMMENT '输出类型:flow 流形式输出, json格式输出',
`page` tinyint(2) NULL DEFAULT '0' COMMENT '是否分页:0 false ,1 true', `page` tinyint(2) NULL DEFAULT '0' COMMENT '是否分页:0 false ,1 true',
`version` varchar(20) DEFAULT '1.0' COMMENT '版本号', `version` varchar(20) DEFAULT 'v1.0' COMMENT '版本号',
`sign_type` varchar(50) DEFAULT NULL COMMENT '加密方式: MD5 RSA', `sign_type` varchar(50) DEFAULT NULL COMMENT '加密方式: MD5 RSA',
`timeout` varchar(50) DEFAULT NULL COMMENT '超时时间', `timeout` varchar(50) DEFAULT NULL COMMENT '超时时间',
`file_id` bigint(20) NOT NULL COMMENT '文件夹id', `file_id` bigint(20) NOT NULL COMMENT '文件夹id',
`req_type` varchar(20) DEFAULT NULL COMMENT '限类型:DAY 按天,MONTH 按月, YEAR 按年', `req_type` varchar(20) DEFAULT NULL COMMENT '限类型:DAY 按天,MONTH 按月, YEAR 按年',
`req_frequency` bigint(20) DEFAULT '100' COMMENT '限制次数', `req_frequency` bigint(20) DEFAULT '100' COMMENT '限制次数',
`is_test` tinyint(2) NOT NULL DEFAULT '0' COMMENT '是否测试数据:0 否,1 是', `is_test` tinyint(2) NOT NULL DEFAULT '0' COMMENT '是否测试数据:0 否,1 是',
`remark` varchar(500) DEFAULT NULL COMMENT '备注', `remark` varchar(500) DEFAULT NULL COMMENT '备注',
...@@ -38,7 +38,11 @@ CREATE TABLE `t_api_interface_custom` ( ...@@ -38,7 +38,11 @@ CREATE TABLE `t_api_interface_custom` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT 'api 信息表自增ID', `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT 'api 信息表自增ID',
`api_key` varchar(200) NOT NULL COMMENT 'api唯一标识', `api_key` varchar(200) NOT NULL COMMENT 'api唯一标识',
`api_interface_id` bigint(20) NOT NULL COMMENT 'api表自增id', `api_interface_id` bigint(20) NOT NULL COMMENT 'api表自增id',
`api_type` varchar(50) DEFAULT '' COMMENT 'api类型:1 实时接入 2 数据银行制作API, 3 数据银行制作数据包 6标签查询 9自定义', `api_type` varchar(50) DEFAULT '' COMMENT 'api类型:1 数据银行制作大数据表 2 数据银行制作数据包,3,数据银行制作自定义API 4 API实时接入 5 DMP标签查询 6.DMP大数据表查询 7 DMP自定义',
`es_data_source` varchar(100) DEFAULT NULL COMMENT '数据源id',
`es_data_base` varchar(100) DEFAULT NULL COMMENT '源数据库名称',
`es_table` varchar(100) DEFAULT NULL COMMENT '源数据表名称',
`handle_type` varchar(50) DEFAULT NULL COMMENT '处理类型',
`request_param` varchar(300) DEFAULT NULL COMMENT '请求参数', `request_param` varchar(300) DEFAULT NULL COMMENT '请求参数',
`response_param` varchar(300) DEFAULT NULL COMMENT '响应参数', `response_param` varchar(300) DEFAULT NULL COMMENT '响应参数',
`req_headers` varchar(300) DEFAULT NULL COMMENT '请求头', `req_headers` varchar(300) DEFAULT NULL COMMENT '请求头',
...@@ -105,7 +109,7 @@ CREATE TABLE `t_api_auth` ( ...@@ -105,7 +109,7 @@ CREATE TABLE `t_api_auth` (
`api_interface_id` bigint(20) NOT NULL COMMENT 'api信息表id', `api_interface_id` bigint(20) NOT NULL COMMENT 'api信息表id',
`api_org_id` bigint(20) NOT NULL COMMENT 'api组织id', `api_org_id` bigint(20) NOT NULL COMMENT 'api组织id',
`auth_type` varchar(20) DEFAULT NULL COMMENT '授权类型:DATA_BANK_AUTH 数据银行购买 DMP_AUTH dmp授权', `auth_type` varchar(20) DEFAULT NULL COMMENT '授权类型:DATA_BANK_AUTH 数据银行购买 DMP_AUTH dmp授权',
`req_type` varchar(20) DEFAULT NULL COMMENT '限类型:DAY 按天,MONTH 按月, YEAR 按年', `req_type` varchar(20) DEFAULT NULL COMMENT '限类型:DAY 按天,MONTH 按月, YEAR 按年',
`req_frequency` bigint(20) DEFAULT '100' COMMENT '限制次数', `req_frequency` bigint(20) DEFAULT '100' COMMENT '限制次数',
`auth_code` varchar(100) DEFAULT NULL COMMENT '授权码', `auth_code` varchar(100) DEFAULT NULL COMMENT '授权码',
`salt` varchar(200) DEFAULT NULL COMMENT '盐值', `salt` varchar(200) DEFAULT NULL COMMENT '盐值',
......
...@@ -25,4 +25,5 @@ public class ApiGatewayApplication { ...@@ -25,4 +25,5 @@ public class ApiGatewayApplication {
public static void main(String[] args) { public static void main(String[] args) {
SpringApplication.run(ApiGatewayApplication.class, args); SpringApplication.run(ApiGatewayApplication.class, args);
} }
} }
package com.jz.dm.common.base;
import com.jz.common.bean.SysUserDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
/**
* @author ZC
* @PACKAGE_NAME: com.jz.dm.common.base
* @PROJECT_NAME: jz-dm-parent
* @NAME: BaseCurrentUserObject
* @DATE: 2020-12-30/16:05
* @DAY_NAME_SHORT: 周三
* @Description: 获取当前登录用户
**/
@Component
public class BaseCurrentUserObject {
@Autowired
private RedisTemplate redisTemplate;
/**
* 获取登录用户
*
* @return
*/
public SysUserDto getUserInfo() {
SysUserDto sysUserDto = (SysUserDto) redisTemplate.opsForValue().get("USER" + "004");//RedisMessageConstant.SENDTYPE_LOGIN_SYS);
return sysUserDto;
}
//SysUserDto currentUser = (SysUserDto)
// redisTemplate.opsForValue().get("user" + RedisMessageConstant.SENDTYPE_LOGIN_SYS);
/*public static void main(String[] args) {
System.out.println(new BaseCurrentUserObject().getUserInfo());
}*/
}
...@@ -48,4 +48,13 @@ public enum GeneralStatusTypeEnum { ...@@ -48,4 +48,13 @@ public enum GeneralStatusTypeEnum {
public String getText() { public String getText() {
return text; return text;
} }
public static GeneralStatusTypeEnum fromGeneralStatus(String typeName) {
for (GeneralStatusTypeEnum type : GeneralStatusTypeEnum.values()) {
if (type.name().equals(typeName)) {
return type;
}
}
return null;
}
} }
...@@ -26,15 +26,13 @@ public class MapUtil { ...@@ -26,15 +26,13 @@ public class MapUtil {
* @param apiKey * @param apiKey
* @param method * @param method
* @param signType * @param signType
* @param timestamp
* @return * @return
*/ */
public static String getSignValue(String apiKey,String method,String signType,String timestamp){ public static String getSignValue(String apiKey,String method,String signType){
StringBuilder builder = new StringBuilder(); StringBuilder builder = new StringBuilder();
builder.append("apiKey=").append(apiKey).append(LoggingConstants.AND_SPILT) builder.append("apiKey=").append(apiKey).append(LoggingConstants.AND_SPILT)
.append("method=").append(method).append(LoggingConstants.AND_SPILT) .append("method=").append(method).append(LoggingConstants.AND_SPILT)
.append("signType=").append(signType).append(LoggingConstants.AND_SPILT) .append("signType=").append(signType);
.append("timestamp=").append(timestamp);
return builder.toString(); return builder.toString();
} }
......
package com.jz.dm.common.util;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
/**
* MD5加密算法
*
* @author Admin
* @version $Id: Md5Utils.java 2014年9月3日 下午4:01:08 $
*/
public class Md5 {
private static Logger log = LoggerFactory.getLogger(Md5.class);
private static final String SIGN_TYPE = "MD5";
private static final String CHARSET_NAME = "UTF-8";
private static final String salt = "3zsAa6W9gfSMMhPSlQTdWFUSHY3LS8Vb";
/**
* MD5加密
*
* @param data
* @return
* @throws NoSuchAlgorithmException
*/
public static String encrypt(byte[] data) {
try {
MessageDigest md5 = MessageDigest.getInstance(SIGN_TYPE);
md5.update(data);
return byte2hex(md5.digest());
} catch (NoSuchAlgorithmException e) {
log.debug("md5 加密异常", e);
}
return "";
}
/**
* MD5加密
*
* @param str
* @return
* @throws NoSuchAlgorithmException
*/
public static String encrypt(String str) {
try {
MessageDigest md5 = MessageDigest.getInstance(SIGN_TYPE);
md5.update((str + salt).getBytes(CHARSET_NAME));
return byte2hex(md5.digest());
} catch (Exception e) {
log.debug("md5 加密异常", e);
}
return null;
}
/**
* MD5加盐加密
*
* @param str
* @param salt
* @return
* @throws NoSuchAlgorithmException
*/
public static String encrypt(String str, String salt) {
try {
MessageDigest md5 = MessageDigest.getInstance(SIGN_TYPE);
md5.update((str + salt).getBytes(CHARSET_NAME));
return byte2hex(md5.digest());
} catch (Exception e) {
if (log.isDebugEnabled()) {
log.debug("md5 加密异常", e);
}
}
return "";
}
public static String encrypt(String str, String salt, String charset) {
try {
MessageDigest md5 = MessageDigest.getInstance(SIGN_TYPE);
md5.update((str + salt).getBytes(charset));
return byte2hex(md5.digest());
} catch (Exception e) {
if (log.isDebugEnabled()) {
log.debug("md5 加密异常", e);
}
}
return "";
}
public static String byte2hex(byte[] bytes) {
StringBuilder sign = new StringBuilder();
for (int i = 0; i < bytes.length; i++) {
String hex = Integer.toHexString(bytes[i] & 0xFF);
if (hex.length() == 1) {
sign.append("0");
}
sign.append(hex.toUpperCase());
}
return sign.toString();
}
public static byte[] hex2byte(String str) {
if (str == null) {
return null;
}
str = str.trim();
int len = str.length();
if (len <= 0 || len % 2 == 1) {
return null;
}
byte[] b = new byte[len / 2];
try {
for (int i = 0; i < str.length(); i += 2) {
b[(i / 2)] = (byte) Integer.decode("0x" + str.substring(i, i + 2)).intValue();
}
return b;
} catch (Exception e) {
}
return null;
}
/**
* 给TOP请求做MD5签名。
*
* @param sortedParams 所有字符型的TOP请求参数
* @param secret 签名密钥
* @return 签名
* @throws IOException
*/
public static String signRequestNew(Map<String, String> sortedParams, String secret) throws IOException {
// 第一步:把字典按Key的字母顺序排序
List<String> keys = new ArrayList<String>(sortedParams.keySet());
Collections.sort(keys);
// 第二步:把所有参数名和参数值串在一起
StringBuilder query = new StringBuilder();
for (int i = 0; i < keys.size(); i++) {
String key = keys.get(i);
String value = sortedParams.get(key);
if (!StringUtils.isEmpty(key) && !StringUtils.isEmpty(value) && !"sign".equals(key)) {
query.append(key).append("=").append(value);
}
}
log.info("获取当APP请求参数,签名前值为:" + query.toString());
return Md5.encrypt(query.toString(), secret);
}
public static void main(String[] args) {
System.out.println(encrypt("200128008012abc@123", ""));
}
}
package com.jz.dm.common.util;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
/**
* @author ZC
* @PACKAGE_NAME: com.jz.dm.common.util
* @PROJECT_NAME: jz-dm-parent
* @NAME: RedisSerializableUtil
* @DATE: 2021-1-12/18:26
* @DAY_NAME_SHORT: 周二
* @Description:
**/
public class RedisSerializableUtil {
/**
* 序列化
* @param object
*/
public static byte[] serialize(Object object) {
ObjectOutputStream oos = null;
ByteArrayOutputStream baos = null;
try {
// 序列化
baos = new ByteArrayOutputStream();
oos = new ObjectOutputStream(baos);
oos.writeObject(object);
byte[] bytes = baos.toByteArray();
return bytes;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 反序列化
* @param bytes
*/
public static Object unserialize(byte[] bytes) {
ByteArrayInputStream bais = null;
try {
// 反序列化
bais = new ByteArrayInputStream(bytes);
ObjectInputStream ois = new ObjectInputStream(bais);
return ois.readObject();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
...@@ -25,7 +25,6 @@ import java.util.Map; ...@@ -25,7 +25,6 @@ import java.util.Map;
* @author zc * @author zc
*/ */
@RestController @RestController
@RequestMapping("api")
@Api(tags = {"api请求controller"}) @Api(tags = {"api请求controller"})
public class GatewayController { public class GatewayController {
......
...@@ -74,13 +74,13 @@ public class OrganizationManageController { ...@@ -74,13 +74,13 @@ public class OrganizationManageController {
return Mono.fromSupplier(() -> organizationManageService.update(req)); return Mono.fromSupplier(() -> organizationManageService.update(req));
} }
/** /**
* @Description:删除组织 * @Description:注销组织
* @Author: Mr.zhang * @Author: Mr.zhang
* @Date: 2020-12-24 * @Date: 2020-12-24
*/ */
@ApiOperation("删除组织") @ApiOperation("注销组织")
@GetMapping(value = "/deleted") @GetMapping(value = "/logoutOrg")
public Mono<Result> delete(@RequestParam(name = "id")Long id) { public Mono<Result> delete(@RequestParam(name = "id")Long id) {
return Mono.fromSupplier(() -> organizationManageService.delete(id)); return Mono.fromSupplier(() -> organizationManageService.logoutOrg(id));
} }
} }
...@@ -30,11 +30,11 @@ public class ProducerController { ...@@ -30,11 +30,11 @@ public class ProducerController {
/** /**
* @Description:Api制作(自定义) * @Description:获取文件夹列表
* @Author: Mr.zhang * @Author: Mr.zhang
* @Date: 2020-12-26 * @Date: 2020-12-26
*/ */
@ApiOperation("Api制作(获取文件夹列表)") @ApiOperation("获取文件夹列表")
@GetMapping(value = "/getFileCatalog") @GetMapping(value = "/getFileCatalog")
public Mono<Result> getFileCatalog(@RequestParam(name = "projectId")Long projectId, public Mono<Result> getFileCatalog(@RequestParam(name = "projectId")Long projectId,
@RequestParam(name = "pageNum",defaultValue = "1",required = false)String pageNum, @RequestParam(name = "pageNum",defaultValue = "1",required = false)String pageNum,
...@@ -42,11 +42,23 @@ public class ProducerController { ...@@ -42,11 +42,23 @@ public class ProducerController {
return Mono.fromSupplier(() -> Result.of_success(producerService.getFileCatalog(projectId,pageNum,pageSize))); return Mono.fromSupplier(() -> Result.of_success(producerService.getFileCatalog(projectId,pageNum,pageSize)));
} }
/** /**
* @Description:Api制作(自定义) * @Description:创建文件夹
* @Author: Mr.zhang * @Author: Mr.zhang
* @Date: 2020-12-26 * @Date: 2020-12-26
*/ */
@ApiOperation("Api制作(自定义)") @ApiOperation("创建项目文件夹")
@PostMapping(value = "/createProjectFolder")
public Mono<Result> createProjectFolder(@RequestParam(name = "projectId")Long projectId,
@RequestParam(name = "parentId")Long parentId,
@RequestParam(name = "currentUser") String currentUser ) {
return Mono.fromSupplier(() -> producerService.createProjectFolder(projectId,parentId,currentUser));
}
/**
* @Description:Api制作(自定义DMP)
* @Author: Mr.zhang
* @Date: 2020-12-26
*/
@ApiOperation("Api制作(自定义DMP)")
@PostMapping(value = "/addCustomApi") @PostMapping(value = "/addCustomApi")
public Mono<Result> makeCustomApi(@RequestBody @Valid ApiInterfaceReq req) { public Mono<Result> makeCustomApi(@RequestBody @Valid ApiInterfaceReq req) {
return Mono.fromSupplier(() -> Result.of_success(producerService.addCustomApi(req))); return Mono.fromSupplier(() -> Result.of_success(producerService.addCustomApi(req)));
...@@ -86,7 +98,7 @@ public class ProducerController { ...@@ -86,7 +98,7 @@ public class ProducerController {
} }
/** /**
* @Description:保存API基本信息 * @Description:保存API基本信息/自定义API
* @return: (保存API基本信息) * @return: (保存API基本信息)
* @Author: Mr.zhang * @Author: Mr.zhang
* @Date: 2020-12-26 * @Date: 2020-12-26
...@@ -152,4 +164,17 @@ public class ProducerController { ...@@ -152,4 +164,17 @@ public class ProducerController {
@RequestParam(name = "id") Long id) { @RequestParam(name = "id") Long id) {
return Mono.fromSupplier(() -> producerService.getIndicesTypesFields(indices,type,id)); return Mono.fromSupplier(() -> producerService.getIndicesTypesFields(indices,type,id));
} }
@ApiOperation("保存数据到redis中")
@GetMapping(value = "/saveRedis")
public Result saveObjOnRedis() {
return producerService.saveObjOnRedis();
}
@ApiOperation("获取redis中的数据")
@GetMapping(value = "/getRedisObj")
public Result getObjOnRedis() {
return producerService.getObjOnRedis();
}
} }
...@@ -21,6 +21,7 @@ import com.jz.dm.service.ApiInterfaceService; ...@@ -21,6 +21,7 @@ import com.jz.dm.service.ApiInterfaceService;
import com.jz.dm.service.AuthService; import com.jz.dm.service.AuthService;
import com.jz.dm.service.OrganizationManageService; import com.jz.dm.service.OrganizationManageService;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
...@@ -82,7 +83,7 @@ public class AuthFilter extends AbstractFilter { ...@@ -82,7 +83,7 @@ public class AuthFilter extends AbstractFilter {
JSONObject parameter = JSONObject.parseObject(request.getParams()); JSONObject parameter = JSONObject.parseObject(request.getParams());
if (null != parameter) { if (null != parameter) {
String authCode = parameter.getString("authCode"); String authCode = parameter.getString("authCode");
ApiAuth authAuth = authService.getAuthUser(authCode,apiInterface.getId()); ApiAuth authAuth = authService.getAuthUser(authCode, apiInterface.getId());
if (null == authAuth) { if (null == authAuth) {
throw new GatewayException(GatewayResultCode.REQUEST_NOT_AUTH); throw new GatewayException(GatewayResultCode.REQUEST_NOT_AUTH);
} }
...@@ -95,8 +96,8 @@ public class AuthFilter extends AbstractFilter { ...@@ -95,8 +96,8 @@ public class AuthFilter extends AbstractFilter {
} }
chain.doFilter(request, response); chain.doFilter(request, response);
} catch (Exception e) { } catch (Exception e) {
if (e instanceof GatewayException){ if (e instanceof GatewayException) {
throw(GatewayException) e; throw (GatewayException) e;
} }
log.error("~~~~~~~~~~~~~~~~认证过滤异常~~~~~~~~~~~~~~~~~"); log.error("~~~~~~~~~~~~~~~~认证过滤异常~~~~~~~~~~~~~~~~~");
log.error("异常信息:{}", e.getMessage()); log.error("异常信息:{}", e.getMessage());
...@@ -112,6 +113,7 @@ public class AuthFilter extends AbstractFilter { ...@@ -112,6 +113,7 @@ public class AuthFilter extends AbstractFilter {
/** /**
* 校验计费信息 * 校验计费信息
*
* @param request * @param request
* @param authCode * @param authCode
* @param authAuth * @param authAuth
...@@ -127,24 +129,24 @@ public class AuthFilter extends AbstractFilter { ...@@ -127,24 +129,24 @@ public class AuthFilter extends AbstractFilter {
throw new GatewayException(GatewayResultCode.ORG_STATE_EXCEPTION); throw new GatewayException(GatewayResultCode.ORG_STATE_EXCEPTION);
} }
//查询数据银行银行余额是否充足 //查询数据银行银行余额是否充足
getDataAmountResult(request); //getDataAmountResult(request);
try { //记录请求次数(每天限制请求次数) try { //记录请求次数(每天限制请求次数)
String limitKey = request.getApiKey() + LoggingConstants.AND_SPILT + authCode; String limitKey = request.getApiKey() + LoggingConstants.AND_SPILT + authCode;
String reqKey = redisUtils.get(limitKey); Integer reqValue = (Integer)redisUtils.getObj(limitKey);
long timeOut =0; long timeOut = 0;
if (AuthReqTypeEnum.DAY.name().equals(authAuth.getReqType())){ //按天 if (AuthReqTypeEnum.DAY.name().equals(authAuth.getReqType())) { //按天
timeOut = DateUtil.calculateNowResidueTime(); timeOut = DateUtil.calculateNowResidueTime();
}else if (AuthReqTypeEnum.MONTH.name().equals(authAuth.getReqType())){//按月 } else if (AuthReqTypeEnum.MONTH.name().equals(authAuth.getReqType())) {//按月
timeOut=DateUtil.calculateNowMonthTime(); timeOut = DateUtil.calculateNowMonthTime();
}else if (AuthReqTypeEnum.YEAR.name().equals(authAuth.getReqType())){//按年 } else if (AuthReqTypeEnum.YEAR.name().equals(authAuth.getReqType())) {//按年
//暂时不支持年 //暂时不支持年
} }
if (null != reqKey) { if (null != reqValue && reqValue != 0) {
Integer value = Integer.valueOf(reqKey); // Integer value = Integer.valueOf(reqKey);
if (value > authAuth.getReqFrequency()) {//超出最大请求次数 if (reqValue > authAuth.getReqFrequency()) {//超出最大请求次数
throw new GatewayException(GatewayResultCode.REQUEST_LIMIT_EXCEPTION); throw new GatewayException(GatewayResultCode.REQUEST_LIMIT_EXCEPTION);
} else if (value <= authAuth.getReqFrequency()) { } else if (reqValue <= authAuth.getReqFrequency()) {
redisUtils.delAndAdd(limitKey, limitKey, value + 1, timeOut); redisUtils.delAndAdd(limitKey, limitKey, reqValue + 1, timeOut);
} }
} else { } else {
redisUtils.set(limitKey, 1, timeOut); redisUtils.set(limitKey, 1, timeOut);
...@@ -174,20 +176,27 @@ public class AuthFilter extends AbstractFilter { ...@@ -174,20 +176,27 @@ public class AuthFilter extends AbstractFilter {
/** /**
* 按次调用检查余额是否充足 * 按次调用检查余额是否充足
*
* @param request * @param request
*/ */
private void getDataAmountResult(GatewayRequest request) { private void getDataAmountResult(GatewayRequest request) {
JSONObject params = JSONObject.parseObject(request.getParams()); JSONObject params = JSONObject.parseObject(request.getParams());
if (null != params){ Integer assetsId = params.getInteger("assetsId");
Integer userId = params.getInteger("userId");
String dataPrice = params.getString("dataPrice");
if (null == assetsId || null == userId || StringUtils.isBlank(dataPrice)) {
throw new GatewayException(GatewayResultCode.ILLEGAL_ARGUMENT);
}
if (null != params) {
JSONObject pObject = new JSONObject(); JSONObject pObject = new JSONObject();
pObject.put("assetsId",params.getInteger("assetsId")); pObject.put("assetsId", assetsId);
pObject.put("userId",params.getInteger("userId")); pObject.put("userId", userId);
pObject.put("dataPrice",params.getString("dataPrice")); pObject.put("dataPrice", dataPrice);
String respResult = httpUtils.submitPost(balanceUrl, pObject.toString()); String respResult = httpUtils.submitPost(balanceUrl, pObject.toString());
JSONObject result = JSONObject.parseObject(respResult); JSONObject result = JSONObject.parseObject(respResult);
if (null != result){ if (null != result) {
if (200 !=result.getInteger("code")){ if (200 != result.getInteger("code")) {
log.info("~~~~~~~~~~~~~~~~~~异常信息为:{}",result.getString("message")); log.info("~~~~~~~~~~~~~~~~~~异常信息为:{}", result.getString("message"));
throw new GatewayException(GatewayResultCode.CALL_AMOUNT_NOT_ENOUGH); throw new GatewayException(GatewayResultCode.CALL_AMOUNT_NOT_ENOUGH);
} }
} }
......
package com.jz.dm.filter; package com.jz.dm.filter;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.jz.common.utils.Md5;
import com.jz.dm.common.constant.Constants; import com.jz.dm.common.constant.Constants;
import com.jz.dm.common.enums.GatewayResultCode; import com.jz.dm.common.enums.GatewayResultCode;
import com.jz.dm.common.exception.GatewayException; import com.jz.dm.common.exception.GatewayException;
import com.jz.dm.common.exception.SignatureException; import com.jz.dm.common.exception.SignatureException;
import com.jz.dm.common.util.LogUtil; import com.jz.dm.common.util.LogUtil;
import com.jz.dm.common.util.MapUtil; import com.jz.dm.common.util.MapUtil;
import com.jz.dm.common.util.Md5;
import com.jz.dm.models.domian.ApiAuth; import com.jz.dm.models.domian.ApiAuth;
import com.jz.dm.models.enity.GatewayRequest; import com.jz.dm.models.enity.GatewayRequest;
import com.jz.dm.models.enity.GatewayResponse; import com.jz.dm.models.enity.GatewayResponse;
...@@ -42,8 +42,7 @@ public class VerifySignFilter extends AbstractFilter { ...@@ -42,8 +42,7 @@ public class VerifySignFilter extends AbstractFilter {
FilterChain chain) { FilterChain chain) {
try { try {
//对签约参数进行字典排序 //对签约参数进行字典排序
String signParams = MapUtil.getSignValue(request.getApiKey(),request.getMethod(), String signParams = MapUtil.getSignValue(request.getApiKey(),request.getMethod(),request.getSignType());
request.getSignType(),String.valueOf(request.getTimestamp()));
if (StringUtils.isNotBlank(signParams)){ if (StringUtils.isNotBlank(signParams)){
JSONObject jsonObject = JSONObject.parseObject(request.getParams()); JSONObject jsonObject = JSONObject.parseObject(request.getParams());
String authCode = jsonObject.getString("authCode"); String authCode = jsonObject.getString("authCode");
......
...@@ -44,7 +44,7 @@ public class ApiAuth extends BaseObject implements Serializable { ...@@ -44,7 +44,7 @@ public class ApiAuth extends BaseObject implements Serializable {
@TableField("auth_type") @TableField("auth_type")
private String authType; private String authType;
/** /**
* 限类型:DAY 按天,MONTH 按月, YEAR 按年 * 限类型:DAY 按天,MONTH 按月, YEAR 按年
*/ */
@TableField("req_type") @TableField("req_type")
private String reqType; private String reqType;
......
...@@ -49,7 +49,7 @@ public class ApiInterface extends BaseObject implements Serializable { ...@@ -49,7 +49,7 @@ public class ApiInterface extends BaseObject implements Serializable {
private String apiProtocl; private String apiProtocl;
/** /**
* api类型:1 数据银行制作API 2 数据银行制作数据包, 3 API实时接入 6 标签查询 9自定义' * api类型:1 数据银行制作大数据表 2 数据银行制作数据包,3,数据银行制作自定义API 4 API实时接入 5 DMP标签查询 6.DMP大数据表查询 7 DMP自定义'
*/ */
@TableField("api_type") @TableField("api_type")
private String apiType; private String apiType;
...@@ -109,7 +109,7 @@ public class ApiInterface extends BaseObject implements Serializable { ...@@ -109,7 +109,7 @@ public class ApiInterface extends BaseObject implements Serializable {
private String signType; private String signType;
/** /**
* 限类型:DAY 按天,MONTH 按月, YEAR 按年 * 限类型:DAY 按天,MONTH 按月, YEAR 按年
*/ */
@TableField("req_type") @TableField("req_type")
private String reqType; private String reqType;
......
...@@ -37,6 +37,30 @@ public class ApiInterfaceCustom extends BaseObject implements Serializable { ...@@ -37,6 +37,30 @@ public class ApiInterfaceCustom extends BaseObject implements Serializable {
private Long apiInterfaceId; private Long apiInterfaceId;
/**
* 数据源id
*/
@TableField("es_data_source")
private String esDataSource;
/**
* 源数据库名称
*/
@TableField("es_data_base")
private String esDataBase;
/**
* 源数据表名称
*/
@TableField("es_table")
private String esTable;
/**
* 处理类型
*/
@TableField("handle_type")
private String handleType;
/** /**
* api请求参数 * api请求参数
*/ */
......
...@@ -52,7 +52,7 @@ public class ApiInterfaceFile extends BaseObject implements Serializable { ...@@ -52,7 +52,7 @@ public class ApiInterfaceFile extends BaseObject implements Serializable {
* 父类id * 父类id
*/ */
@TableField("parent_id") @TableField("parent_id")
private String parentId; private Long parentId;
/** /**
* 文件英文名称 * 文件英文名称
*/ */
......
...@@ -2,6 +2,7 @@ package com.jz.dm.models.req; ...@@ -2,6 +2,7 @@ package com.jz.dm.models.req;
import com.jz.common.bean.BasePageBean; import com.jz.common.bean.BasePageBean;
import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data; import lombok.Data;
import java.io.Serializable; import java.io.Serializable;
...@@ -18,4 +19,9 @@ import java.io.Serializable; ...@@ -18,4 +19,9 @@ import java.io.Serializable;
@Data @Data
@ApiModel("日志信息列表") @ApiModel("日志信息列表")
public class LogInfoListReq extends BasePageBean implements Serializable { public class LogInfoListReq extends BasePageBean implements Serializable {
@ApiModelProperty(value = "状态:SUCCEED 请求成功, FAIL 请求失败")
private String status;
@ApiModelProperty(value = "ApiKey")
private String apiKey;
} }
...@@ -19,9 +19,7 @@ import java.io.Serializable; ...@@ -19,9 +19,7 @@ import java.io.Serializable;
@Data @Data
@ApiModel(value = "api基本信息") @ApiModel(value = "api基本信息")
public class ApiInterfaceReq implements Serializable { public class ApiInterfaceReq implements Serializable {
@ApiModelProperty(value = "api类型:1 实时接入 2 数据银行制作API, 3 数据银行制作数据包 6标签查询 9自定义",required = true)
@NotNull(message = "api类型不能为空")
public String apiType;
@ApiModelProperty(value = "接口描述",required = false) @ApiModelProperty(value = "接口描述",required = false)
public String apiDesc; public String apiDesc;
...@@ -46,19 +44,22 @@ public class ApiInterfaceReq implements Serializable { ...@@ -46,19 +44,22 @@ public class ApiInterfaceReq implements Serializable {
@NotNull(message="超时时间不能为空") @NotNull(message="超时时间不能为空")
public String timeout; public String timeout;
@ApiModelProperty(value = "限类型:DAY 按天,MONTH 按月, YEAR 按年",required = true) @ApiModelProperty(value = "限类型:DAY 按天,MONTH 按月, YEAR 按年",required = true)
@NotNull(message = "限类型不能为空") @NotNull(message = "限类型不能为空")
public String reqType; public String reqType;
@ApiModelProperty(value = "限制次数",required = true) @ApiModelProperty(value = "限制次数",required = false)
public Long reqFrequency; public Long reqFrequency;
@ApiModelProperty(value = "api描述",required = false) @ApiModelProperty(value = "api描述",required = false)
public String apiFunction; public String apiFunction;
@ApiModelProperty(value = "父类文件id,一级文件夹传入0",required = true) @ApiModelProperty(value = "父类文件id,一级文件夹传入0",required = false)
@NotNull(message="父类id文件id不能为空")
public Long parentId; public Long parentId;
@ApiModelProperty(value = "文件id",required = false)
public Long fileId;
@ApiModelProperty(value = "项目id",required = true) @ApiModelProperty(value = "项目id",required = true)
@NotNull(message="项目id不能为空") @NotNull(message="项目id不能为空")
public Long projectId; public Long projectId;
...@@ -69,5 +70,12 @@ public class ApiInterfaceReq implements Serializable { ...@@ -69,5 +70,12 @@ public class ApiInterfaceReq implements Serializable {
@ApiModelProperty(value = "更新时传入api自增id",required = false) @ApiModelProperty(value = "更新时传入api自增id",required = false)
public Long id; public Long id;
@ApiModelProperty(value = "创建用户",hidden = true)
public String createUser;
@ApiModelProperty(value = "api类型:1.数据银行制作大数据表 " +
"2 数据银行制作数据包,3,数据银行制作自定义API " +
"4 API实时接入 6 标签查询 9自定义",hidden = true)
public String apiType;
} }
...@@ -27,12 +27,12 @@ public class MakeBigDataApiReq implements Serializable { ...@@ -27,12 +27,12 @@ public class MakeBigDataApiReq implements Serializable {
@NotNull(message = "apiType不能为空") @NotNull(message = "apiType不能为空")
private String apiType;*/ private String apiType;*/
@ApiModelProperty(value = "接入类型:对应字典表key",required = true) @ApiModelProperty(value = "apiKey",required = true)
@NotNull(message = "接入类型不能为空") @NotNull(message = "apiKey不能为空")
public String joinType; public String apiKey;
@ApiModelProperty(value = "是否分页",required = false) //@ApiModelProperty(value = "是否分页",required = false)
public Integer page; //public Boolean page;
@ApiModelProperty(value = "数据源Id",required = true) @ApiModelProperty(value = "数据源Id",required = true)
@NotNull(message = "数据源Id不能为空") @NotNull(message = "数据源Id不能为空")
...@@ -40,7 +40,7 @@ public class MakeBigDataApiReq implements Serializable { ...@@ -40,7 +40,7 @@ public class MakeBigDataApiReq implements Serializable {
@ApiModelProperty(value = "源库名称",required = true) @ApiModelProperty(value = "源库名称",required = true)
@NotNull(message = "源库名称不能为空") @NotNull(message = "源库名称不能为空")
private String esDatabase; private String esDataBase;
@ApiModelProperty(value = "源表名称",required = true) @ApiModelProperty(value = "源表名称",required = true)
@NotNull(message = "源表名称不能为空") @NotNull(message = "源表名称不能为空")
...@@ -57,12 +57,24 @@ public class MakeBigDataApiReq implements Serializable { ...@@ -57,12 +57,24 @@ public class MakeBigDataApiReq implements Serializable {
@ApiModelProperty(value = "返回参数",required = true) @ApiModelProperty(value = "返回参数",required = true)
@NotNull(message = "返回参数不能为空") @NotNull(message = "返回参数不能为空")
private String resultParam; private String responseParam;
@ApiModelProperty(value = "段列表",required = true) @ApiModelProperty(value = "段列表",required = true)
@NotNull(message = "字段列表不能为空") @NotNull(message = "字段列表不能为空")
private String tableFields; private String tableFields;
//@ApiModelProperty(value = "项目id",required = true)
//@NotNull(message="项目id不能为空")
//public Long projectId;
//@ApiModelProperty(value = "父类文件id,一级文件夹传入0",required = false)
//public Long parentId;
//
//@ApiModelProperty(value = "文件id",required = false)
//public Long fileId;
} }
...@@ -20,13 +20,13 @@ import java.io.Serializable; ...@@ -20,13 +20,13 @@ import java.io.Serializable;
@ApiModel("数据银行api制作") @ApiModel("数据银行api制作")
public class MakeDataBankApiReq implements Serializable { public class MakeDataBankApiReq implements Serializable {
//@ApiModelProperty(value = "api类型:1 数据银行制作API 2 数据银行制作数据包, 3 API实时接入 6 标签查询 9自定义",required = true) //@ApiModelProperty(value = "api类型:1 数据银行制作大数据表 2 数据银行制作数据包,3,数据银行制作自定义API 4 API实时接入 6 标签查询 9自定义",required = true)
//@NotNull(message = "api类型不能为空") //@NotNull(message = "api类型不能为空")
//public String apiType; //public String apiType;
@ApiModelProperty(value = "传输方式(1为HTTPS,2为HTTP)",required = true) @ApiModelProperty(value = "传输方式(1为HTTPS,2为HTTP)",required = true)
@NotNull(message = "传输方式不能为空") @NotNull(message = "传输方式不能为空")
public String apiProtocl; public String transMode;
@ApiModelProperty(value = "加密方式0 无,1:MD5 2:RSA",required = true) @ApiModelProperty(value = "加密方式0 无,1:MD5 2:RSA",required = true)
@NotNull(message = "加密方式不能为空") @NotNull(message = "加密方式不能为空")
...@@ -44,15 +44,23 @@ public class MakeDataBankApiReq implements Serializable { ...@@ -44,15 +44,23 @@ public class MakeDataBankApiReq implements Serializable {
@NotNull(message = "是否分页不能为空") @NotNull(message = "是否分页不能为空")
public Boolean page; public Boolean page;
@ApiModelProperty(value = "限类型:DAY 按天,MONTH 按月",required = true) @ApiModelProperty(value = "限类型:DAY 按天,MONTH 按月",required = true)
@NotNull(message = "限类型不能为空") @NotNull(message = "限类型不能为空")
public String reqType; public String reqType;
@ApiModelProperty(value = "目标地址",required = true)
@NotNull(message = "目标地址不能为空")
public String targetUrl;
@ApiModelProperty(value = "文件id",required = true) @ApiModelProperty(value = "文件id",required = true)
@NotNull(message = "文件id不能为空") @NotNull(message = "文件id不能为空")
public Long fileId; public Long fileId;
@ApiModelProperty(value = "限制次数",required = true) @ApiModelProperty(value = "签名",required = true)
@NotNull(message = "签名不能为空")
public String sign;
@ApiModelProperty(value = "限制次数",required = false)
public Long reqFrequency; public Long reqFrequency;
@ApiModelProperty(value = "请求地址",required = false) @ApiModelProperty(value = "请求地址",required = false)
...@@ -61,8 +69,7 @@ public class MakeDataBankApiReq implements Serializable { ...@@ -61,8 +69,7 @@ public class MakeDataBankApiReq implements Serializable {
@ApiModelProperty(value = "接口描述",required = false) @ApiModelProperty(value = "接口描述",required = false)
public String apiDesc; public String apiDesc;
@ApiModelProperty(value = "目标地址",required = false)
public String targetUrl;
@ApiModelProperty(value = "超时时间",required = false) @ApiModelProperty(value = "超时时间",required = false)
public String timeout; public String timeout;
...@@ -85,13 +92,12 @@ public class MakeDataBankApiReq implements Serializable { ...@@ -85,13 +92,12 @@ public class MakeDataBankApiReq implements Serializable {
@ApiModelProperty(value = "api样例",required = false) @ApiModelProperty(value = "api样例",required = false)
public String apiExample; public String apiExample;
@ApiModelProperty(value = "创建用户",required = false)
public String createUser;
//-------------------------前端无效传参---------------------- //-------------------------前端无效传参----------------------
//@ApiModelProperty(value = "状态",hidden = true) //@ApiModelProperty(value = "状态",hidden = true)
//public String status; //public String status;
//
//@ApiModelProperty(value = "创建用户",hidden = true)
//public String createUser;
} }
...@@ -42,4 +42,7 @@ public class OrganizationManageAddReq implements Serializable { ...@@ -42,4 +42,7 @@ public class OrganizationManageAddReq implements Serializable {
@ApiModelProperty(value = "备注",required = false) @ApiModelProperty(value = "备注",required = false)
private String remark; private String remark;
@ApiModelProperty(value = "创建用户",required = false)
private String createUser;
} }
...@@ -2,6 +2,7 @@ package com.jz.dm.models.req.organizationManage; ...@@ -2,6 +2,7 @@ package com.jz.dm.models.req.organizationManage;
import com.jz.common.bean.BasePageBean; import com.jz.common.bean.BasePageBean;
import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data; import lombok.Data;
import java.io.Serializable; import java.io.Serializable;
...@@ -18,4 +19,11 @@ import java.io.Serializable; ...@@ -18,4 +19,11 @@ import java.io.Serializable;
@Data @Data
@ApiModel("组织管理查询请求体") @ApiModel("组织管理查询请求体")
public class OrganizationManageListQueryReq extends BasePageBean implements Serializable { public class OrganizationManageListQueryReq extends BasePageBean implements Serializable {
@ApiModelProperty(value = "组织名称")
private String orgName;
@ApiModelProperty(value = "组织编码(组织唯一标识)")
private String orgCode;
} }
...@@ -45,4 +45,9 @@ public class OrganizationManageUpdateReq implements Serializable { ...@@ -45,4 +45,9 @@ public class OrganizationManageUpdateReq implements Serializable {
@ApiModelProperty(value = "备注",required = false) @ApiModelProperty(value = "备注",required = false)
private String remark; private String remark;
@ApiModelProperty(value = "创建用户",required = false)
private String updateUser;
} }
...@@ -47,11 +47,11 @@ public interface OrganizationManageService { ...@@ -47,11 +47,11 @@ public interface OrganizationManageService {
Result update(OrganizationManageUpdateReq req); Result update(OrganizationManageUpdateReq req);
/** /**
* 根据id删除组织 * 根据id注销组织
* @param id * @param id
* @return * @return
*/ */
Result delete(Long id); Result logoutOrg(Long id);
/** /**
* 获取认证组织信息 * 获取认证组织信息
......
...@@ -97,4 +97,18 @@ public interface ProducerService { ...@@ -97,4 +97,18 @@ public interface ProducerService {
* @return * @return
*/ */
IPage<ApiInterfaceFile> getFileCatalog(Long projectId ,String pageNum, String pageSize); IPage<ApiInterfaceFile> getFileCatalog(Long projectId ,String pageNum, String pageSize);
/**
* 创建文件夹
* @param projectId
* @param parentId
* @param currentUser
* @return
*/
Result createProjectFolder(Long projectId, Long parentId,String currentUser);
Result saveObjOnRedis();
Result getObjOnRedis();
} }
...@@ -14,6 +14,7 @@ import com.jz.dm.models.req.LogInfoListReq; ...@@ -14,6 +14,7 @@ import com.jz.dm.models.req.LogInfoListReq;
import com.jz.dm.service.ApiLogService; import com.jz.dm.service.ApiLogService;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject; import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
...@@ -47,6 +48,12 @@ public class ApiLogServiceImpl implements ApiLogService { ...@@ -47,6 +48,12 @@ public class ApiLogServiceImpl implements ApiLogService {
public IPage<ApiReqLog> listApiLog(LogInfoListReq req) { public IPage<ApiReqLog> listApiLog(LogInfoListReq req) {
IPage<ApiReqLog> page = new Page<>(req.getPageNum(), req.getPageSize()); IPage<ApiReqLog> page = new Page<>(req.getPageNum(), req.getPageSize());
QueryWrapper<ApiReqLog> query = new QueryWrapper<>(); QueryWrapper<ApiReqLog> query = new QueryWrapper<>();
if (StringUtils.isNotBlank(req.getApiKey())){
query.eq("api_key",req.getApiKey());
}
if (StringUtils.isNotBlank(req.getStatus())){
query.eq("status",req.getStatus());
}
query.eq("is_deleted",0); query.eq("is_deleted",0);
query.orderByDesc("create_date"); query.orderByDesc("create_date");
return apiReqLogMapper.selectPage(page, query); return apiReqLogMapper.selectPage(page, query);
......
...@@ -19,7 +19,6 @@ import com.jz.dm.service.OrganizationManageService; ...@@ -19,7 +19,6 @@ import com.jz.dm.service.OrganizationManageService;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils; import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import javax.annotation.Resource; import javax.annotation.Resource;
...@@ -42,8 +41,6 @@ public class OrganizationManageImpl implements OrganizationManageService { ...@@ -42,8 +41,6 @@ public class OrganizationManageImpl implements OrganizationManageService {
@Resource @Resource
private ApiOrgMapper apiOrgMapper; private ApiOrgMapper apiOrgMapper;
@Resource
private RedisTemplate redisTemplate;
/** /**
* 组织列表信息查询 * 组织列表信息查询
...@@ -55,7 +52,14 @@ public class OrganizationManageImpl implements OrganizationManageService { ...@@ -55,7 +52,14 @@ public class OrganizationManageImpl implements OrganizationManageService {
public IPage<ApiOrg> listOrganization(OrganizationManageListQueryReq req) { public IPage<ApiOrg> listOrganization(OrganizationManageListQueryReq req) {
IPage<ApiOrg> page = new Page<>(req.getPageNum(), req.getPageSize()); IPage<ApiOrg> page = new Page<>(req.getPageNum(), req.getPageSize());
QueryWrapper<ApiOrg> query = new QueryWrapper<>(); QueryWrapper<ApiOrg> query = new QueryWrapper<>();
if (StringUtils.isNotBlank(req.getOrgName())){
query.eq("org_name",req.getOrgName());
}
if (StringUtils.isNotBlank(req.getOrgCode())){
query.eq("org_code",req.getOrgCode());
}
query.eq("is_deleted", 0); query.eq("is_deleted", 0);
query.ne("status",OrgStatusEnum.CANCEL);
query.orderByDesc("create_date"); query.orderByDesc("create_date");
return apiOrgMapper.selectPage(page, query); return apiOrgMapper.selectPage(page, query);
} }
...@@ -71,6 +75,7 @@ public class OrganizationManageImpl implements OrganizationManageService { ...@@ -71,6 +75,7 @@ public class OrganizationManageImpl implements OrganizationManageService {
QueryWrapper<ApiOrg> query = new QueryWrapper<>(); QueryWrapper<ApiOrg> query = new QueryWrapper<>();
query.eq("is_deleted", 0); query.eq("is_deleted", 0);
query.eq("id", req.getId()); query.eq("id", req.getId());
query.ne("status",OrgStatusEnum.CANCEL);
return Result.of_success(apiOrgMapper.selectOne(query)); return Result.of_success(apiOrgMapper.selectOne(query));
} }
...@@ -82,16 +87,18 @@ public class OrganizationManageImpl implements OrganizationManageService { ...@@ -82,16 +87,18 @@ public class OrganizationManageImpl implements OrganizationManageService {
*/ */
@Override @Override
public Result add(OrganizationManageAddReq req) { public Result add(OrganizationManageAddReq req) {
/* SysUserDto currentUser = (SysUserDto)redisTemplate.opsForValue().get("user"+ RedisMessageConstant.SENDTYPE_LOGIN_SYS);
if (null == currentUser){
return Result.of_error(ResultMsg.USER_NOT_EXIST);
}*/
if (StringUtils.isNotBlank(req.getOrgName())) { if (StringUtils.isNotBlank(req.getOrgName())) {
ApiOrg orgNameInfo = getOrgNameInfo(req.getOrgName()); ApiOrg orgNameInfo = getOrgNameInfo(req.getOrgName());
if (null != orgNameInfo) { if (null != orgNameInfo) {
return Result.of_error("组织名称已存在!"); return Result.of_error("组织名称已存在!");
} }
} }
if (StringUtils.isNotBlank(req.getOrgType())) {
if (!Constants.AUTH_INT.equals(req.getOrgType()) ||
!Constants.AUTH_OUT.equals(req.getOrgType())) {
return Result.of_error("组织类型不存在!");
}
}
String coding = ""; String coding = "";
ApiOrg apiOrg = new ApiOrg(); ApiOrg apiOrg = new ApiOrg();
BeanUtils.copyProperties(req, apiOrg); BeanUtils.copyProperties(req, apiOrg);
...@@ -106,7 +113,6 @@ public class OrganizationManageImpl implements OrganizationManageService { ...@@ -106,7 +113,6 @@ public class OrganizationManageImpl implements OrganizationManageService {
} }
apiOrg.setOrgCode(coding);//组织编码 apiOrg.setOrgCode(coding);//组织编码
apiOrg.setStatus(OrgStatusEnum.NORMAL.name());//正常 apiOrg.setStatus(OrgStatusEnum.NORMAL.name());//正常
//apiOrg.setCreateUser(currentUser.getUserName());
if (apiOrgMapper.insert(apiOrg) > 0) { if (apiOrgMapper.insert(apiOrg) > 0) {
return Result.of_success(ResultMsg.INSERT_SUCCESS); return Result.of_success(ResultMsg.INSERT_SUCCESS);
} }
...@@ -140,23 +146,22 @@ public class OrganizationManageImpl implements OrganizationManageService { ...@@ -140,23 +146,22 @@ public class OrganizationManageImpl implements OrganizationManageService {
*/ */
@Override @Override
public Result update(OrganizationManageUpdateReq req) { public Result update(OrganizationManageUpdateReq req) {
/* SysUserDto currentUser = (SysUserDto) redisTemplate.opsForValue().get("user" + RedisMessageConstant.SENDTYPE_LOGIN_SYS);
if (null == currentUser) {
return Result.of_error(ResultMsg.USER_NOT_EXIST);
}*/
ApiOrg apiOrg = apiOrgMapper.selectById(req.getId()); ApiOrg apiOrg = apiOrgMapper.selectById(req.getId());
if (null == apiOrg) { if (null == apiOrg) {
return Result.of_error("组织信息不存在!"); return Result.of_error("组织信息不存在!");
} }
if (StringUtils.isNotBlank(req.getStatus())) { if (StringUtils.isNotBlank(req.getStatus())) {
if (null == fromTypeName(req.getStatus())){ if (null == fromTypeName(req.getStatus())) {
return Result.of_error("更新组织状态不存在!"); return Result.of_error("更新组织状态不存在!");
} }
} }
//原状态为注销状态不可复原
if (OrgStatusEnum.CANCEL.equals(apiOrg.getStatus())){
return Result.of_error("注销状态不可修改");
}
ApiOrg apiOrgUpdate = new ApiOrg(); ApiOrg apiOrgUpdate = new ApiOrg();
BeanUtils.copyProperties(req, apiOrgUpdate); BeanUtils.copyProperties(req, apiOrgUpdate);
apiOrgUpdate.setUpdateDate(new Date()); apiOrgUpdate.setUpdateDate(new Date());
//apiOrgUpdate.setUpdateUser(currentUser.getUserName());
if (apiOrgMapper.updateById(apiOrgUpdate) > 0) { if (apiOrgMapper.updateById(apiOrgUpdate) > 0) {
return Result.of_success(ResultMsg.UPDATE_SUCCESS); return Result.of_success(ResultMsg.UPDATE_SUCCESS);
} }
...@@ -164,37 +169,39 @@ public class OrganizationManageImpl implements OrganizationManageService { ...@@ -164,37 +169,39 @@ public class OrganizationManageImpl implements OrganizationManageService {
} }
/** /**
* 删除组织 * 注销组织
* *
* @param id * @param id
* @return * @return
*/ */
@Override @Override
public Result delete(Long id) { public Result logoutOrg(Long id) {
ApiOrg apiOrg = apiOrgMapper.selectById(id); ApiOrg apiOrg = apiOrgMapper.selectById(id);
if (null == apiOrg) { if (null == apiOrg) {
return Result.of_error(ResultMsg.DATA_NOT_EXIST); return Result.of_error(ResultMsg.DATA_NOT_EXIST);
} }
UpdateWrapper<ApiOrg> delete = new UpdateWrapper<>(); UpdateWrapper<ApiOrg> delete = new UpdateWrapper<>();
delete.set("is_deleted", 1); delete.set("is_deleted", 1);
delete.set("status",OrgStatusEnum.CANCEL);
delete.eq("id", id); delete.eq("id", id);
if (apiOrgMapper.update(null, delete) > 0) { if (apiOrgMapper.update(null, delete) > 0) {
return Result.of_success(ResultMsg.DELETE_SUCCESS); return Result.of_success(ResultMsg.UPDATE_SUCCESS);
} }
return Result.of_success(ResultMsg.DELETE_FAIL); return Result.of_success(ResultMsg.UPDATE_FAIL);
} }
/** /**
* 获取认证组织信息 * 获取认证组织信息
*
* @param apiOrgId * @param apiOrgId
* @return * @return
*/ */
@Override @Override
public ApiOrg getAuthOrganization(Long apiOrgId) { public ApiOrg getAuthOrganization(Long apiOrgId) {
QueryWrapper<ApiOrg> query = new QueryWrapper<>(); QueryWrapper<ApiOrg> query = new QueryWrapper<>();
query.eq("id",apiOrgId); query.eq("id", apiOrgId);
query.eq("status", OrgStatusEnum.NORMAL.name()); query.eq("status", OrgStatusEnum.NORMAL.name());
query.eq("is_deleted",0); query.eq("is_deleted", 0);
return apiOrgMapper.selectOne(query); return apiOrgMapper.selectOne(query);
} }
......
...@@ -11,6 +11,7 @@ import com.jz.common.constant.ResultCode; ...@@ -11,6 +11,7 @@ import com.jz.common.constant.ResultCode;
import com.jz.common.constant.ResultMsg; import com.jz.common.constant.ResultMsg;
import com.jz.common.exception.ResponseException; import com.jz.common.exception.ResponseException;
import com.jz.common.utils.HttpsUtils; import com.jz.common.utils.HttpsUtils;
import com.jz.common.utils.Md5;
import com.jz.common.utils.RedisUtils; import com.jz.common.utils.RedisUtils;
import com.jz.common.utils.Result; import com.jz.common.utils.Result;
import com.jz.dm.common.constant.TagConstants; import com.jz.dm.common.constant.TagConstants;
...@@ -22,6 +23,7 @@ import com.jz.dm.common.util.RandomUtil; ...@@ -22,6 +23,7 @@ import com.jz.dm.common.util.RandomUtil;
import com.jz.dm.mapper.*; import com.jz.dm.mapper.*;
import com.jz.dm.models.domian.*; import com.jz.dm.models.domian.*;
import com.jz.dm.models.req.make.*; import com.jz.dm.models.req.make.*;
import com.jz.dm.service.ApiInterfaceService;
import com.jz.dm.service.ProducerService; import com.jz.dm.service.ProducerService;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.CollectionUtils;
...@@ -29,7 +31,6 @@ import org.apache.commons.lang3.StringUtils; ...@@ -29,7 +31,6 @@ import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils; import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
...@@ -66,7 +67,7 @@ public class ProducerServiceImpl implements ProducerService { ...@@ -66,7 +67,7 @@ public class ProducerServiceImpl implements ProducerService {
@Resource @Resource
private ApiInterfaceFileMapper apiInterfaceFileMapper; private ApiInterfaceFileMapper apiInterfaceFileMapper;
@Autowired @Autowired
private RedisTemplate<String, Object> redisTemplate; private ApiInterfaceService apiInterfaceService;
@Autowired @Autowired
private RedisUtils redisUtils; private RedisUtils redisUtils;
@Autowired @Autowired
...@@ -79,27 +80,66 @@ public class ProducerServiceImpl implements ProducerService { ...@@ -79,27 +80,66 @@ public class ProducerServiceImpl implements ProducerService {
//@Value("${dmp.openapi.env.open:false}") //@Value("${dmp.openapi.env.open:false}")
//private boolean envOpen = false; //private boolean envOpen = false;
@Value("${dmp.ignoreRedis}") @Value("${dmp.ignoreRedis}")
protected boolean ignoreRedis; private boolean ignoreRedis;
/**
* dataBank签名token
*/
@Value("${token.dataBank}")
private String dataBankToken;
/** /**
* 获取文件列表 * 获取文件列表
*
* @param projectId * @param projectId
* @param pageSize * @param pageSize
* @param pageNum * @param pageNum
* @return * @return
*/ */
@Override @Override
public IPage<ApiInterfaceFile> getFileCatalog(Long projectId,String pageNum, String pageSize) { public IPage<ApiInterfaceFile> getFileCatalog(Long projectId, String pageNum, String pageSize) {
Integer pageN = Integer.valueOf(pageNum); Integer pageN = Integer.valueOf(pageNum);
Integer pageS = Integer.valueOf(pageSize); Integer pageS = Integer.valueOf(pageSize);
IPage<ApiInterfaceFile> page = new Page<>(pageN, pageS); IPage<ApiInterfaceFile> page = new Page<>(pageN, pageS);
QueryWrapper<ApiInterfaceFile> query = new QueryWrapper<>(); QueryWrapper<ApiInterfaceFile> query = new QueryWrapper<>();
query.eq("project_id",projectId); query.eq("project_id", projectId);
query.eq("is_deleted", 0); query.eq("is_deleted", 0);
query.orderByDesc("create_date"); query.orderByDesc("create_date");
return apiInterfaceFileMapper.selectPage(page, query); return apiInterfaceFileMapper.selectPage(page, query);
} }
/**
* 创建文件夹
*
* @param projectId
* @param parentId
* @param currentUser
* @return
*/
@Override
public Result createProjectFolder(Long projectId, Long parentId, String currentUser) {
QueryWrapper<ApiInterfaceFile> query = new QueryWrapper<>();
query.eq("id", parentId);
query.eq("is_deleted", 0);
ApiInterfaceFile apiInterfaceFile = apiInterfaceFileMapper.selectOne(query);
if (null == apiInterfaceFile) {
return Result.of_error("父级文件夹不存在!");
}
ApiInterfaceFile instanceFile = new ApiInterfaceFile();
instanceFile.setProjectId(projectId);
instanceFile.setFileSource("1");//文件来源:1 DMP 2 数据银行
instanceFile.setParentId(parentId);
instanceFile.setStatus(GeneralStatusTypeEnum.VALID.name());
instanceFile.setCreateUser(currentUser);
instanceFile.setRemark("DMP创建层级文件夹");
if (apiInterfaceFileMapper.insert(instanceFile) > 0) {
return Result.of_error(ResultMsg.INSERT_SUCCESS);
}
return Result.of_error(ResultMsg.INSERT_FAIL);
}
/** /**
* DMP制作自定义Api * DMP制作自定义Api
* *
...@@ -112,7 +152,7 @@ public class ProducerServiceImpl implements ProducerService { ...@@ -112,7 +152,7 @@ public class ProducerServiceImpl implements ProducerService {
} }
/** /**
* 数据银行制作API/数据包 * 数据银行制作API/数据包/自定义
* *
* @param req * @param req
* @return * @return
...@@ -120,60 +160,100 @@ public class ProducerServiceImpl implements ProducerService { ...@@ -120,60 +160,100 @@ public class ProducerServiceImpl implements ProducerService {
@Override @Override
@Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW) @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
public Result addDataBankApiInfo(MakeDataBankApiReq req) { public Result addDataBankApiInfo(MakeDataBankApiReq req) {
//SysUserDto currentUser = getLoginUser(RedisMessageConstant.SENDTYPE_LOGIN_SYS); QueryWrapper<ApiInterfaceFile> query = new QueryWrapper<>();
//if (null == currentUser) { query.eq("file_source", "2");
// return Result.of_error(ResultMsg.USER_NOT_LOGIN); query.eq("is_deleted", 0);
//} List<ApiInterfaceFile> fileSource = apiInterfaceFileMapper.selectList(query);
List<ApiInterfaceFile> fileSource =
apiInterfaceFileMapper.selectList(new QueryWrapper<ApiInterfaceFile>().eq("file_source", "2"));
if (fileSource.size() == 0 || fileSource.size() >= 2) { if (fileSource.size() == 0 || fileSource.size() >= 2) {
return Result.of_error("文件夹信息异常!"); return Result.of_error("文件夹信息异常!");
} }
if (StringUtils.isNotBlank(req.getOutputType()) && if (StringUtils.isNotBlank(req.getOutputType()) &&
(!req.getOutputType().contains(ApiInfoOutTypeEnum.JSON.name()) || (!req.getOutputType().contains(ApiInfoOutTypeEnum.JSON.name()) ||
!req.getOutputType().contains(ApiInfoOutTypeEnum.FLOW.name()) )){ !req.getOutputType().contains(ApiInfoOutTypeEnum.FLOW.name()))) {
return Result.of_error("输出类型不存在!"); return Result.of_error("输出类型不存在!");
} }
if(StringUtils.isNotBlank(req.getReqType()) ){ if (StringUtils.isNotBlank(req.getReqType())) {
if (null == fromAuthReqTypeEnum(req.getReqType())){ if (null == fromAuthReqTypeEnum(req.getReqType())) {
return Result.of_error("限制类型不存在!"); return Result.of_error("限流类型不存在!");
} }
} }
String apiKey =""; String signStr = dataBankToken + req.getJoinType() + System.currentTimeMillis();
if (StringUtils.isNotBlank(req.getJoinType()) String signResult = Md5.encrypt(signStr, "");
&& "10006".equals(req.getJoinType())) {//数据银行制作API if (!signResult.equals(req.getSign())) {
apiKey = RandomUtil.getStringRandom(16); return Result.of_error("签名错误!");
ApiInterface anInterface = new ApiInterface(); }
//anInterface.setCreateUser(currentUser.getUserName()); String apiKey = getApiKey();
anInterface.setApiType("2");//数据银行制作api switch (req.getJoinType()) {
anInterface.setStatus(ProducerStatusTypeEnum.ISSUE.name());//发布 case "10006"://数据银行三方上传
anInterface.setApiKey(apiKey);//apiKey saveDataBanker(req, apiKey, "3");
BeanUtils.copyProperties(req, anInterface); break;
int resIn = apiInterfaceMapper.insert(anInterface); case "10007"://数据银行数据包上传
ApiInterfaceCustom interfaceCustom = new ApiInterfaceCustom(); saveDataBanker(req, apiKey, "2");
//interfaceCustom.setCreateUser(currentUser.getUserName()); break;
interfaceCustom.setApiKey(apiKey); case "10008"://数据银行制作大数据表
interfaceCustom.setApiInterfaceId(anInterface.getId()); saveDataBanker(req, apiKey, "1");
BeanUtils.copyProperties(req, interfaceCustom); break;
int resOut = apiInterfaceCustomMapper.insert(interfaceCustom); default:
if (resOut == 0 || resIn == 0) { return Result.of_error("接入类型不存在!");
throw ResponseException.of_error("保存信息失败!"); }
} return Result.of_success(ResultMsg.INSERT_SUCCESS, apiKey);
redisUtils.set(apiKey,req); }
} else if (StringUtils.isNotBlank(req.getJoinType())
&& "10007".equals(req.getJoinType())) {//数据银行制作数据包 /**
if (StringUtils.isBlank(req.getTargetUrl())) {//目标地址 * 保存数据银行api信息并缓存
return Result.of_error("目标地址为空!"); *
} * @param req 请求参数
ApiInterfaceReq apiInterfaceReq = new ApiInterfaceReq(); * @param apiKey apiKey
apiInterfaceReq.setApiType("2"); * @param apiType api类型
apiInterfaceReq.setTransMode(req.getApiProtocl());//请求方式:https http */
BeanUtils.copyProperties(req,apiInterfaceReq); private void saveDataBanker(MakeDataBankApiReq req, String apiKey, String apiType) {
Result result = saveInterfaceAPi(apiInterfaceReq); ApiInterface apiInterface = saveApiInterFace(req, apiKey, apiType);
apiKey=(String) result.getData(); saveApiInterFaceCustom(req, apiKey, apiInterface.getId());
redisUtils.set(apiKey,req); JSONObject object = new JSONObject();
} object.put("targetUrl",req.getTargetUrl());
return Result.of_success(ResultMsg.INSERT_SUCCESS,apiKey); object.put("outputType",req.getOutputType());
saveObjOnRedis(apiInterface.getApiKey(),object);
}
/**
* 保存api基本信息
*
* @param req
* @param apiKey
* @param apiType
* @return
*/
private ApiInterface saveApiInterFace(MakeDataBankApiReq req,
String apiKey, String apiType) {
ApiInterface anInterface = new ApiInterface();
anInterface.setApiType(apiType);//数据银行制作大数据表
anInterface.setStatus(ProducerStatusTypeEnum.ISSUE.name());//发布
anInterface.setApiKey(apiKey);//apiKey
BeanUtils.copyProperties(req, anInterface);
if (apiInterfaceMapper.insert(anInterface) == 0) {
throw ResponseException.of(ResultCode.FAILURE, "保存api基本信息异常!");
}
return anInterface;
}
/**
* 保存APi扩展信息
*
* @param req
* @param apiKey
* @param interFaceId
* @return
*/
private ApiInterfaceCustom saveApiInterFaceCustom(MakeDataBankApiReq req, String apiKey,
Long interFaceId) {
ApiInterfaceCustom interfaceCustom = new ApiInterfaceCustom();
interfaceCustom.setApiKey(apiKey);
interfaceCustom.setApiInterfaceId(interFaceId);
BeanUtils.copyProperties(req, interfaceCustom);
if (apiInterfaceCustomMapper.insert(interfaceCustom) == 0) {
throw ResponseException.of(ResultCode.FAILURE, "保存api扩展信息异常!");
}
return interfaceCustom;
} }
/** /**
...@@ -189,7 +269,7 @@ public class ProducerServiceImpl implements ProducerService { ...@@ -189,7 +269,7 @@ public class ProducerServiceImpl implements ProducerService {
} }
/** /**
* Api制作(大数据查询/标签查询) * DMP大数据查询/标签查询
* *
* @param req * @param req
* @return * @return
...@@ -197,18 +277,24 @@ public class ProducerServiceImpl implements ProducerService { ...@@ -197,18 +277,24 @@ public class ProducerServiceImpl implements ProducerService {
@Override @Override
@Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW) @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
public Result addBigDataMakeApi(MakeBigDataApiReq req) { public Result addBigDataMakeApi(MakeBigDataApiReq req) {
SysUserDto currentUser = getLoginUser(RedisMessageConstant.SENDTYPE_LOGIN_SYS); SysUserDto currentUser = getLoginUser("004");
if (null == currentUser) { if (null == currentUser) {
return Result.of_error("用户信息不存在"); return Result.of_error("用户信息不存在");
} }
ApiInterface apiInterface = apiInterfaceService.getApiInfo(req.getApiKey());
if (null == apiInterface) {
return Result.of_error("API基本信息为空!");
}
QueryWrapper<ApiOpenApiEsFields> queryOpenApi = new QueryWrapper<>(); QueryWrapper<ApiOpenApiEsFields> queryOpenApi = new QueryWrapper<>();
queryOpenApi.eq("es_database", req.getEsDatabase()); queryOpenApi.eq("es_database", req.getEsDataBase());
queryOpenApi.eq("es_table", req.getEsTable()); queryOpenApi.eq("es_table", req.getEsTable());
queryOpenApi.eq("is_deleted", 0); queryOpenApi.eq("is_deleted", 0);
List<ApiOpenApiEsFields> listOpenApiEsFields = apiOpenApiEsFieldsMapper.selectList(queryOpenApi); List<ApiOpenApiEsFields> listOpenApiEsFields = apiOpenApiEsFieldsMapper.selectList(queryOpenApi);
//如果存在先根据库,表删除,重新添加 //如果存在先根据库,表删除,重新添加
if (CollectionUtils.isNotEmpty(listOpenApiEsFields)) { if (CollectionUtils.isNotEmpty(listOpenApiEsFields)) {
Map paMap = new HashMap<>(); Map paMap = new HashMap<>();
paMap.put("es_database", req.getEsDataBase());
paMap.put("es_table", req.getEsTable());
apiOpenApiEsFieldsMapper.deleteByMap(paMap); apiOpenApiEsFieldsMapper.deleteByMap(paMap);
} }
ArrayList<ApiOpenApiEsFields> listApiEsFields = new ArrayList<>(); ArrayList<ApiOpenApiEsFields> listApiEsFields = new ArrayList<>();
...@@ -217,7 +303,7 @@ public class ProducerServiceImpl implements ProducerService { ...@@ -217,7 +303,7 @@ public class ProducerServiceImpl implements ProducerService {
for (int i = 0; i < json.size(); i++) { for (int i = 0; i < json.size(); i++) {
JSONObject jsonObject = (JSONObject) json.get(i); JSONObject jsonObject = (JSONObject) json.get(i);
ApiOpenApiEsFields fields = new ApiOpenApiEsFields(); ApiOpenApiEsFields fields = new ApiOpenApiEsFields();
fields.setEsDatabase(req.getEsDatabase()); fields.setEsDatabase(req.getEsDataBase());
fields.setEsTable(req.getEsTable()); fields.setEsTable(req.getEsTable());
fields.setFieldName(jsonObject.get("name").toString()); fields.setFieldName(jsonObject.get("name").toString());
fields.setFieldType(jsonObject.get("type").toString()); fields.setFieldType(jsonObject.get("type").toString());
...@@ -231,24 +317,31 @@ public class ProducerServiceImpl implements ProducerService { ...@@ -231,24 +317,31 @@ public class ProducerServiceImpl implements ProducerService {
} }
ApiSyncingDatasource dataSource = apiSyncingDatasourceMapper.selectById(req.getEsDataSource()); ApiSyncingDatasource dataSource = apiSyncingDatasourceMapper.selectById(req.getEsDataSource());
//api信息在redis中的key //api信息在redis中的key
String redisValueOfKey = RandomUtil.getStringRandom(16); String redisValueOfKey = apiInterface.getApiKey();
if (null != dataSource) { if (null != dataSource) {
//存入调用的基本ApiKey信息
redisTemplate.opsForValue().set( redisValueOfKey, req);
//esjdbc 连接地址 用于接口中调用获取es数据 //esjdbc 连接地址 用于接口中调用获取es数据
redisTemplate.opsForValue().set(TagConstants.OPEN_API_ESTAG_JDBC_INFO_NAMESPACE + redisValueOfKey, dataSource.getJdbcUrl()); redisUtils.set(TagConstants.OPEN_API_ESTAG_JDBC_INFO_NAMESPACE + redisValueOfKey, dataSource.getJdbcUrl());
} }
int result = 0; int result = 0;
ApiOpenApiEsTagconfig apiEsTagconfig = new ApiOpenApiEsTagconfig(); ApiInterfaceCustom interfaceCustom = new ApiInterfaceCustom();
//ApiOpenApiEsTagconfig apiEsTagconfig = new ApiOpenApiEsTagconfig();
if (null != req.getId() && !"".equals(req.getId())) {//更新 if (null != req.getId() && !"".equals(req.getId())) {//更新
apiEsTagconfig.setUpdateDate(new Date()); /* apiEsTagconfig.setUpdateDate(new Date());
apiEsTagconfig.setUpdateUser(currentUser.getUserName()); apiEsTagconfig.setUpdateUser(currentUser.getUserName());
BeanUtils.copyProperties(req, apiEsTagconfig); BeanUtils.copyProperties(req, apiEsTagconfig);
result = apiOpenApiEsTagconfigMapper.updateById(apiEsTagconfig); result = apiOpenApiEsTagconfigMapper.updateById(apiEsTagconfig);*/
BeanUtils.copyProperties(req, interfaceCustom);
interfaceCustom.setUpdateDate(new Date());
interfaceCustom.setUpdateUser(currentUser.getUserName());
result = apiInterfaceCustomMapper.updateById(interfaceCustom);
} else { //保存 } else { //保存
apiEsTagconfig.setCreateUser(currentUser.getUserName()); BeanUtils.copyProperties(req, interfaceCustom);
interfaceCustom.setCreateUser(currentUser.getUserName());
interfaceCustom.setApiInterfaceId(apiInterface.getId());
result = apiInterfaceCustomMapper.insert(interfaceCustom);
/* apiEsTagconfig.setCreateUser(currentUser.getUserName());
BeanUtils.copyProperties(req, apiEsTagconfig); BeanUtils.copyProperties(req, apiEsTagconfig);
result = apiOpenApiEsTagconfigMapper.insert(apiEsTagconfig); result = apiOpenApiEsTagconfigMapper.insert(apiEsTagconfig);*/
} }
if (result <= 0) { if (result <= 0) {
return Result.of_error(ResultMsg.FAILURE); return Result.of_error(ResultMsg.FAILURE);
...@@ -257,7 +350,7 @@ public class ProducerServiceImpl implements ProducerService { ...@@ -257,7 +350,7 @@ public class ProducerServiceImpl implements ProducerService {
} }
/** /**
* 保存api基本信息 * DMP保存api基本信息/自定义API
* *
* @param req * @param req
* @return * @return
...@@ -265,46 +358,27 @@ public class ProducerServiceImpl implements ProducerService { ...@@ -265,46 +358,27 @@ public class ProducerServiceImpl implements ProducerService {
@Override @Override
@Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED) @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
public Result saveInterfaceAPi(ApiInterfaceReq req) { public Result saveInterfaceAPi(ApiInterfaceReq req) {
SysUserDto currentUser = getLoginUser(RedisMessageConstant.SENDTYPE_LOGIN_SYS); if (StringUtils.isNotBlank(req.getReqType())) {
if (null == currentUser) { if (null == fromAuthReqTypeEnum(req.getReqType())) {
return Result.of_error("用户信息不存在"); return Result.of_error("限流类型不存在!");
}
if(StringUtils.isNotBlank(req.getReqType()) ){
if (null == fromAuthReqTypeEnum(req.getReqType())){
return Result.of_error("限制类型不存在!");
}
}
QueryWrapper<ApiInterfaceFile> query = new QueryWrapper<>();
query.eq("project_id", req.getProjectId());
query.eq("parent_id", req.getParentId());
ApiInterfaceFile file = apiInterfaceFileMapper.selectOne(query);
if (null == file) {
//查询父类是否存在
ApiInterfaceFile parentId = apiInterfaceFileMapper.selectOne(new QueryWrapper<ApiInterfaceFile>().eq("parent_id", req.getParentId()));
if (null == parentId && "0".equals(req.getParentId())){
file= new ApiInterfaceFile();
file.setProjectId(req.getProjectId());
file.setFileSource("1");//dmp
file.setParentId("0");
file.setStatus(GeneralStatusTypeEnum.VALID.name());
file.setCreateUser("");
file.setRemark("创建文件夹");
if ( apiInterfaceFileMapper.insert(file) == 0){
throw ResponseException.of_error("创建文件夹失败!");
}
}else {
throw ResponseException.of(ResultCode.FAILURE,"父类文件信息不存在!");
} }
} }
//生成ApiKey //生成ApiKey
String apiKey = RandomUtil.getStringRandom(16); String apiKey = getApiKey();
ApiInterface apiInterface = new ApiInterface(); ApiInterface apiInterface = new ApiInterface();
if (null == req.getFileId()) {//创建下级文件夹
Long fileId = checkFileExist(req.getProjectId(), req.getParentId(), req.getCreateUser());
req.setFileId(fileId);
}
BeanUtils.copyProperties(req, apiInterface);
apiInterface.setApiKey(apiKey); apiInterface.setApiKey(apiKey);
apiInterface.setApiProtocl(req.getTransMode());//传输方式 https http apiInterface.setApiProtocl(req.getTransMode());//传输方式 https http
apiInterface.setStatus(ApiStatusEnum.ISSUE.name());//发布 apiInterface.setStatus(ApiStatusEnum.ISSUE.name());//发布
apiInterface.setFileId(file.getId()); if ("10004".equals(req.getJoinType())) {//dmp自定义
BeanUtils.copyProperties(req, apiInterface); apiInterface.setApiType("7");
apiInterface.setCreateUser(currentUser.getUserName()); } else if ("10002".equals(req.getJoinType())) {//大数据表查询
apiInterface.setApiType("6");
}
Long timeout = Long.parseLong(req.getTimeout()); Long timeout = Long.parseLong(req.getTimeout());
if (timeout == null || timeout == 0) { if (timeout == null || timeout == 0) {
apiInterface.setTimeout(String.valueOf(defaultTimeout)); apiInterface.setTimeout(String.valueOf(defaultTimeout));
...@@ -316,9 +390,78 @@ public class ProducerServiceImpl implements ProducerService { ...@@ -316,9 +390,78 @@ public class ProducerServiceImpl implements ProducerService {
if (apiInterfaceMapper.insert(apiInterface) == 0) { if (apiInterfaceMapper.insert(apiInterface) == 0) {
throw ResponseException.of_error("保存Api信息失败!"); throw ResponseException.of_error("保存Api信息失败!");
} }
//缓存到redis中 JSONObject object = new JSONObject();
redisUtils.set(apiKey,req); object.put("targetUrl",req.getTargetUrl());
return Result.of_success(ResultMsg.INSERT_SUCCESS,apiKey); object.put("outputType",ApiInfoOutTypeEnum.JSON.name());
saveObjOnRedis(apiInterface.getApiKey(),object);
return Result.of_success(ResultMsg.INSERT_SUCCESS, apiKey);
}
/**
* 缓存数据
*
* @param apiKey
* @param params
*/
private void saveObjOnRedis(String apiKey, JSONObject params) {
if (StringUtils.isBlank(apiKey) || null == params) {
log.info("--------------缓存数据为空");
return;
}
try {
String paramKey = redisUtils.get(apiKey);
if (null != paramKey){
redisUtils.del(apiKey);
}
redisUtils.set(apiKey, params.toString());
} catch (Exception ex) {
log.error("缓存api制作数据异常:{}",ex.getMessage());
ex.printStackTrace();
}
}
/**
* 校验文件夹信息
*
* @param projectId
* @param parentId
* @param userName
* @return
*/
private Long checkFileExist(Long projectId, Long parentId, String userName) {
if (null == parentId) {
throw ResponseException.of_error("父文件id不能为空");
}
if (null == projectId) {
throw ResponseException.of_error("项目id不能为空");
}
QueryWrapper<ApiInterfaceFile> query = new QueryWrapper<>();
query.eq("project_id", projectId);
query.eq("parent_id", parentId);
ApiInterfaceFile file = apiInterfaceFileMapper.selectOne(query);
if (null == file && 0 != parentId) {
throw ResponseException.of(ResultCode.FAILURE, "父类文件夹不存在!");
}
if (null == file) {
//查询父类是否存在
ApiInterfaceFile apiInterfaceFile =
apiInterfaceFileMapper.selectOne(new QueryWrapper<ApiInterfaceFile>().eq("parent_id", parentId));
if (null == apiInterfaceFile && 0 == parentId) {
file = new ApiInterfaceFile();
file.setProjectId(projectId);
file.setFileSource("1");//dmp
file.setParentId(0L);
file.setStatus(GeneralStatusTypeEnum.VALID.name());
file.setCreateUser(userName);
file.setRemark("创建文件夹");
if (apiInterfaceFileMapper.insert(file) == 0) {
throw ResponseException.of_error("创建文件夹失败!");
}
} else {
throw ResponseException.of(ResultCode.FAILURE, "父类文件信息不存在!");
}
}
return file.getId();
} }
/** /**
...@@ -329,10 +472,6 @@ public class ProducerServiceImpl implements ProducerService { ...@@ -329,10 +472,6 @@ public class ProducerServiceImpl implements ProducerService {
*/ */
@Override @Override
public Result saveUpdateAPiInfo(ApiInterfaceReq req) { public Result saveUpdateAPiInfo(ApiInterfaceReq req) {
SysUserDto currentUser = getLoginUser(RedisMessageConstant.SENDTYPE_LOGIN_SYS);
if (null == currentUser) {
return Result.of_error("用户信息不存在");
}
ApiInterface apiInterface = apiInterfaceMapper.selectById(req.getId()); ApiInterface apiInterface = apiInterfaceMapper.selectById(req.getId());
if (null == apiInterface) { if (null == apiInterface) {
return Result.of_error(ResultMsg.DATA_NOT_FOUND); return Result.of_error(ResultMsg.DATA_NOT_FOUND);
...@@ -340,53 +479,59 @@ public class ProducerServiceImpl implements ProducerService { ...@@ -340,53 +479,59 @@ public class ProducerServiceImpl implements ProducerService {
if (StringUtils.isBlank(req.getSignType()) || "0".equals(req.getSignType())) { if (StringUtils.isBlank(req.getSignType()) || "0".equals(req.getSignType())) {
return Result.of_error("加密类型错误!"); return Result.of_error("加密类型错误!");
} }
if(StringUtils.isNotBlank(req.getReqType()) ){ if (StringUtils.isNotBlank(req.getReqType())) {
if (null == fromAuthReqTypeEnum(req.getReqType())){ if (null == fromAuthReqTypeEnum(req.getReqType())) {
return Result.of_error("限制类型不存在!"); return Result.of_error("限流类型不存在!");
}
}
if (StringUtils.isNotBlank(req.getStatus())) {
if (null == fromApiStatusName(req.getStatus())) {
return Result.of_error("更新状态不存在!");
}
}
if (StringUtils.isNotBlank(req.getStatus())) {
if (!canChange(apiInterface.getStatus(), req.getStatus())) {
String errorMsg = String.format("api当前状态为%s不可变更为%s",
ApiStatusEnum.valueOf(apiInterface.getStatus()).getText(),
ApiStatusEnum.valueOf(req.getStatus()).getText());
return Result.of_error(errorMsg);
}
}
if (null != req.getReqFrequency()) {
if (req.getReqFrequency() <= 0) {
return Result.of_error("限流次数不能小于或者等于零");
} }
} }
apiInterface.setApiType(req.getApiType()); apiInterface.setApiType(req.getApiType());
apiInterface.setApiDesc(req.getApiDesc()); apiInterface.setApiDesc(req.getApiDesc());
apiInterface.setJoinType(req.getJoinType()); apiInterface.setReqType(req.getReqType());
apiInterface.setReqFrequency(req.getReqFrequency());
apiInterface.setVersion(RandomUtil.generateVersion(apiInterface.getVersion()));//版本自动累加 apiInterface.setVersion(RandomUtil.generateVersion(apiInterface.getVersion()));//版本自动累加
apiInterface.setSignType(req.getSignType()); apiInterface.setSignType(req.getSignType());
apiInterface.setApiFunction(req.getApiFunction());
apiInterface.setStatus(req.getStatus());
apiInterface.setApiProtocl(req.getTransMode());//传输方式 https http apiInterface.setApiProtocl(req.getTransMode());//传输方式 https http
apiInterface.setUpdateDate(new Date());
apiInterface.setUpdateUser(req.getCreateUser());
if (StringUtils.isNotBlank(req.getTargetUrl())) { if (StringUtils.isNotBlank(req.getTargetUrl())) {
apiInterface.setTargetUrl(req.getTargetUrl()); apiInterface.setTargetUrl(req.getTargetUrl());
if (StringUtils.isNotBlank(req.getTimeout())) {
apiInterface.setTimeout(req.getTimeout());
}
apiInterface.setApiFunction(req.getApiFunction());
if (StringUtils.isNotBlank(req.getStatus())){
if (null == fromApiStatusName(req.getStatus())){
return Result.of_error("更新状态不存在!");
}
}
apiInterface.setStatus(req.getStatus());
if (StringUtils.isNotBlank(req.getStatus())) {
boolean b = canChange(apiInterface.getStatus(), req.getStatus());
if (!b) {
String errorMsg = String.format("api当前状态为%s不可变更为%s",
ApiStatusEnum.valueOf(apiInterface.getStatus()).getText(), ApiStatusEnum.valueOf(req.getStatus()).getText());
return Result.of_error(errorMsg);
}
}
Long timeout = Long.parseLong(apiInterface.getTimeout());
if (timeout == null || timeout == 0) {
apiInterface.setTimeout(String.valueOf(defaultTimeout));
} else if (timeout < 0) {
return Result.of_error("接口超时时间最小0ms");
} else if (timeout > maxTimeout) {
return Result.of_success("接口超时时间最大5000ms");
}
apiInterface.setUpdateDate(new Date());
apiInterface.setTimeout(req.getTimeout());
apiInterface.setUpdateUser(currentUser.getUserName());
int result = apiInterfaceMapper.updateById(apiInterface);
if (result > 0) {
return Result.of_success(ResultMsg.UPDATE_SUCCESS);
}
} }
Long timeout = Long.parseLong(req.getTimeout());
if (timeout == null || timeout == 0) {
apiInterface.setTimeout(String.valueOf(defaultTimeout));
} else if (timeout < 0) {
return Result.of_error("接口超时时间最小0ms");
} else if (timeout > maxTimeout) {
return Result.of_success("接口超时时间最大5000ms");
}
apiInterface.setTimeout(req.getTimeout());
if (apiInterfaceMapper.updateById(apiInterface) > 0) {
return Result.of_success(ResultMsg.UPDATE_SUCCESS);
}
JSONObject object = new JSONObject();
object.put("targetUrl",req.getTargetUrl());
object.put("outputType",ApiInfoOutTypeEnum.JSON.name());
saveObjOnRedis(apiInterface.getApiKey(),object);
return Result.of_success(ResultMsg.UPDATE_FAIL); return Result.of_success(ResultMsg.UPDATE_FAIL);
} }
...@@ -435,8 +580,8 @@ public class ProducerServiceImpl implements ProducerService { ...@@ -435,8 +580,8 @@ public class ProducerServiceImpl implements ProducerService {
} }
} else { } else {
QueryWrapper<ApiInterface> query = new QueryWrapper<>(); QueryWrapper<ApiInterface> query = new QueryWrapper<>();
query.eq("api_key",req.getApiKey()); query.eq("api_key", req.getApiKey());
query.eq("is_deleted",0); query.eq("is_deleted", 0);
ApiInterface apiInterface = apiInterfaceMapper.selectOne(query); ApiInterface apiInterface = apiInterfaceMapper.selectOne(query);
if (null != apiInterface) { if (null != apiInterface) {
return Result.of_error("存在重复的Apikey"); return Result.of_error("存在重复的Apikey");
...@@ -459,15 +604,13 @@ public class ProducerServiceImpl implements ProducerService { ...@@ -459,15 +604,13 @@ public class ProducerServiceImpl implements ProducerService {
} }
JSONArray result = new JSONArray(); JSONArray result = new JSONArray();
log.info("查询es标签类下的索引地址信息:" + datasource.getJdbcUrl() + "/es/get/indicess"); log.info("查询es标签类下的索引地址信息:" + datasource.getJdbcUrl() + "/es/get/indicess");
String resp = httpsUtils.doGet(datasource.getJdbcUrl() + "/es/get/indicess", null); String resp = httpsUtils.doGet(datasource.getJdbcUrl() + "/es/get/indicess", new HashMap<>());
if (resp != null) { if (resp != null) {
log.info("返回索引信息集合:" + resp); log.info("返回索引信息集合:" + resp);
JSONArray json = JSONArray.parseArray(resp); JSONArray json = JSONArray.parseArray(resp);
for (int i = 0; i < json.size(); i++) { for (int i = 0; i < json.size(); i++) {
String database = json.get(i).toString(); String database = json.get(i).toString();
/** //除去已点开头的索引返回前端
* 除去已点开头的索引返回前端
*/
if (!database.startsWith(".")) { if (!database.startsWith(".")) {
result.add(database); result.add(database);
} }
...@@ -492,7 +635,6 @@ public class ProducerServiceImpl implements ProducerService { ...@@ -492,7 +635,6 @@ public class ProducerServiceImpl implements ProducerService {
return Result.of_error("数据源不存在!"); return Result.of_error("数据源不存在!");
} }
log.info("查询es标签类索引下的type的地址信息:" + datasource.getJdbcUrl() + "/es/get/indices/types"); log.info("查询es标签类索引下的type的地址信息:" + datasource.getJdbcUrl() + "/es/get/indices/types");
JSONObject param = new JSONObject(); JSONObject param = new JSONObject();
param.put("indices", indices); param.put("indices", indices);
log.info("参数集合:" + param.toString()); log.info("参数集合:" + param.toString());
...@@ -524,7 +666,7 @@ public class ProducerServiceImpl implements ProducerService { ...@@ -524,7 +666,7 @@ public class ProducerServiceImpl implements ProducerService {
param.put("type", type); param.put("type", type);
String resp = null; String resp = null;
try { try {
resp = httpsUtils.submitPost(datasource.getJdbcUrl() + "/es/get/type/fields", param,herders); resp = httpsUtils.submitPost(datasource.getJdbcUrl() + "/es/get/type/fields", param, herders);
log.info("索引下type的fields信息集合:" + resp); log.info("索引下type的fields信息集合:" + resp);
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
...@@ -532,17 +674,75 @@ public class ProducerServiceImpl implements ProducerService { ...@@ -532,17 +674,75 @@ public class ProducerServiceImpl implements ProducerService {
return Result.of_success(resp); return Result.of_success(resp);
} }
/**
* 获取不重复的apiKey
*
* @return
*/
private String getApiKey() {
String random = RandomUtil.getStringRandom(16);
QueryWrapper<ApiInterface> query = new QueryWrapper<>();
query.eq("api_key", random);
query.eq("is_deleted", 0);
ApiInterface apiInterface = apiInterfaceMapper.selectOne(query);
if (null != apiInterface) {
random = RandomUtil.getStringRandom(16);
}
return random;
}
/** /**
* 获取当前登录用户 * 获取当前登录用户
*
* @param userType * @param userType
* @return * @return
*/ */
protected SysUserDto getLoginUser(String userType){ protected SysUserDto getLoginUser(String userType) {
SysUserDto currentUser = (SysUserDto) SysUserDto currentUser = null;
redisTemplate.opsForValue().get("USER_" + RedisMessageConstant.SENDTYPE_LOGIN_SYS); switch (userType) {
if (null != currentUser){ case "004": //平台用户004
return currentUser; currentUser = (SysUserDto) redisUtils.getObj("USER_" + RedisMessageConstant.SENDTYPE_LOGIN_SYS);
} break;
return null; case "003": //商城用户 003
currentUser = (SysUserDto) redisUtils.getObj("USER_" + RedisMessageConstant.SENDTYPE_LOGIN_CUSTOMER);
break;
default:
return null;
}
return currentUser;
}
@Override
public Result saveObjOnRedis() {
MakeDataBankApiReq bankApiReq = new MakeDataBankApiReq();
/* bankApiReq.setTransMode("HTTPS");
bankApiReq.setSignType("MD5");
bankApiReq.setJoinType("10004");
bankApiReq.setOutputType("JSON");
bankApiReq.setPage(false);
bankApiReq.setReqType("DAY");
bankApiReq.setTargetUrl("www.baidu.com");
bankApiReq.setFileId(1L);
bankApiReq.setSign("F2A8E3CFE528D6AE5C5B075046653F3E");
bankApiReq.setReqFrequency(0L);
bankApiReq.setApiDesc("4444");
bankApiReq.setTimeout("5000");
net.sf.json.JSONObject jsonObject = net.sf.json.JSONObject.fromObject(bankApiReq);
redisUtils.set("apiKeyTest", jsonObject, 300);*/
JSONObject object = new JSONObject();
object.put("targetUrl","www.baidu.common");
object.put("outputType",ApiInfoOutTypeEnum.JSON.name());
saveObjOnRedis("apiKeyTest002",object);
return Result.ok();
}
@Override
public Result getObjOnRedis() {
String apiKeyTest002 = redisUtils.get("apiKeyTest002");
// JSONObject jsonObject = JSONObject.parseObject(apiKeyTest);
JSONObject jsonObject = JSONObject.parseObject(apiKeyTest002);
System.out.println(jsonObject);
return Result.ok();
} }
} }
...@@ -18,7 +18,6 @@ import com.jz.dm.models.domian.ApiInterface; ...@@ -18,7 +18,6 @@ import com.jz.dm.models.domian.ApiInterface;
import com.jz.dm.service.ApiInterfaceService; import com.jz.dm.service.ApiInterfaceService;
import com.jz.dm.service.AuthService; import com.jz.dm.service.AuthService;
import com.jz.dm.web.annotation.AccessLimit; import com.jz.dm.web.annotation.AccessLimit;
import com.jz.dm.web.annotation.ApiLogAspect;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
...@@ -71,7 +70,7 @@ public class ApiQueryService extends ApiParamVerify implements OpenApiService { ...@@ -71,7 +70,7 @@ public class ApiQueryService extends ApiParamVerify implements OpenApiService {
* @param response * @param response
*/ */
@Override @Override
@ApiLogAspect(description = "API请求日志") // @ApiLogAspect(description = "API请求日志")
@AccessLimit(limit = 10000, sec = 1) @AccessLimit(limit = 10000, sec = 1)
@SentinelResource(value = "api.gateway", fallback = "fallbackGateway") @SentinelResource(value = "api.gateway", fallback = "fallbackGateway")
@Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW) @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
...@@ -114,6 +113,10 @@ public class ApiQueryService extends ApiParamVerify implements OpenApiService { ...@@ -114,6 +113,10 @@ public class ApiQueryService extends ApiParamVerify implements OpenApiService {
} }
} catch (Exception ex) { } catch (Exception ex) {
if (ex instanceof GatewayException) { if (ex instanceof GatewayException) {
//调用失败回调数据银行解冻
if (AuthModeEnum.POWER_CALL_MODE.name().equals(apiAuth.getAuthMode())){
notifierMinusMoney(parameter, bResult);
}
throw (GatewayException) ex; throw (GatewayException) ex;
} }
log.error("~~~~~~~~~~~~~~~请求api信息异常~~~~~~~~~~~~~"); log.error("~~~~~~~~~~~~~~~请求api信息异常~~~~~~~~~~~~~");
...@@ -186,7 +189,7 @@ public class ApiQueryService extends ApiParamVerify implements OpenApiService { ...@@ -186,7 +189,7 @@ public class ApiQueryService extends ApiParamVerify implements OpenApiService {
jsonReq.put("assetsId",assetsId); jsonReq.put("assetsId",assetsId);
jsonReq.put("userId",userId); jsonReq.put("userId",userId);
jsonReq.put("dataPrice",dataPrice); jsonReq.put("dataPrice",dataPrice);
jsonReq.put("callStatus",bResult);//调用成功 扣款 false 调用失败,解冻金额 jsonReq.put("callStatus",bResult);//true 调用成功 扣款 false 调用失败,解冻金额
String responseResult = httpsUtils.submitPost(withholdUrl, jsonReq.toString()); String responseResult = httpsUtils.submitPost(withholdUrl, jsonReq.toString());
JSONObject paramsResult = JSONObject.parseObject(responseResult); JSONObject paramsResult = JSONObject.parseObject(responseResult);
if (null != paramsResult){ if (null != paramsResult){
......
...@@ -83,7 +83,7 @@ public class SystemLogAspect { ...@@ -83,7 +83,7 @@ public class SystemLogAspect {
String url = UrlUtil.getServerUrl(request); String url = UrlUtil.getServerUrl(request);
// 访问项目名 // 访问项目名
String contextPath = request.getContextPath(); String contextPath = request.getContextPath();
log.info("around请求参数为{}", joinPoint.getArgs()); log.info("around请求参数为{}", params);
//动态修改其参数 //动态修改其参数
//注意,如果调用joinPoint.proceed()方法,则修改的参数值不会生效,必须调用joinPoint.proceed(Object[] args) //注意,如果调用joinPoint.proceed()方法,则修改的参数值不会生效,必须调用joinPoint.proceed(Object[] args)
com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(params); com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(params);
......
...@@ -92,7 +92,8 @@ sentinel: #sentinel每秒中最大的请求个数 ...@@ -92,7 +92,8 @@ sentinel: #sentinel每秒中最大的请求个数
#数据银行调用配置 #数据银行调用配置
data: data:
bank: bank:
balanceUrl: http://localhost:8081/mall/financeCustomerAssets/findAssets #余额信息url balanceUrl: http://192.168.1.139:8081/mall/financeCustomerAssets/findAssets #余额信息url
withholdUrl: http://localhost:8081/mall/financeCustomerAssets/unfreezeMoney #扣款信通知url withholdUrl: http://192.168.1.139:8081/mall/financeCustomerAssets/unfreezeMoney #扣款信通知url
token: #dataBank 制作验签
dataBank: dataBank123
...@@ -2,8 +2,8 @@ package com.jz.dm.gateway.api; ...@@ -2,8 +2,8 @@ package com.jz.dm.gateway.api;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.jz.common.utils.HttpsUtils; import com.jz.common.utils.HttpsUtils;
import com.jz.common.utils.Md5;
import com.jz.dm.common.util.MapUtil; import com.jz.dm.common.util.MapUtil;
import com.jz.dm.common.util.Md5;
import com.jz.dm.gateway.SpringTestCase; import com.jz.dm.gateway.SpringTestCase;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
...@@ -27,14 +27,14 @@ public class ApiReqTest extends SpringTestCase { ...@@ -27,14 +27,14 @@ public class ApiReqTest extends SpringTestCase {
public void TestGatewayReq() { public void TestGatewayReq() {
JSONObject jsonObject = new JSONObject(); JSONObject jsonObject = new JSONObject();
jsonObject.put("apiKey", "9jNA1W5Ydn7Stp12"); jsonObject.put("apiKey", "sE862E97j7Yzo049");
jsonObject.put("method", "query"); jsonObject.put("method", "query");
jsonObject.put("signType", "MD5"); jsonObject.put("signType", "MD5");
long time = System.currentTimeMillis(); long time = System.currentTimeMillis();
jsonObject.put("timestamp", "1609919983045"); jsonObject.put("timestamp", String.valueOf(time));
JSONObject params = new JSONObject(); JSONObject params = new JSONObject();
params.put("authCode", "20200000000221231111455Jg8ug1621"); params.put("authCode", "202100000001118191258T718d78591J");
params.put("selectType", "10006"); params.put("selectType", "10006");
params.put("reqParams", new JSONObject()); params.put("reqParams", new JSONObject());
jsonObject.put("params",params); jsonObject.put("params",params);
...@@ -42,10 +42,9 @@ public class ApiReqTest extends SpringTestCase { ...@@ -42,10 +42,9 @@ public class ApiReqTest extends SpringTestCase {
String apiKey = jsonObject.getString("apiKey"); String apiKey = jsonObject.getString("apiKey");
String method = jsonObject.getString("method"); String method = jsonObject.getString("method");
String signType = jsonObject.getString("signType"); String signType = jsonObject.getString("signType");
String timestamp= jsonObject.getString("timestamp");
String signature = MapUtil.getSignValue(apiKey, method, signType, timestamp); String signature = MapUtil.getSignValue(apiKey, method, signType);
String salt = Md5.encrypt(signature, "OOmeF1gh"); String salt = Md5.encrypt(signature, "33tgT3g2");
jsonObject.put("sign", salt); jsonObject.put("sign", salt);
String response = httpsUtils.submitPost(url, jsonObject.toString()); String response = httpsUtils.submitPost(url, jsonObject.toString());
System.out.println(response); System.out.println(response);
......
package com.jz.dm.gateway.orther; package com.jz.dm.gateway.orther;
import com.jz.dm.common.base.BaseCurrentUserObject; import com.jz.dm.common.util.RedisSerializableUtil;
import com.jz.dm.gateway.SpringTestCase; import com.jz.dm.gateway.SpringTestCase;
import com.jz.dm.models.req.make.MakeDataBankApiReq;
import net.sf.json.JSONObject;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.RedisTemplate;
...@@ -19,17 +21,49 @@ import org.springframework.data.redis.core.RedisTemplate; ...@@ -19,17 +21,49 @@ import org.springframework.data.redis.core.RedisTemplate;
public class TestRedisUserSave extends SpringTestCase { public class TestRedisUserSave extends SpringTestCase {
@Autowired @Autowired
private RedisTemplate redisTemplate; private RedisTemplate<String, Object> redisTemplate;
/*@Autowired
private RedisUtils redisUtils;*/
@Test @Test
public void saveUser(){ public void saveUser(){
redisTemplate.opsForValue().set("USER004","USER9999"); RedisTemplate template = new RedisTemplate();
template.opsForValue().set("USER004","USER9999");
// this.redisTemplate.opsForValue().set("USER004","USER9999");
} }
@Test @Test
public void getUser(){ public void getUser(){
//String str= (String)redisTemplate.opsForValue().get("USER"+"_99999"); redisTemplate.opsForValue().get("USER004");
//System.out.println("获取到的用户:"+str); }
System.out.println(new BaseCurrentUserObject().getUserInfo());
@Test
public void saveObject(){
MakeDataBankApiReq bankApiReq = new MakeDataBankApiReq();
bankApiReq.setTransMode("HTTPS");
bankApiReq.setSignType("MD5");
bankApiReq.setJoinType("10004");
bankApiReq.setOutputType("JSON");
bankApiReq.setPage(false);
bankApiReq.setReqType("DAY");
bankApiReq.setTargetUrl("www.baidu.com");
bankApiReq.setFileId(1L);
bankApiReq.setSign("F2A8E3CFE528D6AE5C5B075046653F3E");
bankApiReq.setReqFrequency(0L);
bankApiReq.setApiDesc("4444");
bankApiReq.setTimeout("5000");
String value = String.valueOf(bankApiReq);
System.out.println(value);
// JSONObject jsonObject = JSONObject.parseObject(value);
JSONObject jsonObject = JSONObject.fromObject(bankApiReq);
System.out.println(jsonObject);
// redisTemplate.opsForValue().set(bankApiReq,jsonObject,300, TimeUnit.SECONDS);
/*RedisUtils redisUtilsaa = new RedisUtils();*/
RedisTemplate redisTemplate1 = new RedisTemplate();
byte[] serialize = RedisSerializableUtil.serialize(jsonObject);
// redisUtilsaa.set("bankApiReq",jsonObject,300);
redisTemplate1.opsForValue().set("bankApiReq",jsonObject);
redisTemplate1.opsForValue().get(bankApiReq);
} }
} }
...@@ -19,6 +19,7 @@ ...@@ -19,6 +19,7 @@
</properties> </properties>
<dependencies> <dependencies>
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId> <artifactId>spring-boot-starter-web</artifactId>
......
...@@ -132,6 +132,15 @@ public class RedisUtils { ...@@ -132,6 +132,15 @@ public class RedisUtils {
return (String) redisTemplate.opsForValue().get(key); return (String) redisTemplate.opsForValue().get(key);
} }
/**
* 实现命令:GET key,返回 key所关联的值。
*
* @param key
* @return obj
*/
public Object getObj(String key) {
return redisTemplate.opsForValue().get(key);
}
/** /**
* Hash(哈希表) * Hash(哈希表)
* 实现命令:HSET key field value,将哈希表 key中的域 field的值设为 value * 实现命令:HSET key field value,将哈希表 key中的域 field的值设为 value
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment