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.ApiTestImportRequest;
import io.metersphere.api.dto.automation.ApiScenarioRequest; import io.metersphere.api.dto.automation.ApiScenarioRequest;
import io.metersphere.api.dto.automation.ReferenceDTO; 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.*;
import io.metersphere.api.dto.definition.parse.ApiDefinitionImport; 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.api.service.ApiDefinitionService;
import io.metersphere.base.domain.ApiDefinition; import io.metersphere.base.domain.ApiDefinition;
import io.metersphere.base.domain.Schedule; import io.metersphere.base.domain.Schedule;
import io.metersphere.commons.constants.RoleConstants; import io.metersphere.commons.constants.RoleConstants;
import io.metersphere.commons.json.JSONSchemaGenerator; import io.metersphere.commons.json.JSONSchemaGenerator;
import io.metersphere.commons.utils.CronUtils;
import io.metersphere.commons.utils.PageUtils; import io.metersphere.commons.utils.PageUtils;
import io.metersphere.commons.utils.Pager; import io.metersphere.commons.utils.Pager;
import io.metersphere.commons.utils.SessionUtils; import io.metersphere.commons.utils.SessionUtils;
import io.metersphere.service.CheckPermissionService; import io.metersphere.service.CheckPermissionService;
import io.metersphere.service.ScheduleService;
import io.metersphere.track.request.testcase.ApiCaseRelevanceRequest; import io.metersphere.track.request.testcase.ApiCaseRelevanceRequest;
import org.apache.shiro.authz.annotation.Logical; import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresRoles; import org.apache.shiro.authz.annotation.RequiresRoles;
@ -24,6 +31,7 @@ import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource; import javax.annotation.Resource;
import java.util.Date;
import java.util.List; import java.util.List;
@ -31,6 +39,8 @@ import java.util.List;
@RequestMapping(value = "/api/definition") @RequestMapping(value = "/api/definition")
@RequiresRoles(value = {RoleConstants.TEST_MANAGER, RoleConstants.TEST_USER, RoleConstants.TEST_VIEWER}, logical = Logical.OR) @RequiresRoles(value = {RoleConstants.TEST_MANAGER, RoleConstants.TEST_USER, RoleConstants.TEST_VIEWER}, logical = Logical.OR)
public class ApiDefinitionController { public class ApiDefinitionController {
@Resource
private ScheduleService scheduleService;
@Resource @Resource
private ApiDefinitionService apiDefinitionService; private ApiDefinitionService apiDefinitionService;
@Resource @Resource
@ -139,7 +149,7 @@ public class ApiDefinitionController {
public ApiDefinitionImport testCaseImport(@RequestPart(value = "file", required = false) MultipartFile file, @RequestPart("request") ApiTestImportRequest request) { public ApiDefinitionImport testCaseImport(@RequestPart(value = "file", required = false) MultipartFile file, @RequestPart("request") ApiTestImportRequest request) {
return apiDefinitionService.apiTestImport(file, request); return apiDefinitionService.apiTestImport(file, request);
} }
//定时任务创建
@PostMapping(value = "/schedule/create") @PostMapping(value = "/schedule/create")
public void createSchedule(@RequestBody Schedule request) { public void createSchedule(@RequestBody Schedule request) {
apiDefinitionService.createSchedule(request); apiDefinitionService.createSchedule(request);
@ -148,7 +158,38 @@ public class ApiDefinitionController {
public void updateSchedule(@RequestBody Schedule request){ public void updateSchedule(@RequestBody Schedule request){
apiDefinitionService.updateSchedule(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") @PostMapping("/getReference")
public ReferenceDTO getReference(@RequestBody ApiScenarioRequest request) { public ReferenceDTO getReference(@RequestBody ApiScenarioRequest request) {
return apiDefinitionService.getReference(request); return apiDefinitionService.getReference(request);

View File

@ -16,4 +16,9 @@ public class ApiTestImportRequest {
// 来自场景的导入不需要存储 // 来自场景的导入不需要存储
private boolean saved = true; private boolean saved = true;
private String swaggerUrl; 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; 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(); ApiDefinitionResult apiDefinition = new ApiDefinitionResult();
apiDefinition.setName(name); apiDefinition.setName(name);
apiDefinition.setPath(formatPath(path)); apiDefinition.setPath(formatPath(path));
@ -133,7 +133,11 @@ public abstract class ApiImportAbstractParser implements ApiImportParser {
apiDefinition.setMethod(method); apiDefinition.setMethod(method);
apiDefinition.setId(id); apiDefinition.setId(id);
apiDefinition.setProjectId(this.projectId); 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; return apiDefinition;
} }

View File

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

View File

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

View File

@ -66,7 +66,7 @@ public class Swagger2Parser extends SwaggerAbstractParser {
for (HttpMethod method : httpMethods) { for (HttpMethod method : httpMethods) {
Operation operation = operationMap.get(method); Operation operation = operationMap.get(method);
MsHTTPSamplerProxy request = buildRequest(operation, pathName, method.name()); 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); parseParameters(operation, request);
apiDefinition.setRequest(JSON.toJSONString(request)); apiDefinition.setRequest(JSON.toJSONString(request));
apiDefinition.setResponse(JSON.toJSONString(parseResponse(operation, operation.getResponses()))); apiDefinition.setResponse(JSON.toJSONString(parseResponse(operation, operation.getResponses())));
@ -79,7 +79,7 @@ public class Swagger2Parser extends SwaggerAbstractParser {
return results; 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 = ""; String name = "";
if (StringUtils.isNotBlank(operation.getSummary())) { if (StringUtils.isNotBlank(operation.getSummary())) {
name = operation.getSummary(); name = operation.getSummary();
@ -88,7 +88,7 @@ public class Swagger2Parser extends SwaggerAbstractParser {
} else { } else {
name = path; name = path;
} }
return buildApiDefinition(id, name, path, method); return buildApiDefinition(id, name, path, method,importRequest);
} }
private MsHTTPSamplerProxy buildRequest(Operation operation, String path, String method) { 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); Operation operation = operationsMap.get(method);
if (operation != null) { if (operation != null) {
MsHTTPSamplerProxy request = buildRequest(operation, pathName, method); 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); parseParameters(operation, request);
parseRequestBody(operation.getRequestBody(), request.getBody()); parseRequestBody(operation.getRequestBody(), request.getBody());
apiDefinition.setRequest(JSON.toJSONString(request)); apiDefinition.setRequest(JSON.toJSONString(request));
@ -111,7 +111,7 @@ public class Swagger3Parser extends SwaggerAbstractParser {
return results; 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 = ""; String name = "";
if (StringUtils.isNotBlank(operation.getSummary())) { if (StringUtils.isNotBlank(operation.getSummary())) {
name = operation.getSummary(); name = operation.getSummary();
@ -120,7 +120,7 @@ public class Swagger3Parser extends SwaggerAbstractParser {
} else { } else {
name = path; name = path;
} }
return buildApiDefinition(id, name, path, method); return buildApiDefinition(id, name, path, method,importRequest);
} }
private MsHTTPSamplerProxy buildRequest(Operation operation, String path, String method) { 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.datacount.ApiDataCountResult;
import io.metersphere.api.dto.definition.*; import io.metersphere.api.dto.definition.*;
import io.metersphere.api.dto.definition.parse.ApiDefinitionImport; 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.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.JMeterService;
import io.metersphere.api.jmeter.TestResult; import io.metersphere.api.jmeter.TestResult;
import io.metersphere.api.parse.ApiImportParser; import io.metersphere.api.parse.ApiImportParser;
import io.metersphere.api.parse.ApiImportParserFactory; import io.metersphere.api.parse.ApiImportParserFactory;
import io.metersphere.base.domain.*; import io.metersphere.base.domain.*;
import io.metersphere.base.mapper.ApiDefinitionMapper; import io.metersphere.base.mapper.*;
import io.metersphere.base.mapper.ApiTestFileMapper; import io.metersphere.base.mapper.ext.*;
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.commons.constants.APITestStatus; import io.metersphere.commons.constants.APITestStatus;
import io.metersphere.commons.constants.ApiRunMode; import io.metersphere.commons.constants.ApiRunMode;
import io.metersphere.commons.constants.ScheduleGroup; import io.metersphere.commons.constants.ScheduleGroup;
@ -79,6 +77,12 @@ public class ApiDefinitionService {
private ProjectMapper projectMapper; private ProjectMapper projectMapper;
@Resource @Resource
private ScheduleService scheduleService; private ScheduleService scheduleService;
@Resource
private SwaggerUrlProjectMapper swaggerUrlProjectMapper;
@Resource
private ExtSwaggerUrlScheduleMapper extSwaggerUrlScheduleMapper;
@Resource
private ScheduleMapper scheduleMapper;
private static Cache cache = Cache.newHardMemoryCache(0, 3600 * 24); 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(); SaveApiDefinitionRequest saveReq = new SaveApiDefinitionRequest();
BeanUtils.copyBean(saveReq, request); BeanUtils.copyBean(saveReq, request);
final ApiDefinitionWithBLOBs apiDefinition = new ApiDefinitionWithBLOBs(); final ApiDefinitionWithBLOBs apiDefinition = new ApiDefinitionWithBLOBs();
@ -309,13 +313,26 @@ public class ApiDefinitionService {
apiDefinition.setDescription(request.getDescription()); apiDefinition.setDescription(request.getDescription());
List<ApiDefinition> sameRequest = getSameRequest(saveReq); 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); batchMapper.insert(apiDefinition);
} else { }else{
//如果存在则修改 if (CollectionUtils.isEmpty(sameRequest)) {
apiDefinition.setId(sameRequest.get(0).getId()); batchMapper.insert(apiDefinition);
apiDefinitionMapper.updateByPrimaryKeyWithBLOBs(apiDefinition); } else {
//如果存在则修改
apiDefinition.setId(sameRequest.get(0).getId());
apiDefinitionMapper.updateByPrimaryKeyWithBLOBs(apiDefinition);
}
} }
return apiDefinition; return apiDefinition;
} }
@ -434,7 +451,7 @@ public class ApiDefinitionService {
item.setName(item.getName().substring(0, 255)); item.setName(item.getName().substring(0, 255));
} }
item.setNum(num++); item.setNum(num++);
importCreate(item, batchMapper); importCreate(item, batchMapper,request);
if (i % 300 == 0) { if (i % 300 == 0) {
sqlSession.flushStatements(); sqlSession.flushStatements();
} }
@ -596,6 +613,16 @@ public class ApiDefinitionService {
/*swagger定时导入*/ /*swagger定时导入*/
public void createSchedule(Schedule request) { 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 schedule = scheduleService.buildApiTestSchedule(request);
schedule.setJob(SwaggerUrlImportJob.class.getName()); schedule.setJob(SwaggerUrlImportJob.class.getName());
schedule.setGroup(ScheduleGroup.SWAGGER_IMPORT.name()); schedule.setGroup(ScheduleGroup.SWAGGER_IMPORT.name());
@ -604,10 +631,35 @@ public class ApiDefinitionService {
this.addOrUpdateSwaggerImportCronJob(request); this.addOrUpdateSwaggerImportCronJob(request);
} }
//关闭
public void updateSchedule(Schedule request){ public void updateSchedule(Schedule request){
scheduleService.editSchedule(request); scheduleService.editSchedule(request);
this.addOrUpdateSwaggerImportCronJob(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) { private void addOrUpdateSwaggerImportCronJob(Schedule request) {
scheduleService.addOrUpdateCronJob(request, SwaggerUrlImportJob.getJobKey(request.getResourceId()), SwaggerUrlImportJob.getTriggerKey(request.getResourceId()), SwaggerUrlImportJob.class); scheduleService.addOrUpdateCronJob(request, SwaggerUrlImportJob.getJobKey(request.getResourceId()), SwaggerUrlImportJob.getTriggerKey(request.getResourceId()), SwaggerUrlImportJob.class);

View File

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

View File

@ -37,5 +37,11 @@ public class Schedule implements Serializable {
//定时任务来源 测试计划/测试场景 //定时任务来源 测试计划/测试场景
private String scheduleFrom; 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.AuthSource;
import io.metersphere.base.domain.AuthSourceExample; import io.metersphere.base.domain.AuthSourceExample;
import org.apache.ibatis.annotations.Param;
import java.util.List; import java.util.List;
import org.apache.ibatis.annotations.Param;
public interface AuthSourceMapper { public interface AuthSourceMapper {
long countByExample(AuthSourceExample example); 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.ApiComputeResult;
import io.metersphere.api.dto.definition.ApiDefinitionRequest; import io.metersphere.api.dto.definition.ApiDefinitionRequest;
import io.metersphere.api.dto.definition.ApiDefinitionResult; import io.metersphere.api.dto.definition.ApiDefinitionResult;
import io.metersphere.api.dto.definition.ApiSwaggerUrlDTO;
import io.metersphere.base.domain.ApiDefinition; import io.metersphere.base.domain.ApiDefinition;
import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Param;
import java.util.List; import java.util.List;
public interface ExtApiDefinitionMapper { public interface ExtApiDefinitionMapper {
List<ApiSwaggerUrlDTO> selectScheduleList(@Param("projectId") String projectId);
List<ApiDefinitionResult> list(@Param("request") ApiDefinitionRequest request); List<ApiDefinitionResult> list(@Param("request") ApiDefinitionRequest request);

View File

@ -421,4 +421,19 @@
</foreach> </foreach>
</if> </if>
</select> </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> </mapper>

View File

@ -1,6 +1,7 @@
package io.metersphere.base.mapper.ext; package io.metersphere.base.mapper.ext;
import io.metersphere.api.dto.datacount.response.TaskInfoResult; import io.metersphere.api.dto.datacount.response.TaskInfoResult;
import io.metersphere.api.dto.definition.ApiSwaggerUrlDTO;
import io.metersphere.controller.request.QueryScheduleRequest; import io.metersphere.controller.request.QueryScheduleRequest;
import io.metersphere.dto.ScheduleDao; import io.metersphere.dto.ScheduleDao;
import org.apache.ibatis.annotations.Param; 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); long countTaskByProjectIdAndCreateTimeRange(@Param("projectId")String projectId, @Param("startTime") long startTime, @Param("endTime") long endTime);
List<TaskInfoResult> findRunningTaskInfoByProjectID(String workspaceID); 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"?> <?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"> <!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"> <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 id="list" resultType="io.metersphere.dto.ScheduleDao">
select schedule.* from schedule select schedule.* from schedule
<where> <where>
@ -37,31 +43,53 @@
</select> </select>
<select id="countTaskByProjectId" resultType="java.lang.Long"> <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 id FROM api_scenario WHERE project_id = #{0,jdbcType=VARCHAR} AND status != 'Trash'
) )
</select> </select>
<select id="countTaskByProjectIdAndCreateTimeRange" resultType="java.lang.Long"> <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 ( WHERE resource_id IN (
SELECT scene.id FROM api_scenario scene SELECT scene.id
WHERE scene.project_id = #{projectId,jdbcType=VARCHAR} AND scene.status != 'Trash' 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>
<select id="findRunningTaskInfoByProjectID" resultType="io.metersphere.api.dto.datacount.response.TaskInfoResult"> <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, SELECT apiScene.id AS scenarioId,
'scenario' AS taskType 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 FROM api_scenario apiScene
INNER JOIN `schedule` sch ON apiScene.id = sch.resource_id INNER JOIN `schedule` sch ON apiScene.id = sch.resource_id
INNER JOIN `user` u ON u.id = sch.user_id INNER JOIN `user` u ON u.id = sch.user_id
WHERE sch.`enable` = true AND apiScene.project_id = #{0,jdbcType=VARCHAR} WHERE sch.`enable` = true
AND apiScene.project_id = #{0,jdbcType=VARCHAR}
UNION 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, SELECT testPlan.id AS scenarioId,
'testPlan' AS taskType 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 FROM test_plan testPlan
INNER JOIN `schedule` sch ON testPlan.id = sch.resource_id INNER JOIN `schedule` sch ON testPlan.id = sch.resource_id
INNER JOIN `user` u ON u.id = sch.user_id INNER JOIN `user` u ON u.id = sch.user_id
WHERE sch.`enable` = true AND testPlan.project_id = #{0,jdbcType=VARCHAR} 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> </select>
</mapper> </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); 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 jobDataMap = new JobDataMap();
jobDataMap.put("resourceId", resourceId); jobDataMap.put("resourceId", resourceId);
jobDataMap.put("expression", expression); jobDataMap.put("expression", expression);
jobDataMap.put("userId", userId); jobDataMap.put("userId", userId);
jobDataMap.put("swaggerUrl",swaggerUrl);
return jobDataMap; return jobDataMap;
} }

View File

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

View File

@ -2,11 +2,10 @@ package io.metersphere.service;
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSON;
import io.metersphere.api.dto.datacount.response.TaskInfoResult; import io.metersphere.api.dto.datacount.response.TaskInfoResult;
import io.metersphere.base.domain.Schedule; import io.metersphere.api.dto.definition.ApiSwaggerUrlDTO;
import io.metersphere.base.domain.ScheduleExample; import io.metersphere.base.domain.*;
import io.metersphere.base.domain.User;
import io.metersphere.base.domain.UserExample;
import io.metersphere.base.mapper.ScheduleMapper; import io.metersphere.base.mapper.ScheduleMapper;
import io.metersphere.base.mapper.SwaggerUrlProjectMapper;
import io.metersphere.base.mapper.UserMapper; import io.metersphere.base.mapper.UserMapper;
import io.metersphere.base.mapper.ext.ExtScheduleMapper; import io.metersphere.base.mapper.ext.ExtScheduleMapper;
import io.metersphere.commons.constants.ScheduleGroup; import io.metersphere.commons.constants.ScheduleGroup;
@ -49,6 +48,8 @@ public class ScheduleService {
private ExtScheduleMapper extScheduleMapper; private ExtScheduleMapper extScheduleMapper;
@Resource @Resource
private UserMapper userMapper; private UserMapper userMapper;
@Resource
private SwaggerUrlProjectMapper swaggerUrlProjectMapper;
public void addSchedule(Schedule schedule) { public void addSchedule(Schedule schedule) {
schedule.setId(UUID.randomUUID().toString()); schedule.setId(UUID.randomUUID().toString());
@ -57,6 +58,12 @@ public class ScheduleService {
schedule.setUpdateTime(System.currentTimeMillis()); schedule.setUpdateTime(System.currentTimeMillis());
scheduleMapper.insert(schedule); 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) { public Schedule getSchedule(String ScheduleId) {
return scheduleMapper.selectByPrimaryKey(ScheduleId); return scheduleMapper.selectByPrimaryKey(ScheduleId);
@ -111,7 +118,7 @@ public class ScheduleService {
LogUtil.error("初始化任务:" + JSON.toJSONString(schedule)); LogUtil.error("初始化任务:" + JSON.toJSONString(schedule));
scheduleManager.addOrUpdateCronJob(new JobKey(schedule.getKey(), schedule.getGroup()), scheduleManager.addOrUpdateCronJob(new JobKey(schedule.getKey(), schedule.getGroup()),
new TriggerKey(schedule.getKey(), schedule.getGroup()), Class.forName(schedule.getJob()), schedule.getValue(), 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) { } catch (Exception e) {
LogUtil.error("初始化任务失败", e); LogUtil.error("初始化任务失败", e);
@ -140,7 +147,7 @@ public class ScheduleService {
if (enable != null && enable && StringUtils.isNotBlank(cronExpression)) { if (enable != null && enable && StringUtils.isNotBlank(cronExpression)) {
try { try {
scheduleManager.addOrUpdateCronJob(jobKey, triggerKey, clazz, cronExpression, 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) { } catch (SchedulerException e) {
LogUtil.error(e.getMessage(), e); LogUtil.error(e.getMessage(), e);
MSException.throwException("定时任务开启异常"); 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="auth_source"/>
<table tableName="swagger_url_project"/>
<!--<table tableName="test_plan_api_scenario"/>--> <!--<table tableName="test_plan_api_scenario"/>-->
<!--<table tableName="test_plan"/>--> <!--<table tableName="test_plan"/>-->
<!--<table tableName="api_scenario_report"/>--> <!--<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-form :model="formData" :rules="rules" label-width="100px" v-loading="result.loading" ref="form">
<el-row> <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')" <el-form-item :label="$t('commons.import_module')"
v-if="selectedPlatformValue != 'Swagger2' || (selectedPlatformValue == 'Swagger2' && !swaggerUrlEable)"> v-if="selectedPlatformValue != 'Swagger2' || (selectedPlatformValue == 'Swagger2' && !swaggerUrlEable)">
<el-select size="small" v-model="formData.moduleId" class="project-select" clearable> <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-option v-for="item in modeOptions" :key="item.id" :label="item.name" :value="item.id"/>
</el-select> </el-select>
</el-form-item> </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>
<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 <el-upload
v-if="selectedPlatformValue != 'Swagger2' || (selectedPlatformValue == 'Swagger2' && !swaggerUrlEable)"
class="api-upload" class="api-upload"
drag drag
action="" action=""
@ -52,28 +73,7 @@
<div class="el-upload__tip" slot="tip">{{ $t('api_test.api_import.file_size_limit') }}</div> <div class="el-upload__tip" slot="tip">{{ $t('api_test.api_import.file_size_limit') }}</div>
</el-upload> </el-upload>
</el-col> </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-row>
</el-form> </el-form>
<div class="format-tip"> <div class="format-tip">
@ -84,7 +84,7 @@
<span>{{ $t('api_test.api_import.export_tip') }}{{ selectedPlatform.exportTip }}</span> <span>{{ $t('api_test.api_import.export_tip') }}{{ selectedPlatform.exportTip }}</span>
</div> </div>
</div> </div>
<schedule-import ref="scheduleEdit"></schedule-import>
</el-dialog> </el-dialog>
</template> </template>
@ -180,11 +180,13 @@ export default {
}, },
methods: { methods: {
scheduleEdit() { scheduleEdit() {
if (this.swaggerSynchronization) { if (!this.formData.swaggerUrl) {
this.$refs.scheduleEdit.open(this.buildParam()); this.$warning(this.$t('commons.please_upload'));
this.swaggerSynchronization = !this.swaggerSynchronization
} else { } else {
this.result = this.$post("/api/definition/schedule/update", this.schedule, response => { if (this.swaggerSynchronization) {
}); this.$refs.scheduleEdit.open(this.buildParam());
}
} }
}, },
open(module) { open(module) {
@ -238,9 +240,15 @@ export default {
Object.assign(param, this.formData); Object.assign(param, this.formData);
param.platform = this.selectedPlatformValue; param.platform = this.selectedPlatformValue;
param.saved = this.saved; param.saved = this.saved;
console.log(this.formData.moduleId)
if (this.currentModule) { if (this.currentModule) {
param.moduleId = this.currentModule.id; param.moduleId = this.formData.moduleId
param.modulePath = this.currentModule.path; this.moduleOptions.filter(item => {
if (item.id === this.formData.moduleId) {
param.modulePath = item.path
}
})
param.modeId = this.formData.modeId
} }
param.projectId = getCurrentProjectID(); param.projectId = getCurrentProjectID();
if (!this.swaggerUrlEable) { if (!this.swaggerUrlEable) {
@ -326,4 +334,8 @@ export default {
margin-left: 80px; margin-left: 80px;
} }
.el-divider {
height: 200px;
}
</style> </style>

View File

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