Commit bd0af079 authored by zhangc's avatar zhangc

优化apigateway部分代码

parent ae0d95a2
...@@ -55,7 +55,8 @@ CREATE TABLE `t_api_interface_custom` ( ...@@ -55,7 +55,8 @@ CREATE TABLE `t_api_interface_custom` (
`update_date` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '修改时间', `update_date` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '修改时间',
`update_user` varchar(100) DEFAULT NULL COMMENT '更新人', `update_user` varchar(100) DEFAULT NULL COMMENT '更新人',
`is_deleted` tinyint(2) unsigned NOT NULL DEFAULT '0' COMMENT '是否删除', `is_deleted` tinyint(2) unsigned NOT NULL DEFAULT '0' COMMENT '是否删除',
PRIMARY KEY (`id`) PRIMARY KEY (`id`),
UNIQUE KEY `API_ID_UNIQ_INDEX` (`api_interface_id`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 ROW_FORMAT=DYNAMIC COMMENT='api自定义信息表'; ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 ROW_FORMAT=DYNAMIC COMMENT='api自定义信息表';
#api api文件表 #api api文件表
...@@ -116,6 +117,7 @@ CREATE TABLE `t_api_auth` ( ...@@ -116,6 +117,7 @@ CREATE TABLE `t_api_auth` (
`auth_mode` varchar(50) DEFAULT NULL COMMENT '授权方式:POWER_CALL_MODE 按次调用 ,RECORD_TIME_MODE 按时间调用 PERMANENT_TIME_MODE 永久有效', `auth_mode` varchar(50) DEFAULT NULL COMMENT '授权方式:POWER_CALL_MODE 按次调用 ,RECORD_TIME_MODE 按时间调用 PERMANENT_TIME_MODE 永久有效',
`valid_start_time` datetime DEFAULT NULL COMMENT '开始时间', `valid_start_time` datetime DEFAULT NULL COMMENT '开始时间',
`valid_end_time` datetime DEFAULT NULL COMMENT '结束时间', `valid_end_time` datetime DEFAULT NULL COMMENT '结束时间',
`handler` tinyint(2) NULL DEFAULT '0' COMMENT '处理状态:0 未处理, 1 已处理',
`status` varchar(50) NOT NULL COMMENT '状态(VALID-正常 UN_VALID-无效)', `status` varchar(50) NOT NULL COMMENT '状态(VALID-正常 UN_VALID-无效)',
`remark` varchar(500) DEFAULT NULL COMMENT '备注', `remark` varchar(500) DEFAULT NULL COMMENT '备注',
`create_date` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `create_date` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
......
ALTER TABLE `t_department` #添加唯一索引
ADD COLUMN `linkman` varchar(100) NULL AFTER `industry`; ALTER TABLE `t_api_interface_custom`
\ No newline at end of file ADD UNIQUE INDEX `API_ID_UNIQ_INDEX` (`api_interface_id`) USING BTREE ;
\ No newline at end of file
...@@ -61,12 +61,6 @@ ...@@ -61,12 +61,6 @@
<groupId>com.alibaba</groupId> <groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId> <artifactId>fastjson</artifactId>
</dependency> </dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>RELEASE</version>
<scope>test</scope>
</dependency>
<dependency> <dependency>
<groupId>org.projectlombok</groupId> <groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId> <artifactId>lombok</artifactId>
...@@ -120,6 +114,14 @@ ...@@ -120,6 +114,14 @@
<groupId>junit</groupId> <groupId>junit</groupId>
<artifactId>junit</artifactId> <artifactId>junit</artifactId>
</dependency> </dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-data-redis</artifactId>
</dependency>
</dependencies> </dependencies>
<build> <build>
......
...@@ -27,4 +27,7 @@ public class TagConstants { ...@@ -27,4 +27,7 @@ public class TagConstants {
// es handler 相关 // es handler 相关
public static final String OPEN_API_ESTAG_INFO_NAMESPACE = "jz:openapi:handler:estag:"; public static final String OPEN_API_ESTAG_INFO_NAMESPACE = "jz:openapi:handler:estag:";
public static final String OPEN_API_ESTAG_JDBC_INFO_NAMESPACE = "jz:openapi:handler:estag:jdbc:"; public static final String OPEN_API_ESTAG_JDBC_INFO_NAMESPACE = "jz:openapi:handler:estag:jdbc:";
//redis限流相关
public static final String OPEN_API_REDIS_LIMIT_KEY = "jz:openapi:redis:limit:";
} }
...@@ -27,6 +27,10 @@ public enum ApiStatusEnum { ...@@ -27,6 +27,10 @@ public enum ApiStatusEnum {
* 冻结 * 冻结
*/ */
FREEZE("冻结"), FREEZE("冻结"),
/**
* 下架(下架时可以调用/不可以购买)
*/
SOLDOUT("下架"),
/** /**
* 失效' * 失效'
......
package com.jz.dm.common.enums.org;
/**
* @author ZC
* @PACKAGE_NAME: com.jz.dm.common.enums.org
* @PROJECT_NAME: jz-dm-parent
* @NAME: OrgTypeEnum
* @DATE: 2021-1-14/16:17
* @DAY_NAME_SHORT: 周四
* @Description:
**/
public enum OrgTypeEnum {
INT("内部组织"),
OUT("外部组织");
private String text;
OrgTypeEnum(String text) {
this.text = text;
}
public String getText() {
return text;
}
public static OrgTypeEnum fromOrgTypeEnumName(String typeName) {
for (OrgTypeEnum type : OrgTypeEnum.values()) {
if (type.name().equals(typeName)) {
return type;
}
}
return null;
}
}
package com.jz.dm.controller;
import com.jz.common.utils.Result;
import com.jz.dm.models.req.api.ApiInterfaceDetailReq;
import com.jz.dm.models.req.api.ApiInterfaceInfoListReq;
import com.jz.dm.service.ApiInterfaceService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Mono;
import javax.validation.Valid;
/**
* @author ZC
* @PACKAGE_NAME: com.jz.dm.controller
* @PROJECT_NAME: jz-dm-parent
* @NAME: ApiInterfaceController
* @DATE: 2021-1-14/15:29
* @DAY_NAME_SHORT: 周四
* @Description:
**/
@RestController
@RequestMapping("api/interface")
@Api(tags = "API接口Controller")
public class ApiInterfaceController {
@Autowired
private ApiInterfaceService apiInterfaceService;
/**
* @Description:API列表查询
* @return: API列表
* @Author: Mr.zhang
* @Date: 2020-12-24
*/
@ApiOperation("API列表查询")
@PostMapping(value = "/listApiInterface")
public Mono<Result> getApiInterfaceList(@RequestBody @Valid ApiInterfaceInfoListReq req) {
return Mono.fromSupplier(() -> Result.of_success(apiInterfaceService.listApiInterface(req)));
}
/**
* @Description:API详情查询
* @return: API详情查询
* @Author: Mr.zhang
* @Date: 2020-12-24
*/
@ApiOperation("API详情查询")
@PostMapping(value = "/getApiInterfaceDetail")
public Mono<Result> getApiInterfaceDetail(@RequestBody @Valid ApiInterfaceDetailReq req) {
return Mono.fromSupplier(() -> apiInterfaceService.getApiInterfaceDetail(req));
}
/**
* @Description:API删除
* @return: API删除
* @Author: Mr.zhang
* @Date: 2020-12-24
*/
@ApiOperation("数据银行API删除")
@PostMapping(value = "/delDataBankApiInterface")
public Mono<Result> delDataBankApiInterface(@RequestParam (name="apiKey")String apiKey) {
return Mono.fromSupplier(() -> apiInterfaceService.delApiInterface(apiKey));
}
/**
* @Description:DMP-API删除
* @return: DMP-API删除
* @Author: Mr.zhang
* @Date: 2020-12-24
*/
@ApiOperation("DMP-API删除/确认提示接口")
@PostMapping(value = "/delDMPApiInterface")
public Mono<Result> delDMPApiInterface(@RequestParam (name="type")String type,
@RequestParam (name="apiKey")String apiKey) {
return Mono.fromSupplier(() -> apiInterfaceService.dmpDeleteAuth(type,apiKey));
}
}
...@@ -25,6 +25,7 @@ import java.util.Map; ...@@ -25,6 +25,7 @@ import java.util.Map;
* @author zc * @author zc
*/ */
@RestController @RestController
@RequestMapping("api/request")
@Api(tags = {"api请求controller"}) @Api(tags = {"api请求controller"})
public class GatewayController { public class GatewayController {
......
...@@ -36,10 +36,8 @@ public class ProducerController { ...@@ -36,10 +36,8 @@ public class ProducerController {
*/ */
@ApiOperation("获取文件夹列表") @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, return Mono.fromSupplier(() -> producerService.getFileCatalog(projectId));
@RequestParam(name = "pageSize",defaultValue = "10",required = false)String pageSize) {
return Mono.fromSupplier(() -> Result.of_success(producerService.getFileCatalog(projectId,pageNum,pageSize)));
} }
/** /**
* @Description:创建文件夹 * @Description:创建文件夹
...@@ -115,7 +113,7 @@ public class ProducerController { ...@@ -115,7 +113,7 @@ public class ProducerController {
* @Date: 2020-12-26 * @Date: 2020-12-26
*/ */
@ApiOperation("保存修改的api信息") @ApiOperation("保存修改的api信息")
@PostMapping(value = "/保存修改的api信息") @PostMapping(value = "/saveUpdate")
public Mono<Result> saveUpdateAPiInfo(@RequestBody @Valid ApiInterfaceReq req) { public Mono<Result> saveUpdateAPiInfo(@RequestBody @Valid ApiInterfaceReq req) {
return Mono.fromSupplier(() -> producerService.saveUpdateAPiInfo(req)); return Mono.fromSupplier(() -> producerService.saveUpdateAPiInfo(req));
} }
......
package com.jz.dm.filter; package com.jz.dm.filter;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.jz.common.utils.HttpsUtils; import com.jz.common.utils.HttpsUtils;
import com.jz.common.utils.RedisUtils; import com.jz.common.utils.RedisUtils;
import com.jz.dm.common.constant.Constants; import com.jz.dm.common.constant.Constants;
import com.jz.dm.common.constant.LoggingConstants;
import com.jz.dm.common.enums.GatewayResultCode; import com.jz.dm.common.enums.GatewayResultCode;
import com.jz.dm.common.enums.apiInterface.ApiStatusEnum; import com.jz.dm.common.enums.apiInterface.ApiStatusEnum;
import com.jz.dm.common.enums.auth.AuthReqTypeEnum; import com.jz.dm.common.enums.auth.AuthReqTypeEnum;
...@@ -12,6 +12,7 @@ import com.jz.dm.common.enums.org.OrgStatusEnum; ...@@ -12,6 +12,7 @@ import com.jz.dm.common.enums.org.OrgStatusEnum;
import com.jz.dm.common.exception.GatewayException; import com.jz.dm.common.exception.GatewayException;
import com.jz.dm.common.util.DateUtil; import com.jz.dm.common.util.DateUtil;
import com.jz.dm.common.util.LogUtil; import com.jz.dm.common.util.LogUtil;
import com.jz.dm.mapper.ApiInterfaceMapper;
import com.jz.dm.models.domian.ApiAuth; import com.jz.dm.models.domian.ApiAuth;
import com.jz.dm.models.domian.ApiInterface; import com.jz.dm.models.domian.ApiInterface;
import com.jz.dm.models.domian.ApiOrg; import com.jz.dm.models.domian.ApiOrg;
...@@ -28,6 +29,7 @@ import org.springframework.beans.factory.annotation.Autowired; ...@@ -28,6 +29,7 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.text.ParseException; import java.text.ParseException;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.Date; import java.util.Date;
...@@ -52,6 +54,8 @@ public class AuthFilter extends AbstractFilter { ...@@ -52,6 +54,8 @@ public class AuthFilter extends AbstractFilter {
private OrganizationManageService organizationManageService; private OrganizationManageService organizationManageService;
@Autowired @Autowired
private ApiInterfaceService apiInterfaceService; private ApiInterfaceService apiInterfaceService;
@Resource
private ApiInterfaceMapper apiInterfaceMapper;
@Autowired @Autowired
private RedisUtils redisUtils; private RedisUtils redisUtils;
@Autowired @Autowired
...@@ -77,8 +81,13 @@ public class AuthFilter extends AbstractFilter { ...@@ -77,8 +81,13 @@ public class AuthFilter extends AbstractFilter {
if (null == apiInterface) { if (null == apiInterface) {
throw new GatewayException(GatewayResultCode.ILLEGAL_REQUEST); throw new GatewayException(GatewayResultCode.ILLEGAL_REQUEST);
} }
if (!ApiStatusEnum.ISSUE.name().equals(apiInterface.getStatus())) { //下架状态$$ 检查是否有有效调用的api,如果有就放行,没有就置为无效
throw new GatewayException(GatewayResultCode.API_STATUS_EXCEPTION); if (ApiStatusEnum.SOLDOUT.name().equals(apiInterface.getStatus())) {
handleApiStatus(apiInterface);
} else {//非下架状态
if (!ApiStatusEnum.ISSUE.name().equals(apiInterface.getStatus())) {
throw new GatewayException(GatewayResultCode.API_STATUS_EXCEPTION);
}
} }
JSONObject parameter = JSONObject.parseObject(request.getParams()); JSONObject parameter = JSONObject.parseObject(request.getParams());
if (null != parameter) { if (null != parameter) {
...@@ -87,11 +96,18 @@ public class AuthFilter extends AbstractFilter { ...@@ -87,11 +96,18 @@ public class AuthFilter extends AbstractFilter {
if (null == authAuth) { if (null == authAuth) {
throw new GatewayException(GatewayResultCode.REQUEST_NOT_AUTH); throw new GatewayException(GatewayResultCode.REQUEST_NOT_AUTH);
} }
if ("1".equals(authAuth.getHandler())) {//处理状态,已经调用成功后授权码失效
throw new GatewayException(GatewayResultCode.ILLEGAL_REQUEST);
}
//查询认证组织信息 //查询认证组织信息
ApiOrg apiOrg = organizationManageService.getAuthOrganization(authAuth.getApiOrgId()); ApiOrg apiOrg = organizationManageService.getAuthOrganization(authAuth.getApiOrgId());
if (null == apiOrg) { if (null == apiOrg) {
throw new GatewayException(GatewayResultCode.ORG_NOT_EXIST); throw new GatewayException(GatewayResultCode.ORG_NOT_EXIST);
} }
//状态检查(只限制按次请求$$ 不限制按时间请求)
if (!OrgStatusEnum.NORMAL.name().equals(apiOrg.getStatus())) {
throw new GatewayException(GatewayResultCode.ORG_STATE_EXCEPTION);
}
checkBill(request, authCode, authAuth, apiOrg); checkBill(request, authCode, authAuth, apiOrg);
} }
chain.doFilter(request, response); chain.doFilter(request, response);
...@@ -124,15 +140,12 @@ public class AuthFilter extends AbstractFilter { ...@@ -124,15 +140,12 @@ public class AuthFilter extends AbstractFilter {
ApiAuth authAuth, ApiOrg apiOrg) throws ParseException { ApiAuth authAuth, ApiOrg apiOrg) throws ParseException {
switch (authAuth.getAuthMode()) { switch (authAuth.getAuthMode()) {
case "POWER_CALL_MODE": //按次调用 case "POWER_CALL_MODE": //按次调用
//状态检查(只限制按次请求$$ 不限制按时间请求)
if (!OrgStatusEnum.NORMAL.name().equals(apiOrg.getStatus())) {
throw new GatewayException(GatewayResultCode.ORG_STATE_EXCEPTION);
}
//查询数据银行银行余额是否充足 //查询数据银行银行余额是否充足
//getDataAmountResult(request); getDataAmountResult(request);
try { //记录请求次数(每天限制请求次数) try { //记录请求次数(每天限制请求次数)
String limitKey = request.getApiKey() + LoggingConstants.AND_SPILT + authCode; // String limitKey = TagConstants.OPEN_API_REDIS_LIMIT_KEY + authCode;
Integer reqValue = (Integer)redisUtils.getObj(limitKey); String limitKey = authCode;
String reqValue = (String)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();
...@@ -141,12 +154,12 @@ public class AuthFilter extends AbstractFilter { ...@@ -141,12 +154,12 @@ public class AuthFilter extends AbstractFilter {
} else if (AuthReqTypeEnum.YEAR.name().equals(authAuth.getReqType())) {//按年 } else if (AuthReqTypeEnum.YEAR.name().equals(authAuth.getReqType())) {//按年
//暂时不支持年 //暂时不支持年
} }
if (null != reqValue && reqValue != 0) { if (null != reqValue) {
// Integer value = Integer.valueOf(reqKey); Integer value = Integer.valueOf(reqValue);
if (reqValue > authAuth.getReqFrequency()) {//超出最大请求次数 if (value > authAuth.getReqFrequency()) {//超出最大请求次数
throw new GatewayException(GatewayResultCode.REQUEST_LIMIT_EXCEPTION); throw new GatewayException(GatewayResultCode.REQUEST_LIMIT_EXCEPTION);
} else if (reqValue <= authAuth.getReqFrequency()) { } else if (value <= authAuth.getReqFrequency()) {
redisUtils.delAndAdd(limitKey, limitKey, reqValue + 1, timeOut); redisUtils.delAndAdd(limitKey, limitKey, value + 1, timeOut);
} }
} else { } else {
redisUtils.set(limitKey, 1, timeOut); redisUtils.set(limitKey, 1, timeOut);
...@@ -164,6 +177,7 @@ public class AuthFilter extends AbstractFilter { ...@@ -164,6 +177,7 @@ public class AuthFilter extends AbstractFilter {
Date validEndTime = authAuth.getValidEndTime(); Date validEndTime = authAuth.getValidEndTime();
//如果 date1 在 date2 之前,before 返回 true,否则返回 false //如果 date1 在 date2 之前,before 返回 true,否则返回 false
if (currentDate.after(validEndTime)) {//超出时间 if (currentDate.after(validEndTime)) {//超出时间
updateCallTimeStatus(authAuth);//查看是否为已处理状态
throw new GatewayException(GatewayResultCode.RATE_LIMIT_EXCEEDED); throw new GatewayException(GatewayResultCode.RATE_LIMIT_EXCEEDED);
} }
break; break;
...@@ -174,6 +188,18 @@ public class AuthFilter extends AbstractFilter { ...@@ -174,6 +188,18 @@ public class AuthFilter extends AbstractFilter {
} }
} }
/**
* 更新调用时间状态
*/
private void updateCallTimeStatus(ApiAuth authAuth) {
if (null != authAuth && "0".equals(authAuth.getHandler())) {
if (authService.updateApiAuthStatus(authAuth) == 0) {
log.info("------------------更新状态调用状态异常---------------");
throw new GatewayException(GatewayResultCode.UNKNOWN_EXCEPTION);
}
}
}
/** /**
* 按次调用检查余额是否充足 * 按次调用检查余额是否充足
* *
...@@ -202,4 +228,23 @@ public class AuthFilter extends AbstractFilter { ...@@ -202,4 +228,23 @@ public class AuthFilter extends AbstractFilter {
} }
} }
} }
/**
* 处理Api状态信息
*
* @param apiInterface
*/
private void handleApiStatus(ApiInterface apiInterface) {
//检查是否有有效的认证的API
Integer authStatus = apiInterfaceService.getValidAuthStatus(apiInterface);
if (null == authStatus || authStatus == 0) {
UpdateWrapper<ApiInterface> updateWra = new UpdateWrapper<>();
updateWra.eq("status", ApiStatusEnum.EXPIRY);
updateWra.eq("is_deleted", 1);
if (apiInterfaceMapper.update(null, updateWra) == 0) {
log.info("------------------更新API状态失败-----------");
throw new GatewayException(GatewayResultCode.FAIL);
}
}
}
} }
package com.jz.dm.filter; package com.jz.dm.filter;
import com.alibaba.fastjson.JSONObject;
import com.jz.dm.common.constant.Constants; import com.jz.dm.common.constant.Constants;
import com.jz.dm.common.enums.Format; import com.jz.dm.common.enums.Format;
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.enums.SignType; import com.jz.dm.common.enums.SignType;
import com.jz.dm.common.exception.GatewayException;
import com.jz.dm.common.util.StringUtil; import com.jz.dm.common.util.StringUtil;
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;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
/** /**
...@@ -27,33 +29,69 @@ public class CheckArgsFilter extends AbstractFilter { ...@@ -27,33 +29,69 @@ public class CheckArgsFilter extends AbstractFilter {
public String getFilterName() { public String getFilterName() {
return "CheckArgsFilter"; return "CheckArgsFilter";
} }
@Value("${apiRequest.testExample.apiKey}")
private String testApiKey;
@Value("${apiRequest.testExample.sign}")
private String testSign;
@Override @Override
protected void internalDoFilter(GatewayRequest request, GatewayResponse response, protected void internalDoFilter(GatewayRequest request, GatewayResponse response,
FilterChain chain) { FilterChain chain) {
// 校验参数非空 if (null != request && StringUtil.isNotBlank(request.getParams())) {
if (StringUtil.isEmpty(request.getApiKey()) || StringUtil.isEmpty(request.getMethod()) JSONObject params = JSONObject.parseObject(request.getParams());
|| StringUtil.isEmpty(request.getSignType())|| StringUtil.isEmpty(request.getSign()) Boolean aBoolean = params.getBoolean("isTest");
|| StringUtil.isEmpty(request.getTimestamp())|| StringUtil.isEmpty(request.getParams())) { if (null == aBoolean){
throw new GatewayException(GatewayResultCode.ILLEGAL_ARGUMENT); //无效参数 throw new GatewayException(GatewayResultCode.ILLEGAL_ARGUMENT); //无效参数
} }
// 设置默认值 if (aBoolean) {//如果是测试数据
if (StringUtil.isEmpty(request.getFormat())) { chain.doFilter(assembleTestData(), response);
request.setFormat(Format.JSON.name()); } else {
} // 校验参数非空
try { if (StringUtil.isEmpty(request.getApiKey()) || StringUtil.isEmpty(request.getMethod())
request.setVersion("v1.0.0"); || StringUtil.isEmpty(request.getSignType()) || StringUtil.isEmpty(request.getSign())
//格式,目前仅支持JSON || StringUtil.isEmpty(request.getTimestamp()) || StringUtil.isEmpty(request.getParams())) {
Format.valueOf(request.getFormat()); throw new GatewayException(GatewayResultCode.ILLEGAL_ARGUMENT); //无效参数
//请求使用的编码格式,如UTF-8,GBK,GB2312等 }
//Charset.forName(request.getCharset()); // 设置默认值
//生成签名字符串所使用的签名算法类型 if (StringUtil.isEmpty(request.getFormat())) {
SignType.valueOf(request.getSignType()); request.setFormat(Format.JSON.name());
} catch (Exception ex) { }
//无效参数 try {
throw new GatewayException(GatewayResultCode.ILLEGAL_ARGUMENT); request.setVersion("v1.0.0");
//格式,目前仅支持JSON
Format.valueOf(request.getFormat());
//请求使用的编码格式,如UTF-8,GBK,GB2312等
//Charset.forName(request.getCharset());
//生成签名字符串所使用的签名算法类型
SignType.valueOf(request.getSignType());
} catch (Exception ex) {
//无效参数
throw new GatewayException(GatewayResultCode.ILLEGAL_ARGUMENT);
}
}
chain.doFilter(request, response);
} }
chain.doFilter(request, response);
} }
/**
* 组装测试数据
*/
private GatewayRequest assembleTestData() {
GatewayRequest gatewayRequest = new GatewayRequest();
gatewayRequest.setApiKey(testApiKey);
gatewayRequest.setMethod("query");
gatewayRequest.setFormat(Format.JSON.name());
gatewayRequest.setSignType("MD5");
gatewayRequest.setSign(testSign);
gatewayRequest.setTimestamp(System.currentTimeMillis() + "");
gatewayRequest.setVersion("v1.0.0");
JSONObject jsonObject = new JSONObject();
jsonObject.put("authCode","202100000001118191258T718d78591J");
jsonObject.put("isTest",true);
gatewayRequest.setParams(jsonObject.toString());
return gatewayRequest;
}
} }
...@@ -8,6 +8,8 @@ import com.jz.dm.models.dto.AuthInfoDto; ...@@ -8,6 +8,8 @@ import com.jz.dm.models.dto.AuthInfoDto;
import com.jz.dm.models.req.auth.AuthDetailInfoReq; import com.jz.dm.models.req.auth.AuthDetailInfoReq;
import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Param;
import java.util.List;
/**api授权信息表 mapper /**api授权信息表 mapper
* @author zc * @author zc
* *
...@@ -28,4 +30,11 @@ public interface ApiAuthMapper extends BaseMapper<ApiAuth> { ...@@ -28,4 +30,11 @@ public interface ApiAuthMapper extends BaseMapper<ApiAuth> {
* @return * @return
*/ */
IPage<AuthInfoDto> listSelectApiAuth(IPage<AuthInfoDto> page, @Param("ew") Wrapper<AuthInfoDto> query); IPage<AuthInfoDto> listSelectApiAuth(IPage<AuthInfoDto> page, @Param("ew") Wrapper<AuthInfoDto> query);
/**
* 批量更新数据
* @param list
* @return
*/
int updateAuthBatch(List<ApiAuth> list);
} }
...@@ -2,6 +2,9 @@ package com.jz.dm.mapper; ...@@ -2,6 +2,9 @@ package com.jz.dm.mapper;
import com.jz.common.base.BaseMapper; import com.jz.common.base.BaseMapper;
import com.jz.dm.models.domian.ApiInterfaceFile; import com.jz.dm.models.domian.ApiInterfaceFile;
import com.jz.dm.models.dto.ApiInterfaceFileDto;
import java.util.List;
/** /**
* @author ZC * @author ZC
...@@ -13,4 +16,10 @@ import com.jz.dm.models.domian.ApiInterfaceFile; ...@@ -13,4 +16,10 @@ import com.jz.dm.models.domian.ApiInterfaceFile;
* @Description: * @Description:
**/ **/
public interface ApiInterfaceFileMapper extends BaseMapper<ApiInterfaceFile> { public interface ApiInterfaceFileMapper extends BaseMapper<ApiInterfaceFile> {
/**
* 查询项目文件等级列表
* @param projectId
* @return
*/
List<ApiInterfaceFileDto> getFileFolderLevel(Long projectId);
} }
package com.jz.dm.mapper; package com.jz.dm.mapper;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.jz.dm.models.domian.ApiInterface; import com.jz.dm.models.domian.ApiInterface;
import com.jz.dm.models.req.api.ApiInterfaceDetailReq;
import org.apache.ibatis.annotations.Param;
/** /**
* @author ZC * @author ZC
...@@ -15,4 +19,20 @@ import com.jz.dm.models.domian.ApiInterface; ...@@ -15,4 +19,20 @@ import com.jz.dm.models.domian.ApiInterface;
public interface ApiInterfaceMapper extends BaseMapper<ApiInterface> { public interface ApiInterfaceMapper extends BaseMapper<ApiInterface> {
/**
* 查询API列表信息
* @param page
* @param query
* @return
*/
IPage<ApiInterface> listApiInterfaceInfo(IPage<ApiInterface> page, @Param("ew") Wrapper<ApiInterface> query);
/**
* 查询API详情信息
* @param req
* @return
*/
ApiInterface selectDetail(ApiInterfaceDetailReq req);
} }
...@@ -97,6 +97,13 @@ public class ApiAuth extends BaseObject implements Serializable { ...@@ -97,6 +97,13 @@ public class ApiAuth extends BaseObject implements Serializable {
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date validEndTime; private Date validEndTime;
/**
* 处理状态:0 未处理, 1 已处理
*/
@TableField("handler")
private Integer handler;
/** /**
* 状态(1-正常 2-作废) * 状态(1-正常 2-作废)
*/ */
......
...@@ -2,6 +2,7 @@ package com.jz.dm.models.domian; ...@@ -2,6 +2,7 @@ package com.jz.dm.models.domian;
import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName; import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.jz.dm.common.base.BaseObject; import com.jz.dm.common.base.BaseObject;
import lombok.Data; import lombok.Data;
import lombok.EqualsAndHashCode; import lombok.EqualsAndHashCode;
...@@ -34,6 +35,7 @@ public class ApiInterface extends BaseObject implements Serializable { ...@@ -34,6 +35,7 @@ public class ApiInterface extends BaseObject implements Serializable {
* api名称 * api名称
*/ */
@TableField("api_name") @TableField("api_name")
@JsonIgnore
private String apiName; private String apiName;
/** /**
...@@ -136,4 +138,33 @@ public class ApiInterface extends BaseObject implements Serializable { ...@@ -136,4 +138,33 @@ public class ApiInterface extends BaseObject implements Serializable {
@TableField("file_id") @TableField("file_id")
private Long fileId; private Long fileId;
/*-----------------------------------保存数据库时忽略字段--------------------------------*/
/**
* 请求总次数
*/
@TableField(exist=false)
private Integer callStat;
/**
* 请求总时间
*/
@TableField(exist = false)
private Integer requestTimeStat;
/**
* 请求参数
*/
@TableField(exist=false)
private String requestParam;
/**
* 响应参数
*/
@TableField(exist = false)
private String responseParam;
/**
* 响应状态码
*/
@TableField(exist = false)
private String respCode;
} }
...@@ -45,6 +45,12 @@ public class AuthInfoDto implements Serializable { ...@@ -45,6 +45,12 @@ public class AuthInfoDto implements Serializable {
@ApiModelProperty(value = "状态(1-正常 2-作废") @ApiModelProperty(value = "状态(1-正常 2-作废")
private String status; private String status;
@ApiModelProperty(value = "请求路径")
private String apiPath;
@ApiModelProperty(value = "api类型")
private String joinType;
@ApiModelProperty(value = "备注") @ApiModelProperty(value = "备注")
private String remark; private String remark;
......
...@@ -38,9 +38,9 @@ public class AuthUserApiReq implements Serializable { ...@@ -38,9 +38,9 @@ public class AuthUserApiReq implements Serializable {
@NotNull(message = "组织编码不能为空") @NotNull(message = "组织编码不能为空")
private String orgCode; private String orgCode;
@ApiModelProperty(value = "授权类型:DATA_BANK_AUTH 数据银行 , DMP_AUTH 授权",required = true) /* @ApiModelProperty(value = "授权类型:DATA_BANK_AUTH 数据银行 , DMP_AUTH 授权",required = true)
@NotNull(message = "授权类型不能为空") @NotNull(message = "授权类型不能为空")
private String authType; private String authType;*/
@ApiModelProperty(value = "授权方式:POWER_CALL_MODE 按次调用 ,RECORD_TIME_MODE 按时间调用,PERMANENT_TIME_MODE 永久有效",required = true) @ApiModelProperty(value = "授权方式:POWER_CALL_MODE 按次调用 ,RECORD_TIME_MODE 按时间调用,PERMANENT_TIME_MODE 永久有效",required = true)
@NotNull(message = "授权方式不能为空") @NotNull(message = "授权方式不能为空")
...@@ -58,4 +58,8 @@ public class AuthUserApiReq implements Serializable { ...@@ -58,4 +58,8 @@ public class AuthUserApiReq implements Serializable {
@ApiModelProperty(value = "备注",required = false) @ApiModelProperty(value = "备注",required = false)
private String remark; private String remark;
@ApiModelProperty(value = "创建用户",required = false)
private String createUser;
} }
...@@ -27,4 +27,7 @@ public class SaltResetReq implements Serializable { ...@@ -27,4 +27,7 @@ public class SaltResetReq implements Serializable {
@NotNull(message = "盐值不能为空") @NotNull(message = "盐值不能为空")
private String salt;*/ private String salt;*/
@ApiModelProperty(value = "创建用户",required = false)
private String createUser;
} }
...@@ -27,7 +27,7 @@ public class MakeBigDataApiReq implements Serializable { ...@@ -27,7 +27,7 @@ public class MakeBigDataApiReq implements Serializable {
@NotNull(message = "apiType不能为空") @NotNull(message = "apiType不能为空")
private String apiType;*/ private String apiType;*/
@ApiModelProperty(value = "apiKey",required = true) @ApiModelProperty(value = "apiKey",required = false)
@NotNull(message = "apiKey不能为空") @NotNull(message = "apiKey不能为空")
public String apiKey; public String apiKey;
...@@ -63,6 +63,9 @@ public class MakeBigDataApiReq implements Serializable { ...@@ -63,6 +63,9 @@ public class MakeBigDataApiReq implements Serializable {
@NotNull(message = "字段列表不能为空") @NotNull(message = "字段列表不能为空")
private String tableFields; private String tableFields;
@ApiModelProperty(value = "创建用户",required = false)
public String createUser;
//@ApiModelProperty(value = "项目id",required = true) //@ApiModelProperty(value = "项目id",required = true)
//@NotNull(message="项目id不能为空") //@NotNull(message="项目id不能为空")
//public Long projectId; //public Long projectId;
......
package com.jz.dm.service; package com.jz.dm.service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.jz.common.utils.Result;
import com.jz.dm.models.domian.ApiAuth; import com.jz.dm.models.domian.ApiAuth;
import com.jz.dm.models.domian.ApiInterface; import com.jz.dm.models.domian.ApiInterface;
import com.jz.dm.models.req.api.ApiInterfaceDetailReq;
import com.jz.dm.models.req.api.ApiInterfaceInfoListReq;
/** /**
* @author ZC * @author ZC
...@@ -35,4 +39,40 @@ public interface ApiInterfaceService { ...@@ -35,4 +39,40 @@ public interface ApiInterfaceService {
* @return * @return
*/ */
ApiInterface getReqTargetInfo(String apiKey); ApiInterface getReqTargetInfo(String apiKey);
/**
* 查询API列表信息
* @param req
* @return
*/
IPage<ApiInterface> listApiInterface(ApiInterfaceInfoListReq req);
/**
* 查询API详情
* @param req
* @return
*/
Result getApiInterfaceDetail(ApiInterfaceDetailReq req);
/**
* 删除API
* @param apiKey
* @return
*/
Result delApiInterface(String apiKey);
/**
* 获取有效授权总数
* @param apiInterface
* @return
*/
Integer getValidAuthStatus(ApiInterface apiInterface);
/**
* dmp删除API
* @param type
* @param apiKey
* @return
*/
Result dmpDeleteAuth(String type,String apiKey);
} }
...@@ -70,4 +70,11 @@ public interface AuthService { ...@@ -70,4 +70,11 @@ public interface AuthService {
* @return * @return
*/ */
ApiAuth getAuthInfo( String authCode); ApiAuth getAuthInfo( String authCode);
/**
* 更新API授权状态
* @param apiAuth
* @return
*/
int updateApiAuthStatus(ApiAuth apiAuth);
} }
package com.jz.dm.service; package com.jz.dm.service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.jz.common.utils.Result; import com.jz.common.utils.Result;
import com.jz.dm.models.domian.ApiInterfaceFile;
import com.jz.dm.models.req.make.*; import com.jz.dm.models.req.make.*;
/** /**
...@@ -91,12 +89,10 @@ public interface ProducerService { ...@@ -91,12 +89,10 @@ public interface ProducerService {
/** /**
* 获取文件列表 * 获取文件列表
* @param pageNum
* @param pageSize
* @param projectId * @param projectId
* @return * @return
*/ */
IPage<ApiInterfaceFile> getFileCatalog(Long projectId ,String pageNum, String pageSize); Result getFileCatalog(Long projectId);
/** /**
* 创建文件夹 * 创建文件夹
......
package com.jz.dm.service.impl; package com.jz.dm.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jz.common.constant.ResultMsg;
import com.jz.common.utils.Result;
import com.jz.dm.common.enums.GeneralStatusTypeEnum;
import com.jz.dm.common.enums.apiInterface.ApiStatusEnum; import com.jz.dm.common.enums.apiInterface.ApiStatusEnum;
import com.jz.dm.common.enums.auth.AuthModeEnum;
import com.jz.dm.mapper.ApiAuthMapper; import com.jz.dm.mapper.ApiAuthMapper;
import com.jz.dm.mapper.ApiInterfaceMapper; import com.jz.dm.mapper.ApiInterfaceMapper;
import com.jz.dm.models.domian.ApiAuth; import com.jz.dm.models.domian.ApiAuth;
import com.jz.dm.models.domian.ApiInterface; import com.jz.dm.models.domian.ApiInterface;
import com.jz.dm.models.req.api.ApiInterfaceDetailReq;
import com.jz.dm.models.req.api.ApiInterfaceInfoListReq;
import com.jz.dm.service.ApiInterfaceService; import com.jz.dm.service.ApiInterfaceService;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import javax.annotation.Resource; import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
/** /**
* @author ZC * @author ZC
...@@ -29,8 +41,163 @@ public class ApiInterfaceServiceImpl implements ApiInterfaceService { ...@@ -29,8 +41,163 @@ public class ApiInterfaceServiceImpl implements ApiInterfaceService {
private ApiInterfaceMapper apiInterfaceMapper; private ApiInterfaceMapper apiInterfaceMapper;
@Resource @Resource
private ApiAuthMapper apiAuthMapper; private ApiAuthMapper apiAuthMapper;
/**
* 获取API列表信息
*
* @param req
* @return
*/
@Override
public IPage<ApiInterface> listApiInterface(ApiInterfaceInfoListReq req) {
IPage<ApiInterface> page = new Page<>(req.getPageNum(), req.getPageSize());
QueryWrapper<ApiInterface> 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("ai.is_deleted", 0);
query.orderByDesc("ai.create_date");
query.groupBy("ai.create_date");
return apiInterfaceMapper.listApiInterfaceInfo(page, query);
}
/**
* 获取API详情信息
*
* @param req
* @return
*/
@Override
public Result getApiInterfaceDetail(ApiInterfaceDetailReq req) {
return Result.of_success(apiInterfaceMapper.selectDetail(req));
}
/**
* 删除API信息
*
* @param apiKey
* @return
*/
@Override
public Result delApiInterface(String apiKey) {
ApiInterface apiInterface = getReqTargetInfo(apiKey);
if (null == apiInterface) {
Result.of_error(ResultMsg.DATA_NOT_FOUND);
}
if (ApiStatusEnum.EXPIRY.name().equals(apiInterface.getStatus())) {
return Result.of_error("API已失效无法再次操作!");
}
Integer authStat = getAuthCall(apiKey, AuthModeEnum.POWER_CALL_MODE.name(), null);
Integer authDateStat = getAuthCall(apiKey, AuthModeEnum.PERMANENT_TIME_MODE.name(), new Date());
UpdateWrapper<ApiInterface> updateInfo = new UpdateWrapper<>();
if (authStat + authDateStat > 0) { //有已授权未使用的先将状态置为$$ 下架
updateInfo.set("status", ApiStatusEnum.SOLDOUT);//下架状态%%可以调用,但不可以购买
} else {
updateInfo.set("status", ApiStatusEnum.EXPIRY);//失效状态
updateInfo.set("is_deleted", 1);
}
updateInfo.eq("id", apiInterface.getId());
if (apiInterfaceMapper.update(null, updateInfo) > 0) {
return Result.of_success(ResultMsg.UPDATE_SUCCESS);
}
return Result.of_success(ResultMsg.UPDATE_FAIL);
}
/**
* dmp 删除处理
*
* @param apiKey
* @return
*/
@Override
public Result dmpDeleteAuth(String type, String apiKey) {
if ("0".equals(type)) {//确认是否删除
Integer call = getAuthCall(apiKey, AuthModeEnum.PERMANENT_TIME_MODE.name(), null);
if (call > 0) {
return Result.of_error("已存在授权用户,是否要删除!");
}
return Result.of_success(ResultMsg.SUCCESS);
} else if ("1".equals(type)) { //正式删除
ApiInterface apiInterface = getApiInfo(apiKey);
if (null == apiInterface) {
return Result.of_error(ResultMsg.DATA_NOT_EXIST);
}
if (ApiStatusEnum.EXPIRY.name().equals(apiInterface.getStatus())) {
return Result.of_error("API已失效无法再次操作!");
}
updateApiAuthStatus(apiKey);
UpdateWrapper<ApiInterface> updateWra = new UpdateWrapper<>();
updateWra.set("status", ApiStatusEnum.EXPIRY);
updateWra.set("is_deleted", 1);
updateWra.eq("id", apiInterface.getId());
if (apiInterfaceMapper.update(null, updateWra) == 0) {
return Result.of_error(ResultMsg.UPDATE_FAIL);
}
}
return Result.of_success(ResultMsg.UPDATE_SUCCESS);
}
/**
* 更新已经认证的API
*
* @param apiKey
*/
private void updateApiAuthStatus(String apiKey) {
QueryWrapper<ApiAuth> queryWra = new QueryWrapper<>();
queryWra.eq("api_key", apiKey);
queryWra.eq("handler", 0);//主要是确认单次调用是否调用
queryWra.eq("auth_mode", AuthModeEnum.PERMANENT_TIME_MODE);
queryWra.eq("status", GeneralStatusTypeEnum.VALID);
queryWra.eq("is_deleted", 0);
List<ApiAuth> authList = apiAuthMapper.selectList(queryWra);
if (!CollectionUtils.isEmpty(authList)) {
apiAuthMapper.updateAuthBatch(authList);
}
}
/**
* 获取单次调用有效授权
*
* @param apiKey
* @param modeType
* @param date
* @return
*/
private Integer getAuthCall(String apiKey, String modeType, Date date) {
//按次调用统计
QueryWrapper<ApiAuth> query = new QueryWrapper<>();
query.eq("api_key", apiKey);
query.eq("handler", 0);//主要是确认单次调用是否调用
query.eq("auth_mode", modeType);
if (null != date) {
query.gt("valid_end_time", date);
}
query.eq("status", GeneralStatusTypeEnum.VALID);
query.eq("is_deleted", 0);
return apiAuthMapper.selectCount(query);
}
/**
* 获取有效授权总数
*
* @param apiInterface
* @return
*/
@Override
public Integer getValidAuthStatus(ApiInterface apiInterface) {
Integer authCall = getAuthCall(apiInterface.getApiKey(), AuthModeEnum.POWER_CALL_MODE.name(), null);
Integer authDateCall = getAuthCall(apiInterface.getApiKey(), AuthModeEnum.PERMANENT_TIME_MODE.name(), new Date());
return authCall + authDateCall;
}
/** /**
* 获取用户授权信息 * 获取用户授权信息
*
* @param apiKey * @param apiKey
* @param authCode * @param authCode
* @return * @return
...@@ -38,40 +205,41 @@ public class ApiInterfaceServiceImpl implements ApiInterfaceService { ...@@ -38,40 +205,41 @@ public class ApiInterfaceServiceImpl implements ApiInterfaceService {
@Override @Override
public ApiAuth getApiAuthInfo(String apiKey, String authCode) { public ApiAuth getApiAuthInfo(String apiKey, String authCode) {
QueryWrapper<ApiInterface> query = new QueryWrapper<>(); QueryWrapper<ApiInterface> query = new QueryWrapper<>();
query.eq("is_deleted",0); query.eq("is_deleted", 0);
query.eq("api_key", apiKey); query.eq("api_key", apiKey);
ApiInterface apiInterface = apiInterfaceMapper.selectOne(query); ApiInterface apiInterface = apiInterfaceMapper.selectOne(query);
if (null != apiInterface){ if (null != apiInterface) {
QueryWrapper<ApiAuth> queryWrapper = new QueryWrapper<>(); QueryWrapper<ApiAuth> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("is_deleted",0); queryWrapper.eq("is_deleted", 0);
queryWrapper.eq("auth_code",authCode); queryWrapper.eq("auth_code", authCode);
ApiAuth apiAuth = apiAuthMapper.selectOne(queryWrapper); ApiAuth apiAuth = apiAuthMapper.selectOne(queryWrapper);
if (null != apiAuth){ if (null != apiAuth) {
return apiAuth; return apiAuth;
} }
} }
return null; return null;
} }
/** /**
* 获取API信息 * 获取API信息
*
* @param apiKey * @param apiKey
* @return * @return
*/ */
@Override @Override
public ApiInterface getApiInfo(String apiKey) { public ApiInterface getApiInfo(String apiKey) {
QueryWrapper<ApiInterface> query = new QueryWrapper<>(); QueryWrapper<ApiInterface> query = new QueryWrapper<>();
query.eq("is_deleted",0); query.eq("is_deleted", 0);
query.eq("api_key",apiKey); query.eq("api_key", apiKey);
return apiInterfaceMapper.selectOne(query); return apiInterfaceMapper.selectOne(query);
} }
@Override @Override
public ApiInterface getReqTargetInfo(String apiKey) { public ApiInterface getReqTargetInfo(String apiKey) {
QueryWrapper<ApiInterface> query = new QueryWrapper<>(); QueryWrapper<ApiInterface> query = new QueryWrapper<>();
query.eq("api_key",apiKey); query.eq("api_key", apiKey);
query.eq("status", ApiStatusEnum.ISSUE.name()); query.eq("status", ApiStatusEnum.ISSUE.name());
query.eq("is_deleted",0); query.eq("is_deleted", 0);
return apiInterfaceMapper.selectOne(query); return apiInterfaceMapper.selectOne(query);
} }
} }
...@@ -25,6 +25,7 @@ import javax.annotation.Resource; ...@@ -25,6 +25,7 @@ import javax.annotation.Resource;
import java.util.Date; import java.util.Date;
import static com.jz.dm.common.enums.org.OrgStatusEnum.fromTypeName; import static com.jz.dm.common.enums.org.OrgStatusEnum.fromTypeName;
import static com.jz.dm.common.enums.org.OrgTypeEnum.fromOrgTypeEnumName;
/** /**
* @author ZC * @author ZC
...@@ -53,7 +54,7 @@ public class OrganizationManageImpl implements OrganizationManageService { ...@@ -53,7 +54,7 @@ public class OrganizationManageImpl implements OrganizationManageService {
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())){ if (StringUtils.isNotBlank(req.getOrgName())){
query.eq("org_name",req.getOrgName()); query.like("org_name",req.getOrgName());
} }
if (StringUtils.isNotBlank(req.getOrgCode())){ if (StringUtils.isNotBlank(req.getOrgCode())){
query.eq("org_code",req.getOrgCode()); query.eq("org_code",req.getOrgCode());
...@@ -94,8 +95,7 @@ public class OrganizationManageImpl implements OrganizationManageService { ...@@ -94,8 +95,7 @@ public class OrganizationManageImpl implements OrganizationManageService {
} }
} }
if (StringUtils.isNotBlank(req.getOrgType())) { if (StringUtils.isNotBlank(req.getOrgType())) {
if (!Constants.AUTH_INT.equals(req.getOrgType()) || if (null == fromOrgTypeEnumName(req.getOrgType())){
!Constants.AUTH_OUT.equals(req.getOrgType())) {
return Result.of_error("组织类型不存在!"); return Result.of_error("组织类型不存在!");
} }
} }
...@@ -215,7 +215,7 @@ public class OrganizationManageImpl implements OrganizationManageService { ...@@ -215,7 +215,7 @@ public class OrganizationManageImpl implements OrganizationManageService {
QueryWrapper<ApiOrg> query = new QueryWrapper<>(); QueryWrapper<ApiOrg> query = new QueryWrapper<>();
query.eq("org_name", orgName); query.eq("org_name", orgName);
query.eq("is_deleted", 0); query.eq("is_deleted", 0);
query.eq("status", "3"); query.eq("status", OrgStatusEnum.NORMAL);
ApiOrg apiOrg = apiOrgMapper.selectOne(query); ApiOrg apiOrg = apiOrgMapper.selectOne(query);
if (null != apiOrg) { if (null != apiOrg) {
return apiOrg; return apiOrg;
......
...@@ -3,8 +3,6 @@ package com.jz.dm.service.impl; ...@@ -3,8 +3,6 @@ package com.jz.dm.service.impl;
import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jz.common.bean.SysUserDto; import com.jz.common.bean.SysUserDto;
import com.jz.common.constant.RedisMessageConstant; import com.jz.common.constant.RedisMessageConstant;
import com.jz.common.constant.ResultCode; import com.jz.common.constant.ResultCode;
...@@ -92,20 +90,11 @@ public class ProducerServiceImpl implements ProducerService { ...@@ -92,20 +90,11 @@ public class ProducerServiceImpl implements ProducerService {
* 获取文件列表 * 获取文件列表
* *
* @param projectId * @param projectId
* @param pageSize
* @param pageNum
* @return * @return
*/ */
@Override @Override
public IPage<ApiInterfaceFile> getFileCatalog(Long projectId, String pageNum, String pageSize) { public Result getFileCatalog(Long projectId) {
Integer pageN = Integer.valueOf(pageNum); return Result.of_success(apiInterfaceFileMapper.getFileFolderLevel(projectId));
Integer pageS = Integer.valueOf(pageSize);
IPage<ApiInterfaceFile> page = new Page<>(pageN, pageS);
QueryWrapper<ApiInterfaceFile> query = new QueryWrapper<>();
query.eq("project_id", projectId);
query.eq("is_deleted", 0);
query.orderByDesc("create_date");
return apiInterfaceFileMapper.selectPage(page, query);
} }
...@@ -277,10 +266,6 @@ public class ProducerServiceImpl implements ProducerService { ...@@ -277,10 +266,6 @@ 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("004");
if (null == currentUser) {
return Result.of_error("用户信息不存在");
}
ApiInterface apiInterface = apiInterfaceService.getApiInfo(req.getApiKey()); ApiInterface apiInterface = apiInterfaceService.getApiInfo(req.getApiKey());
if (null == apiInterface) { if (null == apiInterface) {
return Result.of_error("API基本信息为空!"); return Result.of_error("API基本信息为空!");
...@@ -308,40 +293,31 @@ public class ProducerServiceImpl implements ProducerService { ...@@ -308,40 +293,31 @@ public class ProducerServiceImpl implements ProducerService {
fields.setFieldName(jsonObject.get("name").toString()); fields.setFieldName(jsonObject.get("name").toString());
fields.setFieldType(jsonObject.get("type").toString()); fields.setFieldType(jsonObject.get("type").toString());
fields.setFieldDesc(jsonObject.get("desc").toString()); fields.setFieldDesc(jsonObject.get("desc").toString());
fields.setCreateUser(currentUser.getUserName()); fields.setCreateUser(req.getCreateUser());
listApiEsFields.add(fields); listApiEsFields.add(fields);
} }
//保存字段表中的字段信息 //保存字段表中的字段信息
if (CollectionUtils.isNotEmpty(listApiEsFields)) { if (CollectionUtils.isNotEmpty(listApiEsFields)) {
apiOpenApiEsFieldsMapper.insetBatch(listApiEsFields); apiOpenApiEsFieldsMapper.insetBatch(listApiEsFields);
} }
//调用dmp接口获取数据库连接信息
ApiSyncingDatasource dataSource = apiSyncingDatasourceMapper.selectById(req.getEsDataSource()); ApiSyncingDatasource dataSource = apiSyncingDatasourceMapper.selectById(req.getEsDataSource());
//api信息在redis中的key
String redisValueOfKey = apiInterface.getApiKey();
if (null != dataSource) { if (null != dataSource) {
//esjdbc 连接地址 用于接口中调用获取es数据 //esjdbc 连接地址 用于接口中调用获取es数据
redisUtils.set(TagConstants.OPEN_API_ESTAG_JDBC_INFO_NAMESPACE + redisValueOfKey, dataSource.getJdbcUrl()); redisUtils.set(TagConstants.OPEN_API_ESTAG_JDBC_INFO_NAMESPACE + apiInterface.getApiKey(), dataSource.getJdbcUrl());
} }
int result = 0; int result = 0;
ApiInterfaceCustom interfaceCustom = new ApiInterfaceCustom(); 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.setUpdateUser(currentUser.getUserName());
BeanUtils.copyProperties(req, apiEsTagconfig);
result = apiOpenApiEsTagconfigMapper.updateById(apiEsTagconfig);*/
BeanUtils.copyProperties(req, interfaceCustom); BeanUtils.copyProperties(req, interfaceCustom);
interfaceCustom.setUpdateDate(new Date()); interfaceCustom.setUpdateDate(new Date());
interfaceCustom.setUpdateUser(currentUser.getUserName()); interfaceCustom.setUpdateUser(req.getCreateUser());
result = apiInterfaceCustomMapper.updateById(interfaceCustom); result = apiInterfaceCustomMapper.updateById(interfaceCustom);
} else { //保存 } else { //保存
BeanUtils.copyProperties(req, interfaceCustom); BeanUtils.copyProperties(req, interfaceCustom);
interfaceCustom.setCreateUser(currentUser.getUserName()); interfaceCustom.setCreateUser(req.getCreateUser());
interfaceCustom.setApiInterfaceId(apiInterface.getId()); interfaceCustom.setApiInterfaceId(apiInterface.getId());
result = apiInterfaceCustomMapper.insert(interfaceCustom); result = apiInterfaceCustomMapper.insert(interfaceCustom);
/* apiEsTagconfig.setCreateUser(currentUser.getUserName());
BeanUtils.copyProperties(req, apiEsTagconfig);
result = apiOpenApiEsTagconfigMapper.insert(apiEsTagconfig);*/
} }
if (result <= 0) { if (result <= 0) {
return Result.of_error(ResultMsg.FAILURE); return Result.of_error(ResultMsg.FAILURE);
......
...@@ -13,11 +13,13 @@ import com.jz.dm.common.util.OpenApiRequest; ...@@ -13,11 +13,13 @@ import com.jz.dm.common.util.OpenApiRequest;
import com.jz.dm.common.util.OpenApiResponse; import com.jz.dm.common.util.OpenApiResponse;
import com.jz.dm.common.util.stream.HttpDownload; import com.jz.dm.common.util.stream.HttpDownload;
import com.jz.dm.gateway.OpenApiService; import com.jz.dm.gateway.OpenApiService;
import com.jz.dm.mapper.ApiAuthMapper;
import com.jz.dm.models.domian.ApiAuth; import com.jz.dm.models.domian.ApiAuth;
import com.jz.dm.models.domian.ApiInterface; 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;
...@@ -54,6 +56,8 @@ public class ApiQueryService extends ApiParamVerify implements OpenApiService { ...@@ -54,6 +56,8 @@ public class ApiQueryService extends ApiParamVerify implements OpenApiService {
@Autowired @Autowired
private ApiInterfaceService apiInterfaceService; private ApiInterfaceService apiInterfaceService;
@Autowired @Autowired
private ApiAuthMapper apiAuthMapper;
@Autowired
private AuthService authService; private AuthService authService;
@Autowired @Autowired
private RedisUtils redisUtils; private RedisUtils redisUtils;
...@@ -70,7 +74,7 @@ public class ApiQueryService extends ApiParamVerify implements OpenApiService { ...@@ -70,7 +74,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)
...@@ -98,23 +102,27 @@ public class ApiQueryService extends ApiParamVerify implements OpenApiService { ...@@ -98,23 +102,27 @@ public class ApiQueryService extends ApiParamVerify implements OpenApiService {
JSONObject jsonObject = JSONObject.parseObject(redisReqParam); JSONObject jsonObject = JSONObject.parseObject(redisReqParam);
String targetUrl = jsonObject.getString("targetUrl"); String targetUrl = jsonObject.getString("targetUrl");
String outputType = jsonObject.getString("outputType"); String outputType = jsonObject.getString("outputType");
bResult = rangRequestTarget(outputType, targetUrl, paramMap, response); bResult = rangRequestTarget(outputType, targetUrl, paramMap, response,false);
} else {//不存在查询数据库 } else {//不存在查询数据库
ApiInterface apiInterface = ApiInterface apiInterface =
apiInterfaceService.getReqTargetInfo(request.getApiKey()); apiInterfaceService.getReqTargetInfo(request.getApiKey());
if (null == apiInterface) { if (null == apiInterface) {
throw new GatewayException(GatewayResultCode.REQUEST_INFO_UNEXIST); throw new GatewayException(GatewayResultCode.REQUEST_INFO_UNEXIST);
} }
bResult = rangRequestTarget(apiInterface.getOutputType(), apiInterface.getTargetUrl(), paramMap, response); Boolean aBoolean = parameter.getBoolean("isTest");
bResult = rangRequestTarget(apiInterface.getOutputType(),
apiInterface.getTargetUrl(), paramMap, response,aBoolean);
} }
//调用成功请求数据银行扣款 //调用成功请求数据银行扣款
if (AuthModeEnum.POWER_CALL_MODE.name().equals(apiAuth.getAuthMode())){ if (AuthModeEnum.POWER_CALL_MODE.name().equals(apiAuth.getAuthMode())) {
notifierMinusMoney(parameter, bResult); notifierMinusMoney(parameter, bResult);
//按次调用时处理(处理为已调用)
authService.updateApiAuthStatus(apiAuth);
} }
} catch (Exception ex) { } catch (Exception ex) {
if (ex instanceof GatewayException) { if (ex instanceof GatewayException) {
//调用失败回调数据银行解冻 //调用失败回调数据银行解冻
if (AuthModeEnum.POWER_CALL_MODE.name().equals(apiAuth.getAuthMode())){ if (AuthModeEnum.POWER_CALL_MODE.name().equals(apiAuth.getAuthMode())) {
notifierMinusMoney(parameter, bResult); notifierMinusMoney(parameter, bResult);
} }
throw (GatewayException) ex; throw (GatewayException) ex;
...@@ -127,40 +135,55 @@ public class ApiQueryService extends ApiParamVerify implements OpenApiService { ...@@ -127,40 +135,55 @@ public class ApiQueryService extends ApiParamVerify implements OpenApiService {
} }
/** /**
* 远程请求获取数据 * 远程请求获取数据
* *
* @param outputType * @param outputType
* @param targetUrl * @param targetUrl
* @param param * @param param
* @param isTest
* @param response * @param response
*/ */
private boolean rangRequestTarget(String outputType, String targetUrl, private boolean rangRequestTarget(String outputType, String targetUrl,
Map<String, String> param, OpenApiResponse response) { Map<String, String> param, OpenApiResponse response,Boolean isTest) {
if (StringUtils.isBlank(outputType)) { if (StringUtils.isBlank(outputType)) {
outputType = ApiInfoOutTypeEnum.JSON.name(); outputType = ApiInfoOutTypeEnum.JSON.name();
} }
if (StringUtils.isBlank(targetUrl)) { if (StringUtils.isBlank(targetUrl)) {
throw new GatewayException(GatewayResultCode.ILLEGAL_REQUEST); throw new GatewayException(GatewayResultCode.ILLEGAL_REQUEST);
} }
if (ApiInfoOutTypeEnum.FLOW.name().equals(outputType)) {//文件流形式请求 if (isTest){ //测试数据
StringBuilder builder = new StringBuilder(); String respResult = httpsUtils.doGet(targetUrl, param);
builder.append(targetUrl).append("?"); JSONObject resp = JSONObject.parseObject(respResult);
for (Map.Entry<String, String> entry : param.entrySet()) { if (null != resp && 200 == resp.getInteger("code")) {
String key = entry.getKey(); response.setCode(GatewayResultCode.SUCCESS.getCode());
String value = entry.getValue(); response.setMsg(GatewayResultCode.SUCCESS.getMsg());
builder.append(key).append(LoggingConstants.AND_EQUAL) response.setAttribute(resp.getString("data"));
.append(value).append(LoggingConstants.AND_SPILT); return true;
} else {
log.error("~~~~~~~~~~~~~~~~远程请求异常~~~~~~~~~~~~~~~~~");
throw new GatewayException(GatewayResultCode.DISTANCE_REQUEST_EXCEPTION);
} }
String baseUrl = builder.substring(0, builder.length() - 1); }else {
HttpDownload.download(baseUrl); if (ApiInfoOutTypeEnum.FLOW.name().equals(outputType)) {//文件流形式请求
response.setCode(GatewayResultCode.SUCCESS.getCode()); StringBuilder builder = new StringBuilder();
response.setMsg(GatewayResultCode.SUCCESS.getMsg()); builder.append(targetUrl).append("?");
return true; for (Map.Entry<String, String> entry : param.entrySet()) {
} else if (ApiInfoOutTypeEnum.JSON.name().equals(outputType)) { //json格式请求 String key = entry.getKey();
response.setAttribute("调用成功!"); String value = entry.getValue();
String respResult = httpsUtils.doGet(targetUrl, param); builder.append(key).append(LoggingConstants.AND_EQUAL)
.append(value).append(LoggingConstants.AND_SPILT);
}
String baseUrl = builder.substring(0, builder.length() - 1);
HttpDownload.download(baseUrl);
response.setCode(GatewayResultCode.SUCCESS.getCode());
response.setMsg(GatewayResultCode.SUCCESS.getMsg());
return true;
} else if (ApiInfoOutTypeEnum.JSON.name().equals(outputType)) { //json格式请求
response.setAttribute("调用成功!");
response.setMsg(GatewayResultCode.SUCCESS.getMsg());
response.setCode(GatewayResultCode.SUCCESS.getCode());
/*String respResult = httpsUtils.doGet(targetUrl, param);
JSONObject resp = JSONObject.parseObject(respResult); JSONObject resp = JSONObject.parseObject(respResult);
if (null != resp && 200 == resp.getInteger("code")) { if (null != resp && 200 == resp.getInteger("code")) {
response.setCode(GatewayResultCode.SUCCESS.getCode()); response.setCode(GatewayResultCode.SUCCESS.getCode());
...@@ -170,14 +193,18 @@ public class ApiQueryService extends ApiParamVerify implements OpenApiService { ...@@ -170,14 +193,18 @@ public class ApiQueryService extends ApiParamVerify implements OpenApiService {
} else { } else {
log.error("~~~~~~~~~~~~~~~~远程请求异常~~~~~~~~~~~~~~~~~"); log.error("~~~~~~~~~~~~~~~~远程请求异常~~~~~~~~~~~~~~~~~");
throw new GatewayException(GatewayResultCode.DISTANCE_REQUEST_EXCEPTION); throw new GatewayException(GatewayResultCode.DISTANCE_REQUEST_EXCEPTION);
}*/
} else {
throw new GatewayException(GatewayResultCode.OUTPUT_TYPE_EXCEPTION);
} }
} else {
throw new GatewayException(GatewayResultCode.OUTPUT_TYPE_EXCEPTION);
} }
return false;
} }
/** /**
* 通知扣款 * 通知扣款
*
* @param parameter * @param parameter
* @param bResult * @param bResult
*/ */
...@@ -186,19 +213,20 @@ public class ApiQueryService extends ApiParamVerify implements OpenApiService { ...@@ -186,19 +213,20 @@ public class ApiQueryService extends ApiParamVerify implements OpenApiService {
Integer userId = parameter.getInteger("userId"); Integer userId = parameter.getInteger("userId");
String dataPrice = parameter.getString("dataPrice"); String dataPrice = parameter.getString("dataPrice");
JSONObject jsonReq = new JSONObject(); JSONObject jsonReq = new JSONObject();
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);//true 调用成功 扣款 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) {
if (200 != paramsResult.getInteger("code")){ if (200 != paramsResult.getInteger("code")) {
log.info("~~~~~~~~~~~~~~~调用数据银行扣款失败~~~~~~~~~~~~~"); log.info("~~~~~~~~~~~~~~~调用数据银行扣款失败~~~~~~~~~~~~~");
throw new GatewayException(GatewayResultCode.CALL_AMOUNT_NOT_ENOUGH); throw new GatewayException(GatewayResultCode.CALL_AMOUNT_NOT_ENOUGH);
} }
} }
} }
/** /**
* 限流返回方法 * 限流返回方法
* *
......
...@@ -14,6 +14,7 @@ import javassist.bytecode.LocalVariableAttribute; ...@@ -14,6 +14,7 @@ import javassist.bytecode.LocalVariableAttribute;
import javassist.bytecode.MethodInfo; import javassist.bytecode.MethodInfo;
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.aspectj.lang.JoinPoint; import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Around;
...@@ -79,6 +80,10 @@ public class SystemLogAspect { ...@@ -79,6 +80,10 @@ public class SystemLogAspect {
params += JsonUtils.objectToJson(joinPoint.getArgs()[i]) + ";"; params += JsonUtils.objectToJson(joinPoint.getArgs()[i]) + ";";
} }
} }
if (StringUtils.isNotBlank(params)){
params= params.substring(0,params.length()-1);
params= params.split(";")[0];
}
//获取请求路径 //获取请求路径
String url = UrlUtil.getServerUrl(request); String url = UrlUtil.getServerUrl(request);
// 访问项目名 // 访问项目名
...@@ -87,7 +92,7 @@ public class SystemLogAspect { ...@@ -87,7 +92,7 @@ public class SystemLogAspect {
//动态修改其参数 //动态修改其参数
//注意,如果调用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);
String paramsList = jsonObject.getString("params"); String paramsList = jsonObject.getString("openApiParams");
com.alibaba.fastjson.JSONObject jsonParamsList = com.alibaba.fastjson.JSONObject.parseObject(paramsList); com.alibaba.fastjson.JSONObject jsonParamsList = com.alibaba.fastjson.JSONObject.parseObject(paramsList);
try { try {
ApiReqLog reqLog = new ApiReqLog(); ApiReqLog reqLog = new ApiReqLog();
...@@ -97,7 +102,8 @@ public class SystemLogAspect { ...@@ -97,7 +102,8 @@ public class SystemLogAspect {
reqLog.setResponseParams("");//响应参数 reqLog.setResponseParams("");//响应参数
reqLog.setRequestUrl(url); reqLog.setRequestUrl(url);
reqLog.setRequestMethod(contextPath); reqLog.setRequestMethod(contextPath);
reqLog.setEncryMode(jsonObject.getString("signType")); //加密方式:MD5,RSA // reqLog.setEncryMode(jsonObject.getString("signType")); //加密方式:MD5,RSA
reqLog.setEncryMode("MD5"); //加密方式暂时写死MD5
reqLog.setTransMode(request.getMethod());//传输方式 GET POST reqLog.setTransMode(request.getMethod());//传输方式 GET POST
reqLog.setRequestToken(jsonParamsList.getString("authCode")); reqLog.setRequestToken(jsonParamsList.getString("authCode"));
reqLog.setRequestTime(new Date()); reqLog.setRequestTime(new Date());
......
...@@ -71,6 +71,8 @@ spring: ...@@ -71,6 +71,8 @@ spring:
auto: true auto: true
#ignoreRedis true存入 false不存 api.timeout.default #ignoreRedis true存入 false不存 api.timeout.default
sendgrid:
api-key:
dmp: dmp:
ignoreRedis: true ignoreRedis: true
openapi: openapi:
...@@ -97,3 +99,10 @@ data: ...@@ -97,3 +99,10 @@ data:
token: #dataBank 制作验签 token: #dataBank 制作验签
dataBank: dataBank123 dataBank: dataBank123
apiRequest:
testExample:
apiKey: On6uAg3U09tLY28M
sign: F2A8E3CFE528D6AE5C5B075046653F3E
...@@ -7,6 +7,19 @@ ...@@ -7,6 +7,19 @@
status, remark, create_date, create_user, update_date, status, remark, create_date, create_user, update_date,
update_user, is_deleted update_user, is_deleted
</sql> </sql>
<update id="updateAuthBatch">
<if test="list != null and list.size() >0">
<foreach collection="list" item="item" index="index" open="" close="" separator=";">
update t_api_interface
<set>
status ='UN_VALID',
handler= 1,
is_deleted = 1,
</set>
where id = ${item.id}
</foreach>
</if>
</update>
<select id="selectAuthDetail" resultType="com.jz.dm.models.dto.AuthInfoDto"> <select id="selectAuthDetail" resultType="com.jz.dm.models.dto.AuthInfoDto">
SELECT au.id AS id, SELECT au.id AS id,
au.api_org_id AS apiOrgId, au.api_org_id AS apiOrgId,
...@@ -55,7 +68,9 @@ ...@@ -55,7 +68,9 @@
DATE_FORMAT(au.create_date,'%Y-%m-%d %H:%i:%s') AS createDate, DATE_FORMAT(au.create_date,'%Y-%m-%d %H:%i:%s') AS createDate,
au.create_user AS createUser, au.create_user AS createUser,
ao.org_name AS orgName, ao.org_name AS orgName,
ai.api_key AS apiKey ai.api_key AS apiKey,
ai.api_path AS apiPath,
ai.join_type AS joinType
FROM t_api_auth AS au FROM t_api_auth AS au
JOIN t_api_interface AS ai ON au.api_interface_id = ai.id AND ai.is_deleted =0 AND ai.`status` ='ISSUE' JOIN t_api_interface AS ai ON au.api_interface_id = ai.id AND ai.is_deleted =0 AND ai.`status` ='ISSUE'
JOIN t_api_org AS ao ON au.api_org_id = ao.id AND ao.`status` ='NORMAL' AND ao.is_deleted =0 JOIN t_api_org AS ao ON au.api_org_id = ao.id AND ao.`status` ='NORMAL' AND ao.is_deleted =0
......
...@@ -3,5 +3,24 @@ ...@@ -3,5 +3,24 @@
"http://mybatis.org/dtd/mybatis-3-mapper.dtd"> "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.jz.dm.mapper.ApiInterfaceFileMapper"> <mapper namespace="com.jz.dm.mapper.ApiInterfaceFileMapper">
<select id="getFileFolderLevel" resultType="com.jz.dm.models.dto.ApiInterfaceFileDto">
SELECT id AS id,parent_id AS parentId,levels AS levels FROM (
SELECT id,parent_id,
@le:= IF (parent_id = 0 ,0,IF( LOCATE( CONCAT('|',parent_id,':'),@pathlevel) > 0 ,
SUBSTRING_INDEX( SUBSTRING_INDEX(@pathlevel,CONCAT('|',parent_id,':'),-1),'|',1) +1
,@le+1) ) levels
,@pathlevel:= CONCAT(@pathlevel,'|',id,':', @le ,'|') pathlevel
/* , @pathnodes:= IF( parent_id =0,',0',
CONCAT_WS(',',
IF( LOCATE( CONCAT('|',parent_id,':'),@pathall) > 0 ,
SUBSTRING_INDEX( SUBSTRING_INDEX(@pathall,CONCAT('|',parent_id,':'),-1),'|',1)
,@pathnodes ) ,parent_id ) )paths*/
,@pathall:=CONCAT(@pathall,'|',id,':', @pathnodes ,'|') pathall
FROM t_api_interface_file,
(SELECT @le:=0,@pathlevel:='', @pathall:='',@pathnodes:='') vv
WHERE project_id =#{projectId}
ORDER BY parent_id,id
) src
ORDER BY id
</select>
</mapper> </mapper>
\ No newline at end of file
...@@ -9,5 +9,29 @@ ...@@ -9,5 +9,29 @@
update_user, is_deleted update_user, is_deleted
</sql> </sql>
<select id="listApiInterfaceInfo" resultType="com.jz.dm.models.domian.ApiInterface">
SELECT ai.*,
/* ai.id AS id,
ai.api_key AS apiKey,
ai.join_type AS joinType,
ai.create_user AS createUser,*/
COUNT(ar.id) AS callStat,
SUM(ar.request_time) AS requestTimeStat
FROM t_api_interface AS ai
LEFT JOIN t_api_req_log AS ar ON ai.api_key =ar.api_key
AND ar.is_deleted =0
AND DATE_FORMAT(CURDATE(), '%Y%m') = DATE_FORMAT(ar.create_date, '%Y%m')
${ew.customSqlSegment}
</select>
<select id="selectDetail" resultType="com.jz.dm.models.domian.ApiInterface">
SELECT ai.*,
aic.request_param AS requestParam,
aic.response_param AS responseParam,
aic.resp_code AS respCode
FROM t_api_interface AS ai
LEFT JOIN t_api_interface_custom AS aic ON ai.id = aic.api_interface_id AND aic.is_deleted =0
WHERE ai.id =#{id}
</select>
</mapper> </mapper>
\ No newline at end of file
...@@ -5,7 +5,7 @@ import com.jz.common.utils.HttpsUtils; ...@@ -5,7 +5,7 @@ import com.jz.common.utils.HttpsUtils;
import com.jz.common.utils.Md5; import com.jz.common.utils.Md5;
import com.jz.dm.common.util.MapUtil; import com.jz.dm.common.util.MapUtil;
import com.jz.dm.gateway.SpringTestCase; import com.jz.dm.gateway.SpringTestCase;
import org.junit.jupiter.api.Test; import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
/** /**
......
...@@ -10,6 +10,7 @@ import com.jz.dm.models.req.organizationManage.OrganizationManageDetailQueryReq; ...@@ -10,6 +10,7 @@ import com.jz.dm.models.req.organizationManage.OrganizationManageDetailQueryReq;
import com.jz.dm.models.req.organizationManage.OrganizationManageListQueryReq; import com.jz.dm.models.req.organizationManage.OrganizationManageListQueryReq;
import com.jz.dm.models.req.organizationManage.OrganizationManageUpdateReq; import com.jz.dm.models.req.organizationManage.OrganizationManageUpdateReq;
import com.jz.dm.service.OrganizationManageService; import com.jz.dm.service.OrganizationManageService;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
/** /**
...@@ -29,7 +30,7 @@ public class TestOrganizationManage extends SpringTestCase { ...@@ -29,7 +30,7 @@ public class TestOrganizationManage extends SpringTestCase {
/** /**
* 查询类列表信息 * 查询类列表信息
*/ */
// @Test @Test
public void getOrgList(){ public void getOrgList(){
OrganizationManageListQueryReq req = new OrganizationManageListQueryReq(); OrganizationManageListQueryReq req = new OrganizationManageListQueryReq();
req.setPageNum(1); req.setPageNum(1);
...@@ -40,10 +41,10 @@ public class TestOrganizationManage extends SpringTestCase { ...@@ -40,10 +41,10 @@ public class TestOrganizationManage extends SpringTestCase {
/** /**
* 查询详情信息 * 查询详情信息
*/ */
// @Test @Test
public void getOrgDetail(){ public void getOrgDetail(){
OrganizationManageDetailQueryReq req = new OrganizationManageDetailQueryReq(); OrganizationManageDetailQueryReq req = new OrganizationManageDetailQueryReq();
req.setId(1L); req.setId(2L);
Result detail = organizationManageService.getOrganizationDetail(req); Result detail = organizationManageService.getOrganizationDetail(req);
ApiOrg apiOrg = (ApiOrg)detail.getData(); ApiOrg apiOrg = (ApiOrg)detail.getData();
System.out.println(apiOrg); System.out.println(apiOrg);
...@@ -51,7 +52,7 @@ public class TestOrganizationManage extends SpringTestCase { ...@@ -51,7 +52,7 @@ public class TestOrganizationManage extends SpringTestCase {
/** /**
* 添加组织信息 * 添加组织信息
*/ */
//@Test @Test
public void addOrg(){ public void addOrg(){
OrganizationManageAddReq req = new OrganizationManageAddReq(); OrganizationManageAddReq req = new OrganizationManageAddReq();
req.setOrgName("数据银行"); req.setOrgName("数据银行");
...@@ -68,7 +69,7 @@ public class TestOrganizationManage extends SpringTestCase { ...@@ -68,7 +69,7 @@ public class TestOrganizationManage extends SpringTestCase {
/** /**
* 更新组织信息 * 更新组织信息
*/ */
//@Test @Test
public void updateOrg(){ public void updateOrg(){
OrganizationManageUpdateReq req = new OrganizationManageUpdateReq(); OrganizationManageUpdateReq req = new OrganizationManageUpdateReq();
req.setId(8L); req.setId(8L);
......
...@@ -5,7 +5,7 @@ import com.jz.common.utils.HttpsUtils; ...@@ -5,7 +5,7 @@ import com.jz.common.utils.HttpsUtils;
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.gateway.SpringTestCase; import com.jz.dm.gateway.SpringTestCase;
import org.junit.jupiter.api.Test; import org.junit.Test;
/** /**
* @author ZC * @author ZC
......
...@@ -3,7 +3,7 @@ package com.jz.dm.gateway.orther; ...@@ -3,7 +3,7 @@ package com.jz.dm.gateway.orther;
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.dm.gateway.SpringTestCase; import com.jz.dm.gateway.SpringTestCase;
import org.junit.jupiter.api.Test; import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import java.util.HashMap; import java.util.HashMap;
......
...@@ -4,7 +4,7 @@ import com.alibaba.fastjson.JSONObject; ...@@ -4,7 +4,7 @@ import com.alibaba.fastjson.JSONObject;
import com.jz.common.utils.HttpsUtils; import com.jz.common.utils.HttpsUtils;
import com.jz.dm.gateway.SpringTestCase; import com.jz.dm.gateway.SpringTestCase;
import com.jz.dm.service.ProducerService; import com.jz.dm.service.ProducerService;
import org.junit.jupiter.api.Test; import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import java.util.HashMap; import java.util.HashMap;
......
...@@ -4,7 +4,7 @@ import com.jz.dm.common.util.RedisSerializableUtil; ...@@ -4,7 +4,7 @@ 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 com.jz.dm.models.req.make.MakeDataBankApiReq;
import net.sf.json.JSONObject; import net.sf.json.JSONObject;
import org.junit.jupiter.api.Test; import org.junit.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,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>
...@@ -34,12 +35,6 @@ ...@@ -34,12 +35,6 @@
<groupId>org.springframework.session</groupId> <groupId>org.springframework.session</groupId>
<artifactId>spring-session-data-redis</artifactId> <artifactId>spring-session-data-redis</artifactId>
</dependency> </dependency>
<!--httpclient包-->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.6</version>
</dependency>
<!-- fastjson --> <!-- fastjson -->
<dependency> <dependency>
<groupId>com.alibaba</groupId> <groupId>com.alibaba</groupId>
...@@ -93,7 +88,6 @@ ...@@ -93,7 +88,6 @@
<dependency> <dependency>
<groupId>org.apache.httpcomponents</groupId> <groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId> <artifactId>httpclient</artifactId>
<version>4.5.6</version>
</dependency> </dependency>
</dependencies> </dependencies>
</project> </project>
\ No newline at end of file
...@@ -48,6 +48,7 @@ ...@@ -48,6 +48,7 @@
<lombok.version>1.18.16</lombok.version> <lombok.version>1.18.16</lombok.version>
<spring-cloud.version>Finchley.SR1</spring-cloud.version> <spring-cloud.version>Finchley.SR1</spring-cloud.version>
<commons-net.version>3.5</commons-net.version> <commons-net.version>3.5</commons-net.version>
<http.client>4.5.6</http.client>
</properties> </properties>
<dependencyManagement> <dependencyManagement>
...@@ -222,6 +223,12 @@ ...@@ -222,6 +223,12 @@
<artifactId>commons-net</artifactId> <artifactId>commons-net</artifactId>
<version>${commons-net.version}</version> <version>${commons-net.version}</version>
</dependency> </dependency>
<!--httpclient包-->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>${http.client}</version>
</dependency>
</dependencies> </dependencies>
</dependencyManagement> </dependencyManagement>
......
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