Commit 3ebf5915 authored by zhangc's avatar zhangc

commit

parent 3bc31923
......@@ -45,9 +45,6 @@ public enum GatewayResultCode implements ResultCode {
/** 请求超过限制 */
RATE_LIMIT_EXCEEDED("RATE_LIMIT_EXCEEDED", "请求超过限制"),
/** 无效路由类型 */
ILLEGAL_ROUTE_TYPE("ILLEGAL_ROUTE_TYPE", "无效路由类型"),
/** 提交数据过大 */
POST_DATA_TOO_LARGE("POST_DATA_TOO_LARGE", "提交数据过大"),
......
......@@ -74,4 +74,15 @@ public class ApiInterfaceController {
@RequestParam (name="apiKey")String apiKey) {
return Mono.fromSupplier(() -> apiInterfaceService.dmpDeleteAuth(type,apiKey));
}
/**
* @Description:API测试调用
* @return: DMP-API删除
* @Author: Mr.zhang
* @Date: 2020-12-24
*/
@ApiOperation("API调用测试接口")
@PostMapping(value = "/apiTestApiInterface")
public Mono<Result> apiTestApiInterface(@RequestParam (name="apiKey")String apiKey) {
return Mono.fromSupplier(() -> apiInterfaceService.apiTestInterface(apiKey));
}
}
package com.jz.dm.filter;
import com.alibaba.fastjson.JSONObject;
import com.jz.dm.common.constant.Constants;
import com.jz.dm.common.enums.Format;
import com.jz.dm.common.enums.GatewayResultCode;
......@@ -9,7 +8,6 @@ import com.jz.dm.common.exception.GatewayException;
import com.jz.dm.common.util.StringUtil;
import com.jz.dm.models.enity.GatewayRequest;
import com.jz.dm.models.enity.GatewayResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/**
......@@ -30,68 +28,31 @@ public class CheckArgsFilter extends AbstractFilter {
return "CheckArgsFilter";
}
@Value("${apiRequest.testExample.apiKey}")
private String testApiKey;
@Value("${apiRequest.testExample.sign}")
private String testSign;
@Override
protected void internalDoFilter(GatewayRequest request, GatewayResponse response,
FilterChain chain) {
if (null != request && StringUtil.isNotBlank(request.getParams())) {
JSONObject params = JSONObject.parseObject(request.getParams());
Boolean aBoolean = params.getBoolean("isTest");
if (null == aBoolean){
throw new GatewayException(GatewayResultCode.ILLEGAL_ARGUMENT); //无效参数
}
if (aBoolean) {//如果是测试数据
chain.doFilter(assembleTestData(), response);
} else {
// 校验参数非空
if (StringUtil.isEmpty(request.getApiKey()) || StringUtil.isEmpty(request.getMethod())
|| StringUtil.isEmpty(request.getSignType()) || StringUtil.isEmpty(request.getSign())
|| StringUtil.isEmpty(request.getTimestamp()) || StringUtil.isEmpty(request.getParams())) {
throw new GatewayException(GatewayResultCode.ILLEGAL_ARGUMENT); //无效参数
}
// 设置默认值
if (StringUtil.isEmpty(request.getFormat())) {
request.setFormat(Format.JSON.name());
}
try {
request.setVersion("v1.0.0");
//格式,目前仅支持JSON
Format.valueOf(request.getFormat());
//请求使用的编码格式,如UTF-8,GBK,GB2312等
//Charset.forName(request.getCharset());
//生成签名字符串所使用的签名算法类型
SignType.valueOf(request.getSignType());
} catch (Exception ex) {
//无效参数
throw new GatewayException(GatewayResultCode.ILLEGAL_ARGUMENT);
}
}
chain.doFilter(request, response);
// 校验参数非空
if (StringUtil.isEmpty(request.getApiKey()) || StringUtil.isEmpty(request.getMethod())
|| StringUtil.isEmpty(request.getSignType()) || StringUtil.isEmpty(request.getSign())
|| StringUtil.isEmpty(request.getTimestamp()) || StringUtil.isEmpty(request.getParams())) {
throw new GatewayException(GatewayResultCode.ILLEGAL_ARGUMENT); //无效参数
}
// 设置默认值
if (StringUtil.isEmpty(request.getFormat())) {
request.setFormat(Format.JSON.name());
}
try {
request.setVersion("v1.0.0");
//格式,目前仅支持JSON
Format.valueOf(request.getFormat());
//请求使用的编码格式,如UTF-8,GBK,GB2312等
//Charset.forName(request.getCharset());
//生成签名字符串所使用的签名算法类型
SignType.valueOf(request.getSignType());
} catch (Exception ex) {
//无效参数
throw new GatewayException(GatewayResultCode.ILLEGAL_ARGUMENT);
}
chain.doFilter(request, response);
}
/**
* 组装测试数据
*/
private GatewayRequest assembleTestData() {
GatewayRequest gatewayRequest = new GatewayRequest();
gatewayRequest.setApiKey(testApiKey);
gatewayRequest.setMethod("query");
gatewayRequest.setFormat(Format.JSON.name());
gatewayRequest.setSignType("MD5");
gatewayRequest.setSign(testSign);
gatewayRequest.setTimestamp(System.currentTimeMillis() + "");
gatewayRequest.setVersion("v1.0.0");
JSONObject jsonObject = new JSONObject();
jsonObject.put("authCode","202100000001118191258T718d78591J");
jsonObject.put("isTest",true);
gatewayRequest.setParams(jsonObject.toString());
return gatewayRequest;
}
}
......@@ -4,6 +4,7 @@ import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.jz.dm.models.domian.ApiInterface;
import com.jz.dm.models.domian.ApiInterfaceCustom;
import com.jz.dm.models.req.api.ApiInterfaceDetailReq;
import org.apache.ibatis.annotations.Param;
......@@ -35,4 +36,10 @@ public interface ApiInterfaceMapper extends BaseMapper<ApiInterface> {
ApiInterface selectDetail(ApiInterfaceDetailReq req);
/**
* 获取测试请求数据
* @param apiKey
* @return
*/
ApiInterfaceCustom getTestData(String apiKey);
}
......@@ -75,4 +75,11 @@ public interface ApiInterfaceService {
* @return
*/
Result dmpDeleteAuth(String type,String apiKey);
/**
* api测试接口
* @param apiKey
* @return
*/
Result apiTestInterface(String apiKey);
}
......@@ -5,6 +5,7 @@ import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jz.common.constant.ResultMsg;
import com.jz.common.utils.HttpsUtils;
import com.jz.common.utils.Result;
import com.jz.dm.common.enums.GeneralStatusTypeEnum;
import com.jz.dm.common.enums.apiInterface.ApiStatusEnum;
......@@ -13,10 +14,12 @@ import com.jz.dm.mapper.ApiAuthMapper;
import com.jz.dm.mapper.ApiInterfaceMapper;
import com.jz.dm.models.domian.ApiAuth;
import com.jz.dm.models.domian.ApiInterface;
import com.jz.dm.models.domian.ApiInterfaceCustom;
import com.jz.dm.models.req.api.ApiInterfaceDetailReq;
import com.jz.dm.models.req.api.ApiInterfaceInfoListReq;
import com.jz.dm.service.ApiInterfaceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
......@@ -37,10 +40,17 @@ import java.util.List;
@Slf4j
public class ApiInterfaceServiceImpl implements ApiInterfaceService {
/**
* 测试url
*/
public static final String testUrl ="";
@Resource
private ApiInterfaceMapper apiInterfaceMapper;
@Resource
private ApiAuthMapper apiAuthMapper;
@Autowired
private HttpsUtils httpsUtils;
/**
* 获取API列表信息
......@@ -129,7 +139,7 @@ public class ApiInterfaceServiceImpl implements ApiInterfaceService {
if (ApiStatusEnum.EXPIRY.name().equals(apiInterface.getStatus())) {
return Result.of_error("API已失效无法再次操作!");
}
updateApiAuthStatus(apiKey);
updateApiAuthStatus(apiInterface.getId());
UpdateWrapper<ApiInterface> updateWra = new UpdateWrapper<>();
updateWra.set("status", ApiStatusEnum.EXPIRY);
updateWra.set("is_deleted", 1);
......@@ -144,11 +154,11 @@ public class ApiInterfaceServiceImpl implements ApiInterfaceService {
/**
* 更新已经认证的API
*
* @param apiKey
* @param apiInterfaceId
*/
private void updateApiAuthStatus(String apiKey) {
private void updateApiAuthStatus(Long apiInterfaceId) {
QueryWrapper<ApiAuth> queryWra = new QueryWrapper<>();
queryWra.eq("api_key", apiKey);
queryWra.eq("api_interface_id", apiInterfaceId);
queryWra.eq("handler", 0);//主要是确认单次调用是否调用
queryWra.eq("auth_mode", AuthModeEnum.PERMANENT_TIME_MODE);
queryWra.eq("status", GeneralStatusTypeEnum.VALID);
......@@ -195,6 +205,27 @@ public class ApiInterfaceServiceImpl implements ApiInterfaceService {
return authCall + authDateCall;
}
/**
* api测试接口
*
* @param apiKey
* @return
*/
@Override
public Result apiTestInterface(String apiKey) {
ApiInterfaceCustom apiInterfaceCustom= apiInterfaceMapper.getTestData(apiKey);
if (null == apiInterfaceCustom) {
return Result.of_error(ResultMsg.DATA_NOT_FOUND);
}
/* if (StringUtils.isNotBlank(apiInterfaceCustom.getApiExample())){
httpsUtils.doGet(testUrl,"");
}else {
}*/
return Result.of_success(ResultMsg.SUCCESS);
}
/**
* 获取用户授权信息
*
......
......@@ -13,7 +13,6 @@ import com.jz.dm.common.util.OpenApiRequest;
import com.jz.dm.common.util.OpenApiResponse;
import com.jz.dm.common.util.stream.HttpDownload;
import com.jz.dm.gateway.OpenApiService;
import com.jz.dm.mapper.ApiAuthMapper;
import com.jz.dm.models.domian.ApiAuth;
import com.jz.dm.models.domian.ApiInterface;
import com.jz.dm.service.ApiInterfaceService;
......@@ -56,8 +55,6 @@ public class ApiQueryService extends ApiParamVerify implements OpenApiService {
@Autowired
private ApiInterfaceService apiInterfaceService;
@Autowired
private ApiAuthMapper apiAuthMapper;
@Autowired
private AuthService authService;
@Autowired
private RedisUtils redisUtils;
......@@ -102,16 +99,15 @@ public class ApiQueryService extends ApiParamVerify implements OpenApiService {
JSONObject jsonObject = JSONObject.parseObject(redisReqParam);
String targetUrl = jsonObject.getString("targetUrl");
String outputType = jsonObject.getString("outputType");
bResult = rangRequestTarget(outputType, targetUrl, paramMap, response,false);
bResult = rangRequestTarget(outputType, targetUrl, paramMap, response);
} else {//不存在查询数据库
ApiInterface apiInterface =
apiInterfaceService.getReqTargetInfo(request.getApiKey());
if (null == apiInterface) {
throw new GatewayException(GatewayResultCode.REQUEST_INFO_UNEXIST);
}
Boolean aBoolean = parameter.getBoolean("isTest");
bResult = rangRequestTarget(apiInterface.getOutputType(),
apiInterface.getTargetUrl(), paramMap, response,aBoolean);
apiInterface.getTargetUrl(), paramMap, response);
}
//调用成功请求数据银行扣款
if (AuthModeEnum.POWER_CALL_MODE.name().equals(apiAuth.getAuthMode())) {
......@@ -141,48 +137,34 @@ public class ApiQueryService extends ApiParamVerify implements OpenApiService {
* @param outputType
* @param targetUrl
* @param param
* @param isTest
* @param response
*/
private boolean rangRequestTarget(String outputType, String targetUrl,
Map<String, String> param, OpenApiResponse response,Boolean isTest) {
Map<String, String> param, OpenApiResponse response) {
if (StringUtils.isBlank(outputType)) {
outputType = ApiInfoOutTypeEnum.JSON.name();
}
if (StringUtils.isBlank(targetUrl)) {
throw new GatewayException(GatewayResultCode.ILLEGAL_REQUEST);
}
if (isTest){ //测试数据
String respResult = httpsUtils.doGet(targetUrl, param);
JSONObject resp = JSONObject.parseObject(respResult);
if (null != resp && 200 == resp.getInteger("code")) {
response.setCode(GatewayResultCode.SUCCESS.getCode());
response.setMsg(GatewayResultCode.SUCCESS.getMsg());
response.setAttribute(resp.getString("data"));
return true;
} else {
log.error("~~~~~~~~~~~~~~~~远程请求异常~~~~~~~~~~~~~~~~~");
throw new GatewayException(GatewayResultCode.DISTANCE_REQUEST_EXCEPTION);
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);
}
}else {
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);
response.setCode(GatewayResultCode.SUCCESS.getCode());
response.setMsg(GatewayResultCode.SUCCESS.getMsg());
return true;
} else if (ApiInfoOutTypeEnum.JSON.name().equals(outputType)) { //json格式请求
response.setAttribute("调用成功!");
response.setMsg(GatewayResultCode.SUCCESS.getMsg());
response.setCode(GatewayResultCode.SUCCESS.getCode());
String baseUrl = builder.substring(0, builder.length() - 1);
HttpDownload.download(baseUrl);
response.setCode(GatewayResultCode.SUCCESS.getCode());
response.setMsg(GatewayResultCode.SUCCESS.getMsg());
return true;
} else if (ApiInfoOutTypeEnum.JSON.name().equals(outputType)) { //json格式请求
response.setAttribute("调用成功!");
response.setMsg(GatewayResultCode.SUCCESS.getMsg());
response.setCode(GatewayResultCode.SUCCESS.getCode());
/*String respResult = httpsUtils.doGet(targetUrl, param);
JSONObject resp = JSONObject.parseObject(respResult);
if (null != resp && 200 == resp.getInteger("code")) {
......@@ -194,9 +176,8 @@ public class ApiQueryService extends ApiParamVerify implements OpenApiService {
log.error("~~~~~~~~~~~~~~~~远程请求异常~~~~~~~~~~~~~~~~~");
throw new GatewayException(GatewayResultCode.DISTANCE_REQUEST_EXCEPTION);
}*/
} else {
throw new GatewayException(GatewayResultCode.OUTPUT_TYPE_EXCEPTION);
}
} else {
throw new GatewayException(GatewayResultCode.OUTPUT_TYPE_EXCEPTION);
}
return false;
}
......
......@@ -55,10 +55,10 @@ public class SystemLogAspect {
/* //前置通知切入点
@Pointcut("@annotation(com.jz.dm.web.annotation.ApiLogAspect)")
public void beforeAspect() {
}
}*/
//最终通知切入点
@Pointcut("@annotation(com.jz.dm.web.annotation.ApiLogAspect)")
/* @Pointcut("@annotation(com.jz.dm.web.annotation.ApiLogAspect)")
public void lastAspect() {
}*/
......@@ -81,8 +81,7 @@ public class SystemLogAspect {
}
}
if (StringUtils.isNotBlank(params)){
params= params.substring(0,params.length()-1);
params= params.split(";")[0];
params= params.substring(0,params.length()-1).split(";")[0];;
}
//获取请求路径
String url = UrlUtil.getServerUrl(request);
......@@ -94,7 +93,7 @@ public class SystemLogAspect {
com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(params);
String paramsList = jsonObject.getString("openApiParams");
com.alibaba.fastjson.JSONObject jsonParamsList = com.alibaba.fastjson.JSONObject.parseObject(paramsList);
try {
try {
ApiReqLog reqLog = new ApiReqLog();
reqLog.setRequestIp(ip);
reqLog.setApiKey(jsonObject.getString("apiKey"));
......@@ -102,7 +101,7 @@ public class SystemLogAspect {
reqLog.setResponseParams("");//响应参数
reqLog.setRequestUrl(url);
reqLog.setRequestMethod(contextPath);
// reqLog.setEncryMode(jsonObject.getString("signType")); //加密方式:MD5,RSA
reqLog.setEncryMode(jsonObject.getString("signType")); //加密方式:MD5,RSA
reqLog.setEncryMode("MD5"); //加密方式暂时写死MD5
reqLog.setTransMode(request.getMethod());//传输方式 GET POST
reqLog.setRequestToken(jsonParamsList.getString("authCode"));
......@@ -168,39 +167,39 @@ public class SystemLogAspect {
* 返回异常通知,返回抛出异常的时候执行的通知,可以获得返回的异常
* 可以访问到异常对象,且可以指定在出现特定异常的时候再执行通知代码
*/
/*@AfterReturning(value = "lastAspect()", returning = "result")
public void afterReturn(JoinPoint joinPoint, Object result) {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
.getRequest();
log.info("~~~~~~~~~~~~~~~~~~~~~~最终通知执行~~~~~~~~~~~~~~~~~~~~~~~~");
String classType = joinPoint.getTarget().getClass().getName();
try {
Class<?> clazz = Class.forName(classType);
String clazzName = clazz.getName();
// 拦截的方法名称。当前正在执行的方法
String methodName = joinPoint.getSignature().getName();
// 获取方法的参数
Object[] args = joinPoint.getArgs();
// 获取传入参数的键值对
Map<String, Object> map = (Map<String, Object>)
getFieldsName(this.getClass(), clazzName, methodName,
args);
// 将request中的参数转化为键值对,方便取出
// Map<String, Object> requestMap = (Map<String, Object>) map.get("request");
// 获取返回方法的参数
JSONObject jsonObject = JSONObject.fromObject(result);
Map mapResult = (Map) jsonObject;
//将返回的result参数取出
Map<String, Object> res = (Map<String, Object>) mapResult.get("data");
Integer id = (Integer) res.get("id");
JSONObject data = jsonObject.getJSONObject("data");
// apiLogService.updateLog(id.longValue(), data);
} catch (Exception e) {
log.error("~~~~~~~~~~~~~~~~~~~~~~~最终通知异常~~~~~~~~~~~~~~~~~~~~~~~");
log.error("异常信息{}", e.getMessage());
}
}*/
//@AfterReturning(value = "lastAspect()", returning = "result")
//public void afterReturn(JoinPoint joinPoint, Object result) {
// HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
// .getRequest();
// log.info("~~~~~~~~~~~~~~~~~~~~~~最终通知执行~~~~~~~~~~~~~~~~~~~~~~~~");
// String classType = joinPoint.getTarget().getClass().getName();
// try {
// Class<?> clazz = Class.forName(classType);
// String clazzName = clazz.getName();
// // 拦截的方法名称。当前正在执行的方法
// String methodName = joinPoint.getSignature().getName();
// // 获取方法的参数
// Object[] args = joinPoint.getArgs();
// // 获取传入参数的键值对
// Map<String, Object> map = (Map<String, Object>)
// getFieldsName(this.getClass(), clazzName, methodName,
// args);
// // 将request中的参数转化为键值对,方便取出
// // Map<String, Object> requestMap = (Map<String, Object>) map.get("request");
// // 获取返回方法的参数
// JSONObject jsonObject = JSONObject.fromObject(result);
// Map mapResult = (Map) jsonObject;
// //将返回的result参数取出
// Map<String, Object> res = (Map<String, Object>) mapResult.get("data");
// Integer id = (Integer) res.get("id");
// JSONObject data = jsonObject.getJSONObject("data");
// // apiLogService.updateLog(id.longValue(), data);
// } catch (Exception e) {
// log.error("~~~~~~~~~~~~~~~~~~~~~~~最终通知异常~~~~~~~~~~~~~~~~~~~~~~~");
// log.error("异常信息{}", e.getMessage());
// }
// }
/**
* 获取注解中对方法的描述信息 用于service层注解
......
......@@ -32,6 +32,13 @@
LEFT JOIN t_api_interface_custom AS aic ON ai.id = aic.api_interface_id AND aic.is_deleted =0
WHERE ai.id =#{id}
</select>
<select id="getTestData" resultType="com.jz.dm.models.domian.ApiInterfaceCustom">
SELECT aic.*
FROM t_api_interface AS ai
JOIN t_api_interface_custom AS aic ON ai.id =aic.api_interface_id AND aic.is_deleted =0
WHERE ai.is_deleted = 0
AND ai.api_key =#{apiKey}
</select>
</mapper>
\ No newline at end of file
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