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` ( ...@@ -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文件表
...@@ -86,8 +87,9 @@ CREATE TABLE `t_api_org` ( ...@@ -86,8 +87,9 @@ CREATE TABLE `t_api_org` (
`org_desc` varchar(300) DEFAULT NULL COMMENT '组织描述', `org_desc` varchar(300) DEFAULT NULL COMMENT '组织描述',
`org_cn_name` varchar(100) DEFAULT NULL COMMENT '组织英文名称', `org_cn_name` varchar(100) DEFAULT NULL COMMENT '组织英文名称',
`org_phone` varchar(20) NULL 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 内部组织', `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_mail` varchar(100) DEFAULT NULL COMMENT '组织邮箱',
`org_sort` int(10) DEFAULT '999' COMMENT '组织排序', `org_sort` int(10) DEFAULT '999' COMMENT '组织排序',
`parent_id` varchar(100) DEFAULT NULL COMMENT '父类组织编码', `parent_id` varchar(100) DEFAULT NULL COMMENT '父类组织编码',
...@@ -116,6 +118,7 @@ CREATE TABLE `t_api_auth` ( ...@@ -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 永久有效', `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 '创建时间',
...@@ -143,7 +146,9 @@ CREATE TABLE `t_api_req_log` ( ...@@ -143,7 +146,9 @@ CREATE TABLE `t_api_req_log` (
`encry_mode` varchar(20) DEFAULT NULL COMMENT '加密方式:MD5,RSA', `encry_mode` varchar(20) DEFAULT NULL COMMENT '加密方式:MD5,RSA',
`trans_mode` varchar(20) DEFAULT NULL COMMENT '传输方式:POST,GET', `trans_mode` varchar(20) DEFAULT NULL COMMENT '传输方式:POST,GET',
`request_token` varchar(64) DEFAULT NULL COMMENT '客户请求token', `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 请求失败', `status` varchar(50) DEFAULT NULL COMMENT '状态:SUCCEED 请求成功, FAIL 请求失败',
`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
...@@ -9,7 +9,6 @@ ...@@ -9,7 +9,6 @@
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<artifactId>jz-dm-apigateway</artifactId> <artifactId>jz-dm-apigateway</artifactId>
<dependencies> <dependencies>
<!-- spring-boot --> <!-- spring-boot -->
<dependency> <dependency>
...@@ -33,12 +32,6 @@ ...@@ -33,12 +32,6 @@
<artifactId>mybatis-plus-boot-starter</artifactId> <artifactId>mybatis-plus-boot-starter</artifactId>
</dependency> </dependency>
<!-- 引入Druid依赖,阿里巴巴所提供的数据源 -->
<!-- <dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
</dependency>-->
<dependency> <dependency>
<groupId>com.alibaba</groupId> <groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId> <artifactId>druid-spring-boot-starter</artifactId>
...@@ -61,12 +54,6 @@ ...@@ -61,12 +54,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>
...@@ -110,6 +97,27 @@ ...@@ -110,6 +97,27 @@
<!-- <version>0.9.0.RELEASE</version>--> <!-- <version>0.9.0.RELEASE</version>-->
</dependency> </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> <dependency>
<groupId>net.sf.json-lib</groupId> <groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId> <artifactId>json-lib</artifactId>
...@@ -120,6 +128,14 @@ ...@@ -120,6 +128,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:";
} }
...@@ -45,9 +45,6 @@ public enum GatewayResultCode implements ResultCode { ...@@ -45,9 +45,6 @@ public enum GatewayResultCode implements ResultCode {
/** 请求超过限制 */ /** 请求超过限制 */
RATE_LIMIT_EXCEEDED("RATE_LIMIT_EXCEEDED", "请求超过限制"), RATE_LIMIT_EXCEEDED("RATE_LIMIT_EXCEEDED", "请求超过限制"),
/** 无效路由类型 */
ILLEGAL_ROUTE_TYPE("ILLEGAL_ROUTE_TYPE", "无效路由类型"),
/** 提交数据过大 */ /** 提交数据过大 */
POST_DATA_TOO_LARGE("POST_DATA_TOO_LARGE", "提交数据过大"), POST_DATA_TOO_LARGE("POST_DATA_TOO_LARGE", "提交数据过大"),
......
...@@ -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删除/确认提示接口")
@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; ...@@ -7,10 +7,7 @@ import com.jz.dm.service.ApiLogService;
import io.swagger.annotations.Api; import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono; import reactor.core.publisher.Mono;
import javax.validation.Valid; import javax.validation.Valid;
...@@ -54,4 +51,15 @@ public class ApiLogController { ...@@ -54,4 +51,15 @@ public class ApiLogController {
public Mono<Result> getApiLogDetail(@RequestBody @Valid LogInfoDetailReq req) { public Mono<Result> getApiLogDetail(@RequestBody @Valid LogInfoDetailReq req) {
return Mono.fromSupplier(() -> apiLogService.getApiLogDetail(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 { ...@@ -73,6 +73,17 @@ public class AuthController {
public Mono<Result> selectAuthListInfo(@RequestBody @Valid AuthListInfoReq req) { public Mono<Result> selectAuthListInfo(@RequestBody @Valid AuthListInfoReq req) {
return Mono.fromSupplier(() -> authService.getAuthListInfo(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: 认证信息修改 * @Description: 认证信息修改
* @return: 认证信息修改 * @return: 认证信息修改
......
...@@ -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 {
......
...@@ -4,7 +4,6 @@ import com.jz.common.utils.Result; ...@@ -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.OrganizationManageAddReq;
import com.jz.dm.models.req.organizationManage.OrganizationManageDetailQueryReq; 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.service.OrganizationManageService; import com.jz.dm.service.OrganizationManageService;
import io.swagger.annotations.Api; import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiOperation;
...@@ -58,7 +57,7 @@ public class OrganizationManageController { ...@@ -58,7 +57,7 @@ public class OrganizationManageController {
* @Author: Mr.zhang * @Author: Mr.zhang
* @Date: 2020-12-24 * @Date: 2020-12-24
*/ */
@ApiOperation("添加组织") @ApiOperation("添加/更新组织")
@PostMapping(value = "/add") @PostMapping(value = "/add")
public Mono<Result> add(@RequestBody @Valid OrganizationManageAddReq req) { public Mono<Result> add(@RequestBody @Valid OrganizationManageAddReq req) {
return Mono.fromSupplier(() -> organizationManageService.add(req)); return Mono.fromSupplier(() -> organizationManageService.add(req));
...@@ -68,11 +67,11 @@ public class OrganizationManageController { ...@@ -68,11 +67,11 @@ public class OrganizationManageController {
* @Author: Mr.zhang * @Author: Mr.zhang
* @Date: 2020-12-24 * @Date: 2020-12-24
*/ */
@ApiOperation("更新组织信息") /* @ApiOperation("更新组织信息")
@PostMapping(value = "/update") @PostMapping(value = "/update")
public Mono<Result> update(@RequestBody @Valid OrganizationManageUpdateReq req) { public Mono<Result> update(@RequestBody @Valid OrganizationManageUpdateReq req) {
return Mono.fromSupplier(() -> organizationManageService.update(req)); return Mono.fromSupplier(() -> organizationManageService.update(req));
} }*/
/** /**
* @Description:注销组织 * @Description:注销组织
* @Author: Mr.zhang * @Author: Mr.zhang
......
...@@ -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;
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 +28,7 @@ import org.springframework.beans.factory.annotation.Autowired; ...@@ -28,6 +28,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 +53,8 @@ public class AuthFilter extends AbstractFilter { ...@@ -52,6 +53,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 +80,13 @@ public class AuthFilter extends AbstractFilter { ...@@ -77,8 +80,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 +95,18 @@ public class AuthFilter extends AbstractFilter { ...@@ -87,11 +95,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 (!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 +139,12 @@ public class AuthFilter extends AbstractFilter { ...@@ -124,15 +139,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 +153,12 @@ public class AuthFilter extends AbstractFilter { ...@@ -141,12 +153,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 +176,7 @@ public class AuthFilter extends AbstractFilter { ...@@ -164,6 +176,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 +187,18 @@ public class AuthFilter extends AbstractFilter { ...@@ -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 { ...@@ -192,7 +217,7 @@ public class AuthFilter extends AbstractFilter {
pObject.put("assetsId", assetsId); pObject.put("assetsId", assetsId);
pObject.put("userId", userId); pObject.put("userId", userId);
pObject.put("dataPrice", dataPrice); 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); JSONObject result = JSONObject.parseObject(respResult);
if (null != result) { if (null != result) {
if (200 != result.getInteger("code")) { if (200 != result.getInteger("code")) {
...@@ -202,4 +227,23 @@ public class AuthFilter extends AbstractFilter { ...@@ -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; ...@@ -3,8 +3,8 @@ package com.jz.dm.filter;
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;
...@@ -27,15 +27,16 @@ public class CheckArgsFilter extends AbstractFilter { ...@@ -27,15 +27,16 @@ public class CheckArgsFilter extends AbstractFilter {
public String getFilterName() { public String getFilterName() {
return "CheckArgsFilter"; return "CheckArgsFilter";
} }
@Override @Override
protected void internalDoFilter(GatewayRequest request, GatewayResponse response, protected void internalDoFilter(GatewayRequest request, GatewayResponse response,
FilterChain chain) { FilterChain chain) {
// 校验参数非空 // 校验参数非空
if (StringUtil.isEmpty(request.getApiKey()) || StringUtil.isEmpty(request.getMethod()) if (StringUtil.isEmpty(request.getApiKey()) || StringUtil.isEmpty(request.getMethod())
|| StringUtil.isEmpty(request.getSignType())|| StringUtil.isEmpty(request.getSign()) || StringUtil.isEmpty(request.getSignType()) || StringUtil.isEmpty(request.getSign())
|| StringUtil.isEmpty(request.getTimestamp())|| StringUtil.isEmpty(request.getParams())) { || StringUtil.isEmpty(request.getTimestamp()) || StringUtil.isEmpty(request.getParams())) {
throw new GatewayException(GatewayResultCode.ILLEGAL_ARGUMENT); //无效参数 throw new GatewayException(GatewayResultCode.ILLEGAL_ARGUMENT); //无效参数
} }
// 设置默认值 // 设置默认值
if (StringUtil.isEmpty(request.getFormat())) { if (StringUtil.isEmpty(request.getFormat())) {
request.setFormat(Format.JSON.name()); request.setFormat(Format.JSON.name());
...@@ -54,6 +55,4 @@ public class CheckArgsFilter extends AbstractFilter { ...@@ -54,6 +55,4 @@ public class CheckArgsFilter extends AbstractFilter {
} }
chain.doFilter(request, response); chain.doFilter(request, response);
} }
} }
...@@ -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.domian.ApiInterfaceCustom;
import com.jz.dm.models.req.api.ApiInterfaceDetailReq;
import org.apache.ibatis.annotations.Param;
/** /**
* @author ZC * @author ZC
...@@ -15,4 +20,26 @@ import com.jz.dm.models.domian.ApiInterface; ...@@ -15,4 +20,26 @@ 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);
/**
* 获取测试请求数据
* @param apiKey
* @return
*/
ApiInterfaceCustom getTestData(String apiKey);
} }
...@@ -2,8 +2,12 @@ package com.jz.dm.mapper; ...@@ -2,8 +2,12 @@ package com.jz.dm.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.jz.dm.models.domian.ApiReqLog; import com.jz.dm.models.domian.ApiReqLog;
import com.jz.dm.models.dto.ApiCallDataDto;
import org.apache.ibatis.annotations.Select; import org.apache.ibatis.annotations.Select;
import java.util.Date;
import java.util.List;
/**api请求日志表 mapper /**api请求日志表 mapper
* @author ybz * @author ybz
*/ */
...@@ -16,4 +20,11 @@ public interface ApiReqLogMapper extends BaseMapper<ApiReqLog> { ...@@ -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)") @Select("SELECT * FROM t_api_req_log WHERE id =(SELECT MAX(id) FROM t_api_req_log)")
ApiReqLog maxId(Long id); ApiReqLog maxId(Long id);
/**
* 统计API调用
* @return
*/
List<ApiCallDataDto> countApiCallMonthData(Date date);
} }
...@@ -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;
} }
...@@ -50,6 +50,11 @@ public class ApiOrg extends BaseObject implements Serializable { ...@@ -50,6 +50,11 @@ public class ApiOrg extends BaseObject implements Serializable {
*/ */
@TableField("org_phone") @TableField("org_phone")
private String orgPhone; private String orgPhone;
/**
* 组织联系人
*/
@TableField("linkman")
private String linkman;
/** /**
* 组织类型 OUT 外部组织 IN 内部组织 * 组织类型 OUT 外部组织 IN 内部组织
*/ */
...@@ -57,10 +62,10 @@ public class ApiOrg extends BaseObject implements Serializable { ...@@ -57,10 +62,10 @@ public class ApiOrg extends BaseObject implements Serializable {
private String orgType; private String orgType;
/** /**
* 状态(NORMAL-正常 FREEZE-冻结 CANCEL-注销) * 状态(NORMAL-正常(true) FREEZE-冻结 CANCEL-注销(false))
*/ */
@TableField("status") @TableField("status")
private String status; private Boolean status;
/** /**
* 组织邮箱 * 组织邮箱
......
...@@ -90,13 +90,27 @@ public class ApiReqLog implements Serializable { ...@@ -90,13 +90,27 @@ public class ApiReqLog implements Serializable {
private String requestToken; private String requestToken;
/** /**
* 请求时间 * 请求总耗时
*/ */
@ApiModelProperty("请求时间") @ApiModelProperty("请求总耗时")
@TableField("request_time") @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") @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date requestTime; private Date requestEndTime;
/** /**
* 请求状态: SUCCEED 成功 ,FAIL 失败 * 请求状态: 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 { ...@@ -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;
......
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 { ...@@ -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;
......
...@@ -40,9 +40,22 @@ public class OrganizationManageAddReq implements Serializable { ...@@ -40,9 +40,22 @@ public class OrganizationManageAddReq implements Serializable {
@ApiModelProperty(value = "组织电话",required = false) @ApiModelProperty(value = "组织电话",required = false)
private String orgPhone; private String orgPhone;
@ApiModelProperty(value = "组织联系人",required = false)
private String linkman;
@ApiModelProperty(value = "备注",required = false) @ApiModelProperty(value = "备注",required = false)
private String remark; private String remark;
@ApiModelProperty(value = "创建用户",required = false) @ApiModelProperty(value = "创建用户",required = false)
private String createUser; 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 ...@@ -26,4 +26,7 @@ public class OrganizationManageListQueryReq extends BasePageBean implements Seri
@ApiModelProperty(value = "组织编码(组织唯一标识)") @ApiModelProperty(value = "组织编码(组织唯一标识)")
private String orgCode; private String orgCode;
@ApiModelProperty(value = "组织联系人")
private String linkman;
} }
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,50 @@ public interface ApiInterfaceService { ...@@ -35,4 +39,50 @@ 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);
/**
* api测试接口
* @param apiKey
* @return
*/
Result apiTestInterface(String apiKey);
} }
...@@ -43,4 +43,11 @@ public interface ApiLogService { ...@@ -43,4 +43,11 @@ public interface ApiLogService {
* @param jsonObject * @param jsonObject
*/ */
void updateLog(Long id, JSONObject jsonObject); void updateLog(Long id, JSONObject jsonObject);
/**
* 统计API调用数据
* @param date
* @return
*/
Result countAPiCallStat(String date);
} }
...@@ -70,4 +70,18 @@ public interface AuthService { ...@@ -70,4 +70,18 @@ public interface AuthService {
* @return * @return
*/ */
ApiAuth getAuthInfo( String authCode); 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; ...@@ -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.OrganizationManageAddReq;
import com.jz.dm.models.req.organizationManage.OrganizationManageDetailQueryReq; 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;
/** /**
* @author ZC * @author ZC
...@@ -44,7 +43,7 @@ public interface OrganizationManageService { ...@@ -44,7 +43,7 @@ public interface OrganizationManageService {
* @param req * @param req
* @return * @return
*/ */
Result update(OrganizationManageUpdateReq req); //Result update(OrganizationManageUpdateReq req);
/** /**
* 根据id注销组织 * 根据id注销组织
......
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.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.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.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 com.jz.dm.service.ApiInterfaceService;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
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
...@@ -25,12 +41,196 @@ import javax.annotation.Resource; ...@@ -25,12 +41,196 @@ import javax.annotation.Resource;
@Slf4j @Slf4j
public class ApiInterfaceServiceImpl implements ApiInterfaceService { public class ApiInterfaceServiceImpl implements ApiInterfaceService {
/**
* 测试url
*/
public static final String testUrl ="";
@Resource @Resource
private ApiInterfaceMapper apiInterfaceMapper; private ApiInterfaceMapper apiInterfaceMapper;
@Resource @Resource
private ApiAuthMapper apiAuthMapper; 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 apiKey
* @param authCode * @param authCode
* @return * @return
...@@ -38,40 +238,41 @@ public class ApiInterfaceServiceImpl implements ApiInterfaceService { ...@@ -38,40 +238,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);
} }
} }
...@@ -19,6 +19,8 @@ import org.springframework.beans.factory.annotation.Autowired; ...@@ -19,6 +19,8 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import javax.annotation.Resource; import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date; import java.util.Date;
/** /**
...@@ -34,6 +36,7 @@ import java.util.Date; ...@@ -34,6 +36,7 @@ import java.util.Date;
@Slf4j @Slf4j
public class ApiLogServiceImpl implements ApiLogService { public class ApiLogServiceImpl implements ApiLogService {
@Resource @Resource
private ApiReqLogMapper apiReqLogMapper; private ApiReqLogMapper apiReqLogMapper;
// 加锁 // 加锁
...@@ -77,7 +80,22 @@ public class ApiLogServiceImpl implements ApiLogService { ...@@ -77,7 +80,22 @@ public class ApiLogServiceImpl implements ApiLogService {
public void insetLogInfo(ApiReqLog reqLog) { public void insetLogInfo(ApiReqLog reqLog) {
apiReqLogMapper.insert(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更新日志 * 根据id更新日志
...@@ -98,6 +116,12 @@ public class ApiLogServiceImpl implements ApiLogService { ...@@ -98,6 +116,12 @@ public class ApiLogServiceImpl implements ApiLogService {
} }
update.set("response_params",jsonObject.toString()); update.set("response_params",jsonObject.toString());
update.set("update_date",new Date()); 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); update.eq("id",id);
if (apiReqLogMapper.update(null,update) == 0){ if (apiReqLogMapper.update(null,update) == 0){
log.info("~~~~~~~~~~~更新日志信息失败~~~~~~~~"); log.info("~~~~~~~~~~~更新日志信息失败~~~~~~~~");
...@@ -109,4 +133,6 @@ public class ApiLogServiceImpl implements ApiLogService { ...@@ -109,4 +133,6 @@ public class ApiLogServiceImpl implements ApiLogService {
log.error("更新日志返回信息异常:{}",ex.getMessage()); log.error("更新日志返回信息异常:{}",ex.getMessage());
} }
} }
} }
...@@ -5,10 +5,13 @@ import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper; ...@@ -5,10 +5,13 @@ import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jz.common.constant.ResultMsg; import com.jz.common.constant.ResultMsg;
import com.jz.common.enums.auth.AuthTypeEnum;
import com.jz.common.utils.Result; import com.jz.common.utils.Result;
import com.jz.dm.common.constant.Constants; import com.jz.dm.common.constant.Constants;
import com.jz.dm.common.enums.GeneralStatusTypeEnum; 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.common.enums.auth.AuthModeEnum;
import com.jz.dm.common.enums.org.OrgStatusEnum;
import com.jz.dm.common.util.RandomUtil; import com.jz.dm.common.util.RandomUtil;
import com.jz.dm.mapper.ApiAuthMapper; import com.jz.dm.mapper.ApiAuthMapper;
import com.jz.dm.mapper.ApiInterfaceMapper; import com.jz.dm.mapper.ApiInterfaceMapper;
...@@ -31,7 +34,6 @@ import javax.annotation.Resource; ...@@ -31,7 +34,6 @@ import javax.annotation.Resource;
import java.util.Date; import java.util.Date;
import static com.jz.dm.common.enums.auth.AuthModeEnum.fromTypeModeName; import static com.jz.dm.common.enums.auth.AuthModeEnum.fromTypeModeName;
import static com.jz.dm.common.enums.auth.AuthTypeEnum.fromTypeName;
/** /**
* @author ZC * @author ZC
...@@ -64,13 +66,13 @@ public class AuthServiceImpl implements AuthService { ...@@ -64,13 +66,13 @@ public class AuthServiceImpl implements AuthService {
public Result getAuthListInfo(AuthListInfoReq req) { public Result getAuthListInfo(AuthListInfoReq req) {
IPage<AuthInfoDto> page = new Page<>(req.getPageNum(), req.getPageSize()); IPage<AuthInfoDto> page = new Page<>(req.getPageNum(), req.getPageSize());
QueryWrapper<AuthInfoDto> query = new QueryWrapper<>(); QueryWrapper<AuthInfoDto> query = new QueryWrapper<>();
if (StringUtils.isNotBlank(req.getApiKey())){ if (StringUtils.isNotBlank(req.getApiKey())) {
query.eq("ai.api_key",req.getApiKey()); query.eq("ai.api_key", req.getApiKey());
} }
if (StringUtils.isNotBlank(req.getAuthCode())){ if (StringUtils.isNotBlank(req.getAuthCode())) {
query.eq("au.auth_code",req.getAuthCode()); query.eq("au.auth_code", req.getAuthCode());
} }
query.eq("au.is_deleted",0); query.eq("au.is_deleted", 0);
query.orderByDesc("au.create_date"); query.orderByDesc("au.create_date");
IPage<AuthInfoDto> listSelectApiAuth = apiAuthMapper.listSelectApiAuth(page, query); IPage<AuthInfoDto> listSelectApiAuth = apiAuthMapper.listSelectApiAuth(page, query);
return Result.of_success(listSelectApiAuth); return Result.of_success(listSelectApiAuth);
...@@ -94,25 +96,29 @@ public class AuthServiceImpl implements AuthService { ...@@ -94,25 +96,29 @@ public class AuthServiceImpl implements AuthService {
* @return * @return
*/ */
@Override @Override
@Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRES_NEW) @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
public Result addDmpUserApiAuth(AuthUserApiReq req) { public Result addDmpUserApiAuth(AuthUserApiReq req) {
ApiInterface apiInterface = getInterface(req.getApiKey()); ApiInterface apiInterface = getInterface(req.getApiKey());
if (null == apiInterface) { if (null == apiInterface) {
return Result.of_error("api授权信息不存在!"); return Result.of_error("api授权信息不存在!");
} }
ApiOrg apiOrg = apiOrgMapper.selectOne(new QueryWrapper<ApiOrg>().eq("org_code",req.getOrgCode())); if (ApiStatusEnum.EXPIRY.name().equals(apiInterface.getStatus())) {
if (null == apiOrg) { return Result.of_error("api已下架,无法授权");
}
ApiOrg apiOrg = apiOrgMapper.selectOne(new QueryWrapper<ApiOrg>().eq("org_code", req.getOrgCode()));
if (null == apiOrg || OrgStatusEnum.CANCEL.name().equals(apiOrg)) {
return Result.of_error("组织信息不存在!"); return Result.of_error("组织信息不存在!");
} }
//授权验证 //授权验证
if (StringUtils.isNotBlank(req.getAuthType())){ //if (StringUtils.isNotBlank(req.getAuthType())){
if (null == fromTypeName(req.getAuthType())){ // if (null == fromTypeName(req.getAuthType())){
return Result.of_error("授权类型不存在!"); // return Result.of_error("授权类型不存在!");
} // }
} //}
//验证授权方式 //验证授权方式
if (StringUtils.isNotBlank(req.getAuthMode())){ if (StringUtils.isNotBlank(req.getAuthMode())) {
if (null == fromTypeModeName(req.getAuthMode())){ if (null == fromTypeModeName(req.getAuthMode())) {
return Result.of_error("授权方式不存在!"); return Result.of_error("授权方式不存在!");
} }
} }
...@@ -121,10 +127,10 @@ public class AuthServiceImpl implements AuthService { ...@@ -121,10 +127,10 @@ public class AuthServiceImpl implements AuthService {
!AuthModeEnum.PERMANENT_TIME_MODE.name().equals(req.getAuthMode())) { !AuthModeEnum.PERMANENT_TIME_MODE.name().equals(req.getAuthMode())) {
return Result.of_error("授权类型错误!"); return Result.of_error("授权类型错误!");
} }
if (StringUtils.isBlank(apiOrg.getOrgCode())){ if (StringUtils.isBlank(apiOrg.getOrgCode())) {
return Result.of_error("内部授权组织编码不能为空!!"); return Result.of_error("内部授权组织编码不能为空!!");
} }
return saveAuthInfo(apiInterface,apiOrg,req,Constants.AUTH_INT); return saveAuthInfo(apiInterface, apiOrg, req, Constants.AUTH_INT);
} }
/** /**
...@@ -134,25 +140,28 @@ public class AuthServiceImpl implements AuthService { ...@@ -134,25 +140,28 @@ public class AuthServiceImpl implements AuthService {
* @return * @return
*/ */
@Override @Override
@Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRES_NEW) @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
public Result addMallUserApiAuth(AuthUserApiReq req) { public Result addMallUserApiAuth(AuthUserApiReq req) {
ApiInterface apiInterface = getInterface(req.getApiKey()); ApiInterface apiInterface = getInterface(req.getApiKey());
if (null == apiInterface) { if (null == apiInterface) {
return Result.of_error("api授权信息不存在!"); return Result.of_error("api授权信息不存在!");
} }
ApiOrg apiOrg = apiOrgMapper.selectOne(new QueryWrapper<ApiOrg>().eq("org_code",req.getOrgCode())); if (ApiStatusEnum.SOLDOUT.name().equals(apiInterface.getStatus())) {
if (null == apiOrg) { return Result.of_error("api已下架,无法授权");
}
ApiOrg apiOrg = apiOrgMapper.selectOne(new QueryWrapper<ApiOrg>().eq("org_code", req.getOrgCode()));
if (null == apiOrg || OrgStatusEnum.CANCEL.name().equals(apiOrg)) {
return Result.of_error("组织信息不存在!"); return Result.of_error("组织信息不存在!");
} }
//授权验证 //授权验证
if (StringUtils.isNotBlank(req.getAuthType())){ //if (StringUtils.isNotBlank(req.getAuthType())){
if (null == fromTypeName(req.getAuthType())){ // if (null == fromTypeName(req.getAuthType())){
return Result.of_error("授权类型不存在!"); // return Result.of_error("授权类型不存在!");
} // }
} //}
//验证授权方式 //验证授权方式
if (StringUtils.isNotBlank(req.getAuthMode())){ if (StringUtils.isNotBlank(req.getAuthMode())) {
if (null == fromTypeModeName(req.getAuthMode())){ if (null == fromTypeModeName(req.getAuthMode())) {
return Result.of_error("授权方式不存在!"); return Result.of_error("授权方式不存在!");
} }
} }
...@@ -163,66 +172,74 @@ public class AuthServiceImpl implements AuthService { ...@@ -163,66 +172,74 @@ public class AuthServiceImpl implements AuthService {
} }
//认证类型 //认证类型
if (StringUtils.isNotBlank(req.getAuthMode()) && if (StringUtils.isNotBlank(req.getAuthMode()) &&
AuthModeEnum.RECORD_TIME_MODE.name().equals(req.getAuthMode())){ AuthModeEnum.RECORD_TIME_MODE.name().equals(req.getAuthMode())) {
if (null == req.getValidStartTime() || null == req.getValidEndTime()) { if (null == req.getValidStartTime() || null == req.getValidEndTime()) {
return Result.of_error("开始或结束时间不能为空!"); return Result.of_error("开始或结束时间不能为空!");
} }
} }
//验证用户id //验证用户id
if (StringUtils.isBlank(req.getUserId())){ if (StringUtils.isBlank(req.getUserId())) {
return Result.of_error("外部授权用户Id不能为空"); return Result.of_error("外部授权用户Id不能为空");
} }
return saveAuthInfo(apiInterface,apiOrg,req,Constants.AUTH_OUT); return saveAuthInfo(apiInterface, apiOrg, req, Constants.AUTH_OUT);
} }
/** /**
* 保存授权信息 * 保存授权信息
*
* @param apiInterface * @param apiInterface
* @param apiOrg * @param apiOrg
* @param req * @param req
* @param orgType * @param orgType
* @return * @return
*/ */
private Result saveAuthInfo(ApiInterface apiInterface, ApiOrg apiOrg , private Result saveAuthInfo(ApiInterface apiInterface, ApiOrg apiOrg,
AuthUserApiReq req,String orgType){ AuthUserApiReq req, String orgType) {
AuthUserResponse response = new AuthUserResponse(); AuthUserResponse response = new AuthUserResponse();
ApiAuth apiAuth = new ApiAuth(); ApiAuth apiAuth = new ApiAuth();
apiAuth.setApiInterfaceId(apiInterface.getId()); BeanUtils.copyProperties(req, apiAuth);
apiAuth.setApiOrgId(apiOrg.getId()); apiAuth.setApiInterfaceId(apiInterface.getId());
apiAuth.setReqType(apiInterface.getReqType()); apiAuth.setApiOrgId(apiOrg.getId());
apiAuth.setReqFrequency(apiInterface.getReqFrequency()); apiAuth.setReqType(apiInterface.getReqType());
BeanUtils.copyProperties(req, apiAuth); apiAuth.setReqFrequency(apiInterface.getReqFrequency());
//商城只有外部授权 if (Constants.AUTH_INT.equals(orgType)) {//内部授权
String authCode =""; apiAuth.setAuthType(AuthTypeEnum.DMP_AUTH.name());
//内部组织 } else {
apiAuth.setAuthType(AuthTypeEnum.DATA_BANK_AUTH.name());
}
//商城只有外部授权
String authCode = "";
//内部组织
if (StringUtils.isNotBlank(orgType) && Constants.AUTH_INT.equalsIgnoreCase(orgType)) { if (StringUtils.isNotBlank(orgType) && Constants.AUTH_INT.equalsIgnoreCase(orgType)) {
authCode = getAuthCode(apiOrg.getOrgCode(),"",Constants.AUTH_INT); authCode = getAuthCode(apiOrg.getOrgCode(), "", Constants.AUTH_INT);
//外部组织 //外部组织
} else if (StringUtils.isNotBlank(orgType) } else if (StringUtils.isNotBlank(orgType)
&& Constants.AUTH_OUT.equalsIgnoreCase(orgType)) { && Constants.AUTH_OUT.equalsIgnoreCase(orgType)) {
authCode = getAuthCode("", req.getUserId(),Constants.AUTH_OUT); authCode = getAuthCode("", req.getUserId(), Constants.AUTH_OUT);
}
//生成盐值
String salt = RandomUtil.getStringRandom(8);
apiAuth.setAuthCode(authCode);//授权码
apiAuth.setSalt(salt);//盐值
apiAuth.setStatus(GeneralStatusTypeEnum.VALID.name());//授权状态
apiAuth.setCreateUser(req.getCreateUser());
response.setAuthCode(authCode);
response.setSalt(salt);
if (apiAuthMapper.insert(apiAuth) > 0) {
return Result.of_success(ResultMsg.SUCCESS, response);
} }
//生成盐值 return Result.of_error(ResultMsg.INSERT_FAIL);
String salt = RandomUtil.getStringRandom(8); }
apiAuth.setAuthCode(authCode);//授权码
apiAuth.setSalt(salt);//盐值
apiAuth.setStatus(GeneralStatusTypeEnum.VALID.name());//授权状态
apiAuth.setCreateUser("");
response.setAuthCode(authCode);
response.setSalt(salt);
if (apiAuthMapper.insert(apiAuth) > 0) {
return Result.of_success(ResultMsg.SUCCESS,response);
}
return Result.of_error(ResultMsg.INSERT_FAIL);
}
/** /**
* 获取授权码 * 获取授权码
*
* @param type * @param type
* @param userId * @param userId
* @param apiOrgCode * @param apiOrgCode
* @return * @return
*/ */
private String getAuthCode(String apiOrgCode,String userId,String type) { private String getAuthCode(String apiOrgCode, String userId, String type) {
String authCode = ""; String authCode = "";
authCode = RandomUtil.generateTokenCode(type, apiOrgCode, userId); authCode = RandomUtil.generateTokenCode(type, apiOrgCode, userId);
QueryWrapper<ApiAuth> query = new QueryWrapper<>(); QueryWrapper<ApiAuth> query = new QueryWrapper<>();
...@@ -243,15 +260,15 @@ public class AuthServiceImpl implements AuthService { ...@@ -243,15 +260,15 @@ public class AuthServiceImpl implements AuthService {
@Override @Override
public Result updateAuthInfo(AuthInfoUpdateReq req) { public Result updateAuthInfo(AuthInfoUpdateReq req) {
ApiAuth apiAuth = apiAuthMapper.selectById(req.getId()); ApiAuth apiAuth = apiAuthMapper.selectById(req.getId());
if (null == apiAuth){ if (null == apiAuth) {
return Result.of_error(ResultMsg.DATA_NOT_EXIST); return Result.of_error(ResultMsg.DATA_NOT_EXIST);
} }
UpdateWrapper<ApiAuth> updateWra = new UpdateWrapper<>(); UpdateWrapper<ApiAuth> updateWra = new UpdateWrapper<>();
updateWra.set("is_deleted",1); updateWra.set("is_deleted", 1);
updateWra.set("status",GeneralStatusTypeEnum.UN_VALID.name()); updateWra.set("status", GeneralStatusTypeEnum.UN_VALID.name());
updateWra.eq("id",req.getId()); updateWra.eq("id", req.getId());
if (apiAuthMapper.update(null,updateWra) == 0){ if (apiAuthMapper.update(null, updateWra) == 0) {
return Result.of_error(ResultMsg.UPDATE_FAIL); return Result.of_error(ResultMsg.UPDATE_FAIL);
} }
return Result.of_success(ResultMsg.UPDATE_SUCCESS); return Result.of_success(ResultMsg.UPDATE_SUCCESS);
} }
...@@ -265,55 +282,86 @@ public class AuthServiceImpl implements AuthService { ...@@ -265,55 +282,86 @@ public class AuthServiceImpl implements AuthService {
@Override @Override
public Result updateSaltInfo(SaltResetReq req) { public Result updateSaltInfo(SaltResetReq req) {
AuthUserResponse response = new AuthUserResponse(); AuthUserResponse response = new AuthUserResponse();
QueryWrapper<ApiAuth> query = new QueryWrapper<>(); ApiAuth apiAuth = getAuthInfo(req.getAuthCode());
query.eq("auth_code",req.getAuthCode());
query.eq("is_deleted",0);
query.eq("status",GeneralStatusTypeEnum.VALID);
ApiAuth apiAuth = apiAuthMapper.selectOne(query);
if (null == apiAuth) { if (null == apiAuth) {
return Result.of_error("认证用户不存在"); return Result.of_error("认证信息不存在!");
}
String salt = RandomUtil.getStringRandom(8);
UpdateWrapper<ApiAuth> update = new UpdateWrapper<>();
update.set("salt", salt);
update.set("update_date", new Date());
update.set("update_user", req.getCreateUser());
update.eq("id", apiAuth.getId());
if (apiAuthMapper.update(null, update) > 0) {
response.setSalt(salt);
return Result.of_success(ResultMsg.UPDATE_SUCCESS, response);
} }
String salt = RandomUtil.getStringRandom(8);
UpdateWrapper<ApiAuth> update = new UpdateWrapper<>();
update.set("salt", salt);
update.set("update_date", new Date());
update.set("update_user", "");
update.eq("id", apiAuth.getId());
if (apiAuthMapper.update(null, update) > 0) {
response.setSalt(salt);
return Result.of_success(ResultMsg.UPDATE_SUCCESS,response);
}
return Result.of_success(ResultMsg.UPDATE_FAIL); return Result.of_success(ResultMsg.UPDATE_FAIL);
} }
/** /**
* 获取API授权信息 * 获取API授权信息
*
* @param authCode * @param authCode
* @param apiId * @param apiId
* @return * @return
*/ */
@Override @Override
public ApiAuth getAuthUser(String authCode,Long apiId) { public ApiAuth getAuthUser(String authCode, Long apiId) {
QueryWrapper<ApiAuth> query = new QueryWrapper<>(); QueryWrapper<ApiAuth> query = new QueryWrapper<>();
query.eq("auth_code",authCode); query.eq("auth_code", authCode);
query.eq("status",GeneralStatusTypeEnum.VALID.name()); query.eq("status", GeneralStatusTypeEnum.VALID.name());
query.eq("api_interface_id",apiId); query.eq("api_interface_id", apiId);
query.eq("is_deleted",0); query.eq("is_deleted", 0);
return apiAuthMapper.selectOne(query); return apiAuthMapper.selectOne(query);
} }
/** /**
* 获取API授权信息 * 获取API授权信息
*
* @param authCode * @param authCode
* @return * @return
*/ */
@Override @Override
public ApiAuth getAuthInfo(String authCode) { public ApiAuth getAuthInfo(String authCode) {
QueryWrapper<ApiAuth> query = new QueryWrapper<>(); QueryWrapper<ApiAuth> query = new QueryWrapper<>();
query.eq("auth_code",authCode); query.eq("auth_code", authCode);
query.eq("is_deleted",0); query.eq("status", GeneralStatusTypeEnum.VALID);
query.eq("is_deleted", 0);
return apiAuthMapper.selectOne(query); return apiAuthMapper.selectOne(query);
} }
/**
* 更新API状态
* @param apiAuth
* @return
*/
@Override
public int updateApiAuthStatus(ApiAuth apiAuth) {
UpdateWrapper<ApiAuth> update = new UpdateWrapper<>();
update.set("status", GeneralStatusTypeEnum.UN_VALID);
update.set("handler",1);
update.set("is_deleted",1);
update.eq("id",apiAuth.getId());
return apiAuthMapper.update(null,update);
}
/**
* 模糊查询/
* @param key
* @return
*/
@Override
public Result getAuthNameList(String key) {
QueryWrapper<ApiOrg> query = new QueryWrapper<>();
if (StringUtils.isNotBlank(key)){
query.and(wrapper -> wrapper.like("org_name",key)
.or().like("org_code",key)
.or().like("linkman",key));
}
return Result.of_success(apiOrgMapper.selectList(query));
}
private ApiInterface getInterface(String apiKey) { private ApiInterface getInterface(String apiKey) {
QueryWrapper<ApiInterface> queryInface = new QueryWrapper<>(); QueryWrapper<ApiInterface> queryInface = new QueryWrapper<>();
queryInface.last("where is_deleted=0 and api_key ='" + apiKey + "'"); queryInface.last("where is_deleted=0 and api_key ='" + apiKey + "'");
......
...@@ -14,7 +14,6 @@ import com.jz.dm.models.domian.ApiOrg; ...@@ -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.OrganizationManageAddReq;
import com.jz.dm.models.req.organizationManage.OrganizationManageDetailQueryReq; 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.service.OrganizationManageService; import com.jz.dm.service.OrganizationManageService;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
...@@ -24,7 +23,7 @@ import org.springframework.stereotype.Service; ...@@ -24,7 +23,7 @@ import org.springframework.stereotype.Service;
import javax.annotation.Resource; 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.OrgTypeEnum.fromOrgTypeEnumName;
/** /**
* @author ZC * @author ZC
...@@ -52,14 +51,17 @@ public class OrganizationManageImpl implements OrganizationManageService { ...@@ -52,14 +51,17 @@ public class OrganizationManageImpl implements OrganizationManageService {
public IPage<ApiOrg> listOrganization(OrganizationManageListQueryReq req) { public IPage<ApiOrg> listOrganization(OrganizationManageListQueryReq req) {
IPage<ApiOrg> page = new Page<>(req.getPageNum(), req.getPageSize()); IPage<ApiOrg> page = new Page<>(req.getPageNum(), req.getPageSize());
QueryWrapper<ApiOrg> query = new QueryWrapper<>(); QueryWrapper<ApiOrg> query = new QueryWrapper<>();
if (StringUtils.isNotBlank(req.getOrgName())){ 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())){ if (StringUtils.isNotBlank(req.getOrgCode())){
query.eq("org_code",req.getOrgCode()); query.eq("org_code",req.getOrgCode());
} }
query.eq("is_deleted", 0); query.eq("is_deleted", 0);
query.ne("status",OrgStatusEnum.CANCEL);
query.orderByDesc("create_date"); query.orderByDesc("create_date");
return apiOrgMapper.selectPage(page, query); return apiOrgMapper.selectPage(page, query);
} }
...@@ -75,18 +77,44 @@ public class OrganizationManageImpl implements OrganizationManageService { ...@@ -75,18 +77,44 @@ public class OrganizationManageImpl implements OrganizationManageService {
QueryWrapper<ApiOrg> query = new QueryWrapper<>(); QueryWrapper<ApiOrg> query = new QueryWrapper<>();
query.eq("is_deleted", 0); query.eq("is_deleted", 0);
query.eq("id", req.getId()); query.eq("id", req.getId());
query.ne("status",OrgStatusEnum.CANCEL); /*query.ne("status",0);*/
return Result.of_success(apiOrgMapper.selectOne(query)); return Result.of_success(apiOrgMapper.selectOne(query));
} }
/** /**
* 添加组织 * 添加组织/更新
* *
* @param req * @param req
* @return * @return
*/ */
@Override @Override
public Result add(OrganizationManageAddReq req) { 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())) { if (StringUtils.isNotBlank(req.getOrgName())) {
ApiOrg orgNameInfo = getOrgNameInfo(req.getOrgName()); ApiOrg orgNameInfo = getOrgNameInfo(req.getOrgName());
if (null != orgNameInfo) { if (null != orgNameInfo) {
...@@ -94,14 +122,10 @@ public class OrganizationManageImpl implements OrganizationManageService { ...@@ -94,14 +122,10 @@ 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("组织类型不存在!");
} }
} }
String coding = "";
ApiOrg apiOrg = new ApiOrg();
BeanUtils.copyProperties(req, apiOrg);
if (StringUtils.isNotBlank(req.getOrgType()) //内部组织 if (StringUtils.isNotBlank(req.getOrgType()) //内部组织
&& Constants.AUTH_INT.equals(req.getOrgType())) { && Constants.AUTH_INT.equals(req.getOrgType())) {
coding = generateCode(req.getOrgName(), Constants.AUTH_INT); coding = generateCode(req.getOrgName(), Constants.AUTH_INT);
...@@ -112,11 +136,10 @@ public class OrganizationManageImpl implements OrganizationManageService { ...@@ -112,11 +136,10 @@ public class OrganizationManageImpl implements OrganizationManageService {
return Result.of_error("生成组织编码异常!"); return Result.of_error("生成组织编码异常!");
} }
apiOrg.setOrgCode(coding);//组织编码 apiOrg.setOrgCode(coding);//组织编码
apiOrg.setStatus(OrgStatusEnum.NORMAL.name());//正常
if (apiOrgMapper.insert(apiOrg) > 0) { if (apiOrgMapper.insert(apiOrg) > 0) {
return Result.of_success(ResultMsg.INSERT_SUCCESS); 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 { ...@@ -144,7 +167,7 @@ public class OrganizationManageImpl implements OrganizationManageService {
* @param req * @param req
* @return * @return
*/ */
@Override /* @Override
public Result update(OrganizationManageUpdateReq req) { public Result update(OrganizationManageUpdateReq req) {
ApiOrg apiOrg = apiOrgMapper.selectById(req.getId()); ApiOrg apiOrg = apiOrgMapper.selectById(req.getId());
if (null == apiOrg) { if (null == apiOrg) {
...@@ -166,7 +189,7 @@ public class OrganizationManageImpl implements OrganizationManageService { ...@@ -166,7 +189,7 @@ public class OrganizationManageImpl implements OrganizationManageService {
return Result.of_success(ResultMsg.UPDATE_SUCCESS); return Result.of_success(ResultMsg.UPDATE_SUCCESS);
} }
return Result.of_success(ResultMsg.UPDATE_FAIL); return Result.of_success(ResultMsg.UPDATE_FAIL);
} }*/
/** /**
* 注销组织 * 注销组织
...@@ -182,7 +205,7 @@ public class OrganizationManageImpl implements OrganizationManageService { ...@@ -182,7 +205,7 @@ public class OrganizationManageImpl implements OrganizationManageService {
} }
UpdateWrapper<ApiOrg> delete = new UpdateWrapper<>(); UpdateWrapper<ApiOrg> delete = new UpdateWrapper<>();
delete.set("is_deleted", 1); delete.set("is_deleted", 1);
delete.set("status",OrgStatusEnum.CANCEL); delete.set("status",0);
delete.eq("id", id); delete.eq("id", id);
if (apiOrgMapper.update(null, delete) > 0) { if (apiOrgMapper.update(null, delete) > 0) {
return Result.of_success(ResultMsg.UPDATE_SUCCESS); return Result.of_success(ResultMsg.UPDATE_SUCCESS);
...@@ -215,7 +238,7 @@ public class OrganizationManageImpl implements OrganizationManageService { ...@@ -215,7 +238,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,10 +3,6 @@ package com.jz.dm.service.impl; ...@@ -3,10 +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.constant.RedisMessageConstant;
import com.jz.common.constant.ResultCode; import com.jz.common.constant.ResultCode;
import com.jz.common.constant.ResultMsg; import com.jz.common.constant.ResultMsg;
import com.jz.common.exception.ResponseException; import com.jz.common.exception.ResponseException;
...@@ -14,7 +10,6 @@ import com.jz.common.utils.HttpsUtils; ...@@ -14,7 +10,6 @@ import com.jz.common.utils.HttpsUtils;
import com.jz.common.utils.Md5; import com.jz.common.utils.Md5;
import com.jz.common.utils.RedisUtils; import com.jz.common.utils.RedisUtils;
import com.jz.common.utils.Result; import com.jz.common.utils.Result;
import com.jz.dm.common.constant.TagConstants;
import com.jz.dm.common.enums.GeneralStatusTypeEnum; import com.jz.dm.common.enums.GeneralStatusTypeEnum;
import com.jz.dm.common.enums.apiInterface.ApiInfoOutTypeEnum; import com.jz.dm.common.enums.apiInterface.ApiInfoOutTypeEnum;
import com.jz.dm.common.enums.apiInterface.ApiStatusEnum; import com.jz.dm.common.enums.apiInterface.ApiStatusEnum;
...@@ -97,15 +92,8 @@ public class ProducerServiceImpl implements ProducerService { ...@@ -97,15 +92,8 @@ public class ProducerServiceImpl implements ProducerService {
* @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);
} }
...@@ -179,7 +167,6 @@ public class ProducerServiceImpl implements ProducerService { ...@@ -179,7 +167,6 @@ public class ProducerServiceImpl implements ProducerService {
} }
String signStr = dataBankToken + req.getJoinType(); String signStr = dataBankToken + req.getJoinType();
String signResult = Md5.encrypt(signStr, ""); String signResult = Md5.encrypt(signStr, "");
System.out.println(signResult);
if (!signResult.equals(req.getSign())) { if (!signResult.equals(req.getSign())) {
return Result.of_error("签名错误!"); return Result.of_error("签名错误!");
} }
...@@ -211,9 +198,9 @@ public class ProducerServiceImpl implements ProducerService { ...@@ -211,9 +198,9 @@ public class ProducerServiceImpl implements ProducerService {
ApiInterface apiInterface = saveApiInterFace(req, apiKey, apiType); ApiInterface apiInterface = saveApiInterFace(req, apiKey, apiType);
saveApiInterFaceCustom(req, apiKey, apiInterface.getId()); saveApiInterFaceCustom(req, apiKey, apiInterface.getId());
JSONObject object = new JSONObject(); JSONObject object = new JSONObject();
object.put("targetUrl",req.getTargetUrl()); object.put("targetUrl", req.getTargetUrl());
object.put("outputType",req.getOutputType()); object.put("outputType", req.getOutputType());
saveObjOnRedis(apiInterface.getApiKey(),object); saveObjOnRedis(apiInterface.getApiKey(), object);
} }
/** /**
...@@ -278,10 +265,6 @@ public class ProducerServiceImpl implements ProducerService { ...@@ -278,10 +265,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基本信息为空!");
...@@ -309,40 +292,31 @@ public class ProducerServiceImpl implements ProducerService { ...@@ -309,40 +292,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);
...@@ -392,9 +366,9 @@ public class ProducerServiceImpl implements ProducerService { ...@@ -392,9 +366,9 @@ public class ProducerServiceImpl implements ProducerService {
throw ResponseException.of_error("保存Api信息失败!"); throw ResponseException.of_error("保存Api信息失败!");
} }
JSONObject object = new JSONObject(); JSONObject object = new JSONObject();
object.put("targetUrl",req.getTargetUrl()); object.put("targetUrl", req.getTargetUrl());
object.put("outputType",ApiInfoOutTypeEnum.JSON.name()); object.put("outputType", ApiInfoOutTypeEnum.JSON.name());
saveObjOnRedis(apiInterface.getApiKey(),object); saveObjOnRedis(apiInterface.getApiKey(), object);
return Result.of_success(ResultMsg.INSERT_SUCCESS, apiKey); return Result.of_success(ResultMsg.INSERT_SUCCESS, apiKey);
} }
...@@ -411,13 +385,13 @@ public class ProducerServiceImpl implements ProducerService { ...@@ -411,13 +385,13 @@ public class ProducerServiceImpl implements ProducerService {
} }
try { try {
String paramKey = redisUtils.get(apiKey); String paramKey = redisUtils.get(apiKey);
if (null != paramKey){ if (null != paramKey) {
redisUtils.del(apiKey); redisUtils.del(apiKey);
} }
redisUtils.set(apiKey, params.toString()); redisUtils.set(apiKey, params.toString());
} catch (Exception ex) { } catch (Exception ex) {
log.error("缓存api制作数据异常:{}",ex.getMessage()); log.error("缓存api制作数据异常:{}", ex.getMessage());
ex.printStackTrace(); ex.printStackTrace();
} }
} }
...@@ -530,9 +504,9 @@ public class ProducerServiceImpl implements ProducerService { ...@@ -530,9 +504,9 @@ public class ProducerServiceImpl implements ProducerService {
return Result.of_success(ResultMsg.UPDATE_SUCCESS); return Result.of_success(ResultMsg.UPDATE_SUCCESS);
} }
JSONObject object = new JSONObject(); JSONObject object = new JSONObject();
object.put("targetUrl",req.getTargetUrl()); object.put("targetUrl", req.getTargetUrl());
object.put("outputType",ApiInfoOutTypeEnum.JSON.name()); object.put("outputType", ApiInfoOutTypeEnum.JSON.name());
saveObjOnRedis(apiInterface.getApiKey(),object); saveObjOnRedis(apiInterface.getApiKey(), object);
return Result.of_success(ResultMsg.UPDATE_FAIL); return Result.of_success(ResultMsg.UPDATE_FAIL);
} }
...@@ -693,26 +667,6 @@ public class ProducerServiceImpl implements ProducerService { ...@@ -693,26 +667,6 @@ public class ProducerServiceImpl implements ProducerService {
return random; 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 @Override
public Result saveObjOnRedis() { public Result saveObjOnRedis() {
...@@ -732,9 +686,9 @@ public class ProducerServiceImpl implements ProducerService { ...@@ -732,9 +686,9 @@ public class ProducerServiceImpl implements ProducerService {
net.sf.json.JSONObject jsonObject = net.sf.json.JSONObject.fromObject(bankApiReq); net.sf.json.JSONObject jsonObject = net.sf.json.JSONObject.fromObject(bankApiReq);
redisUtils.set("apiKeyTest", jsonObject, 300);*/ redisUtils.set("apiKeyTest", jsonObject, 300);*/
JSONObject object = new JSONObject(); JSONObject object = new JSONObject();
object.put("targetUrl","www.baidu.common"); object.put("targetUrl", "www.baidu.common");
object.put("outputType",ApiInfoOutTypeEnum.JSON.name()); object.put("outputType", ApiInfoOutTypeEnum.JSON.name());
saveObjOnRedis("apiKeyTest002",object); saveObjOnRedis("apiKeyTest002", object);
return Result.ok(); return Result.ok();
} }
......
...@@ -18,6 +18,7 @@ import com.jz.dm.models.domian.ApiInterface; ...@@ -18,6 +18,7 @@ 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;
...@@ -60,8 +61,8 @@ public class ApiQueryService extends ApiParamVerify implements OpenApiService { ...@@ -60,8 +61,8 @@ public class ApiQueryService extends ApiParamVerify implements OpenApiService {
@Autowired @Autowired
private HttpsUtils httpsUtils; private HttpsUtils httpsUtils;
@Value("${data.bank.withholdUrl}") @Value("${data.bank.balanceUrl}")
private String withholdUrl; private String balanceUrl;
/** /**
* API请求逻辑处理 * API请求逻辑处理
...@@ -70,7 +71,7 @@ public class ApiQueryService extends ApiParamVerify implements OpenApiService { ...@@ -70,7 +71,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)
...@@ -105,16 +106,19 @@ public class ApiQueryService extends ApiParamVerify implements OpenApiService { ...@@ -105,16 +106,19 @@ public class ApiQueryService extends ApiParamVerify implements OpenApiService {
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); 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); 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,7 +131,6 @@ public class ApiQueryService extends ApiParamVerify implements OpenApiService { ...@@ -127,7 +131,6 @@ public class ApiQueryService extends ApiParamVerify implements OpenApiService {
} }
/** /**
* 远程请求获取数据 * 远程请求获取数据
* *
...@@ -160,7 +163,9 @@ public class ApiQueryService extends ApiParamVerify implements OpenApiService { ...@@ -160,7 +163,9 @@ public class ApiQueryService extends ApiParamVerify implements OpenApiService {
return true; return true;
} else if (ApiInfoOutTypeEnum.JSON.name().equals(outputType)) { //json格式请求 } else if (ApiInfoOutTypeEnum.JSON.name().equals(outputType)) { //json格式请求
response.setAttribute("调用成功!"); 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); 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 +175,17 @@ public class ApiQueryService extends ApiParamVerify implements OpenApiService { ...@@ -170,14 +175,17 @@ 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 { } else {
throw new GatewayException(GatewayResultCode.OUTPUT_TYPE_EXCEPTION); throw new GatewayException(GatewayResultCode.OUTPUT_TYPE_EXCEPTION);
} }
return false;
} }
/** /**
* 通知扣款 * 通知扣款
*
* @param parameter * @param parameter
* @param bResult * @param bResult
*/ */
...@@ -186,19 +194,20 @@ public class ApiQueryService extends ApiParamVerify implements OpenApiService { ...@@ -186,19 +194,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(balanceUrl+"/mall/financeCustomerAssets/unfreezeMoney", 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);
} }
} }
} }
/** /**
* 限流返回方法 * 限流返回方法
* *
......
...@@ -4,6 +4,7 @@ package com.jz.dm.web.aspect; ...@@ -4,6 +4,7 @@ package com.jz.dm.web.aspect;
import com.jz.common.utils.IpUtils; import com.jz.common.utils.IpUtils;
import com.jz.common.utils.JsonUtils; import com.jz.common.utils.JsonUtils;
import com.jz.common.utils.UrlUtil; import com.jz.common.utils.UrlUtil;
import com.jz.dm.common.exception.GatewayException;
import com.jz.dm.mapper.ApiReqLogMapper; import com.jz.dm.mapper.ApiReqLogMapper;
import com.jz.dm.models.domian.ApiReqLog; import com.jz.dm.models.domian.ApiReqLog;
import com.jz.dm.service.ApiLogService; import com.jz.dm.service.ApiLogService;
...@@ -14,6 +15,7 @@ import javassist.bytecode.LocalVariableAttribute; ...@@ -14,6 +15,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;
...@@ -54,10 +56,10 @@ public class SystemLogAspect { ...@@ -54,10 +56,10 @@ public class SystemLogAspect {
/* //前置通知切入点 /* //前置通知切入点
@Pointcut("@annotation(com.jz.dm.web.annotation.ApiLogAspect)") @Pointcut("@annotation(com.jz.dm.web.annotation.ApiLogAspect)")
public void beforeAspect() { public void beforeAspect() {
} }*/
//最终通知切入点 //最终通知切入点
@Pointcut("@annotation(com.jz.dm.web.annotation.ApiLogAspect)") /* @Pointcut("@annotation(com.jz.dm.web.annotation.ApiLogAspect)")
public void lastAspect() { public void lastAspect() {
}*/ }*/
...@@ -79,6 +81,9 @@ public class SystemLogAspect { ...@@ -79,6 +81,9 @@ 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).split(";")[0];;
}
//获取请求路径 //获取请求路径
String url = UrlUtil.getServerUrl(request); String url = UrlUtil.getServerUrl(request);
// 访问项目名 // 访问项目名
...@@ -87,10 +92,11 @@ public class SystemLogAspect { ...@@ -87,10 +92,11 @@ 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);
ApiReqLog reqLog = new ApiReqLog();
JSONObject jsonResult =null;
try { try {
ApiReqLog reqLog = new ApiReqLog();
reqLog.setRequestIp(ip); reqLog.setRequestIp(ip);
reqLog.setApiKey(jsonObject.getString("apiKey")); reqLog.setApiKey(jsonObject.getString("apiKey"));
reqLog.setRequestParams(params); reqLog.setRequestParams(params);
...@@ -98,19 +104,23 @@ public class SystemLogAspect { ...@@ -98,19 +104,23 @@ public class SystemLogAspect {
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.setRequestStartTime(new Date());
reqLog.setRemark(getServiceMethodDescription(joinPoint)); reqLog.setRemark(getServiceMethodDescription(joinPoint));
log.info("请求参数:",reqLog); log.info("请求参数:",reqLog);
if (null != reqLog) { if (null != reqLog) {
apiReqLogMapper.insert(reqLog); apiReqLogMapper.insert(reqLog);
} }
Object result = joinPoint.proceed(joinPoint.getArgs()); Object result = joinPoint.proceed(joinPoint.getArgs());
JSONObject jsonResult = JSONObject.fromObject(result); jsonResult = JSONObject.fromObject(result);
log.info("around响应结果为{}", jsonResult); log.info("around响应结果为{}", jsonResult);
apiLogService.updateLog(reqLog.getId(), 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(); throwable.printStackTrace();
} }
} }
...@@ -162,39 +172,39 @@ public class SystemLogAspect { ...@@ -162,39 +172,39 @@ public class SystemLogAspect {
* 返回异常通知,返回抛出异常的时候执行的通知,可以获得返回的异常 * 返回异常通知,返回抛出异常的时候执行的通知,可以获得返回的异常
* 可以访问到异常对象,且可以指定在出现特定异常的时候再执行通知代码 * 可以访问到异常对象,且可以指定在出现特定异常的时候再执行通知代码
*/ */
/*@AfterReturning(value = "lastAspect()", returning = "result") //@AfterReturning(value = "lastAspect()", returning = "result")
public void afterReturn(JoinPoint joinPoint, Object result) { //public void afterReturn(JoinPoint joinPoint, Object result) {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()) // HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
.getRequest(); // .getRequest();
log.info("~~~~~~~~~~~~~~~~~~~~~~最终通知执行~~~~~~~~~~~~~~~~~~~~~~~~"); // log.info("~~~~~~~~~~~~~~~~~~~~~~最终通知执行~~~~~~~~~~~~~~~~~~~~~~~~");
String classType = joinPoint.getTarget().getClass().getName(); // String classType = joinPoint.getTarget().getClass().getName();
try { // try {
Class<?> clazz = Class.forName(classType); // Class<?> clazz = Class.forName(classType);
String clazzName = clazz.getName(); // String clazzName = clazz.getName();
// 拦截的方法名称。当前正在执行的方法 // // 拦截的方法名称。当前正在执行的方法
String methodName = joinPoint.getSignature().getName(); // String methodName = joinPoint.getSignature().getName();
// 获取方法的参数 // // 获取方法的参数
Object[] args = joinPoint.getArgs(); // Object[] args = joinPoint.getArgs();
// 获取传入参数的键值对 // // 获取传入参数的键值对
Map<String, Object> map = (Map<String, Object>) // Map<String, Object> map = (Map<String, Object>)
getFieldsName(this.getClass(), clazzName, methodName, // getFieldsName(this.getClass(), clazzName, methodName,
args); // args);
// 将request中的参数转化为键值对,方便取出 // // 将request中的参数转化为键值对,方便取出
// Map<String, Object> requestMap = (Map<String, Object>) map.get("request"); // // Map<String, Object> requestMap = (Map<String, Object>) map.get("request");
// 获取返回方法的参数 // // 获取返回方法的参数
JSONObject jsonObject = JSONObject.fromObject(result); // JSONObject jsonObject = JSONObject.fromObject(result);
Map mapResult = (Map) jsonObject; // Map mapResult = (Map) jsonObject;
//将返回的result参数取出 // //将返回的result参数取出
Map<String, Object> res = (Map<String, Object>) mapResult.get("data"); // Map<String, Object> res = (Map<String, Object>) mapResult.get("data");
Integer id = (Integer) res.get("id"); // Integer id = (Integer) res.get("id");
JSONObject data = jsonObject.getJSONObject("data"); // JSONObject data = jsonObject.getJSONObject("data");
// apiLogService.updateLog(id.longValue(), data); // // apiLogService.updateLog(id.longValue(), data);
} catch (Exception e) { // } catch (Exception e) {
log.error("~~~~~~~~~~~~~~~~~~~~~~~最终通知异常~~~~~~~~~~~~~~~~~~~~~~~"); // log.error("~~~~~~~~~~~~~~~~~~~~~~~最终通知异常~~~~~~~~~~~~~~~~~~~~~~~");
log.error("异常信息{}", e.getMessage()); // log.error("异常信息{}", e.getMessage());
} // }
}*/ // }
/** /**
* 获取注解中对方法的描述信息 用于service层注解 * 获取注解中对方法的描述信息 用于service层注解
......
...@@ -47,5 +47,63 @@ spring: ...@@ -47,5 +47,63 @@ spring:
# 日志用的filter:log4j # 日志用的filter:log4j
# 防御sql注入的filter:wall # 防御sql注入的filter:wall
filters: stat 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: ...@@ -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:
...@@ -92,8 +94,18 @@ sentinel: #sentinel每秒中最大的请求个数 ...@@ -92,8 +94,18 @@ sentinel: #sentinel每秒中最大的请求个数
#数据银行调用配置 #数据银行调用配置
data: data:
bank: bank:
balanceUrl: http://192.168.1.139:8081/mall/financeCustomerAssets/findAssets #余额信息url balanceUrl: http://192.168.1.139:8081 #余额信息url #扣款信通知url
withholdUrl: http://192.168.1.139:8081/mall/financeCustomerAssets/unfreezeMoney #扣款信通知url
token: #dataBank 制作验签 token: #dataBank 制作验签
dataBank: dataBank123 dataBank: dataBank123
#logback日志配置
logging:
config: classpath:logback-dev.xml
level:
com:
zhl:
springbootlogback: off
...@@ -8,6 +8,7 @@ logging: ...@@ -8,6 +8,7 @@ logging:
level: level:
com.netflix.discovery: 'OFF' com.netflix.discovery: 'OFF'
org.springframework.cloud: 'DEBUG' org.springframework.cloud: 'DEBUG'
com.jz.dm: debug
#SPRING配置文件 #SPRING配置文件
spring: spring:
...@@ -20,20 +21,24 @@ spring: ...@@ -20,20 +21,24 @@ spring:
profiles: profiles:
active: test #默认使用的配置文件 active: test #默认使用的配置文件
cloud: cloud:
sentinel: #sentinel 限流框架配置 sentinel:
transport: 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通讯 # 项目本地会启动一个服务的端口号,默认8719,用于与sentinel-dashboard通讯
port: 8719 port: 8719
# sentinel-dashboard服务地址 # sentinel-dashboard-1.6.0 的访问路径 ,启动方式java -jar sentinel-dashboard-1.6.0.jar #服务器ip
dashboard: localhost:9090 clientIp: 192.168.1.114
filter: filter:
# 需要进行限流监控的接口,多个匹配用逗号隔开 # 需要进行限流监控的接口,多个匹配用逗号隔开
url-patterns: /* url-patterns: /*
servlet: servlet:
# 触发限流后重定向的页面 # 触发限流后重定向的页面
block-page: /sentinel/block block-page: /sentinel/block
#取消Sentinel控制台懒加载 #取消Sentinel控制台懒加载
#eager: true eager: true
# ====================MybatisPlus==================== # ====================MybatisPlus====================
mybatis-plus: mybatis-plus:
...@@ -41,7 +46,7 @@ spring: ...@@ -41,7 +46,7 @@ spring:
# 如果是放在resource目录 classpath:/mapper/*Mapper.xml # 如果是放在resource目录 classpath:/mapper/*Mapper.xml
mapper-locations: classpath*:com/frame/**/**.xml,classpath*:mapping/**/**.xml mapper-locations: classpath*:com/frame/**/**.xml,classpath*:mapping/**/**.xml
#实体扫描,多个package用逗号或者分号分隔 #实体扫描,多个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: global-config:
#刷新mapper 调试神器 #刷新mapper 调试神器
db-config: 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 @@ ...@@ -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,36 @@ ...@@ -9,5 +9,36 @@
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_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> </mapper>
\ No newline at end of file
...@@ -7,5 +7,11 @@ ...@@ -7,5 +7,11 @@
request_token, request_time, remark, create_date, create_user, request_token, request_time, remark, create_date, create_user,
update_date, update_user, is_deleted update_date, update_user, is_deleted
</sql> </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> </mapper>
...@@ -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;
/** /**
......
...@@ -8,8 +8,8 @@ import com.jz.dm.models.domian.ApiOrg; ...@@ -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.OrganizationManageAddReq;
import com.jz.dm.models.req.organizationManage.OrganizationManageDetailQueryReq; 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.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 +29,7 @@ public class TestOrganizationManage extends SpringTestCase { ...@@ -29,7 +29,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 +40,10 @@ public class TestOrganizationManage extends SpringTestCase { ...@@ -40,10 +40,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 +51,7 @@ public class TestOrganizationManage extends SpringTestCase { ...@@ -51,7 +51,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,15 +68,15 @@ public class TestOrganizationManage extends SpringTestCase { ...@@ -68,15 +68,15 @@ 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);
req.setOrgDesc("粗这次002"); //req.setOrgDesc("粗这次002");
req.setOrgCnName("AOKK33"); //req.setOrgCnName("AOKK33");
req.setOrgMail("727322JA@QQ.COM"); //req.setOrgMail("727322JA@QQ.COM");
req.setRemark("sfsihsio"); //req.setRemark("sfsihsio");
Result result = organizationManageService.update(req); //Result result = organizationManageService.update(req);
System.out.println(result.getMessage()); //System.out.println(result.getMessage());
} }
} }
...@@ -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;
......
...@@ -34,12 +34,6 @@ ...@@ -34,12 +34,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 +87,6 @@ ...@@ -93,7 +87,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
...@@ -223,6 +223,7 @@ ...@@ -223,6 +223,7 @@
<artifactId>commons-net</artifactId> <artifactId>commons-net</artifactId>
<version>${commons-net.version}</version> <version>${commons-net.version}</version>
</dependency> </dependency>
<!--httpclient包-->
<dependency> <dependency>
<groupId>org.apache.httpcomponents</groupId> <groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId> <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