Commit c6700669 authored by ysongq's avatar ysongq

Merge remote-tracking branch 'origin/dm_dev' into dm_dev

# Conflicts:
#	jz-dm-apigateway/src/main/java/com/jz/dm/service/impl/ProducerServiceImpl.java
parents 978ef031 1ef7d947
......@@ -55,7 +55,8 @@ CREATE TABLE `t_api_interface_custom` (
`update_date` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '修改时间',
`update_user` varchar(100) DEFAULT NULL 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自定义信息表';
#api api文件表
......@@ -86,8 +87,9 @@ CREATE TABLE `t_api_org` (
`org_desc` varchar(300) DEFAULT NULL COMMENT '组织描述',
`org_cn_name` varchar(100) DEFAULT NULL COMMENT '组织英文名称',
`org_phone` varchar(20) NULL DEFAULT NULL COMMENT '组织电话',
`linkman` varchar(50) NULL DEFAULT NULL COMMENT '组织联系人'
`org_type` varchar(20) NULL DEFAULT NULL COMMENT '组织类型:OUT 外部组织, IN 内部组织',
`status` varchar(100) NOT NULL COMMENT '状态(NORMAL-正常 FREEZE-冻结 CANCEL-注销)',
`status` tinyint(2) DEFAULT '1' COMMENT '状态: 0- 注销 1- 正常',
`org_mail` varchar(100) DEFAULT NULL COMMENT '组织邮箱',
`org_sort` int(10) DEFAULT '999' COMMENT '组织排序',
`parent_id` varchar(100) DEFAULT NULL COMMENT '父类组织编码',
......@@ -116,6 +118,7 @@ CREATE TABLE `t_api_auth` (
`auth_mode` varchar(50) DEFAULT NULL COMMENT '授权方式:POWER_CALL_MODE 按次调用 ,RECORD_TIME_MODE 按时间调用 PERMANENT_TIME_MODE 永久有效',
`valid_start_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-无效)',
`remark` varchar(500) DEFAULT NULL COMMENT '备注',
`create_date` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
......@@ -143,7 +146,9 @@ CREATE TABLE `t_api_req_log` (
`encry_mode` varchar(20) DEFAULT NULL COMMENT '加密方式:MD5,RSA',
`trans_mode` varchar(20) DEFAULT NULL COMMENT '传输方式:POST,GET',
`request_token` varchar(64) DEFAULT NULL COMMENT '客户请求token',
`request_time` datetime DEFAULT NULL COMMENT '请求时间',
`request_consuming` varchar(64) DEFAULT NULL COMMENT '请求总耗时',
`request_start_time` datetime DEFAULT NULL COMMENT '请求开始时间',
`request_end_time` datetime DEFAULT NULL COMMENT '请求结束时间',
`status` varchar(50) DEFAULT NULL COMMENT '状态:SUCCEED 请求成功, FAIL 请求失败',
`remark` varchar(500) DEFAULT NULL COMMENT '备注',
`create_date` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
......
ALTER TABLE `t_department`
ADD COLUMN `linkman` varchar(100) NULL AFTER `industry`;
\ No newline at end of file
#添加唯一索引
ALTER TABLE `t_api_interface_custom`
ADD UNIQUE INDEX `API_ID_UNIQ_INDEX` (`api_interface_id`) USING BTREE ;
\ No newline at end of file
......@@ -9,7 +9,6 @@
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>jz-dm-apigateway</artifactId>
<dependencies>
<!-- spring-boot -->
<dependency>
......@@ -33,12 +32,6 @@
<artifactId>mybatis-plus-boot-starter</artifactId>
</dependency>
<!-- 引入Druid依赖,阿里巴巴所提供的数据源 -->
<!-- <dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
</dependency>-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
......@@ -61,12 +54,6 @@
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
......@@ -110,6 +97,27 @@
<!-- <version>0.9.0.RELEASE</version>-->
</dependency>
<!-- 客户端需要引入 Transport 模块来与 Sentinel 控制台进行通信 -->
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-transport-simple-http</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-parameter-flow-control</artifactId>
</dependency>
<!-- 开启注解 -->
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-annotation-aspectj</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-core</artifactId>
</dependency>
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
......@@ -120,6 +128,14 @@
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</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>
<build>
......
......@@ -27,4 +27,7 @@ public class TagConstants {
// es handler 相关
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:";
//redis限流相关
public static final String OPEN_API_REDIS_LIMIT_KEY = "jz:openapi:redis:limit:";
}
......@@ -45,9 +45,6 @@ public enum GatewayResultCode implements ResultCode {
/** 请求超过限制 */
RATE_LIMIT_EXCEEDED("RATE_LIMIT_EXCEEDED", "请求超过限制"),
/** 无效路由类型 */
ILLEGAL_ROUTE_TYPE("ILLEGAL_ROUTE_TYPE", "无效路由类型"),
/** 提交数据过大 */
POST_DATA_TOO_LARGE("POST_DATA_TOO_LARGE", "提交数据过大"),
......
......@@ -27,6 +27,10 @@ public enum ApiStatusEnum {
* 冻结
*/
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删除/确认提示接口")
@GetMapping(value = "/delDMPApiInterface")
public Mono<Result> delDMPApiInterface(@RequestParam (name="type")String type,
@RequestParam (name="apiKey")String apiKey) {
return Mono.fromSupplier(() -> apiInterfaceService.dmpDeleteAuth(type,apiKey));
}
/**
* @Description:API测试调用
* @return: DMP-API删除
* @Author: Mr.zhang
* @Date: 2020-12-24
*/
@ApiOperation("API调用测试接口")
@GetMapping(value = "/apiTestApiInterface")
public Mono<Result> apiTestApiInterface(@RequestParam (name="apiKey")String apiKey) {
return Mono.fromSupplier(() -> apiInterfaceService.apiTestInterface(apiKey));
}
}
......@@ -7,10 +7,7 @@ import com.jz.dm.service.ApiLogService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Mono;
import javax.validation.Valid;
......@@ -54,4 +51,15 @@ public class ApiLogController {
public Mono<Result> getApiLogDetail(@RequestBody @Valid LogInfoDetailReq req) {
return Mono.fromSupplier(() -> apiLogService.getApiLogDetail(req));
}
/**
* @Description:Api调用统计
* @return: DMP-Api调用统计
* @Author: Mr.zhang
* @Date: 2020-12-24
*/
@ApiOperation("DMP-Api调用统计")
@GetMapping(value = "/countAPiCallStat")
public Mono<Result> countAPiCallStat(@RequestParam(name = "date") String date) {
return Mono.fromSupplier(() -> apiLogService.countAPiCallStat(date));
}
}
......@@ -73,6 +73,17 @@ public class AuthController {
public Mono<Result> selectAuthListInfo(@RequestBody @Valid AuthListInfoReq req) {
return Mono.fromSupplier(() -> authService.getAuthListInfo(req));
}
/**
* @Description: 授权模糊查询列表信息
* @return: 认证列表查询
* @Author: Mr.zhang
* @Date: 2020-12-26
*/
@ApiOperation("授权模糊查询列表信息")
@GetMapping(value = "/getAuthNameList")
public Mono<Result> getAuthNameList(@RequestParam("key") String key) {
return Mono.fromSupplier(() -> authService.getAuthNameList(key));
}
/**
* @Description: 认证信息修改
* @return: 认证信息修改
......
......@@ -25,6 +25,7 @@ import java.util.Map;
* @author zc
*/
@RestController
@RequestMapping("api/request")
@Api(tags = {"api请求controller"})
public class GatewayController {
......
......@@ -4,7 +4,6 @@ import com.jz.common.utils.Result;
import com.jz.dm.models.req.organizationManage.OrganizationManageAddReq;
import com.jz.dm.models.req.organizationManage.OrganizationManageDetailQueryReq;
import com.jz.dm.models.req.organizationManage.OrganizationManageListQueryReq;
import com.jz.dm.models.req.organizationManage.OrganizationManageUpdateReq;
import com.jz.dm.service.OrganizationManageService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
......@@ -58,7 +57,7 @@ public class OrganizationManageController {
* @Author: Mr.zhang
* @Date: 2020-12-24
*/
@ApiOperation("添加组织")
@ApiOperation("添加/更新组织")
@PostMapping(value = "/add")
public Mono<Result> add(@RequestBody @Valid OrganizationManageAddReq req) {
return Mono.fromSupplier(() -> organizationManageService.add(req));
......@@ -68,11 +67,11 @@ public class OrganizationManageController {
* @Author: Mr.zhang
* @Date: 2020-12-24
*/
@ApiOperation("更新组织信息")
/* @ApiOperation("更新组织信息")
@PostMapping(value = "/update")
public Mono<Result> update(@RequestBody @Valid OrganizationManageUpdateReq req) {
return Mono.fromSupplier(() -> organizationManageService.update(req));
}
}*/
/**
* @Description:注销组织
* @Author: Mr.zhang
......
......@@ -36,10 +36,8 @@ public class ProducerController {
*/
@ApiOperation("获取文件夹列表")
@GetMapping(value = "/getFileCatalog")
public Mono<Result> getFileCatalog(@RequestParam(name = "projectId")Long projectId,
@RequestParam(name = "pageNum",defaultValue = "1",required = false)String pageNum,
@RequestParam(name = "pageSize",defaultValue = "10",required = false)String pageSize) {
return Mono.fromSupplier(() -> Result.of_success(producerService.getFileCatalog(projectId,pageNum,pageSize)));
public Mono<Result> getFileCatalog(@RequestParam(name = "projectId")Long projectId) {
return Mono.fromSupplier(() -> producerService.getFileCatalog(projectId));
}
/**
* @Description:创建文件夹
......@@ -115,7 +113,7 @@ public class ProducerController {
* @Date: 2020-12-26
*/
@ApiOperation("保存修改的api信息")
@PostMapping(value = "/保存修改的api信息")
@PostMapping(value = "/saveUpdate")
public Mono<Result> saveUpdateAPiInfo(@RequestBody @Valid ApiInterfaceReq req) {
return Mono.fromSupplier(() -> producerService.saveUpdateAPiInfo(req));
}
......
package com.jz.dm.filter;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.jz.common.utils.HttpsUtils;
import com.jz.common.utils.RedisUtils;
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.apiInterface.ApiStatusEnum;
import com.jz.dm.common.enums.auth.AuthReqTypeEnum;
import com.jz.dm.common.enums.org.OrgStatusEnum;
import com.jz.dm.common.exception.GatewayException;
import com.jz.dm.common.util.DateUtil;
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.ApiInterface;
import com.jz.dm.models.domian.ApiOrg;
......@@ -28,6 +28,7 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
......@@ -52,6 +53,8 @@ public class AuthFilter extends AbstractFilter {
private OrganizationManageService organizationManageService;
@Autowired
private ApiInterfaceService apiInterfaceService;
@Resource
private ApiInterfaceMapper apiInterfaceMapper;
@Autowired
private RedisUtils redisUtils;
@Autowired
......@@ -77,8 +80,13 @@ public class AuthFilter extends AbstractFilter {
if (null == apiInterface) {
throw new GatewayException(GatewayResultCode.ILLEGAL_REQUEST);
}
if (!ApiStatusEnum.ISSUE.name().equals(apiInterface.getStatus())) {
throw new GatewayException(GatewayResultCode.API_STATUS_EXCEPTION);
//下架状态$$ 检查是否有有效调用的api,如果有就放行,没有就置为无效
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());
if (null != parameter) {
......@@ -87,11 +95,18 @@ public class AuthFilter extends AbstractFilter {
if (null == authAuth) {
throw new GatewayException(GatewayResultCode.REQUEST_NOT_AUTH);
}
if ("1".equals(authAuth.getHandler())) {//处理状态,已经调用成功后授权码失效
throw new GatewayException(GatewayResultCode.ILLEGAL_REQUEST);
}
//查询认证组织信息
ApiOrg apiOrg = organizationManageService.getAuthOrganization(authAuth.getApiOrgId());
if (null == apiOrg) {
throw new GatewayException(GatewayResultCode.ORG_NOT_EXIST);
}
//状态检查(只限制按次请求$$ 不限制按时间请求)
if (!apiOrg.getStatus()) {
throw new GatewayException(GatewayResultCode.ORG_STATE_EXCEPTION);
}
checkBill(request, authCode, authAuth, apiOrg);
}
chain.doFilter(request, response);
......@@ -124,15 +139,12 @@ public class AuthFilter extends AbstractFilter {
ApiAuth authAuth, ApiOrg apiOrg) throws ParseException {
switch (authAuth.getAuthMode()) {
case "POWER_CALL_MODE": //按次调用
//状态检查(只限制按次请求$$ 不限制按时间请求)
if (!OrgStatusEnum.NORMAL.name().equals(apiOrg.getStatus())) {
throw new GatewayException(GatewayResultCode.ORG_STATE_EXCEPTION);
}
//查询数据银行银行余额是否充足
//getDataAmountResult(request);
getDataAmountResult(request);
try { //记录请求次数(每天限制请求次数)
String limitKey = request.getApiKey() + LoggingConstants.AND_SPILT + authCode;
Integer reqValue = (Integer)redisUtils.getObj(limitKey);
// String limitKey = TagConstants.OPEN_API_REDIS_LIMIT_KEY + authCode;
String limitKey = authCode;
String reqValue = (String)redisUtils.getObj(limitKey);
long timeOut = 0;
if (AuthReqTypeEnum.DAY.name().equals(authAuth.getReqType())) { //按天
timeOut = DateUtil.calculateNowResidueTime();
......@@ -141,12 +153,12 @@ public class AuthFilter extends AbstractFilter {
} else if (AuthReqTypeEnum.YEAR.name().equals(authAuth.getReqType())) {//按年
//暂时不支持年
}
if (null != reqValue && reqValue != 0) {
// Integer value = Integer.valueOf(reqKey);
if (reqValue > authAuth.getReqFrequency()) {//超出最大请求次数
if (null != reqValue) {
Integer value = Integer.valueOf(reqValue);
if (value > authAuth.getReqFrequency()) {//超出最大请求次数
throw new GatewayException(GatewayResultCode.REQUEST_LIMIT_EXCEPTION);
} else if (reqValue <= authAuth.getReqFrequency()) {
redisUtils.delAndAdd(limitKey, limitKey, reqValue + 1, timeOut);
} else if (value <= authAuth.getReqFrequency()) {
redisUtils.delAndAdd(limitKey, limitKey, value + 1, timeOut);
}
} else {
redisUtils.set(limitKey, 1, timeOut);
......@@ -164,6 +176,7 @@ public class AuthFilter extends AbstractFilter {
Date validEndTime = authAuth.getValidEndTime();
//如果 date1 在 date2 之前,before 返回 true,否则返回 false
if (currentDate.after(validEndTime)) {//超出时间
updateCallTimeStatus(authAuth);//查看是否为已处理状态
throw new GatewayException(GatewayResultCode.RATE_LIMIT_EXCEEDED);
}
break;
......@@ -174,6 +187,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);
}
}
}
/**
* 按次调用检查余额是否充足
*
......@@ -192,7 +217,7 @@ public class AuthFilter extends AbstractFilter {
pObject.put("assetsId", assetsId);
pObject.put("userId", userId);
pObject.put("dataPrice", dataPrice);
String respResult = httpUtils.submitPost(balanceUrl, pObject.toString());
String respResult = httpUtils.submitPost(balanceUrl+"/mall/financeCustomerAssets/findAssets", pObject.toString());
JSONObject result = JSONObject.parseObject(respResult);
if (null != result) {
if (200 != result.getInteger("code")) {
......@@ -202,4 +227,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);
}
}
}
}
......@@ -3,8 +3,8 @@ package com.jz.dm.filter;
import com.jz.dm.common.constant.Constants;
import com.jz.dm.common.enums.Format;
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.exception.GatewayException;
import com.jz.dm.common.util.StringUtil;
import com.jz.dm.models.enity.GatewayRequest;
import com.jz.dm.models.enity.GatewayResponse;
......@@ -27,15 +27,16 @@ public class CheckArgsFilter extends AbstractFilter {
public String getFilterName() {
return "CheckArgsFilter";
}
@Override
protected void internalDoFilter(GatewayRequest request, GatewayResponse response,
FilterChain chain) {
// 校验参数非空
if (StringUtil.isEmpty(request.getApiKey()) || StringUtil.isEmpty(request.getMethod())
|| StringUtil.isEmpty(request.getSignType())|| StringUtil.isEmpty(request.getSign())
|| StringUtil.isEmpty(request.getTimestamp())|| StringUtil.isEmpty(request.getParams())) {
|| StringUtil.isEmpty(request.getSignType()) || StringUtil.isEmpty(request.getSign())
|| StringUtil.isEmpty(request.getTimestamp()) || StringUtil.isEmpty(request.getParams())) {
throw new GatewayException(GatewayResultCode.ILLEGAL_ARGUMENT); //无效参数
}
}
// 设置默认值
if (StringUtil.isEmpty(request.getFormat())) {
request.setFormat(Format.JSON.name());
......@@ -54,6 +55,4 @@ public class CheckArgsFilter extends AbstractFilter {
}
chain.doFilter(request, response);
}
}
......@@ -8,6 +8,8 @@ import com.jz.dm.models.dto.AuthInfoDto;
import com.jz.dm.models.req.auth.AuthDetailInfoReq;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**api授权信息表 mapper
* @author zc
*
......@@ -28,4 +30,11 @@ public interface ApiAuthMapper extends BaseMapper<ApiAuth> {
* @return
*/
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;
import com.jz.common.base.BaseMapper;
import com.jz.dm.models.domian.ApiInterfaceFile;
import com.jz.dm.models.dto.ApiInterfaceFileDto;
import java.util.List;
/**
* @author ZC
......@@ -13,4 +16,10 @@ import com.jz.dm.models.domian.ApiInterfaceFile;
* @Description:
**/
public interface ApiInterfaceFileMapper extends BaseMapper<ApiInterfaceFile> {
/**
* 查询项目文件等级列表
* @param projectId
* @return
*/
List<ApiInterfaceFileDto> getFileFolderLevel(Long projectId);
}
package com.jz.dm.mapper;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
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.ApiInterfaceCustom;
import com.jz.dm.models.req.api.ApiInterfaceDetailReq;
import org.apache.ibatis.annotations.Param;
/**
* @author ZC
......@@ -15,4 +20,26 @@ import com.jz.dm.models.domian.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);
/**
* 获取测试请求数据
* @param apiKey
* @return
*/
ApiInterfaceCustom getTestData(String apiKey);
}
......@@ -2,8 +2,12 @@ package com.jz.dm.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.jz.dm.models.domian.ApiReqLog;
import com.jz.dm.models.dto.ApiCallDataDto;
import org.apache.ibatis.annotations.Select;
import java.util.Date;
import java.util.List;
/**api请求日志表 mapper
* @author ybz
*/
......@@ -16,4 +20,11 @@ public interface ApiReqLogMapper extends BaseMapper<ApiReqLog> {
*/
@Select("SELECT * FROM t_api_req_log WHERE id =(SELECT MAX(id) FROM t_api_req_log)")
ApiReqLog maxId(Long id);
/**
* 统计API调用
* @return
*/
List<ApiCallDataDto> countApiCallMonthData(Date date);
}
......@@ -97,6 +97,13 @@ public class ApiAuth extends BaseObject implements Serializable {
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date validEndTime;
/**
* 处理状态:0 未处理, 1 已处理
*/
@TableField("handler")
private Integer handler;
/**
* 状态(1-正常 2-作废)
*/
......
......@@ -2,6 +2,7 @@ package com.jz.dm.models.domian;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.jz.dm.common.base.BaseObject;
import lombok.Data;
import lombok.EqualsAndHashCode;
......@@ -34,6 +35,7 @@ public class ApiInterface extends BaseObject implements Serializable {
* api名称
*/
@TableField("api_name")
@JsonIgnore
private String apiName;
/**
......@@ -136,4 +138,33 @@ public class ApiInterface extends BaseObject implements Serializable {
@TableField("file_id")
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;
}
......@@ -50,6 +50,11 @@ public class ApiOrg extends BaseObject implements Serializable {
*/
@TableField("org_phone")
private String orgPhone;
/**
* 组织联系人
*/
@TableField("linkman")
private String linkman;
/**
* 组织类型 OUT 外部组织 IN 内部组织
*/
......@@ -57,10 +62,10 @@ public class ApiOrg extends BaseObject implements Serializable {
private String orgType;
/**
* 状态(NORMAL-正常 FREEZE-冻结 CANCEL-注销)
* 状态(NORMAL-正常(true) FREEZE-冻结 CANCEL-注销(false))
*/
@TableField("status")
private String status;
private Boolean status;
/**
* 组织邮箱
......
......@@ -90,13 +90,27 @@ public class ApiReqLog implements Serializable {
private String requestToken;
/**
* 请求时间
* 请求总耗时
*/
@ApiModelProperty("请求时间")
@TableField("request_time")
@ApiModelProperty("请求总耗时")
@TableField("request_consuming")
private Double requestConsuming;
/**
* 请求开始时间
*/
@ApiModelProperty("请求开始时间")
@TableField("request_start_time")
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date requestStartTime;
/**
* 请求结束时间
*/
@ApiModelProperty("请求结束时间")
@TableField("request_end_time")
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date requestTime;
private Date requestEndTime;
/**
* 请求状态: SUCCEED 成功 ,FAIL 失败
......
package com.jz.dm.models.dto;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.io.Serializable;
/**
* @author ZC
* @PACKAGE_NAME: com.jz.dm.models.dto
* @PROJECT_NAME: jz-dm-parent
* @NAME: ApiCallDataDto
* @DATE: 2021-1-20/10:17
* @DAY_NAME_SHORT: 周三
* @Description:
**/
@Data
@ApiModel("api计量统计dto")
public class ApiCallDataDto implements Serializable {
@ApiModelProperty(value = "调用总次数")
private Integer callLimit;
@ApiModelProperty(value = "调用总耗时")
private Double callTimeStat;
}
package com.jz.dm.models.dto;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.io.Serializable;
/**
* @author ZC
* @PACKAGE_NAME: com.jz.dm.models.resp
* @PROJECT_NAME: jz-dm-parent
* @NAME: ApiInterfaceFileResp
* @DATE: 2021-1-15/14:33
* @DAY_NAME_SHORT: 周五
* @Description:
**/
@Data
@ApiModel("api文件夹列表返回体")
public class ApiInterfaceFileDto implements Serializable {
@ApiModelProperty(value = "文件自增id")
private Long id;
@ApiModelProperty(value="父级id")
private Long parentId;
@ApiModelProperty(value="父到子之间级数")
private Integer levels;
}
......@@ -45,6 +45,12 @@ public class AuthInfoDto implements Serializable {
@ApiModelProperty(value = "状态(1-正常 2-作废")
private String status;
@ApiModelProperty(value = "请求路径")
private String apiPath;
@ApiModelProperty(value = "api类型")
private String joinType;
@ApiModelProperty(value = "备注")
private String remark;
......
package com.jz.dm.models.req.api;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import javax.validation.constraints.NotNull;
import java.io.Serializable;
/**
* @author ZC
* @PACKAGE_NAME: com.jz.dm.models.req
* @PROJECT_NAME: jz-dm-parent
* @NAME: LogInfoDetailReq
* @DATE: 2020-12-25/15:18
* @DAY_NAME_SHORT: 周五
* @Description:
**/
@Data
@ApiModel("API详情信息")
public class ApiInterfaceDetailReq implements Serializable {
@ApiModelProperty(value = "id",required = true)
@NotNull(message = "id不能为空")
private Long id;
}
package com.jz.dm.models.req.api;
import com.jz.common.bean.BasePageBean;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.io.Serializable;
/**
* @author ZC
* @PACKAGE_NAME: com.jz.dm.models.req
* @PROJECT_NAME: jz-dm-parent
* @NAME: LogInfoListReq
* @DATE: 2020-12-25/14:59
* @DAY_NAME_SHORT: 周五
* @Description:
**/
@Data
@ApiModel("APi信息列表")
public class ApiInterfaceInfoListReq extends BasePageBean implements Serializable {
@ApiModelProperty(value = "状态:SUCCEED 请求成功, FAIL 请求失败")
private String status;
@ApiModelProperty(value = "ApiKey")
private String apiKey;
}
......@@ -38,9 +38,9 @@ public class AuthUserApiReq implements Serializable {
@NotNull(message = "组织编码不能为空")
private String orgCode;
@ApiModelProperty(value = "授权类型:DATA_BANK_AUTH 数据银行 , DMP_AUTH 授权",required = true)
/* @ApiModelProperty(value = "授权类型:DATA_BANK_AUTH 数据银行 , DMP_AUTH 授权",required = true)
@NotNull(message = "授权类型不能为空")
private String authType;
private String authType;*/
@ApiModelProperty(value = "授权方式:POWER_CALL_MODE 按次调用 ,RECORD_TIME_MODE 按时间调用,PERMANENT_TIME_MODE 永久有效",required = true)
@NotNull(message = "授权方式不能为空")
......@@ -58,4 +58,8 @@ public class AuthUserApiReq implements Serializable {
@ApiModelProperty(value = "备注",required = false)
private String remark;
@ApiModelProperty(value = "创建用户",required = false)
private String createUser;
}
......@@ -27,4 +27,7 @@ public class SaltResetReq implements Serializable {
@NotNull(message = "盐值不能为空")
private String salt;*/
@ApiModelProperty(value = "创建用户",required = false)
private String createUser;
}
......@@ -27,7 +27,7 @@ public class MakeBigDataApiReq implements Serializable {
@NotNull(message = "apiType不能为空")
private String apiType;*/
@ApiModelProperty(value = "apiKey",required = true)
@ApiModelProperty(value = "apiKey",required = false)
@NotNull(message = "apiKey不能为空")
public String apiKey;
......@@ -63,6 +63,9 @@ public class MakeBigDataApiReq implements Serializable {
@NotNull(message = "字段列表不能为空")
private String tableFields;
@ApiModelProperty(value = "创建用户",required = false)
public String createUser;
//@ApiModelProperty(value = "项目id",required = true)
//@NotNull(message="项目id不能为空")
//public Long projectId;
......
......@@ -40,9 +40,22 @@ public class OrganizationManageAddReq implements Serializable {
@ApiModelProperty(value = "组织电话",required = false)
private String orgPhone;
@ApiModelProperty(value = "组织联系人",required = false)
private String linkman;
@ApiModelProperty(value = "备注",required = false)
private String remark;
@ApiModelProperty(value = "创建用户",required = false)
private String createUser;
@ApiModelProperty(value = "创建用户",required = false)
private String updateUser;
@ApiModelProperty(value = "id ----更新时必传",required = false)
private Long id;
@ApiModelProperty(value = "状态(true-正常 false-注销----更新时传",required = false)
private Boolean status;
}
......@@ -26,4 +26,7 @@ public class OrganizationManageListQueryReq extends BasePageBean implements Seri
@ApiModelProperty(value = "组织编码(组织唯一标识)")
private String orgCode;
@ApiModelProperty(value = "组织联系人")
private String linkman;
}
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.ApiInterface;
import com.jz.dm.models.req.api.ApiInterfaceDetailReq;
import com.jz.dm.models.req.api.ApiInterfaceInfoListReq;
/**
* @author ZC
......@@ -35,4 +39,50 @@ public interface ApiInterfaceService {
* @return
*/
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);
/**
* api测试接口
* @param apiKey
* @return
*/
Result apiTestInterface(String apiKey);
}
......@@ -43,4 +43,11 @@ public interface ApiLogService {
* @param jsonObject
*/
void updateLog(Long id, JSONObject jsonObject);
/**
* 统计API调用数据
* @param date
* @return
*/
Result countAPiCallStat(String date);
}
......@@ -70,4 +70,18 @@ public interface AuthService {
* @return
*/
ApiAuth getAuthInfo( String authCode);
/**
* 更新API授权状态
* @param apiAuth
* @return
*/
int updateApiAuthStatus(ApiAuth apiAuth);
/**
* 根据名称/组织编号摸索查询
* @param key
* @return
*/
Result getAuthNameList(String key);
}
......@@ -6,7 +6,6 @@ import com.jz.dm.models.domian.ApiOrg;
import com.jz.dm.models.req.organizationManage.OrganizationManageAddReq;
import com.jz.dm.models.req.organizationManage.OrganizationManageDetailQueryReq;
import com.jz.dm.models.req.organizationManage.OrganizationManageListQueryReq;
import com.jz.dm.models.req.organizationManage.OrganizationManageUpdateReq;
/**
* @author ZC
......@@ -44,7 +43,7 @@ public interface OrganizationManageService {
* @param req
* @return
*/
Result update(OrganizationManageUpdateReq req);
//Result update(OrganizationManageUpdateReq req);
/**
* 根据id注销组织
......
package com.jz.dm.service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.jz.common.utils.Result;
import com.jz.dm.models.domian.ApiInterfaceFile;
import com.jz.dm.models.req.make.*;
/**
......@@ -91,12 +89,10 @@ public interface ProducerService {
/**
* 获取文件列表
* @param pageNum
* @param pageSize
* @param projectId
* @return
*/
IPage<ApiInterfaceFile> getFileCatalog(Long projectId ,String pageNum, String pageSize);
Result getFileCatalog(Long projectId);
/**
* 创建文件夹
......
package com.jz.dm.service.impl;
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.HttpsUtils;
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.auth.AuthModeEnum;
import com.jz.dm.mapper.ApiAuthMapper;
import com.jz.dm.mapper.ApiInterfaceMapper;
import com.jz.dm.models.domian.ApiAuth;
import com.jz.dm.models.domian.ApiInterface;
import com.jz.dm.models.domian.ApiInterfaceCustom;
import com.jz.dm.models.dto.ApiCallDataDto;
import com.jz.dm.models.req.api.ApiInterfaceDetailReq;
import com.jz.dm.models.req.api.ApiInterfaceInfoListReq;
import com.jz.dm.service.ApiInterfaceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
/**
* @author ZC
......@@ -25,12 +41,196 @@ import javax.annotation.Resource;
@Slf4j
public class ApiInterfaceServiceImpl implements ApiInterfaceService {
/**
* 测试url
*/
public static final String testUrl ="";
@Resource
private ApiInterfaceMapper apiInterfaceMapper;
@Resource
private ApiAuthMapper apiAuthMapper;
@Autowired
private HttpsUtils httpsUtils;
/**
* 获取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(apiInterface.getId());
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 apiInterfaceId
*/
private void updateApiAuthStatus(Long apiInterfaceId) {
QueryWrapper<ApiAuth> queryWra = new QueryWrapper<>();
queryWra.eq("api_interface_id", apiInterfaceId);
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;
}
/**
* api测试接口
*
* @param apiKey
* @return
*/
@Override
public Result apiTestInterface(String apiKey) {
ApiInterfaceCustom apiInterfaceCustom= apiInterfaceMapper.getTestData(apiKey);
if (null == apiInterfaceCustom) {
return Result.of_error(ResultMsg.DATA_NOT_FOUND);
}
/* if (StringUtils.isNotBlank(apiInterfaceCustom.getApiExample())){
httpsUtils.doGet(testUrl,"");
}else {
}*/
return Result.of_success(ResultMsg.SUCCESS);
}
/**
* 获取用户授权信息
*
* @param apiKey
* @param authCode
* @return
......@@ -38,40 +238,41 @@ public class ApiInterfaceServiceImpl implements ApiInterfaceService {
@Override
public ApiAuth getApiAuthInfo(String apiKey, String authCode) {
QueryWrapper<ApiInterface> query = new QueryWrapper<>();
query.eq("is_deleted",0);
query.eq("is_deleted", 0);
query.eq("api_key", apiKey);
ApiInterface apiInterface = apiInterfaceMapper.selectOne(query);
if (null != apiInterface){
if (null != apiInterface) {
QueryWrapper<ApiAuth> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("is_deleted",0);
queryWrapper.eq("auth_code",authCode);
queryWrapper.eq("is_deleted", 0);
queryWrapper.eq("auth_code", authCode);
ApiAuth apiAuth = apiAuthMapper.selectOne(queryWrapper);
if (null != apiAuth){
return apiAuth;
if (null != apiAuth) {
return apiAuth;
}
}
return null;
return null;
}
/**
* 获取API信息
*
* @param apiKey
* @return
*/
@Override
public ApiInterface getApiInfo(String apiKey) {
QueryWrapper<ApiInterface> query = new QueryWrapper<>();
query.eq("is_deleted",0);
query.eq("api_key",apiKey);
query.eq("is_deleted", 0);
query.eq("api_key", apiKey);
return apiInterfaceMapper.selectOne(query);
}
@Override
public ApiInterface getReqTargetInfo(String apiKey) {
QueryWrapper<ApiInterface> query = new QueryWrapper<>();
query.eq("api_key",apiKey);
query.eq("api_key", apiKey);
query.eq("status", ApiStatusEnum.ISSUE.name());
query.eq("is_deleted",0);
query.eq("is_deleted", 0);
return apiInterfaceMapper.selectOne(query);
}
}
......@@ -19,6 +19,8 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
/**
......@@ -34,6 +36,7 @@ import java.util.Date;
@Slf4j
public class ApiLogServiceImpl implements ApiLogService {
@Resource
private ApiReqLogMapper apiReqLogMapper;
// 加锁
......@@ -77,7 +80,22 @@ public class ApiLogServiceImpl implements ApiLogService {
public void insetLogInfo(ApiReqLog reqLog) {
apiReqLogMapper.insert(reqLog);
}
/**
* api计量统计
* @param date
* @return
*/
@Override
public Result countAPiCallStat(String date ) {
Date dateParam =null;
try {
SimpleDateFormat dateFormat = new SimpleDateFormat("YYYY-MM");
dateParam = dateFormat.parse(date);
}catch (Exception ex){
log.error("时间转换异常:{}",ex.getMessage());
}
return Result.of_success(apiReqLogMapper.countApiCallMonthData(dateParam));
}
/**
* 根据id更新日志
......@@ -98,6 +116,12 @@ public class ApiLogServiceImpl implements ApiLogService {
}
update.set("response_params",jsonObject.toString());
update.set("update_date",new Date());
update.set("request_end_time",new Date());
Calendar calendar = Calendar.getInstance();
calendar.setTime(apiReqLog.getRequestStartTime());
Long time = System.currentTimeMillis() - calendar.getTimeInMillis() / 1000;
double timeConsuming = time.doubleValue();
update.set("request_consuming",timeConsuming);
update.eq("id",id);
if (apiReqLogMapper.update(null,update) == 0){
log.info("~~~~~~~~~~~更新日志信息失败~~~~~~~~");
......@@ -109,4 +133,6 @@ public class ApiLogServiceImpl implements ApiLogService {
log.error("更新日志返回信息异常:{}",ex.getMessage());
}
}
}
......@@ -14,7 +14,6 @@ import com.jz.dm.models.domian.ApiOrg;
import com.jz.dm.models.req.organizationManage.OrganizationManageAddReq;
import com.jz.dm.models.req.organizationManage.OrganizationManageDetailQueryReq;
import com.jz.dm.models.req.organizationManage.OrganizationManageListQueryReq;
import com.jz.dm.models.req.organizationManage.OrganizationManageUpdateReq;
import com.jz.dm.service.OrganizationManageService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
......@@ -24,7 +23,7 @@ import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.Date;
import static com.jz.dm.common.enums.org.OrgStatusEnum.fromTypeName;
import static com.jz.dm.common.enums.org.OrgTypeEnum.fromOrgTypeEnumName;
/**
* @author ZC
......@@ -52,14 +51,17 @@ public class OrganizationManageImpl implements OrganizationManageService {
public IPage<ApiOrg> listOrganization(OrganizationManageListQueryReq req) {
IPage<ApiOrg> page = new Page<>(req.getPageNum(), req.getPageSize());
QueryWrapper<ApiOrg> query = new QueryWrapper<>();
if (StringUtils.isNotBlank(req.getOrgName())){
query.eq("org_name",req.getOrgName());
query.like("org_name",req.getOrgName());
}
if (StringUtils.isNotBlank(req.getLinkman())){
query.like("linkman",req.getLinkman());
}
if (StringUtils.isNotBlank(req.getOrgCode())){
query.eq("org_code",req.getOrgCode());
}
query.eq("is_deleted", 0);
query.ne("status",OrgStatusEnum.CANCEL);
query.orderByDesc("create_date");
return apiOrgMapper.selectPage(page, query);
}
......@@ -75,18 +77,44 @@ public class OrganizationManageImpl implements OrganizationManageService {
QueryWrapper<ApiOrg> query = new QueryWrapper<>();
query.eq("is_deleted", 0);
query.eq("id", req.getId());
query.ne("status",OrgStatusEnum.CANCEL);
/*query.ne("status",0);*/
return Result.of_success(apiOrgMapper.selectOne(query));
}
/**
* 添加组织
* 添加组织/更新
*
* @param req
* @return
*/
@Override
public Result add(OrganizationManageAddReq req) {
ApiOrg apiOrg = new ApiOrg();
BeanUtils.copyProperties(req, apiOrg);
if (null != req.getId()){//更新
ApiOrg org = apiOrgMapper.selectById(req.getId());
if (null == org){
return Result.of_error(ResultMsg.DATA_NOT_EXIST);
}
org.setUpdateDate(new Date());
if ( apiOrgMapper.updateById(apiOrg) > 0){
return Result.of_success(ResultMsg.UPDATE_SUCCESS);
}
}else {//添加
Result result = addOrg(req, apiOrg);
if (result != null) return result;
}
return Result.of_error(ResultMsg.FAILURE);
}
/**
* 添加组织
* @param req
* @param apiOrg
* @return
*/
private Result addOrg(OrganizationManageAddReq req, ApiOrg apiOrg) {
String coding = "";
if (StringUtils.isNotBlank(req.getOrgName())) {
ApiOrg orgNameInfo = getOrgNameInfo(req.getOrgName());
if (null != orgNameInfo) {
......@@ -94,14 +122,10 @@ public class OrganizationManageImpl implements OrganizationManageService {
}
}
if (StringUtils.isNotBlank(req.getOrgType())) {
if (!Constants.AUTH_INT.equals(req.getOrgType()) ||
!Constants.AUTH_OUT.equals(req.getOrgType())) {
if (null == fromOrgTypeEnumName(req.getOrgType())){
return Result.of_error("组织类型不存在!");
}
}
String coding = "";
ApiOrg apiOrg = new ApiOrg();
BeanUtils.copyProperties(req, apiOrg);
if (StringUtils.isNotBlank(req.getOrgType()) //内部组织
&& Constants.AUTH_INT.equals(req.getOrgType())) {
coding = generateCode(req.getOrgName(), Constants.AUTH_INT);
......@@ -112,11 +136,10 @@ public class OrganizationManageImpl implements OrganizationManageService {
return Result.of_error("生成组织编码异常!");
}
apiOrg.setOrgCode(coding);//组织编码
apiOrg.setStatus(OrgStatusEnum.NORMAL.name());//正常
if (apiOrgMapper.insert(apiOrg) > 0) {
return Result.of_success(ResultMsg.INSERT_SUCCESS);
}
return Result.of_error(ResultMsg.INSERT_FAIL);
return null;
}
/**
......@@ -144,7 +167,7 @@ public class OrganizationManageImpl implements OrganizationManageService {
* @param req
* @return
*/
@Override
/* @Override
public Result update(OrganizationManageUpdateReq req) {
ApiOrg apiOrg = apiOrgMapper.selectById(req.getId());
if (null == apiOrg) {
......@@ -166,7 +189,7 @@ public class OrganizationManageImpl implements OrganizationManageService {
return Result.of_success(ResultMsg.UPDATE_SUCCESS);
}
return Result.of_success(ResultMsg.UPDATE_FAIL);
}
}*/
/**
* 注销组织
......@@ -182,7 +205,7 @@ public class OrganizationManageImpl implements OrganizationManageService {
}
UpdateWrapper<ApiOrg> delete = new UpdateWrapper<>();
delete.set("is_deleted", 1);
delete.set("status",OrgStatusEnum.CANCEL);
delete.set("status",0);
delete.eq("id", id);
if (apiOrgMapper.update(null, delete) > 0) {
return Result.of_success(ResultMsg.UPDATE_SUCCESS);
......@@ -215,7 +238,7 @@ public class OrganizationManageImpl implements OrganizationManageService {
QueryWrapper<ApiOrg> query = new QueryWrapper<>();
query.eq("org_name", orgName);
query.eq("is_deleted", 0);
query.eq("status", "3");
query.eq("status", OrgStatusEnum.NORMAL);
ApiOrg apiOrg = apiOrgMapper.selectOne(query);
if (null != apiOrg) {
return apiOrg;
......
......@@ -3,10 +3,6 @@ package com.jz.dm.service.impl;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
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.constant.RedisMessageConstant;
import com.jz.common.constant.ResultCode;
import com.jz.common.constant.ResultMsg;
import com.jz.common.exception.ResponseException;
......@@ -14,7 +10,6 @@ import com.jz.common.utils.HttpsUtils;
import com.jz.common.utils.Md5;
import com.jz.common.utils.RedisUtils;
import com.jz.common.utils.Result;
import com.jz.dm.common.constant.TagConstants;
import com.jz.dm.common.enums.GeneralStatusTypeEnum;
import com.jz.dm.common.enums.apiInterface.ApiInfoOutTypeEnum;
import com.jz.dm.common.enums.apiInterface.ApiStatusEnum;
......@@ -97,15 +92,8 @@ public class ProducerServiceImpl implements ProducerService {
* @return
*/
@Override
public IPage<ApiInterfaceFile> getFileCatalog(Long projectId, String pageNum, String pageSize) {
Integer pageN = Integer.valueOf(pageNum);
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);
public Result getFileCatalog(Long projectId) {
return Result.of_success(apiInterfaceFileMapper.getFileFolderLevel(projectId));
}
......@@ -179,7 +167,6 @@ public class ProducerServiceImpl implements ProducerService {
}
String signStr = dataBankToken + req.getJoinType();
String signResult = Md5.encrypt(signStr, "");
System.out.println(signResult);
if (!signResult.equals(req.getSign())) {
return Result.of_error("签名错误!");
}
......@@ -211,9 +198,9 @@ public class ProducerServiceImpl implements ProducerService {
ApiInterface apiInterface = saveApiInterFace(req, apiKey, apiType);
saveApiInterFaceCustom(req, apiKey, apiInterface.getId());
JSONObject object = new JSONObject();
object.put("targetUrl",req.getTargetUrl());
object.put("outputType",req.getOutputType());
saveObjOnRedis(apiInterface.getApiKey(),object);
object.put("targetUrl", req.getTargetUrl());
object.put("outputType", req.getOutputType());
saveObjOnRedis(apiInterface.getApiKey(), object);
}
/**
......@@ -278,10 +265,6 @@ public class ProducerServiceImpl implements ProducerService {
@Override
@Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
public Result addBigDataMakeApi(MakeBigDataApiReq req) {
SysUserDto currentUser = getLoginUser("004");
if (null == currentUser) {
return Result.of_error("用户信息不存在");
}
ApiInterface apiInterface = apiInterfaceService.getApiInfo(req.getApiKey());
if (null == apiInterface) {
return Result.of_error("API基本信息为空!");
......@@ -309,40 +292,31 @@ public class ProducerServiceImpl implements ProducerService {
fields.setFieldName(jsonObject.get("name").toString());
fields.setFieldType(jsonObject.get("type").toString());
fields.setFieldDesc(jsonObject.get("desc").toString());
fields.setCreateUser(currentUser.getUserName());
fields.setCreateUser(req.getCreateUser());
listApiEsFields.add(fields);
}
//保存字段表中的字段信息
if (CollectionUtils.isNotEmpty(listApiEsFields)) {
apiOpenApiEsFieldsMapper.insetBatch(listApiEsFields);
}
/* //调用dmp接口获取数据库连接信息
ApiSyncingDatasource dataSource = apiSyncingDatasourceMapper.selectById(req.getEsDataSource());
//api信息在redis中的key
String redisValueOfKey = apiInterface.getApiKey();
if (null != dataSource) {
//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;
ApiInterfaceCustom interfaceCustom = new ApiInterfaceCustom();
//ApiOpenApiEsTagconfig apiEsTagconfig = new ApiOpenApiEsTagconfig();
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);
interfaceCustom.setUpdateDate(new Date());
interfaceCustom.setUpdateUser(currentUser.getUserName());
interfaceCustom.setUpdateUser(req.getCreateUser());
result = apiInterfaceCustomMapper.updateById(interfaceCustom);
} else { //保存
BeanUtils.copyProperties(req, interfaceCustom);
interfaceCustom.setCreateUser(currentUser.getUserName());
interfaceCustom.setCreateUser(req.getCreateUser());
interfaceCustom.setApiInterfaceId(apiInterface.getId());
result = apiInterfaceCustomMapper.insert(interfaceCustom);
/* apiEsTagconfig.setCreateUser(currentUser.getUserName());
BeanUtils.copyProperties(req, apiEsTagconfig);
result = apiOpenApiEsTagconfigMapper.insert(apiEsTagconfig);*/
}
if (result <= 0) {
return Result.of_error(ResultMsg.FAILURE);
......@@ -392,9 +366,9 @@ public class ProducerServiceImpl implements ProducerService {
throw ResponseException.of_error("保存Api信息失败!");
}
JSONObject object = new JSONObject();
object.put("targetUrl",req.getTargetUrl());
object.put("outputType",ApiInfoOutTypeEnum.JSON.name());
saveObjOnRedis(apiInterface.getApiKey(),object);
object.put("targetUrl", req.getTargetUrl());
object.put("outputType", ApiInfoOutTypeEnum.JSON.name());
saveObjOnRedis(apiInterface.getApiKey(), object);
return Result.of_success(ResultMsg.INSERT_SUCCESS, apiKey);
}
......@@ -411,13 +385,13 @@ public class ProducerServiceImpl implements ProducerService {
}
try {
String paramKey = redisUtils.get(apiKey);
if (null != paramKey){
if (null != paramKey) {
redisUtils.del(apiKey);
}
redisUtils.set(apiKey, params.toString());
} catch (Exception ex) {
log.error("缓存api制作数据异常:{}",ex.getMessage());
ex.printStackTrace();
log.error("缓存api制作数据异常:{}", ex.getMessage());
ex.printStackTrace();
}
}
......@@ -530,9 +504,9 @@ public class ProducerServiceImpl implements ProducerService {
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);
object.put("targetUrl", req.getTargetUrl());
object.put("outputType", ApiInfoOutTypeEnum.JSON.name());
saveObjOnRedis(apiInterface.getApiKey(), object);
return Result.of_success(ResultMsg.UPDATE_FAIL);
}
......@@ -693,26 +667,6 @@ public class ProducerServiceImpl implements ProducerService {
return random;
}
/**
* 获取当前登录用户
*
* @param userType
* @return
*/
protected SysUserDto getLoginUser(String userType) {
SysUserDto currentUser = null;
switch (userType) {
case "004": //平台用户004
currentUser = (SysUserDto) redisUtils.getObj("USER_" + RedisMessageConstant.SENDTYPE_LOGIN_SYS);
break;
case "003": //商城用户 003
currentUser = (SysUserDto) redisUtils.getObj("USER_" + RedisMessageConstant.SENDTYPE_LOGIN_CUSTOMER);
break;
default:
return null;
}
return currentUser;
}
@Override
public Result saveObjOnRedis() {
......@@ -732,9 +686,9 @@ public class ProducerServiceImpl implements ProducerService {
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);
object.put("targetUrl", "www.baidu.common");
object.put("outputType", ApiInfoOutTypeEnum.JSON.name());
saveObjOnRedis("apiKeyTest002", object);
return Result.ok();
}
......
......@@ -18,6 +18,7 @@ import com.jz.dm.models.domian.ApiInterface;
import com.jz.dm.service.ApiInterfaceService;
import com.jz.dm.service.AuthService;
import com.jz.dm.web.annotation.AccessLimit;
import com.jz.dm.web.annotation.ApiLogAspect;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
......@@ -60,8 +61,8 @@ public class ApiQueryService extends ApiParamVerify implements OpenApiService {
@Autowired
private HttpsUtils httpsUtils;
@Value("${data.bank.withholdUrl}")
private String withholdUrl;
@Value("${data.bank.balanceUrl}")
private String balanceUrl;
/**
* API请求逻辑处理
......@@ -70,7 +71,7 @@ public class ApiQueryService extends ApiParamVerify implements OpenApiService {
* @param response
*/
@Override
// @ApiLogAspect(description = "API请求日志")
@ApiLogAspect(description = "API请求日志")
@AccessLimit(limit = 10000, sec = 1)
@SentinelResource(value = "api.gateway", fallback = "fallbackGateway")
@Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
......@@ -105,16 +106,19 @@ public class ApiQueryService extends ApiParamVerify implements OpenApiService {
if (null == apiInterface) {
throw new GatewayException(GatewayResultCode.REQUEST_INFO_UNEXIST);
}
bResult = rangRequestTarget(apiInterface.getOutputType(), apiInterface.getTargetUrl(), paramMap, response);
bResult = rangRequestTarget(apiInterface.getOutputType(),
apiInterface.getTargetUrl(), paramMap, response);
}
//调用成功请求数据银行扣款
if (AuthModeEnum.POWER_CALL_MODE.name().equals(apiAuth.getAuthMode())){
if (AuthModeEnum.POWER_CALL_MODE.name().equals(apiAuth.getAuthMode())) {
notifierMinusMoney(parameter, bResult);
//按次调用时处理(处理为已调用)
authService.updateApiAuthStatus(apiAuth);
}
} catch (Exception ex) {
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);
}
throw (GatewayException) ex;
......@@ -127,7 +131,6 @@ public class ApiQueryService extends ApiParamVerify implements OpenApiService {
}
/**
* 远程请求获取数据
*
......@@ -160,7 +163,9 @@ public class ApiQueryService extends ApiParamVerify implements OpenApiService {
return true;
} else if (ApiInfoOutTypeEnum.JSON.name().equals(outputType)) { //json格式请求
response.setAttribute("调用成功!");
String respResult = httpsUtils.doGet(targetUrl, param);
response.setMsg(GatewayResultCode.SUCCESS.getMsg());
response.setCode(GatewayResultCode.SUCCESS.getCode());
/*String respResult = httpsUtils.doGet(targetUrl, param);
JSONObject resp = JSONObject.parseObject(respResult);
if (null != resp && 200 == resp.getInteger("code")) {
response.setCode(GatewayResultCode.SUCCESS.getCode());
......@@ -170,14 +175,17 @@ public class ApiQueryService extends ApiParamVerify implements OpenApiService {
} else {
log.error("~~~~~~~~~~~~~~~~远程请求异常~~~~~~~~~~~~~~~~~");
throw new GatewayException(GatewayResultCode.DISTANCE_REQUEST_EXCEPTION);
}
}*/
} else {
throw new GatewayException(GatewayResultCode.OUTPUT_TYPE_EXCEPTION);
}
return false;
}
/**
* 通知扣款
*
* @param parameter
* @param bResult
*/
......@@ -186,19 +194,20 @@ public class ApiQueryService extends ApiParamVerify implements OpenApiService {
Integer userId = parameter.getInteger("userId");
String dataPrice = parameter.getString("dataPrice");
JSONObject jsonReq = new JSONObject();
jsonReq.put("assetsId",assetsId);
jsonReq.put("userId",userId);
jsonReq.put("dataPrice",dataPrice);
jsonReq.put("callStatus",bResult);//true 调用成功 扣款 false 调用失败,解冻金额
String responseResult = httpsUtils.submitPost(withholdUrl, jsonReq.toString());
jsonReq.put("assetsId", assetsId);
jsonReq.put("userId", userId);
jsonReq.put("dataPrice", dataPrice);
jsonReq.put("callStatus", bResult);//true 调用成功 扣款 false 调用失败,解冻金额
String responseResult = httpsUtils.submitPost(balanceUrl+"/mall/financeCustomerAssets/unfreezeMoney", jsonReq.toString());
JSONObject paramsResult = JSONObject.parseObject(responseResult);
if (null != paramsResult){
if (200 != paramsResult.getInteger("code")){
if (null != paramsResult) {
if (200 != paramsResult.getInteger("code")) {
log.info("~~~~~~~~~~~~~~~调用数据银行扣款失败~~~~~~~~~~~~~");
throw new GatewayException(GatewayResultCode.CALL_AMOUNT_NOT_ENOUGH);
}
}
}
/**
* 限流返回方法
*
......
......@@ -4,6 +4,7 @@ package com.jz.dm.web.aspect;
import com.jz.common.utils.IpUtils;
import com.jz.common.utils.JsonUtils;
import com.jz.common.utils.UrlUtil;
import com.jz.dm.common.exception.GatewayException;
import com.jz.dm.mapper.ApiReqLogMapper;
import com.jz.dm.models.domian.ApiReqLog;
import com.jz.dm.service.ApiLogService;
......@@ -14,6 +15,7 @@ import javassist.bytecode.LocalVariableAttribute;
import javassist.bytecode.MethodInfo;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
......@@ -54,10 +56,10 @@ public class SystemLogAspect {
/* //前置通知切入点
@Pointcut("@annotation(com.jz.dm.web.annotation.ApiLogAspect)")
public void beforeAspect() {
}
}*/
//最终通知切入点
@Pointcut("@annotation(com.jz.dm.web.annotation.ApiLogAspect)")
/* @Pointcut("@annotation(com.jz.dm.web.annotation.ApiLogAspect)")
public void lastAspect() {
}*/
......@@ -79,6 +81,9 @@ public class SystemLogAspect {
params += JsonUtils.objectToJson(joinPoint.getArgs()[i]) + ";";
}
}
if (StringUtils.isNotBlank(params)){
params= params.substring(0,params.length()-1).split(";")[0];;
}
//获取请求路径
String url = UrlUtil.getServerUrl(request);
// 访问项目名
......@@ -87,10 +92,11 @@ public class SystemLogAspect {
//动态修改其参数
//注意,如果调用joinPoint.proceed()方法,则修改的参数值不会生效,必须调用joinPoint.proceed(Object[] args)
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);
ApiReqLog reqLog = new ApiReqLog();
JSONObject jsonResult =null;
try {
ApiReqLog reqLog = new ApiReqLog();
reqLog.setRequestIp(ip);
reqLog.setApiKey(jsonObject.getString("apiKey"));
reqLog.setRequestParams(params);
......@@ -98,19 +104,23 @@ public class SystemLogAspect {
reqLog.setRequestUrl(url);
reqLog.setRequestMethod(contextPath);
reqLog.setEncryMode(jsonObject.getString("signType")); //加密方式:MD5,RSA
reqLog.setEncryMode("MD5"); //加密方式暂时写死MD5
reqLog.setTransMode(request.getMethod());//传输方式 GET POST
reqLog.setRequestToken(jsonParamsList.getString("authCode"));
reqLog.setRequestTime(new Date());
reqLog.setRequestStartTime(new Date());
reqLog.setRemark(getServiceMethodDescription(joinPoint));
log.info("请求参数:",reqLog);
if (null != reqLog) {
apiReqLogMapper.insert(reqLog);
}
Object result = joinPoint.proceed(joinPoint.getArgs());
JSONObject jsonResult = JSONObject.fromObject(result);
jsonResult = JSONObject.fromObject(result);
log.info("around响应结果为{}", jsonResult);
apiLogService.updateLog(reqLog.getId(), jsonResult);
} catch (Throwable throwable) {
} catch (GatewayException ex) {
log.info("切面处理保存异常信息:{}",ex.getMessage());
apiLogService.updateLog(reqLog.getId(), jsonResult);
}catch (Throwable throwable){
throwable.printStackTrace();
}
}
......@@ -162,39 +172,39 @@ public class SystemLogAspect {
* 返回异常通知,返回抛出异常的时候执行的通知,可以获得返回的异常
* 可以访问到异常对象,且可以指定在出现特定异常的时候再执行通知代码
*/
/*@AfterReturning(value = "lastAspect()", returning = "result")
public void afterReturn(JoinPoint joinPoint, Object result) {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
.getRequest();
log.info("~~~~~~~~~~~~~~~~~~~~~~最终通知执行~~~~~~~~~~~~~~~~~~~~~~~~");
String classType = joinPoint.getTarget().getClass().getName();
try {
Class<?> clazz = Class.forName(classType);
String clazzName = clazz.getName();
// 拦截的方法名称。当前正在执行的方法
String methodName = joinPoint.getSignature().getName();
// 获取方法的参数
Object[] args = joinPoint.getArgs();
// 获取传入参数的键值对
Map<String, Object> map = (Map<String, Object>)
getFieldsName(this.getClass(), clazzName, methodName,
args);
// 将request中的参数转化为键值对,方便取出
// Map<String, Object> requestMap = (Map<String, Object>) map.get("request");
// 获取返回方法的参数
JSONObject jsonObject = JSONObject.fromObject(result);
Map mapResult = (Map) jsonObject;
//将返回的result参数取出
Map<String, Object> res = (Map<String, Object>) mapResult.get("data");
Integer id = (Integer) res.get("id");
JSONObject data = jsonObject.getJSONObject("data");
// apiLogService.updateLog(id.longValue(), data);
} catch (Exception e) {
log.error("~~~~~~~~~~~~~~~~~~~~~~~最终通知异常~~~~~~~~~~~~~~~~~~~~~~~");
log.error("异常信息{}", e.getMessage());
}
//@AfterReturning(value = "lastAspect()", returning = "result")
//public void afterReturn(JoinPoint joinPoint, Object result) {
// HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
// .getRequest();
// log.info("~~~~~~~~~~~~~~~~~~~~~~最终通知执行~~~~~~~~~~~~~~~~~~~~~~~~");
// String classType = joinPoint.getTarget().getClass().getName();
// try {
// Class<?> clazz = Class.forName(classType);
// String clazzName = clazz.getName();
// // 拦截的方法名称。当前正在执行的方法
// String methodName = joinPoint.getSignature().getName();
// // 获取方法的参数
// Object[] args = joinPoint.getArgs();
// // 获取传入参数的键值对
// Map<String, Object> map = (Map<String, Object>)
// getFieldsName(this.getClass(), clazzName, methodName,
// args);
// // 将request中的参数转化为键值对,方便取出
// // Map<String, Object> requestMap = (Map<String, Object>) map.get("request");
// // 获取返回方法的参数
// JSONObject jsonObject = JSONObject.fromObject(result);
// Map mapResult = (Map) jsonObject;
// //将返回的result参数取出
// Map<String, Object> res = (Map<String, Object>) mapResult.get("data");
// Integer id = (Integer) res.get("id");
// JSONObject data = jsonObject.getJSONObject("data");
// // apiLogService.updateLog(id.longValue(), data);
// } catch (Exception e) {
// log.error("~~~~~~~~~~~~~~~~~~~~~~~最终通知异常~~~~~~~~~~~~~~~~~~~~~~~");
// log.error("异常信息{}", e.getMessage());
// }
}*/
// }
/**
* 获取注解中对方法的描述信息 用于service层注解
......
......@@ -47,5 +47,63 @@ spring:
# 日志用的filter:log4j
# 防御sql注入的filter:wall
filters: stat
cache:
type: CAFFEINE
caffeine:
spec: maximumSize=1000,expireAfterWrite=30s
public-key: rajZdV0xpCox+2vEHFLsKq2o2XVdMaQq
redis:
#database: 0
cluster:
nodes:
- 192.168.1.146:6379
- 192.168.1.146:6380
- 192.168.1.146:6381
- 192.168.1.146:6382
- 192.168.1.146:6383
- 192.168.1.146:6384
#使用redis管理session设置为redis,否则none
session:
store-type: none
#切面启用
aop:
proxy-target-class: true
auto: true
# ====================MybatisPlus====================
#ignoreRedis true存入 false不存 api.timeout.default
sendgrid:
api-key:
dmp:
ignoreRedis: true
openapi:
timeout:
default: 5000
max: 5000
#流处理配置
windows: #文件流输出地址设置
name: stream
isWindows: true
#sentinel限流配置
sentinel: #sentinel每秒中最大的请求个数
resource: api.gateway
request:
max: 100
#数据银行调用配置
data:
bank:
balanceUrl: http://192.168.1.139:8081 #余额信息url
withholdUrl: http://192.168.1.139:8081/mall/financeCustomerAssets/unfreezeMoney #扣款信通知url
token: #dataBank 制作验签
dataBank: dataBank123
#logback日志配置
logging:
config: classpath:logback-pro.xml
level:
com:
zhl:
springbootlogback: off
......@@ -71,6 +71,8 @@ spring:
auto: true
#ignoreRedis true存入 false不存 api.timeout.default
sendgrid:
api-key:
dmp:
ignoreRedis: true
openapi:
......@@ -92,8 +94,18 @@ sentinel: #sentinel每秒中最大的请求个数
#数据银行调用配置
data:
bank:
balanceUrl: http://192.168.1.139:8081/mall/financeCustomerAssets/findAssets #余额信息url
withholdUrl: http://192.168.1.139:8081/mall/financeCustomerAssets/unfreezeMoney #扣款信通知url
balanceUrl: http://192.168.1.139:8081 #余额信息url #扣款信通知url
token: #dataBank 制作验签
dataBank: dataBank123
#logback日志配置
logging:
config: classpath:logback-dev.xml
level:
com:
zhl:
springbootlogback: off
......@@ -8,6 +8,7 @@ logging:
level:
com.netflix.discovery: 'OFF'
org.springframework.cloud: 'DEBUG'
com.jz.dm: debug
#SPRING配置文件
spring:
......@@ -20,20 +21,24 @@ spring:
profiles:
active: test #默认使用的配置文件
cloud:
sentinel: #sentinel 限流框架配置
sentinel:
transport:
# sentinel-dashboard服务地址 # sentinel-dashboard-1.6.0 的访问路径 ,
#启动方式java -jar sentinel-dashboard-1.6.0.jar --server.port=9090
dashboard: localhost:8080
heartbeat-interval-ms: 500
# 项目本地会启动一个服务的端口号,默认8719,用于与sentinel-dashboard通讯
port: 8719
# sentinel-dashboard服务地址 # sentinel-dashboard-1.6.0 的访问路径 ,启动方式java -jar sentinel-dashboard-1.6.0.jar
dashboard: localhost:9090
#服务器ip
clientIp: 192.168.1.114
filter:
# 需要进行限流监控的接口,多个匹配用逗号隔开
url-patterns: /*
servlet:
# 触发限流后重定向的页面
block-page: /sentinel/block
#取消Sentinel控制台懒加载
#eager: true
# 触发限流后重定向的页面
block-page: /sentinel/block
#取消Sentinel控制台懒加载
eager: true
# ====================MybatisPlus====================
mybatis-plus:
......@@ -41,7 +46,7 @@ spring:
# 如果是放在resource目录 classpath:/mapper/*Mapper.xml
mapper-locations: classpath*:com/frame/**/**.xml,classpath*:mapping/**/**.xml
#实体扫描,多个package用逗号或者分号分隔
typeAliasesPackage: com.frame.**.entity,com.frame.**.dto
typeAliasesPackage: com.jz.dm.models.domian;com.jz.dm.models.dto;com.jz.dm.models.enity
global-config:
#刷新mapper 调试神器
db-config:
......
____.__________ _____ __________.___ ___________________
| |\____ / / _ \\______ \ | \____ /\_ ___ \
| | / / / /_\ \| ___/ | / / / \ \/
/\__| | / /_ / | \ | | | / /_ \ \____
\________|/_______ \ \____|__ /____| |___| /_______ \ \______ /
\/ \/ \/ \/
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<substitutionProperty name="log.proj" value="gateway" />
<!-- 服务器 -->
<substitutionProperty name="log.base" value="/logs/${log.proj}" />
<!-- 本地 -->
<!--<substitutionProperty name="log.base" value="C:/Users/key/Desktop/logs/${log.proj}" />-->
<substitutionProperty name="max.size" value="100MB" />
<jmxConfigurator />
<appender name="stdout" class="ch.qos.logback.core.ConsoleAppender">
<layout class="ch.qos.logback.classic.PatternLayout">
<pattern>%date [${log.proj}:%thread] %-5level %logger{80} - %msg%n
</pattern>
</layout>
</appender>
<appender name="file.debug" class="ch.qos.logback.core.rolling.RollingFileAppender"><!-- All Log Info -->
<File>${log.base}/${log.proj}.log</File>
<rollingPolicy
class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<FileNamePattern>${log.base}/${log.proj}_%d{yyyy-MM-dd}.%i.log
</FileNamePattern>
<timeBasedFileNamingAndTriggeringPolicy
class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>${max.size}</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
</rollingPolicy>
<layout class="ch.qos.logback.classic.PatternLayout">
<pattern>%date [%thread] %-5level %logger{80} - %msg%n</pattern>
</layout>
</appender>
<appender name="file.info" class="ch.qos.logback.core.rolling.RollingFileAppender">
<!-- <File>${log.base}/${log.proj}_info.log</File> -->
<rollingPolicy
class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<FileNamePattern>${log.base}/${log.proj}_info_%d{yyyy-MM-dd}.%i.log
</FileNamePattern>
<timeBasedFileNamingAndTriggeringPolicy
class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>${max.size}</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
</rollingPolicy>
<layout class="ch.qos.logback.classic.PatternLayout">
<pattern>%date [%thread] %-5level %logger{80} - %msg%n</pattern>
</layout>
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>INFO</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
</appender>
<appender name="file.error" class="ch.qos.logback.core.rolling.RollingFileAppender">
<rollingPolicy
class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<FileNamePattern>${log.base}/${log.proj}_error_%d{yyyy-MM-dd}.%i.log
</FileNamePattern>
<timeBasedFileNamingAndTriggeringPolicy
class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>${max.size}</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
</rollingPolicy>
<layout class="ch.qos.logback.classic.PatternLayout">
<pattern>%date [%thread] %-5level %logger{80} - %msg%n</pattern>
</layout>
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>ERROR</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
</appender>
<appender name="file.warn" class="ch.qos.logback.core.rolling.RollingFileAppender">
<rollingPolicy
class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<FileNamePattern>${log.base}/${log.proj}_warn_%d{yyyy-MM-dd}.%i.log
</FileNamePattern>
<timeBasedFileNamingAndTriggeringPolicy
class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>${max.size}</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
</rollingPolicy>
<layout class="ch.qos.logback.classic.PatternLayout">
<pattern>%date [%thread] %-5level %logger{80} - %msg%n</pattern>
</layout>
<filter class="ch.qos.logback.classic.filter.ThresholdFilter"><!-- 临界值过滤器,过滤掉低于指定临界值的日志 -->
<level>WARN</level>
</filter>
</appender>
<!--异步输出 -->
<appender name="async.file.info" class="ch.qos.logback.classic.AsyncAppender">
<discardingThreshold>0</discardingThreshold>
<queueSize>256</queueSize>
<appender-ref ref="file.info" />
</appender>
<appender name="async.file.debug" class="ch.qos.logback.classic.AsyncAppender">
<discardingThreshold>0</discardingThreshold>
<queueSize>256</queueSize>
<appender-ref ref="file.debug" />
</appender>
<appender name="async.file.warn" class="ch.qos.logback.classic.AsyncAppender">
<discardingThreshold>0</discardingThreshold>
<queueSize>256</queueSize>
<appender-ref ref="file.warn" />
</appender>
<appender name="async.file.error" class="ch.qos.logback.classic.AsyncAppender">
<discardingThreshold>0</discardingThreshold>
<queueSize>256</queueSize>
<appender-ref ref="file.error" />
</appender>
<root level="info" additivity="false">
<appender-ref ref="stdout" />
<appender-ref ref="async.file.debug" />
<appender-ref ref="async.file.info" />
<appender-ref ref="async.file.error" />
<appender-ref ref="async.file.warn" />
</root>
<logger name="io.lettuce.core.protocol.ConnectionWatchdog" additivity="false">
<appender-ref ref="stdout" />
<level value="ERROR" />
</logger>
<logger name="io.lettuce.core.protocol.ReconnectionHandler" additivity="false">
<appender-ref ref="stdout" />
<level value="ERROR" />
</logger>
</configuration>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<substitutionProperty name="log.proj" value="jz-dm-gateway" />
<!-- 服务器 -->
<substitutionProperty name="log.base" value="/logs/${log.proj}" />
<!-- 本地 -->
<!-- <substitutionProperty name="log.base" value="/Users/luoyichang/Desktop/jz/logs/${log.proj}" />-->
<substitutionProperty name="max.size" value="100MB" />
<jmxConfigurator />
<appender name="stdout" class="ch.qos.logback.core.ConsoleAppender">
<layout class="ch.qos.logback.classic.PatternLayout">
<pattern>%date [${log.proj}:%thread] %-5level %logger{80} TraceId[%X{mdc_key}] - %msg%n
</pattern>
</layout>
</appender>
<appender name="file.debug" class="ch.qos.logback.core.rolling.RollingFileAppender"><!-- All Log Info -->
<File>${log.base}/${log.proj}.log</File>
<rollingPolicy
class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<FileNamePattern>${log.base}/${log.proj}_%d{yyyy-MM-dd}.%i.log
</FileNamePattern>
<timeBasedFileNamingAndTriggeringPolicy
class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>${max.size}</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
</rollingPolicy>
<layout class="ch.qos.logback.classic.PatternLayout">
<pattern>%date [%thread] %-5level %logger{80} - %msg%n</pattern>
</layout>
</appender>
<appender name="file.info" class="ch.qos.logback.core.rolling.RollingFileAppender">
<!-- <File>${log.base}/${log.proj}_info.log</File> -->
<rollingPolicy
class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<FileNamePattern>${log.base}/${log.proj}_info_%d{yyyy-MM-dd}.%i.log
</FileNamePattern>
<timeBasedFileNamingAndTriggeringPolicy
class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>${max.size}</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
</rollingPolicy>
<layout class="ch.qos.logback.classic.PatternLayout">
<pattern>%date [%thread] %-5level %logger{80} TraceId[%X{mdc_key}] - %msg%n</pattern>
</layout>
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>INFO</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
</appender>
<appender name="file.error" class="ch.qos.logback.core.rolling.RollingFileAppender">
<rollingPolicy
class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<FileNamePattern>${log.base}/${log.proj}_error_%d{yyyy-MM-dd}.%i.log
</FileNamePattern>
<timeBasedFileNamingAndTriggeringPolicy
class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>${max.size}</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
</rollingPolicy>
<layout class="ch.qos.logback.classic.PatternLayout">
<pattern>%date [%thread] %-5level %logger{80} - %msg%n</pattern>
</layout>
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>ERROR</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
</appender>
<appender name="file.warn" class="ch.qos.logback.core.rolling.RollingFileAppender">
<rollingPolicy
class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<FileNamePattern>${log.base}/${log.proj}_warn_%d{yyyy-MM-dd}.%i.log
</FileNamePattern>
<timeBasedFileNamingAndTriggeringPolicy
class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>${max.size}</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
</rollingPolicy>
<layout class="ch.qos.logback.classic.PatternLayout">
<pattern>%date [%thread] %-5level %logger{80} - %msg%n</pattern>
</layout>
<filter class="ch.qos.logback.classic.filter.ThresholdFilter"><!-- 临界值过滤器,过滤掉低于指定临界值的日志 -->
<level>WARN</level>
</filter>
</appender>
<!--异步输出 -->
<appender name="async.file.info" class="ch.qos.logback.classic.AsyncAppender">
<discardingThreshold>0</discardingThreshold>
<queueSize>256</queueSize>
<appender-ref ref="file.info" />
</appender>
<appender name="async.file.debug" class="ch.qos.logback.classic.AsyncAppender">
<discardingThreshold>0</discardingThreshold>
<queueSize>256</queueSize>
<appender-ref ref="file.debug" />
</appender>
<appender name="async.file.warn" class="ch.qos.logback.classic.AsyncAppender">
<discardingThreshold>0</discardingThreshold>
<queueSize>256</queueSize>
<appender-ref ref="file.warn" />
</appender>
<appender name="async.file.error" class="ch.qos.logback.classic.AsyncAppender">
<discardingThreshold>0</discardingThreshold>
<queueSize>256</queueSize>
<appender-ref ref="file.error" />
</appender>
<root level="info" additivity="false">
<appender-ref ref="stdout" />
<appender-ref ref="async.file.debug" />
<appender-ref ref="async.file.info" />
<appender-ref ref="async.file.error" />
<appender-ref ref="async.file.warn" />
</root>
<logger name="io.lettuce.core.protocol.ConnectionWatchdog" additivity="false">
<appender-ref ref="stdout" />
<level value="ERROR" />
</logger>
<logger name="io.lettuce.core.protocol.ReconnectionHandler" additivity="false">
<appender-ref ref="stdout" />
<level value="info" />
</logger>
</configuration>
\ No newline at end of file
......@@ -7,6 +7,19 @@
status, remark, create_date, create_user, update_date,
update_user, is_deleted
</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 au.id AS id,
au.api_org_id AS apiOrgId,
......@@ -55,7 +68,9 @@
DATE_FORMAT(au.create_date,'%Y-%m-%d %H:%i:%s') AS createDate,
au.create_user AS createUser,
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
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
......
......@@ -3,5 +3,24 @@
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<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>
\ No newline at end of file
......@@ -9,5 +9,36 @@
update_user, is_deleted
</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_consuming) 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>
<select id="getTestData" resultType="com.jz.dm.models.domian.ApiInterfaceCustom">
SELECT aic.*
FROM t_api_interface AS ai
JOIN t_api_interface_custom AS aic ON ai.id =aic.api_interface_id AND aic.is_deleted =0
WHERE ai.is_deleted = 0
AND ai.api_key =#{apiKey}
</select>
</mapper>
\ No newline at end of file
......@@ -7,5 +7,11 @@
request_token, request_time, remark, create_date, create_user,
update_date, update_user, is_deleted
</sql>
<select id="countApiCallMonthData" resultType="com.jz.dm.models.dto.ApiCallDataDto">
SELECT COUNT(1) AS callLimit,
SUM(request_consuming) AS timeStat
FROM t_api_req_log
WHERE DATE_FORMAT(create_date,'%Y:%m')=DATE_FORMAT(#{date},'%Y:%m')
</select>
</mapper>
......@@ -5,7 +5,7 @@ import com.jz.common.utils.HttpsUtils;
import com.jz.common.utils.Md5;
import com.jz.dm.common.util.MapUtil;
import com.jz.dm.gateway.SpringTestCase;
import org.junit.jupiter.api.Test;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
/**
......
......@@ -8,8 +8,8 @@ import com.jz.dm.models.domian.ApiOrg;
import com.jz.dm.models.req.organizationManage.OrganizationManageAddReq;
import com.jz.dm.models.req.organizationManage.OrganizationManageDetailQueryReq;
import com.jz.dm.models.req.organizationManage.OrganizationManageListQueryReq;
import com.jz.dm.models.req.organizationManage.OrganizationManageUpdateReq;
import com.jz.dm.service.OrganizationManageService;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
/**
......@@ -29,7 +29,7 @@ public class TestOrganizationManage extends SpringTestCase {
/**
* 查询类列表信息
*/
// @Test
@Test
public void getOrgList(){
OrganizationManageListQueryReq req = new OrganizationManageListQueryReq();
req.setPageNum(1);
......@@ -40,10 +40,10 @@ public class TestOrganizationManage extends SpringTestCase {
/**
* 查询详情信息
*/
// @Test
@Test
public void getOrgDetail(){
OrganizationManageDetailQueryReq req = new OrganizationManageDetailQueryReq();
req.setId(1L);
req.setId(2L);
Result detail = organizationManageService.getOrganizationDetail(req);
ApiOrg apiOrg = (ApiOrg)detail.getData();
System.out.println(apiOrg);
......@@ -51,7 +51,7 @@ public class TestOrganizationManage extends SpringTestCase {
/**
* 添加组织信息
*/
//@Test
@Test
public void addOrg(){
OrganizationManageAddReq req = new OrganizationManageAddReq();
req.setOrgName("数据银行");
......@@ -68,15 +68,15 @@ public class TestOrganizationManage extends SpringTestCase {
/**
* 更新组织信息
*/
//@Test
@Test
public void updateOrg(){
OrganizationManageUpdateReq req = new OrganizationManageUpdateReq();
req.setId(8L);
req.setOrgDesc("粗这次002");
req.setOrgCnName("AOKK33");
req.setOrgMail("727322JA@QQ.COM");
req.setRemark("sfsihsio");
Result result = organizationManageService.update(req);
System.out.println(result.getMessage());
//OrganizationManageUpdateReq req = new OrganizationManageUpdateReq();
//req.setId(8L);
//req.setOrgDesc("粗这次002");
//req.setOrgCnName("AOKK33");
//req.setOrgMail("727322JA@QQ.COM");
//req.setRemark("sfsihsio");
//Result result = organizationManageService.update(req);
//System.out.println(result.getMessage());
}
}
......@@ -5,7 +5,7 @@ import com.jz.common.utils.HttpsUtils;
import com.jz.dm.common.enums.GatewayResultCode;
import com.jz.dm.common.exception.GatewayException;
import com.jz.dm.gateway.SpringTestCase;
import org.junit.jupiter.api.Test;
import org.junit.Test;
/**
* @author ZC
......
......@@ -3,7 +3,7 @@ package com.jz.dm.gateway.orther;
import com.alibaba.fastjson.JSONObject;
import com.jz.common.utils.HttpsUtils;
import com.jz.dm.gateway.SpringTestCase;
import org.junit.jupiter.api.Test;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.HashMap;
......
......@@ -4,7 +4,7 @@ import com.alibaba.fastjson.JSONObject;
import com.jz.common.utils.HttpsUtils;
import com.jz.dm.gateway.SpringTestCase;
import com.jz.dm.service.ProducerService;
import org.junit.jupiter.api.Test;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.HashMap;
......
......@@ -4,7 +4,7 @@ import com.jz.dm.common.util.RedisSerializableUtil;
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.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
......
......@@ -34,12 +34,6 @@
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-data-redis</artifactId>
</dependency>
<!--httpclient包-->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.6</version>
</dependency>
<!-- fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
......@@ -93,7 +87,6 @@
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.6</version>
</dependency>
</dependencies>
</project>
\ No newline at end of file
......@@ -223,6 +223,7 @@
<artifactId>commons-net</artifactId>
<version>${commons-net.version}</version>
</dependency>
<!--httpclient包-->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
......
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