提交 bbe13e5e authored 作者: mry's avatar mry

feat(web): swagger解析中,增加了参数的解析

上级 e28c911f
package org.matrix.autotest.controller;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.Swagger;
import org.matrix.autotest.swaggerEntity.*;
import org.matrix.database.entity.Environment;
import org.matrix.database.entity.InterfaceInformation;
import org.matrix.database.entity.Parameter;
import org.matrix.database.service.IEnvironmentService;
import org.matrix.database.vo.CommonPage;
import org.matrix.exception.GlobalException;
......@@ -20,10 +26,7 @@ import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
......@@ -42,6 +45,304 @@ public class SwaggerController {
this.environmentService = environmentService;
}
/**
* 解析所有的接口
*
* @param swaggerJson swagger中的json数据
* @return 封装好的接口信息
*/
public static List<PathInfoVo> getPathInfo(JSONObject swaggerJson) {
Long i = 0L;
JSONObject paths = swaggerJson.getJSONObject("paths");
String host = String.valueOf(swaggerJson.get("host"));
String basePath = String.valueOf(swaggerJson.get("basePath"));
List<PathInfoVo> list = new ArrayList<>();
//所有的definitions
Map<String, JSONObject> refMap = getDefinitions(swaggerJson);
if (paths != null) {
for (Map.Entry<String, Object> stringObjectEntry : paths.entrySet()) {
PathInfoVo pathInfo = new PathInfoVo();
String pathUrl = stringObjectEntry.getKey();
//请求方式
JSONObject pathJson = paths.getJSONObject(pathUrl);
Set<String> methodSets = pathJson.keySet();
if (CollectionUtils.isNotEmpty(methodSets)) {
for (String httpMethod : methodSets) {
pathInfo.setId(i++);
pathInfo.setPathUrl(pathUrl);
pathInfo.setHttpMethod(httpMethod);
JSONObject methodJson = pathJson.getJSONObject(httpMethod);
String summary = methodJson.getString("summary");
String tags = methodJson.getString("tags");
String description = methodJson.getString("description");
pathInfo.setDescription(description);
pathInfo.setTags(tags);
pathInfo.setSummary(summary);
JSONArray parameters = methodJson.getJSONArray("parameters");
JSONObject responses = methodJson.getJSONObject("responses");
List<ParameterVo> reqParameters = getParameter(parameters, refMap);
pathInfo.setReqList(reqParameters);
List<ResponseVo> respList = getResponse(responses, refMap);
pathInfo.setRespList(respList);
pathInfo.setHost(host);
pathInfo.setBasePath(basePath);
}
}
list.add(pathInfo);
}
}
return list;
}
/**
* 解析响应数据
*
* @param responses 响应参数
* @param refMap 所有的definitions
* @return 封装好的响应数据
*/
public static List<ResponseVo> getResponse(JSONObject responses, Map<String, JSONObject> refMap) {
List<ResponseVo> respParameters = new ArrayList<>();
if (responses != null && responses.containsKey("200")) {
//只解析200的数据
JSONObject successJson = responses.getJSONObject("200");
if (successJson.containsKey("schema")) {
JSONObject schema = successJson.getJSONObject("schema");
String schemaType = schema.getString("type");
String ref = "";
if (schema.containsKey("$ref")) {
ref = schema.getString("$ref");
}
if ("array".equalsIgnoreCase(schemaType)) {
JSONObject items = schema.getJSONObject("items");
if (items.containsKey("$ref")) {
ref = schema.getString("$ref");
} else {
ResponseVo resp = new ResponseVo();
resp.setName("");
resp.setType(items.getString("type"));
respParameters.add(resp);
}
}
if (StringUtils.isNotBlank(ref)) {
String def = ref.substring(14);
JSONObject defJson = refMap.get(def);
JSONObject properties = defJson.getJSONObject("properties");
Set<String> respKeys = properties.keySet();
for (String key : respKeys) {
JSONObject respMap = properties.getJSONObject(key);
ResponseVo resp = new ResponseVo();
resp.setName(key);
resp.setDescription(respMap.getString("description"));
String respType = respMap.getString("type");
resp.setType(StringUtils.isBlank(respType) ? "object" : respType);
resp.setRequired(respMap.getBooleanValue("required"));
if (respMap.containsKey("$ref")) {
String childRef = respMap.getString("$ref");
String childDef = childRef.substring(14);
JSONObject childDefJson = refMap.get(childDef);
JSONObject childProperties = childDefJson.getJSONObject("properties");
getRef(refMap, childProperties, resp, childDef, childDefJson);
} else if ("array".equalsIgnoreCase(respType)) {
JSONObject items = respMap.getJSONObject("items");
if (items.containsKey("$ref")) {
String itemRef = items.getString("$ref");
String itemDef = itemRef.substring(14);
JSONObject itemDefJson = refMap.get(itemDef);
JSONObject childProperties = itemDefJson.getJSONObject("properties");
getRef(refMap, childProperties, resp, itemDef, itemDefJson);
}
}
respParameters.add(resp);
}
}
}
}
return respParameters;
}
/**
* 递归响应数据
*
* @param refMap 所有的definitions
* @param parentVoName 上级ref的名称,与上级相同不继续递归(树结构)
* @return 封装好的响应数据
*/
public static List<ResponseVo> getRef(Map<String, JSONObject> refMap, JSONObject childProperties, ResponseVo parentResp, String parentVoName, JSONObject childJson) {
Set<String> childSet = childProperties.keySet();
List<ResponseVo> childResp = new ArrayList<>();
for (String key : childSet) {
JSONObject childMap = childProperties.getJSONObject(key);
ResponseVo resp = new ResponseVo();
resp.setName(key);
resp.setDescription(childMap.getString("description"));
String childType = childMap.getString("type");
resp.setType(StringUtils.isNotBlank(childType) ? childType : childJson.getString("type"));
resp.setRequired(childMap.getBooleanValue("required"));
childResp.add(resp);
parentResp.setChildResp(childResp);
if (childMap.containsKey("$ref")) {
String childRef = childMap.getString("$ref");
String childDef = childRef.substring(14);
JSONObject childDefJson = refMap.get(childDef);
JSONObject pro = childDefJson.getJSONObject("properties");
//additionalProperties
if (pro != null && !childDef.equalsIgnoreCase(parentVoName)) {
getRef(refMap, pro, resp, childDef, childDefJson);
}
} else if ("array".equalsIgnoreCase(childType)) {
JSONObject items = childMap.getJSONObject("items");
if (items.containsKey("$ref")) {
String itemRef = items.getString("$ref");
String itemDef = itemRef.substring(14);
JSONObject itemDefJson = refMap.get(itemDef);
JSONObject pro = itemDefJson.getJSONObject("properties");
if (pro != null && !itemDef.equalsIgnoreCase(parentVoName)) {
getRef(refMap, pro, resp, itemDef, itemDefJson);
}
}
}
}
return childResp;
}
/**
* 解析请求参数
*
* @param parameters 参数
* @param refMap 所有的definitions
* @return 封装好的参数信息
*/
public static List<ParameterVo> getParameter(JSONArray parameters, Map<String, JSONObject> refMap) {
List<ParameterVo> reqParameters = new ArrayList<>();
if (CollectionUtils.isNotEmpty(parameters)) {
for (int i = 0; i < parameters.size(); i++) {
JSONObject paramJson = parameters.getJSONObject(i);
ParameterVo param = JSON.parseObject(JSON.toJSONString(paramJson), ParameterVo.class);
if (paramJson.containsKey("schema")) {
JSONObject schema = paramJson.getJSONObject("schema");
String schemaType = schema.getString("type");
String ref = "";
if (schema.containsKey("$ref")) {
ref = schema.getString("$ref");
}
if ("array".equalsIgnoreCase(schemaType)) {
JSONObject items = schema.getJSONObject("items");
if (items.containsKey("$ref")) {
ref = schema.getString("$ref");
} else {
List<ParameterVo> childParamList = new ArrayList<>();
ParameterVo childParam = new ParameterVo();
childParam.setName("");
childParam.setType(items.getString("type"));
childParamList.add(childParam);
param.setChildParam(childParamList);
}
} else {
param.setType(schemaType);
}
if (StringUtils.isNotBlank(ref)) {
String def = ref.substring(14);
JSONObject defJson = refMap.get(def);
if (defJson != null) {
param.setType(defJson.getString("type"));
JSONObject properties = defJson.getJSONObject("properties");
Set<String> propertiesSet = properties.keySet();
List<ParameterVo> childParamList = new ArrayList<>();
for (String key : propertiesSet) {
ParameterVo childParam = new ParameterVo();
childParam.setName(key);
JSONObject proMap = properties.getJSONObject(key);
//根据type判断是否是array
String type = proMap.getString("type");
childParam.setDescription(StringUtils.isNotBlank(proMap.getString("description")) ? proMap.getString("description") : "");
childParam.setType(StringUtils.isBlank(type) ? "object" : type);
childParam.setRequired(proMap.getBooleanValue("required"));
if (proMap.containsKey("$ref")) {
String childRef = proMap.getString("$ref");
String childDef = childRef.substring(14);
JSONObject childDefJson = refMap.get(childDef);
JSONObject childProperties = childDefJson.getJSONObject("properties");
if (childProperties != null) {
getParamRef(refMap, childProperties, childParam, childDef, childDefJson);
}
} else if ("array".equalsIgnoreCase(type)) {
JSONObject items = proMap.getJSONObject("items");
if (items.containsKey("$ref")) {
String itemRef = items.getString("$ref");
String itemDef = itemRef.substring(14);
JSONObject itemDefJson = refMap.get(itemDef);
JSONObject pro = itemDefJson.getJSONObject("properties");
if (pro != null) {
getParamRef(refMap, pro, childParam, itemDef, itemDefJson);
}
}
}
childParamList.add(childParam);
param.setChildParam(childParamList);
}
}
}
}
reqParameters.add(param);
}
}
return reqParameters;
}
public static void getParamRef(Map<String, JSONObject> refMap, JSONObject childProperties, ParameterVo parentResp, String parentVoName, JSONObject childJson) {
List<ParameterVo> paramList = new ArrayList<>();
Set<String> childSet = childProperties.keySet();
for (String key : childSet) {
JSONObject childMap = childProperties.getJSONObject(key);
ParameterVo resp = new ParameterVo();
resp.setName(key);
resp.setDescription(childMap.getString("description"));
String childType = childMap.getString("type");
resp.setType(StringUtils.isNotBlank(childType) ? childType : childJson.getString("type"));
resp.setRequired(childMap.getBooleanValue("required"));
paramList.add(resp);
parentResp.setChildParam(paramList);
if (childMap.containsKey("$ref")) {
String childRef = childMap.getString("$ref");
String childDef = childRef.substring(14);
JSONObject childDefJson = refMap.get(childDef);
JSONObject pro = childDefJson.getJSONObject("properties");
//additionalProperties
if (pro != null && !childDef.equalsIgnoreCase(parentVoName)) {
getParamRef(refMap, pro, resp, childDef, childDefJson);
}
} else if ("array".equalsIgnoreCase(childType)) {
JSONObject items = childMap.getJSONObject("items");
if (items.containsKey("$ref")) {
String itemRef = items.getString("$ref");
String itemDef = itemRef.substring(14);
JSONObject itemDefJson = refMap.get(itemDef);
JSONObject pro = itemDefJson.getJSONObject("properties");
if (pro != null && !itemDef.equalsIgnoreCase(parentVoName)) {
getParamRef(refMap, pro, resp, itemDef, itemDefJson);
}
}
}
}
}
/**
* 获取所有的关联参数对象
*
* @param swaggerJson swagger的json信息
* @return 所有的definitions
*/
public static Map<String, JSONObject> getDefinitions(JSONObject swaggerJson) {
Map<String, JSONObject> map = new HashMap<>();
JSONObject definitions = swaggerJson.getJSONObject("definitions");
Set<String> definitionSet = definitions.keySet();
for (String def : definitionSet) {
map.put(def, definitions.getJSONObject(def));
}
return map;
}
/**
* 读取swagger地址里的JSON信息
*
......@@ -75,10 +376,10 @@ public class SwaggerController {
* @param list 查询的集合
* @return 模糊查询的结果
*/
public List<InterfaceInformation> tagSearch(String name, List<InterfaceInformation> list) {
@SuppressWarnings(value = "all") List<InterfaceInformation> results = new ArrayList();
public List<PathInfoVo> tagSearch(String name, List<PathInfoVo> list) {
@SuppressWarnings(value = "all") List<PathInfoVo> results = new ArrayList();
Pattern pattern = Pattern.compile(name, Pattern.CASE_INSENSITIVE);
for (InterfaceInformation o : list) {
for (PathInfoVo o : list) {
Matcher matcher = pattern.matcher(o.getTags());
if (matcher.find()) {
results.add(o);
......@@ -94,10 +395,10 @@ public class SwaggerController {
* @param list 查询的集合
* @return 模糊查询的结果
*/
public List<InterfaceInformation> nameSearch(String name, List<InterfaceInformation> list) {
@SuppressWarnings(value = "all") List<InterfaceInformation> results = new ArrayList();
public List<PathInfoVo> nameSearch(String name, List<PathInfoVo> list) {
@SuppressWarnings(value = "all") List<PathInfoVo> results = new ArrayList();
Pattern pattern = Pattern.compile(name, Pattern.CASE_INSENSITIVE);
for (InterfaceInformation o : list) {
for (PathInfoVo o : list) {
Matcher matcher = pattern.matcher(o.getSummary());
if (matcher.find()) {
results.add(o);
......@@ -113,11 +414,11 @@ public class SwaggerController {
* @param list 查询的集合
* @return 模糊查询的结果
*/
public List<InterfaceInformation> urlSearch(String name, List<InterfaceInformation> list) {
@SuppressWarnings(value = "all") List<InterfaceInformation> results = new ArrayList();
public List<PathInfoVo> urlSearch(String name, List<PathInfoVo> list) {
@SuppressWarnings(value = "all") List<PathInfoVo> results = new ArrayList();
Pattern pattern = Pattern.compile(name, Pattern.CASE_INSENSITIVE);
for (InterfaceInformation o : list) {
Matcher matcher = pattern.matcher(o.getMethodUrl());
for (PathInfoVo o : list) {
Matcher matcher = pattern.matcher(o.getPathUrl());
if (matcher.find()) {
results.add(o);
}
......@@ -125,76 +426,6 @@ public class SwaggerController {
return results;
}
/**
* 用来获取Swagger中的信息
*
* @param json json字符串
* @return json中过滤出的信息
*/
private List<InterfaceInformation> getList(String json) {
long i = 0;
JSONObject swaggerJson = JSONObject.parseObject(json);
//localhost:8765
Object host = swaggerJson.get("host");
//"/"
Object basePath = swaggerJson.get("basePath");
Object paths = swaggerJson.get("paths");
//将paths转成map集合
@SuppressWarnings(value = "unchecked") Map<String, String> pathsMaps = (Map<String, String>) paths;
//获取key
Set<String> methodUrls = pathsMaps.keySet();
List<InterfaceInformation> list = new ArrayList<>();
//循环获取每个methodUrl
for (String methodUrl : methodUrls) {
//将paths转成JSON
JSONObject objPaths = (JSONObject) paths;
//通过JSON获取到methodUrl,用来获取methodUrl内部的信息
Object objMethodUrls = objPaths.get(methodUrl);
JSONObject objUrlsJson = (JSONObject) objMethodUrls;
@SuppressWarnings(value = "unchecked") Map<String, String> objMethodUrlsMaps = (Map<String, String>) objMethodUrls;
Set<String> requests = objMethodUrlsMaps.keySet();
for (String request : requests) {
//拿到请求内部的信息
Object objRequest = objUrlsJson.get(request);
@SuppressWarnings(value = "unchecked") Map<String, String> objRequestMaps = (Map<String, String>) objRequest;
Object parameters = objRequestMaps.get("parameters");
Object tags = objRequestMaps.get("tags");
Object summary = objRequestMaps.get("summary");
List<Parameter> parameterAllList = new ArrayList<>();
InterfaceInformation interfaceInformation = new InterfaceInformation();
@SuppressWarnings(value = "all")
List<String> parameterLists = parameters == null ? new ArrayList<>() : (List<String>) parameters;
for (Object parameterList : parameterLists) {
@SuppressWarnings(value = "unchecked") Map<String, String> parameterMaps = (Map<String, String>) parameterList;
String methodIn = parameterMaps.get("in");
String methodName = parameterMaps.get("name");
String methodType = parameterMaps.get("type");
// String methodSchema = parameterMaps.get("schema");
Parameter parameter = new Parameter();
//传参格式
parameter.setIn(methodIn);
//拿到参数名称
parameter.setName(methodName);
//拿到参数类型
parameter.setType(methodType);
// parameter.setSchema(methodSchema);
parameterAllList.add(parameter);
}
interfaceInformation.setId(i++);
interfaceInformation.setHost(String.valueOf(host));
interfaceInformation.setParameterAllList(parameterAllList);
interfaceInformation.setBasePath(String.valueOf(basePath));
interfaceInformation.setRequest(request.toUpperCase());
interfaceInformation.setSummary(String.valueOf(summary));
interfaceInformation.setMethodUrl(methodUrl);
interfaceInformation.setTags(String.valueOf(tags));
list.add(interfaceInformation);
}
}
return list;
}
/**
* 查询快速添加的接口
* name -> summary
......@@ -212,7 +443,7 @@ public class SwaggerController {
@GetMapping
@Transactional(rollbackFor = Exception.class)
@ApiOperation(value = "查询快速添加的接口")
public CommonPage<List<InterfaceInformation>> parameter(
public CommonPage<List<PathInfoVo>> parameter(
Long projectId,
Long id,
@RequestParam(defaultValue = "10") int pageSize,
......@@ -228,10 +459,11 @@ public class SwaggerController {
String swaggerUrl = String.format("%s/v2/api-docs", environment.getIp());
//获得json字符串
String json = loadJson(swaggerUrl);
List<InterfaceInformation> list = getList(json);
List<InterfaceInformation> swaggerSearch;
List<InterfaceInformation> swaggerUrlSearch;
List<InterfaceInformation> swaggerTagSearch;
JSONObject swaggerJson = JSON.parseObject(json, Feature.DisableCircularReferenceDetect);
List<PathInfoVo> list = getPathInfo(swaggerJson);
List<PathInfoVo> swaggerSearch;
List<PathInfoVo> swaggerUrlSearch;
List<PathInfoVo> swaggerTagSearch;
if ("".equals(url) && "".equals(tag) && "".equals(name)) {
swaggerSearch = list;
} else if ("".equals(tag) && "".equals(name)) {
......@@ -255,8 +487,8 @@ public class SwaggerController {
swaggerSearch = nameSearch(name, swaggerTagSearch);
}
int total = swaggerSearch.size();
List<InterfaceInformation> subList = swaggerSearch.subList(pageSize * (pageNum - 1), (Math.min((pageNum * pageSize), total)));
CommonPage<List<InterfaceInformation>> listCommonPage = new CommonPage<>();
List<PathInfoVo> subList = swaggerSearch.subList(pageSize * (pageNum - 1), (Math.min((pageNum * pageSize), total)));
CommonPage<List<PathInfoVo>> listCommonPage = new CommonPage<>();
listCommonPage.setList(subList);
listCommonPage.setTotal(total);
listCommonPage.setPageNum(pageNum);
......
package org.matrix.database.entity;
package org.matrix.autotest.swaggerEntity;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
......@@ -6,39 +6,30 @@ import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
/**
* Swagger中的参数信息
*
* @author mry
* @author MRY
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
@ApiModel(value = "参数信息")
public class Parameter {
@ApiModel("参数信息")
public class ParameterVo {
/**
* 名称
*/
@ApiModelProperty(value = "参数名称")
@ApiModelProperty("名称")
private String name;
/**
* 类型
*/
@ApiModelProperty(value = "参数类型")
@ApiModelProperty("类型")
private String type;
/**
* in
*/
@ApiModelProperty(value = "in")
private String in;
/**
* schema
*/
@ApiModelProperty(value = "schema")
private String schema;
@ApiModelProperty("描述")
private String description;
@ApiModelProperty("是否必填")
private Boolean required;
@ApiModelProperty("子类参数")
private List<ParameterVo> childParam;
}
package org.matrix.database.entity;
package org.matrix.autotest.swaggerEntity;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
......@@ -9,63 +9,42 @@ import lombok.NoArgsConstructor;
import java.util.List;
/**
* Swagger中的接口信息
*
* @author mry
* @author MRY
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
@ApiModel(value = "接口信息")
public class InterfaceInformation {
@ApiModel("接口信息")
public class PathInfoVo {
/**
* id
*/
@ApiModelProperty(value = "id")
@ApiModelProperty("id")
private Long id;
/**
* ip 以及端口信息
*/
@ApiModelProperty(value = "ip以及端口信息")
@ApiModelProperty("host")
private String host;
/**
* /
*/
@ApiModelProperty(value = "/")
@ApiModelProperty("/")
private String basePath;
/**
* 请求方式
*/
@ApiModelProperty(value = "请求方式")
private String request;
@ApiModelProperty("url地址")
private String pathUrl;
/**
* 标签
*/
@ApiModelProperty(value = "标签")
private String tags;
@ApiModelProperty("请求方式")
private String httpMethod;
@ApiModelProperty("描述")
private String description;
/**
* 总结
*/
@ApiModelProperty(value = "总结")
@ApiModelProperty("方法名,总结")
private String summary;
/**
* 方法拼接的url
*/
@ApiModelProperty(value = "方法拼接的url")
private String methodUrl;
@ApiModelProperty("类名,标签")
private String tags;
/**
* 参数
*/
@ApiModelProperty(value = "参数")
private List<Parameter> parameterAllList;
@ApiModelProperty("入参")
private List<ParameterVo> reqList;
@ApiModelProperty("返回值")
private List<ResponseVo> respList;
}
package org.matrix.autotest.swaggerEntity;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
/**
* @author MRY
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
@ApiModel("返回值信息")
public class ResponseVo {
@ApiModelProperty("名称")
private String name;
@ApiModelProperty("类型")
private String type;
@ApiModelProperty("描述")
private String description;
@ApiModelProperty("是否必填")
private Boolean required;
@ApiModelProperty("子类返回值")
private List<ResponseVo> childResp;
}
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论