Commit da3c8b94 authored by ysongq's avatar ysongq

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

parents deb9ea2e 86d6f621
......@@ -4,24 +4,20 @@ CREATE TABLE `t_api_interface` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT 'api 信息表自增ID',
`api_key` varchar(200) NOT NULL COMMENT 'api唯一标识',
`api_name` varchar(100) DEFAULT NULL COMMENT 'api名称',
`api_desc` varchar(300) DEFAULT NULL COMMENT 'api描述',
`api_protocl` varchar(32) DEFAULT NULL COMMENT 'api请求协议:http,https',
`api_path` varchar(100) DEFAULT NULL COMMENT '请求地址',
`target_url` varchar(100) DEFAULT NULL COMMENT '目标url',
`api_type` varchar(50) NULL DEFAULT '' COMMENT 'api类型:1 数据银行制作大数据表 2 数据银行制作数据包,3,数据银行制作自定义API 4 API实时接入 6 标签查询 9自定义',
`api_type` varchar(50) NULL DEFAULT '' COMMENT '接入类型:字典表对应key值',
`req_type` varchar(20) NULL DEFAULT NULL COMMENT '请求方式: GET, POST',
`api_function` varchar(200) DEFAULT NULL COMMENT '接口功能',
`join_type` varchar(50) NULL DEFAULT NULL COMMENT '接入类型:字典表对应key值',
`test_example` varchar(255) NULL DEFAULT NULL COMMENT '测试实例',
`status` varchar(50) NOT NULL COMMENT '状态(DRAFT-草稿 ISSUE-发布 OUTMODED-过时 4FREEZE-冻结 EXPIRY-失效)',
`output_type` varchar(50) NULL DEFAULT 'JSON' COMMENT '输出类型:flow 流形式输出, json格式输出',
`page` tinyint(2) NULL DEFAULT '0' COMMENT '是否分页:0 false ,1 true',
`version` varchar(20) DEFAULT 'v1.0' COMMENT '版本号',
`sign_type` varchar(50) DEFAULT NULL COMMENT '加密方式: MD5 RSA',
`timeout` varchar(50) DEFAULT NULL COMMENT '超时时间',
`file_id` bigint(20) NOT NULL COMMENT '文件夹id',
`req_type` varchar(20) DEFAULT NULL COMMENT '限流类型:DAY 按天,MONTH 按月, YEAR 按年',
`file_id` bigint(20) DEFAULT NULL COMMENT '文件夹id',
`limit_type` varchar(20) DEFAULT NULL COMMENT '限流类型:DAY 按天,MONTH 按月, YEAR 按年',
`req_frequency` bigint(20) DEFAULT '100' COMMENT '限制次数',
`is_test` tinyint(2) NOT NULL DEFAULT '0' COMMENT '是否测试数据:0 否,1 是',
`is_send_bank` tinyint(2) NULL DEFAULT 0 COMMENT '是否发送到数据银行: 0 false ,1 true '
`remark` varchar(500) DEFAULT NULL COMMENT '备注',
`create_date` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`create_user` varchar(100) DEFAULT NULL COMMENT '创建人',
......@@ -37,18 +33,18 @@ DROP TABLE IF EXISTS `t_api_interface_custom`;
CREATE TABLE `t_api_interface_custom` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT 'api 信息表自增ID',
`api_key` varchar(200) NOT NULL COMMENT 'api唯一标识',
`api_interface_id` bigint(20) NOT NULL COMMENT 'api表自增id',
`api_type` varchar(50) DEFAULT '' COMMENT 'api类型:1 数据银行制作大数据表 2 数据银行制作数据包,3,数据银行制作自定义API 4 API实时接入 5 DMP标签查询 6.DMP大数据表查询 7 DMP自定义',
`es_data_source` varchar(100) DEFAULT NULL COMMENT '数据源id',
`es_data_base` varchar(100) DEFAULT NULL COMMENT '源数据库名称',
`es_table` varchar(100) DEFAULT NULL COMMENT '源数据表名称',
`handle_type` varchar(50) DEFAULT NULL COMMENT '处理类型',
`request_param` varchar(300) DEFAULT NULL COMMENT '请求参数',
`response_param` varchar(300) DEFAULT NULL COMMENT '响应参数',
`req_headers` varchar(300) DEFAULT NULL COMMENT '请求头',
`resp_code` varchar(300) DEFAULT NULL COMMENT '响应状态码',
`api_example` varchar(300) DEFAULT NULL COMMENT 'api返回样例',
`inbox_param` varchar(300) NULL DEFAULT NULL COMMENT '固定参数',
`page_num` int(10) NULL DEFAULT 1000000 COMMENT '最大行数',
`page_size` int(10) NULL DEFAULT 1000 COMMENT '每页返回行数',
`remark` varchar(500) DEFAULT NULL COMMENT '备注',
`create_date` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`create_user` varchar(100) DEFAULT NULL COMMENT '创建人',
......@@ -64,7 +60,7 @@ DROP TABLE IF EXISTS `t_api_interface_file`;
CREATE TABLE `t_api_interface_file` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT 'api文件表自增ID',
`project_id` bigint(20) NOT NULL COMMENT '项目编号',
`file_source` varchar(50) DEFAULT NULL COMMENT '文件来源:,1 dmp, 2 数据银行',
`file_source` varchar(50) DEFAULT NULL COMMENT '文件来源:,1 API制做,2 组织创建',
`file_name` varchar(50) DEFAULT NULL COMMENT '文件名称',
`file_en_name` varchar(50) DEFAULT NULL COMMENT '文件英文名称',
`parent_id` bigint(20) DEFAULT NULL COMMENT '父类id',
......@@ -91,6 +87,7 @@ CREATE TABLE `t_api_org` (
`org_type` varchar(20) NULL DEFAULT NULL COMMENT '组织类型:OUT 外部组织, IN 内部组织',
`status` tinyint(2) DEFAULT '1' COMMENT '状态: 0- 注销 1- 正常',
`org_mail` varchar(100) DEFAULT NULL COMMENT '组织邮箱',
`org_folder_id` bigint(20) DEFAULT NULL COMMENT '组织所在文件夹id',
`org_sort` int(10) DEFAULT '999' COMMENT '组织排序',
`parent_id` varchar(100) DEFAULT NULL COMMENT '父类组织编码',
`remark` varchar(500) DEFAULT NULL COMMENT '备注',
......@@ -118,6 +115,7 @@ CREATE TABLE `t_api_auth` (
`auth_mode` varchar(50) DEFAULT NULL COMMENT '授权方式:POWER_CALL_MODE 按次调用 ,RECORD_TIME_MODE 按时间调用 PERMANENT_TIME_MODE 永久有效',
`valid_start_time` datetime DEFAULT NULL COMMENT '开始时间',
`valid_end_time` datetime DEFAULT NULL COMMENT '结束时间',
`valid_expr_date` datetime DEFAULT NULL COMMENT '有效截止时间',
`handler` tinyint(2) NULL DEFAULT '0' COMMENT '处理状态:0 未处理, 1 已处理',
`status` varchar(50) NOT NULL COMMENT '状态(VALID-正常 UN_VALID-无效)',
`remark` varchar(500) DEFAULT NULL COMMENT '备注',
......
......@@ -30,4 +30,10 @@ public class TagConstants {
//redis限流相关
public static final String OPEN_API_REDIS_LIMIT_KEY = "jz:openapi:redis:limit:";
//API缓存Key
public static final String OPEN_API_CACHE_KEY = "jz:openapi:cache:";
}
......@@ -37,7 +37,6 @@ public enum GatewayResultCode implements ResultCode {
ILLEGAL_TIMETEMP("ILLEGAL_TIMETEMP", "无效时间戳"),
/** 请求次数受限 */
REQUEST_LIMIT_EXCEPTION("REQUEST_LIMIT_EXCEPTION", "请求次数受限"),
......@@ -60,6 +59,12 @@ public enum GatewayResultCode implements ResultCode {
/** API状态异常 */
API_STATUS_EXCEPTION("API_STATUS_EXCEPTION", "API状态异常"),
/** API类型错误 */
API_TYPE_ERROR("API_TYPE_ERROR", "API类型错误"),
/** 文件地址不存在 */
DATA_BIG_ADDR_UNEXIST("DATA_BIG_ADDR_UNEXIST", "文件地址不存在!"),
/** 请求组织状态异常 */
ORG_STATE_EXCEPTION("ORG_STATE_EXCEPTION", "请求组织状态异常"),
/** 请求信息不存在 */
......@@ -70,6 +75,9 @@ public enum GatewayResultCode implements ResultCode {
/** 单次调用金额不足 */
CALL_AMOUNT_NOT_ENOUGH("CALL_AMOUNT_NOT_ENOUGH", "单次调用金额不足"),
/** 认证API已过有效期 */
AUTH_EXCEED_TIME("AUTH_EXCEED_TIME", "认证API已过有效期"),
/** 输出类型错误 */
OUTPUT_TYPE_EXCEPTION("OUTPUT_TYPE_EXCEPTION", "输出类型错误!");
/**
......
......@@ -30,7 +30,7 @@ public enum AuthTypeEnum {
return text;
}
public static AuthTypeEnum fromTypeName(String typeName) {
public static AuthTypeEnum fromAuthTypeName(String typeName) {
for (AuthTypeEnum type : AuthTypeEnum.values()) {
if (type.name().equals(typeName)) {
return type;
......
......@@ -43,6 +43,24 @@ public class DateUtil {
c.set(Calendar.SECOND, 59);
return (c.getTimeInMillis() - System.currentTimeMillis()) / 1000;
}
/**
* 获取指定年份的时间
* @param year
* @return
*/
public static Date getAssignYearDate(Integer year){
Calendar cal = Calendar.getInstance();
/* int year =cal.get(Calendar.YEAR)+1;
int month=cal.get(Calendar.MONTH)+1;
cal.add(Calendar.MONTH, 0);*/
//Date date = cal.getTime(); //结果
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
cal.set(Calendar.YEAR,cal.get(Calendar.YEAR)+year);
Date date=cal.getTime();
System.out.println(sdf.format(date));
return date;
}
public static void main(String[] args) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//System.out.println(calculateNowResidueTime());
......
......@@ -125,6 +125,11 @@ public class RandomUtil {
builder.append(userNum);
}
coding = getCodeInfo(userId, coding, builder, month, day, hour, minute, second);
}else { //无内外部之分
if (StringUtils.isBlank(orgCode)) {
return "";
}
coding = getCodeInfo(orgCode, coding, builder, month, day, hour, minute, second);
}
return coding;
}
......
package com.jz.dm.common.util.stream;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.*;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import java.io.File;
......@@ -14,6 +19,7 @@ import java.text.MessageFormat;
import static com.jz.common.utils.HttpClientPool.getHttpClient;
/**
* @author ZC
* @PACKAGE_NAME: com.sentinel.project.util
......@@ -48,10 +54,92 @@ public class HttpDownload {
* @param url
* @return
*/
public static void download(String url) {
public static void getDownload(String url) {
download(url, null);
}
/**
* 根据url下载文件,文件名从response header头中获取
*
* @param url
* @param params
*/
public static void postDownload(String url, JSONObject params) {
postDownloadFolder(url, params,null);
}
/**
* 根据url下载文件,保存到filepath中
*
* @param url
* @param params
* @param filepath
*/
private static void postDownloadFolder(String url, JSONObject params,String filepath) {
CloseableHttpClient httpClient = getHttpClient();
InputStream is = null;
FileOutputStream fileOut = null;
CloseableHttpResponse response = null;
try {
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("Content-Type","application/json" );
if (StringUtils.isNotBlank(params.toString())) {
httpPost.setEntity(new StringEntity(params.toString(), Consts.UTF_8));
}
response = httpClient.execute(httpPost);
Header[] allHeaders = response.getAllHeaders();
for (Header header : allHeaders) {
System.out.println(MessageFormat.format("header:{0}={1}", header.getName(), header.getValue()));
}
String fileName = response.getHeaders("Content-Disposition")[0].getValue().split("filename=")[1];
System.out.println("文件名为" + fileName);
HttpEntity entity = response.getEntity();
is = entity.getContent();
if (fileName == null) {
fileName = getFilePath(response);
}
if (filepath != null) {
fileName = filepath + splash + fileName;
} else {
fileName = splash + fileName;
}
File file = new File(fileName);
file.getParentFile().mkdirs();
fileOut = new FileOutputStream(file);
/**
* 根据实际运行效果 设置缓冲区大小
*/
byte[] buffer = new byte[cache];
int ch = 0;
while ((ch = is.read(buffer)) != -1) {
fileOut.write(buffer, 0, ch);
}
fileOut.flush();
log.info("文件下载成功!");
} catch (Exception e) {
log.info("数据下载异常:{}", e.getMessage());
e.printStackTrace();
}finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != fileOut) {
try {
fileOut.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
/**
* 根据url下载文件,保存到filepath中
*
......@@ -81,8 +169,8 @@ public class HttpDownload {
}
if (filepath != null) {
fileName = filepath + splash + fileName;
}else {
fileName= splash + fileName;
} else {
fileName = splash + fileName;
}
File file = new File(fileName);
file.getParentFile().mkdirs();
......@@ -185,8 +273,22 @@ public class HttpDownload {
String docx = "http://192.168.1.140:8090/api/download/docx";
String pdf = "http://192.168.1.140:8090/api/download/pdf";
String xlsx = "http://192.168.1.140:8090/api/download/xlsx";
String getDownload ="http://192.168.1.140:8082/api/data/query/streaming?datasourceId=2&query_database=product&query_table=table1&request_fileds=%7b%22flelds1%22:%20%22xxxx%22,%20%22field2%22:%22xxxx%22%7d&response_fields=field1,field2,field3,field4&data_size=100";
String postDownload="http://192.168.1.140:8082/api/data/query/streaming1";
//String filepath = "C:\\Users\\key\\Desktop\\ideaIU-2019.3.3";
//HttpDownload.download(xlsx, null);
//getDownload(getDownload);
JSONObject jsonObject = new JSONObject();
jsonObject.put("datasourceId",1);
jsonObject.put("query_database","product");
jsonObject.put("query_table","table1");
JSONObject jsonObject1 = new JSONObject();
jsonObject1.put("flelds1","xxxxx");
jsonObject1.put("field2","xxxxx");
jsonObject.put("request_fileds",jsonObject1);
jsonObject.put("response_fields","field1,field2,field3,field4");
jsonObject.put("data_size",100);
String filepath = "C:\\Users\\key\\Desktop\\ideaIU-2019.3.3";
HttpDownload.download(xlsx, filepath);
postDownloadFolder(postDownload,jsonObject,null);
}
}
......@@ -31,18 +31,26 @@ public class ApiInterfaceController {
/**
* @Description:API列表查询
* @return: API列表
* @Author: Mr.zhang
* @Date: 2020-12-24
*/
@ApiOperation("API列表查询")
@ApiOperation("API---(已调用列表)列表查询")
@PostMapping(value = "/listApiInterface")
public Mono<Result> getApiInterfaceCallList(@RequestBody @Valid ApiInterfaceInfoListReq req) {
return Mono.fromSupplier(() -> Result.of_success(apiInterfaceService.listCallApiInterface(req)));
}
/**
* @Description:API列表查询
* @Author: Mr.zhang
* @Date: 2020-12-24
*/
@ApiOperation("API---(未调用列表)列表查询")
@PostMapping(value = "/listUnCallApiInterface")
public Mono<Result> getApiInterfaceList(@RequestBody @Valid ApiInterfaceInfoListReq req) {
return Mono.fromSupplier(() -> Result.of_success(apiInterfaceService.listApiInterface(req)));
return Mono.fromSupplier(() -> Result.of_success(apiInterfaceService.listUnCallApiInterface(req)));
}
/**
* @Description:API详情查询
* @return: API详情查询
* @Author: Mr.zhang
* @Date: 2020-12-24
*/
......@@ -53,7 +61,6 @@ public class ApiInterfaceController {
}
/**
* @Description:API删除
* @return: API删除
* @Author: Mr.zhang
* @Date: 2020-12-24
*/
......@@ -64,7 +71,6 @@ public class ApiInterfaceController {
}
/**
* @Description:DMP-API删除
* @return: DMP-API删除
* @Author: Mr.zhang
* @Date: 2020-12-24
*/
......@@ -74,16 +80,27 @@ public class ApiInterfaceController {
@RequestParam (name="apiKey")String apiKey) {
return Mono.fromSupplier(() -> apiInterfaceService.dmpDeleteAuth(type,apiKey));
}
/**
* @Description:数据修改发送状态接口
* @Author: Mr.zhang
* @Date: 2020-12-24
*/
@ApiOperation("数据修改发送状态接口")
@GetMapping(value = "/updateSendStatus")
public Mono<Result> updateApiSendStatus(@RequestParam (name="apiKey")String apiKey) {
return Mono.fromSupplier(() -> apiInterfaceService.updateApiSendStatus(apiKey));
}
/**
* @Description:API测试调用
* @return: DMP-API删除
* @Description: 已发送到数据银行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));
@ApiOperation("已发送到数据银行API列表")
@GetMapping(value = "/listSendDataBank")
public Mono<Result> listSendDataBank(@RequestParam (name="pageNum",defaultValue = "1",required = false)String pageNum,
@RequestParam (name="pageSize",defaultValue = "20",required = false)String pageSize) {
return Mono.fromSupplier(() -> apiInterfaceService.getSendDataBankList(pageNum, pageSize));
}
}
......@@ -29,6 +29,16 @@ public class AuthController {
@Autowired
private AuthService authService;
/**
* @Description:服务授权列表
* @Author: Mr.zhang
* @Date: 2020-12-26
*/
@ApiOperation("服务授权列表")
@PostMapping(value = "/getServiceAuthList")
public Mono<Result> getServiceAuthList(@RequestBody @Valid ServiceAuthReq req) {
return Mono.fromSupplier(() -> authService.getServiceAuthList(req));
}
/**
* @Description:商城用户API认证
* @return: 商城用户API认证
......
......@@ -12,6 +12,7 @@ import io.swagger.annotations.Api;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
......@@ -32,7 +33,8 @@ public class GatewayController {
@Autowired
private GatewayService gatewayService;
@RequestMapping(value = "/gateway", consumes = "application/json")
//@RequestMapping(value = "/gateway", consumes = "application/json")
@PostMapping(value="/gateway",consumes = "application/json")
public String gateway(@RequestBody String json, HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse) {
GatewayRequest gatewayRequest = JSON.parseObject(json, GatewayRequest.class);
......
......@@ -62,16 +62,6 @@ public class OrganizationManageController {
public Mono<Result> add(@RequestBody @Valid OrganizationManageAddReq req) {
return Mono.fromSupplier(() -> organizationManageService.add(req));
}
/**
* @Description:更新组织信息
* @Author: Mr.zhang
* @Date: 2020-12-24
*/
/* @ApiOperation("更新组织信息")
@PostMapping(value = "/update")
public Mono<Result> update(@RequestBody @Valid OrganizationManageUpdateReq req) {
return Mono.fromSupplier(() -> organizationManageService.update(req));
}*/
/**
* @Description:注销组织
* @Author: Mr.zhang
......
package com.jz.dm.controller;
import com.jz.common.utils.Result;
import com.jz.dm.models.req.make.*;
import com.jz.dm.models.req.folder.CreateFolderReq;
import com.jz.dm.models.req.producer.ApiInterfaceReq;
import com.jz.dm.models.req.producer.ServiceIssueReq;
import com.jz.dm.service.ProducerService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
......@@ -46,115 +48,147 @@ public class ProducerController {
*/
@ApiOperation("创建项目文件夹")
@PostMapping(value = "/createProjectFolder")
public Mono<Result> createProjectFolder(@RequestParam(name = "projectId")Long projectId,
@RequestParam(name = "parentId")Long parentId,
@RequestParam(name = "currentUser") String currentUser ) {
return Mono.fromSupplier(() -> producerService.createProjectFolder(projectId,parentId,currentUser));
public Mono<Result> createProjectFolder(@RequestBody @Valid CreateFolderReq req) {
return Mono.fromSupplier(() -> producerService.createProjectFolder(req));
}
/**
* @Description:Api制作(自定义DMP)
* @Description:服务发布列表
* @Author: Mr.zhang
* @Date: 2020-12-26
*/
@ApiOperation("Api制作(自定义DMP)")
@PostMapping(value = "/addCustomApi")
public Mono<Result> makeCustomApi(@RequestBody @Valid ApiInterfaceReq req) {
return Mono.fromSupplier(() -> Result.of_success(producerService.addCustomApi(req)));
@ApiOperation("服务发布列表")
@PostMapping(value = "/getServiceIssueList")
public Mono<Result> getServiceIssueList(@RequestBody @Valid ServiceIssueReq req) {
return Mono.fromSupplier(() -> producerService.getServiceIssueList(req));
}
/**
* @Description:Api制作(数据银行)
* @Description:服务发布/服务取消
* @Author: Mr.zhang
* @Date: 2020-12-26
*/
@ApiOperation("Api制作(数据银行)")
@PostMapping(value = "/addDataBankApiInfo")
public Mono<Result> addDataBankApiInfo(@RequestBody @Valid MakeDataBankApiReq req) {
return Mono.fromSupplier(() -> producerService.addDataBankApiInfo(req));
@ApiOperation("服务发布/服务取消")
@GetMapping(value = "/optionApiIssueStatus")
public Mono<Result> optionApiIssueStatus(@RequestParam(name = "id")Long id,
@RequestParam(name="optStatus")Boolean optStatus) {
return Mono.fromSupplier(() -> producerService.optionApiIssueStatus(id,optStatus));
}
/**
* @Description:Api制作(实时接入)
* @Description:获取APIID
* @Author: Mr.zhang
* @Date: 2020-12-26
*/
@ApiOperation("Api制作(实时接入)")
@PostMapping(value = "/realMakeApi")
public Mono<Result> realCustomApi(@RequestBody @Valid MakeRealCustomApiReq req) {
return Mono.fromSupplier(() -> Result.of_success(producerService.addRealCustomApi(req)));
@ApiOperation("Api制作(获取ApiId)")
@PostMapping(value = "/getCustomApiId")
public Mono<Result> getCustomApiId() {
return Mono.fromSupplier(() ->producerService.getCustomApiId());
}
/**
* @Description:Api制作(大数据查询/标签查询)
* @return:
* @Description:Api制作(第三方)
* @Author: Mr.zhang
* @Date: 2020-12-26
*/
@ApiOperation("Api制作(大数据查询/标签查询)")
@PostMapping(value = "/makeBigDataApi")
public Mono<Result> bigDataMakeApi(@RequestBody @Valid MakeBigDataApiReq req) {
return Mono.fromSupplier(() -> producerService.addBigDataMakeApi(req));
@ApiOperation("Api制作(第三方)")
@PostMapping(value = "/addCustomApi")
public Mono<Result> makeCustomApi(@RequestBody @Valid ApiInterfaceReq req) {
return Mono.fromSupplier(() -> Result.of_success(producerService.saveInterfaceAPi(req)));
}
/**
* @Description:保存API基本信息/自定义API
* @return: (保存API基本信息)
* @Description:Api制作(数据查询/标签查询)
* @Author: Mr.zhang
* @Date: 2020-12-26
*/
@ApiOperation("保存API基本信息")
@PostMapping(value = "/saveInterface")
public Mono<Result> saveInsetInterface(@RequestBody @Valid ApiInterfaceReq req) {
return Mono.fromSupplier(() -> producerService.saveInterfaceAPi(req));
@ApiOperation("Api制作(数据查询/标签查询)")
@PostMapping(value = "/addDataTableSelect")
public Mono<Result> bigDataMakeApi(@RequestBody @Valid ApiInterfaceReq req) {
return Mono.fromSupplier(() -> producerService.addBigDataMakeApi(req));
}
/**
* @Description:Api制作(大数据查询/标签查询)保存修改的api信息
* @return: (自定义更新同时使用)
* @Author: Mr.zhang
* @Date: 2020-12-26
*/
@ApiOperation("保存修改的api信息")
/* @ApiOperation("保存修改的api信息")
@PostMapping(value = "/saveUpdate")
public Mono<Result> saveUpdateAPiInfo(@RequestBody @Valid ApiInterfaceReq req) {
return Mono.fromSupplier(() -> producerService.saveUpdateAPiInfo(req));
}*/
/* *//**
* @Description:Api制作(数据银行)
* @Author: Mr.zhang
* @Date: 2020-12-26
*//*
@ApiOperation("Api制作(数据银行)")
@PostMapping(value = "/addDataBankApiInfo")
public Mono<Result> addDataBankApiInfo(@RequestBody @Valid MakeDataBankApiReq req) {
return Mono.fromSupplier(() -> producerService.addDataBankApiInfo(req));
}
*//**
* @Description:Api制作(实时接入)
* @Author: Mr.zhang
* @Date: 2020-12-26
*//*
@ApiOperation("Api制作(实时接入)")
@PostMapping(value = "/realMakeApi")
public Mono<Result> realCustomApi(@RequestBody @Valid MakeRealCustomApiReq req) {
return Mono.fromSupplier(() -> Result.of_success(producerService.addRealCustomApi(req)));
}*/
/**
* @Description:保存API基本信息/自定义API
* @return: (保存API基本信息)
* @Author: Mr.zhang
* @Date: 2020-12-26
*//*
@ApiOperation("保存API基本信息")
@PostMapping(value = "/saveInterface")
public Mono<Result> saveInsetInterface(@RequestBody @Valid ApiInterfaceReq req) {
return Mono.fromSupplier(() -> producerService.saveInterfaceAPi(req));
}*/
/*
*//**
* @Description:获取数据源配置
* @Author: Mr.zhang
* @Date: 2020-12-26
*/
*//*
@ApiOperation("获取数据源配置")
@PostMapping(value = "/getSourceConfig")
public Mono<Result> getSourceConfig(@RequestBody @Valid SourceConfigReq req) {
return Mono.fromSupplier(() -> producerService.getSourceConfig(req));
}
/**
*//**
* @Description:获取索引
* @Author: Mr.zhang
* @Date: 2020-12-26
*/
*//*
@ApiOperation("获取索引")
@GetMapping(value = "/getIndicess")
public Mono<Result> getSourceWarehouseList(@RequestParam(name = "id") Long id) {
return Mono.fromSupplier(() -> producerService.getSourceWarehouseList(id));
}
/**
*//**
* @Description:获取某个索引下的type
* @Author: Mr.zhang
* @Date: 2020-12-26
*/
*//*
@ApiOperation("获取某个索引下的type")
@GetMapping(value = "/getIndicesTypes")
public Mono<Result> getIndicesTypes(@RequestParam(name = "indices") String indices,
@RequestParam(name = "id") Long id) {
return Mono.fromSupplier(() -> producerService.getIndicesTypes(indices,id));
}
/**
*//**
* @Description:获取某个索引 type的fields
* @Author: Mr.zhang
* @Date: 2020-12-26
*/
*//*
@ApiOperation("获取某个索引 type的fields")
@GetMapping(value = "/getIndicesTypesFields")
public Mono<Result> getIndicesTypesFields(@RequestParam(name = "indices") String indices,
......@@ -174,5 +208,5 @@ public class ProducerController {
@GetMapping(value = "/getRedisObj")
public Result getObjOnRedis() {
return producerService.getObjOnRedis();
}
}*/
}
......@@ -5,6 +5,7 @@ import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.jz.common.utils.HttpsUtils;
import com.jz.common.utils.RedisUtils;
import com.jz.dm.common.constant.Constants;
import com.jz.dm.common.constant.TagConstants;
import com.jz.dm.common.enums.GatewayResultCode;
import com.jz.dm.common.enums.apiInterface.ApiStatusEnum;
import com.jz.dm.common.enums.auth.AuthReqTypeEnum;
......@@ -89,7 +90,11 @@ public class AuthFilter extends AbstractFilter {
}
}
JSONObject parameter = JSONObject.parseObject(request.getParams());
if (null != parameter) {
if (null == parameter) {
throw new GatewayException(GatewayResultCode.REQUEST_PARAM_EMPTY);
}
Boolean isTest = parameter.getBoolean("isTest");
if (!isTest) {//是否测试数据
String authCode = parameter.getString("authCode");
ApiAuth authAuth = authService.getAuthUser(authCode, apiInterface.getId());
if (null == authAuth) {
......@@ -107,7 +112,7 @@ public class AuthFilter extends AbstractFilter {
if (!apiOrg.getStatus()) {
throw new GatewayException(GatewayResultCode.ORG_STATE_EXCEPTION);
}
checkBill(request, authCode, authAuth, apiOrg);
checkBill(request, authCode, authAuth);
}
chain.doFilter(request, response);
} catch (Exception e) {
......@@ -121,7 +126,6 @@ public class AuthFilter extends AbstractFilter {
response.clearAttributes();
response.setCode(GatewayResultCode.UNKNOWN_EXCEPTION.getCode());
response.setMsg(GatewayResultCode.UNKNOWN_EXCEPTION.getMsg());
}
}
......@@ -132,19 +136,24 @@ public class AuthFilter extends AbstractFilter {
* @param request
* @param authCode
* @param authAuth
* @param apiOrg
* @throws ParseException
*/
private void checkBill(GatewayRequest request, String authCode,
ApiAuth authAuth, ApiOrg apiOrg) throws ParseException {
ApiAuth authAuth) throws ParseException {
SimpleDateFormat dateFormat = new SimpleDateFormat(Constants.DATE_TIME_FORMAT);
String formatDate = dateFormat.format(new Date());
Date currentDate = dateFormat.parse(formatDate);
switch (authAuth.getAuthMode()) {
case "POWER_CALL_MODE": //按次调用
Date validExprDate = authAuth.getValidExprDate();
if (currentDate.after(validExprDate)) {//超出时间
throw new GatewayException(GatewayResultCode.AUTH_EXCEED_TIME);
}
try { //记录请求次数(每天限制请求次数)
//查询数据银行银行余额是否充足
getDataAmountResult(request);
try { //记录请求次数(每天限制请求次数)
// String limitKey = TagConstants.OPEN_API_REDIS_LIMIT_KEY + authCode;
String limitKey = authCode;
String reqValue = (String)redisUtils.getObj(limitKey);
String limitKey = TagConstants.OPEN_API_REDIS_LIMIT_KEY + authCode;
Integer reqValue = (Integer) redisUtils.getObj(limitKey);
long timeOut = 0;
if (AuthReqTypeEnum.DAY.name().equals(authAuth.getReqType())) { //按天
timeOut = DateUtil.calculateNowResidueTime();
......@@ -154,11 +163,11 @@ public class AuthFilter extends AbstractFilter {
//暂时不支持年
}
if (null != reqValue) {
Integer value = Integer.valueOf(reqValue);
if (value > authAuth.getReqFrequency()) {//超出最大请求次数
/* Integer value = Integer.valueOf(reqValue);*/
if (reqValue > authAuth.getReqFrequency()) {//超出最大请求次数
throw new GatewayException(GatewayResultCode.REQUEST_LIMIT_EXCEPTION);
} else if (value <= authAuth.getReqFrequency()) {
redisUtils.delAndAdd(limitKey, limitKey, value + 1, timeOut);
} else if (reqValue <= authAuth.getReqFrequency()) {
redisUtils.delAndAdd(limitKey, limitKey, reqValue + 1, timeOut);
}
} else {
redisUtils.set(limitKey, 1, timeOut);
......@@ -170,9 +179,6 @@ public class AuthFilter extends AbstractFilter {
}
break;
case "RECORD_TIME_MODE": //按时间调用
SimpleDateFormat dateFormat = new SimpleDateFormat(Constants.DATE_TIME_FORMAT);
String formatDate = dateFormat.format(new Date());
Date currentDate = dateFormat.parse(formatDate);
Date validEndTime = authAuth.getValidEndTime();
//如果 date1 在 date2 之前,before 返回 true,否则返回 false
if (currentDate.after(validEndTime)) {//超出时间
......@@ -181,6 +187,10 @@ public class AuthFilter extends AbstractFilter {
}
break;
case "PERMANENT_TIME_MODE"://永久有效(直接跳出)
Date validExpr = authAuth.getValidExprDate();
if (currentDate.after(validExpr)) {//超出时间
throw new GatewayException(GatewayResultCode.AUTH_EXCEED_TIME);
}
break;
default:
throw new GatewayException(GatewayResultCode.ILLEGAL_REQUEST);
......@@ -217,7 +227,7 @@ public class AuthFilter extends AbstractFilter {
pObject.put("assetsId", assetsId);
pObject.put("userId", userId);
pObject.put("dataPrice", dataPrice);
String respResult = httpUtils.submitPost(balanceUrl+"/mall/financeCustomerAssets/findAssets", pObject.toString());
String respResult = httpUtils.submitPost(balanceUrl + "/mall/financeCustomerAssets/findAssets", pObject.toString());
JSONObject result = JSONObject.parseObject(respResult);
if (null != result) {
if (200 != result.getInteger("code")) {
......
package com.jz.dm.filter;
import com.jz.dm.common.enums.GatewayResultCode;
import com.jz.dm.common.exception.OpenApiException;
import com.jz.dm.common.util.LogUtil;
import com.jz.dm.common.util.ResultCode;
import com.jz.dm.models.enity.GatewayRequest;
import com.jz.dm.models.enity.GatewayResponse;
import com.jz.dm.common.enums.GatewayResultCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
......@@ -25,7 +25,8 @@ public class FilterChainImpl implements FilterChain {
private final List<Filter> filters = new ArrayList<Filter>();
public FilterChainImpl() { }
public FilterChainImpl() {
}
public FilterChainImpl(List<Filter> filters) {
addFilters(filters);
......
......@@ -19,15 +19,16 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
* @Description: 验签过滤器(验证签名信息)
* @Author: Mr.zhang
* @Date: 2021-1-6
*/
* @Description: 验签过滤器(验证签名信息)
* @Author: Mr.zhang
* @Date: 2021-1-6
*/
@Component
public class VerifySignFilter extends AbstractFilter {
private static final Logger LOGGER = LoggerFactory.getLogger(VerifySignFilter.class);
@Autowired
private ApiInterfaceService apiInterfaceService;
@Override
public int getOrder() {
return Constants.FILTER_ORDER_3;
......@@ -37,27 +38,30 @@ public class VerifySignFilter extends AbstractFilter {
public String getFilterName() {
return "VerifySignFilter";
}
@Override
protected void internalDoFilter(GatewayRequest request, GatewayResponse response,
FilterChain chain) {
try {
//对签约参数进行字典排序
String signParams = MapUtil.getSignValue(request.getApiKey(),request.getMethod(),request.getSignType());
if (StringUtils.isNotBlank(signParams)){
JSONObject jsonObject = JSONObject.parseObject(request.getParams());
if (!jsonObject.getBoolean("isTest")) {//是否测试调用
//对签约参数进行字典排序
String signParams = MapUtil.getSignValue(request.getApiKey(), request.getMethod(), request.getSignType());
if (StringUtils.isNotBlank(signParams)) {
String authCode = jsonObject.getString("authCode");
//需要传入授权码
ApiAuth apiAuthInfo = apiInterfaceService.getApiAuthInfo(request.getApiKey(),authCode );
if (null == apiAuthInfo){
ApiAuth apiAuthInfo = apiInterfaceService.getApiAuthInfo(request.getApiKey(), authCode);
if (null == apiAuthInfo) {
throw new GatewayException(GatewayResultCode.ILLEGAL_REQUEST);
}
String sign = Md5.encrypt(signParams, apiAuthInfo.getSalt());
if (!request.getSign().equals(sign)){
if (!request.getSign().equals(sign)) {
throw new GatewayException(GatewayResultCode.SIGN_ERROR);
}
}else {
} else {
throw new GatewayException(GatewayResultCode.SIGN_ERROR);
}
}
chain.doFilter(request, response);
} catch (SignatureException ex) {
LogUtil.error(LOGGER, ex,
......@@ -66,8 +70,8 @@ public class VerifySignFilter extends AbstractFilter {
response.setCode(ex.getResultCode().getCode());
response.setMsg(ex.getResultCode().getMsg());
} catch (Throwable ex) {
if(ex instanceof GatewayException){
throw(GatewayException) ex;
if (ex instanceof GatewayException) {
throw (GatewayException) ex;
}
LogUtil.error(LOGGER, ex,
"signatureFilter doFilter error. response=" + response.getResponse());
......
package com.jz.dm.gateway;
import com.alibaba.fastjson.JSON;
import com.jz.dm.common.exception.GatewayException;
import com.jz.dm.common.exception.OpenApiException;
import com.jz.dm.common.util.OpenApiRequest;
import com.jz.dm.common.util.OpenApiResponse;
......@@ -65,18 +66,17 @@ public class DefaultOpenApiDispatcher implements OpenApiDispatcher {
response.setMsg(OpenApiResultCode.ILLEGAL_INTERFACE.getMsg());
return JSON.toJSONString(response.getAttributes());
}
try {
OpenApiRequest request = new OpenApiRequest(context.getOpenApiParams());
request.setApiKey(context.getApiKey());
request.setExtAttributes(context.getExtAttributes());
openApiService.doService(request, response);
} catch (Throwable ex) {
}catch (Throwable ex) {
if (ex instanceof OpenApiException) {
OpenApiException oae = (OpenApiException) ex;
response.setCode(oae.getResultCode().getCode());
response.setMsg(oae.getResultCode().getMsg());
} else {
throw(OpenApiException) ex;
} else if (ex instanceof GatewayException){
throw(GatewayException) ex;
}else{
LOGGER.error("OpenApiService doService error,DispatchContext=" + context, ex);
response.setCode(OpenApiResultCode.UNKNOWN_EXCEPTION.getCode());
response.setMsg(OpenApiResultCode.UNKNOWN_EXCEPTION.getMsg());
......@@ -84,8 +84,8 @@ public class DefaultOpenApiDispatcher implements OpenApiDispatcher {
return JSON.toJSONString(response.getAttributes());
}
if (StringUtil.isEmpty(response.getCode())) {
response.setCode(OpenApiResultCode.SUCCESS.getCode());
response.setMsg(OpenApiResultCode.SUCCESS.getMsg());
response.setCode(OpenApiResultCode.UNKNOWN_EXCEPTION.getCode());
response.setMsg(OpenApiResultCode.UNKNOWN_EXCEPTION.getMsg());
}
return JSON.toJSONString(response.getAttributes());
}
......
......@@ -5,6 +5,7 @@ import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.jz.dm.models.domian.ApiInterface;
import com.jz.dm.models.domian.ApiInterfaceCustom;
import com.jz.dm.models.dto.ApiServiceApplyDto;
import com.jz.dm.models.req.api.ApiInterfaceDetailReq;
import org.apache.ibatis.annotations.Param;
......@@ -21,13 +22,21 @@ public interface ApiInterfaceMapper extends BaseMapper<ApiInterface> {
/**
* 查询API列表信息
* 查询(已调用)API列表信息
* @param page
* @param query
* @return
*/
IPage<ApiInterface > listApiInterfaceInfo(IPage<ApiInterface > page, @Param("ew") Wrapper<ApiInterface > query);
/**
* 查询(未调用)API列表信息
* @param page
* @param query
* @return
*/
IPage<ApiInterface > listCallApiInterfaceInfo(IPage<ApiInterface > page, @Param("ew") Wrapper<ApiInterface > query);
/**
* 查询API详情信息
* @param req
......@@ -42,4 +51,21 @@ public interface ApiInterfaceMapper extends BaseMapper<ApiInterface> {
* @return
*/
ApiInterfaceCustom getTestData(String apiKey);
/**
* 查询服务发布列表
* @param page
* @param query
* @return
*/
IPage<ApiServiceApplyDto > listApiIssueService(IPage<ApiServiceApplyDto> page, @Param("ew") Wrapper<ApiServiceApplyDto> query);
/**
* 查询服务授权列表
* @param page
* @param query
* @return
*/
IPage<ApiServiceApplyDto > listApiAuthService(IPage<ApiServiceApplyDto> page, @Param("ew") Wrapper<ApiServiceApplyDto> query);
}
......@@ -97,6 +97,15 @@ public class ApiAuth extends BaseObject implements Serializable {
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date validEndTime;
/**
* 有效截止时间
*/
@ApiModelProperty("有效截止时间")
@TableField("valid_expr_date")
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date validExprDate;
/**
* 处理状态:0 未处理, 1 已处理
......
......@@ -38,12 +38,6 @@ public class ApiInterface extends BaseObject implements Serializable {
@JsonIgnore
private String apiName;
/**
* api描述
*/
@TableField("api_desc")
private String apiDesc;
/**
* api请求协议:http,https
*/
......@@ -51,41 +45,29 @@ public class ApiInterface extends BaseObject implements Serializable {
private String apiProtocl;
/**
* api类型:1 数据银行制作大数据表 2 数据银行制作数据包,3,数据银行制作自定义API 4 API实时接入 5 DMP标签查询 6.DMP大数据表查询 7 DMP自定义'
* 接入类型:对应字典表key
*/
@TableField("api_type")
private String apiType;
/**
* 请求地址
*/
@TableField("api_path")
private String apiPath;
/**
* 目标url
*/
@TableField("target_url")
private String targetUrl;
/**
* 接入类型:对应字典表key
*/
@TableField("join_type")
private String joinType;
/**
* 测试实例
* 请求方式:GET POST
*/
@TableField("test_example")
private String testExample;
@TableField("req_type")
private String reqType;
/**
* '输出类型:flow 流形式输出, json格式输出',
*/
@TableField("output_type")
private String outputType;
/**
* 是否分页:0 false ,1 true
*/
@TableField("page")
private Boolean page;
/**
* 状态(1-草稿 2-发布 3-过时 4-冻结 5-失效)
......@@ -113,8 +95,8 @@ public class ApiInterface extends BaseObject implements Serializable {
/**
* 限流类型:DAY 按天,MONTH 按月, YEAR 按年
*/
@TableField("req_type")
private String reqType;
@TableField("limit_type")
private String limitType;
/**
* 限制次数
......@@ -127,17 +109,19 @@ public class ApiInterface extends BaseObject implements Serializable {
@TableField("timeout")
private String timeout;
/**
* 是否测试数据:0 否,1 是
*/
@TableField("is_test")
private Integer isTest;
/**
* 文件夹id
*/
@TableField("file_id")
private Long fileId;
/**
* 是否发送到数据银行
*/
@TableField("is_send_bank")
private Boolean isSendBank;
/*-----------------------------------保存数据库时忽略字段--------------------------------*/
/**
* 请求总次数
......
......@@ -93,5 +93,19 @@ public class ApiInterfaceCustom extends BaseObject implements Serializable {
*/
@TableField("inbox_param")
private String inboxParam;
/**
* 最大行数
*/
@TableField("max_row")
private Long maxRow;
/**
* 每页返回行数
*/
@TableField("page_row")
private Long pageRow;
}
......@@ -31,17 +31,11 @@ public class ApiInterfaceFile extends BaseObject implements Serializable {
private Long projectId;
/**
* 文件来源:1 DMP 2 数据银行
* 文件来源:,1 API制做,2 组织创建
*/
@TableField("file_source")
private String fileSource;
///**
//* 文件类型:1 文件夹 ,2 文件
//*/
//@TableField("file_type")
//private String fileType;
/**
* 文件名称
*/
......
......@@ -55,6 +55,13 @@ public class ApiOrg extends BaseObject implements Serializable {
*/
@TableField("linkman")
private String linkman;
/**
* 组织目录文件夹
*/
@TableField("org_folder_id")
private Long orgFolderId;
/**
* 组织类型 OUT 外部组织 IN 内部组织
*/
......
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: ApiServiceApplyDto
* @DATE: 2021-1-28/11:10
* @DAY_NAME_SHORT: 周四
* @Description:
**/
@Data
@ApiModel(value = "服务发布/授权应用类")
public class ApiServiceApplyDto implements Serializable {
@ApiModelProperty(value = "apiId")
private String apiId;
@ApiModelProperty(value = "api名称")
private String apiName;
@ApiModelProperty(value = "api类型")
private String apiType;
@ApiModelProperty(value = "返回类型")
private String outputType;
@ApiModelProperty(value = "请求方式")
private String reqType;
@ApiModelProperty(value = "最大数据量")
private Long maxRow;
@ApiModelProperty(value = "每页行数")
private Long pageRow;
@ApiModelProperty(value = "描述")
private String apiFunction;
@ApiModelProperty(value = "是否发布到数据银行,0 false 1 true")
private Boolean isSendBank;
@ApiModelProperty(value = "授权码")
private String authCode;
}
......@@ -49,6 +49,10 @@ public class GatewayRequest implements Serializable {
@ApiModelProperty(value="请求参数,JSON格式")
private String params;
@ApiModelProperty(value="是否测试请求")
private Boolean isTest;
@ApiModelProperty(value="扩展属性")
private final Map<String, Attribute> extAttributes = new HashMap<String, Attribute>();
......
......@@ -38,9 +38,9 @@ public class AuthUserApiReq implements Serializable {
@NotNull(message = "组织编码不能为空")
private String orgCode;
/* @ApiModelProperty(value = "授权类型:DATA_BANK_AUTH 数据银行 , DMP_AUTH 授权",required = true)
@ApiModelProperty(value = "授权类型:DATA_BANK_AUTH 数据银行 , DMP_AUTH 授权",required = true)
@NotNull(message = "授权类型不能为空")
private String authType;*/
private String authType;
@ApiModelProperty(value = "授权方式:POWER_CALL_MODE 按次调用 ,RECORD_TIME_MODE 按时间调用,PERMANENT_TIME_MODE 永久有效",required = true)
@NotNull(message = "授权方式不能为空")
......
package com.jz.dm.models.req.auth;
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.auth
* @PROJECT_NAME: jz-dm-parent
* @NAME: ServiceAuthReq
* @DATE: 2021-1-28/11:50
* @DAY_NAME_SHORT: 周四
* @Description:
**/
@Data
@ApiModel(value = "服务授权请求体")
public class ServiceAuthReq extends BasePageBean implements Serializable {
@ApiModelProperty(value = "文件夹id",required = false)
private Long folderId;
@ApiModelProperty(value = "api名称",required = false)
private String apiName;
@ApiModelProperty(value = "apiId",required = false)
private String apiId;
}
package com.jz.dm.models.req.folder;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import org.hibernate.validator.constraints.NotBlank;
import java.io.Serializable;
/**
* @author ZC
* @PACKAGE_NAME: com.jz.dm.models.req
* @PROJECT_NAME: jz-dm-parent
* @NAME: CreateFolderReq
* @DATE: 2021-1-27/18:12
* @DAY_NAME_SHORT: 周三
* @Description:
**/
@Data
@ApiModel("创建文件请求体")
public class CreateFolderReq implements Serializable {
@ApiModelProperty(value = "项目id",required = false)
private Long projectId;
@ApiModelProperty(value = "父类文件夹id ,创建同级不传",required = false)
private Long parentId;
@ApiModelProperty(value = "文件夹名称",required = true)
@NotBlank(message = "文件夹名称不能为空!")
private String fileName;
@ApiModelProperty(value = "文件来源:,1 API制做,2 组织创建",required = true)
@NotBlank(message = "文件来源不能为空")
private String fileSource;
@ApiModelProperty(value = "创建用户",required = false)
private String createUser;
}
package com.jz.dm.models.req.make;
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: MakeBigDataApiReq
* @DATE: 2020-12-26/13:08
* @DAY_NAME_SHORT: 周六
* @Description:
**/
@Data
@ApiModel("Api制作大数据查询/标签查询请求体")
public class MakeBigDataApiReq implements Serializable {
@ApiModelProperty(value = "id--更新时id不能为空",required = false)
private Long id;
/* @ApiModelProperty(value = "数据类型:api类型:1 实时接入 2 数据银行制作API, 3 数据银行制作数据包 6标签查询 8 查询hive数据源 9自定义",required = true)
@NotNull(message = "apiType不能为空")
private String apiType;*/
@ApiModelProperty(value = "apiKey",required = false)
@NotNull(message = "apiKey不能为空")
public String apiKey;
//@ApiModelProperty(value = "是否分页",required = false)
//public Boolean page;
@ApiModelProperty(value = "数据源Id",required = true)
@NotNull(message = "数据源Id不能为空")
private String esDataSource;
@ApiModelProperty(value = "源库名称",required = true)
@NotNull(message = "源库名称不能为空")
private String esDataBase;
@ApiModelProperty(value = "源表名称",required = true)
@NotNull(message = "源表名称不能为空")
private String esTable;
@ApiModelProperty(value = "处理类型",required = true)
@NotNull(message = "处理类型不能为空")
private String handleType;
@ApiModelProperty(value = "请求参数",required = true)
@NotNull(message = "请求参数不能为空")
private String requestParam;
@ApiModelProperty(value = "返回参数",required = true)
@NotNull(message = "返回参数不能为空")
private String responseParam;
@ApiModelProperty(value = "段列表",required = true)
@NotNull(message = "字段列表不能为空")
private String tableFields;
@ApiModelProperty(value = "创建用户",required = false)
public String createUser;
//@ApiModelProperty(value = "项目id",required = true)
//@NotNull(message="项目id不能为空")
//public Long projectId;
//@ApiModelProperty(value = "父类文件id,一级文件夹传入0",required = false)
//public Long parentId;
//
//@ApiModelProperty(value = "文件id",required = false)
//public Long fileId;
}
......@@ -20,14 +20,10 @@ import java.io.Serializable;
@ApiModel("组织管理详情请求体")
public class OrganizationManageAddReq implements Serializable {
@ApiModelProperty(value = "组织类型:INT 内部组织 OUT 外部组织",required = true)
/*@ApiModelProperty(value = "组织类型:INT 内部组织 OUT 外部组织",required = true)
@NotNull(message = "组织类型不能为空!")
private String orgType;
@ApiModelProperty(value = "组织名称",required = true)
@NotNull(message = "组织名称不能为空")
private String orgName;
@ApiModelProperty(value = "组织描述",required = false)
private String orgDesc;
......@@ -35,21 +31,31 @@ public class OrganizationManageAddReq implements Serializable {
private String orgCnName;
@ApiModelProperty(value = "组织邮箱",required = false)
private String orgMail;
private String orgMail;*/
@ApiModelProperty(value = "组织名称",required = true)
@NotNull(message = "组织名称不能为空")
private String orgName;
@ApiModelProperty(value = "组织电话",required = false)
@ApiModelProperty(value = "组织电话",required = true)
@NotNull(message="组织电话不能为空")
private String orgPhone;
@ApiModelProperty(value = "组织联系人",required = false)
@ApiModelProperty(value = "组织联系人",required = true)
@NotNull(message="组织联系人不能为空")
private String linkman;
@ApiModelProperty(value = "文件夹Id",required = true)
@NotNull(message="文件夹Id不能为空")
private Long orgFolderId;
@ApiModelProperty(value = "备注",required = false)
private String remark;
@ApiModelProperty(value = "创建用户",required = false)
private String createUser;
@ApiModelProperty(value = "创建用户",required = false)
@ApiModelProperty(value = "更新用户",required = false)
private String updateUser;
@ApiModelProperty(value = "id ----更新时必传",required = false)
......
......@@ -29,4 +29,9 @@ public class OrganizationManageListQueryReq extends BasePageBean implements Seri
@ApiModelProperty(value = "组织联系人")
private String linkman;
@ApiModelProperty(value = "组织文件夹")
private Long fileId;
}
package com.jz.dm.models.req.make;
package com.jz.dm.models.req.producer;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
......@@ -20,33 +20,39 @@ import java.io.Serializable;
@ApiModel(value = "api基本信息")
public class ApiInterfaceReq implements Serializable {
@ApiModelProperty(value = "接口描述",required = false)
public String apiDesc;
@ApiModelProperty(value = "传输方式:http https",required = true)
@NotNull(message = "传输方式不能为空")
public String transMode;
public String apiProtocl;
@ApiModelProperty(value = "加密方式0 无,1:MD5 2:RSA",required = true)
@NotNull(message = "加密方式不能为空")
public String signType;
@ApiModelProperty(value = "接入类型:对应字典表key",required = true)
@NotNull(message = "接入类型不能为空")
public String joinType;
@ApiModelProperty(value = "Api类型:对应字典表key",required = true)
@NotNull(message = "Api类型不能为空")
public String apiType;
@ApiModelProperty(value = "目标地址",required = true)
@NotNull(message="目标地址不能为空")
@ApiModelProperty(value = "apiKey",required = true)
@NotNull(message = "apiKey不能为空")
public String apiKey;
@ApiModelProperty(value = "目标地址",required = false)
public String targetUrl;
@ApiModelProperty(value = "请求方式:GET POST",required = true)
@NotNull(message="请求方式不能为空")
public String reqType;
@ApiModelProperty(value = "超时时间",required = true)
@NotNull(message="超时时间不能为空")
public String timeout;
@ApiModelProperty(value = "限流类型:DAY 按天,MONTH 按月, YEAR 按年",required = true)
@NotNull(message = "限流类型不能为空")
public String reqType;
public String limitType;
@ApiModelProperty(value = "API名称",required = false)
public String apiName;
@ApiModelProperty(value = "限制次数",required = false)
public Long reqFrequency;
......@@ -54,16 +60,40 @@ public class ApiInterfaceReq implements Serializable {
@ApiModelProperty(value = "api描述",required = false)
public String apiFunction;
@ApiModelProperty(value = "父类文件id,一级文件夹传入0",required = false)
public Long parentId;
@ApiModelProperty(value = "文件id",required = false)
@ApiModelProperty(value = "文件夹Id",required = true)
@NotNull(message="文件夹Id不能为空")
public Long fileId;
@ApiModelProperty(value = "项目id",required = true)
@NotNull(message="项目id不能为空")
@ApiModelProperty(value = "项目编号",required = true)
@NotNull(message="项目编号不能为空")
public Long projectId;
@ApiModelProperty(value = "输出类型:JSON 文件流形式",required = false)
public String outType;
@ApiModelProperty(value = "最大行数:",required = false)
public Long maxRow;
@ApiModelProperty(value = "每页返回数据数:",required = false)
public Long pageRow;
@ApiModelProperty(value = "请求参数:",required = false)
public String requestParam;
@ApiModelProperty(value = "响应参数:",required = false)
public String responseParam;
@ApiModelProperty(value = "参数字段:",required = false)
public String tableFields;
@ApiModelProperty(value = "数据源id",required = false)
public String esDataSource;
@ApiModelProperty(value = "数据库名称",required = false)
public String esDataBase;
@ApiModelProperty(value = "数据表名称",required = false)
public String esTable;
@ApiModelProperty(value = "状态",required = false)
public String status;
......@@ -72,10 +102,12 @@ public class ApiInterfaceReq implements Serializable {
public Long id;
@ApiModelProperty(value = "创建用户",hidden = true)
public String createUser;
@ApiModelProperty(value = "创建用户",hidden = true)
public String updateUser;
@ApiModelProperty(value = "api类型:1.数据银行制作大数据表 " +
/* @ApiModelProperty(value = "api类型:1.数据银行制作大数据表 " +
"2 数据银行制作数据包,3,数据银行制作自定义API " +
"4 API实时接入 6 标签查询 9自定义",hidden = true)
public String apiType;
public String apiType;*/
}
package com.jz.dm.models.req.producer;
import io.swagger.annotations.ApiModel;
import lombok.Data;
import java.io.Serializable;
/**
* @author ZC
* @PACKAGE_NAME: com.jz.dm.models.req
* @PROJECT_NAME: jz-dm-parent
* @NAME: MakeBigDataApiReq
* @DATE: 2020-12-26/13:08
* @DAY_NAME_SHORT: 周六
* @Description:
**/
@Data
@ApiModel("Api制作大数据查询/标签查询请求体")
public class MakeBigDataApiReq implements Serializable {
// @ApiModelProperty(value = "id--更新时id不能为空",required = false)
// private Long id;
//
///* @ApiModelProperty(value = "数据类型:api类型:1 实时接入 2 数据银行制作API, 3 数据银行制作数据包 6标签查询 8 查询hive数据源 9自定义",required = true)
// @NotNull(message = "apiType不能为空")
// private String apiType;*/
//
// @ApiModelProperty(value = "apiKey",required = false)
// @NotNull(message = "apiKey不能为空")
// public String apiKey;
//
// //@ApiModelProperty(value = "是否分页",required = false)
// //public Boolean page;
//
// @ApiModelProperty(value = "数据源Id",required = true)
// @NotNull(message = "数据源Id不能为空")
// private String esDataSource;
//
// @ApiModelProperty(value = "源库名称",required = true)
// @NotNull(message = "源库名称不能为空")
// private String esDataBase;
//
// @ApiModelProperty(value = "源表名称",required = true)
// @NotNull(message = "源表名称不能为空")
// private String esTable;
//
// @ApiModelProperty(value = "处理类型",required = true)
// @NotNull(message = "处理类型不能为空")
// private String handleType;
//
//
// @ApiModelProperty(value = "请求参数",required = true)
// @NotNull(message = "请求参数不能为空")
// private String requestParam;
//
// @ApiModelProperty(value = "返回参数",required = true)
// @NotNull(message = "返回参数不能为空")
// private String responseParam;
//
// @ApiModelProperty(value = "段列表",required = true)
// @NotNull(message = "字段列表不能为空")
// private String tableFields;
//
// @ApiModelProperty(value = "创建用户",required = false)
// public String createUser;
//
// //@ApiModelProperty(value = "项目id",required = true)
// //@NotNull(message="项目id不能为空")
// //public Long projectId;
//
// //@ApiModelProperty(value = "父类文件id,一级文件夹传入0",required = false)
// //public Long parentId;
// //
// //@ApiModelProperty(value = "文件id",required = false)
// //public Long fileId;
}
package com.jz.dm.models.req.make;
package com.jz.dm.models.req.producer;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
......@@ -40,9 +40,13 @@ public class MakeDataBankApiReq implements Serializable {
@NotNull(message = "输出类型不能为空")
public String outputType;
@ApiModelProperty(value = "是否分页:",required = true)
@ApiModelProperty(value = "请求方式:GET POST",required = true)
@NotNull(message = "请求方式不能为空")
public String reqMethod;
/*@ApiModelProperty(value = "是否分页:",required = true)
@NotNull(message = "是否分页不能为空")
public Boolean page;
public Boolean page;*/
@ApiModelProperty(value = "限流类型:DAY 按天,MONTH 按月",required = true)
@NotNull(message = "限流类型不能为空")
......@@ -52,9 +56,15 @@ public class MakeDataBankApiReq implements Serializable {
@NotNull(message = "目标地址不能为空")
public String targetUrl;
@ApiModelProperty(value = "文件id",required = true)
@NotNull(message = "文件id不能为空")
public Long fileId;
@ApiModelProperty(value = "当前页",required = true)
public Integer pageNum;
@ApiModelProperty(value = "当前页显示条数",required = true)
public Integer pageSize;
//@ApiModelProperty(value = "文件id",required = true)
//@NotNull(message = "文件id不能为空")
//public Long fileId;
@ApiModelProperty(value = "签名",required = true)
@NotNull(message = "签名不能为空")
......@@ -69,7 +79,8 @@ public class MakeDataBankApiReq implements Serializable {
@ApiModelProperty(value = "接口描述",required = false)
public String apiDesc;
@ApiModelProperty(value = "数据包下载路径",required = false)
public String fileLocation;
@ApiModelProperty(value = "超时时间",required = false)
public String timeout;
......
package com.jz.dm.models.req.make;
package com.jz.dm.models.req.producer;
import io.swagger.annotations.ApiModel;
import lombok.Data;
......
package com.jz.dm.models.req.producer;
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.producer
* @PROJECT_NAME: jz-dm-parent
* @NAME: ServiceIssueReq
* @DATE: 2021-1-28/11:00
* @DAY_NAME_SHORT: 周四
* @Description:
**/
@Data
@ApiModel(value = "服务发布请求体")
public class ServiceIssueReq extends BasePageBean implements Serializable {
@ApiModelProperty(value = "文件夹id",required = false)
private Long fileId;
@ApiModelProperty(value = "api名称",required = false)
private String apiName;
@ApiModelProperty(value = "apiId",required = false)
private String apiId;
}
package com.jz.dm.models.req.make;
package com.jz.dm.models.req.producer;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
......
......@@ -4,6 +4,7 @@ import com.baomidou.mybatisplus.core.metadata.IPage;
import com.jz.common.utils.Result;
import com.jz.dm.models.domian.ApiAuth;
import com.jz.dm.models.domian.ApiInterface;
import com.jz.dm.models.domian.ApiInterfaceCustom;
import com.jz.dm.models.req.api.ApiInterfaceDetailReq;
import com.jz.dm.models.req.api.ApiInterfaceInfoListReq;
......@@ -41,11 +42,19 @@ public interface ApiInterfaceService {
ApiInterface getReqTargetInfo(String apiKey);
/**
* 查询API列表信息
* API---(已调用列表)列表查询
* @param req
* @return
*/
IPage<ApiInterface > listApiInterface(ApiInterfaceInfoListReq req);
IPage<ApiInterface > listCallApiInterface(ApiInterfaceInfoListReq req);
/**
* API---(未调用列表)列表查询
* @param req
* @return
*/
IPage<ApiInterface > listUnCallApiInterface(ApiInterfaceInfoListReq req);
/**
* 查询API详情
......@@ -77,12 +86,24 @@ public interface ApiInterfaceService {
Result dmpDeleteAuth(String type,String apiKey);
/**
* api测试接口
* @param apiKey
* 获取api自定义信息
* @param apiInterfaceId
* @return
*/
Result apiTestInterface(String apiKey);
ApiInterfaceCustom getApiCustomInfo(Long apiInterfaceId);
/**
* 更新数据银行调用状态
* @param apiKey
* @return
*/
Result updateApiSendStatus(String apiKey);
/**
* 获取已发送到数据API列表
* @param pageNum
* @param pageSize
* @return
*/
Result getSendDataBankList(String pageNum, String pageSize);
}
......@@ -84,4 +84,11 @@ public interface AuthService {
* @return
*/
Result getAuthNameList(String key);
/**
* 获取服务授权列表
* @param req
* @return
*/
Result getServiceAuthList(ServiceAuthReq req);
}
......@@ -38,12 +38,6 @@ public interface OrganizationManageService {
*/
Result add(OrganizationManageAddReq req);
/**
* 更新组织信息
* @param req
* @return
*/
//Result update(OrganizationManageUpdateReq req);
/**
* 根据id注销组织
......
package com.jz.dm.service;
import com.jz.common.utils.Result;
import com.jz.dm.models.req.make.*;
import com.jz.dm.models.req.folder.CreateFolderReq;
import com.jz.dm.models.req.producer.ApiInterfaceReq;
import com.jz.dm.models.req.producer.ServiceIssueReq;
/**
* @author ZC
......@@ -13,40 +15,29 @@ import com.jz.dm.models.req.make.*;
* @Description:
**/
public interface ProducerService {
/**
* 制作自定义APi
* @param req
* @return
*/
Result addCustomApi(ApiInterfaceReq req);
/**
* Api制作(实时接入)
* @param req
* @return
*/
Result addRealCustomApi(MakeRealCustomApiReq req);
// Result addRealCustomApi(MakeRealCustomApiReq req);
/**
* Api制作(大数据查询/标签查询)
* @param req
* @return
*/
Result addBigDataMakeApi(MakeBigDataApiReq req);
/**
* 获取数据源配置
* @param req
* @return
*/
Result getSourceConfig(SourceConfigReq req);
// Result getSourceConfig(SourceConfigReq req);
/**
* 获取数据库列表
* @param id
* @return
*/
Result getSourceWarehouseList(Long id);
// Result getSourceWarehouseList(Long id);
/**
* 获取某个索引下的type
......@@ -54,7 +45,7 @@ public interface ProducerService {
* @param id
* @return
*/
Result getIndicesTypes(String indices, Long id);
// Result getIndicesTypes(String indices, Long id);
/**
* 获取某个索引 type的fields
......@@ -63,23 +54,28 @@ public interface ProducerService {
* @param id
* @return
*/
Result getIndicesTypesFields(String indices, String type, Long id);
// Result getIndicesTypesFields(String indices, String type, Long id);
/**
* 数据银行制作API/数据包
* @param req
* @return
*/
// Result addDataBankApiInfo(MakeDataBankApiReq req);
/**
* 保存修改的api信息
* @param req
* @return
*/
Result saveUpdateAPiInfo(ApiInterfaceReq req);
//Result saveUpdateAPiInfo(ApiInterfaceReq req);
/**
* 数据银行制作API/数据包
* Api制作(数据查询/标签查询)
* @param req
* @return
*/
Result addDataBankApiInfo(MakeDataBankApiReq req);
Result addBigDataMakeApi(ApiInterfaceReq req);
/**
* 保存 API基本信息
* @param req
......@@ -96,15 +92,36 @@ public interface ProducerService {
/**
* 创建文件夹
* @param projectId
* @param parentId
* @param currentUser
* @param req
* @return
*/
Result createProjectFolder(CreateFolderReq req);
/**
* 获取生成后的APIId
* @return
*/
Result createProjectFolder(Long projectId, Long parentId,String currentUser);
Result getCustomApiId();
/**
* 获取服务发布列表
* @param req
* @return
*/
Result getServiceIssueList(ServiceIssueReq req);
/**
* 服务发布/取消操作
* @param id
* @param optStatus
* @return
*/
Result optionApiIssueStatus(Long id, Boolean optStatus);
//Result saveObjOnRedis();
//Result getObjOnRedis();
Result saveObjOnRedis();
Result getObjOnRedis();
}
......@@ -11,15 +11,16 @@ import com.jz.dm.common.enums.GeneralStatusTypeEnum;
import com.jz.dm.common.enums.apiInterface.ApiStatusEnum;
import com.jz.dm.common.enums.auth.AuthModeEnum;
import com.jz.dm.mapper.ApiAuthMapper;
import com.jz.dm.mapper.ApiInterfaceCustomMapper;
import com.jz.dm.mapper.ApiInterfaceMapper;
import com.jz.dm.models.domian.ApiAuth;
import com.jz.dm.models.domian.ApiInterface;
import com.jz.dm.models.domian.ApiInterfaceCustom;
import com.jz.dm.models.dto.ApiCallDataDto;
import com.jz.dm.models.req.api.ApiInterfaceDetailReq;
import com.jz.dm.models.req.api.ApiInterfaceInfoListReq;
import com.jz.dm.service.ApiInterfaceService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
......@@ -49,26 +50,25 @@ public class ApiInterfaceServiceImpl implements ApiInterfaceService {
@Resource
private ApiInterfaceMapper apiInterfaceMapper;
@Resource
private ApiInterfaceCustomMapper apiInterfaceCustomMapper;
@Resource
private ApiAuthMapper apiAuthMapper;
@Autowired
private HttpsUtils httpsUtils;
/**
* 获取API列表信息
* API---(调用列表)列表查询
*
* @param req
* @return
*/
@Override
public IPage<ApiInterface > listApiInterface(ApiInterfaceInfoListReq req) {
public IPage<ApiInterface > listCallApiInterface(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());
}*/
if (StringUtils.isNotBlank(req.getApiKey())){
query.eq("ai.api_key",req.getApiKey());
}
query.eq("ai.is_deleted", 0);
query.orderByDesc("ai.create_date");
query.groupBy("ai.create_date");
......@@ -76,6 +76,24 @@ public class ApiInterfaceServiceImpl implements ApiInterfaceService {
}
/**
* API---(未调用列表)列表查询
* @param req
* @return
*/
@Override
public IPage<ApiInterface > listUnCallApiInterface(ApiInterfaceInfoListReq req) {
IPage<ApiInterface > page = new Page<>(req.getPageNum(), req.getPageSize());
QueryWrapper<ApiInterface > query = new QueryWrapper<>();
if (StringUtils.isNotBlank(req.getApiKey())){
query.eq("ai.api_key",req.getApiKey());
}
query.isNull("ar.api_key");
query.eq("ai.is_deleted", 0);
query.orderByDesc("ai.create_date");
return apiInterfaceMapper.listCallApiInterfaceInfo(page, query);
}
/**
* 获取API详情信息
*
......@@ -206,28 +224,20 @@ public class ApiInterfaceServiceImpl implements ApiInterfaceService {
return authCall + authDateCall;
}
/**
* api测试接口
*
* @param apiKey
* 获取api自定义信息
* @param apiInterfaceId
* @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);
public ApiInterfaceCustom getApiCustomInfo(Long apiInterfaceId) {
QueryWrapper<ApiInterfaceCustom> queryWra = new QueryWrapper<>();
queryWra.eq("api_interface_id",apiInterfaceId);
queryWra.eq("is_deleted",0);
return apiInterfaceCustomMapper.selectOne(queryWra) ;
}
/**
* 获取用户授权信息
*
......@@ -275,4 +285,39 @@ public class ApiInterfaceServiceImpl implements ApiInterfaceService {
query.eq("is_deleted", 0);
return apiInterfaceMapper.selectOne(query);
}
/**
* 更新APi是否发送到数据银行状态
* @param apiKey
* @return
*/
@Override
public Result updateApiSendStatus(String apiKey) {
QueryWrapper<ApiInterface> queryWra = new QueryWrapper<>();
queryWra.eq("api_key",apiKey);
queryWra.eq("is_deleted",0);
ApiInterface apiInterface = apiInterfaceMapper.selectOne(queryWra);
if (null == apiInterface){
return Result.of_error(ResultMsg.DATA_NOT_FOUND);
}
UpdateWrapper<ApiInterface> updateWra = new UpdateWrapper<>();
updateWra.set("is_send_bank",0);
if (apiInterfaceMapper.update(null,updateWra) > 0){
return Result.of_success(ResultMsg.UPDATE_SUCCESS);
}
return Result.of_error(ResultMsg.UPDATE_FAIL);
}
@Override
public Result getSendDataBankList(String pageNum, String pageSize) {
Integer pageN = Integer.valueOf(pageNum);
Integer pageS = Integer.valueOf(pageSize);
IPage<ApiInterface> page = new Page<>(pageN, pageS);
QueryWrapper<ApiInterface > query = new QueryWrapper<>();
query.eq("is_send_bank",1);
query.eq("status",ApiStatusEnum.ISSUE.name());
query.eq("is_deleted",0);
return Result.of_success(apiInterfaceMapper.selectPage(page, query));
}
}
......@@ -5,13 +5,11 @@ 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.enums.auth.AuthTypeEnum;
import com.jz.common.utils.Result;
import com.jz.dm.common.constant.Constants;
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.org.OrgStatusEnum;
import com.jz.dm.common.util.DateUtil;
import com.jz.dm.common.util.RandomUtil;
import com.jz.dm.mapper.ApiAuthMapper;
import com.jz.dm.mapper.ApiInterfaceMapper;
......@@ -19,6 +17,7 @@ import com.jz.dm.mapper.ApiOrgMapper;
import com.jz.dm.models.domian.ApiAuth;
import com.jz.dm.models.domian.ApiInterface;
import com.jz.dm.models.domian.ApiOrg;
import com.jz.dm.models.dto.ApiServiceApplyDto;
import com.jz.dm.models.dto.AuthInfoDto;
import com.jz.dm.models.req.auth.*;
import com.jz.dm.models.resp.AuthUserResponse;
......@@ -34,6 +33,7 @@ import javax.annotation.Resource;
import java.util.Date;
import static com.jz.dm.common.enums.auth.AuthModeEnum.fromTypeModeName;
import static com.jz.dm.common.enums.auth.AuthTypeEnum.fromAuthTypeName;
/**
* @author ZC
......@@ -89,6 +89,29 @@ public class AuthServiceImpl implements AuthService {
return Result.of_success(apiAuthMapper.selectAuthDetail(req));
}
/**
* 获取服务授权列表
* @param req
* @return
*/
@Override
public Result getServiceAuthList(ServiceAuthReq req) {
IPage<ApiServiceApplyDto> page = new Page<>(req.getPageNum(), req.getPageSize());
QueryWrapper<ApiServiceApplyDto> query = new QueryWrapper<>();
if (null != req.getFolderId()){
query.eq("ai.file_id",req.getFolderId());
}
if (StringUtils.isNotBlank(req.getApiName())){
query.eq("ai.api_name",req.getApiName());
}
if (StringUtils.isNotBlank(req.getApiId())){
query.eq("ai.api_key",req.getApiId());
}
query.eq("ai.is_deleted",0);
query.orderByDesc("ai.create_time");
return Result.of_success(apiInterfaceMapper.listApiAuthService(page, query));
}
/**
* 添加dmp认证信息
*
......@@ -102,20 +125,23 @@ public class AuthServiceImpl implements AuthService {
if (null == apiInterface) {
return Result.of_error("api授权信息不存在!");
}
if (ApiStatusEnum.DRAFT.name().equals(apiInterface.getStatus())){
return Result.of_error("api未发布,无法授权");
}
if (ApiStatusEnum.EXPIRY.name().equals(apiInterface.getStatus())) {
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)) {
if (null == apiOrg || !apiOrg.getStatus()) {
return Result.of_error("组织信息不存在!");
}
//授权验证
//if (StringUtils.isNotBlank(req.getAuthType())){
// if (null == fromTypeName(req.getAuthType())){
// return Result.of_error("授权类型不存在!");
// }
//}
if (StringUtils.isNotBlank(req.getAuthType())){
if (null == fromAuthTypeName(req.getAuthType())){
return Result.of_error("授权类型不存在!");
}
}
//验证授权方式
if (StringUtils.isNotBlank(req.getAuthMode())) {
if (null == fromTypeModeName(req.getAuthMode())) {
......@@ -130,7 +156,7 @@ public class AuthServiceImpl implements AuthService {
if (StringUtils.isBlank(apiOrg.getOrgCode())) {
return Result.of_error("内部授权组织编码不能为空!!");
}
return saveAuthInfo(apiInterface, apiOrg, req, Constants.AUTH_INT);
return saveAuthInfo(apiInterface, apiOrg, req);
}
/**
......@@ -149,16 +175,19 @@ public class AuthServiceImpl implements AuthService {
if (ApiStatusEnum.SOLDOUT.name().equals(apiInterface.getStatus())) {
return Result.of_error("api已下架,无法授权");
}
if (ApiStatusEnum.DRAFT.name().equals(apiInterface.getStatus())){
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)) {
if (null == apiOrg || !apiOrg.getStatus()) {
return Result.of_error("组织信息不存在!");
}
//授权验证
//if (StringUtils.isNotBlank(req.getAuthType())){
// if (null == fromTypeName(req.getAuthType())){
// return Result.of_error("授权类型不存在!");
// }
//}
if (StringUtils.isNotBlank(req.getAuthType())){
if (null == fromAuthTypeName(req.getAuthType())){
return Result.of_error("授权类型不存在!");
}
}
//验证授权方式
if (StringUtils.isNotBlank(req.getAuthMode())) {
if (null == fromTypeModeName(req.getAuthMode())) {
......@@ -181,7 +210,7 @@ public class AuthServiceImpl implements AuthService {
if (StringUtils.isBlank(req.getUserId())) {
return Result.of_error("外部授权用户Id不能为空");
}
return saveAuthInfo(apiInterface, apiOrg, req, Constants.AUTH_OUT);
return saveAuthInfo(apiInterface, apiOrg, req);
}
/**
......@@ -190,11 +219,10 @@ public class AuthServiceImpl implements AuthService {
* @param apiInterface
* @param apiOrg
* @param req
* @param orgType
* @return
*/
private Result saveAuthInfo(ApiInterface apiInterface, ApiOrg apiOrg,
AuthUserApiReq req, String orgType) {
AuthUserApiReq req) {
AuthUserResponse response = new AuthUserResponse();
ApiAuth apiAuth = new ApiAuth();
BeanUtils.copyProperties(req, apiAuth);
......@@ -202,21 +230,11 @@ public class AuthServiceImpl implements AuthService {
apiAuth.setApiOrgId(apiOrg.getId());
apiAuth.setReqType(apiInterface.getReqType());
apiAuth.setReqFrequency(apiInterface.getReqFrequency());
if (Constants.AUTH_INT.equals(orgType)) {//内部授权
apiAuth.setAuthType(AuthTypeEnum.DMP_AUTH.name());
} else {
apiAuth.setAuthType(AuthTypeEnum.DATA_BANK_AUTH.name());
if (!AuthModeEnum.RECORD_TIME_MODE.name().equals(req.getAuthMode())){
apiAuth.setValidExprDate(DateUtil.getAssignYearDate(99));//过期时间
}
//商城只有外部授权
String authCode = "";
//内部组织
if (StringUtils.isNotBlank(orgType) && Constants.AUTH_INT.equalsIgnoreCase(orgType)) {
authCode = getAuthCode(apiOrg.getOrgCode(), "", Constants.AUTH_INT);
//外部组织
} else if (StringUtils.isNotBlank(orgType)
&& Constants.AUTH_OUT.equalsIgnoreCase(orgType)) {
authCode = getAuthCode("", req.getUserId(), Constants.AUTH_OUT);
}
String authCode = getAuthCode(apiOrg.getOrgCode(), "","");
//生成盐值
String salt = RandomUtil.getStringRandom(8);
apiAuth.setAuthCode(authCode);//授权码
......
......@@ -6,10 +6,9 @@ import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jz.common.constant.ResultMsg;
import com.jz.common.utils.Result;
import com.jz.dm.common.constant.Constants;
import com.jz.dm.common.enums.org.OrgStatusEnum;
import com.jz.dm.common.util.RandomUtil;
import com.jz.dm.mapper.ApiInterfaceFileMapper;
import com.jz.dm.mapper.ApiOrgMapper;
import com.jz.dm.models.domian.ApiInterfaceFile;
import com.jz.dm.models.domian.ApiOrg;
import com.jz.dm.models.req.organizationManage.OrganizationManageAddReq;
import com.jz.dm.models.req.organizationManage.OrganizationManageDetailQueryReq;
......@@ -23,8 +22,6 @@ import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.Date;
import static com.jz.dm.common.enums.org.OrgTypeEnum.fromOrgTypeEnumName;
/**
* @author ZC
* @PACKAGE_NAME: com.jz.dm.service.impl
......@@ -40,6 +37,8 @@ public class OrganizationManageImpl implements OrganizationManageService {
@Resource
private ApiOrgMapper apiOrgMapper;
@Resource
private ApiInterfaceFileMapper apiInterfaceFileMapper;
/**
* 组织列表信息查询
......@@ -52,14 +51,17 @@ public class OrganizationManageImpl implements OrganizationManageService {
IPage<ApiOrg> page = new Page<>(req.getPageNum(), req.getPageSize());
QueryWrapper<ApiOrg> query = new QueryWrapper<>();
if (StringUtils.isNotBlank(req.getOrgName())){
query.like("org_name",req.getOrgName());
if (StringUtils.isNotBlank(req.getOrgName())) {
query.like("org_name", req.getOrgName());
}
if (StringUtils.isNotBlank(req.getLinkman())){
query.like("linkman",req.getLinkman());
if (StringUtils.isNotBlank(req.getLinkman())) {
query.like("linkman", req.getLinkman());
}
if (StringUtils.isNotBlank(req.getOrgCode())){
query.eq("org_code",req.getOrgCode());
if (StringUtils.isNotBlank(req.getOrgCode())) {
query.eq("org_code", req.getOrgCode());
}
if (null != req.getFileId()){
query.eq("org_folder_id",req.getFileId());
}
query.eq("is_deleted", 0);
query.orderByDesc("create_date");
......@@ -89,18 +91,34 @@ public class OrganizationManageImpl implements OrganizationManageService {
*/
@Override
public Result add(OrganizationManageAddReq req) {
ApiOrg apiOrg = new ApiOrg();
BeanUtils.copyProperties(req, apiOrg);
if (null != req.getId()){//更新
//更新组织
if (null != req.getId()) {
ApiOrg org = apiOrgMapper.selectById(req.getId());
if (null == org){
if (null == org) {
return Result.of_error(ResultMsg.DATA_NOT_EXIST);
}
if (StringUtils.isNotBlank(req.getOrgName()) && !req.getOrgName().equals(org.getOrgName())) {
if (checkOrgName(req.getOrgName())) {
return Result.of_error("组织名称已存在!");
}
}
if (null != req.getOrgFolderId() && !req.getOrgFolderId().equals(org.getOrgFolderId())) {
if (checkOrgFolderIsExist(req.getOrgFolderId())) {
return Result.of_error("目标文件夹不存在!");
}
}
org.setUpdateDate(new Date());
if ( apiOrgMapper.updateById(apiOrg) > 0){
org.setOrgName(req.getOrgName());
org.setLinkman(req.getLinkman());
org.setOrgPhone(req.getOrgPhone());
org.setOrgFolderId(req.getOrgFolderId());
if (apiOrgMapper.updateById(org) > 0) {
return Result.of_success(ResultMsg.UPDATE_SUCCESS);
}
}else {//添加
//添加组织
} else {
ApiOrg apiOrg = new ApiOrg();
BeanUtils.copyProperties(req, apiOrg);
Result result = addOrg(req, apiOrg);
if (result != null) return result;
}
......@@ -108,88 +126,89 @@ public class OrganizationManageImpl implements OrganizationManageService {
}
/**
* 添加组织
* @param req
* @param apiOrg
* 校验组织名称是否存在
*
* @param newName
* @return
*/
private Result addOrg(OrganizationManageAddReq req, ApiOrg apiOrg) {
String coding = "";
if (StringUtils.isNotBlank(req.getOrgName())) {
ApiOrg orgNameInfo = getOrgNameInfo(req.getOrgName());
if (null != orgNameInfo) {
return Result.of_error("组织名称已存在!");
}
}
if (StringUtils.isNotBlank(req.getOrgType())) {
if (null == fromOrgTypeEnumName(req.getOrgType())){
return Result.of_error("组织类型不存在!");
}
}
if (StringUtils.isNotBlank(req.getOrgType()) //内部组织
&& Constants.AUTH_INT.equals(req.getOrgType())) {
coding = generateCode(req.getOrgName(), Constants.AUTH_INT);
} else {
coding = generateCode(req.getOrgName(), Constants.AUTH_OUT);
private boolean checkOrgName(String newName) {
if (StringUtils.isBlank(newName)) {
return true;
}
if (StringUtils.isBlank(coding)) {
return Result.of_error("生成组织编码异常!");
}
apiOrg.setOrgCode(coding);//组织编码
if (apiOrgMapper.insert(apiOrg) > 0) {
return Result.of_success(ResultMsg.INSERT_SUCCESS);
QueryWrapper<ApiOrg> query = new QueryWrapper<>();
query.eq("org_name", newName);
query.eq("status", 1);
query.eq("is_deleted", 0);
ApiOrg apiOrg = apiOrgMapper.selectOne(query);
if (null != apiOrg) {
return true;
}
return null;
return false;
}
/**
* 获取组织编码(去重)
* 校验组织文件夹是否存在
*
* @param orgName 组织名称
* @param type 生成类型
* @param folderId
* @return
*/
private String generateCode(String orgName, String type) {
String coding = "";
coding = RandomUtil.generateOrgCoding(orgName, type);
QueryWrapper<ApiOrg> query = new QueryWrapper<>();
query.eq("org_code", coding);
ApiOrg org = apiOrgMapper.selectOne(query);
if (null != org) {
coding = RandomUtil.generateOrgCoding(orgName, type);
private boolean checkOrgFolderIsExist(Long folderId) {
if (null == folderId) {
return true;
}
return coding;
QueryWrapper<ApiInterfaceFile> query = new QueryWrapper<>();
query.eq("id", folderId);
query.eq("file_source", 2);
query.eq("is_deleted", 0);
ApiInterfaceFile apiInterfaceFile = apiInterfaceFileMapper.selectOne(query);
if (null != apiInterfaceFile) {
return true;
}
return false;
}
/**
* 更新组织
* 添加组织
*
* @param req
* @param apiOrg
* @return
*/
/* @Override
public Result update(OrganizationManageUpdateReq req) {
ApiOrg apiOrg = apiOrgMapper.selectById(req.getId());
if (null == apiOrg) {
return Result.of_error("组织信息不存在!");
private Result addOrg(OrganizationManageAddReq req, ApiOrg apiOrg) {
if (StringUtils.isNotBlank(req.getOrgName())) {
if (checkOrgName(req.getOrgName())) {
return Result.of_error("组织名称已存在!");
}
if (StringUtils.isNotBlank(req.getStatus())) {
if (null == fromTypeName(req.getStatus())) {
return Result.of_error("更新组织状态不存在!");
}
//生成组织编码
String orgCode = generateCode(6);
if (StringUtils.isBlank(orgCode)) {
return Result.of_error("生成组织编码异常!");
}
//原状态为注销状态不可复原
if (OrgStatusEnum.CANCEL.equals(apiOrg.getStatus())){
return Result.of_error("注销状态不可修改");
apiOrg.setOrgCode(orgCode);//组织编码
if (apiOrgMapper.insert(apiOrg) > 0) {
return Result.of_success(ResultMsg.INSERT_SUCCESS);
}
ApiOrg apiOrgUpdate = new ApiOrg();
BeanUtils.copyProperties(req, apiOrgUpdate);
apiOrgUpdate.setUpdateDate(new Date());
if (apiOrgMapper.updateById(apiOrgUpdate) > 0) {
return Result.of_success(ResultMsg.UPDATE_SUCCESS);
return null;
}
/**
* 生成组织编码
* @param num 生成位数
* @return
*/
private String generateCode(int num) {
QueryWrapper<ApiOrg> queryWra = new QueryWrapper<>();
queryWra.select("org_code");
queryWra.last("where id IN (SELECT MAX(id) FROM t_api_org)");
ApiOrg apiOrg = apiOrgMapper.selectOne(queryWra);
String orgCode = null;
if (null != apiOrg) {
Integer maxOrgCode = Integer.valueOf(apiOrg.getOrgCode());
orgCode = String.format("%0" + num + "d",maxOrgCode+1);
}
return orgCode;
}
return Result.of_success(ResultMsg.UPDATE_FAIL);
}*/
/**
* 注销组织
......@@ -205,7 +224,7 @@ public class OrganizationManageImpl implements OrganizationManageService {
}
UpdateWrapper<ApiOrg> delete = new UpdateWrapper<>();
delete.set("is_deleted", 1);
delete.set("status",0);
delete.set("status", 0);
delete.eq("id", id);
if (apiOrgMapper.update(null, delete) > 0) {
return Result.of_success(ResultMsg.UPDATE_SUCCESS);
......@@ -223,26 +242,9 @@ public class OrganizationManageImpl implements OrganizationManageService {
public ApiOrg getAuthOrganization(Long apiOrgId) {
QueryWrapper<ApiOrg> query = new QueryWrapper<>();
query.eq("id", apiOrgId);
query.eq("status", OrgStatusEnum.NORMAL.name());
query.eq("status", 1);
query.eq("is_deleted", 0);
return apiOrgMapper.selectOne(query);
}
/**
* 根据名称获取组织信息
*
* @param orgName 组织名称
* @return
*/
private ApiOrg getOrgNameInfo(String orgName) {
QueryWrapper<ApiOrg> query = new QueryWrapper<>();
query.eq("org_name", orgName);
query.eq("is_deleted", 0);
query.eq("status", OrgStatusEnum.NORMAL);
ApiOrg apiOrg = apiOrgMapper.selectOne(query);
if (null != apiOrg) {
return apiOrg;
}
return null;
}
}
......@@ -3,21 +3,28 @@ package com.jz.dm.service.impl;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jz.common.constant.ResultCode;
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.exception.ResponseException;
import com.jz.common.utils.HttpsUtils;
import com.jz.common.utils.Md5;
import com.jz.common.utils.RedisUtils;
import com.jz.common.utils.Result;
import com.jz.dm.common.constant.TagConstants;
import com.jz.dm.common.enums.GeneralStatusTypeEnum;
import com.jz.dm.common.enums.apiInterface.ApiInfoOutTypeEnum;
import com.jz.dm.common.enums.apiInterface.ApiStatusEnum;
import com.jz.dm.common.enums.produce.ProducerStatusTypeEnum;
import com.jz.dm.common.util.RandomUtil;
import com.jz.dm.mapper.*;
import com.jz.dm.models.domian.*;
import com.jz.dm.models.req.make.*;
import com.jz.dm.models.domian.ApiInterface;
import com.jz.dm.models.domian.ApiInterfaceCustom;
import com.jz.dm.models.domian.ApiInterfaceFile;
import com.jz.dm.models.domian.ApiOpenApiEsFields;
import com.jz.dm.models.dto.ApiServiceApplyDto;
import com.jz.dm.models.req.folder.CreateFolderReq;
import com.jz.dm.models.req.producer.ApiInterfaceReq;
import com.jz.dm.models.req.producer.ServiceIssueReq;
import com.jz.dm.service.ApiInterfaceService;
import com.jz.dm.service.ProducerService;
import lombok.extern.slf4j.Slf4j;
......@@ -33,7 +40,6 @@ import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.*;
import static com.jz.dm.common.enums.apiInterface.ApiStatusEnum.fromApiStatusName;
import static com.jz.dm.common.enums.auth.AuthReqTypeEnum.fromAuthReqTypeEnum;
/**
......@@ -72,23 +78,23 @@ public class ProducerServiceImpl implements ProducerService {
private int maxTimeout;
@Value("${dmp.openapi.timeout.default}")
private int defaultTimeout;
//@Value("${dmp.openapi.env.open:false}")
//private boolean envOpen = false;
@Value("${dmp.ignoreRedis}")
private boolean ignoreRedis;
/**
* 数据表查询链接JSON
*/
@Value("${data.select.jsonUrl}")
private String jsonUrl;
/**
* dataBank签名token
* 数据表查询链接flow流
*/
@Value("${token.dataBank}")
private String dataBankToken;
@Value("${data.select.flowUrl}")
private String flowUrl;
/**
* 获取文件列表
*
* @param projectId
* @param pageSize
* @param pageNum
* @return
*/
@Override
......@@ -100,174 +106,191 @@ public class ProducerServiceImpl implements ProducerService {
/**
* 创建文件夹
*
* @param projectId
* @param parentId
* @param currentUser
* @param req
* @return
*/
@Override
public Result createProjectFolder(Long projectId, Long parentId, String currentUser) {
QueryWrapper<ApiInterfaceFile> query = new QueryWrapper<>();
query.eq("id", parentId);
query.eq("is_deleted", 0);
ApiInterfaceFile apiInterfaceFile = apiInterfaceFileMapper.selectOne(query);
if (null == apiInterfaceFile) {
public Result createProjectFolder(CreateFolderReq req) {
if (null != req.getParentId()) {
ApiInterfaceFile interfaceFile = apiInterfaceFileMapper.selectById(req.getParentId());
if (null == interfaceFile) {
return Result.of_error("父级文件夹不存在!");
}
ApiInterfaceFile instanceFile = new ApiInterfaceFile();
instanceFile.setProjectId(projectId);
instanceFile.setFileSource("1");//文件来源:1 DMP 2 数据银行
instanceFile.setParentId(parentId);
instanceFile.setStatus(GeneralStatusTypeEnum.VALID.name());
instanceFile.setCreateUser(currentUser);
instanceFile.setRemark("DMP创建层级文件夹");
if (apiInterfaceFileMapper.insert(instanceFile) > 0) {
return Result.of_error(ResultMsg.INSERT_SUCCESS);
if (!req.getFileSource().equals(interfaceFile.getFileSource())){
return Result.of_error("父级文件类型错误!");
}
}
if (StringUtils.isNotBlank(req.getFileSource()) &&
"1".equals(req.getFileSource())) { //api制作创建文件夹
if (null == req.getProjectId()) {
return Result.of_error("项目id不存在!");
}
if (!addFolder(req)) {
return Result.of_success(ResultMsg.INSERT_SUCCESS);
}
} else if (StringUtils.isNotBlank(req.getFileSource()) &&
"2".equals(req.getFileSource())) { //组织创建文件夹
if (!addFolder(req)) {
return Result.of_success(ResultMsg.INSERT_SUCCESS);
}
}
return Result.of_error(ResultMsg.INSERT_FAIL);
}
/**
* DMP制作自定义Api
* 添加文件夹
*
* @param req
* @return
*/
@Override
public Result addCustomApi(ApiInterfaceReq req) {
return saveInterfaceAPi(req);
private boolean addFolder(CreateFolderReq req) {
ApiInterfaceFile interfaceFile = new ApiInterfaceFile();
BeanUtils.copyProperties(req, interfaceFile);
interfaceFile.setStatus(GeneralStatusTypeEnum.VALID.name());
if (null == interfaceFile.getParentId() || "".equals(interfaceFile.getParentId())){
interfaceFile.setParentId(0L);//默认父类id为零
}
if (apiInterfaceFileMapper.insert(interfaceFile) == 0) {
return true;
}
return false;
}
/**
* 数据银行制作API/数据包/自定义
* 获取服务发布列表
*
* @param req
* @return
*/
@Override
@Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
public Result addDataBankApiInfo(MakeDataBankApiReq req) {
QueryWrapper<ApiInterfaceFile> query = new QueryWrapper<>();
query.eq("file_source", "2");
query.eq("is_deleted", 0);
List<ApiInterfaceFile> fileSource = apiInterfaceFileMapper.selectList(query);
if (fileSource.size() == 0 || fileSource.size() >= 2) {
return Result.of_error("文件夹信息异常!");
public Result getServiceIssueList(ServiceIssueReq req) {
IPage<ApiServiceApplyDto> page = new Page<>(req.getPageNum(), req.getPageSize());
QueryWrapper<ApiServiceApplyDto> query = new QueryWrapper<>();
if (null != req.getFileId()) {
query.eq("ai.file_id", req.getFileId());
}
// if (StringUtils.isNotBlank(req.getOutputType()) &&
// (!req.getOutputType().contains(ApiInfoOutTypeEnum.JSON.name()) ||
// !req.getOutputType().contains(ApiInfoOutTypeEnum.FLOW.name()))) {
// return Result.of_error("输出类型不存在!");
// }
if (StringUtils.isNotBlank(req.getReqType())) {
if (null == fromAuthReqTypeEnum(req.getReqType())) {
return Result.of_error("限流类型不存在!");
if (StringUtils.isNotBlank(req.getApiName())) {
query.eq("ai.api_name", req.getApiName());
}
if (StringUtils.isNotBlank(req.getApiId())) {
query.eq("ai.api_key", req.getApiId());
}
String signStr = dataBankToken + req.getJoinType();
String signResult = Md5.encrypt(signStr, "");
if (!signResult.equals(req.getSign())) {
return Result.of_error("签名错误!");
}
String apiKey = getApiKey();
switch (req.getJoinType()) {
case "10006"://数据银行三方上传
saveDataBanker(req, apiKey, "3");
break;
case "10007"://数据银行数据包上传
saveDataBanker(req, apiKey, "2");
break;
case "10008"://数据银行制作大数据表
saveDataBanker(req, apiKey, "1");
break;
default:
return Result.of_error("接入类型不存在!");
}
return Result.of_success(ResultMsg.INSERT_SUCCESS, apiKey);
query.eq("ai.is_deleted", 0);
query.orderByDesc("ai.create_date");
return Result.of_success(apiInterfaceMapper.listApiIssueService(page, query));
}
/**
* 保存数据银行api信息并缓存
* 服务发布取消操作
*
* @param req 请求参数
* @param apiKey apiKey
* @param apiType api类型
*/
private void saveDataBanker(MakeDataBankApiReq req, String apiKey, String apiType) {
ApiInterface apiInterface = saveApiInterFace(req, apiKey, apiType);
saveApiInterFaceCustom(req, apiKey, apiInterface.getId());
JSONObject object = new JSONObject();
object.put("targetUrl", req.getTargetUrl());
object.put("outputType", req.getOutputType());
saveObjOnRedis(apiInterface.getApiKey(), object);
}
/**
* 保存api基本信息
*
* @param req
* @param apiKey
* @param apiType
* @param id
* @param optStatus
* @return
*/
private ApiInterface saveApiInterFace(MakeDataBankApiReq req,
String apiKey, String apiType) {
ApiInterface anInterface = new ApiInterface();
anInterface.setApiType(apiType);//数据银行制作大数据表
anInterface.setStatus(ProducerStatusTypeEnum.ISSUE.name());//发布
anInterface.setApiKey(apiKey);//apiKey
BeanUtils.copyProperties(req, anInterface);
if (apiInterfaceMapper.insert(anInterface) == 0) {
throw ResponseException.of(ResultCode.FAILURE, "保存api基本信息异常!");
@Override
public Result optionApiIssueStatus(Long id, Boolean optStatus) {
int updateStatus = 0;
ApiInterface apiInterface = apiInterfaceMapper.selectById(id);
if (null == apiInterface) {
return Result.of_error(ResultMsg.DATA_NOT_FOUND);
}
return anInterface;
//修改前后状态一致,无需修改直接返回
if (optStatus.equals(apiInterface.getStatus())) {
return Result.of_success(ResultMsg.UPDATE_SUCCESS);
}
if (optStatus) {//发布
UpdateWrapper<ApiInterface> updateWra = new UpdateWrapper<>();
updateWra.set("status", ApiStatusEnum.ISSUE.name());
updateWra.eq("id", id);
updateStatus = apiInterfaceMapper.update(null, updateWra);
} else {//取消发布
if (apiInterface.getIsSendBank()) {
return Result.of_error("API信息已锁定,无法取消发布");
}
UpdateWrapper<ApiInterface> updateWra = new UpdateWrapper<>();
updateWra.set("status", ApiStatusEnum.DRAFT.name());
updateWra.eq("id", id);
updateStatus = apiInterfaceMapper.update(null, updateWra);
}
if (updateStatus > 0) {
return Result.of_success(ResultMsg.UPDATE_SUCCESS);
}
return Result.of_error(ResultMsg.UPDATE_FAIL);
}
/**
* 保存APi扩展信息
* 获取ApiId
*
* @param req
* @param apiKey
* @param interFaceId
* @return
*/
private ApiInterfaceCustom saveApiInterFaceCustom(MakeDataBankApiReq req, String apiKey,
Long interFaceId) {
ApiInterfaceCustom interfaceCustom = new ApiInterfaceCustom();
interfaceCustom.setApiKey(apiKey);
interfaceCustom.setApiInterfaceId(interFaceId);
BeanUtils.copyProperties(req, interfaceCustom);
if (apiInterfaceCustomMapper.insert(interfaceCustom) == 0) {
throw ResponseException.of(ResultCode.FAILURE, "保存api扩展信息异常!");
}
return interfaceCustom;
@Override
public Result getCustomApiId() {
return Result.of_success(ResultMsg.SUCCESS,getApiKey());
}
/**
* Api制作(实时接入)
* 数据查询/标签查询
*
* @param req
* @return
*/
@Override
public Result addRealCustomApi(MakeRealCustomApiReq req) {
return null;
@Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
public Result addBigDataMakeApi(ApiInterfaceReq req) {
ApiInterface anInterface = apiInterfaceService.getApiInfo(req.apiKey);
if (null != anInterface){
return Result.of_error("API已存在!");
}
if ("10002".equals(req.getApiType())) {//数据查询
if (StringUtils.isBlank(req.getEsDataSource()) ||
StringUtils.isBlank(req.getEsDataBase()) ||
StringUtils.isBlank(req.getEsTable())) {
return Result.of_error("数据源信息不存在!");
}
}
if (null != req.getReqFrequency()) {
if (req.getReqFrequency() <= 0) {
return Result.of_error("限流次数不能小于或者等于零");
}
}
if (StringUtils.isBlank(req.getSignType()) || "0".equals(req.getSignType())) {
return Result.of_error("加密类型错误!");
}
if (StringUtils.isNotBlank(req.getLimitType())) {
if (null == fromAuthReqTypeEnum(req.getLimitType())) {
return Result.of_error("限流类型不存在!");
}
}
//校验文件夹信息
if (checkFileifExist(req.getFileId(), req.getProjectId())) {
return Result.of_error("目标文件夹不存在!");
}
//保存表字段信息
saveTableField(req);
if (null != req.getId()) {//更新
if (saveUpdateAPiBaseData(req) || saveUpdateApiExtendData(req)) {
throw ResponseException.of_error(ResultMsg.UPDATE_FAIL);
}
} else { //保存
ApiInterface apiInterface = saveApiBaseData(req);
if (saveApiExtendData(req,apiInterface.getId())) {
throw ResponseException.of_error(ResultMsg.INSERT_FAIL);
}
}
//保存缓存信息
saveObjOnRedis(req);
return Result.of_success(ResultMsg.INSERT_SUCCESS);
}
/**
* DMP大数据查询/标签查询
* 数据表查询 && 保存表字段信息
*
* @param req
* @return
*/
@Override
@Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
public Result addBigDataMakeApi(MakeBigDataApiReq req) {
ApiInterface apiInterface = apiInterfaceService.getApiInfo(req.getApiKey());
if (null == apiInterface) {
return Result.of_error("API基本信息为空!");
private void saveTableField(ApiInterfaceReq req) {
if (StringUtils.isBlank(req.getTableFields())){
return;
}
QueryWrapper<ApiOpenApiEsFields> queryOpenApi = new QueryWrapper<>();
queryOpenApi.eq("es_database", req.getEsDataBase());
......@@ -299,33 +322,10 @@ public class ProducerServiceImpl implements ProducerService {
if (CollectionUtils.isNotEmpty(listApiEsFields)) {
apiOpenApiEsFieldsMapper.insetBatch(listApiEsFields);
}
/* //调用dmp接口获取数据库连接信息
ApiSyncingDatasource dataSource = apiSyncingDatasourceMapper.selectById(req.getEsDataSource());
if (null != dataSource) {
//esjdbc 连接地址 用于接口中调用获取es数据
redisUtils.set(TagConstants.OPEN_API_ESTAG_JDBC_INFO_NAMESPACE + apiInterface.getApiKey(), dataSource.getJdbcUrl());
}*/
int result = 0;
ApiInterfaceCustom interfaceCustom = new ApiInterfaceCustom();
if (null != req.getId() && !"".equals(req.getId())) {//更新
BeanUtils.copyProperties(req, interfaceCustom);
interfaceCustom.setUpdateDate(new Date());
interfaceCustom.setUpdateUser(req.getCreateUser());
result = apiInterfaceCustomMapper.updateById(interfaceCustom);
} else { //保存
BeanUtils.copyProperties(req, interfaceCustom);
interfaceCustom.setCreateUser(req.getCreateUser());
interfaceCustom.setApiInterfaceId(apiInterface.getId());
result = apiInterfaceCustomMapper.insert(interfaceCustom);
}
if (result <= 0) {
return Result.of_error(ResultMsg.FAILURE);
}
return Result.of_success(ResultMsg.SUCCESS, req.getId());
}
/**
* DMP保存api基本信息/自定义API
* DMP保存api基本信息/自定义API(三方查询)
*
* @param req
* @return
......@@ -333,181 +333,191 @@ public class ProducerServiceImpl implements ProducerService {
@Override
@Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
public Result saveInterfaceAPi(ApiInterfaceReq req) {
if (StringUtils.isNotBlank(req.getReqType())) {
if (null == fromAuthReqTypeEnum(req.getReqType())) {
ApiInterface anInterface = apiInterfaceService.getApiInfo(req.apiKey);
if (null != anInterface){
return Result.of_error("API已存在!");
}
if (StringUtils.isNotBlank(req.getLimitType())) {
if (null == fromAuthReqTypeEnum(req.getLimitType())) {
return Result.of_error("限流类型不存在!");
}
}
//生成ApiKey
String apiKey = getApiKey();
ApiInterface apiInterface = new ApiInterface();
if (null == req.getFileId()) {//创建下级文件夹
Long fileId = checkFileExist(req.getProjectId(), req.getParentId(), req.getCreateUser());
req.setFileId(fileId);
if (StringUtils.isBlank(req.getSignType()) || "0".equals(req.getSignType())) {
return Result.of_error("加密类型错误!");
}
BeanUtils.copyProperties(req, apiInterface);
apiInterface.setApiKey(apiKey);
apiInterface.setApiProtocl(req.getTransMode());//传输方式 https http
apiInterface.setStatus(ApiStatusEnum.ISSUE.name());//发布
if ("10004".equals(req.getJoinType())) {//dmp自定义
apiInterface.setApiType("7");
} else if ("10002".equals(req.getJoinType())) {//大数据表查询
apiInterface.setApiType("6");
if (null != req.getReqFrequency()) {
if (req.getReqFrequency() <= 0) {
return Result.of_error("限流次数不能小于或者等于零");
}
Long timeout = Long.parseLong(req.getTimeout());
if (timeout == null || timeout == 0) {
apiInterface.setTimeout(String.valueOf(defaultTimeout));
} else if (timeout < 0) {
return Result.of_error("接口超时时间最小0ms");
} else if (timeout > maxTimeout) {
return Result.of_success("接口超时时间最大5000ms");
}
if (apiInterfaceMapper.insert(apiInterface) == 0) {
throw ResponseException.of_error("保存Api信息失败!");
if (StringUtils.isBlank(req.getTargetUrl())){
return Result.of_error("目标地址不存在!");
}
JSONObject object = new JSONObject();
object.put("targetUrl", req.getTargetUrl());
object.put("outputType", ApiInfoOutTypeEnum.JSON.name());
saveObjOnRedis(apiInterface.getApiKey(), object);
return Result.of_success(ResultMsg.INSERT_SUCCESS, apiKey);
//校验文件夹信息
if (checkFileifExist(req.getFileId(), req.getProjectId())) {
return Result.of_error("目标文件夹不存在!");
}
ApiInterface apiInterface = saveApiBaseData(req);
if (saveApiExtendData(req,apiInterface.getId())) {
throw ResponseException.of_error("保存Api扩展信息失败!");
}
//缓存API信息
saveObjOnRedis(req);
return Result.of_success(ResultMsg.INSERT_SUCCESS);
}
/**
* 缓存数据
*
* @param apiKey
* @param params
* 保存APi扩展信息
* @param id
* @param req
* @return
*/
private void saveObjOnRedis(String apiKey, JSONObject params) {
if (StringUtils.isBlank(apiKey) || null == params) {
log.info("--------------缓存数据为空");
return;
}
try {
String paramKey = redisUtils.get(apiKey);
if (null != paramKey) {
redisUtils.del(apiKey);
}
redisUtils.set(apiKey, params.toString());
} catch (Exception ex) {
log.error("缓存api制作数据异常:{}", ex.getMessage());
ex.printStackTrace();
private boolean saveApiExtendData(ApiInterfaceReq req,Long id) {
ApiInterfaceCustom custom = new ApiInterfaceCustom();
BeanUtils.copyProperties(req, custom);
custom.setApiInterfaceId(id);
if (apiInterfaceCustomMapper.insert(custom) == 0) {
return true;
}
return false;
}
/**
* 校验文件夹信息
* 保存ApiInterfance基本信息
*
* @param projectId
* @param parentId
* @param userName
* @param req
* @return
*/
private Long checkFileExist(Long projectId, Long parentId, String userName) {
if (null == parentId) {
throw ResponseException.of_error("父文件id不能为空");
private ApiInterface saveApiBaseData(ApiInterfaceReq req) {
ApiInterface apiInterface = new ApiInterface();
BeanUtils.copyProperties(req, apiInterface);
apiInterface.setStatus(ApiStatusEnum.DRAFT.name());//草稿状态
apiInterface.setOutputType(ApiInfoOutTypeEnum.JSON.name());//输出类型默认为Json
Long timeout = Long.parseLong(req.getTimeout());
if (timeout == null || timeout == 0) {
apiInterface.setTimeout(String.valueOf(defaultTimeout));
} else if (timeout < 0) {
throw ResponseException.of_error("接口超时时间最小0ms");
} else if (timeout > maxTimeout) {
throw ResponseException.of_error("接口超时时间最大5000ms");
}
if (null == projectId) {
throw ResponseException.of_error("项目id不能为空");
apiInterface.setTimeout(req.getTimeout());
if ("10002".equals(req.getApiType())) {//数据表查询时添加
if (ApiInfoOutTypeEnum.JSON.name().equals(req.getOutType())) {
apiInterface.setTargetUrl(jsonUrl);
} else if (ApiInfoOutTypeEnum.FLOW.name().equals(req.getOutType())) {
apiInterface.setTargetUrl(flowUrl);
}
QueryWrapper<ApiInterfaceFile> query = new QueryWrapper<>();
query.eq("project_id", projectId);
query.eq("parent_id", parentId);
ApiInterfaceFile file = apiInterfaceFileMapper.selectOne(query);
if (null == file && 0 != parentId) {
throw ResponseException.of(ResultCode.FAILURE, "父类文件夹不存在!");
}
if (null == file) {
//查询父类是否存在
ApiInterfaceFile apiInterfaceFile =
apiInterfaceFileMapper.selectOne(new QueryWrapper<ApiInterfaceFile>().eq("parent_id", parentId));
if (null == apiInterfaceFile && 0 == parentId) {
file = new ApiInterfaceFile();
file.setProjectId(projectId);
file.setFileSource("1");//dmp
file.setParentId(0L);
file.setStatus(GeneralStatusTypeEnum.VALID.name());
file.setCreateUser(userName);
file.setRemark("创建文件夹");
if (apiInterfaceFileMapper.insert(file) == 0) {
throw ResponseException.of_error("创建文件夹失败!");
if (apiInterfaceMapper.insert(apiInterface) == 0) {
throw ResponseException.of_error("添加API基本信息异常!");
}
} else {
throw ResponseException.of(ResultCode.FAILURE, "父类文件信息不存在!");
return apiInterface;
}
/**
* 校验文件夹是否存在
*
* @param folderId
* @param projectId
*/
private Boolean checkFileifExist(Long folderId, Long projectId) {
if (null == folderId) {
return true;
}
QueryWrapper<ApiInterfaceFile> queryWra = new QueryWrapper<>();
queryWra.eq("file_source", 1);//Api制作
queryWra.eq("project_id", projectId);
queryWra.eq("id", folderId);
queryWra.eq("is_deleted", 0);
ApiInterfaceFile apiInterfaceFile = apiInterfaceFileMapper.selectOne(queryWra);
if (null == apiInterfaceFile) {
return true;
}
return file.getId();
return false;
}
/**
* 保存修改的api信息
* 保存修改的api基本信息
*
* @param req
* @return
*/
@Override
public Result saveUpdateAPiInfo(ApiInterfaceReq req) {
private Boolean saveUpdateAPiBaseData(ApiInterfaceReq req) {
ApiInterface apiInterface = apiInterfaceMapper.selectById(req.getId());
if (null == apiInterface) {
return Result.of_error(ResultMsg.DATA_NOT_FOUND);
}
if (StringUtils.isBlank(req.getSignType()) || "0".equals(req.getSignType())) {
return Result.of_error("加密类型错误!");
}
if (StringUtils.isNotBlank(req.getReqType())) {
if (null == fromAuthReqTypeEnum(req.getReqType())) {
return Result.of_error("限流类型不存在!");
}
}
if (StringUtils.isNotBlank(req.getStatus())) {
if (null == fromApiStatusName(req.getStatus())) {
return Result.of_error("更新状态不存在!");
}
throw ResponseException.of_error(ResultMsg.DATA_NOT_FOUND);
}
if (StringUtils.isNotBlank(req.getStatus())) {
if (!canChange(apiInterface.getStatus(), req.getStatus())) {
String errorMsg = String.format("api当前状态为%s不可变更为%s",
ApiStatusEnum.valueOf(apiInterface.getStatus()).getText(),
ApiStatusEnum.valueOf(req.getStatus()).getText());
return Result.of_error(errorMsg);
}
}
if (null != req.getReqFrequency()) {
if (req.getReqFrequency() <= 0) {
return Result.of_error("限流次数不能小于或者等于零");
throw ResponseException.of_error(errorMsg);
}
}
apiInterface.setApiType(req.getApiType());
apiInterface.setApiDesc(req.getApiDesc());
apiInterface.setReqType(req.getReqType());
apiInterface.setReqFrequency(req.getReqFrequency());
apiInterface.setVersion(RandomUtil.generateVersion(apiInterface.getVersion()));//版本自动累加
apiInterface.setSignType(req.getSignType());
apiInterface.setApiFunction(req.getApiFunction());
apiInterface.setStatus(req.getStatus());
apiInterface.setApiProtocl(req.getTransMode());//传输方式 https http
apiInterface.setApiProtocl(req.getApiProtocl());//传输方式 https http
apiInterface.setUpdateDate(new Date());
apiInterface.setUpdateUser(req.getCreateUser());
if (StringUtils.isNotBlank(req.getTargetUrl())) {
apiInterface.setTargetUrl(req.getTargetUrl());
}
Long timeout = Long.parseLong(req.getTimeout());
if (timeout == null || timeout == 0) {
apiInterface.setTimeout(String.valueOf(defaultTimeout));
} else if (timeout < 0) {
return Result.of_error("接口超时时间最小0ms");
throw ResponseException.of_error("接口超时时间最小0ms");
} else if (timeout > maxTimeout) {
return Result.of_success("接口超时时间最大5000ms");
throw ResponseException.of_error("接口超时时间最大5000ms");
}
apiInterface.setTimeout(req.getTimeout());
if (apiInterfaceMapper.updateById(apiInterface) > 0) {
return Result.of_success(ResultMsg.UPDATE_SUCCESS);
if (apiInterfaceMapper.updateById(apiInterface) == 0) {
return true;
}
JSONObject object = new JSONObject();
object.put("targetUrl", req.getTargetUrl());
object.put("outputType", ApiInfoOutTypeEnum.JSON.name());
saveObjOnRedis(apiInterface.getApiKey(), object);
return Result.of_success(ResultMsg.UPDATE_FAIL);
return false;
}
/**
* 保存更新数据扩展信息
*
* @param req
* @return
*/
private Boolean saveUpdateApiExtendData(ApiInterfaceReq req) {
ApiInterface apiInterface = apiInterfaceMapper.selectById(req.getId());
ApiInterfaceCustom interfaceCustom = null;
if (null != apiInterface) {
QueryWrapper<ApiInterfaceCustom> query = new QueryWrapper<>();
query.eq("api_interface_id",req.getId());
query.eq("api_key",apiInterface.getApiKey());
query.eq("is_deleted",0);
interfaceCustom = apiInterfaceCustomMapper.selectOne(query);
}
if (null == interfaceCustom) {
throw ResponseException.of_error("更新API扩展信息不存在!");
}
interfaceCustom.setMaxRow(req.getMaxRow());
interfaceCustom.setPageRow(req.getPageRow());
interfaceCustom.setUpdateUser(req.getUpdateUser());
interfaceCustom.setRequestParam(req.getRequestParam());
interfaceCustom.setResponseParam(req.getResponseParam());
if (StringUtils.isNotBlank(req.getEsDataSource())) {
interfaceCustom.setEsDataSource(req.getEsDataSource());
}
if (StringUtils.isNotBlank(req.getEsDataBase())) {
interfaceCustom.setEsDataBase(req.getEsDataBase());
}
if (StringUtils.isNotBlank(req.getEsTable())) {
interfaceCustom.setEsTable(req.getEsTable());
}
if (apiInterfaceCustomMapper.updateById(interfaceCustom) == 0) {
return true;
}
return false;
}
/**
......@@ -538,11 +548,223 @@ public class ProducerServiceImpl implements ProducerService {
/**
* 获取不重复的apiKey
*
* @return
*/
private String getApiKey() {
String random = RandomUtil.getStringRandom(16);
QueryWrapper<ApiInterface> query = new QueryWrapper<>();
query.eq("api_key", random);
query.eq("is_deleted", 0);
ApiInterface apiInterface = apiInterfaceMapper.selectOne(query);
if (null != apiInterface) {
random = RandomUtil.getStringRandom(16);
}
return random;
}
/**
* 缓存数据
*
* @param req
*/
private void saveObjOnRedis(ApiInterfaceReq req) {
if (StringUtils.isBlank(req.getApiKey()) ||
StringUtils.isBlank(req.getOutType()) ||
StringUtils.isBlank(req.getTargetUrl()) ||
StringUtils.isBlank(req.getReqType()) ||
StringUtils.isBlank(req.getApiType())) {
log.info("--------------缓存数据为空");
return;
}
try {
JSONObject object = new JSONObject();
object.put("targetUrl", req.getTargetUrl());
object.put("outputType", ApiInfoOutTypeEnum.JSON.name());
object.put("reqType", req.getReqType());
object.put("apiType",req.getApiType());
String apiKey = TagConstants.OPEN_API_CACHE_KEY + req.getApiKey();
String paramKey = redisUtils.get(apiKey);
if (null != paramKey) {
redisUtils.del(apiKey);
}
redisUtils.set(apiKey, object.toString());
} catch (Exception ex) {
log.error("缓存api制作数据异常:{}", ex.getMessage());
ex.printStackTrace();
}
}
/* *//**
* 数据银行制作API/数据包/自定义
*
* @param req
* @return
*//*
@Override
@Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
public Result addDataBankApiInfo(MakeDataBankApiReq req) {
*//* QueryWrapper<ApiInterfaceFile> query = new QueryWrapper<>();
query.eq("file_source", "2");
query.eq("is_deleted", 0);
List<ApiInterfaceFile> fileSource = apiInterfaceFileMapper.selectList(query);
if (fileSource.size() == 0 || fileSource.size() >= 2) {
return Result.of_error("文件夹信息异常!");
}*//*
if (StringUtils.isNotBlank(req.getOutputType())) {
if (!req.getOutputType().contains(ApiInfoOutTypeEnum.JSON.name()) ||
!req.getOutputType().contains(ApiInfoOutTypeEnum.FLOW.name())) {
return Result.of_error("输出类型不存在!");
}
}
if (StringUtils.isNotBlank(req.getReqType())) {
if (null == fromAuthReqTypeEnum(req.getReqType())) {
return Result.of_error("限流类型不存在!");
}
}
String signStr = dataBankToken + req.getJoinType();
String signResult = Md5.encrypt(signStr, "");
if (!signResult.equals(req.getSign())) {
return Result.of_error("签名错误!");
}
String apiKey = getApiKey();
switch (req.getJoinType()) {
case "10006"://数据银行三方上传
saveDataBanker(req, apiKey, "3");
break;
case "10007"://数据银行数据包上传
if (StringUtils.isNotBlank(req.getFileLocation())) return Result.of_error("文件地址不存在!");
saveDataBanker(req, apiKey, "2");
break;
case "10008"://数据银行制作大数据表
saveDataBanker(req, apiKey, "1");
break;
default:
return Result.of_error("接入类型不存在!");
}
return Result.of_success(ResultMsg.INSERT_SUCCESS, apiKey);
}*/
/* *//**
* 保存数据银行api信息并缓存
*
* @param req 请求参数
* @param apiKey apiKey
* @param apiType api类型
*//*
private void saveDataBanker(MakeDataBankApiReq req, String apiKey, String apiType) {
ApiInterface apiInterface = saveApiInterFace(req, apiKey, apiType);
saveApiInterFaceCustom(req, apiKey, apiInterface.getId());
JSONObject object = new JSONObject();
object.put("targetUrl", req.getTargetUrl());
object.put("outputType", req.getOutputType());
object.put("reqMethod", req.getReqMethod());
saveObjOnRedis(apiInterface.getApiKey(), object);
}*/
/* *//**
* 保存api基本信息
*
* @param req
* @param apiKey
* @param apiType
* @return
*//*
private ApiInterface saveApiInterFace(MakeDataBankApiReq req,
String apiKey, String apiType) {
ApiInterface anInterface = new ApiInterface();
anInterface.setApiType(apiType);//数据银行制作大数据表
anInterface.setStatus(ProducerStatusTypeEnum.ISSUE.name());//发布
anInterface.setApiKey(apiKey);//apiKey
BeanUtils.copyProperties(req, anInterface);
if (apiInterfaceMapper.insert(anInterface) == 0) {
throw ResponseException.of(ResultCode.FAILURE, "保存api基本信息异常!");
}
return anInterface;
}*/
/* *//**
* 保存APi扩展信息
*
* @param req
* @param apiKey
* @param interFaceId
* @return
*//*
private ApiInterfaceCustom saveApiInterFaceCustom(MakeDataBankApiReq req, String apiKey,
Long interFaceId) {
ApiInterfaceCustom interfaceCustom = new ApiInterfaceCustom();
interfaceCustom.setApiKey(apiKey);
interfaceCustom.setApiInterfaceId(interFaceId);
BeanUtils.copyProperties(req, interfaceCustom);
if (apiInterfaceCustomMapper.insert(interfaceCustom) == 0) {
throw ResponseException.of(ResultCode.FAILURE, "保存api扩展信息异常!");
}
return interfaceCustom;
}*/
/* *//**
* Api制作(实时接入)
*
* @param req
* @return
*//*
@Override
public Result addRealCustomApi(MakeRealCustomApiReq req) {
return null;
}*/
/* *//**
* 校验文件夹信息
*
* @param projectId
* @param parentId
* @param userName
* @return
*//*
private Long checkFileExist(Long projectId, Long parentId, String userName) {
if (null == parentId) {
throw ResponseException.of_error("父文件id不能为空");
}
if (null == projectId) {
throw ResponseException.of_error("项目id不能为空");
}
QueryWrapper<ApiInterfaceFile> query = new QueryWrapper<>();
query.eq("project_id", projectId);
query.eq("parent_id", parentId);
ApiInterfaceFile file = apiInterfaceFileMapper.selectOne(query);
if (null == file && 0 != parentId) {
throw ResponseException.of(ResultCode.FAILURE, "父类文件夹不存在!");
}
if (null == file) {
//查询父类是否存在
ApiInterfaceFile apiInterfaceFile =
apiInterfaceFileMapper.selectOne(new QueryWrapper<ApiInterfaceFile>().eq("parent_id", parentId));
if (null == apiInterfaceFile && 0 == parentId) {
file = new ApiInterfaceFile();
file.setProjectId(projectId);
file.setFileSource("1");//dmp
file.setParentId(0L);
file.setStatus(GeneralStatusTypeEnum.VALID.name());
file.setCreateUser(userName);
file.setRemark("创建文件夹");
if (apiInterfaceFileMapper.insert(file) == 0) {
throw ResponseException.of_error("创建文件夹失败!");
}
} else {
throw ResponseException.of(ResultCode.FAILURE, "父类文件信息不存在!");
}
}
return file.getId();
}
*/
/* *//**
* 获取数据源配置
*
* @param req
* @return
*/
*//*
@Override
public Result getSourceConfig(SourceConfigReq req) {
if (StringUtils.isBlank(req.getApiKey())) {
......@@ -565,12 +787,12 @@ public class ProducerServiceImpl implements ProducerService {
return Result.of_success(ResultMsg.SUCCESS);
}
/**
*//**
* 获取数据源库配置
*
* @param id
* @return
*/
*//*
@Override
public Result getSourceWarehouseList(Long id) {
ApiSyncingDatasource datasource = apiSyncingDatasourceMapper.selectById(id);
......@@ -596,13 +818,13 @@ public class ProducerServiceImpl implements ProducerService {
return Result.of_success(result);
}
/**
*//**
* 获取某个索引下的type
*
* @param indices
* @param id
* @return
*/
*//*
@Override
public Result getIndicesTypes(String indices, Long id) {
ApiSyncingDatasource datasource = apiSyncingDatasourceMapper.selectById(id);
......@@ -618,14 +840,14 @@ public class ProducerServiceImpl implements ProducerService {
return Result.of_success(resp);
}
/**
*//**
* 获取某个索引 type的fields
*
* @param indices
* @param type
* @param id
* @return
*/
*//*
@Override
public Result getIndicesTypesFields(String indices, String type, Long id) {
ApiSyncingDatasource datasource = apiSyncingDatasourceMapper.selectById(id);
......@@ -647,31 +869,15 @@ public class ProducerServiceImpl implements ProducerService {
e.printStackTrace();
}
return Result.of_success(resp);
}
}*/
/**
* 获取不重复的apiKey
*
* @return
*/
private String getApiKey() {
String random = RandomUtil.getStringRandom(16);
QueryWrapper<ApiInterface> query = new QueryWrapper<>();
query.eq("api_key", random);
query.eq("is_deleted", 0);
ApiInterface apiInterface = apiInterfaceMapper.selectOne(query);
if (null != apiInterface) {
random = RandomUtil.getStringRandom(16);
}
return random;
}
@Override
/* @Override
public Result saveObjOnRedis() {
MakeDataBankApiReq bankApiReq = new MakeDataBankApiReq();
/* bankApiReq.setTransMode("HTTPS");
*//* bankApiReq.setTransMode("HTTPS");
bankApiReq.setSignType("MD5");
bankApiReq.setJoinType("10004");
bankApiReq.setOutputType("JSON");
......@@ -684,7 +890,7 @@ public class ProducerServiceImpl implements ProducerService {
bankApiReq.setApiDesc("4444");
bankApiReq.setTimeout("5000");
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();
object.put("targetUrl", "www.baidu.common");
object.put("outputType", ApiInfoOutTypeEnum.JSON.name());
......@@ -699,5 +905,5 @@ public class ProducerServiceImpl implements ProducerService {
JSONObject jsonObject = JSONObject.parseObject(apiKeyTest002);
System.out.println(jsonObject);
return Result.ok();
}
}*/
}
......@@ -15,11 +15,13 @@ import com.jz.dm.common.util.stream.HttpDownload;
import com.jz.dm.gateway.OpenApiService;
import com.jz.dm.models.domian.ApiAuth;
import com.jz.dm.models.domian.ApiInterface;
import com.jz.dm.models.domian.ApiInterfaceCustom;
import com.jz.dm.service.ApiInterfaceService;
import com.jz.dm.service.AuthService;
import com.jz.dm.web.annotation.AccessLimit;
import com.jz.dm.web.annotation.ApiLogAspect;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
......@@ -27,6 +29,9 @@ import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
/**
......@@ -61,9 +66,13 @@ public class ApiQueryService extends ApiParamVerify implements OpenApiService {
@Autowired
private HttpsUtils httpsUtils;
/**
* 数据银行扣款链接
*/
@Value("${data.bank.balanceUrl}")
private String balanceUrl;
/**
* API请求逻辑处理
*
......@@ -74,40 +83,42 @@ public class ApiQueryService extends ApiParamVerify implements OpenApiService {
@ApiLogAspect(description = "API请求日志")
@AccessLimit(limit = 10000, sec = 1)
@SentinelResource(value = "api.gateway", fallback = "fallbackGateway")
@Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
@Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
public void doService(OpenApiRequest request, OpenApiResponse response) {
boolean bResult = false;
JSONObject parameter = JSONObject.parseObject(request.getOpenApiParams());
ApiInterface apiInterface = apiInterfaceService.getApiInfo(request.getApiKey());
ApiAuth apiAuth = null;
JSONObject jsonParams = null;
try {
String reqParams = parameter.getString("reqParams");
Map paramMap = null;
if (StringUtils.isNotBlank(reqParams)) {
jsonParams = JSONObject.parseObject(reqParams);
paramMap = JSONObject.parseObject(jsonParams.getString("request_fileds"), Map.class);
jsonParams.put("is_test",false);
}
String authCode = parameter.getString("authCode");
if (StringUtils.isBlank(authCode)) {
throw new GatewayException(GatewayResultCode.ILLEGAL_REQUEST);
}
verifyApiInterface(apiInterfaceService.getApiInfo(request.getApiKey()));
ApiAuth apiAuth = authService.getAuthInfo(authCode);
verifyApiInterface(apiInterface);
apiAuth = authService.getAuthInfo(authCode);
verifyAuth(apiAuth);
String reqParams = parameter.getString("reqParams");
Map paramMap = null;
if (StringUtils.isNotBlank(reqParams)) {
paramMap = (Map) JSONObject.parseObject(reqParams);
}
//取出缓存数据
String redisReqParam = redisUtils.get(request.getApiKey());
boolean bResult = false;
try {
/* String redisReqParam = redisUtils.get(request.getApiKey());*/
String redisReqParam = null;
if (StringUtils.isNotBlank(redisReqParam)) {//redis中存在
//解析出API制作成功时的参数配置
JSONObject jsonObject = JSONObject.parseObject(redisReqParam);
String targetUrl = jsonObject.getString("targetUrl");
String outputType = jsonObject.getString("outputType");
bResult = rangRequestTarget(outputType, targetUrl, paramMap, response);
String apiType = jsonObject.getString("apiType");
bResult = rangRequestTarget(outputType, targetUrl, paramMap,
jsonParams, apiType, apiInterface, response);
} else {//不存在查询数据库
ApiInterface apiInterface =
apiInterfaceService.getReqTargetInfo(request.getApiKey());
if (null == apiInterface) {
throw new GatewayException(GatewayResultCode.REQUEST_INFO_UNEXIST);
}
bResult = rangRequestTarget(apiInterface.getOutputType(),
apiInterface.getTargetUrl(), paramMap, response);
apiInterface.getTargetUrl(), paramMap, jsonParams, apiInterface.getApiType(), apiInterface, response);
}
//调用成功请求数据银行扣款
if (AuthModeEnum.POWER_CALL_MODE.name().equals(apiAuth.getAuthMode())) {
......@@ -137,52 +148,234 @@ public class ApiQueryService extends ApiParamVerify implements OpenApiService {
* @param outputType
* @param targetUrl
* @param param
* @param apiType
* @param response
*/
private boolean rangRequestTarget(String outputType, String targetUrl,
Map<String, String> param, OpenApiResponse response) {
Map<String, String> param, JSONObject jsonParams, String apiType,
ApiInterface apiInterface, OpenApiResponse response) {
if (StringUtils.isBlank(outputType)) {
outputType = ApiInfoOutTypeEnum.JSON.name();
}
if (StringUtils.isBlank(targetUrl)) {
throw new GatewayException(GatewayResultCode.ILLEGAL_REQUEST);
throw new GatewayException(GatewayResultCode.REQUEST_PARAM_EMPTY);
}
if (ApiInfoOutTypeEnum.FLOW.name().equals(outputType)) {//文件流形式请求
StringBuilder builder = new StringBuilder();
builder.append(targetUrl).append("?");
for (Map.Entry<String, String> entry : param.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
builder.append(key).append(LoggingConstants.AND_EQUAL)
.append(value).append(LoggingConstants.AND_SPILT);
}
String baseUrl = builder.substring(0, builder.length() - 1);
HttpDownload.download(baseUrl);
if (StringUtils.isBlank(apiType)) {
throw new GatewayException(GatewayResultCode.API_TYPE_ERROR);
}
if ("10002".equals(apiType) || "10009".equals(apiType)) {//数据表查询
return dataTableSelect(outputType, targetUrl, param, jsonParams, apiInterface, response);
} else if ("10004".equals(apiType) || "10008".equals(apiType)) {//三方查询
return thirdSelect(targetUrl, apiInterface,jsonParams, response);
} else if ("10005".equals(apiType) || "10007".equals(apiType)) {//数据包查询
return dataBagDownload(targetUrl,jsonParams,response);
} else {
throw new GatewayException(GatewayResultCode.API_TYPE_ERROR);
}
}
/**
* 三方查询 $$ 数据银行+DMP
*
* @param targetUrl
* @param apiInterface
* @param response
* @return
*/
private boolean thirdSelect(String targetUrl, ApiInterface apiInterface,JSONObject jsonParams, OpenApiResponse response) {
if ("POST".equalsIgnoreCase(apiInterface.getReqType())) {
return callMethodResponse(httpsUtils.submitPost(targetUrl, jsonParams.toString()), response);
} else {
Map map = JSONObject.parseObject(jsonParams.toString(), Map.class);
return callMethodResponse(httpsUtils.doGet(targetUrl,map), response);
}
}
/**
* 数据包下载 $$ 数据银行+DMP
* @param targetUrl
* @param param
* @return
*/
private boolean dataBagDownload(String targetUrl,JSONObject param,OpenApiResponse response) {
String fileLocation = param.getString("file_location");
String datasourceId = param.getString("datasourceId");
if (null == fileLocation || null == datasourceId) {
throw new GatewayException(GatewayResultCode.DATA_BIG_ADDR_UNEXIST);
}
JSONObject requestParams = new JSONObject();
requestParams.put("file_location",fileLocation);
requestParams.put("datasourceId",datasourceId);
HttpDownload.postDownload(targetUrl,requestParams);
response.setCode(GatewayResultCode.SUCCESS.getCode());
response.setMsg(GatewayResultCode.SUCCESS.getMsg());
return true;
}
/**
* 数据表查询
*
* @param outputType
* @param targetUrl
* @param param
* @param apiInterface
* @param response
* @return
*/
protected boolean dataTableSelect(String outputType, String targetUrl, Map<String, String> param,
JSONObject jsonParams, ApiInterface apiInterface, OpenApiResponse response) {
ApiInterfaceCustom apiCustomInfo = checkParamLegal(param, apiInterface);
if (ApiInfoOutTypeEnum.FLOW.name().equals(outputType)) {//文件流形式请求
return flowRequestMethod(targetUrl, param, response, apiCustomInfo);
} else if (ApiInfoOutTypeEnum.JSON.name().equals(outputType)) { //json格式请求
response.setAttribute("调用成功!");
response.setMsg(GatewayResultCode.SUCCESS.getMsg());
return jsonRequestMethod(targetUrl, param, jsonParams, response, apiCustomInfo);
} else {
throw new GatewayException(GatewayResultCode.OUTPUT_TYPE_EXCEPTION);
}
}
/**
* 校验参数合法性
*
* @param param
* @param apiInterface
* @return
*/
private ApiInterfaceCustom checkParamLegal(Map<String, String> param, ApiInterface apiInterface) {
ApiInterfaceCustom apiCustomInfo = apiInterfaceService.getApiCustomInfo(apiInterface.getId());
boolean tag = false;
if (null != apiCustomInfo) {
List<Map> mapList = JSONObject.parseArray(apiCustomInfo.getRequestParam(), Map.class);
if (CollectionUtils.isNotEmpty(mapList)) {
for (Map map : mapList) {
if ((Boolean) map.get("required")) {
String name = (String) map.get("name");
String field = param.get(name);
if (null == field) {
tag = true;
}
}
}
if (tag) {
throw new GatewayException(GatewayResultCode.REQUEST_PARAM_EMPTY);
}
}
}
return apiCustomInfo;
}
/**
* 数据查询---flow流请求方式
*
* @param targetUrl
* @param param
* @param response
* @return
*/
private boolean flowRequestMethod(String targetUrl, Map<String, String> param,
OpenApiResponse response, ApiInterfaceCustom apiCustomInfo) {
String dataSize = param.get("dataSize");
Integer valueOf = -1;
if (StringUtils.isNotBlank(dataSize)) {
valueOf = Integer.valueOf(dataSize);
}
String request$Filed =null;
net.sf.json.JSONObject reqParams = net.sf.json.JSONObject.fromObject(param);
try {
request$Filed = URLEncoder.encode(reqParams.toString(), "UTF-8");
} catch (UnsupportedEncodingException e) {
log.error("流下载入参编码异常-------",e.getMessage());
}
JSONObject requestParams = new JSONObject();
requestParams.put("datasourceId",apiCustomInfo.getEsDataSource());
requestParams.put("query_database",apiCustomInfo.getEsDataBase());
requestParams.put("query_table",apiCustomInfo.getEsTable());
requestParams.put("request_fileds",request$Filed);
requestParams.put("response_fields",assembleResponseParams(apiCustomInfo.getResponseParam()));
requestParams.put("data_size",valueOf);
HttpDownload.postDownload(targetUrl,requestParams);
response.setCode(GatewayResultCode.SUCCESS.getCode());
/*String respResult = httpsUtils.doGet(targetUrl, param);
JSONObject resp = JSONObject.parseObject(respResult);
if (null != resp && 200 == resp.getInteger("code")) {
response.setMsg(GatewayResultCode.SUCCESS.getMsg());
return true;
}
/**
* 数据查询--json请求方式
*
* @param targetUrl
* @param param
* @param response
* @param apiCustomInfo
* @return
*/
private boolean jsonRequestMethod(String targetUrl, Map<String, String> param, JSONObject jsonParams,
OpenApiResponse response, ApiInterfaceCustom apiCustomInfo) {
JSONObject params = new JSONObject();
try {
params.put("datasourceId", apiCustomInfo.getEsDataSource());//数据源id
params.put("query_database", apiCustomInfo.getEsDataBase());//数据源库名称
params.put("query_table", apiCustomInfo.getEsTable());//数据源库表
net.sf.json.JSONObject reqParams = net.sf.json.JSONObject.fromObject(param);
params.put("request_fileds", reqParams);//请求参数
params.put("response_fields", assembleResponseParams(apiCustomInfo.getResponseParam()));//响应参数
params.put("is_test",jsonParams.get("is_test"));//是否是测试
Integer pageNum = jsonParams.getInteger("page_num");
Integer pageSize = jsonParams.getInteger("page_size");
params.put("page_size", apiCustomInfo.getPageRow());
params.put("page_num", 1);
if (null != pageNum) {
params.put("page_num", pageNum);
}
if (null != pageSize) {
params.put("page_size", pageSize);
}
} catch (Exception ex) {
log.error("数据转换异常:{}", ex.getMessage());
ex.printStackTrace();
}
String respResult = httpsUtils.submitPost(targetUrl, params.toString());
return callMethodResponse(respResult, response);
}
/**
* 组装响应参数
*
* @param respParams
* @return
*/
private String assembleResponseParams(String respParams) {
StringBuilder builder = new StringBuilder();
List<Map> mapList = JSONObject.parseArray(respParams, Map.class);
if (CollectionUtils.isNotEmpty(mapList)) {
for (Map map : mapList) {
String name = (String) map.get("name");
builder.append(name).append(LoggingConstants.SEP);
}
}
return builder.substring(0, builder.length() - 1);
}
/**
* 调用方法处理结果
*
* @param result
* @param response
*/
private boolean callMethodResponse(String result, OpenApiResponse response) {
if (null == result) {
throw new GatewayException(GatewayResultCode.DISTANCE_REQUEST_EXCEPTION);
}
JSONObject resp = JSONObject.parseObject(result);
if (null != resp && "ESC00000".equals(resp.getString("return_code"))) {
response.setCode(GatewayResultCode.SUCCESS.getCode());
response.setMsg(GatewayResultCode.SUCCESS.getMsg());
response.setAttribute(resp.getString("data"));
response.setAttribute(resp);
return true;
} else {
log.error("~~~~~~~~~~~~~~~~远程请求异常~~~~~~~~~~~~~~~~~");
throw new GatewayException(GatewayResultCode.DISTANCE_REQUEST_EXCEPTION);
}*/
} else {
throw new GatewayException(GatewayResultCode.OUTPUT_TYPE_EXCEPTION);
}
return false;
}
/**
* 通知扣款
*
......@@ -198,7 +391,7 @@ public class ApiQueryService extends ApiParamVerify implements OpenApiService {
jsonReq.put("userId", userId);
jsonReq.put("dataPrice", dataPrice);
jsonReq.put("callStatus", bResult);//true 调用成功 扣款 false 调用失败,解冻金额
String responseResult = httpsUtils.submitPost(balanceUrl+"/mall/financeCustomerAssets/unfreezeMoney", jsonReq.toString());
String responseResult = httpsUtils.submitPost(balanceUrl + "/mall/financeCustomerAssets/unfreezeMoney", jsonReq.toString());
JSONObject paramsResult = JSONObject.parseObject(responseResult);
if (null != paramsResult) {
if (200 != paramsResult.getInteger("code")) {
......
package com.jz.dm.service.request;
import com.alibaba.fastjson.JSONObject;
import com.jz.common.utils.RedisUtils;
import com.jz.dm.common.enums.GatewayResultCode;
import com.jz.dm.common.enums.apiInterface.ApiInfoOutTypeEnum;
import com.jz.dm.common.exception.GatewayException;
import com.jz.dm.common.util.OpenApiRequest;
import com.jz.dm.common.util.OpenApiResponse;
import com.jz.dm.gateway.OpenApiService;
import com.jz.dm.models.domian.ApiInterface;
import com.jz.dm.service.ApiInterfaceService;
import com.jz.dm.web.annotation.AccessLimit;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.Map;
/**
* @author ZC
* @PACKAGE_NAME: com.jz.dm.service.request
* @PROJECT_NAME: jz-dm-parent
* @NAME: ApiQueryTestService
* @DATE: 2021-1-25/10:13
* @DAY_NAME_SHORT: 周一
* @Description:
**/
@Service("apiQueryTestService")
@Slf4j
public class ApiQueryTestService extends ApiParamVerify implements OpenApiService {
@Override
public String getOpenApiMethod() {
return "test";
}
@Override
public String getOpenApiVersion() {
return "v1.0.0";
}
@Autowired
private ApiQueryService apiQueryService;
@Resource
private ApiInterfaceService apiInterfaceService;
@Autowired
private RedisUtils redisUtils;
/**
* API测试实现
* @param request
* @param response
*/
@Override
@Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
@AccessLimit(sec = 1,limit = 1000)
public void doService(OpenApiRequest request, OpenApiResponse response) {
JSONObject parameter = JSONObject.parseObject(request.getOpenApiParams());
ApiInterface apiInterface = apiInterfaceService.getApiInfo(request.getApiKey());
verifyApiInterface(apiInterface);
String reqParams = parameter.getString("reqParams");
JSONObject jsonParams = null;
Map paramMap = null;
if (StringUtils.isNotBlank(reqParams)) {
jsonParams = JSONObject.parseObject(reqParams);
paramMap = JSONObject.parseObject(jsonParams.getString("request_fileds"), Map.class);
jsonParams.put("is_test",true);
}
//取出缓存数据
// String redisReqParam = redisUtils.get(request.getApiKey());
String redisReqParam = null;
if (StringUtils.isNotBlank(redisReqParam)) {//redis中存在
//解析出API制作成功时的参数配置
JSONObject jsonObject = JSONObject.parseObject(redisReqParam);
String targetUrl = jsonObject.getString("targetUrl");
String outputType = jsonObject.getString("outputType");
if (StringUtils.isBlank(outputType)) {
outputType = ApiInfoOutTypeEnum.JSON.name();
}
if (StringUtils.isBlank(targetUrl)) {
throw new GatewayException(GatewayResultCode.REQUEST_PARAM_EMPTY);
}
apiQueryService.dataTableSelect(outputType, targetUrl, paramMap,
jsonParams, apiInterface, response);
} else {//不存在查询数据库
apiQueryService.dataTableSelect(apiInterface.getOutputType(),
apiInterface.getTargetUrl(), paramMap, jsonParams, apiInterface, response);
}
}
}
......@@ -69,7 +69,6 @@ public class SystemLogAspect {
}
@Around("aroundAspect()")
public void doAround(ProceedingJoinPoint joinPoint) {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
......@@ -81,8 +80,9 @@ public class SystemLogAspect {
params += JsonUtils.objectToJson(joinPoint.getArgs()[i]) + ";";
}
}
if (StringUtils.isNotBlank(params)){
params= params.substring(0,params.length()-1).split(";")[0];;
if (StringUtils.isNotBlank(params)) {
params = params.substring(0, params.length() - 1).split(";")[0];
;
}
//获取请求路径
String url = UrlUtil.getServerUrl(request);
......@@ -95,7 +95,10 @@ public class SystemLogAspect {
String paramsList = jsonObject.getString("openApiParams");
com.alibaba.fastjson.JSONObject jsonParamsList = com.alibaba.fastjson.JSONObject.parseObject(paramsList);
ApiReqLog reqLog = new ApiReqLog();
JSONObject jsonResult =null;
JSONObject jsonResult = null;
Boolean isTest = jsonParamsList.getBoolean("isTest");
//不保存测试数据
if (!isTest) {
try {
reqLog.setRequestIp(ip);
reqLog.setApiKey(jsonObject.getString("apiKey"));
......@@ -104,12 +107,12 @@ public class SystemLogAspect {
reqLog.setRequestUrl(url);
reqLog.setRequestMethod(contextPath);
reqLog.setEncryMode(jsonObject.getString("signType")); //加密方式:MD5,RSA
reqLog.setEncryMode("MD5"); //加密方式暂时写死MD5
//reqLog.setEncryMode("MD5"); //加密方式暂时写死MD5
reqLog.setTransMode(request.getMethod());//传输方式 GET POST
reqLog.setRequestToken(jsonParamsList.getString("authCode"));
reqLog.setRequestStartTime(new Date());
reqLog.setRemark(getServiceMethodDescription(joinPoint));
log.info("请求参数:",reqLog);
log.info("请求参数:", reqLog);
if (null != reqLog) {
apiReqLogMapper.insert(reqLog);
}
......@@ -118,12 +121,13 @@ public class SystemLogAspect {
log.info("around响应结果为{}", jsonResult);
apiLogService.updateLog(reqLog.getId(), jsonResult);
} catch (GatewayException ex) {
log.info("切面处理保存异常信息:{}",ex.getMessage());
log.info("切面处理保存异常信息:{}", ex.getMessage());
apiLogService.updateLog(reqLog.getId(), jsonResult);
}catch (Throwable throwable){
} catch (Throwable throwable) {
throwable.printStackTrace();
}
}
}
/*@Before("beforeAspect()")
public void doBefore(JoinPoint joinPoint) {
//日志信息收集切面
......
......@@ -77,9 +77,16 @@ dmp:
ignoreRedis: true
openapi:
timeout:
default: 5000
max: 5000
default: 10000
max: 10000
#logback日志配置
logging:
config: classpath:logback-dev.xml
level:
com:
zhl:
springbootlogback: off
#流处理配置
windows: #文件流输出地址设置
name: stream
......@@ -95,17 +102,17 @@ sentinel: #sentinel每秒中最大的请求个数
data:
bank:
balanceUrl: http://192.168.1.139:8081 #余额信息url #扣款信通知url
select: #大数据查询请求链接
jsonUrl: http://192.168.1.140:8082/api/data/query/json
flowUrl: http://192.168.1.140:8082/api/data/query/streaming
#token: #dataBank 制作验签
# dataBank: dataBank123
token: #dataBank 制作验签
dataBank: dataBank123
#logback日志配置
logging:
config: classpath:logback-dev.xml
level:
com:
zhl:
springbootlogback: off
......@@ -11,18 +11,21 @@
<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
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="listCallApiInterfaceInfo" resultType="com.jz.dm.models.domian.ApiInterface">
SELECT
ai.*
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
${ew.customSqlSegment}
</select>
<select id="selectDetail" resultType="com.jz.dm.models.domian.ApiInterface">
SELECT ai.*,
aic.request_param AS requestParam,
......@@ -40,5 +43,35 @@
AND ai.api_key =#{apiKey}
</select>
<select id="listApiIssueService" resultType="com.jz.dm.models.dto.ApiServiceApplyDto">
SELECT ai.api_key AS apiId,
ai.api_name AS apiName,
ai.api_type AS apiType,
ai.output_type AS outputType,
ai.req_type AS reqType,
ai.api_function AS apiFunction,
aic.max_row AS maxRow,
aic.page_row AS pageRow,
aic.is_send_bank AS isSendBank
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
${ew.customSqlSegment}
</select>
<select id="listApiAuthService" resultType="com.jz.dm.models.dto.ApiServiceApplyDto">
SELECT ai.api_key AS apiId,
ai.api_name AS apiName,
ai.api_type AS apiType,
ai.output_type AS outputType,
ai.req_type AS reqType,
ai.api_function AS apiFunction,
aic.max_row AS maxRow,
aic.page_row AS pageRow,
au.auth_code AS authCode
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
JOIN t_api_auth AS au ON au.api_interface_id = ai.id AND aic.is_deleted =0
${ew.customSqlSegment}
</select>
</mapper>
\ No newline at end of file
......@@ -27,15 +27,14 @@ public class ApiReqTest extends SpringTestCase {
public void TestGatewayReq() {
JSONObject jsonObject = new JSONObject();
jsonObject.put("apiKey", "sE862E97j7Yzo049");
jsonObject.put("apiKey", "8trDpp4WRl92850o");
jsonObject.put("method", "query");
jsonObject.put("signType", "MD5");
long time = System.currentTimeMillis();
jsonObject.put("timestamp", String.valueOf(time));
JSONObject params = new JSONObject();
params.put("authCode", "202100000001118191258T718d78591J");
params.put("selectType", "10006");
params.put("authCode", "2021000000011118104856J1QR4u9Afm");
params.put("reqParams", new JSONObject());
jsonObject.put("params",params);
try {
......@@ -44,7 +43,7 @@ public class ApiReqTest extends SpringTestCase {
String signType = jsonObject.getString("signType");
String signature = MapUtil.getSignValue(apiKey, method, signType);
String salt = Md5.encrypt(signature, "33tgT3g2");
String salt = Md5.encrypt(signature, "7330lQl2");
jsonObject.put("sign", salt);
String response = httpsUtils.submitPost(url, jsonObject.toString());
System.out.println(response);
......
......@@ -2,10 +2,8 @@ package com.jz.dm.gateway.org;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.jz.common.utils.Result;
import com.jz.dm.common.enums.auth.AuthTypeEnum;
import com.jz.dm.gateway.SpringTestCase;
import com.jz.dm.models.domian.ApiOrg;
import com.jz.dm.models.req.organizationManage.OrganizationManageAddReq;
import com.jz.dm.models.req.organizationManage.OrganizationManageDetailQueryReq;
import com.jz.dm.models.req.organizationManage.OrganizationManageListQueryReq;
import com.jz.dm.service.OrganizationManageService;
......@@ -53,7 +51,7 @@ public class TestOrganizationManage extends SpringTestCase {
*/
@Test
public void addOrg(){
OrganizationManageAddReq req = new OrganizationManageAddReq();
/* OrganizationManageAddReq req = new OrganizationManageAddReq();
req.setOrgName("数据银行");
req.setOrgDesc("粗这次");
req.setOrgCnName("databank");
......@@ -62,7 +60,7 @@ public class TestOrganizationManage extends SpringTestCase {
req.setOrgPhone("18279668524");
req.setOrgType(AuthTypeEnum.DATA_BANK_AUTH.name());
Result result = organizationManageService.add(req);
System.out.println(result.getMessage());
System.out.println(result.getMessage());*/
}
/**
......
......@@ -2,7 +2,7 @@ package com.jz.dm.gateway.orther;
import com.jz.dm.common.util.RedisSerializableUtil;
import com.jz.dm.gateway.SpringTestCase;
import com.jz.dm.models.req.make.MakeDataBankApiReq;
import com.jz.dm.models.req.producer.MakeDataBankApiReq;
import net.sf.json.JSONObject;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
......@@ -43,10 +43,10 @@ public class TestRedisUserSave extends SpringTestCase {
bankApiReq.setSignType("MD5");
bankApiReq.setJoinType("10004");
bankApiReq.setOutputType("JSON");
bankApiReq.setPage(false);
//bankApiReq.setPage(false);
bankApiReq.setReqType("DAY");
bankApiReq.setTargetUrl("www.baidu.com");
bankApiReq.setFileId(1L);
//bankApiReq.setFileId(1L);
bankApiReq.setSign("F2A8E3CFE528D6AE5C5B075046653F3E");
bankApiReq.setReqFrequency(0L);
bankApiReq.setApiDesc("4444");
......
package com.jz.dm.gateway.orther;
import com.alibaba.fastjson.JSONObject;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
/**
* @ClassName:
* @Author: Carl
......@@ -8,10 +14,89 @@ package com.jz.dm.gateway.orther;
*/
public class TestStr {
public static void main(String[] args) {
String str = "/picture/logo/T6gxlv137nFA555z.jpg";
// String[] split = str.split("\\/");
System.out.println(str.substring(0, str.lastIndexOf("/") + 1));
String substring = str.substring(str.lastIndexOf("."));
System.out.println(substring);
Calendar cal = Calendar.getInstance();
/* int year =cal.get(Calendar.YEAR)+1;
int month=cal.get(Calendar.MONTH)+1;
cal.add(Calendar.MONTH, 0);*/
//Date date = cal.getTime(); //结果
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
cal.set(Calendar.YEAR,cal.get(Calendar.YEAR)+2);
Date date=cal.getTime();
System.out.println( sdf.format(date));
//String stereo = "000101";
// Integer valueOf = Integer.valueOf(stereo);
// System.out.println(valueOf);
}
public void resolveParameter(){
String str ="[{\"name\":\"flelds1\",\"bindName\":\"flelds1\",\"type\":\"BIGINT\",\"sampleValue\":\"1\",\"defaultValue\":\"1\",\"required\":true,\"desc\":\"\"},{\"name\":\"flelds2\",\"bindName\":\"flelds2\",\"type\":\"BIGINT\",\"sampleValue\":\"1\",\"defaultValue\":\"1\",\"required\":true,\"desc\":\"\"}]";
String str2="[{\"name\":\"field1\",\"bindName\":\"field1\",\"type\":\"STRING\",\"sampleValue\":\"1\",\"desc\":\"\"},{\"name\":\"field2\",\"bindName\":\"field2\",\"type\":\"BIGINT\",\"sampleValue\":\"1\",\"desc\":\"\"},{\"name\":\"field3\",\"bindName\":\"field3\",\"type\":\"BIGINT\",\"sampleValue\":\"1\",\"desc\":\"\"},{\"name\":\"field4\",\"bindName\":\"field4\",\"type\":\"STRING\",\"sampleValue\":\"1\",\"desc\":\"\"}]";
List<Map> maps = JSONObject.parseArray(str2, Map.class);
for (Map map : maps) {
System.out.println("map:"+map);
}
}
/**
* 获取集合信息
*/
public static void getList() {
List<String> list1 = new ArrayList<String>();
list1.add("1");
list1.add("2");
list1.add("3");
list1.add("4");
list1.add("5");
List<String> list2 = new ArrayList<String>();
list2.add("1");
list2.add("2");
list2.add("3");
list2.add("4");
list2.add("5");
list2.add("7");
list2.add("9");
// 交集
List<String> intersection = list1.stream().filter(item -> list2.contains(item)).collect(Collectors.toList());
System.out.println("---交集 intersection---");
intersection.parallelStream().forEach(System.out::println);
// 差集 (list1 - list2)
List<String> reduce1 = list1.stream().filter(item -> !list2.contains(item)).collect(Collectors.toList());
System.out.println("---差集 reduce1 (list1 - list2)---");
reduce1.parallelStream().forEach(System.out::println);
// 差集 (list2 - list1)
List<String> reduce2 = list2.stream().filter(item -> !list1.contains(item)).collect(Collectors.toList());
System.out.println("---差集 reduce2 (list2 - list1)---");
reduce2.parallelStream().forEach(System.out::println);
//合拼差
reduce1.addAll(reduce2);
System.out.println("---合拼差 reduce1 (list2 -> list1)---");
reduce1.parallelStream().forEach(System.out::println);
// 并集
List<String> listAll = list1.parallelStream().collect(Collectors.toList());
List<String> listAll2 = list2.parallelStream().collect(Collectors.toList());
listAll.addAll(listAll2);
System.out.println("---并集 listAll---");
listAll.parallelStream().forEachOrdered(System.out::println);
// 去重并集
List<String> listAllDistinct = listAll.stream().distinct().collect(Collectors.toList());
System.out.println("---得到去重并集 listAllDistinct---");
listAllDistinct.parallelStream().forEachOrdered(System.out::println);
System.out.println("---原来的List1---");
list1.parallelStream().forEachOrdered(System.out::println);
System.out.println("---原来的List2---");
list2.parallelStream().forEachOrdered(System.out::println);
}
}
......@@ -3,7 +3,7 @@ package com.jz.dm.gateway.orther;
import com.jz.dm.gateway.SpringTestCase;
import lombok.extern.slf4j.Slf4j;
import static com.jz.dm.common.util.stream.HttpDownload.download;
import static com.jz.dm.common.util.stream.HttpDownload.getDownload;
/**
* @author ZC
......@@ -21,6 +21,6 @@ public class TestStreamReq extends SpringTestCase {
//@Test
public void testStreamReq() {
download(baseUrl);
getDownload(baseUrl);
}
}
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