feat: swagger定时修改

This commit is contained in:
wenyann 2021-01-26 10:16:35 +08:00
parent 96ae6250be
commit 00ef6a7c76
29 changed files with 532 additions and 110 deletions

View File

@ -6,17 +6,24 @@ import io.metersphere.api.dto.APIReportResult;
import io.metersphere.api.dto.ApiTestImportRequest;
import io.metersphere.api.dto.automation.ApiScenarioRequest;
import io.metersphere.api.dto.automation.ReferenceDTO;
import io.metersphere.api.dto.datacount.request.ScheduleInfoRequest;
import io.metersphere.api.dto.datacount.response.TaskInfoResult;
import io.metersphere.api.dto.definition.*;
import io.metersphere.api.dto.definition.parse.ApiDefinitionImport;
import io.metersphere.api.dto.definition.request.ScheduleInfoSwaggerUrlRequest;
import io.metersphere.api.dto.swaggerurl.SwaggerTaskResult;
import io.metersphere.api.dto.swaggerurl.SwaggerUrlRequest;
import io.metersphere.api.service.ApiDefinitionService;
import io.metersphere.base.domain.ApiDefinition;
import io.metersphere.base.domain.Schedule;
import io.metersphere.commons.constants.RoleConstants;
import io.metersphere.commons.json.JSONSchemaGenerator;
import io.metersphere.commons.utils.CronUtils;
import io.metersphere.commons.utils.PageUtils;
import io.metersphere.commons.utils.Pager;
import io.metersphere.commons.utils.SessionUtils;
import io.metersphere.service.CheckPermissionService;
import io.metersphere.service.ScheduleService;
import io.metersphere.track.request.testcase.ApiCaseRelevanceRequest;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresRoles;
@ -24,6 +31,7 @@ import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
@ -31,6 +39,8 @@ import java.util.List;
@RequestMapping(value = "/api/definition")
@RequiresRoles(value = {RoleConstants.TEST_MANAGER, RoleConstants.TEST_USER, RoleConstants.TEST_VIEWER}, logical = Logical.OR)
public class ApiDefinitionController {
@Resource
private ScheduleService scheduleService;
@Resource
private ApiDefinitionService apiDefinitionService;
@Resource
@ -139,7 +149,7 @@ public class ApiDefinitionController {
public ApiDefinitionImport testCaseImport(@RequestPart(value = "file", required = false) MultipartFile file, @RequestPart("request") ApiTestImportRequest request) {
return apiDefinitionService.apiTestImport(file, request);
}
//定时任务创建
@PostMapping(value = "/schedule/create")
public void createSchedule(@RequestBody Schedule request) {
apiDefinitionService.createSchedule(request);
@ -148,7 +158,38 @@ public class ApiDefinitionController {
public void updateSchedule(@RequestBody Schedule request){
apiDefinitionService.updateSchedule(request);
}
//查找定时任务资源Id
@PostMapping(value = "/getResourceId")
public String getResourceId(@RequestBody SwaggerUrlRequest swaggerUrlRequest){
return apiDefinitionService.getResourceId(swaggerUrlRequest);
}
//查找定时任务列表
@GetMapping("/scheduleTask/{projectId}")
public List<SwaggerTaskResult> getSwaggerScheduleList(@PathVariable String projectId) {
List<SwaggerTaskResult> resultList = apiDefinitionService.getSwaggerScheduleList(projectId);
int dataIndex = 1;
for (SwaggerTaskResult swaggerTaskResult :
resultList) {
swaggerTaskResult.setIndex(dataIndex++);
Date nextExecutionTime = CronUtils.getNextTriggerTime(swaggerTaskResult.getRule());
if(nextExecutionTime!=null){
swaggerTaskResult.setNextExecutionTime(nextExecutionTime.getTime());
}
}
return resultList;
}
//更新定时任务
@PostMapping(value = "/schedule/updateByPrimyKey")
public void updateScheduleEnableByPrimyKey(@RequestBody ScheduleInfoSwaggerUrlRequest request) {
Schedule schedule = scheduleService.getSchedule(request.getTaskId());
schedule.setEnable(request.getTaskStatus());
apiDefinitionService.updateSchedule(schedule);
}
//删除定时任务和swaggereUrl
@PostMapping("/schedule/deleteByPrimyKey")
public void deleteSchedule(@RequestBody ScheduleInfoSwaggerUrlRequest request) {
apiDefinitionService.deleteSchedule(request);
}
@PostMapping("/getReference")
public ReferenceDTO getReference(@RequestBody ApiScenarioRequest request) {
return apiDefinitionService.getReference(request);

View File

@ -16,4 +16,9 @@ public class ApiTestImportRequest {
// 来自场景的导入不需要存储
private boolean saved = true;
private String swaggerUrl;
//导入策略
private String modeId;
private String userId;
//调用类型
private String type;
}

View File

@ -0,0 +1,18 @@
package io.metersphere.api.dto.definition;
import io.metersphere.base.domain.Schedule;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class ApiSwaggerUrlDTO extends Schedule {
//序号
private int index;
private String id;
private String projectId;
private String swaggerUrl;
private String scheduleId;
//下次执行时间
private Long nextExecutionTime;
}

View File

@ -0,0 +1,12 @@
package io.metersphere.api.dto.definition.request;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class ScheduleInfoSwaggerUrlRequest {
private String taskId;
private Boolean taskStatus;
private String id;
}

View File

@ -0,0 +1,27 @@
package io.metersphere.api.dto.swaggerurl;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class SwaggerTaskResult {
//序号
private int index;
//定时任务号
private String taskId;
//SwaggerUrlId
private String SwaggerUrlId;
//SwaggerUrl
private String swaggerUrl;
//导入模块
private String modulePath;
//同步规则
private String rule;
//下次同步时间
private Long nextExecutionTime;
//同步开关
private boolean taskStatus;
//定时任务类型 swaggerUrlType
private String taskType;
}

View File

@ -0,0 +1,12 @@
package io.metersphere.api.dto.swaggerurl;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class SwaggerUrlRequest {
private String projectId;
private String swaggerUrl;
private String moduleId;
}

View File

@ -125,7 +125,7 @@ public abstract class ApiImportAbstractParser implements ApiImportParser {
return bodyType;
}
protected ApiDefinitionResult buildApiDefinition(String id, String name, String path, String method) {
protected ApiDefinitionResult buildApiDefinition(String id, String name, String path, String method,ApiTestImportRequest importRequest) {
ApiDefinitionResult apiDefinition = new ApiDefinitionResult();
apiDefinition.setName(name);
apiDefinition.setPath(formatPath(path));
@ -133,7 +133,11 @@ public abstract class ApiImportAbstractParser implements ApiImportParser {
apiDefinition.setMethod(method);
apiDefinition.setId(id);
apiDefinition.setProjectId(this.projectId);
apiDefinition.setUserId(SessionUtils.getUserId());
if(StringUtils.equalsIgnoreCase("schedule",importRequest.getType())){
apiDefinition.setUserId(importRequest.getUserId());
}else{
apiDefinition.setUserId(SessionUtils.getUserId());
}
return apiDefinition;
}

View File

@ -76,7 +76,7 @@ public class MsParser extends ApiImportAbstractParser {
String method = requestObject.getString("method");
MsHTTPSamplerProxy request = buildRequest(requestName, path, method);
ApiDefinitionResult apiDefinition = buildApiDefinition(request.getId(), requestName, path, method);
ApiDefinitionResult apiDefinition = buildApiDefinition(request.getId(), requestName, path, method,importRequest);
apiDefinition.setModuleId(module.getId());
apiDefinition.setProjectId(this.projectId);
parseBody(requestObject, request.getBody());

View File

@ -60,7 +60,7 @@ public class PostmanParser extends ApiImportAbstractParser {
PostmanUrl url = requestDesc.getUrl();
MsHTTPSamplerProxy request = buildRequest(requestItem.getName(), url.getRaw(), requestDesc.getMethod());
ApiDefinitionResult apiDefinition =
buildApiDefinition(request.getId(), requestItem.getName(), url.getRaw(), requestDesc.getMethod());
buildApiDefinition(request.getId(), requestItem.getName(), url.getRaw(), requestDesc.getMethod(),new ApiTestImportRequest());
if (StringUtils.isNotBlank(request.getPath())) {
String path = request.getPath().split("\\?")[0];
path = path.replace("{{", "${");

View File

@ -66,7 +66,7 @@ public class Swagger2Parser extends SwaggerAbstractParser {
for (HttpMethod method : httpMethods) {
Operation operation = operationMap.get(method);
MsHTTPSamplerProxy request = buildRequest(operation, pathName, method.name());
ApiDefinitionResult apiDefinition = buildApiDefinition(request.getId(), operation, pathName, method.name());
ApiDefinitionResult apiDefinition = buildApiDefinition(request.getId(), operation, pathName, method.name(),importRequest);
parseParameters(operation, request);
apiDefinition.setRequest(JSON.toJSONString(request));
apiDefinition.setResponse(JSON.toJSONString(parseResponse(operation, operation.getResponses())));
@ -79,7 +79,7 @@ public class Swagger2Parser extends SwaggerAbstractParser {
return results;
}
private ApiDefinitionResult buildApiDefinition(String id, Operation operation, String path, String method) {
private ApiDefinitionResult buildApiDefinition(String id, Operation operation, String path, String method,ApiTestImportRequest importRequest) {
String name = "";
if (StringUtils.isNotBlank(operation.getSummary())) {
name = operation.getSummary();
@ -88,7 +88,7 @@ public class Swagger2Parser extends SwaggerAbstractParser {
} else {
name = path;
}
return buildApiDefinition(id, name, path, method);
return buildApiDefinition(id, name, path, method,importRequest);
}
private MsHTTPSamplerProxy buildRequest(Operation operation, String path, String method) {

View File

@ -97,7 +97,7 @@ public class Swagger3Parser extends SwaggerAbstractParser {
Operation operation = operationsMap.get(method);
if (operation != null) {
MsHTTPSamplerProxy request = buildRequest(operation, pathName, method);
ApiDefinitionResult apiDefinition = buildApiDefinition(request.getId(), operation, pathName, method);
ApiDefinitionResult apiDefinition = buildApiDefinition(request.getId(), operation, pathName, method,importRequest);
parseParameters(operation, request);
parseRequestBody(operation.getRequestBody(), request.getBody());
apiDefinition.setRequest(JSON.toJSONString(request));
@ -111,7 +111,7 @@ public class Swagger3Parser extends SwaggerAbstractParser {
return results;
}
private ApiDefinitionResult buildApiDefinition(String id, Operation operation, String path, String method) {
private ApiDefinitionResult buildApiDefinition(String id, Operation operation, String path, String method,ApiTestImportRequest importRequest) {
String name = "";
if (StringUtils.isNotBlank(operation.getSummary())) {
name = operation.getSummary();
@ -120,7 +120,7 @@ public class Swagger3Parser extends SwaggerAbstractParser {
} else {
name = path;
}
return buildApiDefinition(id, name, path, method);
return buildApiDefinition(id, name, path, method,importRequest);
}
private MsHTTPSamplerProxy buildRequest(Operation operation, String path, String method) {

View File

@ -9,19 +9,17 @@ import io.metersphere.api.dto.automation.ReferenceDTO;
import io.metersphere.api.dto.datacount.ApiDataCountResult;
import io.metersphere.api.dto.definition.*;
import io.metersphere.api.dto.definition.parse.ApiDefinitionImport;
import io.metersphere.api.dto.definition.request.ScheduleInfoSwaggerUrlRequest;
import io.metersphere.api.dto.scenario.request.RequestType;
import io.metersphere.api.dto.swaggerurl.SwaggerTaskResult;
import io.metersphere.api.dto.swaggerurl.SwaggerUrlRequest;
import io.metersphere.api.jmeter.JMeterService;
import io.metersphere.api.jmeter.TestResult;
import io.metersphere.api.parse.ApiImportParser;
import io.metersphere.api.parse.ApiImportParserFactory;
import io.metersphere.base.domain.*;
import io.metersphere.base.mapper.ApiDefinitionMapper;
import io.metersphere.base.mapper.ApiTestFileMapper;
import io.metersphere.base.mapper.ProjectMapper;
import io.metersphere.base.mapper.ext.ExtApiDefinitionExecResultMapper;
import io.metersphere.base.mapper.ext.ExtApiDefinitionMapper;
import io.metersphere.base.mapper.ext.ExtApiScenarioMapper;
import io.metersphere.base.mapper.ext.ExtTestPlanMapper;
import io.metersphere.base.mapper.*;
import io.metersphere.base.mapper.ext.*;
import io.metersphere.commons.constants.APITestStatus;
import io.metersphere.commons.constants.ApiRunMode;
import io.metersphere.commons.constants.ScheduleGroup;
@ -79,6 +77,12 @@ public class ApiDefinitionService {
private ProjectMapper projectMapper;
@Resource
private ScheduleService scheduleService;
@Resource
private SwaggerUrlProjectMapper swaggerUrlProjectMapper;
@Resource
private ExtSwaggerUrlScheduleMapper extSwaggerUrlScheduleMapper;
@Resource
private ScheduleMapper scheduleMapper;
private static Cache cache = Cache.newHardMemoryCache(0, 3600 * 24);
@ -293,7 +297,7 @@ public class ApiDefinitionService {
}
}
private ApiDefinition importCreate(ApiDefinitionResult request, ApiDefinitionMapper batchMapper) {
private ApiDefinition importCreate(ApiDefinitionResult request, ApiDefinitionMapper batchMapper,ApiTestImportRequest apiTestImportRequest) {
SaveApiDefinitionRequest saveReq = new SaveApiDefinitionRequest();
BeanUtils.copyBean(saveReq, request);
final ApiDefinitionWithBLOBs apiDefinition = new ApiDefinitionWithBLOBs();
@ -309,13 +313,26 @@ public class ApiDefinitionService {
apiDefinition.setDescription(request.getDescription());
List<ApiDefinition> sameRequest = getSameRequest(saveReq);
if (CollectionUtils.isEmpty(sameRequest)) {
if(StringUtils.equals("fullCoverage",apiTestImportRequest.getModeId())){
if (CollectionUtils.isEmpty(sameRequest)) {
batchMapper.insert(apiDefinition);
} else {
//如果存在则修改
apiDefinition.setId(sameRequest.get(0).getId());
apiDefinitionMapper.updateByPrimaryKeyWithBLOBs(apiDefinition);
}
}else if(StringUtils.equals("incrementalMerge",apiTestImportRequest.getModeId())){
batchMapper.insert(apiDefinition);
} else {
//如果存在则修改
apiDefinition.setId(sameRequest.get(0).getId());
apiDefinitionMapper.updateByPrimaryKeyWithBLOBs(apiDefinition);
}else{
if (CollectionUtils.isEmpty(sameRequest)) {
batchMapper.insert(apiDefinition);
} else {
//如果存在则修改
apiDefinition.setId(sameRequest.get(0).getId());
apiDefinitionMapper.updateByPrimaryKeyWithBLOBs(apiDefinition);
}
}
return apiDefinition;
}
@ -434,7 +451,7 @@ public class ApiDefinitionService {
item.setName(item.getName().substring(0, 255));
}
item.setNum(num++);
importCreate(item, batchMapper);
importCreate(item, batchMapper,request);
if (i % 300 == 0) {
sqlSession.flushStatements();
}
@ -596,6 +613,16 @@ public class ApiDefinitionService {
/*swagger定时导入*/
public void createSchedule(Schedule request) {
/*保存swaggerUrl*/
SwaggerUrlProject swaggerUrlProject=new SwaggerUrlProject();
swaggerUrlProject.setId(UUID.randomUUID().toString());
swaggerUrlProject.setProjectId(request.getProjectId());
swaggerUrlProject.setSwaggerUrl(request.getResourceId());
swaggerUrlProject.setModuleId(request.getModuleId());
swaggerUrlProject.setModulePath(request.getModulePath());
swaggerUrlProject.setModeId(request.getModeId());
scheduleService.addSwaggerUrlSchedule(swaggerUrlProject);
request.setResourceId(swaggerUrlProject.getId());
Schedule schedule = scheduleService.buildApiTestSchedule(request);
schedule.setJob(SwaggerUrlImportJob.class.getName());
schedule.setGroup(ScheduleGroup.SWAGGER_IMPORT.name());
@ -604,10 +631,35 @@ public class ApiDefinitionService {
this.addOrUpdateSwaggerImportCronJob(request);
}
//关闭
public void updateSchedule(Schedule request){
scheduleService.editSchedule(request);
this.addOrUpdateSwaggerImportCronJob(request);
}
//删除
public void deleteSchedule(ScheduleInfoSwaggerUrlRequest request){
swaggerUrlProjectMapper.deleteByPrimaryKey(request.getId());
scheduleMapper.deleteByPrimaryKey(request.getTaskId());
}
//查询swaggerUrl详情
public SwaggerUrlProject getSwaggerInfo(String resourceId){
return swaggerUrlProjectMapper.selectByPrimaryKey(resourceId);
}
public String getResourceId(SwaggerUrlRequest swaggerUrlRequest){
SwaggerUrlProjectExample swaggerUrlProjectExample=new SwaggerUrlProjectExample();
SwaggerUrlProjectExample.Criteria criteria=swaggerUrlProjectExample.createCriteria();
criteria.andProjectIdEqualTo(swaggerUrlRequest.getProjectId()).andSwaggerUrlEqualTo(swaggerUrlRequest.getSwaggerUrl()).andModuleIdEqualTo(swaggerUrlRequest.getModuleId());
List<SwaggerUrlProject> list=swaggerUrlProjectMapper.selectByExample(swaggerUrlProjectExample);
String resourceId="";
if(list.size()==1){
resourceId=list.get(0).getId();
}
return resourceId;
}
public List<SwaggerTaskResult> getSwaggerScheduleList(String projectId){
return extSwaggerUrlScheduleMapper.getSwaggerTaskList(projectId);
}
private void addOrUpdateSwaggerImportCronJob(Schedule request) {
scheduleService.addOrUpdateCronJob(request, SwaggerUrlImportJob.getJobKey(request.getResourceId()), SwaggerUrlImportJob.getTriggerKey(request.getResourceId()), SwaggerUrlImportJob.class);

View File

@ -1,8 +1,7 @@
package io.metersphere.base.domain;
import lombok.Data;
import java.io.Serializable;
import lombok.Data;
@Data
public class AuthSource implements Serializable {

View File

@ -37,5 +37,11 @@ public class Schedule implements Serializable {
//定时任务来源 测试计划/测试场景
private String scheduleFrom;
private String swaggerUrl;
private String projectId;
private String moduleId;
private String modulePath;
private String modeId;
}

View File

@ -2,9 +2,8 @@ package io.metersphere.base.mapper;
import io.metersphere.base.domain.AuthSource;
import io.metersphere.base.domain.AuthSourceExample;
import org.apache.ibatis.annotations.Param;
import java.util.List;
import org.apache.ibatis.annotations.Param;
public interface AuthSourceMapper {
long countByExample(AuthSourceExample example);

View File

@ -4,12 +4,14 @@ import io.metersphere.api.dto.datacount.ApiDataCountResult;
import io.metersphere.api.dto.definition.ApiComputeResult;
import io.metersphere.api.dto.definition.ApiDefinitionRequest;
import io.metersphere.api.dto.definition.ApiDefinitionResult;
import io.metersphere.api.dto.definition.ApiSwaggerUrlDTO;
import io.metersphere.base.domain.ApiDefinition;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface ExtApiDefinitionMapper {
List<ApiSwaggerUrlDTO> selectScheduleList(@Param("projectId") String projectId);
List<ApiDefinitionResult> list(@Param("request") ApiDefinitionRequest request);

View File

@ -421,4 +421,19 @@
</foreach>
</if>
</select>
<select id="selectScheduleList" resultType="io.metersphere.api.dto.definition.ApiSwaggerUrlDTO">
SELECT apiScene.id AS scenarioId,
apiScene.`name` AS `name`,
sch.id AS taskID,
sch.`value` AS rule,
sch.`enable` AS `taskStatus`,
u.`name` AS creator,
sch.update_time AS updateTime,
'scenario' AS taskType
FROM api_scenario apiScene
INNER JOIN `schedule` sch ON apiScene.id = sch.resource_id
INNER JOIN `user` u ON u.id = sch.user_id
WHERE sch.`enable` = true
AND apiScene.project_id = #{0,jdbcType=VARCHAR}
</select>
</mapper>

View File

@ -1,6 +1,7 @@
package io.metersphere.base.mapper.ext;
import io.metersphere.api.dto.datacount.response.TaskInfoResult;
import io.metersphere.api.dto.definition.ApiSwaggerUrlDTO;
import io.metersphere.controller.request.QueryScheduleRequest;
import io.metersphere.dto.ScheduleDao;
import org.apache.ibatis.annotations.Param;
@ -15,4 +16,9 @@ public interface ExtScheduleMapper {
long countTaskByProjectIdAndCreateTimeRange(@Param("projectId")String projectId, @Param("startTime") long startTime, @Param("endTime") long endTime);
List<TaskInfoResult> findRunningTaskInfoByProjectID(String workspaceID);
void insert(@Param("apiSwaggerUrlDTO") ApiSwaggerUrlDTO apiSwaggerUrlDTO);
ApiSwaggerUrlDTO select(String id);
}

View File

@ -1,6 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="io.metersphere.base.mapper.ext.ExtScheduleMapper">
<insert id="insert" parameterType="io.metersphere.api.dto.definition.ApiSwaggerUrlDTO">
insert into swagger_url_project (id, `project_id`, `swagger_url`,
`schedule_id`)
values (#{apiSwaggerUrlDTO.id,jdbcType=VARCHAR}, #{apiSwaggerUrlDTO.projectId,jdbcType=VARCHAR}, #{apiSwaggerUrlDTO.swaggerUrl,jdbcType=VARCHAR},
#{apiSwaggerUrlDTO.scheduleId,jdbcType=VARCHAR})
</insert>
<select id="list" resultType="io.metersphere.dto.ScheduleDao">
select schedule.* from schedule
<where>
@ -37,31 +43,53 @@
</select>
<select id="countTaskByProjectId" resultType="java.lang.Long">
SELECT COUNT(id) AS countNumber FROM `schedule` WHERE resource_id IN (
SELECT COUNT(id) AS countNumber
FROM `schedule`
WHERE resource_id IN (
SELECT id FROM api_scenario WHERE project_id = #{0,jdbcType=VARCHAR} AND status != 'Trash'
)
)
</select>
<select id="countTaskByProjectIdAndCreateTimeRange" resultType="java.lang.Long">
SELECT COUNT(id) AS countNumber FROM `schedule`
SELECT COUNT(id) AS countNumber
FROM `schedule`
WHERE resource_id IN (
SELECT scene.id FROM api_scenario scene
WHERE scene.project_id = #{projectId,jdbcType=VARCHAR} AND scene.status != 'Trash'
SELECT scene.id
FROM api_scenario scene
WHERE scene.project_id = #{projectId,jdbcType=VARCHAR}
AND scene.status != 'Trash'
)
AND create_time BETWEEN #{startTime} and #{endTime}
AND create_time BETWEEN #{startTime} and #{endTime}
</select>
<select id="findRunningTaskInfoByProjectID" resultType="io.metersphere.api.dto.datacount.response.TaskInfoResult">
SELECT apiScene.id AS scenarioId,apiScene.`name` AS `name` ,sch.id AS taskID,sch.`value` AS rule,sch.`enable` AS `taskStatus`,u.`name` AS creator,sch.update_time AS updateTime,
'scenario' AS taskType
SELECT apiScene.id AS scenarioId,
apiScene.`name` AS `name`,
sch.id AS taskID,
sch.`value` AS rule,
sch.`enable` AS `taskStatus`,
u.`name` AS creator,
sch.update_time AS updateTime,
'scenario' AS taskType
FROM api_scenario apiScene
INNER JOIN `schedule` sch ON apiScene.id = sch.resource_id
INNER JOIN `user` u ON u.id = sch.user_id
WHERE sch.`enable` = true AND apiScene.project_id = #{0,jdbcType=VARCHAR}
INNER JOIN `schedule` sch ON apiScene.id = sch.resource_id
INNER JOIN `user` u ON u.id = sch.user_id
WHERE sch.`enable` = true
AND apiScene.project_id = #{0,jdbcType=VARCHAR}
UNION
SELECT testPlan.id AS scenarioId,testPlan.`name` AS `name`,sch.id AS taskID,sch.`value` AS rule,sch.`enable` AS `taskStatus`,u.`name` AS creator,sch.update_time AS updateTime,
'testPlan' AS taskType
SELECT testPlan.id AS scenarioId,
testPlan.`name` AS `name`,
sch.id AS taskID,
sch.`value` AS rule,
sch.`enable` AS `taskStatus`,
u.`name` AS creator,
sch.update_time AS updateTime,
'testPlan' AS taskType
FROM test_plan testPlan
INNER JOIN `schedule` sch ON testPlan.id = sch.resource_id
INNER JOIN `user` u ON u.id = sch.user_id
WHERE sch.`enable` = true AND testPlan.project_id = #{0,jdbcType=VARCHAR}
INNER JOIN `schedule` sch ON testPlan.id = sch.resource_id
INNER JOIN `user` u ON u.id = sch.user_id
WHERE sch.`enable` = true
AND testPlan.project_id = #{0,jdbcType=VARCHAR}
</select>
<select id="select" resultType="io.metersphere.api.dto.definition.ApiSwaggerUrlDTO">
select * from swagger_url_project where id=#{id}
</select>
</mapper>

View File

@ -0,0 +1,11 @@
package io.metersphere.base.mapper.ext;
import io.metersphere.api.dto.swaggerurl.SwaggerTaskResult;
import org.springframework.data.repository.query.Param;
import java.util.List;
public interface ExtSwaggerUrlScheduleMapper {
//接口列表定时导入
List<SwaggerTaskResult> getSwaggerTaskList(@Param("projectId") String projectId);
}

View File

@ -0,0 +1,16 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="io.metersphere.base.mapper.ext.ExtSwaggerUrlScheduleMapper">
<select id="getSwaggerTaskList" resultType="io.metersphere.api.dto.swaggerurl.SwaggerTaskResult"
parameterType="java.lang.String">
SELECT sup.id as SwaggerUrlId,
sup.swagger_url as swaggerUrl,
sup.module_path as modulePath,
sch.value as rule,
sch.enable as taskStatus,
sch.id as taskId
FROM swagger_url_project sup
INNER JOIN schedule sch ON sup.id = sch.resource_id
WHERE sup.project_id = #{projectId}
</select>
</mapper>

View File

@ -290,12 +290,11 @@ public class ScheduleManager {
addOrUpdateCronJob(jobKey, triggerKey, jobClass, cron, null);
}
public JobDataMap getDefaultJobDataMap(String resourceId, String expression, String userId,String swaggerUrl) {
public JobDataMap getDefaultJobDataMap(String resourceId, String expression, String userId) {
JobDataMap jobDataMap = new JobDataMap();
jobDataMap.put("resourceId", resourceId);
jobDataMap.put("expression", expression);
jobDataMap.put("userId", userId);
jobDataMap.put("swaggerUrl",swaggerUrl);
return jobDataMap;
}

View File

@ -1,9 +1,12 @@
package io.metersphere.job.sechedule;
import io.metersphere.api.dto.ApiTestImportRequest;
import io.metersphere.api.dto.definition.ApiSwaggerUrlDTO;
import io.metersphere.api.service.ApiDefinitionService;
import io.metersphere.base.domain.SwaggerUrlProject;
import io.metersphere.commons.constants.ScheduleGroup;
import io.metersphere.commons.utils.CommonBeanFactory;
import io.metersphere.service.ScheduleService;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobKey;
@ -20,12 +23,15 @@ public class SwaggerUrlImportJob extends MsScheduleJob {
void businessExecute(JobExecutionContext context) {
JobDataMap jobDataMap = context.getJobDetail().getJobDataMap();
String resourceId = jobDataMap.getString("resourceId");
String swaggerUrl = jobDataMap.getString("swaggerUrl");
SwaggerUrlProject swaggerUrlProject=apiDefinitionService.getSwaggerInfo(resourceId);
ApiTestImportRequest request = new ApiTestImportRequest();
request.setProjectId(resourceId);
request.setSwaggerUrl(swaggerUrl);
request.setProjectId(swaggerUrlProject.getProjectId());
request.setSwaggerUrl(swaggerUrlProject.getSwaggerUrl());
request.setModuleId(swaggerUrlProject.getModuleId());
request.setPlatform("Swagger2");
request.setSaved(true);
request.setUserId(jobDataMap.getString("userId"));
request.setType("schedule");
apiDefinitionService.apiTestImport(null, request);
}

View File

@ -2,11 +2,10 @@ package io.metersphere.service;
import com.alibaba.fastjson.JSON;
import io.metersphere.api.dto.datacount.response.TaskInfoResult;
import io.metersphere.base.domain.Schedule;
import io.metersphere.base.domain.ScheduleExample;
import io.metersphere.base.domain.User;
import io.metersphere.base.domain.UserExample;
import io.metersphere.api.dto.definition.ApiSwaggerUrlDTO;
import io.metersphere.base.domain.*;
import io.metersphere.base.mapper.ScheduleMapper;
import io.metersphere.base.mapper.SwaggerUrlProjectMapper;
import io.metersphere.base.mapper.UserMapper;
import io.metersphere.base.mapper.ext.ExtScheduleMapper;
import io.metersphere.commons.constants.ScheduleGroup;
@ -49,6 +48,8 @@ public class ScheduleService {
private ExtScheduleMapper extScheduleMapper;
@Resource
private UserMapper userMapper;
@Resource
private SwaggerUrlProjectMapper swaggerUrlProjectMapper;
public void addSchedule(Schedule schedule) {
schedule.setId(UUID.randomUUID().toString());
@ -57,6 +58,12 @@ public class ScheduleService {
schedule.setUpdateTime(System.currentTimeMillis());
scheduleMapper.insert(schedule);
}
public void addSwaggerUrlSchedule(SwaggerUrlProject swaggerUrlProject) {
swaggerUrlProjectMapper.insert(swaggerUrlProject);
}
public ApiSwaggerUrlDTO selectApiSwaggerUrlDTO(String id){
return extScheduleMapper.select(id);
}
public Schedule getSchedule(String ScheduleId) {
return scheduleMapper.selectByPrimaryKey(ScheduleId);
@ -111,7 +118,7 @@ public class ScheduleService {
LogUtil.error("初始化任务:" + JSON.toJSONString(schedule));
scheduleManager.addOrUpdateCronJob(new JobKey(schedule.getKey(), schedule.getGroup()),
new TriggerKey(schedule.getKey(), schedule.getGroup()), Class.forName(schedule.getJob()), schedule.getValue(),
scheduleManager.getDefaultJobDataMap(schedule.getResourceId(), schedule.getValue(), schedule.getUserId(),schedule.getSwaggerUrl()));
scheduleManager.getDefaultJobDataMap(schedule.getResourceId(), schedule.getValue(), schedule.getUserId()));
}
} catch (Exception e) {
LogUtil.error("初始化任务失败", e);
@ -140,7 +147,7 @@ public class ScheduleService {
if (enable != null && enable && StringUtils.isNotBlank(cronExpression)) {
try {
scheduleManager.addOrUpdateCronJob(jobKey, triggerKey, clazz, cronExpression,
scheduleManager.getDefaultJobDataMap(request.getResourceId(), cronExpression, SessionUtils.getUser().getId(),request.getSwaggerUrl()));
scheduleManager.getDefaultJobDataMap(request.getResourceId(), cronExpression, SessionUtils.getUser().getId()));
} catch (SchedulerException e) {
LogUtil.error(e.getMessage(), e);
MSException.throwException("定时任务开启异常");

View File

@ -0,0 +1,12 @@
create table swagger_url_project
(
id varchar(255) not null,
project_id varchar(255) null,
swagger_url varchar(255) null,
module_id varchar(255) null,
module_path varchar(255) null,
mode_id varchar(255) null,
primary key (id)
) ENGINE = InnoDB
DEFAULT CHARSET = utf8mb4;

View File

@ -65,6 +65,7 @@
<!--要生成的数据库表 -->
<table tableName="auth_source"/>
<table tableName="swagger_url_project"/>
<!--<table tableName="test_plan_api_scenario"/>-->
<!--<table tableName="test_plan"/>-->
<!--<table tableName="api_scenario_report"/>-->

View File

@ -20,7 +20,11 @@
<el-form :model="formData" :rules="rules" label-width="100px" v-loading="result.loading" ref="form">
<el-row>
<el-col :span="9">
<el-form-item :label="'Swagger URL'" prop="swaggerUrl" v-if="isSwagger2 && swaggerUrlEable" class="swagger-url">
<el-input size="small" v-model="formData.swaggerUrl" clearable show-word-limit/>
</el-form-item>
<el-col :span="11">
<el-form-item :label="$t('commons.import_module')"
v-if="selectedPlatformValue != 'Swagger2' || (selectedPlatformValue == 'Swagger2' && !swaggerUrlEable)">
<el-select size="small" v-model="formData.moduleId" class="project-select" clearable>
@ -33,10 +37,27 @@
<el-option v-for="item in modeOptions" :key="item.id" :label="item.name" :value="item.id"/>
</el-select>
</el-form-item>
<el-form-item v-if="isSwagger2">
<el-switch
v-model="swaggerUrlEable"
:active-text="$t('api_test.api_import.swagger_url_import')">
</el-switch>
</el-form-item>
<el-form-item v-show="isSwagger2 && swaggerUrlEable">
<el-switch
v-model="swaggerSynchronization"
@click.native="scheduleEdit"
:active-text="$t('api_test.api_import.timing_synchronization')">
</el-switch>
</el-form-item>
</el-col>
<el-col :span="10" style="margin-left: 20px">
<el-col :span="1"
v-if="selectedPlatformValue != 'Swagger2' || (selectedPlatformValue == 'Swagger2' && !swaggerUrlEable)">
<el-divider direction="vertical"/>
</el-col>
<el-col :span="12"
v-if="selectedPlatformValue != 'Swagger2' || (selectedPlatformValue == 'Swagger2' && !swaggerUrlEable)">
<el-upload
v-if="selectedPlatformValue != 'Swagger2' || (selectedPlatformValue == 'Swagger2' && !swaggerUrlEable)"
class="api-upload"
drag
action=""
@ -52,28 +73,7 @@
<div class="el-upload__tip" slot="tip">{{ $t('api_test.api_import.file_size_limit') }}</div>
</el-upload>
</el-col>
<el-form-item :label="'Swagger URL'" prop="wgerUrl" v-if="isSwagger2 && swaggerUrlEable" class="swagger-url">
<el-input size="small" v-model="formData.swaggerUrl" clearable show-word-limit/>
</el-form-item>
<el-form-item v-if="isSwagger2" class="swagger-enable" :class="{'swagger-url-disable': !swaggerUrlEable}">
<el-switch
v-model="swaggerUrlEable"
:active-text="$t('api_test.api_import.swagger_url_import')">
</el-switch>
</el-form-item>
<el-form-item v-if="isSwagger2 && swaggerUrlEable">
<el-switch
v-model="swaggerSynchronization"
@click.native="scheduleEdit"
:active-text="$t('api_test.api_import.timing_synchronization')">
</el-switch>
</el-form-item>
<schedule-import ref="scheduleEdit"></schedule-import>
</el-row>
</el-form>
<div class="format-tip">
@ -84,7 +84,7 @@
<span>{{ $t('api_test.api_import.export_tip') }}{{ selectedPlatform.exportTip }}</span>
</div>
</div>
<schedule-import ref="scheduleEdit"></schedule-import>
</el-dialog>
</template>
@ -180,11 +180,13 @@ export default {
},
methods: {
scheduleEdit() {
if (this.swaggerSynchronization) {
this.$refs.scheduleEdit.open(this.buildParam());
if (!this.formData.swaggerUrl) {
this.$warning(this.$t('commons.please_upload'));
this.swaggerSynchronization = !this.swaggerSynchronization
} else {
this.result = this.$post("/api/definition/schedule/update", this.schedule, response => {
});
if (this.swaggerSynchronization) {
this.$refs.scheduleEdit.open(this.buildParam());
}
}
},
open(module) {
@ -238,9 +240,15 @@ export default {
Object.assign(param, this.formData);
param.platform = this.selectedPlatformValue;
param.saved = this.saved;
console.log(this.formData.moduleId)
if (this.currentModule) {
param.moduleId = this.currentModule.id;
param.modulePath = this.currentModule.path;
param.moduleId = this.formData.moduleId
this.moduleOptions.filter(item => {
if (item.id === this.formData.moduleId) {
param.modulePath = item.path
}
})
param.modeId = this.formData.modeId
}
param.projectId = getCurrentProjectID();
if (!this.swaggerUrlEable) {
@ -326,4 +334,8 @@ export default {
margin-left: 80px;
}
.el-divider {
height: 200px;
}
</style>

View File

@ -28,6 +28,9 @@
ref="crontab"/>
</el-dialog>
</el-tab-pane>
<el-tab-pane :label="$t('api_test.home_page.running_task_list.title')" name="second">
<swagger-task-list></swagger-task-list>
</el-tab-pane>
</el-tabs>
</div>
</template>
@ -35,10 +38,17 @@
</template>
<script>
import {checkoutTestManagerOrTestUser, getCurrentUser, listenGoBack, removeGoBackListener} from "@/common/js/utils";
import {
checkoutTestManagerOrTestUser,
getCurrentProjectID,
getCurrentUser,
listenGoBack,
removeGoBackListener
} from "@/common/js/utils";
import Crontab from "@/business/components/common/cron/Crontab";
import CrontabResult from "@/business/components/common/cron/CrontabResult";
import {cronValidate} from "@/common/js/cron";
import SwaggerTaskList from "@/business/components/api/definition/components/import/SwaggerTaskList";
function defaultCustomValidate() {
return {pass: true};
@ -46,7 +56,7 @@ function defaultCustomValidate() {
export default {
name: "ImportScheduleEdit",
components: {CrontabResult, Crontab},
components: {SwaggerTaskList, CrontabResult, Crontab},
props: {
customValidate: {
@ -89,8 +99,12 @@ export default {
cronValue: ""
},
activeName: 'first',
swaggerUrl:String,
projectId:String,
swaggerUrl: String,
projectId: String,
moduleId: String,
paramSwaggerUrlId: String,
modulePath: String,
modeId: String,
rules: {
cronValue: [{required: true, validator: validateCron, trigger: 'blur'}],
}
@ -101,20 +115,30 @@ export default {
return getCurrentUser();
},
open(param) {
let paramTestId = "";
paramTestId=param.projectId
this.findSchedule(paramTestId);
this.project=param.projectId;
this.swaggerUrl=param.swaggerUrl;
this.dialogVisible = true;
this.form.cronValue = this.schedule.value;
listenGoBack(this.close);
this.$post("/api/definition/getResourceId", param, response => {
this.paramSwaggerUrlId = response.data
if (this.paramSwaggerUrlId === "" || this.paramSwaggerUrlId === null || this.paramSwaggerUrlId === undefined) {
console.log(this.paramSwaggerUrlId)
} else {
this.findSchedule(this.paramSwaggerUrlId);
}
this.project = param.projectId;
this.swaggerUrl = param.swaggerUrl;
this.dialogVisible = true;
this.form.cronValue = this.schedule.value;
this.moduleId = param.moduleId;
this.modulePath = param.modulePath;
this.modeId = param.modeId;
listenGoBack(this.close);
})
this.activeName = 'first';
},
findSchedule(paramTestId) {
let scheduleResourceID = paramTestId;
let taskType="SWAGGER_IMPORT";
this.result = this.$get("/schedule/findOne/" + scheduleResourceID + "/" +taskType, response => {
},
findSchedule(paramSwaggerUrlId) {
let scheduleResourceID = paramSwaggerUrlId;
let taskType = "SWAGGER_IMPORT";
this.result = this.$get("/schedule/findOne/" + scheduleResourceID + "/" + taskType, response => {
if (response.data != null) {
this.schedule = response.data;
} else {
@ -150,9 +174,17 @@ export default {
this.checkScheduleEdit();
let param = {};
param = this.schedule;
param.resourceId =this.project;
param.swaggerUrl=this.swaggerUrl;
let url = '/api/definition/schedule/create';
param.resourceId = this.swaggerUrl;
param.projectId = getCurrentProjectID();
param.moduleId = this.moduleId;
param.modulePath = this.modulePath;
param.modeId = this.modeId;
let url = '';
if (this.paramSwaggerUrlId) {
url = '/api/definition/schedule/update';
} else {
url = '/api/definition/schedule/create';
}
this.$post(url, param, () => {
this.$success(this.$t('commons.save_success'));
});

View File

@ -0,0 +1,100 @@
<template>
<el-table border :data="tableData" class="adjust-table table-content" height="300px">
<el-table-column prop="index" :label="$t('api_test.home_page.running_task_list.table_coloum.index')"
width="50"
show-overflow-tooltip/>
<el-table-column prop="SwaggerUrlId">
</el-table-column>
<el-table-column prop="swaggerUrl" :label="$t('swaggerUrl')" width="100" show-overflow-tooltip>
</el-table-column>
<el-table-column prop="modulePath" :label="$t('导入模块')"
width="100" show-overflow-tooltip/>
<el-table-column prop="rule" label="同步规则" width="120"
show-overflow-tooltip/>
<el-table-column width="100" :label="$t('api_test.home_page.running_task_list.table_coloum.task_status')">
<template v-slot:default="scope">
<div>
<el-switch
v-model="scope.row.taskStatus"
class="captcha-img"
@click.native="closeTaskConfirm(scope.row)"
></el-switch>
</div>
</template>
</el-table-column>
<el-table-column width="170" :label="$t('api_test.home_page.running_task_list.table_coloum.next_execution_time')">
<template v-slot:default="scope">
<span>{{ scope.row.nextExecutionTime | timestampFormatDate }}</span>
</template>
</el-table-column>
<el-table-column width="100" label="操作">
<template v-slot:default="scope">
<el-button
type="danger"
icon="el-icon-delete"
size="mini"
@click.native.prevent="deleteRowTask(scope.row)"
></el-button>
</template>
</el-table-column>
</el-table>
</template>
<script>
import {getCurrentProjectID} from "../../../../../../common/js/utils";
export default {
name: "SwaggerTaskList",
data() {
return {
tableData: [],
}
},
methods: {
search() {
let projectId = getCurrentProjectID();
this.result = this.$get("/api/definition/scheduleTask/" + projectId, response => {
this.tableData = response.data;
})
},
closeTaskConfirm(row) {
let flag = row.taskStatus;
row.taskStatus = !flag;
if (row.taskStatus) {
this.$confirm(this.$t('api_test.home_page.running_task_list.confirm.close_title'), this.$t('commons.prompt'), {
confirmButtonText: this.$t('commons.confirm'),
cancelButtonText: this.$t('commons.cancel'),
type: 'warning'
}).then(() => {
row.taskStatus = !row.taskStatus
this.updateTask(row);
}).catch(() => {
});
} else {
row.taskStatus = !row.taskStatus
this.updateTask(row);
}
},
updateTask(taskRow) {
this.result = this.$post('/api/definition/schedule/updateByPrimyKey', taskRow, response => {
this.search();
});
},
deleteRowTask(row) {
this.result = this.$post('/api/definition/schedule/deleteByPrimyKey', row, response => {
this.search();
});
}
},
mounted() {
this.search()
},
}
</script>
<style scoped>
</style>