提交 cb4ad5bc 编写于 作者: C Captain.B

Merge branch 'master' into compare

# Conflicts:
#	frontend/src/i18n/en-US.js
#	frontend/src/i18n/zh-CN.js
#	frontend/src/i18n/zh-TW.js
......@@ -6,11 +6,11 @@ ARG MS_VERSION=dev
RUN mkdir -p /opt/apps && mkdir -p /opt/jmeter/lib/junit
COPY backend/target/backend-1.7.jar /opt/apps
COPY backend/target/backend-1.8.jar /opt/apps
COPY backend/target/classes/jmeter/ /opt/jmeter/
ENV JAVA_APP_JAR=/opt/apps/backend-1.7.jar
ENV JAVA_APP_JAR=/opt/apps/backend-1.8.jar
ENV AB_OFF=true
......
......@@ -7,7 +7,7 @@
<parent>
<artifactId>metersphere-server</artifactId>
<groupId>io.metersphere</groupId>
<version>1.7</version>
<version>1.8</version>
</parent>
<modelVersion>4.0.0</modelVersion>
......@@ -17,7 +17,7 @@
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<shiro.version>1.6.0</shiro.version>
<java.version>1.8</java.version>
<jmeter.version>5.2.1</jmeter.version>
<jmeter.version>5.4.1</jmeter.version>
<nacos.version>1.1.3</nacos.version>
<dubbo.version>2.7.8</dubbo.version>
<graalvm.version>20.1.0</graalvm.version>
......@@ -153,8 +153,18 @@
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j-impl</artifactId>
</exclusion>
<exclusion>
<artifactId>xstream</artifactId>
<groupId>com.thoughtworks.xstream</groupId>
</exclusion>
</exclusions>
</dependency>
<!-- 排除jmeter中的 xstream 解决bug -->
<dependency>
<groupId>com.thoughtworks.xstream</groupId>
<artifactId>xstream</artifactId>
<version>1.4.16</version>
</dependency>
<dependency>
<groupId>org.python</groupId>
......
......@@ -64,7 +64,6 @@ public class ApiAutomationController {
public void update(@RequestPart("request") SaveApiScenarioRequest request, @RequestPart(value = "files") List<MultipartFile> bodyFiles) {
apiAutomationService.update(request, bodyFiles);
}
@GetMapping("/delete/{id}")
public void delete(@PathVariable String id) {
apiAutomationService.delete(id);
......@@ -81,8 +80,8 @@ public class ApiAutomationController {
}
@PostMapping("/reduction")
public void reduction(@RequestBody List<SaveApiScenarioRequest> requests) {
apiAutomationService.reduction(requests);
public void reduction(@RequestBody List<String> ids) {
apiAutomationService.reduction(ids);
}
@GetMapping("/getApiScenario/{id}")
......@@ -109,8 +108,16 @@ public class ApiAutomationController {
return apiAutomationService.run(request);
}
@PostMapping(value = "/run/jenkins")
public String runByJenkins(@RequestBody RunScenarioRequest request) {
request.setExecuteType(ExecuteType.Saved.name());
request.setTriggerMode(ApiRunMode.API.name());
request.setRunMode(ApiRunMode.SCENARIO.name());
return apiAutomationService.run(request);
}
@PostMapping(value = "/run/batch")
public String runBatch(@RequestBody RunScenarioRequest request) {
public String runBatcah(@RequestBody RunScenarioRequest request) {
request.setExecuteType(ExecuteType.Saved.name());
request.setTriggerMode(ApiRunMode.SCENARIO.name());
request.setRunMode(ApiRunMode.SCENARIO.name());
......
......@@ -12,6 +12,8 @@ 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.EsbApiParamService;
import io.metersphere.api.service.EsbImportService;
import io.metersphere.base.domain.ApiDefinition;
import io.metersphere.base.domain.Schedule;
import io.metersphere.commons.constants.RoleConstants;
......@@ -24,12 +26,14 @@ import io.metersphere.controller.request.ScheduleRequest;
import io.metersphere.service.CheckPermissionService;
import io.metersphere.service.ScheduleService;
import io.metersphere.track.request.testcase.ApiCaseRelevanceRequest;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.net.MalformedURLException;
import java.util.Date;
import java.util.List;
......@@ -45,6 +49,10 @@ public class ApiDefinitionController {
private ApiDefinitionService apiDefinitionService;
@Resource
private CheckPermissionService checkPermissionService;
@Resource
private EsbApiParamService esbApiParamService;
@Resource
private EsbImportService esbImportService;
@PostMapping("/list/{goPage}/{pageSize}")
public Pager<List<ApiDefinitionResult>> list(@PathVariable int goPage, @PathVariable int pageSize, @RequestBody ApiDefinitionRequest request) {
......@@ -59,6 +67,7 @@ public class ApiDefinitionController {
request.setWorkspaceId(SessionUtils.getCurrentWorkspaceId());
return PageUtils.setPageInfo(page, apiDefinitionService.listRelevance(request));
}
@PostMapping("/list/relevance/review/{goPage}/{pageSize}")
public Pager<List<ApiDefinitionResult>> listRelevanceReview(@PathVariable int goPage, @PathVariable int pageSize, @RequestBody ApiDefinitionRequest request) {
Page<Object> page = PageHelper.startPage(goPage, pageSize, true);
......@@ -97,6 +106,15 @@ public class ApiDefinitionController {
apiDefinitionService.deleteBatch(ids);
}
@PostMapping(value = "/updateEsbRequest")
public SaveApiDefinitionRequest updateEsbRequest(@RequestBody SaveApiDefinitionRequest request) {
if (StringUtils.equals(request.getMethod(), "ESB")) {
//ESB的接口类型数据,采用TCP方式去发送。并将方法类型改为TCP。 并修改发送数据
request = esbApiParamService.updateEsbRequest(request);
}
return request;
}
@PostMapping("/deleteBatchByParams")
public void deleteBatchByParams(@RequestBody ApiBatchRequest request) {
apiDefinitionService.deleteByParams(request);
......@@ -115,8 +133,8 @@ public class ApiDefinitionController {
}
@PostMapping("/reduction")
public void reduction(@RequestBody List<SaveApiDefinitionRequest> requests) {
apiDefinitionService.reduction(requests);
public void reduction(@RequestBody ApiBatchRequest request) {
apiDefinitionService.reduction(request);
}
@GetMapping("/get/{id}")
......@@ -167,15 +185,18 @@ public class ApiDefinitionController {
public void createSchedule(@RequestBody ScheduleRequest request) throws MalformedURLException {
apiDefinitionService.createSchedule(request);
}
@PostMapping(value = "/schedule/update")
public void updateSchedule(@RequestBody Schedule request){
public void updateSchedule(@RequestBody Schedule request) {
apiDefinitionService.updateSchedule(request);
}
//查找定时任务资源Id
@PostMapping(value = "/getResourceId")
public String getResourceId(@RequestBody SwaggerUrlRequest swaggerUrlRequest){
public String getResourceId(@RequestBody SwaggerUrlRequest swaggerUrlRequest) {
return apiDefinitionService.getResourceId(swaggerUrlRequest);
}
//查找定时任务列表
@GetMapping("/scheduleTask/{projectId}")
public List<SwaggerTaskResult> getSwaggerScheduleList(@PathVariable String projectId) {
......@@ -185,12 +206,13 @@ public class ApiDefinitionController {
resultList) {
swaggerTaskResult.setIndex(dataIndex++);
Date nextExecutionTime = CronUtils.getNextTriggerTime(swaggerTaskResult.getRule());
if(nextExecutionTime!=null){
if (nextExecutionTime != null) {
swaggerTaskResult.setNextExecutionTime(nextExecutionTime.getTime());
}
}
return resultList;
return resultList;
}
//更新定时任务
@PostMapping(value = "/schedule/updateByPrimyKey")
public void updateScheduleEnableByPrimyKey(@RequestBody ScheduleInfoSwaggerUrlRequest request) {
......@@ -198,11 +220,13 @@ public class ApiDefinitionController {
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);
......@@ -224,8 +248,9 @@ public class ApiDefinitionController {
public void testPlanRelevance(@RequestBody ApiCaseRelevanceRequest request) {
apiDefinitionService.testPlanRelevance(request);
}
@PostMapping("/relevance/review")
public void testCaseReviewRelevance(@RequestBody ApiCaseRelevanceRequest request){
public void testCaseReviewRelevance(@RequestBody ApiCaseRelevanceRequest request) {
apiDefinitionService.testCaseReviewRelevance(request);
}
......@@ -233,4 +258,10 @@ public class ApiDefinitionController {
public String preview(@RequestBody String jsonSchema) {
return JSONSchemaGenerator.getJson(jsonSchema);
}
@GetMapping("/export/esbExcelTemplate")
@RequiresRoles(value = {RoleConstants.ADMIN, RoleConstants.ORG_ADMIN, RoleConstants.TEST_MANAGER}, logical = Logical.OR)
public void testCaseTemplateExport(HttpServletResponse response) {
esbImportService.templateExport(response);
}
}
......@@ -14,6 +14,8 @@ import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* @author song.tianyang
......@@ -39,13 +41,19 @@ public class ApiDocumentController {
@PostMapping("/selectApiInfoByParam")
public List<ApiDocumentInfoDTO> selectApiInfoByParam(@RequestBody ApiDocumentRequest request) {
List<ApiDocumentInfoDTO> returnList = new ArrayList<>();
List<ApiDefinitionWithBLOBs> apiModels = apiDefinitionService.getBLOBs(request.getApiIdList());
for (ApiDefinitionWithBLOBs apiModel : apiModels) {
try{
ApiDocumentInfoDTO returnDTO = apiDocumentService.conversionModelToDTO(apiModel);
if(request.getApiIdList() != null){
//要根据ids的顺序进行返回排序
List<ApiDefinitionWithBLOBs> apiModels = apiDefinitionService.getBLOBs(request.getApiIdList());
Map<String,ApiDefinitionWithBLOBs> apiModelMaps = apiModels.stream().collect(Collectors.toMap(ApiDefinitionWithBLOBs :: getId,a->a,(k1,k2)->k1));
for(String id : request.getApiIdList()){
ApiDefinitionWithBLOBs model = apiModelMaps.get(id);
if(model == null){
model = new ApiDefinitionWithBLOBs();
model.setId(id);
model.setName(id);
}
ApiDocumentInfoDTO returnDTO = apiDocumentService.conversionModelToDTO(model);
returnList.add(returnDTO);
}catch (Exception e){
e.printStackTrace();
}
}
return returnList;
......
......@@ -12,6 +12,7 @@ import io.metersphere.commons.utils.PageUtils;
import io.metersphere.commons.utils.Pager;
import io.metersphere.commons.utils.SessionUtils;
import io.metersphere.track.request.testcase.ApiCaseRelevanceRequest;
import io.metersphere.track.service.TestPlanApiCaseService;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.web.bind.annotation.*;
......@@ -28,7 +29,8 @@ public class ApiTestCaseController {
@Resource
private ApiTestCaseService apiTestCaseService;
@Resource
private TestPlanApiCaseService testPlanApiCaseService;
@PostMapping("/list")
public List<ApiTestCaseResult> list(@RequestBody ApiTestCaseRequest request) {
request.setWorkspaceId(SessionUtils.getCurrentWorkspaceId());
......@@ -47,6 +49,12 @@ public class ApiTestCaseController {
return null;
}
}
@GetMapping("/getStateByTestPlan/{id}")
public String getStateByTestPlan(@PathVariable String id ) {
String status=testPlanApiCaseService.getState(id);
return status;
}
@PostMapping("/list/{goPage}/{pageSize}")
public Pager<List<ApiTestCaseDTO>> listSimple(@PathVariable int goPage, @PathVariable int pageSize, @RequestBody ApiTestCaseRequest request) {
......@@ -130,7 +138,8 @@ public class ApiTestCaseController {
return apiTestCaseService.run(request);
}
@GetMapping(value = "/jenkins/exec/result/{id}")
public String getExecResult(@PathVariable String id) {
return apiTestCaseService.getExecResult(id);
public String getExecResult(@PathVariable String id) {
return apiTestCaseService.getExecResult(id);
}
}
\ No newline at end of file
......@@ -8,6 +8,7 @@ import org.dom4j.Element;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
/**
* //ESB数据格式
......@@ -19,15 +20,69 @@ import java.util.List;
@Getter
@Setter
public class EsbDataStruct {
private String uuid;
private String name;
private String value;
private String type;
private String systemName;
private String contentType;
private String required;
private boolean required;
private String description;
private List<EsbDataStruct> children;
public void init(){
this.uuid = UUID.randomUUID().toString();
this.systemName = "";
this.description = "";
this.value="";
this.required = true;
this.contentType = "";
this.type = "";
this.children = new ArrayList<>();
}
public boolean initDefaultData(String name, String typeLength,String chineseName,String desc){
this.init();
if(StringUtils.isEmpty(name)){return false; }
if(typeLength == null){
typeLength = "";
}else{
typeLength = typeLength.trim();
typeLength = typeLength.toLowerCase();
}
this.name = name;
if(typeLength.startsWith("string")){
this.type = "string";
String lengthStr = typeLength.substring(6);
if(lengthStr.startsWith("(") && lengthStr.endsWith(")")){
try {
int length = Integer.parseInt(lengthStr.substring(1,lengthStr.length()-1));
this.contentType = String.valueOf(length);
}catch (Exception e){ }
}
}else if(typeLength.startsWith("array")){
this.type = "array";
}else{
this.type = "object";
}
if(StringUtils.isEmpty(desc)){desc = "";}
if(StringUtils.isNotEmpty(chineseName)){
this.description = chineseName+":"+desc;
}else{
this.description =desc;
}
if(this.description.endsWith(":")){
this.description = this.description.substring(0,this.description.length()-1);
}
return true;
}
public EsbDataStruct copy(boolean copyChildren) {
EsbDataStruct returnObj = new EsbDataStruct();
returnObj.name = this.name;
......
......@@ -46,8 +46,6 @@ public class HarScenarioParser extends HarScenarioAbstractParser<ScenarioImport>
String harName = request.getFileName();
// 场景步骤
LinkedList<MsTestElement> apiScenarioWithBLOBs = new LinkedList<>();
// ApiScenarioWithBLOBs scenario = new ApiScenarioWithBLOBs();
// scenario.setName(harName);
MsScenario msScenario = new MsScenario();
msScenario.setName(harName);
......
......@@ -136,8 +136,10 @@ public class MsJmeterParser extends ApiImportAbstractParser<ScenarioImport> {
try {
HTTPSamplerProxy source = (HTTPSamplerProxy) key;
BeanUtils.copyBean(samplerProxy, source);
samplerProxy.setRest(new ArrayList<KeyValue>(){{this.add(new KeyValue());}});
samplerProxy.setArguments(new ArrayList<KeyValue>(){{this.add(new KeyValue());}});
if (source != null && source.getHTTPFiles().length > 0) {
samplerProxy.getBody().setBinary(new ArrayList<>());
samplerProxy.getBody().initBinary();
samplerProxy.getBody().setType(Body.FORM_DATA);
List<KeyValue> keyValues = new LinkedList<>();
for (HTTPFileArg arg : source.getHTTPFiles()) {
......@@ -163,6 +165,7 @@ public class MsJmeterParser extends ApiImportAbstractParser<ScenarioImport> {
source.getArguments().getArgumentsAsMap().forEach((k, v) -> {
samplerProxy.getBody().setRaw(v);
});
samplerProxy.getBody().initKvs();
} else {
List<KeyValue> keyValues = new LinkedList<>();
source.getArguments().getArgumentsAsMap().forEach((k, v) -> {
......@@ -173,6 +176,7 @@ public class MsJmeterParser extends ApiImportAbstractParser<ScenarioImport> {
samplerProxy.setArguments(keyValues);
}
}
samplerProxy.getBody().initBinary();
}
samplerProxy.setPath("");
samplerProxy.setMethod(source.getMethod());
......
......@@ -40,4 +40,7 @@ public class ApiTestBatchRequest extends ApiTestCaseWithBLOBs {
private String protocol;
private String status;
private String envId;
}
package io.metersphere.api.dto.definition;
import io.metersphere.base.domain.ApiTestCaseWithBLOBs;
import lombok.Getter;
import lombok.Setter;
@Setter
@Getter
public class ApiTestCaseInfo extends ApiTestCaseWithBLOBs {
private String apiMethod;
}
......@@ -11,6 +11,7 @@ public class ApiTestCaseResult extends ApiTestCaseWithBLOBs {
private String createUser;
private String updateUser;
private String execResult;
private String apiMethod;
private Long execTime;
private boolean active = false;
private boolean responseActive = false;
......
......@@ -14,9 +14,9 @@ import java.util.List;
public class SwaggerApiExportResult extends ApiExportResult{
private String openapi;
private SwaggerInfo info;
private String externalDocs;
private JSONObject externalDocs;
private List<String> servers;
private List<SwaggerTag> tags;
private JSONObject paths; // Map<String, Object>, Object 里放 Operation 对象
private List<String> components;
private JSONObject components;
}
package io.metersphere.api.dto.definition.parse;
import io.metersphere.api.dto.definition.request.MsScenario;
import io.metersphere.base.domain.ApiDefinitionWithBLOBs;
import io.metersphere.base.domain.ApiScenarioWithBLOBs;
import io.metersphere.base.domain.ApiTestCaseWithBLOBs;
import io.metersphere.base.domain.EsbApiParamsWithBLOBs;
import lombok.Data;
import java.util.List;
import java.util.Map;
@Data
public class ApiDefinitionImport {
......@@ -16,4 +16,7 @@ public class ApiDefinitionImport {
// 新版本带用例导出
private List<ApiTestCaseWithBLOBs> cases;
//ESB文件导入的附属数据类
private Map<String,EsbApiParamsWithBLOBs> esbApiParamsMap;
}
......@@ -14,6 +14,8 @@ public class ApiDefinitionImportParserFactory {
return new Swagger2Parser();
}else if (StringUtils.equals(ApiImportPlatform.Har.name(), platform)) {
return new HarParser();
}else if (StringUtils.equals(ApiImportPlatform.ESB.name(), platform)) {
return new ESBParser();
}
return null;
}
......
package io.metersphere.api.dto.definition.parse;
import io.metersphere.api.parse.ApiImportAbstractParser;
import io.metersphere.base.domain.ApiDefinitionWithBLOBs;
import io.metersphere.base.domain.ApiModule;
import java.util.List;
/**
* @author song.tianyang
* @Date 2021/3/10 11:15 上午
* @Description
*/
public abstract class EsbAbstractParser extends ApiImportAbstractParser<ApiDefinitionImport> {
protected void buildModule(ApiModule parentModule, ApiDefinitionWithBLOBs apiDefinition, List<String> tags) {
if (tags != null) {
tags.forEach(tag -> {
ApiModule module = ApiDefinitionImportUtil.buildModule(parentModule, tag, this.projectId);
apiDefinition.setModuleId(module.getId());
});
}else {
apiDefinition.setModuleId(parentModule.getId());
}
}
}
......@@ -21,6 +21,7 @@ import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import java.io.InputStream;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
......@@ -67,19 +68,36 @@ public class HarParser extends HarAbstractParser {
harEntryList = har.log.entries;
}
List<String> savedUrl = new ArrayList<>();
for (HarEntry entry : harEntryList) {
HarRequest harRequest = entry.request;
String url = harRequest.url;
if(url == null){
continue;
}
try {
url = URLDecoder.decode(url,"UTF-8");
}catch (Exception e){
}
if(savedUrl.contains(harRequest.url)){
continue;
}else {
savedUrl.add(harRequest.url);
}
//默认取路径的最后一块
String reqName = "";
if (harRequest.url != null) {
String[] nameArr = harRequest.url.split("/");
String[] nameArr = url.split("/");
reqName = nameArr[nameArr.length - 1];
}
if (harRequest != null) {
MsHTTPSamplerProxy request = super.buildRequest(reqName, harRequest.url, harRequest.method);
ApiDefinitionWithBLOBs apiDefinition = super.buildApiDefinition(request.getId(), reqName, harRequest.url, harRequest.method, importRequest);
MsHTTPSamplerProxy request = super.buildRequest(reqName, url, harRequest.method);
ApiDefinitionWithBLOBs apiDefinition = super.buildApiDefinition(request.getId(), reqName, url, harRequest.method, importRequest);
parseParameters(harRequest, request);
parseRequestBody(harRequest, request.getBody());
addBodyHeader(request);
......@@ -155,7 +173,7 @@ public class HarParser extends HarAbstractParser {
return;
}
HarPostData content = requestBody.postData;
if (!StringUtils.equalsIgnoreCase("GET", requestBody.method) || requestBody.postData == null) {
if (StringUtils.equalsIgnoreCase("GET", requestBody.method) || requestBody.postData == null) {
return;
}
String contentType = content.mimeType;
......
......@@ -9,7 +9,9 @@ import io.metersphere.api.dto.scenario.request.RequestType;
import io.metersphere.api.parse.MsAbstractParser;
import io.metersphere.base.domain.ApiDefinitionWithBLOBs;
import io.metersphere.base.domain.ApiModule;
import io.metersphere.base.domain.ApiTestCaseWithBLOBs;
import io.metersphere.commons.constants.ApiImportPlatform;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import java.io.InputStream;
......@@ -55,13 +57,23 @@ public class MsDefinitionParser extends MsAbstractParser<ApiDefinitionImport> {
private ApiDefinitionImport parseMsFormat(String testStr, ApiTestImportRequest importRequest) {
ApiDefinitionImport apiDefinitionImport = JSON.parseObject(testStr, ApiDefinitionImport.class);
Map<String, List<ApiTestCaseWithBLOBs>> caseMap = new HashMap<>();
apiDefinitionImport.getCases().forEach(item -> {
List<ApiTestCaseWithBLOBs> caseList = caseMap.get(item.getApiDefinitionId());
if (caseList == null) {
caseList = new ArrayList<>();
caseMap.put(item.getApiDefinitionId(), caseList);
}
caseList.add(item);
});
apiDefinitionImport.getData().forEach(apiDefinition -> {
parseApiDefinition(apiDefinition, importRequest);
parseApiDefinition(apiDefinition, importRequest, caseMap);
});
return apiDefinitionImport;
}
private void parseApiDefinition(ApiDefinitionWithBLOBs apiDefinition, ApiTestImportRequest importRequest) {
private void parseApiDefinition(ApiDefinitionWithBLOBs apiDefinition, ApiTestImportRequest importRequest, Map<String, List<ApiTestCaseWithBLOBs>> caseMap) {
String originId = apiDefinition.getId();
String id = UUID.randomUUID().toString();
if (StringUtils.isBlank(apiDefinition.getModulePath())) {
apiDefinition.setModuleId(null);
......@@ -73,6 +85,19 @@ public class MsDefinitionParser extends MsAbstractParser<ApiDefinitionImport> {
JSONObject requestObj = JSONObject.parseObject(request);
requestObj.put("id", id);
apiDefinition.setRequest(JSONObject.toJSONString(requestObj));
parseCase(caseMap, apiDefinition, importRequest, originId);
}
private void parseCase(Map<String, List<ApiTestCaseWithBLOBs>> caseMap, ApiDefinitionWithBLOBs apiDefinition,
ApiTestImportRequest importRequest, String originId) {
List<ApiTestCaseWithBLOBs> cases = caseMap.get(originId);
if (CollectionUtils.isEmpty(cases)) {
return;
}
cases.forEach(item -> {
item.setApiDefinitionId(apiDefinition.getId());
item.setProjectId(importRequest.getProjectId());
});
}
private void parseModule(String modulePath, ApiTestImportRequest importRequest, ApiDefinitionWithBLOBs apiDefinition) {
......
......@@ -58,6 +58,7 @@ public class Swagger2Parser extends SwaggerAbstractParser {
ApiModule parentNode = ApiDefinitionImportUtil.getSelectModule(importRequest.getModuleId());
String basePath = swagger.getBasePath();
for (String pathName : pathNames) {
Path path = paths.get(pathName);
Map<HttpMethod, Operation> operationMap = path.getOperationMap();
......@@ -68,6 +69,10 @@ public class Swagger2Parser extends SwaggerAbstractParser {
ApiDefinitionWithBLOBs apiDefinition = buildApiDefinition(request.getId(), operation, pathName, method.name(),importRequest);
parseParameters(operation, request);
addBodyHeader(request);
if (StringUtils.isNotBlank(basePath)) {
apiDefinition.setPath(basePath + apiDefinition.getPath());
request.setPath(basePath + request.getPath());
}
apiDefinition.setRequest(JSON.toJSONString(request));
apiDefinition.setResponse(JSON.toJSONString(parseResponse(operation, operation.getResponses())));
buildModule(parentNode, apiDefinition, operation.getTags());
......
......@@ -231,6 +231,9 @@ public class Swagger3Parser extends SwaggerAbstractParser {
MediaType mediaType = content.get(contentType);
if (mediaType == null) {
Set<String> contentTypes = content.keySet();
if(contentTypes.size() == 0) { // 防止空指针
return;
}
contentType = contentTypes.iterator().next();
if (StringUtils.isBlank(contentType)) {
return;
......@@ -410,26 +413,34 @@ public class Swagger3Parser extends SwaggerAbstractParser {
result.setInfo(new SwaggerInfo());
result.setServers(new ArrayList<>());
result.setTags(new ArrayList<>());
result.setComponents(new ArrayList<>());
result.setComponents(new JSONObject());
result.setExternalDocs(new JSONObject());
JSONObject paths = new JSONObject();
JSONObject swaggerPath = new JSONObject();
for(ApiDefinitionWithBLOBs apiDefinition : apiDefinitionList) {
SwaggerApiInfo swaggerApiInfo = new SwaggerApiInfo(); // {tags:, summary:, description:, parameters:}
swaggerApiInfo.setSummary(apiDefinition.getName());
// 设置导入后的模块名 (根据 api 的 moduleID 查库获得所属模块,作为导出的模块名)
ApiModuleService apiModuleService = CommonBeanFactory.getBean(ApiModuleService.class);
String moduleName = apiModuleService.getNode(apiDefinition.getModuleId()).getName();
String moduleName = "";
if(apiDefinition.getModuleId() != null) { // module_id 可能为空
moduleName = apiModuleService.getNode(apiDefinition.getModuleId()).getName();
}
swaggerApiInfo.setTags(Arrays.asList(moduleName));
// 设置请求体
JSONObject requestObject = JSON.parseObject(apiDefinition.getRequest()); // 将api的request属性转换成JSON对象以便获得参数
JSONObject requestBody = buildRequestBody(requestObject);
swaggerApiInfo.setRequestBody(requestBody);
// 设置响应体
swaggerApiInfo.setResponses(new JSONObject());
// 设置请求参数列表
List<JSONObject> paramsList = buildParameters(requestObject);
swaggerApiInfo.setParameters(paramsList);
swaggerPath.put(apiDefinition.getMethod().toLowerCase(), JSON.parseObject(JSON.toJSONString(swaggerApiInfo))); // 设置api的请求类型和api定义、参数
paths.put(apiDefinition.getPath(), swaggerPath);
JSONObject methodDetail = JSON.parseObject(JSON.toJSONString(swaggerApiInfo));
if(paths.getJSONObject(apiDefinition.getPath()) == null) {
paths.put(apiDefinition.getPath(), new JSONObject());
} // 一个路径下有多个发方法,如post,get,因此是一个 JSONObject 类型
paths.getJSONObject(apiDefinition.getPath()).put(apiDefinition.getMethod().toLowerCase(), methodDetail);
}
result.setPaths(paths);
return result;
......@@ -477,7 +488,9 @@ public class Swagger3Parser extends SwaggerAbstractParser {
schema.put("format", null);
typeName.put("schema", schema);
JSONObject content = new JSONObject();
content.put(typeMap.get(type), typeName);
if (type != null && StringUtils.isNotBlank(type)) {
content.put(typeMap.get(type), typeName);
}
requestBody.put("content", content);
return requestBody;
}
......
package io.metersphere.api.dto.definition.parse.esb;
import lombok.Getter;
import lombok.Setter;
import java.util.ArrayList;
import java.util.List;
/**
* @author song.tianyang
* @Date 2021/3/23 12:55 下午
* @Description
*/
@Getter
@Setter
public class EsbExcelDataStruct {
private EsbSheetDataStruct headData;
private List<EsbSheetDataStruct> interfaceList = new ArrayList<>();
}
package io.metersphere.api.dto.definition.parse.esb;
import io.metersphere.api.dto.automation.EsbDataStruct;
import io.metersphere.commons.exception.MSException;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.lang3.StringUtils;
import java.util.ArrayList;
import java.util.List;
/**
* @author song.tianyang
* @Date 2021/3/22 9:42 下午
* @Description
*/
@Getter
@Setter
public class EsbSheetDataStruct {
private String serviceName;
private String serviceDesc;
private List<EsbDataStruct> requestList = new ArrayList<>();
private List<EsbDataStruct> responseList = new ArrayList<>();
//单个接口内也可能有报文头中要增加的数据
private List<EsbDataStruct> reqHeadList = new ArrayList<>();
private List<EsbDataStruct> rspHeadList = new ArrayList<>();
public void setInterfaceInfo(String interfaceCode, String interfaceName, String interfaceDesc) {
if(StringUtils.isEmpty(interfaceCode) && StringUtils.isEmpty(interfaceName)){
MSException.throwException("接口的交易码或服务名称不能都为空");
}
if(StringUtils.isNotEmpty(interfaceCode)){
this.serviceName = interfaceCode+":"+interfaceName;
}else {
this.serviceName = interfaceName;
}
if (this.serviceName.endsWith(":")){
this.serviceName = this.serviceName.substring(0,this.serviceName.length()-1);
}
this.serviceDesc = interfaceDesc;
}
}
......@@ -29,6 +29,9 @@ import org.apache.commons.lang3.StringUtils;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
/**
* Utility class for working with HAR files.
......@@ -51,4 +54,13 @@ public class HarUtils {
Har har = JSONObject.parseObject(harJson, Har.class);
return har;
}
public static void main(String[] args) throws UnsupportedEncodingException {
// String str = "%E6%B5%8B%AF";
String str = "测试";
str = URLEncoder.encode(str,"UTF-8");
System.out.println(str);
str = URLDecoder.decode(str,"UTF-8");
System.out.println(str);
}
}
......@@ -14,4 +14,5 @@ public class SwaggerApiInfo {
private String summary; // 对应 API 的名字
private List<JSONObject> parameters; // 对应 API 的请求参数
private JSONObject requestBody;
private JSONObject responses;
}
......@@ -138,9 +138,9 @@ public class MsScenario extends MsTestElement {
// 场景变量和环境变量
Arguments arguments = arguments(config);
if (arguments != null) {
tree.add(config.valueSupposeMock(arguments));
tree.add(ParameterConfig.valueSupposeMock(arguments));
}
this.addCsvDataSet(tree, variables);
this.addCsvDataSet(tree, variables,config);
this.addCounter(tree, variables);
this.addRandom(tree, variables);
if (CollectionUtils.isNotEmpty(this.headers)) {
......
......@@ -32,6 +32,7 @@ import io.metersphere.base.domain.ApiDefinitionWithBLOBs;
import io.metersphere.base.domain.ApiTestEnvironmentWithBLOBs;
import io.metersphere.commons.constants.LoopConstants;
import io.metersphere.commons.constants.MsTestElementConstants;
import io.metersphere.commons.exception.MSException;
import io.metersphere.commons.utils.CommonBeanFactory;
import io.metersphere.commons.utils.FileUtils;
import io.metersphere.commons.utils.LogUtil;
......@@ -48,6 +49,7 @@ import org.apache.jorphan.collections.HashTree;
import org.apache.jorphan.collections.ListedHashTree;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
......@@ -199,7 +201,7 @@ public abstract class MsTestElement {
return null;
}
protected void addCsvDataSet(HashTree tree, List<ScenarioVariable> variables) {
protected void addCsvDataSet(HashTree tree, List<ScenarioVariable> variables,ParameterConfig config) {
if (CollectionUtils.isNotEmpty(variables)) {
List<ScenarioVariable> list = variables.stream().filter(ScenarioVariable::isCSVValid).collect(Collectors.toList());
if (CollectionUtils.isNotEmpty(list)) {
......@@ -211,6 +213,9 @@ public abstract class MsTestElement {
csvDataSet.setName(StringUtils.isEmpty(item.getName()) ? "CSVDataSet" : item.getName());
csvDataSet.setProperty("fileEncoding", StringUtils.isEmpty(item.getEncoding()) ? "UTF-8" : item.getEncoding());
if (CollectionUtils.isNotEmpty(item.getFiles())) {
if (!config.isOperating() && !new File(BODY_FILE_DIR + "/" + item.getFiles().get(0).getId() + "_" + item.getFiles().get(0).getName()).exists()) {
MSException.throwException(StringUtils.isEmpty(item.getName()) ? "CSVDataSet" : item.getName() + ":[ CSV文件不存在 ]");
}
csvDataSet.setProperty("filename", BODY_FILE_DIR + "/" + item.getFiles().get(0).getId() + "_" + item.getFiles().get(0).getName());
}
csvDataSet.setIgnoreFirstLine(false);
......@@ -283,13 +288,13 @@ public abstract class MsTestElement {
if (MsTestElementConstants.LoopController.name().equals(parent.getType())) {
MsLoopController loopController = (MsLoopController) parent;
if (StringUtils.equals(loopController.getLoopType(), LoopConstants.WHILE.name()) && loopController.getWhileController() != null) {
return "While 循环-" + "${LoopCounterConfigXXX}";
return "While 循环-" + "${MS_LOOP_CONTROLLER_CONFIG}";
}
if (StringUtils.equals(loopController.getLoopType(), LoopConstants.FOREACH.name()) && loopController.getForEachController() != null) {
return "ForEach 循环-" + "${LoopCounterConfigXXX}";
return "ForEach 循环-" + "${MS_LOOP_CONTROLLER_CONFIG}";
}
if (StringUtils.equals(loopController.getLoopType(), LoopConstants.LOOP_COUNT.name()) && loopController.getCountController() != null) {
return "次数循环-" + "${LoopCounterConfigXXX}";
return "次数循环-" + "${MS_LOOP_CONTROLLER_CONFIG}";
}
}
// 获取全路径以备后面使用
......
......@@ -67,7 +67,8 @@ public class MsAssertions extends MsTestElement {
private ResponseAssertion responseAssertion(MsAssertionRegex assertionRegex) {
ResponseAssertion assertion = new ResponseAssertion();
assertion.setEnabled(this.isEnable());
assertion.setName(StringUtils.isNotEmpty(this.getName()) ? this.getName() : assertionRegex.getDescription());
assertion.setName(assertionRegex.getDescription());
assertion.setName(StringUtils.isNotEmpty(assertionRegex.getDescription()) ? assertionRegex.getDescription() : this.getName());
assertion.setProperty(TestElement.TEST_CLASS, ResponseAssertion.class.getName());
assertion.setProperty(TestElement.GUI_CLASS, SaveService.aliasToClass("AssertionGui"));
assertion.setAssumeSuccess(assertionRegex.isAssumeSuccess());
......@@ -92,7 +93,8 @@ public class MsAssertions extends MsTestElement {
private JSONPathAssertion jsonPathAssertion(MsAssertionJsonPath assertionJsonPath) {
JSONPathAssertion assertion = new JSONPathAssertion();
assertion.setEnabled(this.isEnable());
assertion.setName(StringUtils.isNotEmpty(this.getName()) ? this.getName() : "JSONPathAssertion");
assertion.setName(StringUtils.isNotEmpty(assertionJsonPath.getDescription()) ? assertionJsonPath.getDescription() : this.getName());
/* assertion.setName(StringUtils.isNotEmpty(this.getName()) ? this.getName() : "JSONPathAssertion");*/
assertion.setProperty(TestElement.TEST_CLASS, JSONPathAssertion.class.getName());
assertion.setProperty(TestElement.GUI_CLASS, SaveService.aliasToClass("JSONPathAssertionGui"));
assertion.setJsonPath(assertionJsonPath.getExpression());
......@@ -112,7 +114,8 @@ public class MsAssertions extends MsTestElement {
private XPath2Assertion xPath2Assertion(MsAssertionXPath2 assertionXPath2) {
XPath2Assertion assertion = new XPath2Assertion();
assertion.setEnabled(this.isEnable());
assertion.setName(StringUtils.isNotEmpty(this.getName()) ? this.getName() : "XPath2Assertion");
assertion.setName(StringUtils.isNotEmpty(assertionXPath2.getExpression()) ? assertionXPath2.getExpression() : this.getName());
/*assertion.setName(StringUtils.isNotEmpty(this.getName()) ? this.getName() : "XPath2Assertion");*/
assertion.setProperty(TestElement.TEST_CLASS, XPath2Assertion.class.getName());
assertion.setProperty(TestElement.GUI_CLASS, SaveService.aliasToClass("XPath2AssertionGui"));
assertion.setXPathString(assertionXPath2.getExpression());
......@@ -123,7 +126,8 @@ public class MsAssertions extends MsTestElement {
private DurationAssertion durationAssertion(MsAssertionDuration assertionDuration) {
DurationAssertion assertion = new DurationAssertion();
assertion.setEnabled(this.isEnable());
assertion.setName(StringUtils.isNotEmpty(this.getName()) ? this.getName() : "Response In Time: " + assertionDuration.getValue());
assertion.setName("Response In Time: " + assertionDuration.getValue());
/* assertion.setName(StringUtils.isNotEmpty(this.getName()) ? this.getName() : "Response In Time: " + assertionDuration.getValue());*/
assertion.setProperty(TestElement.TEST_CLASS, DurationAssertion.class.getName());
assertion.setProperty(TestElement.GUI_CLASS, SaveService.aliasToClass("DurationAssertionGui"));
assertion.setAllowedDuration(assertionDuration.getValue());
......@@ -133,7 +137,8 @@ public class MsAssertions extends MsTestElement {
private JSR223Assertion jsr223Assertion(MsAssertionJSR223 assertionJSR223) {
JSR223Assertion assertion = new JSR223Assertion();
assertion.setEnabled(this.isEnable());
assertion.setName(StringUtils.isNotEmpty(this.getName()) ? this.getName() : "JSR223Assertion");
assertion.setName(StringUtils.isNotEmpty(assertionJSR223.getDesc()) ? assertionJSR223.getDesc() : this.getName());
/*assertion.setName(StringUtils.isNotEmpty(this.getName()) ? this.getName() : "JSR223Assertion");*/
assertion.setProperty(TestElement.TEST_CLASS, JSR223Assertion.class.getName());
assertion.setProperty(TestElement.GUI_CLASS, SaveService.aliasToClass("TestBeanGUI"));
assertion.setProperty("cacheKey", "true");
......
......@@ -43,7 +43,10 @@ public class MsIfController extends MsTestElement {
private IfController ifController() {
IfController ifController = new IfController();
ifController.setEnabled(this.isEnable());
ifController.setName(StringUtils.isEmpty(this.getName()) ? "IfController" : this.getName());
if (StringUtils.isEmpty(this.getName())) {
this.setName(getLabelName());
}
ifController.setName(this.getName());
ifController.setProperty(TestElement.TEST_CLASS, IfController.class.getName());
ifController.setProperty(TestElement.GUI_CLASS, SaveService.aliasToClass("IfControllerPanel"));
ifController.setCondition(this.getCondition());
......@@ -61,13 +64,13 @@ public class MsIfController extends MsTestElement {
public String getLabelName() {
if (isValid()) {
String label = variable + " " + operator;
String label = "条件控制器:" + variable + " " + operator;
if (StringUtils.isNotBlank(value)) {
label += " " + this.value;
}
return label;
}
return "";
return "IfController";
}
public String getCondition() {
......
......@@ -17,6 +17,8 @@ import org.apache.jmeter.control.LoopController;
import org.apache.jmeter.control.RunTime;
import org.apache.jmeter.control.WhileController;
import org.apache.jmeter.modifiers.CounterConfig;
import org.apache.jmeter.modifiers.JSR223PreProcessor;
import org.apache.jmeter.protocol.java.sampler.JSR223Sampler;
import org.apache.jmeter.reporters.ResultAction;
import org.apache.jmeter.save.SaveService;
import org.apache.jmeter.testelement.TestElement;
......@@ -24,6 +26,7 @@ import org.apache.jmeter.timers.ConstantTimer;
import org.apache.jorphan.collections.HashTree;
import java.util.List;
import java.util.UUID;
@Data
@EqualsAndHashCode(callSuper = true)
......@@ -42,6 +45,9 @@ public class MsLoopController extends MsTestElement {
@JSONField(ordinal = 23)
private MsWhileController whileController;
private String ms_current_timer = UUID.randomUUID().toString();
@Override
public void toHashTree(HashTree tree, List<MsTestElement> hashTree, ParameterConfig config) {
// 非导出操作,且不是启用状态则跳过执行
......@@ -50,7 +56,7 @@ public class MsLoopController extends MsTestElement {
}
final HashTree groupTree = controller(tree);
if (CollectionUtils.isNotEmpty(config.getVariables())) {
this.addCsvDataSet(groupTree, config.getVariables());
this.addCsvDataSet(groupTree, config.getVariables(),config);
this.addCounter(groupTree, config.getVariables());
this.addRandom(groupTree, config.getVariables());
}
......@@ -81,7 +87,7 @@ public class MsLoopController extends MsTestElement {
private CounterConfig addCounterConfig() {
CounterConfig counterConfig = new CounterConfig();
counterConfig.setVarName("LoopCounterConfigXXX");
counterConfig.setVarName("MS_LOOP_CONTROLLER_CONFIG");
counterConfig.setName("数循结果统计计数器");
counterConfig.setEnabled(true);
counterConfig.setProperty(TestElement.TEST_CLASS, CounterConfig.class.getName());
......@@ -122,7 +128,8 @@ public class MsLoopController extends MsTestElement {
operator = "";
value = "";
}
return "${__jexl3(" + variable + operator + value + ")}";
ms_current_timer = UUID.randomUUID().toString();
return "${__jexl3(" + variable + operator + value + " && \"${" + ms_current_timer + "}\" !=\"stop\")}";
}
private WhileController initWhileController() {
......@@ -151,6 +158,32 @@ public class MsLoopController extends MsTestElement {
return controller;
}
private String script() {
String script = "\n" +
"import java.util.*;\n" +
"import java.text.SimpleDateFormat;\n" +
"import org.apache.jmeter.threads.JMeterContextService;\n" +
"\n" +
"// 循环控制器超时后结束循环\n" +
"try{\n" +
"\tString ms_current_timer = vars.get(\"" + ms_current_timer + "\");\n" +
"\tlong _nowTime = System.currentTimeMillis(); \n" +
"\tif(ms_current_timer == null ){\n" +
"\t\tvars.put(\"" + ms_current_timer + "\",_nowTime.toString());\n" +
"\t}\n" +
"\tlong time = Long.parseLong(vars.get(\"" + ms_current_timer + "\"));\n" +
"\t if((_nowTime - time) > " + this.whileController.getTimeout() + " ){\n" +
"\t \tvars.put(\"" + ms_current_timer + "\", \"stop\");\n" +
"\t \tlog.info( \"结束循环\");\n" +
"\t }\n" +
"}catch (Exception e){\n" +
"\tlog.info( e.getMessage());\n" +
"\tvars.put(\"" + ms_current_timer + "\", \"stop\");\n" +
"}\n";
return script;
}
private HashTree controller(HashTree tree) {
if (StringUtils.equals(this.loopType, LoopConstants.WHILE.name()) && this.whileController != null) {
RunTime runTime = new RunTime();
......@@ -162,9 +195,17 @@ public class MsLoopController extends MsTestElement {
timeout = 1;
}
runTime.setRuntime(timeout);
HashTree hashTree = tree.add(initWhileController());
// 添加超时处理,防止死循环
HashTree hashTree = tree.add(runTime);
return hashTree.add(initWhileController());
JSR223PreProcessor jsr223PreProcessor = new JSR223PreProcessor();
jsr223PreProcessor.setName("循环超时处理");
jsr223PreProcessor.setProperty(TestElement.TEST_CLASS, JSR223Sampler.class.getName());
jsr223PreProcessor.setProperty(TestElement.GUI_CLASS, SaveService.aliasToClass("TestBeanGUI"));
/*jsr223PreProcessor.setProperty("cacheKey", "true");*/
jsr223PreProcessor.setProperty("scriptLanguage", "beanshell");
jsr223PreProcessor.setProperty("script", script());
hashTree.add(jsr223PreProcessor);
return hashTree;
}
if (StringUtils.equals(this.loopType, LoopConstants.FOREACH.name()) && this.forEachController != null) {
return tree.add(initForeachController());
......
......@@ -34,10 +34,10 @@ public class MsExtract extends MsTestElement {
if (!config.isOperating() && !this.isEnable()) {
return;
}
addRequestExtractors(tree);
addRequestExtractors(tree, config);
}
private void addRequestExtractors(HashTree samplerHashTree) {
private void addRequestExtractors(HashTree samplerHashTree, ParameterConfig config) {
StringJoiner extract = new StringJoiner(";");
if (CollectionUtils.isNotEmpty(this.getRegex())) {
......@@ -55,7 +55,7 @@ public class MsExtract extends MsTestElement {
samplerHashTree.add(jsonPostProcessor(extractJSONPath, extract))
);
}
if (Optional.ofNullable(extract).orElse(extract).length() > 0) {
if (Optional.ofNullable(extract).orElse(extract).length() > 0 && !config.isOperating()) {
JSR223PostProcessor shell = new JSR223PostProcessor();
shell.setEnabled(true);
shell.setName(StringUtils.isEmpty(this.getName()) ? "JSR223PostProcessor" : this.getName());
......@@ -70,7 +70,8 @@ public class MsExtract extends MsTestElement {
RegexExtractor extractor = new RegexExtractor();
extractor.setEnabled(this.isEnable());
extractor.setName(StringUtils.isNotEmpty(this.getName()) ? this.getName() : " RegexExtractor");
extractor.setName(StringUtils.isNotEmpty(extractRegex.getVariable()) ? extractRegex.getVariable() : this.getName());
/*extractor.setName(StringUtils.isNotEmpty(this.getName()) ? this.getName() : " RegexExtractor");*/
extractor.setProperty(TestElement.TEST_CLASS, RegexExtractor.class.getName());
extractor.setProperty(TestElement.GUI_CLASS, SaveService.aliasToClass("RegexExtractorGui"));
extractor.setRefName(extractRegex.getVariable());
......@@ -88,7 +89,8 @@ public class MsExtract extends MsTestElement {
private XPath2Extractor xPath2Extractor(MsExtractXPath extractXPath, StringJoiner extract) {
XPath2Extractor extractor = new XPath2Extractor();
extractor.setEnabled(this.isEnable());
extractor.setName(StringUtils.isNotEmpty(this.getName()) ? this.getName() : " XPath2Extractor");
extractor.setName(StringUtils.isNotEmpty(extractXPath.getVariable()) ? extractXPath.getVariable() : this.getName());
/*extractor.setName(StringUtils.isNotEmpty(this.getName()) ? this.getName() : " XPath2Extractor");*/
extractor.setProperty(TestElement.TEST_CLASS, XPath2Extractor.class.getName());
extractor.setProperty(TestElement.GUI_CLASS, SaveService.aliasToClass("XPath2ExtractorGui"));
extractor.setRefName(extractXPath.getVariable());
......@@ -103,7 +105,8 @@ public class MsExtract extends MsTestElement {
private JSONPostProcessor jsonPostProcessor(MsExtractJSONPath extractJSONPath, StringJoiner extract) {
JSONPostProcessor extractor = new JSONPostProcessor();
extractor.setEnabled(this.isEnable());
extractor.setName(StringUtils.isNotEmpty(this.getName()) ? this.getName() : " JSONExtractor");
extractor.setName(StringUtils.isNotEmpty(extractJSONPath.getVariable()) ? extractJSONPath.getVariable() : this.getName());
/*extractor.setName(StringUtils.isNotEmpty(this.getName()) ? this.getName() : " JSONExtractor");*/
extractor.setProperty(TestElement.TEST_CLASS, JSONPostProcessor.class.getName());
extractor.setProperty(TestElement.GUI_CLASS, SaveService.aliasToClass("JSONPostProcessorGui"));
extractor.setRefNames(extractJSONPath.getVariable());
......
......@@ -48,7 +48,7 @@ public class MsJSR223Processor extends MsTestElement {
processor.setProperty(TestElement.TEST_CLASS, JSR223Sampler.class.getName());
processor.setProperty(TestElement.GUI_CLASS, SaveService.aliasToClass("TestBeanGUI"));
processor.setProperty("cacheKey", "true");
/*processor.setProperty("cacheKey", "true");*/
processor.setProperty("scriptLanguage", this.getScriptLanguage());
if (StringUtils.isNotEmpty(this.getScriptLanguage()) && this.getScriptLanguage().equals("nashornScript")) {
processor.setProperty("scriptLanguage", "nashorn");
......
......@@ -42,7 +42,7 @@ public class MsJSR223PostProcessor extends MsTestElement {
}
processor.setProperty(TestElement.TEST_CLASS, JSR223PostProcessor.class.getName());
processor.setProperty(TestElement.GUI_CLASS, SaveService.aliasToClass("TestBeanGUI"));
processor.setProperty("cacheKey", "true");
/*processor.setProperty("cacheKey", "true");*/
processor.setProperty("scriptLanguage", this.getScriptLanguage());
if (StringUtils.isNotEmpty(this.getScriptLanguage()) && this.getScriptLanguage().equals("nashornScript")) {
processor.setProperty("scriptLanguage", "nashorn");
......
......@@ -54,7 +54,7 @@ public class MsJSR223PreProcessor extends MsTestElement {
}
processor.setProperty(TestElement.TEST_CLASS, JSR223PreProcessor.class.getName());
processor.setProperty(TestElement.GUI_CLASS, SaveService.aliasToClass("TestBeanGUI"));
processor.setProperty("cacheKey", "true");
/*processor.setProperty("cacheKey", "true");*/
processor.setProperty("scriptLanguage", this.getScriptLanguage());
if (StringUtils.isNotEmpty(this.getScriptLanguage()) && this.getScriptLanguage().equals("nashornScript")) {
processor.setProperty("scriptLanguage", "nashorn");
......
......@@ -103,6 +103,9 @@ public class MsHTTPSamplerProxy extends MsTestElement {
HTTPSamplerProxy sampler = new HTTPSamplerProxy();
sampler.setEnabled(this.isEnable());
sampler.setName(this.getName());
if (StringUtils.isEmpty(this.getName())) {
sampler.setName("HTTPSamplerProxy");
}
String name = this.getParentName(this.getParent());
if (StringUtils.isNotEmpty(name) && !config.isOperating()) {
sampler.setName(this.getName() + "<->" + name);
......@@ -126,7 +129,7 @@ public class MsHTTPSamplerProxy extends MsTestElement {
// 添加环境中的公共变量
Arguments arguments = this.addArguments(config);
if (arguments != null) {
tree.add(config.valueSupposeMock(arguments));
tree.add(ParameterConfig.valueSupposeMock(arguments));
}
try {
if (config.isEffective(this.getProjectId())) {
......
......@@ -84,7 +84,9 @@ public class MsTCPSampler extends MsTestElement {
this.setProjectId(config.getProjectId());
config.setConfig(getEnvironmentConfig(useEnvironment));
}
parseEnvironment(config.getConfig().get(this.projectId));
if(config.getConfig()!=null){
parseEnvironment(config.getConfig().get(this.projectId));
}
// 添加环境中的公共变量
Arguments arguments = this.addArguments(config);
......
......@@ -3,11 +3,14 @@ package io.metersphere.api.dto.definition.request.unknown;
import com.alibaba.fastjson.annotation.JSONType;
import io.metersphere.api.dto.definition.request.MsTestElement;
import io.metersphere.api.dto.definition.request.ParameterConfig;
import io.metersphere.commons.exception.MSException;
import io.metersphere.commons.utils.FileUtils;
import io.metersphere.commons.utils.LogUtil;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.jmeter.config.CSVDataSet;
import org.apache.jmeter.save.SaveService;
import org.apache.jmeter.testelement.TestElement;
import org.apache.jmeter.testelement.TestPlan;
......@@ -15,6 +18,7 @@ import org.apache.jmeter.threads.ThreadGroup;
import org.apache.jorphan.collections.HashTree;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;
import java.util.List;
......@@ -53,6 +57,13 @@ public class MsJmeterElement extends MsTestElement {
if (!config.isOperating() && scriptWrapper instanceof ThreadGroup && !((ThreadGroup) scriptWrapper).isEnabled()) {
LogUtil.info(((ThreadGroup) scriptWrapper).getName() + "是被禁用线程组不加入执行");
} else {
// CSV数据检查文件路径是否还存在
if (!config.isOperating() && scriptWrapper instanceof CSVDataSet) {
String path = ((CSVDataSet) scriptWrapper).getPropertyAsString("filename");
if (!new File(path).exists()) {
MSException.throwException(StringUtils.isEmpty(((CSVDataSet) scriptWrapper).getName()) ? "CSVDataSet" : ((CSVDataSet) scriptWrapper).getName() + ":[ CSV文件不存在 ]");
}
}
if (CollectionUtils.isNotEmpty(hashTree)) {
for (MsTestElement el : hashTree) {
el.toHashTree(elementTree, el.getHashTree(), config);
......@@ -62,6 +73,7 @@ public class MsJmeterElement extends MsTestElement {
}
} catch (Exception ex) {
ex.printStackTrace();
MSException.throwException(ex.getMessage());
}
}
......
......@@ -20,4 +20,5 @@ public class ApiDocumentRequest {
private String type;
private String orderCondition;
private List<String> apiIdList;
private boolean trashEnable;
}
......@@ -66,14 +66,11 @@ public class Body {
sampler.setDoMultipart(true);
}
} else {
if (!this.isJson()) {
sampler.setPostBodyRaw(true);
} else {
if (StringUtils.isNotEmpty(this.format) && "JSON-SCHEMA".equals(this.format) && this.getJsonSchema() != null) {
this.raw = JSONSchemaGenerator.getJson(com.alibaba.fastjson.JSON.toJSONString(this.getJsonSchema()));
}
if (StringUtils.isNotEmpty(this.format) && "JSON-SCHEMA".equals(this.format) && this.getJsonSchema() != null) {
this.raw = JSONSchemaGenerator.getJson(com.alibaba.fastjson.JSON.toJSONString(this.getJsonSchema()));
}
KeyValue keyValue = new KeyValue("", "JSON-SCHEMA", this.getRaw(), true, true);
sampler.setPostBodyRaw(true);
keyValue.setEnable(true);
keyValue.setEncode(false);
body.add(keyValue);
......
......@@ -54,6 +54,7 @@ public class APIBackendListenerClient extends AbstractBackendListenerClient impl
private ApiScenarioReportService apiScenarioReportService;
private ApiTestCaseService apiTestCaseService;
public String runMode = ApiRunMode.RUN.name();
......@@ -105,6 +106,10 @@ public class APIBackendListenerClient extends AbstractBackendListenerClient impl
if (apiScenarioReportService == null) {
LogUtil.error("apiScenarioReportService is required");
}
apiTestCaseService = CommonBeanFactory.getBean(ApiTestCaseService.class);
if (apiTestCaseService == null) {
LogUtil.error("apiTestCaseService is required");
}
super.setupTest(context);
}
......@@ -197,11 +202,14 @@ public class APIBackendListenerClient extends AbstractBackendListenerClient impl
apiDefinitionExecResultService.saveApiResultByScheduleTask(testResult, ApiRunMode.SCHEDULE_API_PLAN.name());
List<String> testPlanReportIdList = new ArrayList<>();
testPlanReportIdList.add(debugReportId);
for(String testPlanReportId : testPlanReportIdList) { // 更新每个测试计划的状态
testPlanReportService.checkTestPlanStatus(testPlanReportId);
}
testPlanReportService.updateReport(testPlanReportIdList, ApiRunMode.SCHEDULE_API_PLAN.name(), ReportTriggerMode.SCHEDULE.name());
} else {
apiDefinitionExecResultService.saveApiResult(testResult, ApiRunMode.API_PLAN.name());
}
} else if (StringUtils.equalsAny(this.runMode, ApiRunMode.SCENARIO.name(), ApiRunMode.SCENARIO_PLAN.name(), ApiRunMode.SCHEDULE_SCENARIO_PLAN.name())) {
} else if (StringUtils.equalsAny(this.runMode, ApiRunMode.SCENARIO.name(), ApiRunMode.SCENARIO_PLAN.name(), ApiRunMode.SCHEDULE_SCENARIO_PLAN.name(),ApiRunMode.SCHEDULE_SCENARIO.name())) {
// 执行报告不需要存储,由用户确认后在存储
testResult.setTestId(testId);
ApiScenarioReport scenarioReport = apiScenarioReportService.complete(testResult, this.runMode);
......@@ -236,13 +244,19 @@ public class APIBackendListenerClient extends AbstractBackendListenerClient impl
testPlanTestCaseService.updateTestCaseStates(ids, TestPlanTestCaseStatus.Failure.name());
}
} catch (Exception e) {
LogUtil.error(e.getMessage(), e);
}
}
sendTask(report, reportUrl, testResult);
if (StringUtils.equals(ReportTriggerMode.API.name(), report.getTriggerMode())||StringUtils.equals(ReportTriggerMode.SCHEDULE.name(), report.getTriggerMode())) {
sendTask(report, reportUrl, testResult);
}
}
private static void sendTask(ApiTestReport report, String reportUrl, TestResult testResult) {
if (report == null) {
return;
}
SystemParameterService systemParameterService = CommonBeanFactory.getBean(SystemParameterService.class);
NoticeSendService noticeSendService = CommonBeanFactory.getBean(NoticeSendService.class);
assert systemParameterService != null;
......
package io.metersphere.api.parse;
import io.metersphere.api.dto.ApiTestImportRequest;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import java.io.IOException;
import java.io.InputStream;
public interface ApiImportParser<T> {
T parse(InputStream source, ApiTestImportRequest request);
T parse(InputStream source, ApiTestImportRequest request) throws IOException, InvalidFormatException, Exception;
}
......@@ -114,9 +114,13 @@ public class ApiAutomationService {
Map<String, String> map = d.getEnvironmentMap();
if (map != null) {
if (map.isEmpty()) {
List<String> ids = (List<String>) JSONPath.read(definition, "$..projectId");
if (CollectionUtils.isNotEmpty(ids)) {
idList.addAll(new HashSet<>(ids));
try {
List<String> ids = (List<String>) JSONPath.read(definition, "$..projectId");
if (CollectionUtils.isNotEmpty(ids)) {
idList.addAll(new HashSet<>(ids));
}
} catch (Exception e) {
LogUtil.error("JSONPath.read projectId fail.");
}
} else {
Set<String> set = d.getEnvironmentMap().keySet();
......@@ -265,6 +269,9 @@ public class ApiAutomationService {
}
private void deleteApiScenarioReport(List<String> scenarioIds) {
if (scenarioIds == null || scenarioIds.isEmpty()) {
return;
}
ApiScenarioReportExample scenarioReportExample = new ApiScenarioReportExample();
scenarioReportExample.createCriteria().andScenarioIdIn(scenarioIds);
List<ApiScenarioReport> list = apiScenarioReportMapper.selectByExample(scenarioReportExample);
......@@ -316,13 +323,8 @@ public class ApiAutomationService {
}
}
public void reduction(List<SaveApiScenarioRequest> requests) {
List<String> apiIds = new ArrayList<>();
requests.forEach(item -> {
checkNameExist(item);
apiIds.add(item.getId());
});
extApiScenarioMapper.reduction(apiIds);
public void reduction(List<String> ids) {
extApiScenarioMapper.reduction(ids);
}
private void checkNameExist(SaveApiScenarioRequest request) {
......@@ -369,6 +371,9 @@ public class ApiAutomationService {
public APIScenarioReportResult createScenarioReport(String id, String scenarioId, String scenarioName, String triggerMode, String execType, String projectId, String userID) {
APIScenarioReportResult report = new APIScenarioReportResult();
if (triggerMode.equals(ApiRunMode.SCENARIO.name()) || triggerMode.equals(ApiRunMode.DEFINITION.name())) {
triggerMode = ReportTriggerMode.MANUAL.name();
}
report.setId(id);
report.setTestId(id);
if (StringUtils.isNotEmpty(scenarioName)) {
......@@ -535,8 +540,12 @@ public class ApiAutomationService {
}
// 生成报告和HashTree
HashTree hashTree = generateHashTree(item, reportId, planEnvMap);
HashTree hashTree = null;
try {
hashTree = generateHashTree(item, reportId, planEnvMap);
} catch (Exception ex) {
MSException.throwException(ex.getMessage());
}
//存储报告
batchMapper.insert(report);
......@@ -602,7 +611,12 @@ public class ApiAutomationService {
}
ParameterConfig config = new ParameterConfig();
config.setConfig(envConfig);
HashTree hashTree = request.getTestElement().generateHashTree(config);
HashTree hashTree = null;
try {
hashTree = request.getTestElement().generateHashTree(config);
} catch (Exception e) {
MSException.throwException(e.getMessage());
}
// 调用执行方法
APIScenarioReportResult reportResult = createScenarioReport(request.getId(), request.getScenarioId(), request.getScenarioName(), ReportTriggerMode.MANUAL.name(), request.getExecuteType(), request.getProjectId(),
SessionUtils.getUserId());
......
......@@ -14,6 +14,7 @@ import io.metersphere.api.dto.definition.parse.Swagger3Parser;
import io.metersphere.api.dto.definition.request.ParameterConfig;
import io.metersphere.api.dto.definition.request.ScheduleInfoSwaggerUrlRequest;
import io.metersphere.api.dto.definition.request.sampler.MsHTTPSamplerProxy;
import io.metersphere.api.dto.definition.request.sampler.MsTCPSampler;
import io.metersphere.api.dto.scenario.environment.EnvironmentConfig;
import io.metersphere.api.dto.scenario.request.RequestType;
import io.metersphere.api.dto.swaggerurl.SwaggerTaskResult;
......@@ -136,10 +137,11 @@ public class ApiDefinitionService {
public ApiDefinitionWithBLOBs getBLOBs(String id) {
return apiDefinitionMapper.selectByPrimaryKey(id);
}
public List<ApiDefinitionWithBLOBs> getBLOBs(List<String> idList) {
if(idList == null || idList.isEmpty()){
return new ArrayList<>(0);
}else{
if (idList == null || idList.isEmpty()) {
return new ArrayList<>(0);
} else {
ApiDefinitionExample example = new ApiDefinitionExample();
example.createCriteria().andIdIn(idList);
example.setOrderByClause("create_time DESC ");
......@@ -189,13 +191,8 @@ public class ApiDefinitionService {
extApiDefinitionMapper.removeToGc(apiIds);
}
public void reduction(List<SaveApiDefinitionRequest> requests) {
List<String> apiIds = new ArrayList<>();
requests.forEach(item -> {
checkNameExist(item);
apiIds.add(item.getId());
});
extApiDefinitionMapper.reduction(apiIds);
public void reduction(ApiBatchRequest request) {
extApiDefinitionMapper.reduction(request.getIds());
}
public void deleteBodyFiles(String apiId) {
......@@ -243,7 +240,7 @@ public class ApiDefinitionService {
private ApiDefinition updateTest(SaveApiDefinitionRequest request) {
checkNameExist(request);
if(StringUtils.equals(request.getMethod(),"ESB")){
if (StringUtils.equals(request.getMethod(), "ESB")) {
//ESB的接口类型数据,采用TCP方式去发送。并将方法类型改为TCP。 并修改发送数据
request = esbApiParamService.handleEsbRequest(request);
}
......@@ -272,7 +269,7 @@ public class ApiDefinitionService {
private ApiDefinition createTest(SaveApiDefinitionRequest request) {
checkNameExist(request);
if(StringUtils.equals(request.getMethod(),"ESB")){
if (StringUtils.equals(request.getMethod(), "ESB")) {
//ESB的接口类型数据,采用TCP方式去发送。并将方法类型改为TCP。 并修改发送数据
request = esbApiParamService.handleEsbRequest(request);
}
......@@ -347,26 +344,43 @@ public class ApiDefinitionService {
private void _importCreate(List<ApiDefinition> sameRequest, ApiDefinitionMapper batchMapper, ApiDefinitionWithBLOBs apiDefinition,
ApiTestCaseMapper apiTestCaseMapper, ApiTestImportRequest apiTestImportRequest, List<ApiTestCaseWithBLOBs> cases) {
if (CollectionUtils.isEmpty(sameRequest)) {
String request = setImportHashTree(apiDefinition);
batchMapper.insert(apiDefinition);
apiDefinition.setRequest(request);
importApiCase(apiDefinition, apiTestCaseMapper, apiTestImportRequest, true);
if(StringUtils.equalsIgnoreCase(apiDefinition.getProtocol(),RequestType.HTTP)){
String request = setImportHashTree(apiDefinition);
batchMapper.insert(apiDefinition);
apiDefinition.setRequest(request);
importApiCase(apiDefinition, apiTestCaseMapper, apiTestImportRequest, true);
}else{
if(StringUtils.equalsAnyIgnoreCase(apiDefinition.getProtocol(),RequestType.TCP)){
String request = setImportTCPHashTree(apiDefinition);
}
batchMapper.insert(apiDefinition);
}
} else {
String originId = apiDefinition.getId();
//如果存在则修改
apiDefinition.setId(sameRequest.get(0).getId());
String request = setImportHashTree(apiDefinition);
apiDefinitionMapper.updateByPrimaryKeyWithBLOBs(apiDefinition);
apiDefinition.setRequest(request);
importApiCase(apiDefinition, apiTestCaseMapper, apiTestImportRequest, false);
// 如果是带用例导出,重新设置接口id
if (CollectionUtils.isNotEmpty(cases)) {
cases.forEach(item -> {
if (StringUtils.equals(item.getApiDefinitionId(), originId)) {
item.setApiDefinitionId(apiDefinition.getId());
}
});
if(StringUtils.equalsIgnoreCase(apiDefinition.getProtocol(),RequestType.HTTP)){
//如果存在则修改
apiDefinition.setId(sameRequest.get(0).getId());
String request = setImportHashTree(apiDefinition);
apiDefinitionMapper.updateByPrimaryKeyWithBLOBs(apiDefinition);
apiDefinition.setRequest(request);
importApiCase(apiDefinition, apiTestCaseMapper, apiTestImportRequest, false);
// 如果是带用例导出,重新设置接口id
if (CollectionUtils.isNotEmpty(cases)) {
cases.forEach(item -> {
if (StringUtils.equals(item.getApiDefinitionId(), originId)) {
item.setApiDefinitionId(apiDefinition.getId());
}
});
}
}else {
apiDefinition.setId(sameRequest.get(0).getId());
if(StringUtils.equalsAnyIgnoreCase(apiDefinition.getProtocol(),RequestType.TCP)){
String request = setImportTCPHashTree(apiDefinition);
}
apiDefinitionMapper.updateByPrimaryKeyWithBLOBs(apiDefinition);
}
}
}
......@@ -378,20 +392,35 @@ public class ApiDefinitionService {
apiDefinition.setRequest(JSONObject.toJSONString(msHTTPSamplerProxy));
return request;
}
private String setImportTCPHashTree(ApiDefinitionWithBLOBs apiDefinition) {
String request = apiDefinition.getRequest();
MsTCPSampler tcpSampler = JSONObject.parseObject(request, MsTCPSampler.class);
tcpSampler.setId(apiDefinition.getId());
tcpSampler.setHashTree(new LinkedList<>());
apiDefinition.setRequest(JSONObject.toJSONString(tcpSampler));
return request;
}
private void importMsCase(ApiDefinitionImport apiImport, SqlSession sqlSession, ApiTestCaseMapper apiTestCaseMapper) {
List<ApiTestCaseWithBLOBs> cases = apiImport.getCases();
List<String> caseNames = apiTestCaseService.listPorjectAllCaseName(SessionUtils.getCurrentProjectId());
Set<String> existCaseName = new HashSet<>();
caseNames.forEach(item -> {
existCaseName.add(item);
});
if (CollectionUtils.isNotEmpty(cases)) {
int batchCount = 0;
cases.forEach(item -> {
item.setId(UUID.randomUUID().toString());
item.setCreateTime(System.currentTimeMillis());
item.setUpdateTime(System.currentTimeMillis());
item.setCreateUserId(SessionUtils.getUserId());
item.setUpdateUserId(SessionUtils.getUserId());
item.setProjectId(SessionUtils.getCurrentProjectId());
item.setNum(getNextNum(item.getApiDefinitionId()));
apiTestCaseMapper.insert(item);
if(!existCaseName.contains(item.getName())) {
item.setId(UUID.randomUUID().toString());
item.setCreateTime(System.currentTimeMillis());
item.setUpdateTime(System.currentTimeMillis());
item.setCreateUserId(SessionUtils.getUserId());
item.setUpdateUserId(SessionUtils.getUserId());
item.setProjectId(SessionUtils.getCurrentProjectId());
item.setNum(getNextNum(item.getApiDefinitionId()));
apiTestCaseMapper.insert(item);
}
});
if (batchCount % 300 == 0) {
sqlSession.flushStatements();
......@@ -571,12 +600,43 @@ public class ApiDefinitionService {
item.setName(item.getName().substring(0, 255));
}
item.setNum(num++);
importCreate(item, batchMapper, apiTestCaseMapper, request, apiImport.getCases());
importMsCase(apiImport, sqlSession, apiTestCaseMapper);
//如果EsbData需要存储,则需要进行接口是否更新的判断
if(apiImport.getEsbApiParamsMap()!= null){
String apiId = item.getId();
EsbApiParamsWithBLOBs model = apiImport.getEsbApiParamsMap().get(apiId);
importCreate(item, batchMapper, apiTestCaseMapper, request, apiImport.getCases());
if(model!=null){
apiImport.getEsbApiParamsMap().remove(apiId);
model.setResourceId(item.getId());
apiImport.getEsbApiParamsMap().put(item.getId(),model);
}
}else {
importCreate(item, batchMapper, apiTestCaseMapper, request, apiImport.getCases());
}
if (i % 300 == 0) {
sqlSession.flushStatements();
}
}
//判断EsbData是否需要存储
if(apiImport.getEsbApiParamsMap()!= null && apiImport.getEsbApiParamsMap().size() > 0){
EsbApiParamsMapper esbApiParamsMapper = sqlSession.getMapper(EsbApiParamsMapper.class);
for (EsbApiParamsWithBLOBs model : apiImport.getEsbApiParamsMap().values()) {
EsbApiParamsExample example = new EsbApiParamsExample();
example.createCriteria().andResourceIdEqualTo(model.getResourceId());
List<EsbApiParamsWithBLOBs> exiteModelList = esbApiParamsMapper.selectByExampleWithBLOBs(example);
if(exiteModelList.isEmpty()){
esbApiParamsMapper.insert(model);
}else{
model.setId(exiteModelList.get(0).getId());
esbApiParamsMapper.updateByPrimaryKeyWithBLOBs(model);
}
}
}
if (!CollectionUtils.isEmpty(apiImport.getCases())) {
importMsCase(apiImport, sqlSession, apiTestCaseMapper);
}
sqlSession.flushStatements();
}
......@@ -702,6 +762,7 @@ public class ApiDefinitionService {
calculateResult(resList);
return resList;
}
public List<ApiDefinitionResult> listRelevanceReview(ApiDefinitionRequest request) {
request.setOrders(ServiceUtils.getDefaultOrder(request.getOrders()));
List<ApiDefinitionResult> resList = extApiDefinitionMapper.listRelevanceReview(request);
......@@ -733,7 +794,7 @@ public class ApiDefinitionService {
res.setCaseStatus("-");
}
if(StringUtils.equals("ESB",res.getMethod())){
if (StringUtils.equalsIgnoreCase("esb", res.getMethod())) {
esbApiParamService.handleApiEsbParams(res);
}
}
......@@ -820,8 +881,7 @@ public class ApiDefinitionService {
((MsApiExportResult) apiExportResult).setProtocol(request.getProtocol());
((MsApiExportResult) apiExportResult).setProjectId(request.getProjectId());
((MsApiExportResult) apiExportResult).setVersion(System.getenv("MS_VERSION"));
}
else { // 导出为 Swagger 格式
} else { // 导出为 Swagger 格式
Swagger3Parser swagger3Parser = new Swagger3Parser();
System.out.println(apiDefinitionMapper.selectByExampleWithBLOBs(example));
apiExportResult = swagger3Parser.swagger3Export(apiDefinitionMapper.selectByExampleWithBLOBs(example));
......
......@@ -19,6 +19,7 @@ import io.metersphere.api.jmeter.JMeterService;
import io.metersphere.base.domain.*;
import io.metersphere.base.mapper.*;
import io.metersphere.base.mapper.ext.*;
import io.metersphere.commons.constants.ApiRunMode;
import io.metersphere.commons.constants.TestPlanStatus;
import io.metersphere.commons.exception.MSException;
import io.metersphere.commons.utils.*;
......@@ -50,7 +51,7 @@ public class ApiTestCaseService {
@Resource
TestPlanMapper testPlanMapper;
@Resource
TestCaseReviewMapper testCaseReviewMapper;
TestCaseReviewMapper testCaseReviewMapper;
@Resource
private ApiTestCaseMapper apiTestCaseMapper;
@Resource
......@@ -80,14 +81,20 @@ public class ApiTestCaseService {
private static final String BODY_FILE_DIR = FileUtils.BODY_FILE_DIR;
public List<String> listPorjectAllCaseName(String projectId) {
return extApiTestCaseMapper.listPorjectAllCaseName(projectId);
}
public List<ApiTestCaseResult> list(ApiTestCaseRequest request) {
request.setOrders(ServiceUtils.getDefaultOrder(request.getOrders()));
List<ApiTestCaseResult> returnList = extApiTestCaseMapper.list(request);
List<ApiTestCaseResult> returnList = extApiTestCaseMapper.list(request);
for (ApiTestCaseResult res : returnList) {
esbApiParamService.handleApiEsbParams(res);
if(StringUtils.equalsIgnoreCase(res.getApiMethod(),"esb")){
esbApiParamService.handleApiEsbParams(res);
}
}
return returnList;
return returnList;
}
public List<ApiTestCaseDTO> listSimple(ApiTestCaseRequest request) {
......@@ -145,7 +152,17 @@ public class ApiTestCaseService {
}
public ApiTestCaseWithBLOBs get(String id) {
return apiTestCaseMapper.selectByPrimaryKey(id);
// ApiTestCaseWithBLOBs returnBlobs = apiTestCaseMapper.selectByPrimaryKey(id);
ApiTestCaseInfo model = extApiTestCaseMapper.selectApiCaseInfoByPrimaryKey(id);
if(model != null ){
if(StringUtils.equalsIgnoreCase(model.getApiMethod(),"esb")){
esbApiParamService.handleApiEsbParams(model);
}
}
return model;
}
public ApiTestCaseInfo getResult(String id){
return extApiTestCaseMapper.selectApiCaseInfoByPrimaryKey(id);
}
public ApiTestCase create(SaveApiTestCaseRequest request, List<MultipartFile> bodyFiles) {
......@@ -228,7 +245,7 @@ public class ApiTestCaseService {
private ApiTestCase updateTest(SaveApiTestCaseRequest request) {
checkNameExist(request);
if(StringUtils.isNotEmpty(request.getEsbDataStruct())){
if (StringUtils.isNotEmpty(request.getEsbDataStruct())) {
request = esbApiParamService.handleEsbRequest(request);
}
......@@ -251,7 +268,7 @@ public class ApiTestCaseService {
request.setId(UUID.randomUUID().toString());
checkNameExist(request);
if(StringUtils.isNotEmpty(request.getEsbDataStruct())||StringUtils.isNotEmpty(request.getBackEsbDataStruct())){
if (StringUtils.isNotEmpty(request.getEsbDataStruct()) || StringUtils.isNotEmpty(request.getBackEsbDataStruct())) {
request = esbApiParamService.handleEsbRequest(request);
}
......@@ -330,7 +347,8 @@ public class ApiTestCaseService {
List<ApiTestCase> apiTestCases = apiTestCaseMapper.selectByExample(example);
relevance(apiTestCases, request);
}
public void relevanceByApiByReview(ApiCaseRelevanceRequest request){
public void relevanceByApiByReview(ApiCaseRelevanceRequest request) {
List<String> ids = request.getSelectIds();
if (CollectionUtils.isEmpty(ids)) {
return;
......@@ -340,6 +358,7 @@ public class ApiTestCaseService {
List<ApiTestCase> apiTestCases = apiTestCaseMapper.selectByExample(example);
relevanceByReview(apiTestCases, request);
}
public void relevanceByCase(ApiCaseRelevanceRequest request) {
List<String> ids = request.getSelectIds();
if (CollectionUtils.isEmpty(ids)) {
......@@ -389,7 +408,7 @@ public class ApiTestCaseService {
TestCaseReviewApiCase.setUpdateTime(System.currentTimeMillis());
batchMapper.insertIfNotExists(TestCaseReviewApiCase);
});
TestCaseReview testCaseReview=testCaseReviewMapper.selectByPrimaryKey(request.getReviewId());
TestCaseReview testCaseReview = testCaseReviewMapper.selectByPrimaryKey(request.getReviewId());
if (StringUtils.equals(testCaseReview.getStatus(), TestPlanStatus.Prepare.name())
|| StringUtils.equals(testCaseReview.getStatus(), TestPlanStatus.Completed.name())) {
testCaseReview.setStatus(TestPlanStatus.Underway.name());
......@@ -397,11 +416,13 @@ public class ApiTestCaseService {
}
sqlSession.flushStatements();
}
public List<String> selectIdsNotExistsInPlan(String projectId, String planId) {
return extApiTestCaseMapper.selectIdsNotExistsInPlan(projectId, planId);
}
public List<String> selectIdsNotExistsInReview(String projectId,String reviewId){
return extApiTestCaseMapper.selectIdsNotExistsInReview(projectId,reviewId);
public List<String> selectIdsNotExistsInReview(String projectId, String reviewId) {
return extApiTestCaseMapper.selectIdsNotExistsInReview(projectId, reviewId);
}
public List<ApiDataCountResult> countProtocolByProjectID(String projectId) {
......@@ -434,7 +455,12 @@ public class ApiTestCaseService {
}
public Map<String, String> getRequest(ApiTestCaseRequest request) {
List<ApiTestCaseWithBLOBs> list = extApiTestCaseMapper.getRequest(request);
List<ApiTestCaseInfo> list = extApiTestCaseMapper.getRequest(request);
for (ApiTestCaseInfo model : list) {
if(StringUtils.equalsIgnoreCase(model.getApiMethod(),"esb")){
esbApiParamService.handleApiEsbParams(model);
}
}
return list.stream().collect(Collectors.toMap(ApiTestCaseWithBLOBs::getId, ApiTestCaseWithBLOBs::getRequest));
}
......@@ -492,7 +518,22 @@ public class ApiTestCaseService {
sqlSession.flushStatements();
}
if (StringUtils.isNotEmpty(request.getEnvId())) {
List<ApiTestCaseWithBLOBs> bloBs = apiTestCaseMapper.selectByExampleWithBLOBs(apiDefinitionExample);
SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH);
ApiTestCaseMapper batchMapper = sqlSession.getMapper(ApiTestCaseMapper.class);
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
bloBs.forEach(apiTestCase -> {
JSONObject req = JSON.parseObject(apiTestCase.getRequest());
req.put("useEnvironment", request.getEnvId());
String requestStr = JSON.toJSONString(req);
apiTestCase.setRequest(requestStr);
batchMapper.updateByPrimaryKeySelective(apiTestCase);
});
sqlSession.flushStatements();
}
}
private List<String> getAllApiCaseIdsByFontedSelect(Map<String, List<String>> filters, List<String> moduleIds, String name, String projectId, String protocol, List<String> unSelectIds, String status) {
......@@ -511,7 +552,14 @@ public class ApiTestCaseService {
}
public String run(RunCaseRequest request) {
ApiTestCaseWithBLOBs testCaseWithBLOBs = apiTestCaseMapper.selectByPrimaryKey(request.getCaseId());
ApiTestCaseWithBLOBs testCaseWithBLOBs=new ApiTestCaseWithBLOBs();
if(StringUtils.equals(request.getRunMode(), ApiRunMode.JENKINS_API_PLAN.name())){
testCaseWithBLOBs= apiTestCaseMapper.selectByPrimaryKey(request.getReportId());
request.setCaseId(request.getReportId());
}else{
testCaseWithBLOBs= apiTestCaseMapper.selectByPrimaryKey(request.getCaseId());
}
// 多态JSON普通转换会丢失内容,需要通过 ObjectMapper 获取
if (testCaseWithBLOBs != null && StringUtils.isNotEmpty(testCaseWithBLOBs.getRequest())) {
try {
......@@ -597,4 +645,7 @@ public class ApiTestCaseService {
String status = apiDefinitionExecResultMapper.selectExecResult(id);
return status;
}
public ApiDefinitionExecResult getInfo(String id){
return apiDefinitionExecResultMapper.selectByPrimaryKey(id);
}
}
......@@ -10,6 +10,7 @@ import io.metersphere.api.dto.definition.SaveApiDefinitionRequest;
import io.metersphere.api.dto.definition.SaveApiTestCaseRequest;
import io.metersphere.api.dto.definition.request.sampler.MsTCPSampler;
import io.metersphere.api.dto.scenario.KeyValue;
import io.metersphere.base.domain.ApiTestCaseWithBLOBs;
import io.metersphere.base.domain.EsbApiParamsExample;
import io.metersphere.base.domain.EsbApiParamsWithBLOBs;
import io.metersphere.base.mapper.EsbApiParamsMapper;
......@@ -74,7 +75,7 @@ public class EsbApiParamService {
kv.setType(request.getType());
kv.setDescription(request.getDescription());
kv.setContentType(request.getContentType());
kv.setRequired(Boolean.parseBoolean(request.getRequired()));
kv.setRequired(request.isRequired());
returnList.add(kv);
if (request.getChildren() != null) {
List<KeyValue> childValueList = this.genKeyValueByEsbDataStruct(request.getChildren(), itemName);
......@@ -106,52 +107,124 @@ public class EsbApiParamService {
}
public void handleApiEsbParams(ApiDefinitionResult res) {
if(res == null){
return;
}
EsbApiParamsWithBLOBs esbParamBlobs = this.getEsbParamBLOBsByResourceID(res.getId());
if (esbParamBlobs == null) {
return;
}
try {
if (StringUtils.isNotEmpty(res.getRequest())) {
JSONObject jsonObj = JSONObject.parseObject(res.getRequest());
if (StringUtils.isNotEmpty(res.getRequest())) {
JSONObject jsonObj = this.addEsbInfoToJsonString(esbParamBlobs, res.getRequest());
if (jsonObj != null) {
res.setRequest(jsonObj.toJSONString());
}
JSONArray esbDataArray = JSONArray.parseArray(esbParamBlobs.getDataStruct());
jsonObj.put("esbDataStruct", esbDataArray);
}
JSONArray responseDataArray = JSONArray.parseArray(esbParamBlobs.getResponseDataStruct());
jsonObj.put("backEsbDataStruct", responseDataArray);
// try {
// if (StringUtils.isNotEmpty(res.getRequest())) {
// JSONObject jsonObj = JSONObject.parseObject(res.getRequest());
//
// JSONArray esbDataArray = JSONArray.parseArray(esbParamBlobs.getDataStruct());
// jsonObj.put("esbDataStruct", esbDataArray);
//
// JSONArray responseDataArray = JSONArray.parseArray(esbParamBlobs.getResponseDataStruct());
// jsonObj.put("backEsbDataStruct", responseDataArray);
//
// JSONObject backedScriptObj = JSONObject.parseObject(esbParamBlobs.getBackedScript());
// jsonObj.put("backScript", backedScriptObj);
//
// jsonObj.put("esbFrontedScript", esbParamBlobs.getFrontedScript());
//
// res.setRequest(jsonObj.toJSONString());
// }
// } catch (Exception e) {
// }
}
JSONObject backedScriptObj = JSONObject.parseObject(esbParamBlobs.getBackedScript());
jsonObj.put("backScript", backedScriptObj);
public void handleApiEsbParams(ApiTestCaseWithBLOBs res) {
if(res==null){
return;
}
EsbApiParamsWithBLOBs esbParamBlobs = this.getEsbParamBLOBsByResourceID(res.getId());
if (esbParamBlobs == null) {
return;
}
if (StringUtils.isNotEmpty(res.getRequest())) {
JSONObject jsonObj = this.addEsbInfoToJsonString(esbParamBlobs, res.getRequest());
if (jsonObj != null) {
res.setRequest(jsonObj.toJSONString());
}
jsonObj.put("esbFrontedScript", esbParamBlobs.getFrontedScript());
}
}
res.setRequest(jsonObj.toJSONString());
private JSONObject addEsbInfoToJsonString(EsbApiParamsWithBLOBs esbParamBlobs, String requestString) {
JSONObject returnObj = null;
try {
returnObj = JSONObject.parseObject(requestString);
JSONArray esbDataArray = JSONArray.parseArray(esbParamBlobs.getDataStruct());
if (esbDataArray == null) {
returnObj.put("esbDataStruct", "");
} else {
returnObj.put("esbDataStruct", esbDataArray);
}
JSONArray responseDataArray = JSONArray.parseArray(esbParamBlobs.getResponseDataStruct());
if (responseDataArray == null) {
returnObj.put("backEsbDataStruct", "");
} else {
returnObj.put("backEsbDataStruct", responseDataArray);
}
returnObj.put("esbFrontedScript", esbParamBlobs.getFrontedScript());
JSONObject backedScriptObj = JSONObject.parseObject(esbParamBlobs.getBackedScript());
returnObj.put("backScript", backedScriptObj);
} catch (Exception e) {
}
return returnObj;
}
public void handleApiEsbParams(ApiTestCaseResult res) {
if(res == null){
return;
}
EsbApiParamsWithBLOBs esbParamBlobs = this.getEsbParamBLOBsByResourceID(res.getId());
if (esbParamBlobs == null) {
return;
}
try {
if (StringUtils.isNotEmpty(res.getRequest())) {
JSONObject jsonObj = JSONObject.parseObject(res.getRequest());
JSONArray esbDataArray = JSONArray.parseArray(esbParamBlobs.getDataStruct());
jsonObj.put("esbDataStruct", esbDataArray);
jsonObj.put("esbFrontedScript", esbParamBlobs.getFrontedScript());
if (StringUtils.isNotEmpty(res.getRequest())) {
JSONObject jsonObj = this.addEsbInfoToJsonString(esbParamBlobs, res.getRequest());
if (jsonObj != null) {
res.setRequest(jsonObj.toJSONString());
}
JSONArray responseDataArray = JSONArray.parseArray(esbParamBlobs.getResponseDataStruct());
jsonObj.put("backEsbDataStruct", responseDataArray);
}
}
res.setRequest(jsonObj.toJSONString());
public SaveApiDefinitionRequest updateEsbRequest(SaveApiDefinitionRequest request) {
try {
//修改reqeust.parameters
//用户交互感受:ESB的发送数据以报文模板为主框架,同时前端不再有key-value的表格数据填充。
//业务逻辑: 发送ESB接口数据时,使用报文模板中的数据,同时报文模板中的${取值}目的是为了拼接数据结构(比如xml的子节点)
//代码实现: 此处打算解析前端传来的EsbDataStruct数据结构,将数据结构按照报文模板中的${取值}为最高优先级组装keyValue对象。这样Jmeter会自动拼装为合适的xml
if (StringUtils.isNotEmpty(request.getEsbDataStruct())) {
MsTCPSampler tcpSampler = (MsTCPSampler) request.getRequest();
List<KeyValue> keyValueList = this.genKeyValueListByDataStruct(tcpSampler, request.getEsbDataStruct());
tcpSampler.setParameters(keyValueList);
request.setRequest(tcpSampler);
}
//更新EsbApiParams类
// EsbApiParamsWithBLOBs esbApiParams = this.createEsbApiParam(request.getId(), request.getEsbDataStruct(), request.getBackEsbDataStruct(), request.getBackScript());
} catch (Exception e) {
e.printStackTrace();
}
return request;
}
public SaveApiDefinitionRequest handleEsbRequest(SaveApiDefinitionRequest request) {
try {
//修改reqeust.parameters
......@@ -160,10 +233,10 @@ public class EsbApiParamService {
//代码实现: 此处打算解析前端传来的EsbDataStruct数据结构,将数据结构按照报文模板中的${取值}为最高优先级组装keyValue对象。这样Jmeter会自动拼装为合适的xml
if (StringUtils.isNotEmpty(request.getEsbDataStruct())) {
MsTCPSampler tcpSampler = (MsTCPSampler) request.getRequest();
tcpSampler.setProtocol("ESB");
List<KeyValue> keyValueList = this.genKeyValueListByDataStruct(tcpSampler, request.getEsbDataStruct());
tcpSampler.setParameters(keyValueList);
}
//更新EsbApiParams类
EsbApiParamsWithBLOBs esbApiParams = this.createEsbApiParam(request.getId(), request.getEsbDataStruct(), request.getBackEsbDataStruct(), request.getBackScript());
} catch (Exception e) {
......@@ -172,6 +245,43 @@ public class EsbApiParamService {
return request;
}
// public RunDefinitionRequest handleEsbRequest(RunDefinitionRequest request) {
// try {
// //修改reqeust.parameters
// //用户交互感受:ESB的发送数据以报文模板为主框架,同时前端不再有key-value的表格数据填充。
// //业务逻辑: 发送ESB接口数据时,使用报文模板中的数据,同时报文模板中的${取值}目的是为了拼接数据结构(比如xml的子节点)
// //代码实现: 此处打算解析前端传来的EsbDataStruct数据结构,将数据结构按照报文模板中的${取值}为最高优先级组装keyValue对象。这样Jmeter会自动拼装为合适的xml
// if (StringUtils.isNotEmpty(request.getEsbDataStruct())) {
// if(request.getTestElement() instanceof MsTestPlan){
// MsTestPlan testPlan = (MsTestPlan)request.getTestElement();
// for (MsTestElement testElement: testPlan.getHashTree()) {
// if(testElement instanceof MsThreadGroup){
// MsThreadGroup group = (MsThreadGroup)testElement;
// for (MsTestElement groupElement: testPlan.getHashTree()) {
// if(groupElement instanceof MsScenario){
// MsScenario scenario = (MsScenario)groupElement;
// for (MsTestElement scenarioElement: scenario.getHashTree()) {
// if(scenarioElement instanceof MsTCPSampler){
// MsTCPSampler tcpSampler = (MsTCPSampler) scenarioElement;
// List<KeyValue> keyValueList = this.genKeyValueListByDataStruct(tcpSampler, request.getEsbDataStruct());
// tcpSampler.setParameters(keyValueList);
// }
// }
// }
// }
// }
// }
// }
// }
//
// //更新EsbApiParams类
// EsbApiParamsWithBLOBs esbApiParams = this.createEsbApiParam(request.getId(), request.getEsbDataStruct(), request.getBackEsbDataStruct(), request.getBackScript());
// } catch (Exception e) {
// e.printStackTrace();
// }
// return request;
// }
//通过esb数据结构生成keyValue集合,以及发送参数
private List<KeyValue> genKeyValueListByDataStruct(MsTCPSampler tcpSampler, String esbDataStruct) {
List<KeyValue> keyValueList = new ArrayList<>();
......@@ -236,4 +346,5 @@ public class EsbApiParamService {
example.createCriteria().andResourceIdIn(apiIds);
esbApiParamsMapper.deleteByExample(example);
}
}
package io.metersphere.api.service;
import io.metersphere.api.dto.definition.parse.ESBParser;
import io.metersphere.commons.constants.TestCaseConstants;
import io.metersphere.commons.exception.MSException;
import io.metersphere.commons.user.SessionUser;
import io.metersphere.commons.utils.SessionUtils;
import io.metersphere.excel.domain.UserExcelData;
import io.metersphere.excel.domain.UserExcelDataFactory;
import io.metersphere.excel.utils.EasyExcelExporter;
import io.metersphere.i18n.Translator;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
/**
* @author song.tianyang
* @Date 2021/3/22 7:02 下午
* @Description
*/
@Service
@Transactional(rollbackFor = Exception.class)
public class EsbImportService {
public void esbTemplateExport(HttpServletResponse response) {
try {
EasyExcelExporter easyExcelExporter = new EasyExcelExporter(new UserExcelDataFactory().getExcelDataByLocal());
easyExcelExporter.export(response, generateExportTemplate(),
Translator.get("user_import_template_name"), Translator.get("user_import_template_sheet"));
} catch (Exception e) {
MSException.throwException(e);
}
}
private List<UserExcelData> generateExportTemplate() {
List<UserExcelData> list = new ArrayList<>();
List<String> types = TestCaseConstants.Type.getValues();
List<String> methods = TestCaseConstants.Method.getValues();
SessionUser user = SessionUtils.getUser();
for (int i = 1; i <= 2; i++) {
UserExcelData data = new UserExcelData();
data.setId("user_id_" + i);
data.setName(Translator.get("user") + i);
String workspace = "";
for (int workspaceIndex = 1; workspaceIndex <= i; workspaceIndex++) {
if (workspaceIndex == 1) {
workspace = "workspace" + workspaceIndex;
} else {
workspace = workspace + "\n" + "workspace" + workspaceIndex;
}
}
data.setUserIsAdmin(Translator.get("options_no"));
data.setUserIsTester(Translator.get("options_no"));
data.setUserIsOrgMember(Translator.get("options_no"));
data.setUserIsViewer(Translator.get("options_no"));
data.setUserIsTestManager(Translator.get("options_no"));
data.setUserIsOrgAdmin(Translator.get("options_yes"));
data.setOrgAdminOrganization(workspace);
list.add(data);
}
list.add(new UserExcelData());
UserExcelData explain = new UserExcelData();
explain.setName(Translator.get("do_not_modify_header_order"));
explain.setOrgAdminOrganization("多个工作空间请换行展示");
list.add(explain);
return list;
}
public void templateExport(HttpServletResponse response) {
try {
ESBParser.export(response,"EsbTemplate");
} catch (Exception e) {
MSException.throwException(e);
}
}
}
......@@ -91,7 +91,7 @@ public class HistoricalDataUpgradeService {
for (Request request : oldScenario.getRequests()) {
// 条件控制器
MsIfController ifController = null;
if (request.getController() != null && StringUtils.isNotEmpty(request.getController().getValue())
if (request.getController() != null && StringUtils.isNotEmpty(request.getController().getOperator())
&& StringUtils.isNotEmpty(request.getController().getVariable())) {
ifController = new MsIfController();
BeanUtils.copyBean(ifController, request.getController());
......
package io.metersphere.base.domain;
import lombok.Data;
import java.io.Serializable;
@Data
public class SystemHeader implements Serializable {
private String type;
private String props;
private static final long serialVersionUID = 1L;
}
\ No newline at end of file
package io.metersphere.base.domain;
import java.util.ArrayList;
import java.util.List;
public class SystemHeaderExample {
protected String orderByClause;
protected boolean distinct;
protected List<Criteria> oredCriteria;
public SystemHeaderExample() {
oredCriteria = new ArrayList<Criteria>();
}
public void setOrderByClause(String orderByClause) {
this.orderByClause = orderByClause;
}
public String getOrderByClause() {
return orderByClause;
}
public void setDistinct(boolean distinct) {
this.distinct = distinct;
}
public boolean isDistinct() {
return distinct;
}
public List<Criteria> getOredCriteria() {
return oredCriteria;
}
public void or(Criteria criteria) {
oredCriteria.add(criteria);
}
public Criteria or() {
Criteria criteria = createCriteriaInternal();
oredCriteria.add(criteria);
return criteria;
}
public Criteria createCriteria() {
Criteria criteria = createCriteriaInternal();
if (oredCriteria.size() == 0) {
oredCriteria.add(criteria);
}
return criteria;
}
protected Criteria createCriteriaInternal() {
Criteria criteria = new Criteria();
return criteria;
}
public void clear() {
oredCriteria.clear();
orderByClause = null;
distinct = false;
}
protected abstract static class GeneratedCriteria {
protected List<Criterion> criteria;
protected GeneratedCriteria() {
super();
criteria = new ArrayList<Criterion>();
}
public boolean isValid() {
return criteria.size() > 0;
}
public List<Criterion> getAllCriteria() {
return criteria;
}
public List<Criterion> getCriteria() {
return criteria;
}
protected void addCriterion(String condition) {
if (condition == null) {
throw new RuntimeException("Value for condition cannot be null");
}
criteria.add(new Criterion(condition));
}
protected void addCriterion(String condition, Object value, String property) {
if (value == null) {
throw new RuntimeException("Value for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value));
}
protected void addCriterion(String condition, Object value1, Object value2, String property) {
if (value1 == null || value2 == null) {
throw new RuntimeException("Between values for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value1, value2));
}
public Criteria andTypeIsNull() {
addCriterion("`type` is null");
return (Criteria) this;
}
public Criteria andTypeIsNotNull() {
addCriterion("`type` is not null");
return (Criteria) this;
}
public Criteria andTypeEqualTo(String value) {
addCriterion("`type` =", value, "type");
return (Criteria) this;
}
public Criteria andTypeNotEqualTo(String value) {
addCriterion("`type` <>", value, "type");
return (Criteria) this;
}
public Criteria andTypeGreaterThan(String value) {
addCriterion("`type` >", value, "type");
return (Criteria) this;
}
public Criteria andTypeGreaterThanOrEqualTo(String value) {
addCriterion("`type` >=", value, "type");
return (Criteria) this;
}
public Criteria andTypeLessThan(String value) {
addCriterion("`type` <", value, "type");
return (Criteria) this;
}
public Criteria andTypeLessThanOrEqualTo(String value) {
addCriterion("`type` <=", value, "type");
return (Criteria) this;
}
public Criteria andTypeLike(String value) {
addCriterion("`type` like", value, "type");
return (Criteria) this;
}
public Criteria andTypeNotLike(String value) {
addCriterion("`type` not like", value, "type");
return (Criteria) this;
}
public Criteria andTypeIn(List<String> values) {
addCriterion("`type` in", values, "type");
return (Criteria) this;
}
public Criteria andTypeNotIn(List<String> values) {
addCriterion("`type` not in", values, "type");
return (Criteria) this;
}
public Criteria andTypeBetween(String value1, String value2) {
addCriterion("`type` between", value1, value2, "type");
return (Criteria) this;
}
public Criteria andTypeNotBetween(String value1, String value2) {
addCriterion("`type` not between", value1, value2, "type");
return (Criteria) this;
}
public Criteria andPropsIsNull() {
addCriterion("props is null");
return (Criteria) this;
}
public Criteria andPropsIsNotNull() {
addCriterion("props is not null");
return (Criteria) this;
}
public Criteria andPropsEqualTo(String value) {
addCriterion("props =", value, "props");
return (Criteria) this;
}
public Criteria andPropsNotEqualTo(String value) {
addCriterion("props <>", value, "props");
return (Criteria) this;
}
public Criteria andPropsGreaterThan(String value) {
addCriterion("props >", value, "props");
return (Criteria) this;
}
public Criteria andPropsGreaterThanOrEqualTo(String value) {
addCriterion("props >=", value, "props");
return (Criteria) this;
}
public Criteria andPropsLessThan(String value) {
addCriterion("props <", value, "props");
return (Criteria) this;
}
public Criteria andPropsLessThanOrEqualTo(String value) {
addCriterion("props <=", value, "props");
return (Criteria) this;
}
public Criteria andPropsLike(String value) {
addCriterion("props like", value, "props");
return (Criteria) this;
}
public Criteria andPropsNotLike(String value) {
addCriterion("props not like", value, "props");
return (Criteria) this;
}
public Criteria andPropsIn(List<String> values) {
addCriterion("props in", values, "props");
return (Criteria) this;
}
public Criteria andPropsNotIn(List<String> values) {
addCriterion("props not in", values, "props");
return (Criteria) this;
}
public Criteria andPropsBetween(String value1, String value2) {
addCriterion("props between", value1, value2, "props");
return (Criteria) this;
}
public Criteria andPropsNotBetween(String value1, String value2) {
addCriterion("props not between", value1, value2, "props");
return (Criteria) this;
}
}
public static class Criteria extends GeneratedCriteria {
protected Criteria() {
super();
}
}
public static class Criterion {
private String condition;
private Object value;
private Object secondValue;
private boolean noValue;
private boolean singleValue;
private boolean betweenValue;
private boolean listValue;
private String typeHandler;
public String getCondition() {
return condition;
}
public Object getValue() {
return value;
}
public Object getSecondValue() {
return secondValue;
}
public boolean isNoValue() {
return noValue;
}
public boolean isSingleValue() {
return singleValue;
}
public boolean isBetweenValue() {
return betweenValue;
}
public boolean isListValue() {
return listValue;
}
public String getTypeHandler() {
return typeHandler;
}
protected Criterion(String condition) {
super();
this.condition = condition;
this.typeHandler = null;
this.noValue = true;
}
protected Criterion(String condition, Object value, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.typeHandler = typeHandler;
if (value instanceof List<?>) {
this.listValue = true;
} else {
this.singleValue = true;
}
}
protected Criterion(String condition, Object value) {
this(condition, value, null);
}
protected Criterion(String condition, Object value, Object secondValue, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.secondValue = secondValue;
this.typeHandler = typeHandler;
this.betweenValue = true;
}
protected Criterion(String condition, Object value, Object secondValue) {
this(condition, value, secondValue, null);
}
}
}
\ No newline at end of file
package io.metersphere.base.domain;
import lombok.Data;
import java.io.Serializable;
import lombok.Data;
@Data
public class TestCaseTest implements Serializable {
private String id;
private String testCaseId;
private String testId;
private String testType;
private Long createTime;
private Long updateTime;
private static final long serialVersionUID = 1L;
}
\ No newline at end of file
......@@ -104,76 +104,6 @@ public class TestCaseTestExample {
criteria.add(new Criterion(condition, value1, value2));
}
public Criteria andIdIsNull() {
addCriterion("id is null");
return (Criteria) this;
}
public Criteria andIdIsNotNull() {
addCriterion("id is not null");
return (Criteria) this;
}
public Criteria andIdEqualTo(String value) {
addCriterion("id =", value, "id");
return (Criteria) this;
}
public Criteria andIdNotEqualTo(String value) {
addCriterion("id <>", value, "id");
return (Criteria) this;
}
public Criteria andIdGreaterThan(String value) {
addCriterion("id >", value, "id");
return (Criteria) this;
}
public Criteria andIdGreaterThanOrEqualTo(String value) {
addCriterion("id >=", value, "id");
return (Criteria) this;
}
public Criteria andIdLessThan(String value) {
addCriterion("id <", value, "id");
return (Criteria) this;
}
public Criteria andIdLessThanOrEqualTo(String value) {
addCriterion("id <=", value, "id");
return (Criteria) this;
}
public Criteria andIdLike(String value) {
addCriterion("id like", value, "id");
return (Criteria) this;
}
public Criteria andIdNotLike(String value) {
addCriterion("id not like", value, "id");
return (Criteria) this;
}
public Criteria andIdIn(List<String> values) {
addCriterion("id in", values, "id");
return (Criteria) this;
}
public Criteria andIdNotIn(List<String> values) {
addCriterion("id not in", values, "id");
return (Criteria) this;
}
public Criteria andIdBetween(String value1, String value2) {
addCriterion("id between", value1, value2, "id");
return (Criteria) this;
}
public Criteria andIdNotBetween(String value1, String value2) {
addCriterion("id not between", value1, value2, "id");
return (Criteria) this;
}
public Criteria andTestCaseIdIsNull() {
addCriterion("test_case_id is null");
return (Criteria) this;
......@@ -383,6 +313,126 @@ public class TestCaseTestExample {
addCriterion("test_type not between", value1, value2, "testType");
return (Criteria) this;
}
public Criteria andCreateTimeIsNull() {
addCriterion("create_time is null");
return (Criteria) this;
}
public Criteria andCreateTimeIsNotNull() {
addCriterion("create_time is not null");
return (Criteria) this;
}
public Criteria andCreateTimeEqualTo(Long value) {
addCriterion("create_time =", value, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeNotEqualTo(Long value) {
addCriterion("create_time <>", value, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeGreaterThan(Long value) {
addCriterion("create_time >", value, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeGreaterThanOrEqualTo(Long value) {
addCriterion("create_time >=", value, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeLessThan(Long value) {
addCriterion("create_time <", value, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeLessThanOrEqualTo(Long value) {
addCriterion("create_time <=", value, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeIn(List<Long> values) {
addCriterion("create_time in", values, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeNotIn(List<Long> values) {
addCriterion("create_time not in", values, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeBetween(Long value1, Long value2) {
addCriterion("create_time between", value1, value2, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeNotBetween(Long value1, Long value2) {
addCriterion("create_time not between", value1, value2, "createTime");
return (Criteria) this;
}
public Criteria andUpdateTimeIsNull() {
addCriterion("update_time is null");
return (Criteria) this;
}
public Criteria andUpdateTimeIsNotNull() {
addCriterion("update_time is not null");
return (Criteria) this;
}
public Criteria andUpdateTimeEqualTo(Long value) {
addCriterion("update_time =", value, "updateTime");
return (Criteria) this;
}
public Criteria andUpdateTimeNotEqualTo(Long value) {
addCriterion("update_time <>", value, "updateTime");
return (Criteria) this;
}
public Criteria andUpdateTimeGreaterThan(Long value) {
addCriterion("update_time >", value, "updateTime");
return (Criteria) this;
}
public Criteria andUpdateTimeGreaterThanOrEqualTo(Long value) {
addCriterion("update_time >=", value, "updateTime");
return (Criteria) this;
}
public Criteria andUpdateTimeLessThan(Long value) {
addCriterion("update_time <", value, "updateTime");
return (Criteria) this;
}
public Criteria andUpdateTimeLessThanOrEqualTo(Long value) {
addCriterion("update_time <=", value, "updateTime");
return (Criteria) this;
}
public Criteria andUpdateTimeIn(List<Long> values) {
addCriterion("update_time in", values, "updateTime");
return (Criteria) this;
}
public Criteria andUpdateTimeNotIn(List<Long> values) {
addCriterion("update_time not in", values, "updateTime");
return (Criteria) this;
}
public Criteria andUpdateTimeBetween(Long value1, Long value2) {
addCriterion("update_time between", value1, value2, "updateTime");
return (Criteria) this;
}
public Criteria andUpdateTimeNotBetween(Long value1, Long value2) {
addCriterion("update_time not between", value1, value2, "updateTime");
return (Criteria) this;
}
}
public static class Criteria extends GeneratedCriteria {
......
package io.metersphere.base.mapper;
import io.metersphere.base.domain.SystemHeader;
import io.metersphere.base.domain.SystemHeaderExample;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface SystemHeaderMapper {
long countByExample(SystemHeaderExample example);
int deleteByExample(SystemHeaderExample example);
int deleteByPrimaryKey(String type);
int insert(SystemHeader record);
int insertSelective(SystemHeader record);
List<SystemHeader> selectByExample(SystemHeaderExample example);
SystemHeader selectByPrimaryKey(String type);
int updateByExampleSelective(@Param("record") SystemHeader record, @Param("example") SystemHeaderExample example);
int updateByExample(@Param("record") SystemHeader record, @Param("example") SystemHeaderExample example);
int updateByPrimaryKeySelective(SystemHeader record);
int updateByPrimaryKey(SystemHeader record);
}
\ No newline at end of file
<?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.SystemHeaderMapper">
<resultMap id="BaseResultMap" type="io.metersphere.base.domain.SystemHeader">
<id column="type" jdbcType="VARCHAR" property="type"/>
<result column="props" jdbcType="VARCHAR" property="props"/>
</resultMap>
<sql id="Example_Where_Clause">
<where>
<foreach collection="oredCriteria" item="criteria" separator="or">
<if test="criteria.valid">
<trim prefix="(" prefixOverrides="and" suffix=")">
<foreach collection="criteria.criteria" item="criterion">
<choose>
<when test="criterion.noValue">
and ${criterion.condition}
</when>
<when test="criterion.singleValue">
and ${criterion.condition} #{criterion.value}
</when>
<when test="criterion.betweenValue">
and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
</when>
<when test="criterion.listValue">
and ${criterion.condition}
<foreach close=")" collection="criterion.value" item="listItem" open="("
separator=",">
#{listItem}
</foreach>
</when>
</choose>
</foreach>
</trim>
</if>
</foreach>
</where>
</sql>
<sql id="Update_By_Example_Where_Clause">
<where>
<foreach collection="example.oredCriteria" item="criteria" separator="or">
<if test="criteria.valid">
<trim prefix="(" prefixOverrides="and" suffix=")">
<foreach collection="criteria.criteria" item="criterion">
<choose>
<when test="criterion.noValue">
and ${criterion.condition}
</when>
<when test="criterion.singleValue">
and ${criterion.condition} #{criterion.value}
</when>
<when test="criterion.betweenValue">
and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
</when>
<when test="criterion.listValue">
and ${criterion.condition}
<foreach close=")" collection="criterion.value" item="listItem" open="("
separator=",">
#{listItem}
</foreach>
</when>
</choose>
</foreach>
</trim>
</if>
</foreach>
</where>
</sql>
<sql id="Base_Column_List">
`type`, props
</sql>
<select id="selectByExample" parameterType="io.metersphere.base.domain.SystemHeaderExample"
resultMap="BaseResultMap">
select
<if test="distinct">
distinct
</if>
<include refid="Base_Column_List"/>
from system_header
<if test="_parameter != null">
<include refid="Example_Where_Clause"/>
</if>
<if test="orderByClause != null">
order by ${orderByClause}
</if>
</select>
<select id="selectByPrimaryKey" parameterType="java.lang.String" resultMap="BaseResultMap">
select
<include refid="Base_Column_List"/>
from system_header
where `type` = #{type,jdbcType=VARCHAR}
</select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.String">
delete
from system_header
where `type` = #{type,jdbcType=VARCHAR}
</delete>
<delete id="deleteByExample" parameterType="io.metersphere.base.domain.SystemHeaderExample">
delete from system_header
<if test="_parameter != null">
<include refid="Example_Where_Clause"/>
</if>
</delete>
<insert id="insert" parameterType="io.metersphere.base.domain.SystemHeader">
insert into system_header (`type`, props)
values (#{type,jdbcType=VARCHAR}, #{props,jdbcType=VARCHAR})
</insert>
<insert id="insertSelective" parameterType="io.metersphere.base.domain.SystemHeader">
insert into system_header
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="type != null">
`type`,
</if>
<if test="props != null">
props,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="type != null">
#{type,jdbcType=VARCHAR},
</if>
<if test="props != null">
#{props,jdbcType=VARCHAR},
</if>
</trim>
</insert>
<select id="countByExample" parameterType="io.metersphere.base.domain.SystemHeaderExample"
resultType="java.lang.Long">
select count(*) from system_header
<if test="_parameter != null">
<include refid="Example_Where_Clause"/>
</if>
</select>
<update id="updateByExampleSelective" parameterType="map">
update system_header
<set>
<if test="record.type != null">
`type` = #{record.type,jdbcType=VARCHAR},
</if>
<if test="record.props != null">
props = #{record.props,jdbcType=VARCHAR},
</if>
</set>
<if test="_parameter != null">
<include refid="Update_By_Example_Where_Clause"/>
</if>
</update>
<update id="updateByExample" parameterType="map">
update system_header
set `type` = #{record.type,jdbcType=VARCHAR},
props = #{record.props,jdbcType=VARCHAR}
<if test="_parameter != null">
<include refid="Update_By_Example_Where_Clause"/>
</if>
</update>
<update id="updateByPrimaryKeySelective" parameterType="io.metersphere.base.domain.SystemHeader">
update system_header
<set>
<if test="props != null">
props = #{props,jdbcType=VARCHAR},
</if>
</set>
where `type` = #{type,jdbcType=VARCHAR}
</update>
<update id="updateByPrimaryKey" parameterType="io.metersphere.base.domain.SystemHeader">
update system_header
set props = #{props,jdbcType=VARCHAR}
where `type` = #{type,jdbcType=VARCHAR}
</update>
</mapper>
\ No newline at end of file
......@@ -2,30 +2,21 @@ package io.metersphere.base.mapper;
import io.metersphere.base.domain.TestCaseTest;
import io.metersphere.base.domain.TestCaseTestExample;
import org.apache.ibatis.annotations.Param;
import java.util.List;
import org.apache.ibatis.annotations.Param;
public interface TestCaseTestMapper {
long countByExample(TestCaseTestExample example);
int deleteByExample(TestCaseTestExample example);
int deleteByPrimaryKey(String id);
int insert(TestCaseTest record);
int insertSelective(TestCaseTest record);
List<TestCaseTest> selectByExample(TestCaseTestExample example);
TestCaseTest selectByPrimaryKey(String id);
int updateByExampleSelective(@Param("record") TestCaseTest record, @Param("example") TestCaseTestExample example);
int updateByExample(@Param("record") TestCaseTest record, @Param("example") TestCaseTestExample example);
int updateByPrimaryKeySelective(TestCaseTest record);
int updateByPrimaryKey(TestCaseTest record);
}
\ No newline at end of file
<?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.TestCaseTestMapper">
<resultMap id="BaseResultMap" type="io.metersphere.base.domain.TestCaseTest">
<id column="id" jdbcType="VARCHAR" property="id"/>
<result column="test_case_id" jdbcType="VARCHAR" property="testCaseId"/>
<result column="test_id" jdbcType="VARCHAR" property="testId"/>
<result column="test_type" jdbcType="VARCHAR" property="testType"/>
</resultMap>
<sql id="Example_Where_Clause">
<where>
<foreach collection="oredCriteria" item="criteria" separator="or">
<if test="criteria.valid">
<trim prefix="(" prefixOverrides="and" suffix=")">
<foreach collection="criteria.criteria" item="criterion">
<choose>
<when test="criterion.noValue">
and ${criterion.condition}
</when>
<when test="criterion.singleValue">
and ${criterion.condition} #{criterion.value}
</when>
<when test="criterion.betweenValue">
and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
</when>
<when test="criterion.listValue">
and ${criterion.condition}
<foreach close=")" collection="criterion.value" item="listItem" open="("
separator=",">
#{listItem}
</foreach>
</when>
</choose>
</foreach>
</trim>
</if>
<resultMap id="BaseResultMap" type="io.metersphere.base.domain.TestCaseTest">
<result column="test_case_id" jdbcType="VARCHAR" property="testCaseId" />
<result column="test_id" jdbcType="VARCHAR" property="testId" />
<result column="test_type" jdbcType="VARCHAR" property="testType" />
<result column="create_time" jdbcType="BIGINT" property="createTime" />
<result column="update_time" jdbcType="BIGINT" property="updateTime" />
</resultMap>
<sql id="Example_Where_Clause">
<where>
<foreach collection="oredCriteria" item="criteria" separator="or">
<if test="criteria.valid">
<trim prefix="(" prefixOverrides="and" suffix=")">
<foreach collection="criteria.criteria" item="criterion">
<choose>
<when test="criterion.noValue">
and ${criterion.condition}
</when>
<when test="criterion.singleValue">
and ${criterion.condition} #{criterion.value}
</when>
<when test="criterion.betweenValue">
and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
</when>
<when test="criterion.listValue">
and ${criterion.condition}
<foreach close=")" collection="criterion.value" item="listItem" open="(" separator=",">
#{listItem}
</foreach>
</when>
</choose>
</foreach>
</where>
</sql>
<sql id="Update_By_Example_Where_Clause">
<where>
<foreach collection="example.oredCriteria" item="criteria" separator="or">
<if test="criteria.valid">
<trim prefix="(" prefixOverrides="and" suffix=")">
<foreach collection="criteria.criteria" item="criterion">
<choose>
<when test="criterion.noValue">
and ${criterion.condition}
</when>
<when test="criterion.singleValue">
and ${criterion.condition} #{criterion.value}
</when>
<when test="criterion.betweenValue">
and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
</when>
<when test="criterion.listValue">
and ${criterion.condition}
<foreach close=")" collection="criterion.value" item="listItem" open="("
separator=",">
#{listItem}
</foreach>
</when>
</choose>
</foreach>
</trim>
</if>
</foreach>
</where>
</sql>
<sql id="Base_Column_List">
id, test_case_id, test_id, test_type
</sql>
<select id="selectByExample" parameterType="io.metersphere.base.domain.TestCaseTestExample"
resultMap="BaseResultMap">
select
<if test="distinct">
distinct
</if>
<include refid="Base_Column_List"/>
from test_case_test
<if test="_parameter != null">
<include refid="Example_Where_Clause"/>
</if>
<if test="orderByClause != null">
order by ${orderByClause}
</if>
</select>
<select id="selectByPrimaryKey" parameterType="java.lang.String" resultMap="BaseResultMap">
select
<include refid="Base_Column_List"/>
from test_case_test
where id = #{id,jdbcType=VARCHAR}
</select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.String">
delete
from test_case_test
where id = #{id,jdbcType=VARCHAR}
</delete>
<delete id="deleteByExample" parameterType="io.metersphere.base.domain.TestCaseTestExample">
delete from test_case_test
<if test="_parameter != null">
<include refid="Example_Where_Clause"/>
</trim>
</if>
</delete>
<insert id="insert" parameterType="io.metersphere.base.domain.TestCaseTest">
insert into test_case_test (id, test_case_id, test_id,
test_type)
values (#{id,jdbcType=VARCHAR}, #{testCaseId,jdbcType=VARCHAR}, #{testId,jdbcType=VARCHAR},
#{testType,jdbcType=VARCHAR})
</insert>
<insert id="insertSelective" parameterType="io.metersphere.base.domain.TestCaseTest">
insert into test_case_test
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="id != null">
id,
</if>
<if test="testCaseId != null">
test_case_id,
</if>
<if test="testId != null">
test_id,
</if>
<if test="testType != null">
test_type,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="id != null">
#{id,jdbcType=VARCHAR},
</if>
<if test="testCaseId != null">
#{testCaseId,jdbcType=VARCHAR},
</if>
<if test="testId != null">
#{testId,jdbcType=VARCHAR},
</if>
<if test="testType != null">
#{testType,jdbcType=VARCHAR},
</if>
</trim>
</insert>
<select id="countByExample" parameterType="io.metersphere.base.domain.TestCaseTestExample"
resultType="java.lang.Long">
select count(*) from test_case_test
<if test="_parameter != null">
<include refid="Example_Where_Clause"/>
</if>
</select>
<update id="updateByExampleSelective" parameterType="map">
update test_case_test
<set>
<if test="record.id != null">
id = #{record.id,jdbcType=VARCHAR},
</if>
<if test="record.testCaseId != null">
test_case_id = #{record.testCaseId,jdbcType=VARCHAR},
</if>
<if test="record.testId != null">
test_id = #{record.testId,jdbcType=VARCHAR},
</if>
<if test="record.testType != null">
test_type = #{record.testType,jdbcType=VARCHAR},
</if>
</set>
<if test="_parameter != null">
<include refid="Update_By_Example_Where_Clause"/>
</foreach>
</where>
</sql>
<sql id="Update_By_Example_Where_Clause">
<where>
<foreach collection="example.oredCriteria" item="criteria" separator="or">
<if test="criteria.valid">
<trim prefix="(" prefixOverrides="and" suffix=")">
<foreach collection="criteria.criteria" item="criterion">
<choose>
<when test="criterion.noValue">
and ${criterion.condition}
</when>
<when test="criterion.singleValue">
and ${criterion.condition} #{criterion.value}
</when>
<when test="criterion.betweenValue">
and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
</when>
<when test="criterion.listValue">
and ${criterion.condition}
<foreach close=")" collection="criterion.value" item="listItem" open="(" separator=",">
#{listItem}
</foreach>
</when>
</choose>
</foreach>
</trim>
</if>
</update>
<update id="updateByExample" parameterType="map">
update test_case_test
set id = #{record.id,jdbcType=VARCHAR},
</foreach>
</where>
</sql>
<sql id="Base_Column_List">
test_case_id, test_id, test_type, create_time, update_time
</sql>
<select id="selectByExample" parameterType="io.metersphere.base.domain.TestCaseTestExample" resultMap="BaseResultMap">
select
<if test="distinct">
distinct
</if>
<include refid="Base_Column_List" />
from test_case_test
<if test="_parameter != null">
<include refid="Example_Where_Clause" />
</if>
<if test="orderByClause != null">
order by ${orderByClause}
</if>
</select>
<delete id="deleteByExample" parameterType="io.metersphere.base.domain.TestCaseTestExample">
delete from test_case_test
<if test="_parameter != null">
<include refid="Example_Where_Clause" />
</if>
</delete>
<insert id="insert" parameterType="io.metersphere.base.domain.TestCaseTest">
insert into test_case_test (test_case_id, test_id, test_type,
create_time, update_time)
values (#{testCaseId,jdbcType=VARCHAR}, #{testId,jdbcType=VARCHAR}, #{testType,jdbcType=VARCHAR},
#{createTime,jdbcType=BIGINT}, #{updateTime,jdbcType=BIGINT})
</insert>
<insert id="insertSelective" parameterType="io.metersphere.base.domain.TestCaseTest">
insert into test_case_test
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="testCaseId != null">
test_case_id,
</if>
<if test="testId != null">
test_id,
</if>
<if test="testType != null">
test_type,
</if>
<if test="createTime != null">
create_time,
</if>
<if test="updateTime != null">
update_time,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="testCaseId != null">
#{testCaseId,jdbcType=VARCHAR},
</if>
<if test="testId != null">
#{testId,jdbcType=VARCHAR},
</if>
<if test="testType != null">
#{testType,jdbcType=VARCHAR},
</if>
<if test="createTime != null">
#{createTime,jdbcType=BIGINT},
</if>
<if test="updateTime != null">
#{updateTime,jdbcType=BIGINT},
</if>
</trim>
</insert>
<select id="countByExample" parameterType="io.metersphere.base.domain.TestCaseTestExample" resultType="java.lang.Long">
select count(*) from test_case_test
<if test="_parameter != null">
<include refid="Example_Where_Clause" />
</if>
</select>
<update id="updateByExampleSelective" parameterType="map">
update test_case_test
<set>
<if test="record.testCaseId != null">
test_case_id = #{record.testCaseId,jdbcType=VARCHAR},
</if>
<if test="record.testId != null">
test_id = #{record.testId,jdbcType=VARCHAR},
test_type = #{record.testType,jdbcType=VARCHAR}
<if test="_parameter != null">
<include refid="Update_By_Example_Where_Clause"/>
</if>
</update>
<update id="updateByPrimaryKeySelective" parameterType="io.metersphere.base.domain.TestCaseTest">
update test_case_test
<set>
<if test="testCaseId != null">
test_case_id = #{testCaseId,jdbcType=VARCHAR},
</if>
<if test="testId != null">
test_id = #{testId,jdbcType=VARCHAR},
</if>
<if test="testType != null">
test_type = #{testType,jdbcType=VARCHAR},
</if>
</set>
where id = #{id,jdbcType=VARCHAR}
</update>
<update id="updateByPrimaryKey" parameterType="io.metersphere.base.domain.TestCaseTest">
update test_case_test
set test_case_id = #{testCaseId,jdbcType=VARCHAR},
test_id = #{testId,jdbcType=VARCHAR},
test_type = #{testType,jdbcType=VARCHAR}
where id = #{id,jdbcType=VARCHAR}
</update>
</if>
<if test="record.testType != null">
test_type = #{record.testType,jdbcType=VARCHAR},
</if>
<if test="record.createTime != null">
create_time = #{record.createTime,jdbcType=BIGINT},
</if>
<if test="record.updateTime != null">
update_time = #{record.updateTime,jdbcType=BIGINT},
</if>
</set>
<if test="_parameter != null">
<include refid="Update_By_Example_Where_Clause" />
</if>
</update>
<update id="updateByExample" parameterType="map">
update test_case_test
set test_case_id = #{record.testCaseId,jdbcType=VARCHAR},
test_id = #{record.testId,jdbcType=VARCHAR},
test_type = #{record.testType,jdbcType=VARCHAR},
create_time = #{record.createTime,jdbcType=BIGINT},
update_time = #{record.updateTime,jdbcType=BIGINT}
<if test="_parameter != null">
<include refid="Update_By_Example_Where_Clause" />
</if>
</update>
</mapper>
\ No newline at end of file
......@@ -36,9 +36,12 @@
SELECT * FROM (
SELECT testCase.testCaseID,testCase.testCaseName AS caseName,testCase.testPlanName AS testPlan ,caseErrorCountData.dataCountNumber AS failureTimes,'apiCase' AS caseType
FROM (
SELECT apiCase.id AS testCaseID,apiCase.`name` AS testCaseName,group_concat(testPlan.`name`) AS testPlanName FROM api_test_case apiCase
SELECT apiCase.id AS testCaseID,apiCase.`name` AS testCaseName,group_concat(testPlan.`name`) AS testPlanName, testPlanCase.update_time as updateTime
FROM api_test_case apiCase
inner join api_definition on api_definition.id = apiCase.api_definition_id
INNER JOIN test_plan_api_case testPlanCase ON testPlanCase.api_case_id = apiCase.id
INNER JOIN test_plan testPlan ON testPlan.id = testPlanCase.test_plan_id
and api_definition.status != 'Trash'
GROUP BY apiCase.id
ORDER BY apiCase.create_time DESC
)testCase
......@@ -48,7 +51,7 @@
SELECT id FROM api_test_case WHERE project_id = #{projectId}
) and `status` = 'error' GROUP BY resource_id
) caseErrorCountData ON caseErrorCountData.testCaseID =testCase.testCaseID
WHERE caseErrorCountData.executeTime >= #{startTimestamp}
WHERE testCase.updateTime >= #{startTimestamp}
UNION
SELECT scene.id AS testCaseID,scene.`name` AS caseName,apiScene.testPlanName AS testPlan,count(report.id) AS failureTimes,'scenario' AS caseType
FROM api_scenario_report report
......
......@@ -2,7 +2,13 @@
<!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.ExtApiDocumentMapper">
<select id="findApiDocumentSimpleInfoByRequest" resultType="io.metersphere.api.dto.document.ApiDocumentInfoDTO">
SELECT api.id,api.name FROM Api_definition api WHERE api.protocol = 'HTTP' AND api.status != 'Trash'
SELECT api.id,api.name FROM Api_definition api WHERE api.protocol = 'HTTP'
<if test="request.trashEnable == true">
AND api.status = 'Trash'
</if>
<if test="request.trashEnable == false">
AND api.status != 'Trash'
</if>
<if test="request.projectId != null">
AND api.project_Id = #{request.projectId}
</if>
......
......@@ -2,19 +2,18 @@ package io.metersphere.base.mapper.ext;
import io.metersphere.api.dto.datacount.ApiDataCountResult;
import io.metersphere.api.dto.definition.ApiTestCaseDTO;
import io.metersphere.api.dto.definition.ApiTestCaseInfo;
import io.metersphere.api.dto.definition.ApiTestCaseRequest;
import io.metersphere.api.dto.definition.ApiTestCaseResult;
import io.metersphere.base.domain.ApiTestCase;
import io.metersphere.base.domain.ApiTestCaseWithBLOBs;
import org.apache.ibatis.annotations.MapKey;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import java.util.List;
import java.util.Map;
public interface ExtApiTestCaseMapper {
List<String> listPorjectAllCaseName(@Param("projectId") String projectId);
List<ApiTestCaseResult> list(@Param("request") ApiTestCaseRequest request);
List<ApiTestCaseDTO> listSimple(@Param("request") ApiTestCaseRequest request);
......@@ -27,7 +26,9 @@ public interface ExtApiTestCaseMapper {
long countByProjectIDAndCreateInThisWeek(@Param("projectId") String projectId, @Param("firstDayTimestamp") long firstDayTimestamp, @Param("lastDayTimestamp") long lastDayTimestamp);
List<ApiTestCaseWithBLOBs> getRequest(@Param("request") ApiTestCaseRequest request);
List<ApiTestCaseInfo> getRequest(@Param("request") ApiTestCaseRequest request);
ApiTestCase getNextNum(@Param("definitionId") String definitionId);
ApiTestCaseInfo selectApiCaseInfoByPrimaryKey(String id);
}
\ No newline at end of file
......@@ -196,13 +196,25 @@
</if>
</sql>
<select id="selectApiCaseInfoByPrimaryKey" resultType="io.metersphere.api.dto.definition.ApiTestCaseInfo">
SELECT
t1.*,
a.method AS apiMethod
FROM
api_test_case t1
inner join api_definition a on t1.api_definition_id = a.id
WHERE t1.id = #{0}
</select>
<select id="list" resultType="io.metersphere.api.dto.definition.ApiTestCaseResult">
SELECT
t1.*,
t2.STATUS AS execResult,
t2.create_time AS execTime,
u2.NAME AS createUser,
u1.NAME AS updateUser
u1.NAME AS updateUser,
a.method AS apiMethod
FROM
api_test_case t1
LEFT JOIN api_definition_exec_result t2 ON t1.last_result_id = t2.id
......@@ -361,15 +373,16 @@
AND testCase.create_time BETWEEN #{firstDayTimestamp} AND #{lastDayTimestamp}
</select>
<select id="getRequest" resultType="io.metersphere.base.domain.ApiTestCaseWithBLOBs">
select id, request
from api_test_case
<select id="getRequest" resultType="io.metersphere.api.dto.definition.ApiTestCaseInfo">
select t1.id, t1.request,a.method AS apiMethod
from api_test_case t1
inner join api_definition a on t1.api_definition_id = a.id
where 1
<if test="request.id != null and request.id!=''">
and id = #{request.id}
and t1.id = #{request.id}
</if>
<if test="request.ids != null and request.ids.size() > 0">
and id in
and t1.id in
<foreach collection="request.ids" item="caseId" separator="," open="(" close=")">
#{caseId}
</foreach>
......@@ -378,6 +391,8 @@
<select id="getNextNum" resultType="io.metersphere.base.domain.ApiTestCase">
SELECT * FROM api_test_case WHERE api_test_case.api_definition_id = #{definitionId} ORDER BY num DESC LIMIT 1;
</select>
<select id="listPorjectAllCaseName" resultType="java.lang.String">
select name from api_test_case where project_id = #{projectId}
</select>
</mapper>
\ No newline at end of file
......@@ -3,6 +3,7 @@ package io.metersphere.base.mapper.ext;
import io.metersphere.base.domain.FileMetadata;
import io.metersphere.base.domain.LoadTest;
import io.metersphere.dto.LoadTestDTO;
import io.metersphere.performance.request.QueryProjectFileRequest;
import io.metersphere.performance.request.QueryTestPlanRequest;
import org.apache.ibatis.annotations.Param;
......@@ -18,6 +19,7 @@ public interface ExtLoadTestMapper {
LoadTest getNextNum(@Param("projectId") String projectId);
List<FileMetadata> getProjectFiles(@Param("projectId") String projectId, @Param("loadTypes") List<String> loadType);
List<FileMetadata> getProjectFiles(@Param("projectId") String projectId, @Param("loadTypes") List<String> loadType,
@Param("request") QueryProjectFileRequest request);
}
......@@ -145,5 +145,9 @@
#{id}
</foreach>
AND project_id = #{projectId,jdbcType=VARCHAR}
<if test="request.name!=null">
AND file_metadata.name LIKE CONCAT('%', #{request.name}, '%')
</if>
order by update_time DESC
</select>
</mapper>
\ No newline at end of file
......@@ -65,7 +65,7 @@ public interface ExtTestCaseMapper {
long countRelevanceCreatedThisWeek(@Param("projectId") String projectId,@Param("firstDayTimestamp") long firstDayTimestamp, @Param("lastDayTimestamp") long lastDayTimestamp);
List<TrackCountResult> countCoverage(@Param("projectId") String projectId);
int countCoverage(@Param("projectId") String projectId);
List<TrackCountResult> countFuncMaintainer(@Param("projectId") String projectId);
......
......@@ -306,8 +306,11 @@
or test_case.num like CONCAT('%', #{request.name},'%')
or test_case.tags like CONCAT('%', #{request.name},'%'))
</if>
<if test="request.relevanceCreateTime >0">
and test_case.id in (select test_case_id from test_case_test where test_case_test.create_time >= #{request.createTime})
</if>
<if test="request.createTime >0">
AND test_case.create_time >= #{request.createTime}
and test_case.create_time >= #{request.createTime}
</if>
<if test="request.nodeIds != null and request.nodeIds.size() > 0">
and test_case.node_id in
......@@ -320,10 +323,10 @@
</if>
<include refid="filters"/>
<if test="request.caseCoverage == 'uncoverage' ">
and test_case.test_id is null and test_case.type != 'functional'
and test_case.id not in (select distinct test_case_test.test_case_id from test_case_test)
</if>
<if test="request.caseCoverage == 'coverage' ">
and test_case.test_id is not null and test_case.type != 'functional'
and test_case.id in (select distinct test_case_test.test_case_id from test_case_test)
</if>
</where>
</sql>
......@@ -343,17 +346,19 @@
</select>
<select id="countRelevance" resultType="io.metersphere.track.response.TrackCountResult">
SELECT type AS groupField, count(id) AS countNumber FROM test_case WHERE test_case.project_id = #{projectId} GROUP BY test_case.type
SELECT test_case_test.test_type AS groupField, count(test_case_test.test_case_id) AS countNumber
FROM test_case join test_case_test on test_case.id = test_case_test.test_case_id
WHERE test_case.project_id = #{projectId} GROUP BY test_case_test.test_type
</select>
<select id="countRelevanceCreatedThisWeek" resultType="java.lang.Long">
SELECT count(id) AS countNumber FROM test_case WHERE test_case.project_id = #{projectId}
AND create_time BETWEEN #{firstDayTimestamp} AND #{lastDayTimestamp}
SELECT count(distinct test_case_test.test_case_id) AS countNumber FROM test_case join test_case_test on test_case.id = test_case_test.test_case_id
WHERE test_case.project_id = #{projectId}
AND test_case_test.create_time BETWEEN #{firstDayTimestamp} AND #{lastDayTimestamp}
</select>
<select id="countCoverage" resultType="io.metersphere.track.response.TrackCountResult">
SELECT count(test_case.id) AS countNumber,
if(test_case.test_id is null,"uncoverage","coverage") AS groupField
FROM test_case WHERE test_case.project_id=#{projectId} and test_case.type != 'functional' GROUP BY groupField
<select id="countCoverage" resultType="int">
select count(test_case.id) from test_case where test_case.project_id = #{projectId}
and test_case.id in (select distinct test_case_test.test_case_id from test_case_test)
</select>
<select id="countFuncMaintainer" resultType="io.metersphere.track.response.TrackCountResult">
select count(tc.id) as countNumber, user.name as groupField from test_case tc right join user on tc.maintainer = user.id
......@@ -362,7 +367,7 @@
</select>
<select id="countRelevanceMaintainer" resultType="io.metersphere.track.response.TrackCountResult">
select count(tc.id) as countNumber, user.name as groupField from test_case tc right join user on tc.maintainer = user.id
where tc.project_id = #{projectId} and tc.test_id is not null
where tc.project_id = #{projectId} and tc.id in (select distinct test_case_test.test_case_id from test_case_test)
group by tc.maintainer
</select>
<select id="getTestPlanBug" resultType="int">
......@@ -382,7 +387,8 @@
union all
select tpac.id as s
from test_plan_api_case tpac join api_test_case on tpac.api_case_id = api_test_case.id
where tpac.test_plan_id = #{planId}
join api_definition on api_test_case.api_definition_id = api_definition.id
where tpac.test_plan_id = #{planId} and api_definition.status != 'Trash'
union all
select tplc.id as s
from test_plan_load_case tplc join load_test on tplc.load_case_id = load_test.id
......
package io.metersphere.base.mapper.ext;
import io.metersphere.track.dto.TestCaseReportStatusResultDTO;
import io.metersphere.track.dto.TestCaseTestDTO;
import io.metersphere.track.dto.TestPlanCaseDTO;
import io.metersphere.track.request.testplancase.QueryTestPlanCaseRequest;
import org.apache.ibatis.annotations.Param;
......@@ -47,4 +48,6 @@ public interface ExtTestPlanTestCaseMapper {
List<String> getExecResultByPlanId(String planId);
List<TestPlanCaseDTO> listForMinder(@Param("planId") String planId);
List<TestCaseTestDTO> listTestCaseTest(@Param("caseId") String caseId);
}
......@@ -75,6 +75,7 @@
<include refid="condition">
<property name="object" value="${condition}.type"/>
</include>
test_case_review_users
</if>
<if test="${condition}.updateTime != null">
and test_case.update_time
......@@ -136,7 +137,7 @@
<select id="list" resultType="io.metersphere.track.dto.TestPlanCaseDTO">
select test_plan_test_case.id as id, test_case.id as caseId, test_case.name, test_case.priority,
test_case.type,test_case.test_id as testId,test_case.node_id, test_case.tags,
test_case.type,test_case.test_id as testId,test_case.node_id, test_case.tags, test_case.maintainer,
test_case.node_path, test_case.method, test_case.num, test_plan_test_case.executor, test_plan_test_case.status,
test_plan_test_case.update_time, test_case_node.name as model, project.name as projectName,
test_plan_test_case.plan_id as planId
......@@ -199,6 +200,12 @@
#{value}
</foreach>
</when>
<when test="key=='maintainer'">
and test_case.maintainer in
<foreach collection="values" item="value" separator="," open="(" close=")">
#{value}
</foreach>
</when>
<when test="key=='executor'">
and test_plan_test_case.executor in
<foreach collection="values" item="value" separator="," open="(" close=")">
......@@ -368,7 +375,7 @@
</if>
</where>
UNION ALL
SELECT test_plan_api_scenario.id as reportId,test_plan_api_scenario.api_scenario_id as id,"scenario" as
SELECT test_plan_api_scenario.api_scenario_id as testId,test_plan_api_scenario.id as id,"scenario" as
type,api_scenario.name,test_plan_api_scenario.status
from test_plan_api_scenario
left join
......@@ -421,6 +428,9 @@
pc.plan_id = #{planId}
</where>
</select>
<select id="listTestCaseTest" resultType="io.metersphere.track.dto.TestCaseTestDTO">
select * from test_case_test where test_case_id = #{caseId};
</select>
<update id="updateTestCaseStates" parameterType="java.lang.String">
update test_plan_test_case
......
package io.metersphere.commons.constants;
public enum ApiImportPlatform {
Metersphere, Postman, Swagger2, Plugin, Jmeter, Har
Metersphere, Postman, Swagger2, Plugin, Jmeter, Har,ESB
}
package io.metersphere.commons.constants;
public enum ApiRunMode {
RUN, DEBUG, DEFINITION, SCENARIO, API_PLAN, JENKINS_API_PLAN, JENKINS, SCENARIO_PLAN, API, SCHEDULE_API_PLAN, SCHEDULE_SCENARIO_PLAN, SCHEDULE_PERFORMANCE_TEST
RUN, DEBUG, DEFINITION, SCENARIO, API_PLAN, JENKINS_API_PLAN, JENKINS, SCENARIO_PLAN, API, SCHEDULE_API_PLAN, SCHEDULE_SCENARIO,SCHEDULE_SCENARIO_PLAN, SCHEDULE_PERFORMANCE_TEST
}
package io.metersphere.commons.constants;
public enum TestPlanStatus {
Prepare, Underway, Completed
Prepare, Underway, Completed, Finished
}
......@@ -22,7 +22,8 @@ public class ScriptEngineUtils {
}
}
public static String calculate(String input) {
// graal.js 禁止多线程同时访问,加上 synchronized
public synchronized static String calculate(String input) {
try {
return engine.eval("calculate('" + input + "')").toString();
} catch (ScriptException e) {
......
......@@ -13,6 +13,7 @@ public class ShiroUtils {
public static void loadBaseFilterChain(Map<String, String> filterChainDefinitionMap){
filterChainDefinitionMap.put("/resource/**", "anon");
filterChainDefinitionMap.put("/*.worker.js", "anon");
filterChainDefinitionMap.put("/login", "anon");
filterChainDefinitionMap.put("/signin", "anon");
filterChainDefinitionMap.put("/ldap/signin", "anon");
......@@ -52,6 +53,7 @@ public class ShiroUtils {
filterChainDefinitionMap.put("/", "apikey, authc"); // 跳转到 / 不用校验 csrf
filterChainDefinitionMap.put("/language", "apikey, authc");// 跳转到 /language 不用校验 csrf
filterChainDefinitionMap.put("/document", "apikey, authc"); // 跳转到 /document 不用校验 csrf
filterChainDefinitionMap.put("/test/case/file/preview/**", "apikey, authc"); // 预览测试用例附件 不用校验 csrf
}
public static Cookie getSessionIdCookie(){
......
......@@ -25,6 +25,6 @@ public class IndexController {
@GetMapping(value = "/document")
public String document() {
return "document:/";
return "document.html";
}
}
......@@ -2,6 +2,7 @@ package io.metersphere.controller;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import io.metersphere.base.domain.FileMetadata;
import io.metersphere.base.domain.Project;
import io.metersphere.commons.constants.RoleConstants;
import io.metersphere.commons.utils.PageUtils;
......@@ -86,8 +87,13 @@ public class ProjectController {
}
@PostMapping(value = "upload/files/{projectId}", consumes = {"multipart/form-data"})
public void uploadFiles(@PathVariable String projectId, @RequestPart(value = "file") List<MultipartFile> files) {
projectService.uploadFiles(projectId, files);
public List<FileMetadata> uploadFiles(@PathVariable String projectId, @RequestPart(value = "file") List<MultipartFile> files) {
return projectService.uploadFiles(projectId, files);
}
@PostMapping(value = "/update/file/{projectId}/{fileId}", consumes = {"multipart/form-data"})
public FileMetadata updateFile(@PathVariable String projectId, @PathVariable String fileId, @RequestPart(value = "file") MultipartFile file) {
return projectService.updateFile(projectId, fileId, file);
}
@GetMapping(value = "delete/file/{fileId}")
......
package io.metersphere.controller;
import io.metersphere.base.domain.SystemHeader;
import io.metersphere.base.domain.SystemParameter;
import io.metersphere.base.domain.UserHeader;
import io.metersphere.commons.constants.ParamConstants;
......@@ -51,13 +52,18 @@ public class SystemParameterController {
}
@GetMapping("/base/info")
public BaseSystemConfigDTO getBaseInfo () {
public BaseSystemConfigDTO getBaseInfo() {
return SystemParameterService.getBaseInfo();
}
@PostMapping("/system/header")
public SystemHeader getHeader(@RequestBody SystemHeader systemHeader) {
return SystemParameterService.getHeader(systemHeader.getType());
}
@PostMapping("/save/base")
@RequiresRoles(value = {RoleConstants.ADMIN})
public void saveBaseInfo (@RequestBody List<SystemParameter> systemParameter) {
public void saveBaseInfo(@RequestBody List<SystemParameter> systemParameter) {
SystemParameterService.saveBaseInfo(systemParameter);
}
......
package io.metersphere.excel.domain;
/**
* @author song.tianyang
* @Date 2021/3/22 7:04 下午
* @Description
*/
public class EsbExcelData {
}
......@@ -50,7 +50,7 @@ public class UserExcelDataCn extends UserExcelData {
@Length(max = 100)
@ColumnWidth(30)
@ExcelProperty("组织管理员工作空间")
@ExcelProperty("组织管理员组织名称")
private String orgAdminOrganization;
@NotBlank(message = "{cannot_be_null}")
......@@ -59,7 +59,7 @@ public class UserExcelDataCn extends UserExcelData {
@Length(max = 100)
@ColumnWidth(30)
@ExcelProperty("组织成员工作空间")
@ExcelProperty("组织成员组织名称")
private String orgMemberOrganization;
@NotBlank(message = "{cannot_be_null}")
......
......@@ -50,7 +50,7 @@ public class UserExcelDataTw extends TestCaseExcelData {
@Length(max = 100)
@ColumnWidth(30)
@ExcelProperty("組織管理員工作空間")
@ExcelProperty("組織管理員組織名稱")
private String orgAdminOrganization;
@NotBlank(message = "{cannot_be_null}")
......@@ -59,7 +59,7 @@ public class UserExcelDataTw extends TestCaseExcelData {
@Length(max = 100)
@ColumnWidth(30)
@ExcelProperty("組織成員工作空間")
@ExcelProperty("組織成員組織名稱")
private String orgMemberOrganization;
@NotBlank(message = "{cannot_be_null}")
......
......@@ -73,7 +73,7 @@ public class TestCaseDataListener extends EasyExcelListener<TestCaseExcelData> {
if (dbExist) {
// db exist
stringBuilder.append(Translator.get("test_case_already_exists_excel") + ":" + data.getName() + "; ");
stringBuilder.append(Translator.get("test_case_already_exists") + ":" + data.getName() + "; ");
} else {
// @Data 重写了 equals 和 hashCode 方法
excelExist = excelDataList.contains(data);
......
......@@ -3,6 +3,7 @@ package io.metersphere.job.sechedule;
import io.metersphere.api.dto.automation.ExecuteType;
import io.metersphere.api.dto.automation.RunScenarioRequest;
import io.metersphere.api.service.ApiAutomationService;
import io.metersphere.commons.constants.ApiRunMode;
import io.metersphere.commons.constants.ReportTriggerMode;
import io.metersphere.commons.constants.ScheduleGroup;
import io.metersphere.commons.utils.CommonBeanFactory;
......@@ -58,6 +59,7 @@ public class ApiScenarioTestJob extends MsScheduleJob {
request.setExecuteType(ExecuteType.Saved.name());
request.setIds(this.scenarioIds);
request.setReportUserID(this.userId);
request.setRunMode(ApiRunMode.SCHEDULE_SCENARIO.name());
apiAutomationService.run(request);
}
......
......@@ -2,6 +2,7 @@ package io.metersphere.notice.service;
import com.alibaba.nacos.client.utils.StringUtils;
import io.metersphere.commons.constants.NoticeConstants;
import io.metersphere.commons.utils.LogUtil;
import io.metersphere.notice.domain.MessageDetail;
import io.metersphere.notice.sender.NoticeModel;
import io.metersphere.notice.sender.NoticeSender;
......@@ -44,22 +45,26 @@ public class NoticeSendService {
}
public void send(String taskType, NoticeModel noticeModel) {
List<MessageDetail> messageDetails;
switch (taskType) {
case NoticeConstants.Mode.API:
messageDetails = noticeService.searchMessageByType(NoticeConstants.TaskType.JENKINS_TASK);
break;
case NoticeConstants.Mode.SCHEDULE:
messageDetails = noticeService.searchMessageByTestId(noticeModel.getTestId());
break;
default:
messageDetails = noticeService.searchMessageByType(taskType);
break;
}
messageDetails.forEach(messageDetail -> {
if (StringUtils.equals(messageDetail.getEvent(), noticeModel.getEvent())) {
this.getNoticeSender(messageDetail).send(messageDetail, noticeModel);
try {
List<MessageDetail> messageDetails;
switch (taskType) {
case NoticeConstants.Mode.API:
messageDetails = noticeService.searchMessageByType(NoticeConstants.TaskType.JENKINS_TASK);
break;
case NoticeConstants.Mode.SCHEDULE:
messageDetails = noticeService.searchMessageByTestId(noticeModel.getTestId());
break;
default:
messageDetails = noticeService.searchMessageByType(taskType);
break;
}
});
messageDetails.forEach(messageDetail -> {
if (StringUtils.equals(messageDetail.getEvent(), noticeModel.getEvent())) {
this.getNoticeSender(messageDetail).send(messageDetail, noticeModel);
}
});
} catch (Exception e) {
LogUtil.error(e.getMessage(), e);
}
}
}
......@@ -5,6 +5,7 @@ import io.metersphere.base.domain.MessageTaskExample;
import io.metersphere.base.mapper.MessageTaskMapper;
import io.metersphere.commons.exception.MSException;
import io.metersphere.commons.user.SessionUser;
import io.metersphere.commons.utils.LogUtil;
import io.metersphere.commons.utils.SessionUtils;
import io.metersphere.i18n.Translator;
import io.metersphere.notice.domain.MessageDetail;
......@@ -102,29 +103,34 @@ public class NoticeService {
}
public List<MessageDetail> searchMessageByType(String type) {
SessionUser user = SessionUtils.getUser();
String orgId = user.getLastOrganizationId();
List<MessageDetail> messageDetails = new ArrayList<>();
try {
SessionUser user = SessionUtils.getUser();
String orgId = user.getLastOrganizationId();
List<MessageDetail> messageDetails = new ArrayList<>();
MessageTaskExample example = new MessageTaskExample();
example.createCriteria()
.andTaskTypeEqualTo(type)
.andOrganizationIdEqualTo(orgId);
List<MessageTask> messageTaskLists = messageTaskMapper.selectByExampleWithBLOBs(example);
MessageTaskExample example = new MessageTaskExample();
example.createCriteria()
.andTaskTypeEqualTo(type)
.andOrganizationIdEqualTo(orgId);
List<MessageTask> messageTaskLists = messageTaskMapper.selectByExampleWithBLOBs(example);
Map<String, List<MessageTask>> messageTaskMap = messageTaskLists.stream()
.collect(Collectors.groupingBy(NoticeService::fetchGroupKey));
messageTaskMap.forEach((k, v) -> {
MessageDetail messageDetail = getMessageDetail(v);
messageDetails.add(messageDetail);
});
Map<String, List<MessageTask>> messageTaskMap = messageTaskLists.stream()
.collect(Collectors.groupingBy(NoticeService::fetchGroupKey));
messageTaskMap.forEach((k, v) -> {
MessageDetail messageDetail = getMessageDetail(v);
messageDetails.add(messageDetail);
});
return messageDetails.stream()
.sorted(Comparator.comparing(MessageDetail::getCreateTime, Comparator.nullsLast(Long::compareTo)).reversed())
.collect(Collectors.toList())
.stream()
.distinct()
.collect(Collectors.toList());
return messageDetails.stream()
.sorted(Comparator.comparing(MessageDetail::getCreateTime, Comparator.nullsLast(Long::compareTo)).reversed())
.collect(Collectors.toList())
.stream()
.distinct()
.collect(Collectors.toList());
} catch (Exception e) {
LogUtil.error(e.getMessage(), e);
return new ArrayList<>();
}
}
private MessageDetail getMessageDetail(List<MessageTask> messageTasks) {
......
......@@ -120,12 +120,13 @@ public class PerformanceTestController {
return performanceTestService.exportJmx(fileIds);
}
@GetMapping("/project/{loadType}/{projectId}/{goPage}/{pageSize}")
@PostMapping("/project/{loadType}/{projectId}/{goPage}/{pageSize}")
public Pager<List<FileMetadata>> getProjectFiles(@PathVariable String projectId, @PathVariable String loadType,
@PathVariable int goPage, @PathVariable int pageSize) {
@PathVariable int goPage, @PathVariable int pageSize,
@RequestBody QueryProjectFileRequest request) {
checkPermissionService.checkProjectOwner(projectId);
Page<Object> page = PageHelper.startPage(goPage, pageSize, true);
return PageUtils.setPageInfo(page, performanceTestService.getProjectFiles(projectId, loadType));
return PageUtils.setPageInfo(page, performanceTestService.getProjectFiles(projectId, loadType, request));
}
@PostMapping("/delete")
......
......@@ -19,8 +19,8 @@ import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;
public abstract class AbstractEngine implements Engine {
protected String JMETER_IMAGE;
......@@ -106,17 +106,20 @@ public abstract class AbstractEngine implements Engine {
String loadConfiguration = t.getLoadConfiguration();
JSONArray jsonArray = JSON.parseArray(loadConfiguration);
for (int i = 0; i < jsonArray.size(); i++) {
if (jsonArray.get(i) instanceof Map) {
JSONObject o = jsonArray.getJSONObject(i);
if (StringUtils.equals(o.getString("key"), "TargetLevel")) {
s = o.getInteger("value");
break;
}
}
if (jsonArray.get(i) instanceof List) {
JSONArray o = jsonArray.getJSONArray(i);
for (int j = 0; j < o.size(); j++) {
JSONObject b = o.getJSONObject(j);
List<JSONObject> enabledConfig = o.stream()
.filter(b -> {
JSONObject c = JSON.parseObject(b.toString());
if (StringUtils.equals(c.getString("deleted"), "true")) {
return false;
}
return !StringUtils.equals(c.getString("enabled"), "false");
})
.map(b -> JSON.parseObject(b.toString()))
.collect(Collectors.toList());
for (JSONObject b : enabledConfig) {
if (StringUtils.equals(b.getString("key"), "TargetLevel")) {
s += b.getInteger("value");
break;
......
......@@ -4,5 +4,5 @@ import lombok.Data;
@Data
public class QueryProjectFileRequest {
private String filename;
private String name;
}
......@@ -74,6 +74,7 @@ public class TestResourcePoolService {
if (StringUtils.isNotBlank(testResourcePoolDTO.getId())) {
criteria.andIdNotEqualTo(testResourcePoolDTO.getId());
}
criteria.andStatusNotEqualTo(DELETE.name());
if (testResourcePoolMapper.countByExample(example) > 0) {
MSException.throwException(Translator.get("test_resource_pool_name_already_exists"));
......
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册