diff --git a/config/jdbc-dev.yml b/config/jdbc-dev.yml index d26d748c..db1255ca 100644 --- a/config/jdbc-dev.yml +++ b/config/jdbc-dev.yml @@ -4,8 +4,20 @@ spring: url: jdbc:mysql://localhost:3306/sonic?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC&autoReconnect=true&serverTimezone=GMT%2b8 username: root password: Sonic!@#123 - jpa: - open-in-view: true - hibernate: - ddl-auto: update - show-sql: true \ No newline at end of file + # 会用到广播的事件 + initialization-mode: always + schema: + - classpath:data.sql +# mybatis-plus配置 +mybatis-plus: + mapper-locations: classpath:mapping/*.xml, classpath*:com/gitee/sunchenbin/mybatis/actable/mapping/*/*.xml + global-config: + # 是否显示mybatis-plus图标 + banner: false + configuration: + # 关闭二级缓存 + cache-enabled: false + # 关闭一级缓存 + localCacheScope: STATEMENT + # sql日志 + # log-impl: org.apache.ibatis.logging.stdout.StdOutImpl \ No newline at end of file diff --git a/config/sonic-server-folder-dev.yml b/config/sonic-server-folder-dev.yml index a4f4843a..f82a7097 100644 --- a/config/sonic-server-folder-dev.yml +++ b/config/sonic-server-folder-dev.yml @@ -2,6 +2,13 @@ server: port: 0 spring: + tomcat: + max-http-post-size: 100M + http: + multipart: + maxFileSize: 3000M + maxRequestSize: 3000M + maxPostSize: 3000M servlet: multipart: maxFileSize: -1 diff --git a/config/sonic-server-gateway-dev.yml b/config/sonic-server-gateway-dev.yml index 473de558..0f55c872 100644 --- a/config/sonic-server-gateway-dev.yml +++ b/config/sonic-server-gateway-dev.yml @@ -2,7 +2,7 @@ server: port: 8094 filter: - white-list: /users/login,/users/register,/swagger-resources,/v2/api-docs,/folder/upload,/folder/recordFiles,/keepFiles/,/imageFiles/,/recordFiles/,/logFiles/,/packageFiles/ + white-list: /users/login,/users/register,/swagger-resources,/v2/api-docs,/folder/upload,/folder/upload/recordFiles,/folder/upload/cv,/keepFiles/,/imageFiles/,/recordFiles/,/logFiles/,/packageFiles/ spring: cloud: diff --git a/config/sonic-server-task-dev.yml b/config/sonic-server-task-dev.yml index 40714e9f..2c392bba 100644 --- a/config/sonic-server-task-dev.yml +++ b/config/sonic-server-task-dev.yml @@ -1,9 +1,5 @@ server: port: 0 - -spring: - datasource: - initialization-mode: always quartz: properties: org: diff --git a/docker-compose.yml b/docker-compose.yml index 22512cc6..2b2d17a3 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1,7 +1,7 @@ version: '3' services: sonic-server-eureka: - image: "sonicorg/sonic-server-eureka:v1.2.0-release" + image: "sonicorg/sonic-server-eureka:v1.3.0-beta2" hostname: sonic-server-eureka environment: - EUREKA_HOST=sonic-server-eureka @@ -12,7 +12,7 @@ services: ports: - "9090:9090" sonic-server-bus: - image: "sonicorg/sonic-server-bus:v1.2.0-release" + image: "sonicorg/sonic-server-bus:v1.3.0-beta2" environment: - PROFILE=prod - EUREKA_URL=http://sonic:sonic@sonic-server-eureka:9090/eureka/ @@ -24,7 +24,7 @@ services: depends_on: - sonic-server-eureka sonic-server-gateway: - image: "sonicorg/sonic-server-gateway:v1.2.0-release" + image: "sonicorg/sonic-server-gateway:v1.3.0-beta2" environment: - PROFILE=prod - EUREKA_URL=http://sonic:sonic@sonic-server-eureka:9090/eureka/ @@ -38,7 +38,7 @@ services: ports: - "8094:8094" sonic-server-controller: - image: "sonicorg/sonic-server-controller:v1.3.0-beta1" + image: "sonicorg/sonic-server-controller:v1.3.0-beta2" environment: - PROFILE=prod - EUREKA_URL=http://sonic:sonic@sonic-server-eureka:9090/eureka/ @@ -51,7 +51,7 @@ services: - sonic-server-eureka - sonic-server-gateway sonic-server-folder: - image: "sonicorg/sonic-server-folder:v1.2.0-release" + image: "sonicorg/sonic-server-folder:v1.3.0-beta2" environment: - PROFILE=prod - EUREKA_URL=http://sonic:sonic@sonic-server-eureka:9090/eureka/ @@ -68,7 +68,7 @@ services: - sonic-server-eureka - sonic-server-gateway sonic-server-task: - image: "sonicorg/sonic-server-task:v1.2.0-release" + image: "sonicorg/sonic-server-task:v1.3.0-beta2" environment: - PROFILE=prod - EUREKA_URL=http://sonic:sonic@sonic-server-eureka:9090/eureka/ @@ -81,7 +81,7 @@ services: - sonic-server-eureka - sonic-server-gateway sonic-server-transport: - image: "sonicorg/sonic-server-transport:v1.3.0-beta1" + image: "sonicorg/sonic-server-transport:v1.3.0-beta2" environment: - PROFILE=prod - EUREKA_URL=http://sonic:sonic@sonic-server-eureka:9090/eureka/ diff --git a/pom.xml b/pom.xml index 5372a7d7..802781b9 100644 --- a/pom.xml +++ b/pom.xml @@ -4,7 +4,7 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - com.sonic + org.cloud.sonic sonic-server 1.0.0 pom diff --git a/sonic-server-bus/pom.xml b/sonic-server-bus/pom.xml index 47df1720..89a59eef 100644 --- a/sonic-server-bus/pom.xml +++ b/sonic-server-bus/pom.xml @@ -4,13 +4,13 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> sonic-server - com.sonic + org.cloud.sonic 1.0.0 4.0.0 sonic-server-bus - v1.2.0-release + v1.3.0-beta2 jar @@ -42,23 +42,23 @@ - - - - - org.springframework.boot - spring-boot-maven-plugin - - true - - - - com.spotify - docker-maven-plugin - - true - - - - + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/sonic-server-bus/src/main/java/com/sonic/bus/BusApplication.java b/sonic-server-bus/src/main/java/org/cloud/sonic/bus/BusApplication.java similarity index 92% rename from sonic-server-bus/src/main/java/com/sonic/bus/BusApplication.java rename to sonic-server-bus/src/main/java/org/cloud/sonic/bus/BusApplication.java index dfcf9baa..31a94eda 100644 --- a/sonic-server-bus/src/main/java/com/sonic/bus/BusApplication.java +++ b/sonic-server-bus/src/main/java/org/cloud/sonic/bus/BusApplication.java @@ -1,15 +1,15 @@ -package com.sonic.bus; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.cloud.config.server.EnableConfigServer; -import org.springframework.cloud.netflix.eureka.EnableEurekaClient; - -@SpringBootApplication -@EnableEurekaClient -@EnableConfigServer -public class BusApplication { - public static void main(String[] args) { - SpringApplication.run(BusApplication.class, args); - } +package org.cloud.sonic.bus; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.config.server.EnableConfigServer; +import org.springframework.cloud.netflix.eureka.EnableEurekaClient; + +@SpringBootApplication +@EnableEurekaClient +@EnableConfigServer +public class BusApplication { + public static void main(String[] args) { + SpringApplication.run(BusApplication.class, args); + } } \ No newline at end of file diff --git a/sonic-server-common/pom.xml b/sonic-server-common/pom.xml index 424e4223..12821aa8 100644 --- a/sonic-server-common/pom.xml +++ b/sonic-server-common/pom.xml @@ -4,7 +4,7 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> sonic-server - com.sonic + org.cloud.sonic 1.0.0 4.0.0 @@ -47,6 +47,12 @@ java-jwt 3.10.3 + + + org.projectlombok + lombok + 1.18.20 + diff --git a/sonic-server-common/src/main/java/com/sonic/common/exception/SonicException.java b/sonic-server-common/src/main/java/com/sonic/common/exception/SonicException.java deleted file mode 100644 index e180c700..00000000 --- a/sonic-server-common/src/main/java/com/sonic/common/exception/SonicException.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.sonic.common.exception; - -/** - * @author ZhouYiXun - * @des - * @date 2021/10/10 11:57 - */ -public class SonicException extends Exception { - public SonicException(String message) { - super(message); - } -} diff --git a/sonic-server-common/src/main/java/com/sonic/common/config/APIDocumentConfig.java b/sonic-server-common/src/main/java/org/cloud/sonic/common/config/APIDocumentConfig.java similarity index 96% rename from sonic-server-common/src/main/java/com/sonic/common/config/APIDocumentConfig.java rename to sonic-server-common/src/main/java/org/cloud/sonic/common/config/APIDocumentConfig.java index 07d6aa34..b1093fc9 100644 --- a/sonic-server-common/src/main/java/com/sonic/common/config/APIDocumentConfig.java +++ b/sonic-server-common/src/main/java/org/cloud/sonic/common/config/APIDocumentConfig.java @@ -1,120 +1,120 @@ -package com.sonic.common.config; - -import com.github.xiaoymin.knife4j.spring.extension.OpenApiExtensionResolver; -import io.swagger.annotations.ApiOperation; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import springfox.documentation.builders.ApiInfoBuilder; -import springfox.documentation.builders.PathSelectors; -import springfox.documentation.builders.RequestHandlerSelectors; -import springfox.documentation.service.*; -import springfox.documentation.spi.DocumentationType; -import springfox.documentation.spi.service.contexts.SecurityContext; -import springfox.documentation.spring.web.plugins.Docket; -import springfox.documentation.swagger2.annotations.EnableSwagger2WebMvc; - -import java.util.Arrays; -import java.util.List; -import java.util.Locale; - -/** - * @author ZhouYiXun - * @des swagger配置 - * @date 2021/8/15 18:26 - */ -@Configuration -@EnableSwagger2WebMvc -public class APIDocumentConfig { - //从配置文档获取接口文档信息 - @Value("${spring.application.name}") - private String name; - @Value("${spring.application.des}") - private String title; - @Value("${spring.version}") - private String version; - @Value("${knife4j.setting.enableHostText}") - private String host; - - private final OpenApiExtensionResolver openApiExtensionResolver; - - /** - * @param openApiExtensionResolver - * @return 开启knife4j接口插件 - * @author ZhouYiXun - * @des - * @date 2021/8/15 23:22 - */ - @Autowired - public APIDocumentConfig(OpenApiExtensionResolver openApiExtensionResolver) { - this.openApiExtensionResolver = openApiExtensionResolver; - } - - /** - * @return springfox.documentation.spring.web.plugins.Docket - * @author ZhouYiXun - * @des 生成最终文档的配置,默认所有路径 - * @date 2021/8/15 22:55 - */ - @Bean - public Docket createRestAPIDocket() { - return new Docket(DocumentationType.SWAGGER_2) - .host(host) - .apiInfo(apiInfo()) - .select() - .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class)) - .paths(PathSelectors.any()) - .build() - .extensions(openApiExtensionResolver.buildSettingExtensions()) - .useDefaultResponseMessages(false) - .securitySchemes(Arrays.asList( - new ApiKey("SonicToken", "SonicToken", "header"))) - .securityContexts(securityContexts()); - } - - /** - * @return java.util.List - * @author ZhouYiXun - * @des 放开Login的token校验 - * @date 2021/8/15 22:53 - */ - private List securityContexts() { - return Arrays.asList( - SecurityContext.builder() - .securityReferences(auth()) - .forPaths(PathSelectors.regex("^((?!(register|login)).)*$")) - .build() - ); - } - - /** - * @return java.util.List - * @author ZhouYiXun - * @des 设置SonicToken在接口文档页面 - * @date 2021/8/15 22:54 - */ - private List auth() { - AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything"); - AuthorizationScope[] authorizationScopes = new AuthorizationScope[1]; - authorizationScopes[0] = authorizationScope; - return Arrays.asList( - new SecurityReference("SonicToken", authorizationScopes)); - } - - /** - * @return springfox.documentation.service.ApiInfo - * @author ZhouYiXun - * @des 接口文档信息,从配置文件获取 - * @date 2021/8/15 22:54 - */ - private ApiInfo apiInfo() { - return new ApiInfoBuilder() - .title(title + " Open API") - .termsOfServiceUrl("Please visit: https://github.com/SonicCloudOrg/sonic-server") - .contact(new Contact("ZhouYiXun email: zyx291028775@qq.com", "", "")) - .version(version) - .description(name + " 服务开放API,注意不要频繁请求。") - .build(); - } +package org.cloud.sonic.common.config; + +import com.github.xiaoymin.knife4j.spring.extension.OpenApiExtensionResolver; +import io.swagger.annotations.ApiOperation; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import springfox.documentation.builders.ApiInfoBuilder; +import springfox.documentation.builders.PathSelectors; +import springfox.documentation.builders.RequestHandlerSelectors; +import springfox.documentation.service.*; +import springfox.documentation.spi.DocumentationType; +import springfox.documentation.spi.service.contexts.SecurityContext; +import springfox.documentation.spring.web.plugins.Docket; +import springfox.documentation.swagger2.annotations.EnableSwagger2WebMvc; + +import java.util.Arrays; +import java.util.List; +import java.util.Locale; + +/** + * @author ZhouYiXun + * @des swagger配置 + * @date 2021/8/15 18:26 + */ +@Configuration +@EnableSwagger2WebMvc +public class APIDocumentConfig { + //从配置文档获取接口文档信息 + @Value("${spring.application.name}") + private String name; + @Value("${spring.application.des}") + private String title; + @Value("${spring.version}") + private String version; + @Value("${knife4j.setting.enableHostText}") + private String host; + + private final OpenApiExtensionResolver openApiExtensionResolver; + + /** + * @param openApiExtensionResolver + * @return 开启knife4j接口插件 + * @author ZhouYiXun + * @des + * @date 2021/8/15 23:22 + */ + @Autowired + public APIDocumentConfig(OpenApiExtensionResolver openApiExtensionResolver) { + this.openApiExtensionResolver = openApiExtensionResolver; + } + + /** + * @return springfox.documentation.spring.web.plugins.Docket + * @author ZhouYiXun + * @des 生成最终文档的配置,默认所有路径 + * @date 2021/8/15 22:55 + */ + @Bean + public Docket createRestAPIDocket() { + return new Docket(DocumentationType.SWAGGER_2) + .host(host) + .apiInfo(apiInfo()) + .select() + .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class)) + .paths(PathSelectors.any()) + .build() + .extensions(openApiExtensionResolver.buildSettingExtensions()) + .useDefaultResponseMessages(false) + .securitySchemes(Arrays.asList( + new ApiKey("SonicToken", "SonicToken", "header"))) + .securityContexts(securityContexts()); + } + + /** + * @return java.util.List + * @author ZhouYiXun + * @des 放开Login的token校验 + * @date 2021/8/15 22:53 + */ + private List securityContexts() { + return Arrays.asList( + SecurityContext.builder() + .securityReferences(auth()) + .forPaths(PathSelectors.regex("^((?!(register|login)).)*$")) + .build() + ); + } + + /** + * @return java.util.List + * @author ZhouYiXun + * @des 设置SonicToken在接口文档页面 + * @date 2021/8/15 22:54 + */ + private List auth() { + AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything"); + AuthorizationScope[] authorizationScopes = new AuthorizationScope[1]; + authorizationScopes[0] = authorizationScope; + return Arrays.asList( + new SecurityReference("SonicToken", authorizationScopes)); + } + + /** + * @return springfox.documentation.service.ApiInfo + * @author ZhouYiXun + * @des 接口文档信息,从配置文件获取 + * @date 2021/8/15 22:54 + */ + private ApiInfo apiInfo() { + return new ApiInfoBuilder() + .title(title + " Open API") + .termsOfServiceUrl("Please visit: https://github.com/SonicCloudOrg/sonic-server") + .contact(new Contact("ZhouYiXun email: zyx291028775@qq.com", "", "")) + .version(version) + .description(name + " 服务开放API,注意不要频繁请求。") + .build(); + } } \ No newline at end of file diff --git a/sonic-server-common/src/main/java/com/sonic/common/config/GlobalWebException.java b/sonic-server-common/src/main/java/org/cloud/sonic/common/config/GlobalWebException.java similarity index 88% rename from sonic-server-common/src/main/java/com/sonic/common/config/GlobalWebException.java rename to sonic-server-common/src/main/java/org/cloud/sonic/common/config/GlobalWebException.java index 4e68bf5a..c23f5797 100644 --- a/sonic-server-common/src/main/java/com/sonic/common/config/GlobalWebException.java +++ b/sonic-server-common/src/main/java/org/cloud/sonic/common/config/GlobalWebException.java @@ -1,43 +1,43 @@ -package com.sonic.common.config; - -import com.sonic.common.exception.SonicException; -import com.sonic.common.http.RespEnum; -import com.sonic.common.http.RespModel; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.http.converter.HttpMessageNotReadableException; -import org.springframework.web.bind.MethodArgumentNotValidException; -import org.springframework.web.bind.MissingServletRequestParameterException; -import org.springframework.web.bind.annotation.ExceptionHandler; -import org.springframework.web.bind.annotation.RestControllerAdvice; - -import javax.validation.ConstraintViolationException; - -/** - * @author ZhouYiXun - * @des 全局异常拦截 - * @date 2021/8/15 18:26 - */ -@RestControllerAdvice -public class GlobalWebException { - private final Logger logger = LoggerFactory.getLogger(GlobalWebException.class); - - @ExceptionHandler(Exception.class) - public RespModel ErrHandler(Exception exception) { - logger.error(exception.getMessage()); - if (exception instanceof MissingServletRequestParameterException) { - return new RespModel(RespEnum.PARAMS_MISSING_ERROR); - } else if (exception instanceof ConstraintViolationException) { - return new RespModel(RespEnum.PARAMS_VIOLATE_ERROR); - } else if (exception instanceof MethodArgumentNotValidException) { - return new RespModel(RespEnum.PARAMS_NOT_VALID); - } else if (exception instanceof HttpMessageNotReadableException) { - return new RespModel(RespEnum.PARAMS_NOT_READABLE); - } else if (exception instanceof SonicException) { - return new RespModel(4006, exception.getMessage()); - } else { - exception.printStackTrace(); - return new RespModel(RespEnum.UNKNOWN_ERROR); - } - } +package org.cloud.sonic.common.config; + +import org.cloud.sonic.common.exception.SonicException; +import org.cloud.sonic.common.http.RespEnum; +import org.cloud.sonic.common.http.RespModel; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.http.converter.HttpMessageNotReadableException; +import org.springframework.web.bind.MethodArgumentNotValidException; +import org.springframework.web.bind.MissingServletRequestParameterException; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestControllerAdvice; + +import javax.validation.ConstraintViolationException; + +/** + * @author ZhouYiXun + * @des 全局异常拦截 + * @date 2021/8/15 18:26 + */ +@RestControllerAdvice +public class GlobalWebException { + private final Logger logger = LoggerFactory.getLogger(GlobalWebException.class); + + @ExceptionHandler(Exception.class) + public RespModel ErrHandler(Exception exception) { + logger.error(exception.getMessage()); + if (exception instanceof MissingServletRequestParameterException) { + return new RespModel(RespEnum.PARAMS_MISSING_ERROR); + } else if (exception instanceof ConstraintViolationException) { + return new RespModel(RespEnum.PARAMS_VIOLATE_ERROR); + } else if (exception instanceof MethodArgumentNotValidException) { + return new RespModel(RespEnum.PARAMS_NOT_VALID); + } else if (exception instanceof HttpMessageNotReadableException) { + return new RespModel(RespEnum.PARAMS_NOT_READABLE); + } else if (exception instanceof SonicException) { + return new RespModel(4006, exception.getMessage()); + } else { + exception.printStackTrace(); + return new RespModel(RespEnum.UNKNOWN_ERROR); + } + } } \ No newline at end of file diff --git a/sonic-server-common/src/main/java/com/sonic/common/config/WebAspect.java b/sonic-server-common/src/main/java/org/cloud/sonic/common/config/WebAspect.java similarity index 89% rename from sonic-server-common/src/main/java/com/sonic/common/config/WebAspect.java rename to sonic-server-common/src/main/java/org/cloud/sonic/common/config/WebAspect.java index 325de44c..0c4ac35a 100644 --- a/sonic-server-common/src/main/java/com/sonic/common/config/WebAspect.java +++ b/sonic-server-common/src/main/java/org/cloud/sonic/common/config/WebAspect.java @@ -1,16 +1,16 @@ -package com.sonic.common.config; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * @author ZhouYiXun - * @des 配合AOP指定对应的接口打印web请求日志 - * @date 2021/8/15 18:26 - */ -@Target({ElementType.METHOD, ElementType.TYPE}) -@Retention(RetentionPolicy.RUNTIME) -public @interface WebAspect { +package org.cloud.sonic.common.config; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * @author ZhouYiXun + * @des 配合AOP指定对应的接口打印web请求日志 + * @date 2021/8/15 18:26 + */ +@Target({ElementType.METHOD, ElementType.TYPE}) +@Retention(RetentionPolicy.RUNTIME) +public @interface WebAspect { } \ No newline at end of file diff --git a/sonic-server-common/src/main/java/com/sonic/common/config/WebAspectConfig.java b/sonic-server-common/src/main/java/org/cloud/sonic/common/config/WebAspectConfig.java similarity index 95% rename from sonic-server-common/src/main/java/com/sonic/common/config/WebAspectConfig.java rename to sonic-server-common/src/main/java/org/cloud/sonic/common/config/WebAspectConfig.java index 6abce897..052813ae 100644 --- a/sonic-server-common/src/main/java/com/sonic/common/config/WebAspectConfig.java +++ b/sonic-server-common/src/main/java/org/cloud/sonic/common/config/WebAspectConfig.java @@ -1,95 +1,95 @@ -package com.sonic.common.config; - -import com.alibaba.fastjson.JSONObject; -import org.aspectj.lang.JoinPoint; -import org.aspectj.lang.annotation.*; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.stereotype.Component; -import org.springframework.web.context.request.RequestContextHolder; -import org.springframework.web.context.request.ServletRequestAttributes; - -import javax.servlet.http.HttpServletRequest; -import java.util.Arrays; - -/** - * @author ZhouYiXun - * @des AOP框架搭配注解类,生成对应web请求日志 - * @date 2021/8/15 18:26 - */ -@Aspect -@Component -public class WebAspectConfig { - private final Logger logger = LoggerFactory.getLogger(WebAspectConfig.class); - - /** - * @return void - * @author ZhouYiXun - * @des 定义切点,注解类webAspect - * @date 2021/8/15 23:08 - */ - @Pointcut("@annotation(WebAspect)") - public void webAspect() { - } - - /** - * @param joinPoint - * @return void - * @author ZhouYiXun - * @des 请求前获取所有信息 - * @date 2021/8/15 23:08 - */ - @Before("webAspect()") - public void deBefore(JoinPoint joinPoint) throws Throwable { - ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); - HttpServletRequest request = attributes.getRequest(); - //默认打印为json格式,接入elasticsearch等会方便查看 - JSONObject jsonObject = new JSONObject(); - jsonObject.put("url", request.getRequestURL().toString()); - jsonObject.put("method", request.getMethod()); - jsonObject.put("auth", request.getHeader("SonicToken")); - jsonObject.put("class", joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName()); - jsonObject.put("request", Arrays.toString(joinPoint.getArgs())); - logger.info(jsonObject.toJSONString()); - } - - /** - * @param ret - * @return void - * @author ZhouYiXun - * @des 请求完毕后打印结果 - * @date 2021/8/15 23:10 - */ - @AfterReturning(returning = "ret", pointcut = "webAspect()") - public void doAfterReturning(Object ret) throws Throwable { - JSONObject jsonObject = new JSONObject(); - jsonObject.put("response", ret); - logger.info(jsonObject.toJSONString()); - } - - /** - * @param joinPoint - * @param ex - * @return void - * @author ZhouYiXun - * @des 报错的话打印错误信息 - * @date 2021/8/15 23:11 - */ - @AfterThrowing(throwing = "ex", pointcut = "webAspect()") - public void error(JoinPoint joinPoint, Exception ex) { - logger.info("error : " + ex.getMessage()); - } - - /** - * @param jp - * @return void - * @author ZhouYiXun - * @des 方法结束后给出标识 - * @date 2021/8/15 23:11 - */ - @After("webAspect()") - public void after(JoinPoint jp) { - logger.info("handle end"); - } - +package org.cloud.sonic.common.config; + +import com.alibaba.fastjson.JSONObject; +import org.aspectj.lang.JoinPoint; +import org.aspectj.lang.annotation.*; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; +import org.springframework.web.context.request.RequestContextHolder; +import org.springframework.web.context.request.ServletRequestAttributes; + +import javax.servlet.http.HttpServletRequest; +import java.util.Arrays; + +/** + * @author ZhouYiXun + * @des AOP框架搭配注解类,生成对应web请求日志 + * @date 2021/8/15 18:26 + */ +@Aspect +@Component +public class WebAspectConfig { + private final Logger logger = LoggerFactory.getLogger(WebAspectConfig.class); + + /** + * @return void + * @author ZhouYiXun + * @des 定义切点,注解类webAspect + * @date 2021/8/15 23:08 + */ + @Pointcut("@annotation(WebAspect)") + public void webAspect() { + } + + /** + * @param joinPoint + * @return void + * @author ZhouYiXun + * @des 请求前获取所有信息 + * @date 2021/8/15 23:08 + */ + @Before("webAspect()") + public void deBefore(JoinPoint joinPoint) throws Throwable { + ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); + HttpServletRequest request = attributes.getRequest(); + //默认打印为json格式,接入elasticsearch等会方便查看 + JSONObject jsonObject = new JSONObject(); + jsonObject.put("url", request.getRequestURL().toString()); + jsonObject.put("method", request.getMethod()); + jsonObject.put("auth", request.getHeader("SonicToken")); + jsonObject.put("class", joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName()); + jsonObject.put("request", Arrays.toString(joinPoint.getArgs())); + logger.info(jsonObject.toJSONString()); + } + + /** + * @param ret + * @return void + * @author ZhouYiXun + * @des 请求完毕后打印结果 + * @date 2021/8/15 23:10 + */ + @AfterReturning(returning = "ret", pointcut = "webAspect()") + public void doAfterReturning(Object ret) throws Throwable { + JSONObject jsonObject = new JSONObject(); + jsonObject.put("response", ret); + logger.info(jsonObject.toJSONString()); + } + + /** + * @param joinPoint + * @param ex + * @return void + * @author ZhouYiXun + * @des 报错的话打印错误信息 + * @date 2021/8/15 23:11 + */ + @AfterThrowing(throwing = "ex", pointcut = "webAspect()") + public void error(JoinPoint joinPoint, Exception ex) { + logger.info("error : " + ex.getMessage()); + } + + /** + * @param jp + * @return void + * @author ZhouYiXun + * @des 方法结束后给出标识 + * @date 2021/8/15 23:11 + */ + @After("webAspect()") + public void after(JoinPoint jp) { + logger.info("handle end"); + } + } \ No newline at end of file diff --git a/sonic-server-common/src/main/java/org/cloud/sonic/common/exception/BeanToolException.java b/sonic-server-common/src/main/java/org/cloud/sonic/common/exception/BeanToolException.java new file mode 100644 index 00000000..7793e1a9 --- /dev/null +++ b/sonic-server-common/src/main/java/org/cloud/sonic/common/exception/BeanToolException.java @@ -0,0 +1,24 @@ +package org.cloud.sonic.common.exception; + +import org.springframework.http.HttpStatus; + +/** + * BeanUtils exception. + * + * @author JayWenStar + */ +public class BeanToolException extends SonicException { + + public BeanToolException(String message) { + super(message); + } + + public BeanToolException(String message, Throwable cause) { + super(message, cause); + } + + @Override + public HttpStatus getStatus() { + return HttpStatus.INTERNAL_SERVER_ERROR; + } +} diff --git a/sonic-server-common/src/main/java/org/cloud/sonic/common/exception/ServerErrorException.java b/sonic-server-common/src/main/java/org/cloud/sonic/common/exception/ServerErrorException.java new file mode 100644 index 00000000..ebb322b3 --- /dev/null +++ b/sonic-server-common/src/main/java/org/cloud/sonic/common/exception/ServerErrorException.java @@ -0,0 +1,22 @@ +package org.cloud.sonic.common.exception; + +import org.springframework.http.HttpStatus; + +/** + * @author JayWenStar + */ +public class ServerErrorException extends SonicException { + + public ServerErrorException(String message) { + super(message); + } + + public ServerErrorException(String message, Throwable cause) { + super(message, cause); + } + + @Override + public HttpStatus getStatus() { + return HttpStatus.INTERNAL_SERVER_ERROR; + } +} diff --git a/sonic-server-common/src/main/java/org/cloud/sonic/common/exception/SonicException.java b/sonic-server-common/src/main/java/org/cloud/sonic/common/exception/SonicException.java new file mode 100644 index 00000000..888b980b --- /dev/null +++ b/sonic-server-common/src/main/java/org/cloud/sonic/common/exception/SonicException.java @@ -0,0 +1,39 @@ +package org.cloud.sonic.common.exception; + +import org.springframework.http.HttpStatus; +import org.springframework.lang.NonNull; +import org.springframework.lang.Nullable; + +/** + * @author ZhouYiXun + * @des + * @date 2021/10/10 11:57 + */ +public class SonicException extends RuntimeException { + + private Object errorData; + + public SonicException(String message) { + super(message); + } + + public SonicException(String message, Throwable cause) { + super(message, cause); + } + + @NonNull + public HttpStatus getStatus() { + return HttpStatus.OK; + } + + @Nullable + public Object getErrorData() { + return errorData; + } + + @NonNull + public SonicException setErrorData(@Nullable Object errorData) { + this.errorData = errorData; + return this; + } +} diff --git a/sonic-server-common/src/main/java/com/sonic/common/http/RespEnum.java b/sonic-server-common/src/main/java/org/cloud/sonic/common/http/RespEnum.java similarity index 94% rename from sonic-server-common/src/main/java/com/sonic/common/http/RespEnum.java rename to sonic-server-common/src/main/java/org/cloud/sonic/common/http/RespEnum.java index 0f9fb2df..fc5e3a8f 100644 --- a/sonic-server-common/src/main/java/com/sonic/common/http/RespEnum.java +++ b/sonic-server-common/src/main/java/org/cloud/sonic/common/http/RespEnum.java @@ -1,48 +1,48 @@ -package com.sonic.common.http; - -/** - * @author ZhouYiXun - * @des 接口响应枚举 - * @date 2021/8/15 18:26 - */ -public enum RespEnum { - HANDLE_OK(2000, "操作成功!"), - SEARCH_OK(2000, "查询成功!"), - UPDATE_OK(2000, "编辑成功!"), - DELETE_OK(2000, "删除成功!"), - UPLOAD_OK(2000, "上传成功!"), - UNAUTHORIZED(1001, "身份验证异常!"), - SERVICE_NOT_FOUND(1002, "相关服务不可用!"), - ID_NOT_FOUND(3001, "id不存在!"), - DELETE_ERROR(3002, "删除失败!"), - UPLOAD_ERROR(3003, "上传失败!"), - PARAMS_MISSING_ERROR(4001, "部分参数缺失!"), - PARAMS_VIOLATE_ERROR(4002, "字段校验异常!"), - UNKNOWN_ERROR(4003, "发生未知异常!"), - PARAMS_NOT_VALID(4004, "字段缺失或校验异常!"), - PARAMS_NOT_READABLE(4005, "解析参数失败!"); - - private int code; - private String message; - - RespEnum(int code, String message) { - this.code = code; - this.message = message; - } - - public int getCode() { - return code; - } - - public void setCode(int code) { - this.code = code; - } - - public String getMessage() { - return message; - } - - public void setMessage(String message) { - this.message = message; - } -} +package org.cloud.sonic.common.http; + +/** + * @author ZhouYiXun + * @des 接口响应枚举 + * @date 2021/8/15 18:26 + */ +public enum RespEnum { + HANDLE_OK(2000, "操作成功!"), + SEARCH_OK(2000, "查询成功!"), + UPDATE_OK(2000, "编辑成功!"), + DELETE_OK(2000, "删除成功!"), + UPLOAD_OK(2000, "上传成功!"), + UNAUTHORIZED(1001, "身份验证异常!"), + SERVICE_NOT_FOUND(1002, "相关服务不可用!"), + ID_NOT_FOUND(3001, "id不存在!"), + DELETE_ERROR(3002, "删除失败!"), + UPLOAD_ERROR(3003, "上传失败!"), + PARAMS_MISSING_ERROR(4001, "部分参数缺失!"), + PARAMS_VIOLATE_ERROR(4002, "字段校验异常!"), + UNKNOWN_ERROR(4003, "发生未知异常!"), + PARAMS_NOT_VALID(4004, "字段缺失或校验异常!"), + PARAMS_NOT_READABLE(4005, "解析参数失败!"); + + private int code; + private String message; + + RespEnum(int code, String message) { + this.code = code; + this.message = message; + } + + public int getCode() { + return code; + } + + public void setCode(int code) { + this.code = code; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } +} diff --git a/sonic-server-common/src/main/java/com/sonic/common/http/RespModel.java b/sonic-server-common/src/main/java/org/cloud/sonic/common/http/RespModel.java similarity index 94% rename from sonic-server-common/src/main/java/com/sonic/common/http/RespModel.java rename to sonic-server-common/src/main/java/org/cloud/sonic/common/http/RespModel.java index dd95850a..cdf2b85a 100644 --- a/sonic-server-common/src/main/java/com/sonic/common/http/RespModel.java +++ b/sonic-server-common/src/main/java/org/cloud/sonic/common/http/RespModel.java @@ -1,78 +1,78 @@ -package com.sonic.common.http; - -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; - -/** - * @author ZhouYiXun - * @des 接口响应模型,后续开发相关模块会共用 - * @date 2021/8/15 18:26 - */ -@ApiModel("请求响应模型") -public class RespModel { - @ApiModelProperty(value = "状态码", example = "2000") - private int code; - @ApiModelProperty(value = "状态描述", example = "操作成功!") - private String message; - @ApiModelProperty(value = "响应详情") - private T data; - - public RespModel() { - } - - public RespModel(int code, String message) { - this(code, message, null); - } - - public RespModel(int code, String message, T data) { - this.code = code; - this.message = message; - this.data = data; - } - - public RespModel(RespEnum respEnum) { - this.code = respEnum.getCode(); - this.message = respEnum.getMessage(); - } - - public RespModel(RespEnum respEnum, T data) { - this.code = respEnum.getCode(); - this.message = respEnum.getMessage(); - this.data = data; - } - - public int getCode() { - return code; - } - - public void setCode(int code) { - this.code = code; - } - - public String getMessage() { - return message; - } - - public RespModel setMessage(String msg) { - this.message = msg; - return this; - } - - public T getData() { - return data; - } - - public RespModel setData(T data) { - this.data = data; - return this; - } - - @Override - public String toString() { - return "RespModel{" + - "error=" + code + - ", errMsg='" + message + '\'' + - ", data=" + data + - '}'; - } -} +package org.cloud.sonic.common.http; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * @author ZhouYiXun + * @des 接口响应模型,后续开发相关模块会共用 + * @date 2021/8/15 18:26 + */ +@ApiModel("请求响应模型") +public class RespModel { + @ApiModelProperty(value = "状态码", example = "2000") + private int code; + @ApiModelProperty(value = "状态描述", example = "操作成功!") + private String message; + @ApiModelProperty(value = "响应详情") + private T data; + + public RespModel() { + } + + public RespModel(int code, String message) { + this(code, message, null); + } + + public RespModel(int code, String message, T data) { + this.code = code; + this.message = message; + this.data = data; + } + + public RespModel(RespEnum respEnum) { + this.code = respEnum.getCode(); + this.message = respEnum.getMessage(); + } + + public RespModel(RespEnum respEnum, T data) { + this.code = respEnum.getCode(); + this.message = respEnum.getMessage(); + this.data = data; + } + + public int getCode() { + return code; + } + + public void setCode(int code) { + this.code = code; + } + + public String getMessage() { + return message; + } + + public RespModel setMessage(String msg) { + this.message = msg; + return this; + } + + public T getData() { + return data; + } + + public RespModel setData(T data) { + this.data = data; + return this; + } + + @Override + public String toString() { + return "RespModel{" + + "error=" + code + + ", errMsg='" + message + '\'' + + ", data=" + data + + '}'; + } +} diff --git a/sonic-server-common/src/main/java/org/cloud/sonic/common/tools/BeanTool.java b/sonic-server-common/src/main/java/org/cloud/sonic/common/tools/BeanTool.java new file mode 100644 index 00000000..b53b6517 --- /dev/null +++ b/sonic-server-common/src/main/java/org/cloud/sonic/common/tools/BeanTool.java @@ -0,0 +1,141 @@ +package org.cloud.sonic.common.tools; + +import org.cloud.sonic.common.exception.BeanToolException; +import org.springframework.beans.BeanWrapperImpl; +import org.springframework.beans.BeansException; +import org.springframework.lang.NonNull; +import org.springframework.lang.Nullable; +import org.springframework.util.Assert; +import org.springframework.util.CollectionUtils; + +import java.beans.PropertyDescriptor; +import java.util.*; +import java.util.stream.Collectors; + +/** + * Bean utilities. + * + * @author JayWenStar + */ +public class BeanTool { + + private BeanTool() { + } + + /** + * Transforms from the source object. (copy same properties only) + * + * @param source source data + * @param targetClass target class must not be null + * @param target class type + * @return instance with specified type copying from source data; or null if source data is null + * @throws BeanToolException if newing target instance failed or copying failed + */ + @Nullable + public static T transformFrom(@Nullable Object source, @NonNull Class targetClass) { + Assert.notNull(targetClass, "Target class must not be null"); + + if (source == null) { + return null; + } + + // Init the instance + try { + // New instance for the target class + T targetInstance = targetClass.getDeclaredConstructor().newInstance(); + // Copy properties + org.springframework.beans.BeanUtils.copyProperties(source, targetInstance, getNullPropertyNames(source)); + // Return the target instance + return targetInstance; + } catch (Exception e) { + throw new BeanToolException("Failed to new " + targetClass.getName() + " instance or copy properties", e); + } + } + + /** + * Transforms from source data collection in batch. + * + * @param sources source data collection + * @param targetClass target class must not be null + * @param target class type + * @return target collection transforming from source data collection. + * @throws BeanToolException if newing target instance failed or copying failed + */ + @NonNull + public static List transformFromInBatch(Collection sources, @NonNull Class targetClass) { + if (CollectionUtils.isEmpty(sources)) { + return Collections.emptyList(); + } + + // Transform in batch + return sources.stream() + .map(source -> transformFrom(source, targetClass)) + .collect(Collectors.toList()); + } + + /** + * Update properties (non null). + * + * @param source source data must not be null + * @param target target data must not be null + * @throws BeanToolException if copying failed + */ + public static void updateProperties(@NonNull Object source, @NonNull Object target) { + Assert.notNull(source, "source object must not be null"); + Assert.notNull(target, "target object must not be null"); + + // Set non null properties from source properties to target properties + try { + org.springframework.beans.BeanUtils.copyProperties(source, target, getNullPropertyNames(source)); + } catch (BeansException e) { + throw new BeanToolException("Failed to copy properties", e); + } + } + + /** + * Gets null names array of property. + * + * @param source object data must not be null + * @return null name array of property + */ + @NonNull + private static String[] getNullPropertyNames(@NonNull Object source) { + return getNullPropertyNameSet(source).toArray(new String[0]); + } + + /** + * Gets null names set of property. + * + * @param source object data must not be null + * @return null name set of property + */ + @NonNull + private static Set getNullPropertyNameSet(@NonNull Object source) { + + Assert.notNull(source, "source object must not be null"); + BeanWrapperImpl beanWrapper = new BeanWrapperImpl(source); + PropertyDescriptor[] propertyDescriptors = beanWrapper.getPropertyDescriptors(); + + Set emptyNames = new HashSet<>(); + + for (PropertyDescriptor propertyDescriptor : propertyDescriptors) { + String propertyName = propertyDescriptor.getName(); + Object propertyValue = beanWrapper.getPropertyValue(propertyName); + + // if property value is equal to null, add it to empty name set + if (propertyValue == null) { + emptyNames.add(propertyName); + } + } + + return emptyNames; + } + + @NonNull + public static T toBean(Object source, Class clazz) { + Assert.notNull(source, "object must not be null"); + Assert.notNull(clazz, "clazz must not be null"); + + return BeanTool.toBean(source, clazz); + } +} diff --git a/sonic-server-common/src/main/java/com/sonic/common/tools/JWTTokenTool.java b/sonic-server-common/src/main/java/org/cloud/sonic/common/tools/JWTTokenTool.java similarity index 94% rename from sonic-server-common/src/main/java/com/sonic/common/tools/JWTTokenTool.java rename to sonic-server-common/src/main/java/org/cloud/sonic/common/tools/JWTTokenTool.java index ff8c2261..b339f839 100644 --- a/sonic-server-common/src/main/java/com/sonic/common/tools/JWTTokenTool.java +++ b/sonic-server-common/src/main/java/org/cloud/sonic/common/tools/JWTTokenTool.java @@ -1,73 +1,73 @@ -package com.sonic.common.tools; - -import com.auth0.jwt.JWT; -import com.auth0.jwt.JWTVerifier; -import com.auth0.jwt.algorithms.Algorithm; -import com.auth0.jwt.exceptions.JWTDecodeException; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.context.annotation.Configuration; - -import java.util.Calendar; -import java.util.Date; -import java.util.UUID; - -/** - * @author ZhouYiXun - * @des Token加解密工具类 - * @date 2021/8/15 18:26 - */ -@Configuration -public class JWTTokenTool { - @Value("${gateway.secret}") - private String TOKEN_SECRET; - @Value("${gateway.expireDay}") - private int EXPIRE_DAY; - - /** - * @param username - * @return java.lang.String - * @author ZhouYiXun - * @des 通过用户名生成token - * @date 2021/8/15 23:05 - */ - public String getToken(String username) { - Calendar now = Calendar.getInstance(); - now.add(Calendar.DATE, EXPIRE_DAY); - Date nowTime = now.getTime(); - return JWT.create().withAudience(username, UUID.randomUUID().toString()) - .withExpiresAt(nowTime) - .sign(Algorithm.HMAC256(TOKEN_SECRET)); - } - - /** - * @param token - * @return java.lang.String - * @author ZhouYiXun - * @des 由token获取生成时的用户信息 - * @date 2021/8/15 23:05 - */ - public String getUserName(String token) { - try { - return JWT.decode(token).getAudience().get(0); - } catch (JWTDecodeException e) { - return null; - } - } - - /** - * @param token - * @return boolean - * @author ZhouYiXun - * @des 校验token的签名是否合法 - * @date 2021/8/15 23:05 - */ - public boolean verify(String token) { - JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(TOKEN_SECRET)).build(); - try { - jwtVerifier.verify(token); - return true; - } catch (Exception e) { - return false; - } - } +package org.cloud.sonic.common.tools; + +import com.auth0.jwt.JWT; +import com.auth0.jwt.JWTVerifier; +import com.auth0.jwt.algorithms.Algorithm; +import com.auth0.jwt.exceptions.JWTDecodeException; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Configuration; + +import java.util.Calendar; +import java.util.Date; +import java.util.UUID; + +/** + * @author ZhouYiXun + * @des Token加解密工具类 + * @date 2021/8/15 18:26 + */ +@Configuration +public class JWTTokenTool { + @Value("${gateway.secret}") + private String TOKEN_SECRET; + @Value("${gateway.expireDay}") + private int EXPIRE_DAY; + + /** + * @param username + * @return java.lang.String + * @author ZhouYiXun + * @des 通过用户名生成token + * @date 2021/8/15 23:05 + */ + public String getToken(String username) { + Calendar now = Calendar.getInstance(); + now.add(Calendar.DATE, EXPIRE_DAY); + Date nowTime = now.getTime(); + return JWT.create().withAudience(username, UUID.randomUUID().toString()) + .withExpiresAt(nowTime) + .sign(Algorithm.HMAC256(TOKEN_SECRET)); + } + + /** + * @param token + * @return java.lang.String + * @author ZhouYiXun + * @des 由token获取生成时的用户信息 + * @date 2021/8/15 23:05 + */ + public String getUserName(String token) { + try { + return JWT.decode(token).getAudience().get(0); + } catch (JWTDecodeException e) { + return null; + } + } + + /** + * @param token + * @return boolean + * @author ZhouYiXun + * @des 校验token的签名是否合法 + * @date 2021/8/15 23:05 + */ + public boolean verify(String token) { + JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(TOKEN_SECRET)).build(); + try { + jwtVerifier.verify(token); + return true; + } catch (Exception e) { + return false; + } + } } \ No newline at end of file diff --git a/sonic-server-common/src/main/java/org/cloud/sonic/common/tools/ReflectionTool.java b/sonic-server-common/src/main/java/org/cloud/sonic/common/tools/ReflectionTool.java new file mode 100644 index 00000000..1e620e63 --- /dev/null +++ b/sonic-server-common/src/main/java/org/cloud/sonic/common/tools/ReflectionTool.java @@ -0,0 +1,92 @@ +package org.cloud.sonic.common.tools; + +import org.springframework.lang.NonNull; +import org.springframework.lang.Nullable; +import org.springframework.util.Assert; + +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; + +/** + * Reflection utilities. + * + * @author JayWenStar + */ +public class ReflectionTool { + + private ReflectionTool() { + } + + /** + * Gets parameterized type. + * + * @param superType super type must not be null (super class or super interface) + * @param genericTypes generic type array + * @return parameterized type of the interface or null if it is mismatch + */ + @Nullable + public static ParameterizedType getParameterizedType(@NonNull Class superType, Type... genericTypes) { + Assert.notNull(superType, "Interface or super type must not be null"); + + ParameterizedType currentType = null; + + for (Type genericType : genericTypes) { + if (genericType instanceof ParameterizedType) { + ParameterizedType parameterizedType = (ParameterizedType) genericType; + if (parameterizedType.getRawType().getTypeName().equals(superType.getTypeName())) { + currentType = parameterizedType; + break; + } + } + } + + return currentType; + } + + /** + * Gets parameterized type. + * + * @param interfaceType interface type must not be null + * @param implementationClass implementation class of the interface must not be null + * @return parameterized type of the interface or null if it is mismatch + */ + @Nullable + public static ParameterizedType getParameterizedType(@NonNull Class interfaceType, Class implementationClass) { + Assert.notNull(interfaceType, "Interface type must not be null"); + Assert.isTrue(interfaceType.isInterface(), "The give type must be an interface"); + + if (implementationClass == null) { + // If the super class is Object parent then return null + return null; + } + + // Get parameterized type + ParameterizedType currentType = getParameterizedType(interfaceType, implementationClass.getGenericInterfaces()); + + if (currentType != null) { + // return the current type + return currentType; + } + + Class superclass = implementationClass.getSuperclass(); + + return getParameterizedType(interfaceType, superclass); + } + + /** + * Gets parameterized type by super class. + * + * @param superClassType super class type must not be null + * @param extensionClass extension class + * @return parameterized type or null + */ + @Nullable + public static ParameterizedType getParameterizedTypeBySuperClass(@NonNull Class superClassType, Class extensionClass) { + + if (extensionClass == null) { + return null; + } + + return getParameterizedType(superClassType, extensionClass.getGenericSuperclass()); + } +} diff --git a/sonic-server-controller/pom.xml b/sonic-server-controller/pom.xml index 0abe67b9..5042fc24 100644 --- a/sonic-server-controller/pom.xml +++ b/sonic-server-controller/pom.xml @@ -4,13 +4,13 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> sonic-server - com.sonic + org.cloud.sonic 1.0.0 4.0.0 sonic-server-controller - v1.3.0-beta1 + v1.3.0-beta2 jar @@ -35,20 +35,54 @@ org.springframework.boot spring-boot-starter-undertow - - - org.springframework.boot - spring-boot-starter-data-jpa - mysql mysql-connector-java runtime + + + com.baomidou + mybatis-plus-boot-starter + 3.4.3.4 + + + + com.gitee.sunchenbin.mybatis.actable + mybatis-enhance-actable + 1.5.0.RELEASE + + + com.baomidou + mybatis-plus-annotation + + + org.springframework + spring-context + + + org.springframework + spring-tx + + + org.mybatis.scripting + mybatis-velocity + + + org.projectlombok + lombok + + + + + commons-lang + commons-lang + 2.6 + - com.sonic + org.cloud.sonic sonic-server-common 1.1.0 diff --git a/sonic-server-controller/src/main/java/com/sonic/controller/controller/AgentsController.java b/sonic-server-controller/src/main/java/com/sonic/controller/controller/AgentsController.java deleted file mode 100644 index 93e99566..00000000 --- a/sonic-server-controller/src/main/java/com/sonic/controller/controller/AgentsController.java +++ /dev/null @@ -1,85 +0,0 @@ -package com.sonic.controller.controller; - -import com.alibaba.fastjson.JSONObject; -import com.sonic.common.config.WebAspect; -import com.sonic.common.http.RespEnum; -import com.sonic.common.http.RespModel; -import com.sonic.controller.models.Agents; -import com.sonic.controller.services.AgentsService; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.web.bind.annotation.*; - -import java.util.List; - -/** - * @author ZhouYiXun - * @des - * @date 2021/8/28 21:49 - */ -@Api(tags = "Agent端相关") -@RestController -@RequestMapping("/agents") -public class AgentsController { - @Autowired - private AgentsService agentsService; - - @WebAspect - @ApiOperation(value = "查询所有Agent端", notes = "获取所有Agent端以及详细信息") - @GetMapping("/list") - public RespModel> findAgents() { - return new RespModel(RespEnum.SEARCH_OK, agentsService.findAgents()); - } - - @WebAspect - @PutMapping - public RespModel save(@RequestBody JSONObject jsonObject) { - agentsService.save(jsonObject); - return new RespModel(RespEnum.HANDLE_OK); - } - - @WebAspect - @PutMapping("/updateName") - public RespModel updateName(@RequestBody JSONObject jsonObject) { - agentsService.updateName(jsonObject.getInteger("id"), jsonObject.getString("name")); - return new RespModel(RespEnum.HANDLE_OK); - } - - @WebAspect - @GetMapping("/offLine") - public RespModel offLine(@RequestParam(name = "id") int id) { - agentsService.offLine(id); - return new RespModel(RespEnum.HANDLE_OK); - } - - @WebAspect - @GetMapping("/auth") - public RespModel auth(@RequestParam(name = "key") String key) { - return new RespModel(RespEnum.SEARCH_OK, agentsService.auth(key)); - } - - @WebAspect - @GetMapping("/findKeyById") - public RespModel findKeyById(@RequestParam(name = "id") int id) { - String key = agentsService.findKeyById(id); - if (key != null) { - return new RespModel(RespEnum.SEARCH_OK, key); - } else { - return new RespModel(RespEnum.ID_NOT_FOUND); - } - } - - @WebAspect - @ApiOperation(value = "查询Agent端信息", notes = "获取对应id的Agent信息") - @GetMapping - public RespModel findOne(@RequestParam(name = "id") int id) { - Agents agents = agentsService.findById(id); - if (agents != null) { - return new RespModel(RespEnum.SEARCH_OK, agents); - } else { - return new RespModel(RespEnum.ID_NOT_FOUND); - } - } - -} diff --git a/sonic-server-controller/src/main/java/com/sonic/controller/controller/ElementsController.java b/sonic-server-controller/src/main/java/com/sonic/controller/controller/ElementsController.java deleted file mode 100644 index d585d6a9..00000000 --- a/sonic-server-controller/src/main/java/com/sonic/controller/controller/ElementsController.java +++ /dev/null @@ -1,81 +0,0 @@ -package com.sonic.controller.controller; - -import com.sonic.common.config.WebAspect; -import com.sonic.common.http.RespEnum; -import com.sonic.common.http.RespModel; -import com.sonic.controller.models.Elements; -import com.sonic.controller.services.ElementsService; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiImplicitParam; -import io.swagger.annotations.ApiImplicitParams; -import io.swagger.annotations.ApiOperation; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.PageRequest; -import org.springframework.data.domain.Pageable; -import org.springframework.data.domain.Sort; -import org.springframework.validation.annotation.Validated; -import org.springframework.web.bind.annotation.*; - -import java.util.List; - -@Api(tags = "控件元素管理相关") -@RestController -@RequestMapping("/elements") -public class ElementsController { - @Autowired - private ElementsService elementsService; - - @WebAspect - @ApiOperation(value = "查找控件元素列表1", notes = "查找对应项目id的控件元素列表") - @ApiImplicitParams(value = { - @ApiImplicitParam(name = "projectId", value = "项目id", dataTypeClass = Integer.class), - @ApiImplicitParam(name = "eleTypes[]", value = "类型(多个)", dataTypeClass = String.class), - @ApiImplicitParam(name = "name", value = "控件名称", dataTypeClass = String.class), - @ApiImplicitParam(name = "type", value = "类型", dataTypeClass = String.class), - @ApiImplicitParam(name = "page", value = "页码", dataTypeClass = Integer.class), - @ApiImplicitParam(name = "pageSize", value = "页数据大小", dataTypeClass = Integer.class) - }) - @GetMapping("/list") - public RespModel> findAll(@RequestParam(name = "projectId") int projectId, - @RequestParam(name = "type", required = false) String type, - @RequestParam(name = "eleTypes[]", required = false) List eleTypes, - @RequestParam(name = "name", required = false) String name, - @RequestParam(name = "page") int page, - @RequestParam(name = "pageSize") int pageSize) { - Pageable pageable = PageRequest.of(page - 1, pageSize); - return new RespModel(RespEnum.SEARCH_OK, elementsService.findAll(projectId, type, eleTypes, name, pageable)); - } - - @WebAspect - @ApiOperation(value = "查找控件元素详情", notes = "查找对应id的对应控件元素详细信息") - @ApiImplicitParam(name = "id", value = "控件元素id", dataTypeClass = Integer.class) - @GetMapping - public RespModel findById(@RequestParam(name = "id") int id) { - Elements elements = elementsService.findById(id); - if (elements != null) { - return new RespModel(RespEnum.SEARCH_OK, elements); - } else { - return new RespModel(RespEnum.ID_NOT_FOUND); - } - } - - @WebAspect - @ApiOperation(value = "删除控件元素", notes = "删除对应id的控件元素,当控件元素存在于用例或id不存在时,删除失败") - @ApiImplicitParam(name = "id", value = "元素id", dataTypeClass = Integer.class) - @DeleteMapping - public RespModel delete(@RequestParam(name = "id") int id) { - return elementsService.delete(id); - } - - @WebAspect - @ApiOperation(value = "更新控件元素", notes = "新增或更新控件元素信息,id为0时新增,否则为更新对应id的信息") - @PutMapping - public RespModel save(@Validated @RequestBody Elements elements) { - if (elementsService.save(elements)) { - return new RespModel(RespEnum.UPDATE_OK); - } else { - return new RespModel(-1, "操作失败!请检查控件元素值是否过长!"); - } - } -} diff --git a/sonic-server-controller/src/main/java/com/sonic/controller/controller/StepsController.java b/sonic-server-controller/src/main/java/com/sonic/controller/controller/StepsController.java deleted file mode 100644 index 4a25ae09..00000000 --- a/sonic-server-controller/src/main/java/com/sonic/controller/controller/StepsController.java +++ /dev/null @@ -1,112 +0,0 @@ -package com.sonic.controller.controller; - -import com.sonic.common.config.WebAspect; -import com.sonic.common.http.RespEnum; -import com.sonic.common.http.RespModel; -import com.sonic.controller.models.Steps; -import com.sonic.controller.models.http.StepSort; -import com.sonic.controller.services.StepsService; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiImplicitParam; -import io.swagger.annotations.ApiImplicitParams; -import io.swagger.annotations.ApiOperation; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.PageRequest; -import org.springframework.data.domain.Pageable; -import org.springframework.data.domain.Sort; -import org.springframework.validation.annotation.Validated; -import org.springframework.web.bind.annotation.*; - -import java.util.List; - -/** - * @author ZhouYiXun - * @des - * @date 2021/9/19 11:45 - */ -@Api(tags = "操作步骤相关") -@RestController -@RequestMapping("/steps") -public class StepsController { - @Autowired - private StepsService stepsService; - - @WebAspect - @ApiOperation(value = "查找步骤列表", notes = "查找对应用例id下的步骤列表(分页)") - @ApiImplicitParams(value = { - @ApiImplicitParam(name = "projectId", value = "项目id", dataTypeClass = Integer.class), - @ApiImplicitParam(name = "platform", value = "平台", dataTypeClass = Integer.class), - @ApiImplicitParam(name = "page", value = "页码", dataTypeClass = Integer.class), - @ApiImplicitParam(name = "pageSize", value = "页数据大小", dataTypeClass = Integer.class) - }) - @GetMapping("/list") - public RespModel> findAll(@RequestParam(name = "projectId") int projectId, - @RequestParam(name = "platform") int platform, - @RequestParam(name = "page") int page, - @RequestParam(name = "pageSize") int pageSize) { - Pageable pageable = PageRequest.of(page - 1, pageSize, Sort.by(Sort.Direction.DESC, "id")); - return new RespModel(RespEnum.SEARCH_OK, stepsService.findByProjectIdAndPlatform(projectId, platform, pageable)); - } - - @WebAspect - @ApiOperation(value = "查找步骤列表", notes = "查找对应用例id下的步骤列表") - @ApiImplicitParam(name = "caseId", value = "测试用例id", dataTypeClass = Integer.class) - @GetMapping("/listAll") - public RespModel> findByCaseIdOrderBySort(@RequestParam(name = "caseId") int caseId) { - return new RespModel(RespEnum.SEARCH_OK, stepsService.findByCaseIdOrderBySort(caseId)); - } - - @WebAspect - @ApiOperation(value = "移出测试用例", notes = "将步骤从测试用例移出") - @ApiImplicitParam(name = "id", value = "步骤id", dataTypeClass = Integer.class) - @GetMapping("/resetCaseId") - public RespModel resetCaseId(@RequestParam(name = "id") int id) { - if (stepsService.resetCaseId(id)) { - return new RespModel(2000, "移出测试用例成功!"); - } else { - return new RespModel(RespEnum.ID_NOT_FOUND); - } - } - - @WebAspect - @ApiOperation(value = "删除操作步骤", notes = "将步骤删除,并且从所有公共步骤里移除") - @ApiImplicitParam(name = "id", value = "步骤id", dataTypeClass = Integer.class) - @DeleteMapping - public RespModel delete(@RequestParam(name = "id") int id) { - if (stepsService.delete(id)) { - return new RespModel(RespEnum.DELETE_OK); - } else { - return new RespModel(RespEnum.DELETE_ERROR); - } - } - - @WebAspect - @ApiOperation(value = "更新操作步骤", notes = "新增或更新操作步骤") - @PutMapping - public RespModel save(@Validated @RequestBody Steps steps) { - stepsService.save(steps); - return new RespModel(RespEnum.UPDATE_OK); - } - - @WebAspect - @ApiOperation(value = "拖拽排序步骤", notes = "用于前端页面拖拽排序步骤") - @PutMapping("/stepSort") - public RespModel stepSort(@Validated @RequestBody StepSort stepSort) { - stepsService.sortSteps(stepSort); - return new RespModel(RespEnum.UPDATE_OK); - } - - @WebAspect - @ApiOperation(value = "查询步骤详情", notes = "查询对应步骤id的详情信息") - @ApiImplicitParam(name = "id", value = "步骤id", dataTypeClass = Integer.class) - @GetMapping - public RespModel findById(@RequestParam(name = "id") int id) { - Steps steps = stepsService.findById(id); - if (steps != null) { - return new RespModel(RespEnum.SEARCH_OK, steps); - } else { - return new RespModel(RespEnum.ID_NOT_FOUND); - } - } -} diff --git a/sonic-server-controller/src/main/java/com/sonic/controller/dao/AgentsRepository.java b/sonic-server-controller/src/main/java/com/sonic/controller/dao/AgentsRepository.java deleted file mode 100644 index b63e085c..00000000 --- a/sonic-server-controller/src/main/java/com/sonic/controller/dao/AgentsRepository.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.sonic.controller.dao; - -import com.sonic.controller.models.Agents; -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.data.jpa.repository.Query; - -import java.util.List; - -/** - * @author ZhouYiXun - * @des Agent数据库操作 - * @date 2021/8/16 20:29 - */ -public interface AgentsRepository extends JpaRepository { - Agents findBySecretKey(String key); -} diff --git a/sonic-server-controller/src/main/java/com/sonic/controller/dao/DevicesRepository.java b/sonic-server-controller/src/main/java/com/sonic/controller/dao/DevicesRepository.java deleted file mode 100644 index 92e7d560..00000000 --- a/sonic-server-controller/src/main/java/com/sonic/controller/dao/DevicesRepository.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.sonic.controller.dao; - -import com.sonic.controller.models.Devices; -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.data.jpa.repository.JpaSpecificationExecutor; -import org.springframework.data.jpa.repository.Query; - -import java.util.List; - -/** - * @author ZhouYiXun - * @des Devices数据库操作 - * @date 2021/8/16 20:29 - */ -public interface DevicesRepository extends JpaRepository, JpaSpecificationExecutor { - Devices findByAgentIdAndUdId(int agentId, String udId); - - List findByAgentId(int agentId); - - List findByIdIn(List ids); - - List findByPlatformOrderByIdDesc(int platform); - - @Query(value = "select avg(temperature) as avg from devices " + - "where temperature <> 0 and status in (?1)", nativeQuery = true) - Integer findTemper(List ids); - - @Query(value = "select cpu from devices group by cpu", nativeQuery = true) - List findCpuList(); - - @Query(value = "select size from devices group by size", nativeQuery = true) - List findSizeList(); -} diff --git a/sonic-server-controller/src/main/java/com/sonic/controller/dao/ElementsRepository.java b/sonic-server-controller/src/main/java/com/sonic/controller/dao/ElementsRepository.java deleted file mode 100644 index c4efa4fe..00000000 --- a/sonic-server-controller/src/main/java/com/sonic/controller/dao/ElementsRepository.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.sonic.controller.dao; - -import com.sonic.controller.models.Elements; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.Pageable; -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.data.jpa.repository.JpaSpecificationExecutor; -import org.springframework.transaction.annotation.Transactional; - -import java.util.List; - -/** - * @author ZhouYiXun - * @des Elements数据库操作 - * @date 2021/8/16 20:29 - */ -public interface ElementsRepository extends JpaRepository, JpaSpecificationExecutor { - @Transactional - void deleteByProjectId(int projectId); -} diff --git a/sonic-server-controller/src/main/java/com/sonic/controller/dao/GlobalParamsRepository.java b/sonic-server-controller/src/main/java/com/sonic/controller/dao/GlobalParamsRepository.java deleted file mode 100644 index 9d7b5313..00000000 --- a/sonic-server-controller/src/main/java/com/sonic/controller/dao/GlobalParamsRepository.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.sonic.controller.dao; - -import com.sonic.controller.models.GlobalParams; -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.transaction.annotation.Transactional; - -import java.util.List; - -/** - * @author ZhouYiXun - * @des GlobalParams数据库操作 - * @date 2021/8/20 20:29 - */ -public interface GlobalParamsRepository extends JpaRepository { - List findByProjectId(int projectId); - - @Transactional - void deleteByProjectId(int projectId); -} diff --git a/sonic-server-controller/src/main/java/com/sonic/controller/dao/ModulesRepository.java b/sonic-server-controller/src/main/java/com/sonic/controller/dao/ModulesRepository.java deleted file mode 100644 index 30d50934..00000000 --- a/sonic-server-controller/src/main/java/com/sonic/controller/dao/ModulesRepository.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.sonic.controller.dao; - -import com.sonic.controller.models.Modules; -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.transaction.annotation.Transactional; - -import java.util.List; -/** - * @author ZhouYiXun - * @des Modules数据库操作 - * @date 2021/8/16 20:29 - */ -public interface ModulesRepository extends JpaRepository { - List findByProjectId(int projectId); - - @Transactional - void deleteByProjectId(int projectId); -} diff --git a/sonic-server-controller/src/main/java/com/sonic/controller/dao/ProjectsRepository.java b/sonic-server-controller/src/main/java/com/sonic/controller/dao/ProjectsRepository.java deleted file mode 100644 index ebbd039c..00000000 --- a/sonic-server-controller/src/main/java/com/sonic/controller/dao/ProjectsRepository.java +++ /dev/null @@ -1,7 +0,0 @@ -package com.sonic.controller.dao; - -import com.sonic.controller.models.Projects; -import org.springframework.data.jpa.repository.JpaRepository; - -public interface ProjectsRepository extends JpaRepository { -} diff --git a/sonic-server-controller/src/main/java/com/sonic/controller/dao/PublicStepsRepository.java b/sonic-server-controller/src/main/java/com/sonic/controller/dao/PublicStepsRepository.java deleted file mode 100644 index b9755982..00000000 --- a/sonic-server-controller/src/main/java/com/sonic/controller/dao/PublicStepsRepository.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.sonic.controller.dao; - -import com.sonic.controller.models.PublicSteps; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.Pageable; -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.data.jpa.repository.Query; -import org.springframework.transaction.annotation.Transactional; - -import java.util.List; -import java.util.Map; - -/** - * @author ZhouYiXun - * @des PublicSteps数据库操作 - * @date 2021/8/16 20:29 - */ -public interface PublicStepsRepository extends JpaRepository { - Page findByProjectId(int projectId, Pageable pageable); - - @Query(value = "select id,name from public_steps where project_id=?1 and platform=?2 order by id desc", nativeQuery = true) - List> findByProjectIdAndPlatform(int projectId, int platform); - - @Transactional - void deleteByProjectId(int projectId); -} diff --git a/sonic-server-controller/src/main/java/com/sonic/controller/dao/ResultDetailRepository.java b/sonic-server-controller/src/main/java/com/sonic/controller/dao/ResultDetailRepository.java deleted file mode 100644 index e9bf17b2..00000000 --- a/sonic-server-controller/src/main/java/com/sonic/controller/dao/ResultDetailRepository.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.sonic.controller.dao; - -import com.alibaba.fastjson.JSONObject; -import com.sonic.controller.models.ResultDetail; -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.data.jpa.repository.JpaSpecificationExecutor; -import org.springframework.data.jpa.repository.Query; -import org.springframework.transaction.annotation.Transactional; - -import java.util.List; - -public interface ResultDetailRepository extends JpaRepository, JpaSpecificationExecutor { - @Query(value = "select case_id, max(time) as endTime,min(time) as startTime from result_detail where result_id=?1 and type = 'step' group by case_id", nativeQuery = true) - List findTimeByResultIdGroupByCaseId(int resultId); - - @Query(value = "select t2.device_id, t2.case_id, IFNULL(t1.status,4) as status " + - "from (select case_id, device_id, status from result_detail where result_id=?1 and type = 'status')t1" + - " right join" + - "(select case_id, device_id from result_detail where result_id=?1 and type = 'step' group by case_id, device_id)t2" + - " on t1.device_id = t2.device_id and t1.case_id = t2.case_id", nativeQuery = true) - List findStatusByResultIdGroupByCaseId(int resultId); - - @Query(value = "select t.case_id,sum(t.diff) as total from (select case_id,result_id,TIMESTAMPDIFF(SECOND,min(time),max(time)) as diff " + - "from result_detail where result_id in " + - "(select id from results where end_time>?1 and end_time<=?2 and project_id=?3) " + - "and type='step' group by result_id,case_id)t group by t.case_id order by total desc limit 5", nativeQuery = true) - List findTopCases(String startTime, String endTime, int projectId); - - @Query(value = "select t.device_id,sum(t.diff) as total from (select device_id,case_id,result_id,TIMESTAMPDIFF(SECOND,min(time),max(time)) as diff " + - "from result_detail where result_id in " + - "(select id from results where end_time>?1 and end_time<=?2 and project_id=?3) " + - "and type='step' group by result_id,case_id,device_id)t group by t.device_id order by total desc limit 5", nativeQuery = true) - List findTopDevices(String startTime, String endTime, int projectId); - - @Transactional - void deleteByResultId(int resultId); -} diff --git a/sonic-server-controller/src/main/java/com/sonic/controller/dao/ResultsRepository.java b/sonic-server-controller/src/main/java/com/sonic/controller/dao/ResultsRepository.java deleted file mode 100644 index 668e0ecb..00000000 --- a/sonic-server-controller/src/main/java/com/sonic/controller/dao/ResultsRepository.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.sonic.controller.dao; - -import com.alibaba.fastjson.JSONObject; -import com.sonic.controller.models.Results; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.Pageable; -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.data.jpa.repository.Query; -import org.springframework.transaction.annotation.Transactional; - -import java.util.Date; -import java.util.List; - -public interface ResultsRepository extends JpaRepository { - Page findByProjectId(int projectId, Pageable pageable); - - List findByProjectId(int projectId); - - @Query(value = "select t2.date,round(IFNULL((t1.count/t2.count),0)*100,2) as rate from " + - "(select DATE_FORMAT(end_time,'%Y-%m-%d') as date,count(status) as count from results where end_time>?1 and end_time<=?2 and project_id=?3 and status=1 " + - "group by status,DATE_FORMAT(end_time,'%Y-%m-%d'))t1 " + - "right join" + - "(select DATE_FORMAT(end_time,'%Y-%m-%d') as date,count(status) as count from results where end_time>?1 and end_time<=?2 and project_id=?3 " + - "group by DATE_FORMAT(end_time,'%Y-%m-%d'))t2 " + - "on t1.date = t2.date", nativeQuery = true) - List findDayPassRate(String startTime, String endTime, int projectId); - - @Query(value = "select status,count(*) as total from results where end_time>?1 and end_time<=?2 and project_id=?3 group by status", nativeQuery = true) - List findDayStatus(String startTime, String endTime, int projectId); - - @Query(value = "select count(*) as total from results where end_time>?1 and end_time<=?2 and project_id=?3", nativeQuery = true) - int findRunCount(String startTime, String endTime, int projectId); - - @Transactional - void deleteByProjectId(int projectId); - - List findByCreateTimeBefore(Date time); -} diff --git a/sonic-server-controller/src/main/java/com/sonic/controller/dao/StepsRepository.java b/sonic-server-controller/src/main/java/com/sonic/controller/dao/StepsRepository.java deleted file mode 100644 index 53db8617..00000000 --- a/sonic-server-controller/src/main/java/com/sonic/controller/dao/StepsRepository.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.sonic.controller.dao; - -import com.sonic.controller.models.Steps; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.Pageable; -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.data.jpa.repository.Query; -import org.springframework.data.repository.query.Param; -import org.springframework.transaction.annotation.Transactional; - -import java.util.List; - -/** - * @author ZhouYiXun - * @des Steps数据库操作 - * @date 2021/8/16 20:29 - */ -public interface StepsRepository extends JpaRepository { - List findByCaseIdOrderBySort(int caseId); - - @Query(value = "select IFNULL(max(sort),0) from steps", nativeQuery = true) - int findMaxSort(); - - List findByCaseIdAndSortLessThanEqualAndSortGreaterThanEqualOrderBySort(int caseId, int startSort, int endSort); - - @Transactional - void deleteByCaseId(int caseId); - - @Transactional - void deleteByProjectId(@Param("projectId") int projectId); - - Page findByProjectIdAndPlatform(int projectId, int platform, Pageable pageable); -} diff --git a/sonic-server-controller/src/main/java/com/sonic/controller/dao/TestCasesRepository.java b/sonic-server-controller/src/main/java/com/sonic/controller/dao/TestCasesRepository.java deleted file mode 100644 index a4c1ab79..00000000 --- a/sonic-server-controller/src/main/java/com/sonic/controller/dao/TestCasesRepository.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.sonic.controller.dao; - -import com.sonic.controller.models.TestCases; -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.data.jpa.repository.JpaSpecificationExecutor; -import org.springframework.transaction.annotation.Transactional; - -import java.util.List; - -/** - * @author ZhouYiXun - * @des TestCases数据库操作 - * @date 2021/8/20 15:29 - */ -public interface TestCasesRepository extends JpaRepository, JpaSpecificationExecutor { - List findByProjectIdAndPlatformOrderByEditTimeDesc(int projectId, int platform); - - List findByIdIn(List ids); - - @Transactional - void deleteByProjectId(int projectId); -} diff --git a/sonic-server-controller/src/main/java/com/sonic/controller/dao/TestSuitesRepository.java b/sonic-server-controller/src/main/java/com/sonic/controller/dao/TestSuitesRepository.java deleted file mode 100644 index f5b3cd6f..00000000 --- a/sonic-server-controller/src/main/java/com/sonic/controller/dao/TestSuitesRepository.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.sonic.controller.dao; - -import com.sonic.controller.models.TestSuites; -import org.springframework.data.domain.Sort; -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.data.jpa.repository.JpaSpecificationExecutor; -import org.springframework.data.repository.query.Param; -import org.springframework.transaction.annotation.Transactional; - -import java.util.List; - -/** - * @author ZhouYiXun - * @des TestSuites数据库操作 - * @date 2021/8/20 15:29 - */ -public interface TestSuitesRepository extends JpaRepository, JpaSpecificationExecutor { - List findByProjectId(int projectId, Sort sort); - - @Transactional - void deleteByProjectId(@Param("projectId") int projectId); -} diff --git a/sonic-server-controller/src/main/java/com/sonic/controller/dao/UsersRepository.java b/sonic-server-controller/src/main/java/com/sonic/controller/dao/UsersRepository.java deleted file mode 100644 index 9a0ecdec..00000000 --- a/sonic-server-controller/src/main/java/com/sonic/controller/dao/UsersRepository.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.sonic.controller.dao; - -import com.sonic.controller.models.Users; -import org.springframework.data.jpa.repository.JpaRepository; - -public interface UsersRepository extends JpaRepository { - Users findByUserName(String username); -} diff --git a/sonic-server-controller/src/main/java/com/sonic/controller/dao/VersionsRepository.java b/sonic-server-controller/src/main/java/com/sonic/controller/dao/VersionsRepository.java deleted file mode 100644 index 9b5d61ef..00000000 --- a/sonic-server-controller/src/main/java/com/sonic/controller/dao/VersionsRepository.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.sonic.controller.dao; - -import com.sonic.controller.models.Versions; -import org.springframework.data.domain.Sort; -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.transaction.annotation.Transactional; - -import java.util.List; - -/** - * @author ZhouYiXun - * @des Versions数据库操作 - * @date 2021/8/20 20:29 - */ -public interface VersionsRepository extends JpaRepository { - List findByProjectId(int projectId, Sort s); - - @Transactional - void deleteByProjectId(int projectId); -} diff --git a/sonic-server-controller/src/main/java/com/sonic/controller/models/Agents.java b/sonic-server-controller/src/main/java/com/sonic/controller/models/Agents.java deleted file mode 100644 index 13ec9cce..00000000 --- a/sonic-server-controller/src/main/java/com/sonic/controller/models/Agents.java +++ /dev/null @@ -1,120 +0,0 @@ -package com.sonic.controller.models; - -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; - -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.validation.constraints.NotNull; -import javax.validation.constraints.Positive; - -@Entity -@ApiModel("Agent端模型") -public class Agents { - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - @ApiModelProperty(value = "id", example = "1") - int id; - @NotNull - @ApiModelProperty(value = "Agent端名称", example = "本地Agent") - String name; - @NotNull - @ApiModelProperty(value = "Agent端系统类型", example = "Windows 10") - String systemType; - @NotNull - @ApiModelProperty(value = "Agent端版本号", example = "1.0.0") - String version; - @NotNull - @ApiModelProperty(value = "Agent端所在host", example = "127.0.0.1") - String host; - @NotNull - @ApiModelProperty(value = "Agent端暴露web端口", example = "1234") - int port; - @ApiModelProperty(value = "Agent端状态", example = "1") - int status; - @ApiModelProperty(value = "Agent端密钥", example = "qwe") - String secretKey; - - public Agents() { - } - - public int getId() { - return id; - } - - public void setId(int id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getSystemType() { - return systemType; - } - - public void setSystemType(String systemType) { - this.systemType = systemType; - } - - public String getVersion() { - return version; - } - - public void setVersion(String version) { - this.version = version; - } - - public String getHost() { - return host; - } - - public void setHost(String host) { - this.host = host; - } - - public int getPort() { - return port; - } - - public void setPort(int port) { - this.port = port; - } - - public int getStatus() { - return status; - } - - public void setStatus(int status) { - this.status = status; - } - - public String getSecretKey() { - return secretKey; - } - - public void setSecretKey(String secretKey) { - this.secretKey = secretKey; - } - - @Override - public String toString() { - return "Agents{" + - "id=" + id + - ", name='" + name + '\'' + - ", systemType='" + systemType + '\'' + - ", version='" + version + '\'' + - ", host='" + host + '\'' + - ", port=" + port + - ", status=" + status + - ", secretKey='" + secretKey + '\'' + - '}'; - } -} diff --git a/sonic-server-controller/src/main/java/com/sonic/controller/models/Devices.java b/sonic-server-controller/src/main/java/com/sonic/controller/models/Devices.java deleted file mode 100644 index 7551b642..00000000 --- a/sonic-server-controller/src/main/java/com/sonic/controller/models/Devices.java +++ /dev/null @@ -1,227 +0,0 @@ -package com.sonic.controller.models; - -import com.alibaba.fastjson.annotation.JSONField; -import com.fasterxml.jackson.annotation.JsonIgnore; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; - -import javax.persistence.*; -import java.util.Set; - -@Entity -@ApiModel("设备模型") -//添加udId字段索引 -@Table(indexes = {@Index(columnList = "udId")}) -public class Devices { - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - @ApiModelProperty(value = "id", example = "1") - int id; - @ApiModelProperty(value = "设备名称", example = "My HUAWEI") - String name; - @ApiModelProperty(value = "中文设备", example = "荣耀全网通") - String chiName; - @ApiModelProperty(value = "设备备注", example = "My HUAWEI") - String nickName; - @ApiModelProperty(value = "型号", example = "HUAWEI MATE 40") - String model; - @ApiModelProperty(value = "序列号", example = "random") - String udId; - @ApiModelProperty(value = "设备状态", example = "ONLINE") - String status; - @ApiModelProperty(value = "所属Agent", example = "1") - int agentId; - @ApiModelProperty(value = "设备系统", example = "1") - int platform; - @ApiModelProperty(value = "分辨率", example = "1080x1920") - String size; - @ApiModelProperty(value = "系统版本", example = "12") - String version; - @ApiModelProperty(value = "cpu", example = "arm64") - String cpu; - @ApiModelProperty(value = "制造商", example = "HUAWEI") - String manufacturer; - @ApiModelProperty(value = "安装密码", example = "123456") - String password; - @ApiModelProperty(value = "设备图片路径") - String imgUrl; - @ManyToMany(mappedBy = "devices") - @JsonIgnore - @JSONField(serialize = false) - Set testSuites; - @ApiModelProperty(value = "设备占用者") - String user; - @Column(columnDefinition="int default 0") - @ApiModelProperty(value = "设备温度", example = "33") - Integer temperature; - - public Devices() { - } - - public int getId() { - return id; - } - - public void setId(int id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getChiName() { - return chiName; - } - - public void setChiName(String chiName) { - this.chiName = chiName; - } - - public String getNickName() { - return nickName; - } - - public void setNickName(String nickName) { - this.nickName = nickName; - } - - public String getModel() { - return model; - } - - public void setModel(String model) { - this.model = model; - } - - public String getUdId() { - return udId; - } - - public void setUdId(String udId) { - this.udId = udId; - } - - public String getStatus() { - return status; - } - - public void setStatus(String status) { - this.status = status; - } - - public int getAgentId() { - return agentId; - } - - public void setAgentId(int agentId) { - this.agentId = agentId; - } - - public int getPlatform() { - return platform; - } - - public void setPlatform(int platform) { - this.platform = platform; - } - - public String getSize() { - return size; - } - - public void setSize(String size) { - this.size = size; - } - - public String getVersion() { - return version; - } - - public void setVersion(String version) { - this.version = version; - } - - public String getCpu() { - return cpu; - } - - public void setCpu(String cpu) { - this.cpu = cpu; - } - - public String getManufacturer() { - return manufacturer; - } - - public void setManufacturer(String manufacturer) { - this.manufacturer = manufacturer; - } - - public String getPassword() { - return password; - } - - public void setPassword(String password) { - this.password = password; - } - - public String getImgUrl() { - return imgUrl; - } - - public void setImgUrl(String imgUrl) { - this.imgUrl = imgUrl; - } - - public Set getTestSuites() { - return testSuites; - } - - public void setTestSuites(Set testSuites) { - this.testSuites = testSuites; - } - - public String getUser() { - return user; - } - - public void setUser(String user) { - this.user = user; - } - - public float getTemperature() { - return temperature; - } - - public void setTemperature(Integer temperature) { - this.temperature = temperature; - } - - @Override - public String toString() { - return "Devices{" + - "id=" + id + - ", name='" + name + '\'' + - ", chiName='" + chiName + '\'' + - ", nickName='" + nickName + '\'' + - ", model='" + model + '\'' + - ", udId='" + udId + '\'' + - ", status='" + status + '\'' + - ", agentId=" + agentId + - ", platform=" + platform + - ", size='" + size + '\'' + - ", version='" + version + '\'' + - ", cpu='" + cpu + '\'' + - ", manufacturer='" + manufacturer + '\'' + - ", password='" + password + '\'' + - ", imgUrl='" + imgUrl + '\'' + - ", user='" + user + '\'' + - ", temperature='" + temperature + '\'' + - '}'; - } -} diff --git a/sonic-server-controller/src/main/java/com/sonic/controller/models/Elements.java b/sonic-server-controller/src/main/java/com/sonic/controller/models/Elements.java deleted file mode 100644 index 9d2b7653..00000000 --- a/sonic-server-controller/src/main/java/com/sonic/controller/models/Elements.java +++ /dev/null @@ -1,108 +0,0 @@ -package com.sonic.controller.models; - -import com.alibaba.fastjson.annotation.JSONField; -import com.fasterxml.jackson.annotation.JsonIgnore; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; - -import javax.persistence.*; -import javax.validation.constraints.NotNull; -import javax.validation.constraints.Positive; -import java.util.List; - -@Entity -@ApiModel("页面控件模型") -@Table(indexes = {@Index(columnList = "projectId")}) -public class Elements { - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - @ApiModelProperty(value = "id", example = "1") - int id; - @NotNull - @ApiModelProperty(value = "控件名称", required = true, example = "首页底部按钮") - String eleName; - @NotNull - @ApiModelProperty(value = "控件类型", required = true, example = "xpath") - String eleType; - @Lob - @Basic(fetch = FetchType.LAZY) - @NotNull - @ApiModelProperty(value = "控件值", required = true, example = "//@[text()='home']") - String eleValue; - @Positive - @ApiModelProperty(value = "项目id", required = true, example = "1") - int projectId; - //因为一个控件可以存在于多个步骤,也可以一个步骤有多个同样的控件,所以是多对多关系 - @ManyToMany(mappedBy = "elements", fetch = FetchType.EAGER) - @JsonIgnore - @JSONField(serialize = false) - List steps; - - public Elements() { - } - - public int getId() { - return id; - } - - public void setId(int id) { - this.id = id; - } - - public String getEleName() { - return eleName; - } - - public void setEleName(String eleName) { - this.eleName = eleName; - } - - public String getEleType() { - return eleType; - } - - public void setEleType(String eleType) { - this.eleType = eleType; - } - - public String getEleValue() { - return eleValue; - } - - public void setEleValue(String eleValue) { - this.eleValue = eleValue; - } - - public int getProjectId() { - return projectId; - } - - public void setProjectId(int projectId) { - this.projectId = projectId; - } - - public List getSteps() { - return steps; - } - - public void setSteps(List steps) { - this.steps = steps; - } - - /** - * @return java.lang.String - * @author ZhouYiXun - * @des 注意,打印不能打印步骤模型,会造成堆溢出 - * @date 2021/8/15 19:50 - */ - @Override - public String toString() { - return "Elements{" + - "id=" + id + - ", eleName='" + eleName + '\'' + - ", eleType='" + eleType + '\'' + - ", eleValue='" + eleValue + '\'' + - ", projectId=" + projectId + - '}'; - } -} diff --git a/sonic-server-controller/src/main/java/com/sonic/controller/models/GlobalParams.java b/sonic-server-controller/src/main/java/com/sonic/controller/models/GlobalParams.java deleted file mode 100644 index c524d6ac..00000000 --- a/sonic-server-controller/src/main/java/com/sonic/controller/models/GlobalParams.java +++ /dev/null @@ -1,72 +0,0 @@ -package com.sonic.controller.models; - -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; - -import javax.persistence.*; -import javax.validation.constraints.NotNull; -import javax.validation.constraints.Positive; - -@Entity -@ApiModel("全局参数模型") -@Table(indexes = {@Index(columnList = "projectId")}) -public class GlobalParams { - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - @ApiModelProperty(value = "id", example = "1") - int id; - @Positive - @ApiModelProperty(value = "项目id", required = true, example = "1") - int projectId; - @NotNull - @ApiModelProperty(value = "参数名", required = true, example = "account") - String paramsKey; - @NotNull - @ApiModelProperty(value = "参数值", required = true, example = "123456789") - String paramsValue; - - public GlobalParams() { - } - - public int getId() { - return id; - } - - public void setId(int id) { - this.id = id; - } - - public int getProjectId() { - return projectId; - } - - public void setProjectId(int projectId) { - this.projectId = projectId; - } - - public String getParamsKey() { - return paramsKey; - } - - public void setParamsKey(String paramsKey) { - this.paramsKey = paramsKey; - } - - public String getParamsValue() { - return paramsValue; - } - - public void setParamsValue(String paramsValue) { - this.paramsValue = paramsValue; - } - - @Override - public String toString() { - return "GlobalParams{" + - "id=" + id + - ", projectId=" + projectId + - ", paramsKey='" + paramsKey + '\'' + - ", paramsValue='" + paramsValue + '\'' + - '}'; - } -} diff --git a/sonic-server-controller/src/main/java/com/sonic/controller/models/Modules.java b/sonic-server-controller/src/main/java/com/sonic/controller/models/Modules.java deleted file mode 100644 index 8919a223..00000000 --- a/sonic-server-controller/src/main/java/com/sonic/controller/models/Modules.java +++ /dev/null @@ -1,60 +0,0 @@ -package com.sonic.controller.models; - -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; - -import javax.persistence.*; -import javax.validation.constraints.NotNull; -import javax.validation.constraints.Positive; - -@Entity -@ApiModel("模块模型") -@Table(indexes = {@Index(columnList = "projectId")}) -public class Modules { - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - @ApiModelProperty(value = "id", example = "1") - int id; - @Positive - @ApiModelProperty(value = "项目id", required = true, example = "1") - int projectId; - @NotNull - @ApiModelProperty(value = "模块名称", required = true, example = "首页") - String name; - - public Modules() { - } - - public int getId() { - return id; - } - - public void setId(int id) { - this.id = id; - } - - public int getProjectId() { - return projectId; - } - - public void setProjectId(int projectId) { - this.projectId = projectId; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - @Override - public String toString() { - return "Modules{" + - "id=" + id + - ", projectId=" + projectId + - ", name='" + name + '\'' + - '}'; - } -} diff --git a/sonic-server-controller/src/main/java/com/sonic/controller/models/Projects.java b/sonic-server-controller/src/main/java/com/sonic/controller/models/Projects.java deleted file mode 100644 index 4e009ce5..00000000 --- a/sonic-server-controller/src/main/java/com/sonic/controller/models/Projects.java +++ /dev/null @@ -1,123 +0,0 @@ -package com.sonic.controller.models; - -import com.fasterxml.jackson.annotation.JsonFormat; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.springframework.data.annotation.LastModifiedDate; -import org.springframework.data.jpa.domain.support.AuditingEntityListener; - -import javax.persistence.*; -import javax.validation.constraints.NotNull; -import java.util.Date; - -@Entity -@ApiModel("项目模型") -@EntityListeners(AuditingEntityListener.class) -public class Projects { - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - @ApiModelProperty(value = "id", example = "1") - int id; - @NotNull - @ApiModelProperty(value = "项目名称", required = true, example = "test") - String projectName; - @NotNull - @ApiModelProperty(value = "项目描述", required = true, example = "Sonic项目描述") - String projectDes; - @ApiModelProperty(value = "机器人类型", required = true, example = "1") - int robotType; - @NotNull - @ApiModelProperty(value = "机器人token", required = true, example = "http://dingTalk.com?token=*****") - String robotToken; - @NotNull - @ApiModelProperty(value = "机器人加签密钥", required = true, example = "qwe***") - String robotSecret; - @NotNull - @ApiModelProperty(value = "项目图标", required = true, example = "http://img.jpg") - String projectImg; - @ApiModelProperty(value = "最后修改日期", example = "2021-08-15 11:23:00") - @LastModifiedDate - @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") - Date editTime; - - public Projects() { - } - - public int getId() { - return id; - } - - public void setId(int id) { - this.id = id; - } - - public String getProjectName() { - return projectName; - } - - public void setProjectName(String projectName) { - this.projectName = projectName; - } - - public String getProjectDes() { - return projectDes; - } - - public void setProjectDes(String projectDes) { - this.projectDes = projectDes; - } - - public int getRobotType() { - return robotType; - } - - public void setRobotType(int robotType) { - this.robotType = robotType; - } - - public String getRobotToken() { - return robotToken; - } - - public void setRobotToken(String robotToken) { - this.robotToken = robotToken; - } - - public String getRobotSecret() { - return robotSecret; - } - - public void setRobotSecret(String robotSecret) { - this.robotSecret = robotSecret; - } - - public String getProjectImg() { - return projectImg; - } - - public void setProjectImg(String projectImg) { - this.projectImg = projectImg; - } - - public Date getEditTime() { - return editTime; - } - - public void setEditTime(Date editTime) { - this.editTime = editTime; - } - - @Override - public String toString() { - return "Projects{" + - "id=" + id + - ", projectName='" + projectName + '\'' + - ", projectDes='" + projectDes + '\'' + - ", robotType=" + robotType + - ", robotToken='" + robotToken + '\'' + - ", robotSecret='" + robotSecret + '\'' + - ", projectImg='" + projectImg + '\'' + - ", editTime=" + editTime + - '}'; - } -} diff --git a/sonic-server-controller/src/main/java/com/sonic/controller/models/PublicSteps.java b/sonic-server-controller/src/main/java/com/sonic/controller/models/PublicSteps.java deleted file mode 100644 index df1b4a02..00000000 --- a/sonic-server-controller/src/main/java/com/sonic/controller/models/PublicSteps.java +++ /dev/null @@ -1,85 +0,0 @@ -package com.sonic.controller.models; - -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; - -import javax.persistence.*; -import javax.validation.constraints.NotNull; -import javax.validation.constraints.Positive; -import java.util.List; - -@Entity -@ApiModel("公共步骤模型") -@Table(indexes = {@Index(columnList = "projectId")}) -public class PublicSteps { - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - @ApiModelProperty(value = "id", example = "1") - int id; - @Positive - @ApiModelProperty(value = "项目id", required = true, example = "1") - int projectId; - @Positive - @ApiModelProperty(value = "平台", required = true, example = "1") - int platform; - @NotNull - @ApiModelProperty(value = "公共步骤名称", required = true, example = "登陆步骤") - String name; - @ApiModelProperty(value = "包含操作步骤列表") - @ManyToMany(fetch = FetchType.EAGER) - List steps; - - public PublicSteps() { - } - - public int getId() { - return id; - } - - public void setId(int id) { - this.id = id; - } - - public int getProjectId() { - return projectId; - } - - public void setProjectId(int projectId) { - this.projectId = projectId; - } - - public int getPlatform() { - return platform; - } - - public void setPlatform(int platform) { - this.platform = platform; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public List getSteps() { - return steps; - } - - public void setSteps(List steps) { - this.steps = steps; - } - - @Override - public String toString() { - return "PublicSteps{" + - "id=" + id + - ", projectId=" + projectId + - ", platform=" + platform + - ", name='" + name + '\'' + - ", steps=" + steps + - '}'; - } -} diff --git a/sonic-server-controller/src/main/java/com/sonic/controller/models/ResultDetail.java b/sonic-server-controller/src/main/java/com/sonic/controller/models/ResultDetail.java deleted file mode 100644 index b445cac5..00000000 --- a/sonic-server-controller/src/main/java/com/sonic/controller/models/ResultDetail.java +++ /dev/null @@ -1,136 +0,0 @@ -package com.sonic.controller.models; - -import com.fasterxml.jackson.annotation.JsonFormat; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; - -import javax.persistence.*; -import java.util.Date; - -@Entity -@ApiModel("测试结果详情模型") -@Table(indexes = { - @Index(name = "IDX_RESULT_ID", columnList = "resultId"), - @Index(name = "IDX_TIME", columnList = "time"), - @Index(name = "IDX_TYPE", columnList = "type"), - @Index(name = "IDX_RESULT_ID_CASE_ID_TYPE_DEVICE_ID", columnList = "resultId"), - @Index(name = "IDX_RESULT_ID_CASE_ID_TYPE_DEVICE_ID", columnList = "caseId"), - @Index(name = "IDX_RESULT_ID_CASE_ID_TYPE_DEVICE_ID", columnList = "type"), - @Index(name = "IDX_RESULT_ID_CASE_ID_TYPE_DEVICE_ID", columnList = "deviceId"), -}) -public class ResultDetail { - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - @ApiModelProperty(value = "id", example = "1") - int id; - @ApiModelProperty(value = "测试用例id", example = "1") - int caseId; - @ApiModelProperty(value = "测试结果id", example = "1") - int resultId; - @ApiModelProperty(value = "测试结果详情类型", example = "step") - String type; - @ApiModelProperty(value = "测试结果详情描述", example = "点击xxx") - String des; - @ApiModelProperty(value = "测试结果详情状态", example = "1") - int status; - @ApiModelProperty(value = "设备id", example = "1") - int deviceId; - @ApiModelProperty(value = "测试结果详情详细日志", example = "点击xpath://*[@text()='xxx']") - @Lob - @Basic(fetch = FetchType.LAZY) - String log; - @ApiModelProperty(value = "时间", example = "16:00:00") - @Temporal(TemporalType.TIMESTAMP) - @JsonFormat(pattern = "HH:mm:ss", timezone = "GMT+8") - Date time; - - public ResultDetail() { - } - - public int getId() { - return id; - } - - public void setId(int id) { - this.id = id; - } - - public int getCaseId() { - return caseId; - } - - public void setCaseId(int caseId) { - this.caseId = caseId; - } - - public int getResultId() { - return resultId; - } - - public void setResultId(int resultId) { - this.resultId = resultId; - } - - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type; - } - - public String getDes() { - return des; - } - - public void setDes(String des) { - this.des = des; - } - - public int getStatus() { - return status; - } - - public void setStatus(int status) { - this.status = status; - } - - public int getDeviceId() { - return deviceId; - } - - public void setDeviceId(int deviceId) { - this.deviceId = deviceId; - } - - public String getLog() { - return log; - } - - public void setLog(String log) { - this.log = log; - } - - public Date getTime() { - return time; - } - - public void setTime(Date time) { - this.time = time; - } - - @Override - public String toString() { - return "ResultDetail{" + - "id=" + id + - ", caseId=" + caseId + - ", resultId=" + resultId + - ", type='" + type + '\'' + - ", des='" + des + '\'' + - ", status=" + status + - ", deviceId=" + deviceId + - ", log='" + log + '\'' + - ", time=" + time + - '}'; - } -} diff --git a/sonic-server-controller/src/main/java/com/sonic/controller/models/Results.java b/sonic-server-controller/src/main/java/com/sonic/controller/models/Results.java deleted file mode 100644 index 090091f3..00000000 --- a/sonic-server-controller/src/main/java/com/sonic/controller/models/Results.java +++ /dev/null @@ -1,141 +0,0 @@ -package com.sonic.controller.models; - -import com.fasterxml.jackson.annotation.JsonFormat; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.springframework.data.annotation.CreatedDate; -import org.springframework.data.jpa.domain.support.AuditingEntityListener; - -import javax.persistence.*; -import java.util.Date; - -@Entity -@ApiModel("测试结果模型") -@Table(indexes = {@Index(columnList = "projectId")}) -@EntityListeners(AuditingEntityListener.class) -public class Results { - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - @ApiModelProperty(value = "id", example = "1") - int id; - @ApiModelProperty(value = "测试套件id", example = "1") - int suiteId; - @ApiModelProperty(value = "测试套件名称", example = "测试套件A") - String suiteName; - @ApiModelProperty(value = "项目id", example = "1") - int projectId; - @ApiModelProperty(value = "触发者", example = "ZhouYiXun") - String strike; - @ApiModelProperty(value = "发送的消息数量", example = "1") - int sendMsgCount; - @ApiModelProperty(value = "接收的消息数量", example = "2") - int receiveMsgCount; - @ApiModelProperty(value = "状态", example = "WARN") - int status; - @ApiModelProperty(value = "创建时间", example = "2021-08-15 11:36:00") - @CreatedDate - @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") - Date createTime; - @ApiModelProperty(value = "结束时间", example = "2021-08-15 11:36:00") - @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") - Date endTime; - - public Results() { - } - - public int getId() { - return id; - } - - public void setId(int id) { - this.id = id; - } - - public int getSuiteId() { - return suiteId; - } - - public void setSuiteId(int suiteId) { - this.suiteId = suiteId; - } - - public String getSuiteName() { - return suiteName; - } - - public void setSuiteName(String suiteName) { - this.suiteName = suiteName; - } - - public int getProjectId() { - return projectId; - } - - public void setProjectId(int projectId) { - this.projectId = projectId; - } - - public String getStrike() { - return strike; - } - - public void setStrike(String strike) { - this.strike = strike; - } - - public int getSendMsgCount() { - return sendMsgCount; - } - - public void setSendMsgCount(int sendMsgCount) { - this.sendMsgCount = sendMsgCount; - } - - public int getReceiveMsgCount() { - return receiveMsgCount; - } - - public void setReceiveMsgCount(int receiveMsgCount) { - this.receiveMsgCount = receiveMsgCount; - } - - public int getStatus() { - return status; - } - - public void setStatus(int status) { - this.status = status; - } - - public Date getCreateTime() { - return createTime; - } - - public void setCreateTime(Date createTime) { - this.createTime = createTime; - } - - public Date getEndTime() { - return endTime; - } - - public void setEndTime(Date endTime) { - this.endTime = endTime; - } - - @Override - public String toString() { - return "Results{" + - "id=" + id + - ", suiteId=" + suiteId + - ", suiteName='" + suiteName + '\'' + - ", projectId=" + projectId + - ", strike='" + strike + '\'' + - ", sendMsgCount=" + sendMsgCount + - ", receiveMsgCount=" + receiveMsgCount + - ", status=" + status + - ", createTime=" + createTime + - ", endTime=" + endTime + - '}'; - } -} diff --git a/sonic-server-controller/src/main/java/com/sonic/controller/models/Steps.java b/sonic-server-controller/src/main/java/com/sonic/controller/models/Steps.java deleted file mode 100644 index 11caafa2..00000000 --- a/sonic-server-controller/src/main/java/com/sonic/controller/models/Steps.java +++ /dev/null @@ -1,170 +0,0 @@ -package com.sonic.controller.models; - - -import com.alibaba.fastjson.annotation.JSONField; -import com.fasterxml.jackson.annotation.JsonIgnore; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; - -import javax.persistence.*; -import javax.validation.constraints.NotNull; -import javax.validation.constraints.Positive; -import java.util.List; -import java.util.Set; - -@Entity -@ApiModel("运行步骤模型") -//添加caseId字段索引 -@Table(indexes = {@Index(columnList = "caseId")}) -public class Steps { - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - @ApiModelProperty(value = "id", example = "1") - int id; - @Positive - @ApiModelProperty(value = "项目id", required = true, example = "1") - int projectId; - @ApiModelProperty(value = "测试用例id", example = "1") - int caseId; - @Positive - @ApiModelProperty(value = "类型", required = true, example = "1") - int platform; - @NotNull - @ApiModelProperty(value = "步骤类型", required = true, example = "click") - String stepType; - @NotNull - @ApiModelProperty(value = "输入文本", required = true, example = "123") - @Lob - @Basic(fetch = FetchType.LAZY) - String content; - @NotNull - @ApiModelProperty(value = "其他信息", required = true, example = "456") - @Lob - @Basic(fetch = FetchType.LAZY) - String text; - @ApiModelProperty(value = "排序号", example = "123") - int sort; - @Positive - @ApiModelProperty(value = "异常处理类型", required = true, example = "1") - int error; - @ApiModelProperty(value = "包含元素列表") - @ManyToMany(fetch = FetchType.EAGER) - List elements; - @ManyToMany(mappedBy = "steps",fetch = FetchType.EAGER) - @JsonIgnore - @JSONField(serialize = false) - Set publicSteps; - - public Steps() { - } - - public int getId() { - return id; - } - - public void setId(int id) { - this.id = id; - } - - public int getProjectId() { - return projectId; - } - - public void setProjectId(int projectId) { - this.projectId = projectId; - } - - public int getCaseId() { - return caseId; - } - - public void setCaseId(int caseId) { - this.caseId = caseId; - } - - public int getPlatform() { - return platform; - } - - public void setPlatform(int platform) { - this.platform = platform; - } - - public String getStepType() { - return stepType; - } - - public void setStepType(String stepType) { - this.stepType = stepType; - } - - public String getContent() { - return content; - } - - public void setContent(String content) { - this.content = content; - } - - public String getText() { - return text; - } - - public void setText(String text) { - this.text = text; - } - - public int getSort() { - return sort; - } - - public void setSort(int sort) { - this.sort = sort; - } - - public int getError() { - return error; - } - - public void setError(int error) { - this.error = error; - } - - public List getElements() { - return elements; - } - - public void setElements(List elements) { - this.elements = elements; - } - - public Set getPublicSteps() { - return publicSteps; - } - - public void setPublicSteps(Set publicSteps) { - this.publicSteps = publicSteps; - } - - /** - * @return java.lang.String - * @author ZhouYiXun - * @des 注意,打印不能打印公共步骤模型,会造成堆溢出 - * @date 2021/8/15 19:50 - */ - @Override - public String toString() { - return "Steps{" + - "id=" + id + - ", projectId=" + projectId + - ", caseId=" + caseId + - ", platform=" + platform + - ", stepType='" + stepType + '\'' + - ", content='" + content + '\'' + - ", text='" + text + '\'' + - ", sort=" + sort + - ", error=" + error + - ", elements=" + elements + - '}'; - } -} diff --git a/sonic-server-controller/src/main/java/com/sonic/controller/models/TestCases.java b/sonic-server-controller/src/main/java/com/sonic/controller/models/TestCases.java deleted file mode 100644 index 28865906..00000000 --- a/sonic-server-controller/src/main/java/com/sonic/controller/models/TestCases.java +++ /dev/null @@ -1,154 +0,0 @@ -package com.sonic.controller.models; - -import com.alibaba.fastjson.annotation.JSONField; -import com.fasterxml.jackson.annotation.JsonFormat; -import com.fasterxml.jackson.annotation.JsonIgnore; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.springframework.data.annotation.LastModifiedDate; -import org.springframework.data.jpa.domain.support.AuditingEntityListener; - -import javax.persistence.*; -import javax.validation.constraints.NotNull; -import javax.validation.constraints.Positive; -import java.util.Date; -import java.util.List; -import java.util.Set; - -@Entity -@ApiModel("测试用例模型") -@Table(indexes = {@Index(columnList = "projectId")}) -@EntityListeners(AuditingEntityListener.class) -public class TestCases { - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - @ApiModelProperty(value = "id", example = "1") - int id; - @NotNull - @ApiModelProperty(value = "用例名称", required = true, example = "测试用例") - String name; - @Positive - @ApiModelProperty(value = "所属平台", required = true, example = "1") - int platform; - @Positive - @ApiModelProperty(value = "项目id", required = true, example = "1") - int projectId; - @NotNull - @ApiModelProperty(value = "模块名称", required = true, example = "xxx模块") - String module; - @NotNull - @ApiModelProperty(value = "项目迭代名称", required = true, example = "v1.0.0需求增加") - String version; - @NotNull - @ApiModelProperty(value = "用例描述", required = true, example = "xxx测试用例描述") - String des; - @NotNull - @ApiModelProperty(value = "用例设计人", required = true, example = "YiXunZhou") - String designer; - @ApiModelProperty(value = "最后修改日期", required = true, example = "2021-08-15 11:10:00") - @LastModifiedDate - @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") - Date editTime; - @ManyToMany(mappedBy = "testCases", fetch = FetchType.EAGER) - @JsonIgnore - @JSONField(serialize = false) - List testSuites; - - public TestCases() { - } - - public int getId() { - return id; - } - - public void setId(int id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public int getPlatform() { - return platform; - } - - public void setPlatform(int platform) { - this.platform = platform; - } - - public int getProjectId() { - return projectId; - } - - public void setProjectId(int projectId) { - this.projectId = projectId; - } - - public String getModule() { - return module; - } - - public void setModule(String module) { - this.module = module; - } - - public String getVersion() { - return version; - } - - public void setVersion(String version) { - this.version = version; - } - - public String getDes() { - return des; - } - - public void setDes(String des) { - this.des = des; - } - - public String getDesigner() { - return designer; - } - - public void setDesigner(String designer) { - this.designer = designer; - } - - public Date getEditTime() { - return editTime; - } - - public void setEditTime(Date editTime) { - this.editTime = editTime; - } - - public List getTestSuites() { - return testSuites; - } - - public void setTestSuites(List testSuites) { - this.testSuites = testSuites; - } - - @Override - public String toString() { - return "TestCases{" + - "id=" + id + - ", name='" + name + '\'' + - ", platform=" + platform + - ", projectId=" + projectId + - ", module='" + module + '\'' + - ", version='" + version + '\'' + - ", des='" + des + '\'' + - ", designer='" + designer + '\'' + - ", editTime=" + editTime + - '}'; - } -} diff --git a/sonic-server-controller/src/main/java/com/sonic/controller/models/TestSuites.java b/sonic-server-controller/src/main/java/com/sonic/controller/models/TestSuites.java deleted file mode 100644 index cdbc5d67..00000000 --- a/sonic-server-controller/src/main/java/com/sonic/controller/models/TestSuites.java +++ /dev/null @@ -1,110 +0,0 @@ -package com.sonic.controller.models; - -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; - -import javax.persistence.*; -import javax.validation.constraints.NotNull; -import javax.validation.constraints.Positive; -import java.util.List; -import java.util.Set; - -@Entity -@ApiModel("测试套件模型") -@Table(indexes = {@Index(columnList = "projectId")}) -public class TestSuites { - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - @ApiModelProperty(value = "id", example = "1") - int id; - @NotNull - @ApiModelProperty(value = "测试套件名称", required = true, example = "首页测试套件") - String name; - @Positive - @ApiModelProperty(value = "测试套件平台类型", required = true, example = "1") - int platform; - @Positive - @ApiModelProperty(value = "覆盖类型", required = true, example = "1") - int cover; - @Positive - @ApiModelProperty(value = "项目id", required = true, example = "1") - int projectId; - @ApiModelProperty(value = "包含的测试用例") - @ManyToMany(fetch = FetchType.EAGER) - List testCases; - @ApiModelProperty(value = "指定设备列表") - @ManyToMany(fetch = FetchType.EAGER) - Set devices; - - public TestSuites() { - } - - public int getId() { - return id; - } - - public void setId(int id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public int getPlatform() { - return platform; - } - - public void setPlatform(int platform) { - this.platform = platform; - } - - public int getCover() { - return cover; - } - - public void setCover(int cover) { - this.cover = cover; - } - - public int getProjectId() { - return projectId; - } - - public void setProjectId(int projectId) { - this.projectId = projectId; - } - - public List getTestCases() { - return testCases; - } - - public void setTestCases(List testCases) { - this.testCases = testCases; - } - - public Set getDevices() { - return devices; - } - - public void setDevices(Set devices) { - this.devices = devices; - } - - @Override - public String toString() { - return "TestSuites{" + - "id=" + id + - ", name='" + name + '\'' + - ", platform=" + platform + - ", cover=" + cover + - ", projectId=" + projectId + - ", testCases=" + testCases + - ", devices=" + devices + - '}'; - } -} diff --git a/sonic-server-controller/src/main/java/com/sonic/controller/models/Users.java b/sonic-server-controller/src/main/java/com/sonic/controller/models/Users.java deleted file mode 100644 index d19d27e8..00000000 --- a/sonic-server-controller/src/main/java/com/sonic/controller/models/Users.java +++ /dev/null @@ -1,72 +0,0 @@ -package com.sonic.controller.models; - -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; - -import javax.persistence.*; -import javax.validation.constraints.NotNull; -import javax.validation.constraints.Positive; - -@Entity -@ApiModel("用户模型") -@Table(uniqueConstraints = @UniqueConstraint(columnNames = {"userName"})) -public class Users { - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - @ApiModelProperty(value = "id", example = "1") - int id; - @NotNull - @ApiModelProperty(value = "用户名称", required = true, example = "ZhouYiXun") - String userName; - @NotNull - @ApiModelProperty(value = "用户密码", required = true, example = "123456") - String password; - @Positive - @ApiModelProperty(value = "角色", required = true, example = "1") - int role; - - public Users() { - } - - public int getId() { - return id; - } - - public void setId(int id) { - this.id = id; - } - - public String getUserName() { - return userName; - } - - public void setUserName(String userName) { - this.userName = userName; - } - - public String getPassword() { - return password; - } - - public void setPassword(String password) { - this.password = password; - } - - public int getRole() { - return role; - } - - public void setRole(int role) { - this.role = role; - } - - @Override - public String toString() { - return "Users{" + - "id=" + id + - ", userName='" + userName + '\'' + - ", password='" + password + '\'' + - ", role=" + role + - '}'; - } -} \ No newline at end of file diff --git a/sonic-server-controller/src/main/java/com/sonic/controller/models/Versions.java b/sonic-server-controller/src/main/java/com/sonic/controller/models/Versions.java deleted file mode 100644 index 590d5fcd..00000000 --- a/sonic-server-controller/src/main/java/com/sonic/controller/models/Versions.java +++ /dev/null @@ -1,74 +0,0 @@ -package com.sonic.controller.models; - -import com.fasterxml.jackson.annotation.JsonFormat; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; - -import javax.persistence.*; -import javax.validation.constraints.NotNull; -import javax.validation.constraints.Positive; -import java.util.Date; - -@Entity -@ApiModel("版本迭代模型") -@Table(indexes = {@Index(columnList = "projectId")}) -public class Versions { - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - @ApiModelProperty(value = "id", example = "1") - int id; - @Positive - @ApiModelProperty(value = "项目id", example = "1") - int projectId; - @NotNull - @ApiModelProperty(value = "迭代名称", example = "xxx迭代") - String versionName; - @NotNull - @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") - @ApiModelProperty(value = "日期", example = "2021-08-15T16:00:00.000+00:00") - Date createTime; - - public Versions(){} - - public int getId() { - return id; - } - - public void setId(int id) { - this.id = id; - } - - public int getProjectId() { - return projectId; - } - - public void setProjectId(int projectId) { - this.projectId = projectId; - } - - public String getVersionName() { - return versionName; - } - - public void setVersionName(String versionName) { - this.versionName = versionName; - } - - public Date getCreateTime() { - return createTime; - } - - public void setCreateTime(Date createTime) { - this.createTime = createTime; - } - - @Override - public String toString() { - return "Versions{" + - "id=" + id + - ", projectId=" + projectId + - ", versionName='" + versionName + '\'' + - ", createTime=" + createTime + - '}'; - } -} diff --git a/sonic-server-controller/src/main/java/com/sonic/controller/services/AgentsService.java b/sonic-server-controller/src/main/java/com/sonic/controller/services/AgentsService.java deleted file mode 100644 index 916eb967..00000000 --- a/sonic-server-controller/src/main/java/com/sonic/controller/services/AgentsService.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.sonic.controller.services; - -import com.alibaba.fastjson.JSONObject; -import com.sonic.controller.models.Agents; - -import java.util.List; - -/** - * @author ZhouYiXun - * @des Agent逻辑层 - * @date 2021/8/19 22:51 - */ -public interface AgentsService { - List findAgents(); - - void updateName(int id, String name); - - void save(JSONObject agents); - - boolean offLine(int id); - - int auth(String key); - - String findKeyById(int id); - - Agents findById(int id); -} \ No newline at end of file diff --git a/sonic-server-controller/src/main/java/com/sonic/controller/services/ElementsService.java b/sonic-server-controller/src/main/java/com/sonic/controller/services/ElementsService.java deleted file mode 100644 index a7a392e6..00000000 --- a/sonic-server-controller/src/main/java/com/sonic/controller/services/ElementsService.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.sonic.controller.services; - -import com.sonic.common.http.RespModel; -import com.sonic.controller.models.Elements; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.Pageable; - -import java.util.List; - -public interface ElementsService { - Page findAll(int projectId, String type, List eleTypes, String name, Pageable pageable); - - RespModel delete(int id); - - boolean save(Elements elements); - - Elements findById(int id); -} diff --git a/sonic-server-controller/src/main/java/com/sonic/controller/services/GlobalParamsService.java b/sonic-server-controller/src/main/java/com/sonic/controller/services/GlobalParamsService.java deleted file mode 100644 index 39893685..00000000 --- a/sonic-server-controller/src/main/java/com/sonic/controller/services/GlobalParamsService.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.sonic.controller.services; - -import com.sonic.controller.models.GlobalParams; - -import java.util.List; - -public interface GlobalParamsService { - List findAll(int projectId); - - boolean delete(int id); - - void save(GlobalParams globalParams); - - GlobalParams findById(int id); -} diff --git a/sonic-server-controller/src/main/java/com/sonic/controller/services/ModulesService.java b/sonic-server-controller/src/main/java/com/sonic/controller/services/ModulesService.java deleted file mode 100644 index dcce4b26..00000000 --- a/sonic-server-controller/src/main/java/com/sonic/controller/services/ModulesService.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.sonic.controller.services; - -import com.sonic.controller.models.Modules; - -import java.util.List; - -public interface ModulesService { - void save(Modules modules); - - boolean delete(int id); - - List findByProjectId(int projectId); - - Modules findById(int id); -} diff --git a/sonic-server-controller/src/main/java/com/sonic/controller/services/ProjectsService.java b/sonic-server-controller/src/main/java/com/sonic/controller/services/ProjectsService.java deleted file mode 100644 index 86a95e24..00000000 --- a/sonic-server-controller/src/main/java/com/sonic/controller/services/ProjectsService.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.sonic.controller.services; - -import com.sonic.common.exception.SonicException; -import com.sonic.controller.models.Projects; - -import java.util.List; - -/** - * @author ZhouYiXun - * @des 项目逻辑层 - * @date 2021/8/20 20:51 - */ -public interface ProjectsService { - void save(Projects projects); - - Projects findById(int id); - - List findAll(); - - void delete(int id) throws SonicException; -} diff --git a/sonic-server-controller/src/main/java/com/sonic/controller/services/PublicStepsService.java b/sonic-server-controller/src/main/java/com/sonic/controller/services/PublicStepsService.java deleted file mode 100644 index 5a4c6515..00000000 --- a/sonic-server-controller/src/main/java/com/sonic/controller/services/PublicStepsService.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.sonic.controller.services; - -import com.sonic.controller.models.PublicSteps; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.Pageable; - -import java.util.List; -import java.util.Map; - -/** - * @author ZhouYiXun - * @des 公共步骤逻辑层 - * @date 2021/8/20 17:51 - */ -public interface PublicStepsService { - Page findByProjectId(int projectId, Pageable pageable); - - List> findByProjectIdAndPlatform(int projectId, int platform); - - PublicSteps save(PublicSteps publicSteps); - - boolean delete(int id); - - PublicSteps findById(int id); -} diff --git a/sonic-server-controller/src/main/java/com/sonic/controller/services/ResultDetailService.java b/sonic-server-controller/src/main/java/com/sonic/controller/services/ResultDetailService.java deleted file mode 100644 index 9f28b943..00000000 --- a/sonic-server-controller/src/main/java/com/sonic/controller/services/ResultDetailService.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.sonic.controller.services; - -import com.alibaba.fastjson.JSONObject; -import com.sonic.controller.models.ResultDetail; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.Pageable; - -import java.util.List; - -/** - * @author ZhouYiXun - * @des 测试结果详情逻辑层 - * @date 2021/8/21 16:08 - */ -public interface ResultDetailService { - void save(ResultDetail resultDetail); - - void saveByTransport(JSONObject jsonObject); - - Page findAll(int resultId, int caseId, String type, int deviceId, Pageable pageable); - - List findAll(int resultId, int caseId, String type, int deviceId); - - void deleteByResultId(int resultId); -} diff --git a/sonic-server-controller/src/main/java/com/sonic/controller/services/StepsService.java b/sonic-server-controller/src/main/java/com/sonic/controller/services/StepsService.java deleted file mode 100644 index 1e0f399d..00000000 --- a/sonic-server-controller/src/main/java/com/sonic/controller/services/StepsService.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.sonic.controller.services; - -import com.sonic.controller.models.Steps; -import com.sonic.controller.models.http.StepSort; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.Pageable; - -import java.util.List; - -/** - * @author ZhouYiXun - * @des 测试步骤逻辑层 - * @date 2021/8/20 17:51 - */ -public interface StepsService { - List findByCaseIdOrderBySort(int caseId); - - boolean resetCaseId(int id); - - boolean delete(int id); - - void save(Steps operations); - - Steps findById(int id); - - void sortSteps(StepSort stepSort); - - Page findByProjectIdAndPlatform(int projectId, int platform, Pageable pageable); -} diff --git a/sonic-server-controller/src/main/java/com/sonic/controller/services/TestCasesService.java b/sonic-server-controller/src/main/java/com/sonic/controller/services/TestCasesService.java deleted file mode 100644 index 9f74d533..00000000 --- a/sonic-server-controller/src/main/java/com/sonic/controller/services/TestCasesService.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.sonic.controller.services; - -import com.alibaba.fastjson.JSONObject; -import com.sonic.controller.models.TestCases; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.Pageable; - -import java.util.List; - -/** - * @author ZhouYiXun - * @des 测试用例逻辑层 - * @date 2021/8/20 17:51 - */ -public interface TestCasesService { - Page findAll(int projectId, int platform, String name, Pageable pageable); - - List findAll(int projectId, int platform); - - boolean delete(int id); - - void save(TestCases testCases); - - TestCases findById(int id); - - JSONObject findSteps(int id); - - List findByIdIn(List ids); -} diff --git a/sonic-server-controller/src/main/java/com/sonic/controller/services/TestSuitesService.java b/sonic-server-controller/src/main/java/com/sonic/controller/services/TestSuitesService.java deleted file mode 100644 index f1054be5..00000000 --- a/sonic-server-controller/src/main/java/com/sonic/controller/services/TestSuitesService.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.sonic.controller.services; - - -import com.sonic.common.http.RespModel; -import com.sonic.controller.models.TestSuites; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.Pageable; - -import java.util.List; - -/** - * @author ZhouYiXun - * @des 测试套件逻辑层 - * @date 2021/8/20 17:51 - */ -public interface TestSuitesService { - RespModel runSuite(int id, String strike); - - TestSuites findById(int id); - - boolean delete(int id); - - RespModel forceStopSuite(int id, String strike); - - void save(TestSuites testSuites); - - Page findByProjectId(int projectId, String name, Pageable pageable); - - List findByProjectId(int projectId); -} diff --git a/sonic-server-controller/src/main/java/com/sonic/controller/services/UsersService.java b/sonic-server-controller/src/main/java/com/sonic/controller/services/UsersService.java deleted file mode 100644 index f4e41692..00000000 --- a/sonic-server-controller/src/main/java/com/sonic/controller/services/UsersService.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.sonic.controller.services; - -import com.sonic.common.exception.SonicException; -import com.sonic.common.http.RespModel; -import com.sonic.controller.models.Users; -import com.sonic.controller.models.http.ChangePwd; -import com.sonic.controller.models.http.UserInfo; - -public interface UsersService { - void register(Users users) throws SonicException; - - String login(UserInfo userInfo); - - Users getUserInfo(String token); - - RespModel resetPwd(String token, ChangePwd changePwd); -} diff --git a/sonic-server-controller/src/main/java/com/sonic/controller/services/VersionsService.java b/sonic-server-controller/src/main/java/com/sonic/controller/services/VersionsService.java deleted file mode 100644 index 33ab7167..00000000 --- a/sonic-server-controller/src/main/java/com/sonic/controller/services/VersionsService.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.sonic.controller.services; - - -import com.sonic.controller.models.Versions; - -import java.util.List; - -/** - * @author ZhouYiXun - * @des 迭代逻辑层 - * @date 2021/8/16 22:54 - */ -public interface VersionsService { - void save(Versions versions); - - boolean delete(int id); - - List findByProjectId(int projectId); - - Versions findById(int id); -} diff --git a/sonic-server-controller/src/main/java/com/sonic/controller/services/impl/DevicesServiceImpl.java b/sonic-server-controller/src/main/java/com/sonic/controller/services/impl/DevicesServiceImpl.java deleted file mode 100644 index f50af96a..00000000 --- a/sonic-server-controller/src/main/java/com/sonic/controller/services/impl/DevicesServiceImpl.java +++ /dev/null @@ -1,321 +0,0 @@ -package com.sonic.controller.services.impl; - -import com.alibaba.fastjson.JSON; -import com.alibaba.fastjson.JSONObject; -import com.sonic.controller.dao.DevicesRepository; -import com.sonic.controller.models.Devices; -import com.sonic.controller.models.Users; -import com.sonic.controller.models.http.DeviceDetailChange; -import com.sonic.controller.models.http.UpdateDeviceImg; -import com.sonic.controller.models.interfaces.DeviceStatus; -import com.sonic.controller.models.interfaces.PlatformType; -import com.sonic.controller.services.DevicesService; -import com.sonic.controller.services.UsersService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.Pageable; -import org.springframework.data.jpa.domain.Specification; -import org.springframework.stereotype.Service; - -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.Order; -import javax.persistence.criteria.Predicate; -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -/** - * @author ZhouYiXun - * @des 设备逻辑层实现 - * @date 2021/8/16 22:51 - */ -@Service -public class DevicesServiceImpl implements DevicesService { - @Autowired - private DevicesRepository devicesRepository; - @Autowired - private UsersService usersService; - - @Override - public boolean saveDetail(DeviceDetailChange deviceDetailChange) { - if (devicesRepository.existsById(deviceDetailChange.getId())) { - Devices devices = devicesRepository.findById(deviceDetailChange.getId()).get(); - devices.setNickName(deviceDetailChange.getNickName()); - devices.setPassword(deviceDetailChange.getPassword()); - devicesRepository.save(devices); - return true; - } else { - return false; - } - } - - @Override - public void updateDevicesUser(JSONObject jsonObject) { - Users users = usersService.getUserInfo(jsonObject.getString("token")); - Devices devices = findByAgentIdAndUdId(jsonObject.getInteger("agentId"), - jsonObject.getString("udId")); - devices.setUser(users.getUserName()); - save(devices); - } - - @Override - public void updateImg(UpdateDeviceImg updateDeviceImg) { - if (devicesRepository.existsById(updateDeviceImg.getId())) { - Devices devices = devicesRepository.findById(updateDeviceImg.getId()).get(); - devices.setImgUrl(updateDeviceImg.getImgUrl()); - devicesRepository.save(devices); - } - } - - @Override - public void save(Devices devices) { - devicesRepository.save(devices); - } - - @Override - public Page findAll(List iOSVersion, List androidVersion, - List manufacturer, List cpu, List size, - List agentId, List status, String deviceInfo, - Pageable pageable) { - Specification spc = (root, query, cb) -> { - //根据status的字符串自定义排序 - List orders = new ArrayList<>(); - orders.add(cb.asc(cb.selectCase() - .when(cb.equal(root.get("status").as(String.class), DeviceStatus.ONLINE), 1) - .when(cb.equal(root.get("status").as(String.class), DeviceStatus.DEBUGGING), 2) - .when(cb.equal(root.get("status").as(String.class), DeviceStatus.TESTING), 3) - .when(cb.equal(root.get("status").as(String.class), DeviceStatus.ERROR), 4) - .when(cb.equal(root.get("status").as(String.class), DeviceStatus.UNAUTHORIZED), 5) - .when(cb.equal(root.get("status").as(String.class), DeviceStatus.OFFLINE), 6) - .when(cb.equal(root.get("status").as(String.class), DeviceStatus.DISCONNECTED), 7) - .otherwise(8))); - orders.add(cb.asc(root.get("status"))); - orders.add(cb.desc(root.get("id"))); - query.orderBy(orders); - List predicateList = new ArrayList<>(); - if (androidVersion != null || iOSVersion != null) { - List androidAndiOS = new ArrayList<>(); - //查找类型为安卓的并且version%的设备 - if (androidVersion != null) { - List list = new ArrayList<>(); - for (String version : androidVersion) { - List platform = new ArrayList<>(); - platform.add(cb.equal(root.get("platform"), PlatformType.ANDROID)); - platform.add(cb.like(root.get("version"), version + "%")); - Predicate[] p = new Predicate[platform.size()]; - list.add(cb.and(platform.toArray(p))); - } - Predicate[] l = new Predicate[list.size()]; - androidAndiOS.add(cb.or(list.toArray(l))); - } - //查找类型为iOS的并且version%的设备 - if (iOSVersion != null) { - List list = new ArrayList<>(); - for (String version : iOSVersion) { - List platform = new ArrayList<>(); - platform.add(cb.equal(root.get("platform"), PlatformType.IOS)); - platform.add(cb.like(root.get("version"), version + "%")); - Predicate[] p = new Predicate[platform.size()]; - list.add(cb.and(platform.toArray(p))); - } - Predicate[] l = new Predicate[list.size()]; - androidAndiOS.add(cb.or(list.toArray(l))); - } - //最后两个条件为or - Predicate[] result = new Predicate[androidAndiOS.size()]; - predicateList.add(cb.or(androidAndiOS.toArray(result))); - } - if (manufacturer != null) { - CriteriaBuilder.In in = cb.in(root.get("manufacturer")); - for (String man : manufacturer) { - in.value(man); - } - predicateList.add(cb.and(in)); - } - if (cpu != null) { - CriteriaBuilder.In in = cb.in(root.get("cpu")); - for (String c : cpu) { - in.value(c); - } - predicateList.add(cb.and(in)); - } - if (size != null) { - CriteriaBuilder.In in = cb.in(root.get("size")); - for (String s : size) { - in.value(s); - } - predicateList.add(cb.and(in)); - } - if (agentId != null) { - CriteriaBuilder.In in = cb.in(root.get("agentId")); - for (int a : agentId) { - in.value(a); - } - predicateList.add(cb.and(in)); - } - if (status != null) { - CriteriaBuilder.In in = cb.in(root.get("status")); - for (String s : status) { - in.value(s); - } - predicateList.add(cb.and(in)); - } - if (deviceInfo != null) { - //因为是型号或者udId或者中文,所以三个条件为or - List modelOrUdId = new ArrayList<>(); - modelOrUdId.add(cb.like(root.get("model"), "%" + deviceInfo + "%")); - modelOrUdId.add(cb.like(root.get("chiName"), "%" + deviceInfo + "%")); - modelOrUdId.add(cb.like(root.get("udId"), "%" + deviceInfo + "%")); - Predicate[] result = new Predicate[modelOrUdId.size()]; - predicateList.add(cb.or(modelOrUdId.toArray(result))); - } - if (predicateList.size() != 0) { - Predicate[] p = new Predicate[predicateList.size()]; - return query.where(predicateList.toArray(p)).getRestriction(); - } else { - return query.getRestriction(); - } - }; - return devicesRepository.findAll(spc, pageable); - } - - @Override - public List findAll(int platform) { - return devicesRepository.findByPlatformOrderByIdDesc(platform); - } - - @Override - public List findByIdIn(List ids) { - return devicesRepository.findByIdIn(ids); - } - - @Override - public Devices findByAgentIdAndUdId(int agentId, String udId) { - return devicesRepository.findByAgentIdAndUdId(agentId, udId); - } - - @Override - public JSONObject getFilterOption() { - JSONObject jsonObject = new JSONObject(); - List cpuList = devicesRepository.findCpuList(); - if (cpuList.contains("未知")) { - cpuList.remove("未知"); - cpuList.add("未知"); - } - jsonObject.put("cpu", cpuList); - List sizeList = devicesRepository.findSizeList(); - if (sizeList.contains("未知")) { - sizeList.remove("未知"); - sizeList.add("未知"); - } - jsonObject.put("size", sizeList); - return jsonObject; - } - - public String getName(String model) { - InputStream config = getClass().getResourceAsStream("/result.json"); - JSONObject jsonObject = null; - try { - jsonObject = JSON.parseObject(config, JSONObject.class); - } catch (IOException e) { - e.printStackTrace(); - } finally { - try { - config.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - return jsonObject.getString(model) == null ? "" : jsonObject.getString(model); - } - - @Override - public void deviceStatus(JSONObject jsonMsg) { - Devices devices = findByAgentIdAndUdId(jsonMsg.getInteger("agentId") - , jsonMsg.getString("udId")); - if (devices == null) { - Devices newDevices = new Devices(); - newDevices.setUdId(jsonMsg.getString("udId")); - if (jsonMsg.getString("name") != null) { - newDevices.setName(jsonMsg.getString("name")); - } - if (jsonMsg.getString("model") != null) { - newDevices.setName(jsonMsg.getString("model")); - newDevices.setChiName(getName(jsonMsg.getString("model"))); - } - newDevices.setPlatform(jsonMsg.getInteger("platform")); - newDevices.setVersion(jsonMsg.getString("version")); - newDevices.setCpu(jsonMsg.getString("cpu")); - newDevices.setSize(jsonMsg.getString("size")); - newDevices.setManufacturer(jsonMsg.getString("manufacturer")); - newDevices.setAgentId(jsonMsg.getInteger("agentId")); - newDevices.setStatus(jsonMsg.getString("status")); - newDevices.setPassword(""); - newDevices.setImgUrl(""); - newDevices.setTemperature(0); - save(newDevices); - } else { - devices.setAgentId(jsonMsg.getInteger("agentId")); - if (jsonMsg.getString("name") != null) { - if (!jsonMsg.getString("name").equals("未知")) { - devices.setName(jsonMsg.getString("name")); - } - } - if (jsonMsg.getString("model") != null) { - if (!jsonMsg.getString("model").equals("未知")) { - devices.setModel(jsonMsg.getString("model")); - devices.setChiName(getName(jsonMsg.getString("model"))); - } - } - if (jsonMsg.getString("version") != null) { - devices.setVersion(jsonMsg.getString("version")); - } - if (jsonMsg.getString("platform") != null) { - devices.setPlatform(jsonMsg.getInteger("platform")); - } - if (jsonMsg.getString("cpu") != null) { - devices.setCpu(jsonMsg.getString("cpu")); - } - if (jsonMsg.getString("size") != null) { - devices.setSize(jsonMsg.getString("size")); - } - if (jsonMsg.getString("manufacturer") != null) { - devices.setManufacturer(jsonMsg.getString("manufacturer")); - } - if (jsonMsg.getString("status") != null) { - devices.setStatus(jsonMsg.getString("status")); - } - save(devices); - } - } - - @Override - public Devices findById(int id) { - if (devicesRepository.existsById(id)) { - return devicesRepository.findById(id).get(); - } else { - return null; - } - } - - @Override - public Integer findTemper() { - return devicesRepository.findTemper(Arrays.asList(DeviceStatus.ONLINE - ,DeviceStatus.DEBUGGING,DeviceStatus.TESTING)); - } - - @Override - public void refreshDevicesTemper(JSONObject jsonObject) { - int agentId = jsonObject.getInteger("agentId"); - List deviceTemList = jsonObject.getJSONArray("detail").toJavaList(JSONObject.class); - for (JSONObject d : deviceTemList) { - Devices devices = findByAgentIdAndUdId(agentId, d.getString("udId")); - if (devices != null) { - devices.setTemperature(d.getInteger("tem")); - devicesRepository.save(devices); - } - } - } -} diff --git a/sonic-server-controller/src/main/java/com/sonic/controller/services/impl/ElementsServiceImpl.java b/sonic-server-controller/src/main/java/com/sonic/controller/services/impl/ElementsServiceImpl.java deleted file mode 100644 index 7af9d347..00000000 --- a/sonic-server-controller/src/main/java/com/sonic/controller/services/impl/ElementsServiceImpl.java +++ /dev/null @@ -1,108 +0,0 @@ -package com.sonic.controller.services.impl; - -import com.sonic.common.http.RespEnum; -import com.sonic.common.http.RespModel; -import com.sonic.controller.dao.ElementsRepository; -import com.sonic.controller.dao.StepsRepository; -import com.sonic.controller.models.Elements; -import com.sonic.controller.models.Steps; -import com.sonic.controller.services.ElementsService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.Pageable; -import org.springframework.data.jpa.domain.Specification; -import org.springframework.stereotype.Service; - -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.Order; -import javax.persistence.criteria.Predicate; -import java.util.ArrayList; -import java.util.List; - -@Service -public class ElementsServiceImpl implements ElementsService { - @Autowired - private ElementsRepository elementsRepository; - @Autowired - private StepsRepository stepsRepository; - - @Override - public boolean save(Elements elements) { - try { - elementsRepository.save(elements); - return true; - } catch (Exception e) { - return false; - } - } - - @Override - public Page findAll(int projectId, String type, List eleTypes, String name, Pageable pageable) { - Specification spc = (root, query, cb) -> { - List orders = new ArrayList<>(); - orders.add(cb.desc(root.get("id"))); - query.orderBy(orders); - List predicateList = new ArrayList<>(); - predicateList.add(cb.and(cb.equal(root.get("projectId"), projectId))); - if (type != null && type.length() > 0) { - switch (type) { - case "normal": - predicateList.add(cb.and(cb.notEqual(root.get("eleType"), "point"))); - predicateList.add(cb.and(cb.notEqual(root.get("eleType"), "image"))); - break; - case "point": - predicateList.add(cb.and(cb.equal(root.get("eleType"), "point"))); - break; - case "image": - predicateList.add(cb.and(cb.equal(root.get("eleType"), "image"))); - break; - } - } - if (eleTypes != null) { - CriteriaBuilder.In in = cb.in(root.get("eleType")); - for (String e : eleTypes) { - in.value(e); - } - predicateList.add(cb.and(in)); - } - if (name != null && name.length() > 0) { - predicateList.add(cb.and(cb.like(root.get("eleName"), "%" + name + "%"))); - } - Predicate[] p = new Predicate[predicateList.size()]; - return query.where(predicateList.toArray(p)).getRestriction(); - }; - return elementsRepository.findAll(spc, pageable); - } - - @Override - public RespModel delete(int id) { - if (elementsRepository.existsById(id)) { - try { - elementsRepository.deleteById(id); - return new RespModel(RespEnum.DELETE_OK); - } catch (Exception e) { - List stepsList = elementsRepository.findById(id).get().getSteps(); - String sList = ""; - for (Steps s : stepsList) { - if (sList.length() == 0) { - sList += s.getId(); - } else { - sList += "," + s.getId(); - } - } - return new RespModel(-2, "删除失败!控件元素已存在于步骤id:" + sList + "中!"); - } - } else { - return new RespModel(RespEnum.ID_NOT_FOUND); - } - } - - @Override - public Elements findById(int id) { - if (elementsRepository.existsById(id)) { - return elementsRepository.findById(id).get(); - } else { - return null; - } - } -} diff --git a/sonic-server-controller/src/main/java/com/sonic/controller/services/impl/GlobalParamsServiceImpl.java b/sonic-server-controller/src/main/java/com/sonic/controller/services/impl/GlobalParamsServiceImpl.java deleted file mode 100644 index 2fe35a5d..00000000 --- a/sonic-server-controller/src/main/java/com/sonic/controller/services/impl/GlobalParamsServiceImpl.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.sonic.controller.services.impl; - -import com.sonic.common.http.RespModel; -import com.sonic.controller.dao.GlobalParamsRepository; -import com.sonic.controller.models.GlobalParams; -import com.sonic.controller.services.GlobalParamsService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -import java.util.List; - -/** - * @author ZhouYiXun - * @des - * @date 2021/10/9 23:28 - */ -@Service -public class GlobalParamsServiceImpl implements GlobalParamsService { - @Autowired - private GlobalParamsRepository globalParamsRepository; - - @Override - public List findAll(int projectId) { - return globalParamsRepository.findByProjectId(projectId); - } - - @Override - public boolean delete(int id) { - if (globalParamsRepository.existsById(id)) { - globalParamsRepository.deleteById(id); - return true; - } else { - return false; - } - } - - @Override - public void save(GlobalParams globalParams) { - globalParamsRepository.save(globalParams); - } - - @Override - public GlobalParams findById(int id) { - if (globalParamsRepository.existsById(id)) { - return globalParamsRepository.findById(id).get(); - } else { - return null; - } - } -} diff --git a/sonic-server-controller/src/main/java/com/sonic/controller/services/impl/ModulesServiceImpl.java b/sonic-server-controller/src/main/java/com/sonic/controller/services/impl/ModulesServiceImpl.java deleted file mode 100644 index 11dd3013..00000000 --- a/sonic-server-controller/src/main/java/com/sonic/controller/services/impl/ModulesServiceImpl.java +++ /dev/null @@ -1,44 +0,0 @@ -package com.sonic.controller.services.impl; - -import com.sonic.controller.dao.ModulesRepository; -import com.sonic.controller.models.Modules; -import com.sonic.controller.services.ModulesService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -import java.util.List; - -@Service -public class ModulesServiceImpl implements ModulesService { - @Autowired - private ModulesRepository modulesRepository; - - @Override - public void save(Modules modules) { - modulesRepository.save(modules); - } - - @Override - public boolean delete(int id) { - if (modulesRepository.existsById(id)) { - modulesRepository.deleteById(id); - return true; - } else { - return false; - } - } - - @Override - public List findByProjectId(int projectId) { - return modulesRepository.findByProjectId(projectId); - } - - @Override - public Modules findById(int id) { - if (modulesRepository.existsById(id)) { - return modulesRepository.findById(id).get(); - } else { - return null; - } - } -} diff --git a/sonic-server-controller/src/main/java/com/sonic/controller/services/impl/ProjectsServiceImpl.java b/sonic-server-controller/src/main/java/com/sonic/controller/services/impl/ProjectsServiceImpl.java deleted file mode 100644 index 8a03859c..00000000 --- a/sonic-server-controller/src/main/java/com/sonic/controller/services/impl/ProjectsServiceImpl.java +++ /dev/null @@ -1,85 +0,0 @@ -package com.sonic.controller.services.impl; - -import com.sonic.common.exception.SonicException; -import com.sonic.controller.dao.*; -import com.sonic.controller.models.Projects; -import com.sonic.controller.models.Results; -import com.sonic.controller.services.ProjectsService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -import java.util.List; - -/** - * @author ZhouYiXun - * @des 项目逻辑实现 - * @date 2021/8/21 20:57 - */ -@Service -public class ProjectsServiceImpl implements ProjectsService { - @Autowired - private ProjectsRepository projectsRepository; - @Autowired - private ElementsRepository elementsRepository; - @Autowired - private GlobalParamsRepository globalParamsRepository; - @Autowired - private ModulesRepository modulesRepository; - @Autowired - private VersionsRepository versionsRepository; - @Autowired - private PublicStepsRepository publicStepsRepository; - @Autowired - private ResultsRepository resultsRepository; - @Autowired - private ResultDetailRepository resultDetailRepository; - @Autowired - private StepsRepository stepsRepository; - @Autowired - private TestSuitesRepository testSuitesRepository; - @Autowired - private TestCasesRepository testCasesRepository; - - @Override - public void save(Projects projects) { - projectsRepository.save(projects); - } - - @Override - public Projects findById(int id) { - if (projectsRepository.existsById(id)) { - return projectsRepository.findById(id).get(); - } else { - return null; - } - } - - @Override - public List findAll() { - return projectsRepository.findAll(); - } - - @Override - @Transactional(rollbackFor = SonicException.class) - public void delete(int id) throws SonicException { - try { - testSuitesRepository.deleteByProjectId(id); - publicStepsRepository.deleteByProjectId(id); - testCasesRepository.deleteByProjectId(id); - stepsRepository.deleteByProjectId(id); - elementsRepository.deleteByProjectId(id); - modulesRepository.deleteByProjectId(id); - globalParamsRepository.deleteByProjectId(id); - List resultsList = resultsRepository.findByProjectId(id); - for (Results results : resultsList) { - resultDetailRepository.deleteByResultId(results.getId()); - } - resultsRepository.deleteByProjectId(id); - versionsRepository.deleteByProjectId(id); - projectsRepository.deleteById(id); - } catch (Exception e) { - throw new SonicException("删除出错!请联系管理员!"); - } - } -} diff --git a/sonic-server-controller/src/main/java/com/sonic/controller/services/impl/PublicStepsServiceImpl.java b/sonic-server-controller/src/main/java/com/sonic/controller/services/impl/PublicStepsServiceImpl.java deleted file mode 100644 index 9138babb..00000000 --- a/sonic-server-controller/src/main/java/com/sonic/controller/services/impl/PublicStepsServiceImpl.java +++ /dev/null @@ -1,58 +0,0 @@ -package com.sonic.controller.services.impl; - -import com.sonic.controller.dao.PublicStepsRepository; -import com.sonic.controller.models.PublicSteps; -import com.sonic.controller.services.PublicStepsService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.Pageable; -import org.springframework.stereotype.Service; - -import java.util.List; -import java.util.Map; - -/** - * @author ZhouYiXun - * @des 公共步骤逻辑实现 - * @date 2021/8/20 17:51 - */ -@Service -public class PublicStepsServiceImpl implements PublicStepsService { - @Autowired - private PublicStepsRepository publicStepsRepository; - - @Override - public Page findByProjectId(int projectId, Pageable pageable) { - return publicStepsRepository.findByProjectId(projectId, pageable); - } - - @Override - public List> findByProjectIdAndPlatform(int projectId, int platform) { - return publicStepsRepository.findByProjectIdAndPlatform(projectId, platform); - } - - @Override - public PublicSteps save(PublicSteps publicSteps) { - publicStepsRepository.save(publicSteps); - return publicSteps; - } - - @Override - public boolean delete(int id) { - if (publicStepsRepository.existsById(id)) { - publicStepsRepository.deleteById(id); - return true; - } else { - return false; - } - } - - @Override - public PublicSteps findById(int id) { - if (publicStepsRepository.existsById(id)) { - return publicStepsRepository.findById(id).get(); - } else { - return null; - } - } -} diff --git a/sonic-server-controller/src/main/java/com/sonic/controller/services/impl/ResultDetailServiceImpl.java b/sonic-server-controller/src/main/java/com/sonic/controller/services/impl/ResultDetailServiceImpl.java deleted file mode 100644 index 33c4ac87..00000000 --- a/sonic-server-controller/src/main/java/com/sonic/controller/services/impl/ResultDetailServiceImpl.java +++ /dev/null @@ -1,120 +0,0 @@ -package com.sonic.controller.services.impl; - -import com.alibaba.fastjson.JSONObject; -import com.sonic.controller.dao.ResultDetailRepository; -import com.sonic.controller.models.Devices; -import com.sonic.controller.models.Elements; -import com.sonic.controller.models.ResultDetail; -import com.sonic.controller.models.Results; -import com.sonic.controller.models.interfaces.ResultDetailStatus; -import com.sonic.controller.models.interfaces.ResultStatus; -import com.sonic.controller.services.DevicesService; -import com.sonic.controller.services.ProjectsService; -import com.sonic.controller.services.ResultDetailService; -import com.sonic.controller.services.ResultsService; -import com.sonic.controller.tools.RobotMsgTool; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.Pageable; -import org.springframework.data.jpa.domain.Specification; -import org.springframework.stereotype.Service; - -import javax.persistence.criteria.Order; -import javax.persistence.criteria.Predicate; -import java.util.ArrayList; -import java.util.List; - -/** - * @author ZhouYiXun - * @des 测试结果详情逻辑实现 - * @date 2021/8/21 20:55 - */ -@Service -public class ResultDetailServiceImpl implements ResultDetailService { - @Autowired - private ResultDetailRepository resultDetailRepository; - @Autowired - private DevicesService devicesService; - @Autowired - private ResultsService resultsService; - - @Override - public void save(ResultDetail resultDetail) { - resultDetailRepository.save(resultDetail); - } - - @Override - public void saveByTransport(JSONObject jsonMsg) { - Devices resultDevice = devicesService.findByAgentIdAndUdId(jsonMsg.getInteger("agentId") - , jsonMsg.getString("udId")); - ResultDetail resultInfo = new ResultDetail(); - resultInfo.setType(jsonMsg.getString("msg")); - resultInfo.setLog(jsonMsg.getString("log")); - resultInfo.setDes(jsonMsg.getString("des")); - resultInfo.setStatus(jsonMsg.getInteger("status")); - resultInfo.setResultId(jsonMsg.getInteger("rid")); - resultInfo.setCaseId(jsonMsg.getInteger("cid")); - resultInfo.setTime(jsonMsg.getDate("time")); - resultInfo.setDeviceId(resultDevice == null ? 0 : resultDevice.getId()); - save(resultInfo); - if (jsonMsg.getString("msg").equals("status")) { - resultsService.suiteResult(jsonMsg.getInteger("rid")); - } - } - - @Override - public Page findAll(int resultId, int caseId, String type, int deviceId, Pageable pageable) { - Specification spc = (root, query, cb) -> { - List orders = new ArrayList<>(); - orders.add(cb.asc(root.get("time"))); - query.orderBy(orders); - List predicateList = new ArrayList<>(); - if (resultId != 0) { - predicateList.add(cb.and(cb.equal(root.get("resultId"), resultId))); - } - if (caseId != 0) { - predicateList.add(cb.and(cb.equal(root.get("caseId"), caseId))); - } - if (type != null && type.length() > 0) { - predicateList.add(cb.and(cb.equal(root.get("type"), type))); - } - if (deviceId != 0) { - predicateList.add(cb.and(cb.equal(root.get("deviceId"), deviceId))); - } - Predicate[] p = new Predicate[predicateList.size()]; - return query.where(predicateList.toArray(p)).getRestriction(); - }; - return resultDetailRepository.findAll(spc, pageable); - } - - @Override - public List findAll(int resultId, int caseId, String type, int deviceId) { - Specification spc = (root, query, cb) -> { - List orders = new ArrayList<>(); - orders.add(cb.asc(root.get("time"))); - query.orderBy(orders); - List predicateList = new ArrayList<>(); - if (resultId != 0) { - predicateList.add(cb.and(cb.equal(root.get("resultId"), resultId))); - } - if (caseId != 0) { - predicateList.add(cb.and(cb.equal(root.get("caseId"), caseId))); - } - if (type != null && type.length() > 0) { - predicateList.add(cb.and(cb.equal(root.get("type"), type))); - } - if (deviceId != 0) { - predicateList.add(cb.and(cb.equal(root.get("deviceId"), deviceId))); - } - Predicate[] p = new Predicate[predicateList.size()]; - return query.where(predicateList.toArray(p)).getRestriction(); - }; - return resultDetailRepository.findAll(spc); - } - - - @Override - public void deleteByResultId(int resultId) { - resultDetailRepository.deleteByResultId(resultId); - } -} diff --git a/sonic-server-controller/src/main/java/com/sonic/controller/services/impl/StepsServiceImpl.java b/sonic-server-controller/src/main/java/com/sonic/controller/services/impl/StepsServiceImpl.java deleted file mode 100644 index bbc148b6..00000000 --- a/sonic-server-controller/src/main/java/com/sonic/controller/services/impl/StepsServiceImpl.java +++ /dev/null @@ -1,113 +0,0 @@ -package com.sonic.controller.services.impl; - -import com.sonic.controller.dao.StepsRepository; -import com.sonic.controller.models.PublicSteps; -import com.sonic.controller.models.Steps; -import com.sonic.controller.models.http.StepSort; -import com.sonic.controller.services.PublicStepsService; -import com.sonic.controller.services.StepsService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.cache.Cache; -import org.springframework.cache.CacheManager; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.Pageable; -import org.springframework.stereotype.Service; - -import java.util.List; - -/** - * @author ZhouYiXun - * @des 测试步骤实现 - * @date 2021/8/20 17:51 - */ -@Service -public class StepsServiceImpl implements StepsService { - @Autowired - private StepsRepository stepsRepository; - @Autowired - private PublicStepsService publicStepsService; - - @Override - public List findByCaseIdOrderBySort(int caseId) { - return stepsRepository.findByCaseIdOrderBySort(caseId); - } - - @Override - public boolean resetCaseId(int id) { - if (stepsRepository.existsById(id)) { - Steps steps = stepsRepository.findById(id).get(); - steps.setCaseId(0); - stepsRepository.save(steps); - return true; - } else { - return false; - } - } - - @Override - public boolean delete(int id) { - if (stepsRepository.existsById(id)) { - Steps steps = stepsRepository.findById(id).get(); - for (PublicSteps publicSteps : steps.getPublicSteps()) { - publicSteps.getSteps().remove(steps); - publicStepsService.save(publicSteps); - } - stepsRepository.deleteById(id); - return true; - } else { - return false; - } - } - - @Override - public void save(Steps steps) { - if (steps.getStepType().equals("publicStep")) { - PublicSteps publicSteps = publicStepsService.findById(Integer.parseInt(steps.getText())); - if (publicSteps != null) { - steps.setContent(publicSteps.getName()); - } else { - steps.setContent("未知"); - } - } - if (!stepsRepository.existsById(steps.getId())) { - steps.setSort(stepsRepository.findMaxSort() + 1); - } - stepsRepository.save(steps); - } - - @Override - public Steps findById(int id) { - if (stepsRepository.existsById(id)) { - return stepsRepository.findById(id).get(); - } else { - return null; - } - } - - @Override - public void sortSteps(StepSort stepSort) { - List stepsList = - stepsRepository.findByCaseIdAndSortLessThanEqualAndSortGreaterThanEqualOrderBySort( - stepSort.getCaseId(), stepSort.getStartId(), stepSort.getEndId()); - if (stepSort.getDirection().equals("down")) { - for (int i = 0; i < stepsList.size() - 1; i++) { - int temp = stepsList.get(stepsList.size() - 1).getSort(); - stepsList.get(stepsList.size() - 1).setSort(stepsList.get(i).getSort()); - stepsList.get(i).setSort(temp); - } - } else { - for (int i = 0; i < stepsList.size() - 1; i++) { - int temp = stepsList.get(0).getSort(); - stepsList.get(0).setSort(stepsList.get(stepsList.size() - 1 - i).getSort()); - stepsList.get(stepsList.size() - 1 - i).setSort(temp); - } - } - stepsRepository.saveAll(stepsList); - } - - @Override - public Page findByProjectIdAndPlatform(int projectId, int platform, Pageable pageable) { - return stepsRepository.findByProjectIdAndPlatform(projectId, platform - , pageable); - } -} diff --git a/sonic-server-controller/src/main/java/com/sonic/controller/services/impl/TestCasesServiceImpl.java b/sonic-server-controller/src/main/java/com/sonic/controller/services/impl/TestCasesServiceImpl.java deleted file mode 100644 index 901d45b8..00000000 --- a/sonic-server-controller/src/main/java/com/sonic/controller/services/impl/TestCasesServiceImpl.java +++ /dev/null @@ -1,164 +0,0 @@ -package com.sonic.controller.services.impl; - -import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.JSONObject; -import com.sonic.controller.dao.GlobalParamsRepository; -import com.sonic.controller.dao.TestCasesRepository; -import com.sonic.controller.models.*; -import com.sonic.controller.services.PublicStepsService; -import com.sonic.controller.services.StepsService; -import com.sonic.controller.services.TestCasesService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.Pageable; -import org.springframework.data.jpa.domain.Specification; -import org.springframework.stereotype.Service; - -import javax.persistence.criteria.Predicate; -import java.util.*; - -/** - * @author ZhouYiXun - * @des 测试用例逻辑实现 - * @date 2021/8/20 17:51 - */ -@Service -public class TestCasesServiceImpl implements TestCasesService { - @Autowired - private TestCasesRepository testCasesRepository; - @Autowired - private StepsService stepsService; - @Autowired - private PublicStepsService publicStepsService; - @Autowired - private GlobalParamsRepository globalParamsRepository; - - @Override - public Page findAll(int projectId, int platform, String name, Pageable pageable) { - Specification spc = (root, query, cb) -> { - List predicateList = new ArrayList<>(); - if (projectId != 0) { - predicateList.add(cb.and(cb.equal(root.get("projectId"), projectId))); - } - if (platform != 0) { - predicateList.add(cb.and(cb.equal(root.get("platform"), platform))); - } - if (name != null && name.length() > 0) { - predicateList.add(cb.and(cb.like(root.get("name"), "%" + name + "%"))); - } - //默认按照最后更新时间倒序 - query.orderBy(cb.desc(root.get("editTime"))); - if (predicateList.size() != 0) { - Predicate[] p = new Predicate[predicateList.size()]; - return query.where(predicateList.toArray(p)).getRestriction(); - } else { - return query.getRestriction(); - } - }; - return testCasesRepository.findAll(spc, pageable); - } - - @Override - public List findAll(int projectId, int platform) { - return testCasesRepository.findByProjectIdAndPlatformOrderByEditTimeDesc(projectId, platform); - } - - @Override - public boolean delete(int id) { - if (testCasesRepository.existsById(id)) { - TestCases testCases = testCasesRepository.findById(id).get(); - List testSuitesSet = testCases.getTestSuites(); - for (TestSuites testSuites : testSuitesSet) { - testSuites.getTestCases().remove(testCases); - } - List stepsList = stepsService.findByCaseIdOrderBySort(id); - for (Steps steps : stepsList) { - steps.setCaseId(0); - stepsService.save(steps); - } - testCasesRepository.deleteById(id); - return true; - } else { - return false; - } - } - - @Override - public void save(TestCases testCases) { - testCasesRepository.save(testCases); - } - - @Override - public TestCases findById(int id) { - if (testCasesRepository.existsById(id)) { - return testCasesRepository.findById(id).get(); - } else { - return null; - } - } - - @Override - public JSONObject findSteps(int id) { - if (testCasesRepository.existsById(id)) { - TestCases runStepCase = testCasesRepository.findById(id).get(); - JSONObject jsonDebug = new JSONObject(); - jsonDebug.put("pf", runStepCase.getPlatform()); - JSONArray array = new JSONArray(); - List stepsList = stepsService.findByCaseIdOrderBySort(id); - for (Steps steps : stepsList) { - array.add(getStep(steps)); - } - jsonDebug.put("steps", array); - List globalParamsList = globalParamsRepository.findByProjectId(runStepCase.getProjectId()); - JSONObject gp = new JSONObject(); - Map> valueMap = new HashMap<>(); - for (GlobalParams g : globalParamsList) { - if (g.getParamsValue().contains("|")) { - List shuffle = Arrays.asList(g.getParamsValue().split("|")); - Collections.shuffle(shuffle); - valueMap.put(g.getParamsKey(), shuffle); - } else { - gp.put(g.getParamsKey(), g.getParamsValue()); - } - } - for (String k : valueMap.keySet()) { - if (valueMap.get(k).size() > 0) { - String v = valueMap.get(k).get(0); - gp.put(k, v); - } - } - jsonDebug.put("gp", gp); - return jsonDebug; - } else { - return null; - } - } - - @Override - public List findByIdIn(List ids) { - return testCasesRepository.findByIdIn(ids); - } - - /** - * @param steps - * @return com.alibaba.fastjson.JSONObject - * @author ZhouYiXun - * @des 递归获取步骤 - * @date 2021/8/20 17:50 - */ - private JSONObject getStep(Steps steps) { - JSONObject step = new JSONObject(); - if (steps.getStepType().equals("publicStep")) { - PublicSteps publicSteps = publicStepsService.findById(Integer.parseInt(steps.getText())); - if (publicSteps != null) { - JSONArray publicStepsJson = new JSONArray(); - for (Steps pubStep : publicSteps.getSteps()) { - publicStepsJson.add(getStep(pubStep)); - } - step.put("pubSteps", publicStepsJson); - } - } - step.put("step", steps); - return step; - } -} diff --git a/sonic-server-controller/src/main/java/com/sonic/controller/services/impl/TestSuitesServiceImpl.java b/sonic-server-controller/src/main/java/com/sonic/controller/services/impl/TestSuitesServiceImpl.java deleted file mode 100644 index 236c46ea..00000000 --- a/sonic-server-controller/src/main/java/com/sonic/controller/services/impl/TestSuitesServiceImpl.java +++ /dev/null @@ -1,350 +0,0 @@ -package com.sonic.controller.services.impl; - -import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.JSONObject; -import com.sonic.common.http.RespEnum; -import com.sonic.common.http.RespModel; -import com.sonic.controller.dao.AgentsRepository; -import com.sonic.controller.dao.GlobalParamsRepository; -import com.sonic.controller.dao.TestSuitesRepository; -import com.sonic.controller.feign.TransportFeignClient; -import com.sonic.controller.models.*; -import com.sonic.controller.models.interfaces.AgentStatus; -import com.sonic.controller.models.interfaces.CoverType; -import com.sonic.controller.models.interfaces.DeviceStatus; -import com.sonic.controller.models.interfaces.ResultStatus; -import com.sonic.controller.services.*; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.Pageable; -import org.springframework.data.domain.Sort; -import org.springframework.data.jpa.domain.Specification; -import org.springframework.stereotype.Service; -import org.springframework.util.ObjectUtils; - -import javax.persistence.criteria.Predicate; -import java.util.*; - -/** - * @author ZhouYiXun - * @des 测试套件逻辑实现 - * @date 2021/8/20 17:51 - */ -@Service -public class TestSuitesServiceImpl implements TestSuitesService { - @Autowired - private TestSuitesRepository testSuitesRepository; - @Autowired - private StepsService stepsService; - @Autowired - private PublicStepsService publicStepsService; - @Autowired - private ResultsService resultsService; - @Autowired - private AgentsService agentsService; - @Autowired - private GlobalParamsRepository globalParamsRepository; - @Autowired - private TransportFeignClient transportFeignClient; - - @Override - public RespModel runSuite(int suiteId, String strike) { - TestSuites testSuites; - if (testSuitesRepository.existsById(suiteId)) { - testSuites = testSuitesRepository.findById(suiteId).get(); - } else { - return new RespModel(3001, "测试套件已删除!"); - } - Set testCasesSet = new HashSet<>(testSuites.getTestCases()); - testSuites.setTestCases(new ArrayList<>(testCasesSet)); - if (testSuites.getTestCases().size() == 0) { - return new RespModel(3002, "该测试套件内无测试用例!"); - } - List devicesList = new ArrayList<>(testSuites.getDevices()); - for (int i = devicesList.size() - 1; i >= 0; i--) { - if (devicesList.get(i).getStatus().equals(DeviceStatus.OFFLINE) || devicesList.get(i).getStatus().equals(DeviceStatus.DISCONNECTED)) { - devicesList.remove(devicesList.get(i)); - } - } - if (devicesList.size() == 0) { - return new RespModel(3003, "所选设备暂无可用!"); - } - Results results = new Results(); - results.setStatus(ResultStatus.RUNNING); - results.setSuiteId(suiteId); - results.setSuiteName(testSuites.getName()); - results.setStrike(strike); - if (testSuites.getCover() == CoverType.CASE) { - results.setSendMsgCount(testSuites.getTestCases().size()); - } - if (testSuites.getCover() == CoverType.DEVICE) { - results.setSendMsgCount(testSuites.getTestCases().size() * testSuites.getDevices().size()); - } - results.setReceiveMsgCount(0); - results.setProjectId(testSuites.getProjectId()); - resultsService.save(results); - //组装全局参数为json对象 - List globalParamsList = globalParamsRepository.findByProjectId(testSuites.getProjectId()); - //将包含|的拆开多个参数并打乱,去掉json对象多参数的字段 - Map> valueMap = new HashMap<>(); - JSONObject gp = new JSONObject(); - for (GlobalParams g : globalParamsList) { - if (g.getParamsValue().contains("|")) { - List shuffle = Arrays.asList(g.getParamsValue().split("|")); - Collections.shuffle(shuffle); - valueMap.put(g.getParamsKey(), shuffle); - } else { - gp.put(g.getParamsKey(), g.getParamsValue()); - } - } - int deviceIndex = 0; - if (testSuites.getCover() == CoverType.CASE) { - List suiteDetail = new ArrayList<>(); - Set agentIds = new HashSet<>(); - for (TestCases testCases : testSuites.getTestCases()) { - JSONObject suite = new JSONObject(); - List steps = new ArrayList<>(); - List stepsList = stepsService.findByCaseIdOrderBySort(testCases.getId()); - for (Steps s : stepsList) { - steps.add(getStep(s)); - } - suite.put("steps", steps); - suite.put("cid", testCases.getId()); - Devices devices = devicesList.get(deviceIndex); - suite.put("device", Arrays.asList(devices)); - if (deviceIndex == devicesList.size() - 1) { - deviceIndex = 0; - } else { - deviceIndex++; - } - //如果该字段的多参数数组还有,放入对象。否则去掉字段 - for (String k : valueMap.keySet()) { - if (valueMap.get(k).size() > 0) { - String v = valueMap.get(k).get(0); - gp.put(k, v); - valueMap.get(k).remove(0); - } else { - valueMap.remove(k); - } - } - suite.put("gp", gp); - suite.put("rid", results.getId()); - agentIds.add(devices.getAgentId()); - suiteDetail.add(suite); - } - JSONObject result = new JSONObject(); - result.put("cases", suiteDetail); - for (Integer id : agentIds) { - result.put("id", id); - result.put("pf",testSuites.getPlatform()); - result.put("msg", "suite"); - transportFeignClient.sendTestData(result); - } -// RespModel testDataResp = transportFeignClient.sendTestData(suite); -// if (testDataResp.getCode() != 2000) { -// resultsService.subResultCount(results.getId()); -// } - } - if (testSuites.getCover() == CoverType.DEVICE) { - List suiteDetail = new ArrayList<>(); - Set agentIds = new HashSet<>(); - for (TestCases testCases : testSuites.getTestCases()) { - JSONObject suite = new JSONObject(); - List steps = new ArrayList<>(); - List stepsList = stepsService.findByCaseIdOrderBySort(testCases.getId()); - for (Steps s : stepsList) { - steps.add(getStep(s)); - } - for (Devices devices : devicesList) { - agentIds.add(devices.getAgentId()); - } - suite.put("steps", steps); - suite.put("cid", testCases.getId()); - suite.put("device", devicesList); - //如果该字段的多参数数组还有,放入对象。否则去掉字段 - for (String k : valueMap.keySet()) { - if (valueMap.get(k).size() > 0) { - String v = valueMap.get(k).get(0); - gp.put(k, v); - valueMap.get(k).remove(0); - } else { - valueMap.remove(k); - } - } - suite.put("gp", gp); - suite.put("rid", results.getId()); - suiteDetail.add(suite); - } - JSONObject result = new JSONObject(); - result.put("cases", suiteDetail); - for (Integer id : agentIds) { - result.put("id", id); - result.put("pf",testSuites.getPlatform()); - result.put("msg", "suite"); - transportFeignClient.sendTestData(result); - } - } - return new RespModel(RespEnum.HANDLE_OK); - } - - @Override - public TestSuites findById(int id) { - if (testSuitesRepository.existsById(id)) { - TestSuites testSuites = testSuitesRepository.findById(id).get(); - Set testCasesSet = new HashSet<>(testSuites.getTestCases()); - testSuites.setTestCases(new ArrayList<>(testCasesSet)); - return testSuites; - } else { - return null; - } - } - - /** - * @param steps - * @return com.alibaba.fastjson.JSONObject - * @author ZhouYiXun - * @des 递归获取步骤 - * @date 2021/8/20 17:50 - */ - private JSONObject getStep(Steps steps) { - JSONObject step = new JSONObject(); - if (steps.getStepType().equals("publicStep")) { - PublicSteps publicSteps = publicStepsService.findById(Integer.parseInt(steps.getText())); - if (publicSteps != null) { - JSONArray publicStepsJson = new JSONArray(); - for (Steps pubStep : publicSteps.getSteps()) { - publicStepsJson.add(getStep(pubStep)); - } - step.put("pubSteps", publicStepsJson); - } - } - step.put("step", steps); - return step; - } - - @Override - public boolean delete(int id) { - if (testSuitesRepository.existsById(id)) { - testSuitesRepository.deleteById(id); - return true; - } else { - return false; - } - } - - @Override - public RespModel forceStopSuite(int resultId, String strike) { - Results results = resultsService.findById(resultId); - if (ObjectUtils.isEmpty(results)) { - return new RespModel<>(3001, "测试结果模板不存在!"); - } - int suiteId = results.getSuiteId(); - - TestSuites testSuites; - if (testSuitesRepository.existsById(suiteId)) { - testSuites = testSuitesRepository.findById(suiteId).get(); - } else { - return new RespModel<>(3001, "测试套件已删除!"); - } - Set testCasesSet = new HashSet<>(testSuites.getTestCases()); - testSuites.setTestCases(new ArrayList<>(testCasesSet)); - if (testSuites.getTestCases().size() == 0) { - return new RespModel<>(3002, "该测试套件内无测试用例!"); - } - List devicesList = new ArrayList<>(testSuites.getDevices()); - - results.setStatus(ResultStatus.FAIL); - results.setStrike(strike); - if (testSuites.getCover() == CoverType.CASE) { - results.setSendMsgCount(testSuites.getTestCases().size()); - } - if (testSuites.getCover() == CoverType.DEVICE) { - results.setSendMsgCount(testSuites.getTestCases().size() * testSuites.getDevices().size()); - } - results.setProjectId(testSuites.getProjectId()); - resultsService.save(results); - - - int deviceIndex = 0; - if (testSuites.getCover() == CoverType.CASE) { - List suiteDetail = new ArrayList<>(); - Set agentIds = new HashSet<>(); - for (TestCases testCases : testSuites.getTestCases()) { - JSONObject suite = new JSONObject(); - suite.put("cid", testCases.getId()); - Devices devices = devicesList.get(deviceIndex); - suite.put("device", Arrays.asList(devices)); - if (deviceIndex == devicesList.size() - 1) { - deviceIndex = 0; - } else { - deviceIndex++; - } - suite.put("rid", results.getId()); - agentIds.add(devices.getAgentId()); - suiteDetail.add(suite); - } - JSONObject result = new JSONObject(); - result.put("msg", "forceStopSuite"); - result.put("pf",testSuites.getPlatform()); - result.put("cases", suiteDetail); - for (Integer id : agentIds) { - result.put("id", id); - transportFeignClient.sendTestData(result); - } - } - if (testSuites.getCover() == CoverType.DEVICE) { - List suiteDetail = new ArrayList<>(); - Set agentIds = new HashSet<>(); - for (TestCases testCases : testSuites.getTestCases()) { - JSONObject suite = new JSONObject(); - for (Devices devices : devicesList) { - agentIds.add(devices.getAgentId()); - } - suite.put("cid", testCases.getId()); - suite.put("device", devicesList); - suite.put("rid", results.getId()); - suiteDetail.add(suite); - } - JSONObject result = new JSONObject(); - result.put("msg", "forceStopSuite"); - result.put("pf",testSuites.getPlatform()); - result.put("cases", suiteDetail); - for (Integer id : agentIds) { - result.put("id", id); - transportFeignClient.sendTestData(result); - } - } - return new RespModel(RespEnum.HANDLE_OK); - } - - @Override - public void save(TestSuites testSuites) { - testSuitesRepository.save(testSuites); - } - - @Override - public Page findByProjectId(int projectId, String name, Pageable pageable) { - Specification spc = (root, query, cb) -> { - List predicateList = new ArrayList<>(); - if (projectId != 0) { - predicateList.add(cb.and(cb.equal(root.get("projectId"), projectId))); - } - if (name != null && name.length() > 0) { - predicateList.add(cb.and(cb.like(root.get("name"), "%" + name + "%"))); - } - query.orderBy(cb.desc(root.get("id"))); - if (predicateList.size() != 0) { - Predicate[] p = new Predicate[predicateList.size()]; - return query.where(predicateList.toArray(p)).getRestriction(); - } else { - return query.getRestriction(); - } - }; - return testSuitesRepository.findAll(spc, pageable); - } - - @Override - public List findByProjectId(int projectId) { - return testSuitesRepository.findByProjectId(projectId, Sort.by(Sort.Direction.DESC, "id")); - } -} \ No newline at end of file diff --git a/sonic-server-controller/src/main/java/com/sonic/controller/services/impl/VersionsServiceImpl.java b/sonic-server-controller/src/main/java/com/sonic/controller/services/impl/VersionsServiceImpl.java deleted file mode 100644 index 1cf972cf..00000000 --- a/sonic-server-controller/src/main/java/com/sonic/controller/services/impl/VersionsServiceImpl.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.sonic.controller.services.impl; - -import com.sonic.controller.dao.VersionsRepository; -import com.sonic.controller.models.Versions; -import com.sonic.controller.services.VersionsService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.domain.Sort; -import org.springframework.stereotype.Service; - -import java.util.List; - -/** - * @author ZhouYiXun - * @des 迭代逻辑层实现 - * @date 2021/8/16 22:56 - */ -@Service -public class VersionsServiceImpl implements VersionsService { - @Autowired - private VersionsRepository versionsRepository; - - @Override - public void save(Versions versions) { - versionsRepository.save(versions); - } - - @Override - public boolean delete(int id) { - if (versionsRepository.existsById(id)) { - versionsRepository.deleteById(id); - return true; - } else { - return false; - } - } - - @Override - public List findByProjectId(int projectId) { - Sort s = Sort.by(Sort.Direction.DESC, "createTime"); - return versionsRepository.findByProjectId(projectId, s); - } - - @Override - public Versions findById(int id) { - if (versionsRepository.existsById(id)) { - return versionsRepository.findById(id).get(); - } else { - return null; - } - } -} diff --git a/sonic-server-controller/src/main/java/com/sonic/controller/ControllerApplication.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/ControllerApplication.java similarity index 53% rename from sonic-server-controller/src/main/java/com/sonic/controller/ControllerApplication.java rename to sonic-server-controller/src/main/java/org/cloud/sonic/controller/ControllerApplication.java index 46f2e6a9..b161762a 100644 --- a/sonic-server-controller/src/main/java/com/sonic/controller/ControllerApplication.java +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/ControllerApplication.java @@ -1,22 +1,31 @@ -package com.sonic.controller; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.cloud.netflix.eureka.EnableEurekaClient; -import org.springframework.cloud.openfeign.EnableFeignClients; -import org.springframework.data.jpa.repository.config.EnableJpaAuditing; - -/** - * @author ZhouYiXun - * @des 控制中心启动类 - * @date 2021/8/15 19:56 - */ -@SpringBootApplication(scanBasePackages = {"com/sonic/controller", "com/sonic/common"}) -@EnableJpaAuditing -@EnableFeignClients -@EnableEurekaClient -public class ControllerApplication { - public static void main(String[] args) { - SpringApplication.run(ControllerApplication.class, args); - } -} +package org.cloud.sonic.controller; + +import org.mybatis.spring.annotation.MapperScan; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.netflix.eureka.EnableEurekaClient; +import org.springframework.cloud.openfeign.EnableFeignClients; +import org.springframework.context.annotation.ComponentScan; + +/** + * @author ZhouYiXun + * @des 控制中心启动类 + * @date 2021/8/15 19:56 + */ +@SpringBootApplication +@MapperScan(basePackages = { + "org.cloud.sonic.controller.mapper", + "com.gitee.sunchenbin.mybatis.actable.dao.*" +}) +@ComponentScan(basePackages = { + "org.cloud.sonic.controller.*", + "com.gitee.sunchenbin.mybatis.actable.manager.*", + "org.cloud.sonic.common.*" +}) +@EnableFeignClients +@EnableEurekaClient +public class ControllerApplication { + public static void main(String[] args) { + SpringApplication.run(ControllerApplication.class, args); + } +} diff --git a/sonic-server-controller/src/main/java/com/sonic/controller/config/RestTempConfig.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/config/RestTempConfig.java similarity index 92% rename from sonic-server-controller/src/main/java/com/sonic/controller/config/RestTempConfig.java rename to sonic-server-controller/src/main/java/org/cloud/sonic/controller/config/RestTempConfig.java index 1751389f..66bddcc9 100644 --- a/sonic-server-controller/src/main/java/com/sonic/controller/config/RestTempConfig.java +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/config/RestTempConfig.java @@ -1,29 +1,29 @@ -package com.sonic.controller.config; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.http.client.ClientHttpRequestFactory; -import org.springframework.http.client.SimpleClientHttpRequestFactory; -import org.springframework.web.client.RestTemplate; - -/** - * @author ZhouYiXun - * @des 远程调接口的rest配置 - * @date 2021/8/14 19:16 - */ -@Configuration -public class RestTempConfig { - - @Bean - public RestTemplate restTemplate(ClientHttpRequestFactory factory) { - return new RestTemplate(factory); - } - - @Bean - public ClientHttpRequestFactory simpleClientHttpRequestFactory() { - SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory(); - factory.setReadTimeout(5000); - factory.setConnectTimeout(5000); - return factory; - } +package org.cloud.sonic.controller.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.http.client.ClientHttpRequestFactory; +import org.springframework.http.client.SimpleClientHttpRequestFactory; +import org.springframework.web.client.RestTemplate; + +/** + * @author ZhouYiXun + * @des 远程调接口的rest配置 + * @date 2021/8/14 19:16 + */ +@Configuration +public class RestTempConfig { + + @Bean + public RestTemplate restTemplate(ClientHttpRequestFactory factory) { + return new RestTemplate(factory); + } + + @Bean + public ClientHttpRequestFactory simpleClientHttpRequestFactory() { + SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory(); + factory.setReadTimeout(5000); + factory.setConnectTimeout(5000); + return factory; + } } \ No newline at end of file diff --git a/sonic-server-controller/src/main/java/org/cloud/sonic/controller/config/mybatis/ClearForeignKey.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/config/mybatis/ClearForeignKey.java new file mode 100644 index 00000000..0b57e41d --- /dev/null +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/config/mybatis/ClearForeignKey.java @@ -0,0 +1,72 @@ +package org.cloud.sonic.controller.config.mybatis; + +import lombok.extern.slf4j.Slf4j; +import org.springframework.boot.autoconfigure.jdbc.DataSourceSchemaCreatedEvent; +import org.springframework.context.ApplicationListener; +import org.springframework.stereotype.Component; + +import javax.sql.DataSource; +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.List; + +/** + * 清除历史遗留的外键 + * @author JayWenStar, Eason + * @date 2021/12/26 1:39 上午 + */ +@Component +@Slf4j +public class ClearForeignKey implements ApplicationListener { + + @Override + public void onApplicationEvent(DataSourceSchemaCreatedEvent event) { + DataSource dataSource = (DataSource) event.getSource(); + String dataBase = ""; + String findFKSql = "SELECT CONCAT('ALTER TABLE ', TABLE_NAME,' DROP FOREIGN KEY ',CONSTRAINT_NAME) as ddl " + + "FROM information_schema.TABLE_CONSTRAINTS c " + + "WHERE c.TABLE_SCHEMA='%s' AND c.CONSTRAINT_TYPE='FOREIGN KEY'"; + //兼容v1.3.0-beta1及以下版本className更改 + String transSql1 = "UPDATE QRTZ_JOB_DETAILS set JOB_CLASS_NAME='org.cloud.sonic.task.quartz.QuartzJob'"; + List deleteSqlList = new ArrayList<>(); + try (Connection connection = dataSource.getConnection()) { + try (Statement statement = connection.createStatement()) { + + // 获取当前数据库名 + ResultSet resultSet1 = statement.executeQuery("select DATABASE() db"); + if (resultSet1.next()) { + dataBase = resultSet1.getString("db"); + } + + // 查询所有外键索引,并拼装成删除sql + ResultSet resultSet2 = statement.executeQuery(String.format(findFKSql, dataBase)); + while (resultSet2.next()) { + deleteSqlList.add(resultSet2.getString("ddl")); + } + + // 版本兼容sql + Boolean resultSet3 = statement.execute(String.format(transSql1, dataBase)); + if (!resultSet3) { + log.info(String.format("迁移数据sql执行失败,%s", transSql1)); + } + + // 执行删除外键sql + for (String deleteSql : deleteSqlList) { + statement.executeUpdate(deleteSql); + } + + // 删除 test_suites_devices 表的主键 + try { + statement.executeUpdate("Alter table test_suites_devices Drop primary key"); + } catch (Exception e) { + // 无视错误 + } + } + } catch (Exception e) { + log.error("删除数据库外键失败"); + e.printStackTrace(); + } + } +} diff --git a/sonic-server-controller/src/main/java/org/cloud/sonic/controller/config/mybatis/MyBatisPlusConfig.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/config/mybatis/MyBatisPlusConfig.java new file mode 100644 index 00000000..458886c5 --- /dev/null +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/config/mybatis/MyBatisPlusConfig.java @@ -0,0 +1,26 @@ +package org.cloud.sonic.controller.config.mybatis; + +import com.baomidou.mybatisplus.annotation.DbType; +import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor; +import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.transaction.annotation.EnableTransactionManagement; + +/** + * mybatis-plus 分页插件 + * 参考:https://baomidou.com/pages/8f40ae/ + * + * @author JayWenStar + */ +@Configuration +@EnableTransactionManagement +public class MyBatisPlusConfig { + + @Bean + public MybatisPlusInterceptor mybatisPlusInterceptor() { + MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor(); + interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL)); + return interceptor; + } +} diff --git a/sonic-server-controller/src/main/java/org/cloud/sonic/controller/config/mybatis/MyMetaObjectHandler.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/config/mybatis/MyMetaObjectHandler.java new file mode 100644 index 00000000..60f70c58 --- /dev/null +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/config/mybatis/MyMetaObjectHandler.java @@ -0,0 +1,36 @@ +package org.cloud.sonic.controller.config.mybatis; + +import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler; +import lombok.extern.slf4j.Slf4j; +import org.apache.ibatis.reflection.MetaObject; +import org.springframework.stereotype.Component; + +import java.util.Date; + +/** + * 自动填充 + * 参考:https://baomidou.com/pages/4c6bcf/ + * 后面在统一时间字段的规范 + * + * @author JayWenStar + */ +@Slf4j +@Component +public class MyMetaObjectHandler implements MetaObjectHandler { + + @Override + public void insertFill(MetaObject metaObject) { + log.debug("start insert fill ...."); + this.strictInsertFill(metaObject, "createTime", Date.class, new Date()); + this.strictInsertFill(metaObject, "updateTime", Date.class, new Date()); + this.strictInsertFill(metaObject, "time", Date.class, new Date()); + this.strictInsertFill(metaObject, "editTime", Date.class, new Date()); + } + + @Override + public void updateFill(MetaObject metaObject) { + log.debug("start update fill ...."); + this.strictUpdateFill(metaObject, "updateTime", Date.class, new Date()); + this.strictUpdateFill(metaObject, "editTime", Date.class, new Date()); + } +} \ No newline at end of file diff --git a/sonic-server-controller/src/main/java/org/cloud/sonic/controller/controller/AgentsController.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/controller/AgentsController.java new file mode 100644 index 00000000..56933a53 --- /dev/null +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/controller/AgentsController.java @@ -0,0 +1,92 @@ +package org.cloud.sonic.controller.controller; + +import com.alibaba.fastjson.JSONObject; +import org.cloud.sonic.common.config.WebAspect; +import org.cloud.sonic.common.http.RespEnum; +import org.cloud.sonic.common.http.RespModel; +import org.cloud.sonic.controller.models.base.TypeConverter; +import org.cloud.sonic.controller.models.domain.Agents; +import org.cloud.sonic.controller.models.dto.AgentsDTO; +import org.cloud.sonic.controller.services.AgentsService; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import java.util.List; +import java.util.stream.Collectors; + +/** + * @author ZhouYiXun + * @des + * @date 2021/8/28 21:49 + */ +@Api(tags = "Agent端相关") +@RestController +@RequestMapping("/agents") +public class AgentsController { + + @Autowired + private AgentsService agentsService; + + @WebAspect + @ApiOperation(value = "查询所有Agent端", notes = "获取所有Agent端以及详细信息") + @GetMapping("/list") + public RespModel> findAgents() { + return new RespModel<>( + RespEnum.SEARCH_OK, + agentsService.findAgents().stream().map(TypeConverter::convertTo).collect(Collectors.toList()) + ); + } + + @WebAspect + @PutMapping + public RespModel save(@RequestBody JSONObject jsonObject) { + agentsService.saveAgents(jsonObject); + return new RespModel<>(RespEnum.HANDLE_OK); + } + + @WebAspect + @PutMapping("/updateName") + public RespModel updateName(@RequestBody JSONObject jsonObject) { + agentsService.updateName(jsonObject.getInteger("id"), jsonObject.getString("name")); + return new RespModel<>(RespEnum.HANDLE_OK); + } + + @WebAspect + @GetMapping("/offLine") + public RespModel offLine(@RequestParam(name = "id") int id) { + agentsService.offLine(id); + return new RespModel<>(RespEnum.HANDLE_OK); + } + + @WebAspect + @GetMapping("/auth") + public RespModel auth(@RequestParam(name = "key") String key) { + return new RespModel<>(RespEnum.SEARCH_OK, agentsService.auth(key)); + } + + @WebAspect + @GetMapping("/findKeyById") + public RespModel findKeyById(@RequestParam(name = "id") int id) { + String key = agentsService.findKeyById(id); + if (key != null) { + return new RespModel<>(RespEnum.SEARCH_OK, key); + } else { + return new RespModel<>(RespEnum.ID_NOT_FOUND); + } + } + + @WebAspect + @ApiOperation(value = "查询Agent端信息", notes = "获取对应id的Agent信息") + @GetMapping + public RespModel findOne(@RequestParam(name = "id") int id) { + Agents agents = agentsService.findById(id); + if (agents != null) { + return new RespModel<>(RespEnum.SEARCH_OK, agents); + } else { + return new RespModel<>(RespEnum.ID_NOT_FOUND); + } + } + +} diff --git a/sonic-server-controller/src/main/java/com/sonic/controller/controller/DevicesController.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/controller/DevicesController.java similarity index 58% rename from sonic-server-controller/src/main/java/com/sonic/controller/controller/DevicesController.java rename to sonic-server-controller/src/main/java/org/cloud/sonic/controller/controller/DevicesController.java index 0ac803ff..dbf2d742 100644 --- a/sonic-server-controller/src/main/java/com/sonic/controller/controller/DevicesController.java +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/controller/DevicesController.java @@ -1,155 +1,159 @@ -package com.sonic.controller.controller; - -import com.alibaba.fastjson.JSONObject; -import com.sonic.common.config.WebAspect; -import com.sonic.common.http.RespEnum; -import com.sonic.common.http.RespModel; -import com.sonic.controller.models.Devices; -import com.sonic.controller.models.http.DeviceDetailChange; -import com.sonic.controller.models.http.UpdateDeviceImg; -import com.sonic.controller.services.DevicesService; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiImplicitParam; -import io.swagger.annotations.ApiImplicitParams; -import io.swagger.annotations.ApiOperation; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.PageRequest; -import org.springframework.data.domain.Pageable; -import org.springframework.validation.annotation.Validated; -import org.springframework.web.bind.annotation.*; - -import java.util.List; - -@Api(tags = "设备管理相关") -@RestController -@RequestMapping("/devices") -public class DevicesController { - @Autowired - private DevicesService devicesService; - - @WebAspect - @ApiOperation(value = "修改设备安装密码", notes = "修改对应设备id的安装密码") - @PutMapping("/saveDetail") - public RespModel saveDetail(@Validated @RequestBody DeviceDetailChange deviceDetailChange) { - if (devicesService.saveDetail(deviceDetailChange)) { - return new RespModel(RespEnum.UPDATE_OK); - } else { - return new RespModel(3000, "保存异常!"); - } - } - - @PutMapping("/updateDevicesUser") - public RespModel updateDevicesUser(@RequestBody JSONObject jsonObject) { - devicesService.updateDevicesUser(jsonObject); - return new RespModel(RespEnum.UPDATE_OK); - } - - @PutMapping("/refreshDevicesTemper") - public RespModel refreshDevicesTemper(@RequestBody JSONObject jsonObject) { - devicesService.refreshDevicesTemper(jsonObject); - return new RespModel(RespEnum.UPDATE_OK); - } - - @WebAspect - @ApiOperation(value = "获取温度概况", notes = "获取现有温度概况") - @GetMapping("/findTemper") - public RespModel findTemper() { - return new RespModel(RespEnum.SEARCH_OK, devicesService.findTemper()); - } - - @WebAspect - @ApiOperation(value = "修改设备图片", notes = "修改对应设备id的图片") - @PutMapping("/updateImg") - public RespModel updateImg(@Validated @RequestBody UpdateDeviceImg updateDeviceImg) { - devicesService.updateImg(updateDeviceImg); - return new RespModel(RespEnum.UPDATE_OK); - } - - @WebAspect - @ApiOperation(value = "查询所有设备", notes = "查找筛选条件下的所有设备,带[]的参数可以重复传") - @ApiImplicitParams(value = { - @ApiImplicitParam(name = "androidVersion[]", value = "安卓版本", dataTypeClass = String.class), - @ApiImplicitParam(name = "iOSVersion[]", value = "iOS版本", dataTypeClass = String.class), - @ApiImplicitParam(name = "manufacturer[]", value = "制造商", dataTypeClass = String.class), - @ApiImplicitParam(name = "cpu[]", value = "cpu类型", dataTypeClass = String.class), - @ApiImplicitParam(name = "size[]", value = "屏幕尺寸", dataTypeClass = String.class), - @ApiImplicitParam(name = "agentId[]", value = "所在Agent", dataTypeClass = Integer.class), - @ApiImplicitParam(name = "status[]", value = "当前状态", dataTypeClass = String.class), - @ApiImplicitParam(name = "deviceInfo", value = "设备型号或udId", dataTypeClass = String.class), - @ApiImplicitParam(name = "page", value = "页码", dataTypeClass = Integer.class), - @ApiImplicitParam(name = "pageSize", value = "页数据大小", dataTypeClass = Integer.class) - }) - @GetMapping("/list") - public RespModel> findAll(@RequestParam(name = "androidVersion[]", required = false) List androidVersion, - @RequestParam(name = "iOSVersion[]", required = false) List iOSVersion, - @RequestParam(name = "manufacturer[]", required = false) List manufacturer, - @RequestParam(name = "cpu[]", required = false) List cpu, - @RequestParam(name = "size[]", required = false) List size, - @RequestParam(name = "agentId[]", required = false) List agentId, - @RequestParam(name = "status[]", required = false) List status, - @RequestParam(name = "deviceInfo", required = false) String deviceInfo, - @RequestParam(name = "page") int page, - @RequestParam(name = "pageSize") int pageSize) { - Pageable pageable = PageRequest.of(page - 1, pageSize); - return new RespModel(RespEnum.SEARCH_OK, - devicesService.findAll(iOSVersion, androidVersion, manufacturer, cpu, size, - agentId, status, deviceInfo, pageable)); - } - - @WebAspect - @ApiOperation(value = "查询所有设备", notes = "不分页的设备列表") - @ApiImplicitParam(name = "platform", value = "平台", dataTypeClass = Integer.class) - @GetMapping("/listAll") - public RespModel> listAll(@RequestParam(name = "platform") int platform) { - return new RespModel(RespEnum.SEARCH_OK, - devicesService.findAll(platform)); - } - - @WebAspect - @ApiOperation(value = "批量查询设备", notes = "查找id列表的设备信息,可以传多个ids[]") - @ApiImplicitParam(name = "ids[]", value = "id列表", dataTypeClass = Integer.class) - @GetMapping("/findByIdIn") - public RespModel> findByIdIn(@RequestParam(name = "ids[]") List ids) { - return new RespModel(RespEnum.SEARCH_OK, - devicesService.findByIdIn(ids)); - } - - @WebAspect - @ApiOperation(value = "获取查询条件", notes = "获取现有筛选条件(所有设备有的条件)") - @GetMapping("/getFilterOption") - public RespModel getFilterOption() { - return new RespModel(RespEnum.SEARCH_OK, devicesService.getFilterOption()); - } - -// @WebAspect -// @ApiOperation(value = "查询单个设备信息", notes = "获取单个设备的详细信息") -// @ApiImplicitParam(name = "udId", value = "设备序列号", dataTypeClass = String.class) -// @GetMapping -// public RespModel findByUdId(@RequestParam(name = "udId") String udId) { -// Devices devices = devicesService.findByUdId(udId); -// if (devices != null) { -// return new RespModel(RespEnum.SEARCH_OK, devices); -// } else { -// return new RespModel(3000, "设备不存在!"); -// } -// } - - @WebAspect - @PutMapping("/deviceStatus") - public RespModel deviceStatus(@RequestBody JSONObject jsonObject) { - devicesService.deviceStatus(jsonObject); - return new RespModel(RespEnum.UPDATE_OK); - } - - @WebAspect - @GetMapping - public RespModel findById(@RequestParam(name = "id") int id) { - Devices devices = devicesService.findById(id); - if (devices != null) { - return new RespModel(RespEnum.SEARCH_OK, devices); - } else { - return new RespModel(3000, "设备不存在!"); - } - } -} +package org.cloud.sonic.controller.controller; + +import com.alibaba.fastjson.JSONObject; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import org.cloud.sonic.common.config.WebAspect; +import org.cloud.sonic.common.http.RespEnum; +import org.cloud.sonic.common.http.RespModel; +import org.cloud.sonic.controller.models.base.CommentPage; +import org.cloud.sonic.controller.models.domain.Devices; +import org.cloud.sonic.controller.models.http.DeviceDetailChange; +import org.cloud.sonic.controller.models.http.UpdateDeviceImg; +import org.cloud.sonic.controller.services.DevicesService; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiImplicitParam; +import io.swagger.annotations.ApiImplicitParams; +import io.swagger.annotations.ApiOperation; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +@Api(tags = "设备管理相关") +@RestController +@RequestMapping("/devices") +public class DevicesController { + + @Autowired + private DevicesService devicesService; + + @WebAspect + @ApiOperation(value = "修改设备安装密码", notes = "修改对应设备id的安装密码") + @PutMapping("/saveDetail") + public RespModel saveDetail(@Validated @RequestBody DeviceDetailChange deviceDetailChange) { + if (devicesService.saveDetail(deviceDetailChange)) { + return new RespModel<>(RespEnum.UPDATE_OK); + } else { + return new RespModel<>(3000, "保存异常!"); + } + } + + @PutMapping("/updateDevicesUser") + public RespModel updateDevicesUser(@RequestBody JSONObject jsonObject) { + devicesService.updateDevicesUser(jsonObject); + return new RespModel<>(RespEnum.UPDATE_OK); + } + + @PutMapping("/refreshDevicesTemper") + public RespModel refreshDevicesTemper(@RequestBody JSONObject jsonObject) { + devicesService.refreshDevicesTemper(jsonObject); + return new RespModel<>(RespEnum.UPDATE_OK); + } + + @WebAspect + @ApiOperation(value = "修改设备图片", notes = "修改对应设备id的图片") + @PutMapping("/updateImg") + public RespModel updateImg(@Validated @RequestBody UpdateDeviceImg updateDeviceImg) { + devicesService.updateImg(updateDeviceImg); + return new RespModel<>(RespEnum.UPDATE_OK); + } + + @WebAspect + @ApiOperation(value = "查询所有设备", notes = "查找筛选条件下的所有设备,带[]的参数可以重复传") + @ApiImplicitParams(value = { + @ApiImplicitParam(name = "androidVersion[]", value = "安卓版本", dataTypeClass = String.class), + @ApiImplicitParam(name = "iOSVersion[]", value = "iOS版本", dataTypeClass = String.class), + @ApiImplicitParam(name = "manufacturer[]", value = "制造商", dataTypeClass = String.class), + @ApiImplicitParam(name = "cpu[]", value = "cpu类型", dataTypeClass = String.class), + @ApiImplicitParam(name = "size[]", value = "屏幕尺寸", dataTypeClass = String.class), + @ApiImplicitParam(name = "agentId[]", value = "所在Agent", dataTypeClass = Integer.class), + @ApiImplicitParam(name = "status[]", value = "当前状态", dataTypeClass = String.class), + @ApiImplicitParam(name = "deviceInfo", value = "设备型号或udId", dataTypeClass = String.class), + @ApiImplicitParam(name = "page", value = "页码", dataTypeClass = Integer.class), + @ApiImplicitParam(name = "pageSize", value = "页数据大小", dataTypeClass = Integer.class) + }) + @GetMapping("/list") + public RespModel> findAll(@RequestParam(name = "androidVersion[]", required = false) List androidVersion, + @RequestParam(name = "iOSVersion[]", required = false) List iOSVersion, + @RequestParam(name = "manufacturer[]", required = false) List manufacturer, + @RequestParam(name = "cpu[]", required = false) List cpu, + @RequestParam(name = "size[]", required = false) List size, + @RequestParam(name = "agentId[]", required = false) List agentId, + @RequestParam(name = "status[]", required = false) List status, + @RequestParam(name = "deviceInfo", required = false) String deviceInfo, + @RequestParam(name = "page") int page, + @RequestParam(name = "pageSize") int pageSize) { + Page pageable = new Page<>(page, pageSize); + return new RespModel<>( + RespEnum.SEARCH_OK, + CommentPage.convertFrom( + devicesService.findAll(iOSVersion, androidVersion, manufacturer, cpu, size, + agentId, status, deviceInfo, pageable) + ) + ); + } + + @WebAspect + @ApiOperation(value = "查询所有设备", notes = "不分页的设备列表") + @ApiImplicitParam(name = "platform", value = "平台", dataTypeClass = Integer.class) + @GetMapping("/listAll") + public RespModel> listAll(@RequestParam(name = "platform") int platform) { + return new RespModel<>(RespEnum.SEARCH_OK, + devicesService.findAll(platform)); + } + + @WebAspect + @ApiOperation(value = "批量查询设备", notes = "查找id列表的设备信息,可以传多个ids[]") + @ApiImplicitParam(name = "ids[]", value = "id列表", dataTypeClass = Integer.class) + @GetMapping("/findByIdIn") + public RespModel> findByIdIn(@RequestParam(name = "ids[]") List ids) { + return new RespModel<>(RespEnum.SEARCH_OK, + devicesService.findByIdIn(ids)); + } + + @WebAspect + @ApiOperation(value = "获取查询条件", notes = "获取现有筛选条件(所有设备有的条件)") + @GetMapping("/getFilterOption") + public RespModel getFilterOption() { + return new RespModel<>(RespEnum.SEARCH_OK, devicesService.getFilterOption()); + } + +// @WebAspect +// @ApiOperation(value = "查询单个设备信息", notes = "获取单个设备的详细信息") +// @ApiImplicitParam(name = "udId", value = "设备序列号", dataTypeClass = String.class) +// @GetMapping +// public RespModel findByUdId(@RequestParam(name = "udId") String udId) { +// Devices devices = devicesService.findByUdId(udId); +// if (devices != null) { +// return new RespModel(RespEnum.SEARCH_OK, devices); +// } else { +// return new RespModel(3000, "设备不存在!"); +// } +// } + + @WebAspect + @PutMapping("/deviceStatus") + public RespModel deviceStatus(@RequestBody JSONObject jsonObject) { + devicesService.deviceStatus(jsonObject); + return new RespModel<>(RespEnum.UPDATE_OK); + } + + @WebAspect + @GetMapping + public RespModel findById(@RequestParam(name = "id") int id) { + Devices devices = devicesService.findById(id); + if (devices != null) { + return new RespModel<>(RespEnum.SEARCH_OK, devices); + } else { + return new RespModel<>(3000, "设备不存在!"); + } + } + + @WebAspect + @ApiOperation(value = "获取温度概况", notes = "获取现有温度概况") + @GetMapping("/findTemper") + public RespModel findTemper() { + return new RespModel<>(RespEnum.SEARCH_OK, devicesService.findTemper()); + } +} diff --git a/sonic-server-controller/src/main/java/org/cloud/sonic/controller/controller/ElementsController.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/controller/ElementsController.java new file mode 100644 index 00000000..46b623db --- /dev/null +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/controller/ElementsController.java @@ -0,0 +1,95 @@ +package org.cloud.sonic.controller.controller; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import org.cloud.sonic.common.config.WebAspect; +import org.cloud.sonic.common.http.RespEnum; +import org.cloud.sonic.common.http.RespModel; +import org.cloud.sonic.controller.models.base.CommentPage; +import org.cloud.sonic.controller.models.domain.Elements; +import org.cloud.sonic.controller.models.dto.ElementsDTO; +import org.cloud.sonic.controller.models.dto.StepsDTO; +import org.cloud.sonic.controller.services.ElementsService; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiImplicitParam; +import io.swagger.annotations.ApiImplicitParams; +import io.swagger.annotations.ApiOperation; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +@Api(tags = "控件元素管理相关") +@RestController +@RequestMapping("/elements") +public class ElementsController { + + @Autowired + private ElementsService elementsService; + + @WebAspect + @ApiOperation(value = "查找控件元素列表1", notes = "查找对应项目id的控件元素列表") + @ApiImplicitParams(value = { + @ApiImplicitParam(name = "projectId", value = "项目id", dataTypeClass = Integer.class), + @ApiImplicitParam(name = "eleTypes[]", value = "类型(多个)", dataTypeClass = String.class), + @ApiImplicitParam(name = "name", value = "控件名称", dataTypeClass = String.class), + @ApiImplicitParam(name = "type", value = "类型", dataTypeClass = String.class), + @ApiImplicitParam(name = "page", value = "页码", dataTypeClass = Integer.class), + @ApiImplicitParam(name = "pageSize", value = "页数据大小", dataTypeClass = Integer.class) + }) + @GetMapping("/list") + public RespModel> findAll(@RequestParam(name = "projectId") int projectId, + @RequestParam(name = "type", required = false) String type, + @RequestParam(name = "eleTypes[]", required = false) List eleTypes, + @RequestParam(name = "name", required = false) String name, + @RequestParam(name = "page") int page, + @RequestParam(name = "pageSize") int pageSize) { + Page pageable = new Page<>(page, pageSize); + return new RespModel<>( + RespEnum.SEARCH_OK, + CommentPage.convertFrom( + elementsService.findAll(projectId, type, eleTypes, name, pageable) + ) + ); + } + + @WebAspect + @ApiOperation(value = "查找控件元素详情", notes = "查找对应id的对应控件元素详细信息") + @ApiImplicitParam(name = "id", value = "控件元素id", dataTypeClass = Integer.class) + @GetMapping + public RespModel findById(@RequestParam(name = "id") int id) { + Elements elements = elementsService.findById(id); + if (elements != null) { + return new RespModel<>(RespEnum.SEARCH_OK, elements); + } else { + return new RespModel<>(RespEnum.ID_NOT_FOUND); + } + } + + @WebAspect + @ApiOperation(value = "删除控件元素", notes = "删除对应id的控件元素,当控件元素存在于用例或id不存在时,删除失败") + @ApiImplicitParam(name = "id", value = "元素id", dataTypeClass = Integer.class) + @DeleteMapping + public RespModel delete(@RequestParam(name = "id") int id) { + return elementsService.delete(id); + } + + @WebAspect + @ApiOperation(value = "删除控件元素前检验", notes = "返回引用控件的步骤") + @ApiImplicitParam(name = "id", value = "元素id", dataTypeClass = Integer.class) + @GetMapping("deleteCheck") + public RespModel> deleteCheck(@RequestParam(name = "id") int id) { + return new RespModel<>(RespEnum.SEARCH_OK, elementsService.findAllStepsByElementsId(id)); + } + + @WebAspect + @ApiOperation(value = "更新控件元素", notes = "新增或更新控件元素信息,id为0时新增,否则为更新对应id的信息") + @PutMapping + public RespModel save(@Validated @RequestBody ElementsDTO elementsDTO) { + if (elementsService.save(elementsDTO.convertTo())) { + return new RespModel<>(RespEnum.UPDATE_OK); + } else { + return new RespModel<>(-1, "操作失败!请检查控件元素值是否过长!"); + } + } +} diff --git a/sonic-server-controller/src/main/java/com/sonic/controller/controller/GlobalParamsController.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/controller/GlobalParamsController.java similarity index 63% rename from sonic-server-controller/src/main/java/com/sonic/controller/controller/GlobalParamsController.java rename to sonic-server-controller/src/main/java/org/cloud/sonic/controller/controller/GlobalParamsController.java index 69c9a601..6e6c9ff3 100644 --- a/sonic-server-controller/src/main/java/com/sonic/controller/controller/GlobalParamsController.java +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/controller/GlobalParamsController.java @@ -1,64 +1,66 @@ -package com.sonic.controller.controller; - -import com.sonic.common.config.WebAspect; -import com.sonic.common.http.RespEnum; -import com.sonic.common.http.RespModel; -import com.sonic.controller.models.GlobalParams; -import com.sonic.controller.services.GlobalParamsService; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiImplicitParam; -import io.swagger.annotations.ApiOperation; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.validation.annotation.Validated; -import org.springframework.web.bind.annotation.*; - -import java.util.List; - -@Api(tags = "公共参数相关") -@RestController -@RequestMapping("/globalParams") -public class GlobalParamsController { - @Autowired - private GlobalParamsService globalParamsService; - - @WebAspect - @ApiOperation(value = "更新公共参数", notes = "新增或更新对应的公共参数") - @PutMapping - public RespModel save(@Validated @RequestBody GlobalParams globalParams) { - globalParamsService.save(globalParams); - return new RespModel(RespEnum.UPDATE_OK); - } - - @WebAspect - @ApiOperation(value = "查找公共参数", notes = "查找对应项目id的公共参数列表") - @ApiImplicitParam(name = "projectId", value = "项目id", dataTypeClass = Integer.class) - @GetMapping("/list") - public RespModel> findByProjectId(@RequestParam(name = "projectId") int projectId) { - return new RespModel(RespEnum.SEARCH_OK, globalParamsService.findAll(projectId)); - } - - @WebAspect - @ApiOperation(value = "删除公共参数", notes = "删除对应id的公共参数") - @ApiImplicitParam(name = "id", value = "id", dataTypeClass = Integer.class) - @DeleteMapping - public RespModel delete(@RequestParam(name = "id") int id) { - if (globalParamsService.delete(id)) { - return new RespModel(RespEnum.DELETE_OK); - } else { - return new RespModel(RespEnum.DELETE_ERROR); - } - } - - @WebAspect - @ApiOperation(value = "查看公共参数信息", notes = "查看对应id的公共参数") - @ApiImplicitParam(name = "id", value = "id", dataTypeClass = Integer.class) - @GetMapping - public RespModel findById(@RequestParam(name = "id") int id) { - GlobalParams globalParams = globalParamsService.findById(id); - if (globalParams != null) { - return new RespModel(RespEnum.SEARCH_OK, globalParams); - } else { - return new RespModel(RespEnum.ID_NOT_FOUND); - } - } -} +package org.cloud.sonic.controller.controller; + +import org.cloud.sonic.common.config.WebAspect; +import org.cloud.sonic.common.http.RespEnum; +import org.cloud.sonic.common.http.RespModel; +import org.cloud.sonic.controller.models.domain.GlobalParams; +import org.cloud.sonic.controller.models.dto.GlobalParamsDTO; +import org.cloud.sonic.controller.services.GlobalParamsService; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiImplicitParam; +import io.swagger.annotations.ApiOperation; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +@Api(tags = "公共参数相关") +@RestController +@RequestMapping("/globalParams") +public class GlobalParamsController { + + @Autowired + private GlobalParamsService globalParamsService; + + @WebAspect + @ApiOperation(value = "更新公共参数", notes = "新增或更新对应的公共参数") + @PutMapping + public RespModel save(@Validated @RequestBody GlobalParamsDTO globalParamsDTO) { + globalParamsService.save(globalParamsDTO.convertTo()); + return new RespModel<>(RespEnum.UPDATE_OK); + } + + @WebAspect + @ApiOperation(value = "查找公共参数", notes = "查找对应项目id的公共参数列表") + @ApiImplicitParam(name = "projectId", value = "项目id", dataTypeClass = Integer.class) + @GetMapping("/list") + public RespModel> findByProjectId(@RequestParam(name = "projectId") int projectId) { + return new RespModel<>(RespEnum.SEARCH_OK, globalParamsService.findAll(projectId)); + } + + @WebAspect + @ApiOperation(value = "删除公共参数", notes = "删除对应id的公共参数") + @ApiImplicitParam(name = "id", value = "id", dataTypeClass = Integer.class) + @DeleteMapping + public RespModel delete(@RequestParam(name = "id") int id) { + if (globalParamsService.delete(id)) { + return new RespModel<>(RespEnum.DELETE_OK); + } else { + return new RespModel<>(RespEnum.DELETE_ERROR); + } + } + + @WebAspect + @ApiOperation(value = "查看公共参数信息", notes = "查看对应id的公共参数") + @ApiImplicitParam(name = "id", value = "id", dataTypeClass = Integer.class) + @GetMapping + public RespModel findById(@RequestParam(name = "id") int id) { + GlobalParams globalParams = globalParamsService.findById(id); + if (globalParams != null) { + return new RespModel<>(RespEnum.SEARCH_OK, globalParams); + } else { + return new RespModel<>(RespEnum.ID_NOT_FOUND); + } + } +} diff --git a/sonic-server-controller/src/main/java/com/sonic/controller/controller/ModulesController.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/controller/ModulesController.java similarity index 51% rename from sonic-server-controller/src/main/java/com/sonic/controller/controller/ModulesController.java rename to sonic-server-controller/src/main/java/org/cloud/sonic/controller/controller/ModulesController.java index bbc073f4..db6d889a 100644 --- a/sonic-server-controller/src/main/java/com/sonic/controller/controller/ModulesController.java +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/controller/ModulesController.java @@ -1,64 +1,72 @@ -package com.sonic.controller.controller; - -import com.sonic.common.config.WebAspect; -import com.sonic.common.http.RespEnum; -import com.sonic.common.http.RespModel; -import com.sonic.controller.models.Modules; -import com.sonic.controller.services.ModulesService; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiImplicitParam; -import io.swagger.annotations.ApiOperation; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.validation.annotation.Validated; -import org.springframework.web.bind.annotation.*; - -import java.util.List; - -@Api(tags = "模块管理相关") -@RestController -@RequestMapping("/modules") -public class ModulesController { - @Autowired - private ModulesService modulesService; - - @WebAspect - @ApiOperation(value = "更新模块信息", notes = "新增或更新对应的模块信息") - @PutMapping - public RespModel save(@Validated @RequestBody Modules modules) { - modulesService.save(modules); - return new RespModel(RespEnum.UPDATE_OK); - } - - @WebAspect - @ApiOperation(value = "查找模块列表", notes = "查找对应项目id的模块列表") - @ApiImplicitParam(name = "projectId", value = "项目id", dataTypeClass = Integer.class) - @GetMapping("/list") - public RespModel> findByProjectId(@RequestParam(name = "projectId") int projectId) { - return new RespModel(RespEnum.SEARCH_OK, modulesService.findByProjectId(projectId)); - } - - @WebAspect - @ApiOperation(value = "删除模块", notes = "删除对应id的模块") - @ApiImplicitParam(name = "id", value = "模块id", dataTypeClass = Integer.class) - @DeleteMapping - public RespModel delete(@RequestParam(name = "id") int id) { - if (modulesService.delete(id)) { - return new RespModel(RespEnum.DELETE_OK); - } else { - return new RespModel(RespEnum.DELETE_ERROR); - } - } - - @WebAspect - @ApiOperation(value = "查看模块信息", notes = "查看对应id的模块信息") - @ApiImplicitParam(name = "id", value = "模块id", dataTypeClass = Integer.class) - @GetMapping - public RespModel findById(@RequestParam(name = "id") int id) { - Modules modules = modulesService.findById(id); - if (modules != null) { - return new RespModel(RespEnum.SEARCH_OK, modules); - } else { - return new RespModel(RespEnum.ID_NOT_FOUND); - } - } -} +package org.cloud.sonic.controller.controller; + +import org.cloud.sonic.common.config.WebAspect; +import org.cloud.sonic.common.http.RespEnum; +import org.cloud.sonic.common.http.RespModel; +import org.cloud.sonic.controller.models.base.TypeConverter; +import org.cloud.sonic.controller.models.domain.Modules; +import org.cloud.sonic.controller.models.dto.ModulesDTO; +import org.cloud.sonic.controller.services.ModulesService; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiImplicitParam; +import io.swagger.annotations.ApiOperation; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.*; + +import java.util.List; +import java.util.stream.Collectors; + +@Api(tags = "模块管理相关") +@RestController +@RequestMapping("/modules") +public class ModulesController { + + @Autowired + private ModulesService modulesService; + + @WebAspect + @ApiOperation(value = "更新模块信息", notes = "新增或更新对应的模块信息") + @PutMapping + public RespModel save(@Validated @RequestBody ModulesDTO modules) { + modulesService.save(modules.convertTo()); + return new RespModel<>(RespEnum.UPDATE_OK); + } + + @WebAspect + @ApiOperation(value = "查找模块列表", notes = "查找对应项目id的模块列表") + @ApiImplicitParam(name = "projectId", value = "项目id", dataTypeClass = Integer.class) + @GetMapping("/list") + public RespModel> findByProjectId(@RequestParam(name = "projectId") int projectId) { + return new RespModel<>( + RespEnum.SEARCH_OK, + modulesService.findByProjectId(projectId) + .stream().map(TypeConverter::convertTo).collect(Collectors.toList()) + ); + } + + @WebAspect + @ApiOperation(value = "删除模块", notes = "删除对应id的模块") + @ApiImplicitParam(name = "id", value = "模块id", dataTypeClass = Integer.class) + @DeleteMapping + public RespModel delete(@RequestParam(name = "id") int id) { + if (modulesService.delete(id)) { + return new RespModel<>(RespEnum.DELETE_OK); + } else { + return new RespModel<>(RespEnum.DELETE_ERROR); + } + } + + @WebAspect + @ApiOperation(value = "查看模块信息", notes = "查看对应id的模块信息") + @ApiImplicitParam(name = "id", value = "模块id", dataTypeClass = Integer.class) + @GetMapping + public RespModel findById(@RequestParam(name = "id") int id) { + Modules modules = modulesService.findById(id); + if (modules != null) { + return new RespModel<>(RespEnum.SEARCH_OK, modules.convertTo()); + } else { + return new RespModel<>(RespEnum.ID_NOT_FOUND); + } + } +} diff --git a/sonic-server-controller/src/main/java/com/sonic/controller/controller/ProjectsController.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/controller/ProjectsController.java similarity index 51% rename from sonic-server-controller/src/main/java/com/sonic/controller/controller/ProjectsController.java rename to sonic-server-controller/src/main/java/org/cloud/sonic/controller/controller/ProjectsController.java index 91a812bb..f4c44171 100644 --- a/sonic-server-controller/src/main/java/com/sonic/controller/controller/ProjectsController.java +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/controller/ProjectsController.java @@ -1,66 +1,73 @@ -package com.sonic.controller.controller; - -import com.sonic.common.config.WebAspect; -import com.sonic.common.exception.SonicException; -import com.sonic.common.http.RespEnum; -import com.sonic.common.http.RespModel; -import com.sonic.controller.models.Projects; -import com.sonic.controller.services.ProjectsService; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiImplicitParam; -import io.swagger.annotations.ApiOperation; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.validation.annotation.Validated; -import org.springframework.web.bind.annotation.*; - -import java.util.List; - -/** - * @author ZhouYiXun - * @des - * @date 2021/9/9 22:46 - */ -@Api(tags = "项目管理相关") -@RestController -@RequestMapping("/projects") -public class ProjectsController { - @Autowired - private ProjectsService projectsService; - - @WebAspect - @ApiOperation(value = "更新项目信息", notes = "新增或更新项目信息") - @PutMapping - public RespModel save(@Validated @RequestBody Projects projects) { - projectsService.save(projects); - return new RespModel(RespEnum.UPDATE_OK); - } - - @WebAspect - @ApiOperation(value = "查找所有项目", notes = "查找所有项目列表") - @GetMapping("/list") - public RespModel> findAll() { - return new RespModel(RespEnum.SEARCH_OK, projectsService.findAll()); - } - - @WebAspect - @ApiOperation(value = "查询项目信息", notes = "查找对应id下的详细信息") - @ApiImplicitParam(name = "id", value = "项目id", dataTypeClass = Integer.class) - @GetMapping - public RespModel findById(@RequestParam(name = "id") int id) { - Projects projects = projectsService.findById(id); - if (projects != null) { - return new RespModel(RespEnum.SEARCH_OK, projects); - } else { - return new RespModel(RespEnum.ID_NOT_FOUND); - } - } - - @WebAspect - @ApiOperation(value = "删除", notes = "删除对应id下的详细信息") - @ApiImplicitParam(name = "id", value = "项目id", dataTypeClass = Integer.class) - @DeleteMapping - public RespModel delete(@RequestParam(name = "id") int id) throws SonicException { - projectsService.delete(id); - return new RespModel(RespEnum.DELETE_OK); - } -} +package org.cloud.sonic.controller.controller; + +import org.cloud.sonic.common.config.WebAspect; +import org.cloud.sonic.common.exception.SonicException; +import org.cloud.sonic.common.http.RespEnum; +import org.cloud.sonic.common.http.RespModel; +import org.cloud.sonic.controller.models.base.TypeConverter; +import org.cloud.sonic.controller.models.domain.Projects; +import org.cloud.sonic.controller.models.dto.ProjectsDTO; +import org.cloud.sonic.controller.services.ProjectsService; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiImplicitParam; +import io.swagger.annotations.ApiOperation; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.*; + +import java.util.List; +import java.util.stream.Collectors; + +/** + * @author ZhouYiXun + * @des + * @date 2021/9/9 22:46 + */ +@Api(tags = "项目管理相关") +@RestController +@RequestMapping("/projects") +public class ProjectsController { + + @Autowired + private ProjectsService projectsService; + + @WebAspect + @ApiOperation(value = "更新项目信息", notes = "新增或更新项目信息") + @PutMapping + public RespModel save(@Validated @RequestBody ProjectsDTO projects) { + projectsService.save(projects.convertTo()); + return new RespModel<>(RespEnum.UPDATE_OK); + } + + @WebAspect + @ApiOperation(value = "查找所有项目", notes = "查找所有项目列表") + @GetMapping("/list") + public RespModel> findAll() { + return new RespModel<>( + RespEnum.SEARCH_OK, + projectsService.findAll().stream().map(TypeConverter::convertTo).collect(Collectors.toList()) + ); + } + + @WebAspect + @ApiOperation(value = "查询项目信息", notes = "查找对应id下的详细信息") + @ApiImplicitParam(name = "id", value = "项目id", dataTypeClass = Integer.class) + @GetMapping + public RespModel findById(@RequestParam(name = "id") int id) { + Projects projects = projectsService.findById(id); + if (projects != null) { + return new RespModel<>(RespEnum.SEARCH_OK, projects.convertTo()); + } else { + return new RespModel<>(RespEnum.ID_NOT_FOUND); + } + } + + @WebAspect + @ApiOperation(value = "删除", notes = "删除对应id下的详细信息") + @ApiImplicitParam(name = "id", value = "项目id", dataTypeClass = Integer.class) + @DeleteMapping + public RespModel delete(@RequestParam(name = "id") int id) throws SonicException { + projectsService.delete(id); + return new RespModel<>(RespEnum.DELETE_OK); + } +} diff --git a/sonic-server-controller/src/main/java/com/sonic/controller/controller/PublicStepsController.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/controller/PublicStepsController.java similarity index 52% rename from sonic-server-controller/src/main/java/com/sonic/controller/controller/PublicStepsController.java rename to sonic-server-controller/src/main/java/org/cloud/sonic/controller/controller/PublicStepsController.java index 0031a1ed..60930072 100644 --- a/sonic-server-controller/src/main/java/com/sonic/controller/controller/PublicStepsController.java +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/controller/PublicStepsController.java @@ -1,89 +1,105 @@ -package com.sonic.controller.controller; - -import com.sonic.common.config.WebAspect; -import com.sonic.common.http.RespEnum; -import com.sonic.common.http.RespModel; -import com.sonic.controller.models.PublicSteps; -import com.sonic.controller.services.PublicStepsService; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiImplicitParam; -import io.swagger.annotations.ApiImplicitParams; -import io.swagger.annotations.ApiOperation; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.PageRequest; -import org.springframework.data.domain.Pageable; -import org.springframework.data.domain.Sort; -import org.springframework.validation.annotation.Validated; -import org.springframework.web.bind.annotation.*; - -import java.util.List; -import java.util.Map; - -@Api(tags = "公共步骤相关") -@RestController -@RequestMapping("/publicSteps") -public class PublicStepsController { - @Autowired - private PublicStepsService publicStepsService; - - @WebAspect - @ApiOperation(value = "查询公共步骤列表1", notes = "查找对应项目id下的公共步骤列表(分页)") - @ApiImplicitParams(value = { - @ApiImplicitParam(name = "projectId", value = "项目id", dataTypeClass = Integer.class), - @ApiImplicitParam(name = "page", value = "页码", dataTypeClass = Integer.class), - @ApiImplicitParam(name = "pageSize", value = "页数据大小", dataTypeClass = Integer.class) - }) - @GetMapping("/list") - public RespModel> findByProjectId(@RequestParam(name = "projectId") int projectId, - @RequestParam(name = "page") int page, - @RequestParam(name = "pageSize") int pageSize) { - Pageable pageable = PageRequest.of(page - 1, pageSize, Sort.by(Sort.Direction.DESC, "id")); - return new RespModel(RespEnum.SEARCH_OK, publicStepsService.findByProjectId(projectId, pageable)); - } - - @WebAspect - @ApiOperation(value = "查询公共步骤列表2", notes = "查找对应项目id下的公共步骤列表(不分页,只查询id和name)") - @ApiImplicitParams(value = { - @ApiImplicitParam(name = "projectId", value = "项目id", dataTypeClass = Integer.class), - @ApiImplicitParam(name = "platform", value = "平台", dataTypeClass = Integer.class), - }) - @GetMapping("/findNameByProjectId") - public RespModel>> findByProjectId(@RequestParam(name = "projectId") int projectId, - @RequestParam(name = "platform") int platform) { - return new RespModel(RespEnum.SEARCH_OK, publicStepsService.findByProjectIdAndPlatform(projectId, platform)); - } - - @WebAspect - @ApiOperation(value = "更新公共步骤信息", notes = "新增或更新公共步骤信息") - @PutMapping - public RespModel save(@Validated @RequestBody PublicSteps publicSteps) { - publicStepsService.save(publicSteps); - return new RespModel(RespEnum.UPDATE_OK); - } - - @WebAspect - @ApiOperation(value = "删除公共步骤", notes = "删除对应公共步骤id,包含的操作步骤不会被删除") - @ApiImplicitParam(name = "id", value = "公共步骤id", dataTypeClass = Integer.class) - @DeleteMapping - public RespModel delete(@RequestParam(name = "id") int id) { - if (publicStepsService.delete(id)) { - return new RespModel(RespEnum.DELETE_OK); - } else { - return new RespModel(RespEnum.ID_NOT_FOUND); - } - } - - @WebAspect - @ApiOperation(value = "查找公共步骤信息", notes = "查询对应公共步骤的详细信息") - @ApiImplicitParam(name = "id", value = "公共步骤id", dataTypeClass = Integer.class) - @GetMapping - public RespModel findById(@RequestParam(name = "id") int id) { - PublicSteps publicSteps = publicStepsService.findById(id); - if (publicSteps != null) { - return new RespModel(RespEnum.SEARCH_OK, publicSteps); - } else { - return new RespModel(RespEnum.ID_NOT_FOUND); - } - } -} +package org.cloud.sonic.controller.controller; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import org.cloud.sonic.common.config.WebAspect; +import org.cloud.sonic.common.http.RespEnum; +import org.cloud.sonic.common.http.RespModel; +import org.cloud.sonic.controller.models.base.CommentPage; +import org.cloud.sonic.controller.models.domain.PublicSteps; +import org.cloud.sonic.controller.models.domain.TestCases; +import org.cloud.sonic.controller.models.dto.PublicStepsDTO; +import org.cloud.sonic.controller.services.PublicStepsService; +import org.cloud.sonic.controller.services.TestCasesService; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiImplicitParam; +import io.swagger.annotations.ApiImplicitParams; +import io.swagger.annotations.ApiOperation; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.*; + +import java.util.List; +import java.util.Map; + +@Api(tags = "公共步骤相关") +@RestController +@RequestMapping("/publicSteps") +public class PublicStepsController { + + @Autowired + private PublicStepsService publicStepsService; + @Autowired + private TestCasesService testCasesService; + + @WebAspect + @ApiOperation(value = "查询公共步骤列表1", notes = "查找对应项目id下的公共步骤列表(分页)") + @ApiImplicitParams(value = { + @ApiImplicitParam(name = "projectId", value = "项目id", dataTypeClass = Integer.class), + @ApiImplicitParam(name = "page", value = "页码", dataTypeClass = Integer.class), + @ApiImplicitParam(name = "pageSize", value = "页数据大小", dataTypeClass = Integer.class) + }) + @GetMapping("/list") + public RespModel> findByProjectId(@RequestParam(name = "projectId") int projectId, + @RequestParam(name = "page") int page, + @RequestParam(name = "pageSize") int pageSize) { + Page pageable = new Page<>(page, pageSize); + return new RespModel<>( + RespEnum.SEARCH_OK, + publicStepsService.findByProjectId(projectId, pageable) + ); + } + + @WebAspect + @ApiOperation(value = "查询公共步骤列表2", notes = "查找对应项目id下的公共步骤列表(不分页,只查询id和name)") + @ApiImplicitParams(value = { + @ApiImplicitParam(name = "projectId", value = "项目id", dataTypeClass = Integer.class), + @ApiImplicitParam(name = "platform", value = "平台", dataTypeClass = Integer.class), + }) + @GetMapping("/findNameByProjectId") + public RespModel>> findByProjectId(@RequestParam(name = "projectId") int projectId, + @RequestParam(name = "platform") int platform) { + return new RespModel<>(RespEnum.SEARCH_OK, publicStepsService.findByProjectIdAndPlatform(projectId, platform)); + } + + @WebAspect + @ApiOperation(value = "更新公共步骤信息", notes = "新增或更新公共步骤信息") + @PutMapping + public RespModel save(@Validated @RequestBody PublicStepsDTO publicStepsDTO) { + publicStepsService.savePublicSteps(publicStepsDTO); + return new RespModel<>(RespEnum.UPDATE_OK); + } + + @WebAspect + @ApiOperation(value = "删除公共步骤", notes = "删除对应公共步骤id,包含的操作步骤不会被删除") + @ApiImplicitParam(name = "id", value = "公共步骤id", dataTypeClass = Integer.class) + @DeleteMapping + public RespModel delete(@RequestParam(name = "id") int id) { + if (publicStepsService.delete(id)) { + return new RespModel<>(RespEnum.DELETE_OK); + } else { + return new RespModel<>(RespEnum.ID_NOT_FOUND); + } + } + + @WebAspect + @ApiOperation(value = "删除公共步骤检查", notes = "返回引用公共步骤的用例") + @ApiImplicitParam(name = "id", value = "公共步骤id", dataTypeClass = Integer.class) + @GetMapping("deleteCheck") + public RespModel> deleteCheck(@RequestParam(name = "id") int id) { + return new RespModel<>(RespEnum.SEARCH_OK, testCasesService.listByPublicStepsId(id)); + } + + + @WebAspect + @ApiOperation(value = "查找公共步骤信息", notes = "查询对应公共步骤的详细信息") + @ApiImplicitParam(name = "id", value = "公共步骤id", dataTypeClass = Integer.class) + @GetMapping + public RespModel findById(@RequestParam(name = "id") int id) { + PublicStepsDTO publicStepsDTO = publicStepsService.findById(id); + if (publicStepsDTO != null) { + return new RespModel<>(RespEnum.SEARCH_OK, publicStepsDTO); + } else { + return new RespModel<>(RespEnum.ID_NOT_FOUND); + } + } +} diff --git a/sonic-server-controller/src/main/java/com/sonic/controller/controller/ResultDetailController.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/controller/ResultDetailController.java similarity index 64% rename from sonic-server-controller/src/main/java/com/sonic/controller/controller/ResultDetailController.java rename to sonic-server-controller/src/main/java/org/cloud/sonic/controller/controller/ResultDetailController.java index b7e6e283..7f772c4d 100644 --- a/sonic-server-controller/src/main/java/com/sonic/controller/controller/ResultDetailController.java +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/controller/ResultDetailController.java @@ -1,77 +1,78 @@ -package com.sonic.controller.controller; - -import com.alibaba.fastjson.JSONObject; -import com.sonic.common.config.WebAspect; -import com.sonic.common.http.RespEnum; -import com.sonic.common.http.RespModel; -import com.sonic.controller.models.ResultDetail; -import com.sonic.controller.services.ResultDetailService; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiImplicitParam; -import io.swagger.annotations.ApiImplicitParams; -import io.swagger.annotations.ApiOperation; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.PageRequest; -import org.springframework.data.domain.Pageable; -import org.springframework.data.domain.Sort; -import org.springframework.web.bind.annotation.*; - -import java.util.List; - -/** - * @author ZhouYiXun - * @des - * @date 2021/8/29 16:59 - */ -@Api(tags = "测试结果详情相关") -@RestController -@RequestMapping("/resultDetail") -public class ResultDetailController { - @Autowired - private ResultDetailService resultDetailService; - - @WebAspect - @PostMapping - public RespModel save(@RequestBody JSONObject jsonObject) { - resultDetailService.saveByTransport(jsonObject); - return new RespModel(RespEnum.HANDLE_OK); - } - - @WebAspect - @ApiOperation(value = "查找测试结果详情", notes = "查找对应测试结果详情") - @ApiImplicitParams(value = { - @ApiImplicitParam(name = "caseId", value = "测试用例id", dataTypeClass = Integer.class), - @ApiImplicitParam(name = "resultId", value = "测试结果id", dataTypeClass = Integer.class), - @ApiImplicitParam(name = "deviceId", value = "设备id", dataTypeClass = Integer.class), - @ApiImplicitParam(name = "type", value = "类型", dataTypeClass = String.class), - @ApiImplicitParam(name = "page", value = "页码", dataTypeClass = Integer.class) - }) - @GetMapping("/list") - public RespModel> findAll(@RequestParam(name = "caseId") int caseId, - @RequestParam(name = "resultId") int resultId, - @RequestParam(name = "deviceId") int deviceId, - @RequestParam(name = "type") String type, - @RequestParam(name = "page") int page) { - Pageable pageable = PageRequest.of(page - 1, 20); - return new RespModel(RespEnum.SEARCH_OK, - resultDetailService.findAll(resultId, caseId, type, deviceId, pageable)); - } - - @WebAspect - @ApiOperation(value = "查找测试结果详情2", notes = "查找对应测试结果详情") - @ApiImplicitParams(value = { - @ApiImplicitParam(name = "caseId", value = "测试用例id", dataTypeClass = Integer.class), - @ApiImplicitParam(name = "resultId", value = "测试结果id", dataTypeClass = Integer.class), - @ApiImplicitParam(name = "deviceId", value = "设备id", dataTypeClass = Integer.class), - @ApiImplicitParam(name = "type", value = "类型", dataTypeClass = String.class), - }) - @GetMapping("/listAll") - public RespModel> findAll(@RequestParam(name = "caseId") int caseId, - @RequestParam(name = "resultId") int resultId, - @RequestParam(name = "deviceId") int deviceId, - @RequestParam(name = "type") String type) { - return new RespModel(RespEnum.SEARCH_OK, - resultDetailService.findAll(resultId, caseId, type, deviceId)); - } -} +package org.cloud.sonic.controller.controller; + +import com.alibaba.fastjson.JSONObject; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import org.cloud.sonic.common.config.WebAspect; +import org.cloud.sonic.common.http.RespEnum; +import org.cloud.sonic.common.http.RespModel; +import org.cloud.sonic.controller.models.base.CommentPage; +import org.cloud.sonic.controller.models.domain.ResultDetail; +import org.cloud.sonic.controller.services.ResultDetailService; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiImplicitParam; +import io.swagger.annotations.ApiImplicitParams; +import io.swagger.annotations.ApiOperation; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +/** + * @author ZhouYiXun + * @des + * @date 2021/8/29 16:59 + */ +@Api(tags = "测试结果详情相关") +@RestController +@RequestMapping("/resultDetail") +public class ResultDetailController { + + @Autowired + private ResultDetailService resultDetailService; + + @WebAspect + @PostMapping + public RespModel save(@RequestBody JSONObject jsonObject) { + resultDetailService.saveByTransport(jsonObject); + return new RespModel<>(RespEnum.HANDLE_OK); + } + + @WebAspect + @ApiOperation(value = "查找测试结果详情", notes = "查找对应测试结果详情") + @ApiImplicitParams(value = { + @ApiImplicitParam(name = "caseId", value = "测试用例id", dataTypeClass = Integer.class), + @ApiImplicitParam(name = "resultId", value = "测试结果id", dataTypeClass = Integer.class), + @ApiImplicitParam(name = "deviceId", value = "设备id", dataTypeClass = Integer.class), + @ApiImplicitParam(name = "type", value = "类型", dataTypeClass = String.class), + @ApiImplicitParam(name = "page", value = "页码", dataTypeClass = Integer.class) + }) + @GetMapping("/list") + public RespModel> findAll(@RequestParam(name = "caseId") int caseId, + @RequestParam(name = "resultId") int resultId, + @RequestParam(name = "deviceId") int deviceId, + @RequestParam(name = "type") String type, + @RequestParam(name = "page") int page) { + Page pageable = new Page<>(page, 20); + return new RespModel<>(RespEnum.SEARCH_OK, + CommentPage.convertFrom( + resultDetailService.findAll(resultId, caseId, type, deviceId, pageable)) + ); + } + + @WebAspect + @ApiOperation(value = "查找测试结果详情2", notes = "查找对应测试结果详情") + @ApiImplicitParams(value = { + @ApiImplicitParam(name = "caseId", value = "测试用例id", dataTypeClass = Integer.class), + @ApiImplicitParam(name = "resultId", value = "测试结果id", dataTypeClass = Integer.class), + @ApiImplicitParam(name = "deviceId", value = "设备id", dataTypeClass = Integer.class), + @ApiImplicitParam(name = "type", value = "类型", dataTypeClass = String.class), + }) + @GetMapping("/listAll") + public RespModel> findAll(@RequestParam(name = "caseId") int caseId, + @RequestParam(name = "resultId") int resultId, + @RequestParam(name = "deviceId") int deviceId, + @RequestParam(name = "type") String type) { + return new RespModel<>(RespEnum.SEARCH_OK, + resultDetailService.findAll(resultId, caseId, type, deviceId)); + } +} diff --git a/sonic-server-controller/src/main/java/com/sonic/controller/controller/ResultsController.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/controller/ResultsController.java similarity index 63% rename from sonic-server-controller/src/main/java/com/sonic/controller/controller/ResultsController.java rename to sonic-server-controller/src/main/java/org/cloud/sonic/controller/controller/ResultsController.java index c9ce7f06..a0c9d851 100644 --- a/sonic-server-controller/src/main/java/com/sonic/controller/controller/ResultsController.java +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/controller/ResultsController.java @@ -1,119 +1,120 @@ -package com.sonic.controller.controller; - -import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.JSONObject; -import com.sonic.common.config.WebAspect; -import com.sonic.common.http.RespEnum; -import com.sonic.common.http.RespModel; -import com.sonic.controller.models.Results; -import com.sonic.controller.services.ResultsService; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiImplicitParam; -import io.swagger.annotations.ApiImplicitParams; -import io.swagger.annotations.ApiOperation; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.PageRequest; -import org.springframework.data.domain.Pageable; -import org.springframework.data.domain.Sort; -import org.springframework.web.bind.annotation.*; - -@Api(tags = "测试结果相关") -@RestController -@RequestMapping("/results") -public class ResultsController { - @Autowired - private ResultsService resultsService; - - @WebAspect - @ApiOperation(value = "查询测试结果列表", notes = "查找对应项目id下的测试结果列表") - @ApiImplicitParams(value = { - @ApiImplicitParam(name = "projectId", value = "项目id", dataTypeClass = Integer.class), - @ApiImplicitParam(name = "page", value = "页码", dataTypeClass = Integer.class), - @ApiImplicitParam(name = "pageSize", value = "页数据大小", dataTypeClass = Integer.class) - }) - @GetMapping("/list") - public RespModel> findByProjectId(@RequestParam(name = "projectId") int projectId, - @RequestParam(name = "page") int page, - @RequestParam(name = "pageSize") int pageSize) { - Pageable pageable = PageRequest.of(page - 1, pageSize, Sort.by(Sort.Direction.DESC, "id")); - return new RespModel(RespEnum.SEARCH_OK, resultsService.findByProjectId(projectId, pageable)); - } - - @WebAspect - @ApiOperation(value = "删除测试结果", notes = "删除对应的测试结果id以及测试结果详情") - @ApiImplicitParam(name = "id", value = "测试结果id", dataTypeClass = Integer.class) - @DeleteMapping - public RespModel delete(@RequestParam(name = "id") int id) { - if (resultsService.delete(id)) { - return new RespModel(RespEnum.DELETE_OK); - } else { - return new RespModel(RespEnum.ID_NOT_FOUND); - } - } - - @WebAspect - @ApiOperation(value = "查询测试结果信息", notes = "查询对应id的测试结果信息") - @ApiImplicitParam(name = "id", value = "测试结果id", dataTypeClass = Integer.class) - @GetMapping - public RespModel findById(@RequestParam(name = "id") int id) { - return new RespModel(RespEnum.SEARCH_OK, resultsService.findById(id)); - } - - @WebAspect - @GetMapping("/clean") - public RespModel clean(@RequestParam(name = "day") int day) { - resultsService.clean(day); - return new RespModel(0, "开始清理测试结果!"); - } - - @WebAspect - @GetMapping("/subResultCount") - public RespModel subResultCount(@RequestParam(name = "id") int id) { - resultsService.subResultCount(id); - return new RespModel(RespEnum.HANDLE_OK); - } - - @WebAspect - @ApiOperation(value = "查询测试结果用例状态", notes = "查询对应id的测试结果用例状态") - @ApiImplicitParam(name = "id", value = "测试结果id", dataTypeClass = Integer.class) - @GetMapping("/findCaseStatus") - public RespModel findCaseStatus(@RequestParam(name = "id") int id) { - JSONArray result = resultsService.findCaseStatus(id); - if (result == null) { - return new RespModel(RespEnum.ID_NOT_FOUND); - } else { - return new RespModel(RespEnum.SEARCH_OK, result); - } - } - - @WebAspect - @ApiOperation(value = "查询报表", notes = "查找前端首页报表信息") - @ApiImplicitParams(value = { - @ApiImplicitParam(name = "projectId", value = "项目id", dataTypeClass = Integer.class), - @ApiImplicitParam(name = "startTime", value = "起始时间", dataTypeClass = String.class), - @ApiImplicitParam(name = "endTime", value = "结束时间", dataTypeClass = String.class) - }) - @GetMapping("/chart") - public RespModel chart(@RequestParam(name = "projectId") int projectId, - @RequestParam(name = "startTime") String startTime, - @RequestParam(name = "endTime") String endTime) { - return new RespModel(RespEnum.SEARCH_OK, resultsService.chart(startTime, endTime, projectId)); - } - - @WebAspect - @ApiOperation(value = "发送日报", notes = "发送所有项目日报") - @GetMapping("/sendDayReport") - public RespModel sendDayReport() { - resultsService.sendDayReport(); - return new RespModel(RespEnum.HANDLE_OK); - } - - @WebAspect - @ApiOperation(value = "发送周报", notes = "发送所有项目周报") - @GetMapping("/sendWeekReport") - public RespModel sendWeekReport() { - resultsService.sendWeekReport(); - return new RespModel(RespEnum.HANDLE_OK); - } -} +package org.cloud.sonic.controller.controller; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import org.cloud.sonic.common.config.WebAspect; +import org.cloud.sonic.common.http.RespEnum; +import org.cloud.sonic.common.http.RespModel; +import org.cloud.sonic.controller.models.base.CommentPage; +import org.cloud.sonic.controller.models.domain.Results; +import org.cloud.sonic.controller.services.ResultsService; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiImplicitParam; +import io.swagger.annotations.ApiImplicitParams; +import io.swagger.annotations.ApiOperation; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +@Api(tags = "测试结果相关") +@RestController +@RequestMapping("/results") +public class ResultsController { + @Autowired + private ResultsService resultsService; + + @WebAspect + @ApiOperation(value = "查询测试结果列表", notes = "查找对应项目id下的测试结果列表") + @ApiImplicitParams(value = { + @ApiImplicitParam(name = "projectId", value = "项目id", dataTypeClass = Integer.class), + @ApiImplicitParam(name = "page", value = "页码", dataTypeClass = Integer.class), + @ApiImplicitParam(name = "pageSize", value = "页数据大小", dataTypeClass = Integer.class) + }) + @GetMapping("/list") + public RespModel> findByProjectId(@RequestParam(name = "projectId") int projectId, + @RequestParam(name = "page") int page, + @RequestParam(name = "pageSize") int pageSize) { + Page pageable = new Page<>(page, pageSize); + return new RespModel<>( + RespEnum.SEARCH_OK, + CommentPage.convertFrom(resultsService.findByProjectId(projectId, pageable)) + ); + } + + @WebAspect + @ApiOperation(value = "删除测试结果", notes = "删除对应的测试结果id以及测试结果详情") + @ApiImplicitParam(name = "id", value = "测试结果id", dataTypeClass = Integer.class) + @DeleteMapping + public RespModel delete(@RequestParam(name = "id") int id) { + if (resultsService.delete(id)) { + return new RespModel<>(RespEnum.DELETE_OK); + } else { + return new RespModel<>(RespEnum.ID_NOT_FOUND); + } + } + + @WebAspect + @ApiOperation(value = "查询测试结果信息", notes = "查询对应id的测试结果信息") + @ApiImplicitParam(name = "id", value = "测试结果id", dataTypeClass = Integer.class) + @GetMapping + public RespModel findById(@RequestParam(name = "id") int id) { + return new RespModel<>(RespEnum.SEARCH_OK, resultsService.findById(id)); + } + + @WebAspect + @GetMapping("/clean") + public RespModel clean(@RequestParam(name = "day") int day) { + resultsService.clean(day); + return new RespModel<>(0, "开始清理测试结果!"); + } + + @WebAspect + @GetMapping("/subResultCount") + public RespModel subResultCount(@RequestParam(name = "id") int id) { + resultsService.subResultCount(id); + return new RespModel<>(RespEnum.HANDLE_OK); + } + + @WebAspect + @ApiOperation(value = "查询测试结果用例状态", notes = "查询对应id的测试结果用例状态") + @ApiImplicitParam(name = "id", value = "测试结果id", dataTypeClass = Integer.class) + @GetMapping("/findCaseStatus") + public RespModel findCaseStatus(@RequestParam(name = "id") int id) { + JSONArray result = resultsService.findCaseStatus(id); + if (result == null) { + return new RespModel<>(RespEnum.ID_NOT_FOUND); + } else { + return new RespModel<>(RespEnum.SEARCH_OK, result); + } + } + + @WebAspect + @ApiOperation(value = "查询报表", notes = "查找前端首页报表信息") + @ApiImplicitParams(value = { + @ApiImplicitParam(name = "projectId", value = "项目id", dataTypeClass = Integer.class), + @ApiImplicitParam(name = "startTime", value = "起始时间", dataTypeClass = String.class), + @ApiImplicitParam(name = "endTime", value = "结束时间", dataTypeClass = String.class) + }) + @GetMapping("/chart") + public RespModel chart(@RequestParam(name = "projectId") int projectId, + @RequestParam(name = "startTime") String startTime, + @RequestParam(name = "endTime") String endTime) { + return new RespModel<>(RespEnum.SEARCH_OK, resultsService.chart(startTime, endTime, projectId)); + } + + @WebAspect + @ApiOperation(value = "发送日报", notes = "发送所有项目日报") + @GetMapping("/sendDayReport") + public RespModel sendDayReport() { + resultsService.sendDayReport(); + return new RespModel<>(RespEnum.HANDLE_OK); + } + + @WebAspect + @ApiOperation(value = "发送周报", notes = "发送所有项目周报") + @GetMapping("/sendWeekReport") + public RespModel sendWeekReport() { + resultsService.sendWeekReport(); + return new RespModel<>(RespEnum.HANDLE_OK); + } +} diff --git a/sonic-server-controller/src/main/java/org/cloud/sonic/controller/controller/StepsController.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/controller/StepsController.java new file mode 100644 index 00000000..ce2eeedf --- /dev/null +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/controller/StepsController.java @@ -0,0 +1,123 @@ +package org.cloud.sonic.controller.controller; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import org.cloud.sonic.common.config.WebAspect; +import org.cloud.sonic.common.http.RespEnum; +import org.cloud.sonic.common.http.RespModel; +import org.cloud.sonic.controller.mapper.PublicStepsMapper; +import org.cloud.sonic.controller.models.base.CommentPage; +import org.cloud.sonic.controller.models.domain.PublicSteps; +import org.cloud.sonic.controller.models.domain.Steps; +import org.cloud.sonic.controller.models.dto.StepsDTO; +import org.cloud.sonic.controller.models.http.StepSort; +import org.cloud.sonic.controller.services.StepsService; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiImplicitParam; +import io.swagger.annotations.ApiImplicitParams; +import io.swagger.annotations.ApiOperation; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +/** + * @author ZhouYiXun + * @des + * @date 2021/9/19 11:45 + */ +@Api(tags = "操作步骤相关") +@RestController +@RequestMapping("/steps") +public class StepsController { + @Autowired + private StepsService stepsService; + @Autowired + private PublicStepsMapper publicStepsMapper; + + @WebAspect + @ApiOperation(value = "查找步骤列表", notes = "查找对应用例id下的步骤列表(分页)") + @ApiImplicitParams(value = { + @ApiImplicitParam(name = "projectId", value = "项目id", dataTypeClass = Integer.class), + @ApiImplicitParam(name = "platform", value = "平台", dataTypeClass = Integer.class), + @ApiImplicitParam(name = "page", value = "页码", dataTypeClass = Integer.class), + @ApiImplicitParam(name = "pageSize", value = "页数据大小", dataTypeClass = Integer.class) + }) + @GetMapping("/list") + public RespModel> findAll(@RequestParam(name = "projectId") int projectId, + @RequestParam(name = "platform") int platform, + @RequestParam(name = "page") int page, + @RequestParam(name = "pageSize") int pageSize) { + Page pageable = new Page<>(page, pageSize); + return new RespModel<>(RespEnum.SEARCH_OK, stepsService.findByProjectIdAndPlatform(projectId, platform, pageable)); + } + + @WebAspect + @ApiOperation(value = "查找步骤列表", notes = "查找对应用例id下的步骤列表") + @ApiImplicitParam(name = "caseId", value = "测试用例id", dataTypeClass = Integer.class) + @GetMapping("/listAll") + public RespModel> findByCaseIdOrderBySort(@RequestParam(name = "caseId") int caseId) { + return new RespModel<>(RespEnum.SEARCH_OK, stepsService.findByCaseIdOrderBySort(caseId)); + } + + @WebAspect + @ApiOperation(value = "移出测试用例", notes = "将步骤从测试用例移出") + @ApiImplicitParam(name = "id", value = "步骤id", dataTypeClass = Integer.class) + @GetMapping("/resetCaseId") + public RespModel resetCaseId(@RequestParam(name = "id") int id) { + if (stepsService.resetCaseId(id)) { + return new RespModel<>(2000, "移出测试用例成功!"); + } else { + return new RespModel<>(RespEnum.ID_NOT_FOUND); + } + } + + @WebAspect + @ApiOperation(value = "删除操作步骤", notes = "将步骤删除,并且从所有公共步骤里移除") + @ApiImplicitParam(name = "id", value = "步骤id", dataTypeClass = Integer.class) + @DeleteMapping + public RespModel delete(@RequestParam(name = "id") int id) { + if (stepsService.delete(id)) { + return new RespModel<>(RespEnum.DELETE_OK); + } else { + return new RespModel<>(RespEnum.DELETE_ERROR); + } + } + + @WebAspect + @ApiOperation(value = "删除操作步骤检查", notes = "返回步骤所属的公共步骤") + @ApiImplicitParam(name = "id", value = "步骤id", dataTypeClass = Integer.class) + @GetMapping("deleteCheck") + public RespModel> deleteCheck(@RequestParam(name = "id") int id) { + return new RespModel<>(RespEnum.SEARCH_OK, publicStepsMapper.listPubStepsByStepId(id)); + } + + @WebAspect + @ApiOperation(value = "更新操作步骤", notes = "新增或更新操作步骤") + @PutMapping + public RespModel save(@Validated @RequestBody StepsDTO stepsDTO) { + stepsService.saveStep(stepsDTO); + return new RespModel<>(RespEnum.UPDATE_OK); + } + + @WebAspect + @ApiOperation(value = "拖拽排序步骤", notes = "用于前端页面拖拽排序步骤") + @PutMapping("/stepSort") + public RespModel stepSort(@Validated @RequestBody StepSort stepSort) { + stepsService.sortSteps(stepSort); + return new RespModel<>(RespEnum.UPDATE_OK); + } + + @WebAspect + @ApiOperation(value = "查询步骤详情", notes = "查询对应步骤id的详情信息") + @ApiImplicitParam(name = "id", value = "步骤id", dataTypeClass = Integer.class) + @GetMapping + public RespModel findById(@RequestParam(name = "id") int id) { + StepsDTO steps = stepsService.findById(id); + if (steps != null) { + return new RespModel<>(RespEnum.SEARCH_OK, steps); + } else { + return new RespModel<>(RespEnum.ID_NOT_FOUND); + } + } +} diff --git a/sonic-server-controller/src/main/java/com/sonic/controller/controller/TestCasesController.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/controller/TestCasesController.java similarity index 58% rename from sonic-server-controller/src/main/java/com/sonic/controller/controller/TestCasesController.java rename to sonic-server-controller/src/main/java/org/cloud/sonic/controller/controller/TestCasesController.java index 482536c3..8b419c1e 100644 --- a/sonic-server-controller/src/main/java/com/sonic/controller/controller/TestCasesController.java +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/controller/TestCasesController.java @@ -1,127 +1,139 @@ -package com.sonic.controller.controller; - -import com.alibaba.fastjson.JSONObject; -import com.sonic.common.config.WebAspect; -import com.sonic.common.http.RespEnum; -import com.sonic.common.http.RespModel; -import com.sonic.common.tools.JWTTokenTool; -import com.sonic.controller.models.TestCases; -import com.sonic.controller.models.Users; -import com.sonic.controller.services.TestCasesService; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiImplicitParam; -import io.swagger.annotations.ApiImplicitParams; -import io.swagger.annotations.ApiOperation; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.PageRequest; -import org.springframework.data.domain.Pageable; -import org.springframework.data.domain.Sort; -import org.springframework.validation.annotation.Validated; -import org.springframework.web.bind.annotation.*; - -import javax.servlet.http.HttpServletRequest; -import java.util.List; - -@Api(tags = "测试用例相关") -@RestController -@RequestMapping("/testCases") -public class TestCasesController { - @Autowired - private TestCasesService testCasesService; - @Autowired - private JWTTokenTool jwtTokenTool; - - @WebAspect - @ApiOperation(value = "查询测试用例列表", notes = "查找对应项目id下的测试用例列表") - @ApiImplicitParams(value = { - @ApiImplicitParam(name = "projectId", value = "项目id", dataTypeClass = Integer.class), - @ApiImplicitParam(name = "platform", value = "平台类型", dataTypeClass = Integer.class), - @ApiImplicitParam(name = "name", value = "用例名称", dataTypeClass = String.class), - @ApiImplicitParam(name = "page", value = "页码", dataTypeClass = Integer.class), - @ApiImplicitParam(name = "pageSize", value = "页数据大小", dataTypeClass = Integer.class) - }) - @GetMapping("/list") - public RespModel> findAll(@RequestParam(name = "projectId") int projectId, - @RequestParam(name = "platform") int platform, - @RequestParam(name = "name") String name, - @RequestParam(name = "page") int page, - @RequestParam(name = "pageSize") int pageSize) { - Pageable pageable = PageRequest.of(page - 1, pageSize, Sort.by(Sort.Direction.DESC, "editTime")); - return new RespModel(RespEnum.SEARCH_OK, - testCasesService.findAll(projectId, platform, name, pageable)); - } - - @WebAspect - @ApiOperation(value = "查询测试用例列表", notes = "不分页的测试用例列表") - @ApiImplicitParams(value = { - @ApiImplicitParam(name = "projectId", value = "项目id", dataTypeClass = Integer.class), - @ApiImplicitParam(name = "platform", value = "平台类型", dataTypeClass = Integer.class), - }) - @GetMapping("/listAll") - public RespModel> findAll(@RequestParam(name = "projectId") int projectId, - @RequestParam(name = "platform") int platform) { - return new RespModel(RespEnum.SEARCH_OK, - testCasesService.findAll(projectId, platform)); - } - - @WebAspect - @ApiOperation(value = "删除测试用例", notes = "删除对应用例id,用例下的操作步骤的caseId重置为0") - @ApiImplicitParam(name = "id", value = "用例id", dataTypeClass = Integer.class) - @DeleteMapping - public RespModel delete(@RequestParam(name = "id") int id) { - if (testCasesService.delete(id)) { - return new RespModel(RespEnum.DELETE_OK); - } else { - return new RespModel(RespEnum.ID_NOT_FOUND); - } - } - - @WebAspect - @ApiOperation(value = "更新测试用例信息", notes = "新增或更改测试用例信息") - @PutMapping - public RespModel save(@Validated @RequestBody TestCases testCases, HttpServletRequest request) { - if (request.getHeader("SonicToken") != null) { - String token = request.getHeader("SonicToken"); - String userName = jwtTokenTool.getUserName(token); - if (userName != null) { - testCases.setDesigner(userName); - } - } - testCasesService.save(testCases); - return new RespModel(RespEnum.UPDATE_OK); - } - - @WebAspect - @ApiOperation(value = "查询测试用例详情", notes = "查找对应用例id的用例详情") - @ApiImplicitParam(name = "id", value = "用例id", dataTypeClass = Integer.class) - @GetMapping - public RespModel findById(@RequestParam(name = "id") int id) { - TestCases testCases = testCasesService.findById(id); - if (testCases != null) { - return new RespModel(RespEnum.SEARCH_OK, testCases); - } else { - return new RespModel(RespEnum.ID_NOT_FOUND); - } - } - - @WebAspect - @GetMapping("/findSteps") - public RespModel findSteps(@RequestParam(name = "id") int id) { - JSONObject jsonObject = testCasesService.findSteps(id); - if (jsonObject != null) { - return new RespModel(RespEnum.SEARCH_OK, jsonObject); - } else { - return new RespModel(-1, "查询出错!"); - } - } - - @WebAspect - @ApiOperation(value = "批量查询用例", notes = "查找id列表的用例信息,可以传多个ids[]") - @ApiImplicitParam(name = "ids[]", value = "id列表", dataTypeClass = Integer.class) - @GetMapping("/findByIdIn") - public RespModel> findByIdIn(@RequestParam(name = "ids[]") List ids) { - return new RespModel(RespEnum.SEARCH_OK, - testCasesService.findByIdIn(ids)); - } -} +package org.cloud.sonic.controller.controller; + +import com.alibaba.fastjson.JSONObject; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import org.cloud.sonic.common.config.WebAspect; +import org.cloud.sonic.common.http.RespEnum; +import org.cloud.sonic.common.http.RespModel; +import org.cloud.sonic.common.tools.JWTTokenTool; +import org.cloud.sonic.controller.models.base.CommentPage; +import org.cloud.sonic.controller.models.domain.TestCases; +import org.cloud.sonic.controller.models.domain.TestSuites; +import org.cloud.sonic.controller.models.dto.TestCasesDTO; +import org.cloud.sonic.controller.services.TestCasesService; +import org.cloud.sonic.controller.services.TestSuitesService; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiImplicitParam; +import io.swagger.annotations.ApiImplicitParams; +import io.swagger.annotations.ApiOperation; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.*; + +import javax.servlet.http.HttpServletRequest; +import java.util.List; + +@Api(tags = "测试用例相关") +@RestController +@RequestMapping("/testCases") +public class TestCasesController { + @Autowired + private TestCasesService testCasesService; + @Autowired + private JWTTokenTool jwtTokenTool; + @Autowired + private TestSuitesService testSuitesService; + + @WebAspect + @ApiOperation(value = "查询测试用例列表", notes = "查找对应项目id下的测试用例列表") + @ApiImplicitParams(value = { + @ApiImplicitParam(name = "projectId", value = "项目id", dataTypeClass = Integer.class), + @ApiImplicitParam(name = "platform", value = "平台类型", dataTypeClass = Integer.class), + @ApiImplicitParam(name = "name", value = "用例名称", dataTypeClass = String.class), + @ApiImplicitParam(name = "page", value = "页码", dataTypeClass = Integer.class), + @ApiImplicitParam(name = "pageSize", value = "页数据大小", dataTypeClass = Integer.class) + }) + @GetMapping("/list") + public RespModel> findAll(@RequestParam(name = "projectId") int projectId, + @RequestParam(name = "platform") int platform, + @RequestParam(name = "name") String name, + @RequestParam(name = "page") int page, + @RequestParam(name = "pageSize") int pageSize) { + Page pageable = new Page<>(page, pageSize); + return new RespModel<>( + RespEnum.SEARCH_OK, + CommentPage.convertFrom(testCasesService.findAll(projectId, platform, name, pageable)) + ); + } + + @WebAspect + @ApiOperation(value = "查询测试用例列表", notes = "不分页的测试用例列表") + @ApiImplicitParams(value = { + @ApiImplicitParam(name = "projectId", value = "项目id", dataTypeClass = Integer.class), + @ApiImplicitParam(name = "platform", value = "平台类型", dataTypeClass = Integer.class), + }) + @GetMapping("/listAll") + public RespModel> findAll(@RequestParam(name = "projectId") int projectId, + @RequestParam(name = "platform") int platform) { + return new RespModel<>(RespEnum.SEARCH_OK, + testCasesService.findAll(projectId, platform)); + } + + @WebAspect + @ApiOperation(value = "删除测试用例", notes = "删除对应用例id,用例下的操作步骤的caseId重置为0") + @ApiImplicitParam(name = "id", value = "用例id", dataTypeClass = Integer.class) + @DeleteMapping + public RespModel delete(@RequestParam(name = "id") int id) { + if (testCasesService.delete(id)) { + return new RespModel<>(RespEnum.DELETE_OK); + } else { + return new RespModel<>(RespEnum.ID_NOT_FOUND); + } + } + + @WebAspect + @ApiOperation(value = "删除测试用例检查", notes = "返回被引用的测试套件") + @ApiImplicitParam(name = "id", value = "用例id", dataTypeClass = Integer.class) + @GetMapping("deleteCheck") + public RespModel> deleteCheck(@RequestParam(name = "id") int id) { + return new RespModel<>(RespEnum.SEARCH_OK, testSuitesService.listTestSuitesByTestCasesId(id)); + } + + @WebAspect + @ApiOperation(value = "更新测试用例信息", notes = "新增或更改测试用例信息") + @PutMapping + public RespModel save(@Validated @RequestBody TestCasesDTO testCasesDTO, HttpServletRequest request) { + if (request.getHeader("SonicToken") != null) { + String token = request.getHeader("SonicToken"); + String userName = jwtTokenTool.getUserName(token); + if (userName != null) { + testCasesDTO.setDesigner(userName); + } + } + testCasesService.save(testCasesDTO.convertTo()); + return new RespModel<>(RespEnum.UPDATE_OK); + } + + @WebAspect + @ApiOperation(value = "查询测试用例详情", notes = "查找对应用例id的用例详情") + @ApiImplicitParam(name = "id", value = "用例id", dataTypeClass = Integer.class) + @GetMapping + public RespModel findById(@RequestParam(name = "id") int id) { + TestCases testCases = testCasesService.findById(id); + if (testCases != null) { + return new RespModel<>(RespEnum.SEARCH_OK, testCases); + } else { + return new RespModel<>(RespEnum.ID_NOT_FOUND); + } + } + + @WebAspect + @GetMapping("/findSteps") + public RespModel findSteps(@RequestParam(name = "id") int id) { + JSONObject jsonObject = testCasesService.findSteps(id); + if (jsonObject != null) { + return new RespModel<>(RespEnum.SEARCH_OK, jsonObject); + } else { + return new RespModel<>(-1, "查询出错!"); + } + } + + @WebAspect + @ApiOperation(value = "批量查询用例", notes = "查找id列表的用例信息,可以传多个ids[]") + @ApiImplicitParam(name = "ids[]", value = "id列表", dataTypeClass = Integer.class) + @GetMapping("/findByIdIn") + public RespModel> findByIdIn(@RequestParam(name = "ids[]") List ids) { + return new RespModel<>(RespEnum.SEARCH_OK, + testCasesService.findByIdIn(ids)); + } +} diff --git a/sonic-server-controller/src/main/java/com/sonic/controller/controller/TestSuitesController.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/controller/TestSuitesController.java similarity index 65% rename from sonic-server-controller/src/main/java/com/sonic/controller/controller/TestSuitesController.java rename to sonic-server-controller/src/main/java/org/cloud/sonic/controller/controller/TestSuitesController.java index eebb6dc0..faac6d1e 100644 --- a/sonic-server-controller/src/main/java/com/sonic/controller/controller/TestSuitesController.java +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/controller/TestSuitesController.java @@ -1,119 +1,118 @@ -package com.sonic.controller.controller; - -import com.sonic.common.config.WebAspect; -import com.sonic.common.http.RespEnum; -import com.sonic.common.http.RespModel; -import com.sonic.common.tools.JWTTokenTool; -import com.sonic.controller.models.TestSuites; -import com.sonic.controller.models.Users; -import com.sonic.controller.services.TestSuitesService; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiImplicitParam; -import io.swagger.annotations.ApiOperation; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.PageRequest; -import org.springframework.data.domain.Pageable; -import org.springframework.validation.annotation.Validated; -import org.springframework.web.bind.annotation.*; - -import javax.servlet.http.HttpServletRequest; -import java.util.List; - -@Api(tags = "测试套件相关") -@RestController -@RequestMapping("/testSuites") -public class TestSuitesController { - @Autowired - private TestSuitesService testSuitesService; - @Autowired - private JWTTokenTool jwtTokenTool; - - @WebAspect - @ApiOperation(value = "运行测试套件", notes = "运行指定项目的指定测试套件") - @ApiImplicitParam(name = "id", value = "测试套件id", dataTypeClass = Integer.class) - @GetMapping("/runSuite") - public RespModel runSuite(@RequestParam(name = "id") int id - , HttpServletRequest request) { - String strike = "SYSTEM"; - if (request.getHeader("SonicToken") != null) { - String token = request.getHeader("SonicToken"); - String userName = jwtTokenTool.getUserName(token); - if (userName != null) { - strike = userName; - } - } - return testSuitesService.runSuite(id, strike); - } - - @WebAspect - @ApiOperation(value = "停止测试套件运行", notes = "停止测试套件运行") - @ApiImplicitParam(name = "resultId", value = "测试结果Id", dataTypeClass = Integer.class) - @GetMapping("/forceStopSuite") - public RespModel forceStopSuite(@RequestParam(name = "resultId") int resultId - , HttpServletRequest request) { - String strike = "SYSTEM"; - if (request.getHeader("SonicToken") != null) { - String token = request.getHeader("SonicToken"); - String userName = jwtTokenTool.getUserName(token); - if (userName != null) { - strike = userName; - } - } - return testSuitesService.forceStopSuite(resultId, strike); - } - - - @WebAspect - @ApiOperation(value = "删除测试套件", notes = "删除指定id的测试套件") - @ApiImplicitParam(name = "id", value = "测试套件id", dataTypeClass = Integer.class) - @DeleteMapping - public RespModel delete(@RequestParam(name = "id") int id) { - if (testSuitesService.delete(id)) { - return new RespModel(RespEnum.DELETE_OK); - } else { - return new RespModel(RespEnum.ID_NOT_FOUND); - } - } - - @WebAspect - @ApiOperation(value = "更新测试套件", notes = "更新或新增测试套件") - @PutMapping - public RespModel save(@Validated @RequestBody TestSuites testSuites) { - testSuitesService.save(testSuites); - return new RespModel(RespEnum.UPDATE_OK); - } - - @WebAspect - @ApiOperation(value = "查询测试套件列表", notes = "用于查询对应项目id下的测试套件列表") - @ApiImplicitParam(name = "projectId", value = "项目id", dataTypeClass = Integer.class) - @GetMapping("/list") - public RespModel> findByProjectId(@RequestParam(name = "projectId") int projectId - , @RequestParam(name = "name") String name - , @RequestParam(name = "page") int page - , @RequestParam(name = "pageSize") int pageSize) { - Pageable pageable = PageRequest.of(page - 1, pageSize); - return new RespModel(RespEnum.SEARCH_OK, testSuitesService.findByProjectId(projectId, name, pageable)); - } - - @WebAspect - @ApiOperation(value = "查询测试套件列表", notes = "用于查询对应项目id下的测试套件列表(不分页)") - @ApiImplicitParam(name = "projectId", value = "项目id", dataTypeClass = Integer.class) - @GetMapping("/listAll") - public RespModel> findByProjectId(@RequestParam(name = "projectId") int projectId) { - return new RespModel(RespEnum.SEARCH_OK, testSuitesService.findByProjectId(projectId)); - } - - @WebAspect - @ApiOperation(value = "测试套件详情", notes = "查看测试套件的配置信息详情") - @ApiImplicitParam(name = "id", value = "测试套件id", dataTypeClass = Integer.class) - @GetMapping - public RespModel findById(@RequestParam(name = "id") int id) { - TestSuites testSuites = testSuitesService.findById(id); - if (testSuites != null) { - return new RespModel(RespEnum.SEARCH_OK, testSuites); - } else { - return new RespModel(RespEnum.ID_NOT_FOUND); - } - } -} +package org.cloud.sonic.controller.controller; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import org.cloud.sonic.common.config.WebAspect; +import org.cloud.sonic.common.http.RespEnum; +import org.cloud.sonic.common.http.RespModel; +import org.cloud.sonic.common.tools.JWTTokenTool; +import org.cloud.sonic.controller.models.base.CommentPage; +import org.cloud.sonic.controller.models.domain.TestSuites; +import org.cloud.sonic.controller.models.dto.TestSuitesDTO; +import org.cloud.sonic.controller.services.TestSuitesService; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiImplicitParam; +import io.swagger.annotations.ApiOperation; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.*; + +import javax.servlet.http.HttpServletRequest; +import java.util.List; + +@Api(tags = "测试套件相关") +@RestController +@RequestMapping("/testSuites") +public class TestSuitesController { + @Autowired + private TestSuitesService testSuitesService; + @Autowired + private JWTTokenTool jwtTokenTool; + + @WebAspect + @ApiOperation(value = "运行测试套件", notes = "运行指定项目的指定测试套件") + @ApiImplicitParam(name = "id", value = "测试套件id", dataTypeClass = Integer.class) + @GetMapping("/runSuite") + public RespModel runSuite(@RequestParam(name = "id") int id + , HttpServletRequest request) { + String strike = "SYSTEM"; + if (request.getHeader("SonicToken") != null) { + String token = request.getHeader("SonicToken"); + String userName = jwtTokenTool.getUserName(token); + if (userName != null) { + strike = userName; + } + } + return testSuitesService.runSuite(id, strike); + } + + @WebAspect + @ApiOperation(value = "停止测试套件运行", notes = "停止测试套件运行") + @ApiImplicitParam(name = "resultId", value = "测试结果Id", dataTypeClass = Integer.class) + @GetMapping("/forceStopSuite") + public RespModel forceStopSuite(@RequestParam(name = "resultId") int resultId + , HttpServletRequest request) { + String strike = "SYSTEM"; + if (request.getHeader("SonicToken") != null) { + String token = request.getHeader("SonicToken"); + String userName = jwtTokenTool.getUserName(token); + if (userName != null) { + strike = userName; + } + } + return testSuitesService.forceStopSuite(resultId, strike); + } + + + @WebAspect + @ApiOperation(value = "删除测试套件", notes = "删除指定id的测试套件") + @ApiImplicitParam(name = "id", value = "测试套件id", dataTypeClass = Integer.class) + @DeleteMapping + public RespModel delete(@RequestParam(name = "id") int id) { + if (testSuitesService.delete(id)) { + return new RespModel<>(RespEnum.DELETE_OK); + } else { + return new RespModel<>(RespEnum.ID_NOT_FOUND); + } + } + + @WebAspect + @ApiOperation(value = "更新测试套件", notes = "更新或新增测试套件") + @PutMapping + public RespModel save(@Validated @RequestBody TestSuitesDTO testSuitesDTO) { + testSuitesService.saveTestSuites(testSuitesDTO); + return new RespModel<>(RespEnum.UPDATE_OK); + } + + @WebAspect + @ApiOperation(value = "查询测试套件列表", notes = "用于查询对应项目id下的测试套件列表") + @ApiImplicitParam(name = "projectId", value = "项目id", dataTypeClass = Integer.class) + @GetMapping("/list") + public RespModel> findByProjectId(@RequestParam(name = "projectId") int projectId + , @RequestParam(name = "name") String name + , @RequestParam(name = "page") int page + , @RequestParam(name = "pageSize") int pageSize) { + Page pageable = new Page<>(page, pageSize); + return new RespModel<>(RespEnum.SEARCH_OK, testSuitesService.findByProjectId(projectId, name, pageable)); + } + + @WebAspect + @ApiOperation(value = "查询测试套件列表", notes = "用于查询对应项目id下的测试套件列表(不分页)") + @ApiImplicitParam(name = "projectId", value = "项目id", dataTypeClass = Integer.class) + @GetMapping("/listAll") + public RespModel> findByProjectId(@RequestParam(name = "projectId") int projectId) { + return new RespModel<>(RespEnum.SEARCH_OK, testSuitesService.findByProjectId(projectId)); + } + + @WebAspect + @ApiOperation(value = "测试套件详情", notes = "查看测试套件的配置信息详情") + @ApiImplicitParam(name = "id", value = "测试套件id", dataTypeClass = Integer.class) + @GetMapping + public RespModel findById(@RequestParam(name = "id") int id) { + TestSuitesDTO testSuitesDTO = testSuitesService.findById(id); + if (testSuitesDTO != null) { + return new RespModel<>(RespEnum.SEARCH_OK, testSuitesDTO); + } else { + return new RespModel<>(RespEnum.ID_NOT_FOUND); + } + } +} diff --git a/sonic-server-controller/src/main/java/com/sonic/controller/controller/UsersController.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/controller/UsersController.java similarity index 52% rename from sonic-server-controller/src/main/java/com/sonic/controller/controller/UsersController.java rename to sonic-server-controller/src/main/java/org/cloud/sonic/controller/controller/UsersController.java index c259bf43..ceb9bc37 100644 --- a/sonic-server-controller/src/main/java/com/sonic/controller/controller/UsersController.java +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/controller/UsersController.java @@ -1,74 +1,74 @@ -package com.sonic.controller.controller; - -import com.sonic.common.config.WebAspect; -import com.sonic.common.exception.SonicException; -import com.sonic.common.http.RespEnum; -import com.sonic.common.http.RespModel; -import com.sonic.controller.models.Users; -import com.sonic.controller.models.http.ChangePwd; -import com.sonic.controller.models.http.UserInfo; -import com.sonic.controller.services.UsersService; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.validation.annotation.Validated; -import org.springframework.web.bind.annotation.*; - -import javax.servlet.http.HttpServletRequest; - -/** - * @author ZhouYiXun - * @des - * @date 2021/10/13 19:05 - */ -@Api(tags = "用户体系相关") -@RestController -@RequestMapping("/users") -public class UsersController { - @Autowired - private UsersService usersService; - - @WebAspect - @ApiOperation(value = "登录", notes = "用户登录") - @PostMapping("/login") - public RespModel login(@Validated @RequestBody UserInfo userInfo) { - String token = usersService.login(userInfo); - if (token != null) { - return new RespModel(2000, "登录成功!", token); - } else { - return new RespModel(2001, "登录失败!"); - } - } - - @WebAspect - @ApiOperation(value = "注册", notes = "注册用户") - @PostMapping("/register") - public RespModel register(@Validated @RequestBody Users users) throws SonicException { - usersService.register(users); - return new RespModel(2000, "注册成功!"); - } - - @WebAspect - @ApiOperation(value = "获取用户信息", notes = "获取token的用户信息") - @GetMapping - public RespModel getUserInfo(HttpServletRequest request) { - if (request.getHeader("SonicToken") != null) { - String token = request.getHeader("SonicToken"); - return new RespModel(RespEnum.SEARCH_OK, usersService.getUserInfo(token)); - } else { - return new RespModel(RespEnum.UNAUTHORIZED); - } - } - - @WebAspect - @ApiOperation(value = "修改密码", notes = "修改token的用户密码") - @PutMapping - public RespModel changePwd(HttpServletRequest request, @Validated @RequestBody ChangePwd changePwd) { - if (request.getHeader("SonicToken") != null) { - String token = request.getHeader("SonicToken"); - return usersService.resetPwd(token, changePwd); - } else { - return new RespModel(RespEnum.UNAUTHORIZED); - } - } -} +package org.cloud.sonic.controller.controller; + +import org.cloud.sonic.common.config.WebAspect; +import org.cloud.sonic.common.exception.SonicException; +import org.cloud.sonic.common.http.RespEnum; +import org.cloud.sonic.common.http.RespModel; +import org.cloud.sonic.controller.models.dto.UsersDTO; +import org.cloud.sonic.controller.models.http.ChangePwd; +import org.cloud.sonic.controller.models.http.UserInfo; +import org.cloud.sonic.controller.services.UsersService; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.*; + +import javax.servlet.http.HttpServletRequest; + +/** + * @author ZhouYiXun + * @des + * @date 2021/10/13 19:05 + */ +@Api(tags = "用户体系相关") +@RestController +@RequestMapping("/users") +public class UsersController { + @Autowired + private UsersService usersService; + + @WebAspect + @ApiOperation(value = "登录", notes = "用户登录") + @PostMapping("/login") + public RespModel login(@Validated @RequestBody UserInfo userInfo) { + String token = usersService.login(userInfo); + if (token != null) { + return new RespModel<>(2000, "登录成功!", token); + } else { + return new RespModel<>(2001, "登录失败!"); + } + } + + @WebAspect + @ApiOperation(value = "注册", notes = "注册用户") + @PostMapping("/register") + public RespModel register(@Validated @RequestBody UsersDTO users) throws SonicException { + usersService.register(users.convertTo()); + return new RespModel<>(2000, "注册成功!"); + } + + @WebAspect + @ApiOperation(value = "获取用户信息", notes = "获取token的用户信息") + @GetMapping + public RespModel getUserInfo(HttpServletRequest request) { + if (request.getHeader("SonicToken") != null) { + String token = request.getHeader("SonicToken"); + return new RespModel<>(RespEnum.SEARCH_OK, usersService.getUserInfo(token).convertTo()); + } else { + return new RespModel<>(RespEnum.UNAUTHORIZED); + } + } + + @WebAspect + @ApiOperation(value = "修改密码", notes = "修改token的用户密码") + @PutMapping + public RespModel changePwd(HttpServletRequest request, @Validated @RequestBody ChangePwd changePwd) { + if (request.getHeader("SonicToken") != null) { + String token = request.getHeader("SonicToken"); + return usersService.resetPwd(token, changePwd); + } else { + return new RespModel<>(RespEnum.UNAUTHORIZED); + } + } +} diff --git a/sonic-server-controller/src/main/java/com/sonic/controller/controller/VersionsController.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/controller/VersionsController.java similarity index 64% rename from sonic-server-controller/src/main/java/com/sonic/controller/controller/VersionsController.java rename to sonic-server-controller/src/main/java/org/cloud/sonic/controller/controller/VersionsController.java index 56358174..bbf7e8b6 100644 --- a/sonic-server-controller/src/main/java/com/sonic/controller/controller/VersionsController.java +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/controller/VersionsController.java @@ -1,64 +1,65 @@ -package com.sonic.controller.controller; - -import com.sonic.common.config.WebAspect; -import com.sonic.common.http.RespEnum; -import com.sonic.common.http.RespModel; -import com.sonic.controller.models.Versions; -import com.sonic.controller.services.VersionsService; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiImplicitParam; -import io.swagger.annotations.ApiOperation; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.validation.annotation.Validated; -import org.springframework.web.bind.annotation.*; - -import java.util.List; - -@Api(tags = "版本迭代相关") -@RestController -@RequestMapping("/versions") -public class VersionsController { - @Autowired - private VersionsService versionsService; - - @WebAspect - @ApiOperation(value = "更新版本迭代", notes = "新增或更改版本迭代信息") - @PutMapping - public RespModel save(@Validated @RequestBody Versions versions) { - versionsService.save(versions); - return new RespModel(RespEnum.UPDATE_OK); - } - - @WebAspect - @ApiOperation(value = "查询版本迭代列表", notes = "用于查询对应项目id下的版本迭代列表") - @ApiImplicitParam(name = "projectId", value = "项目id", dataTypeClass = Integer.class) - @GetMapping("/list") - public RespModel> findByProjectId(@RequestParam(name = "projectId") int projectId) { - return new RespModel(RespEnum.SEARCH_OK, versionsService.findByProjectId(projectId)); - } - - @WebAspect - @ApiOperation(value = "删除版本迭代", notes = "删除指定id的版本迭代") - @ApiImplicitParam(name = "id", value = "版本迭代id", dataTypeClass = Integer.class) - @DeleteMapping - public RespModel delete(@RequestParam(name = "id") int id) { - if (versionsService.delete(id)) { - return new RespModel(RespEnum.DELETE_OK); - } else { - return new RespModel(RespEnum.ID_NOT_FOUND); - } - } - - @WebAspect - @ApiOperation(value = "查询版本迭代信息", notes = "查询指定id的版本迭代的详细信息") - @ApiImplicitParam(name = "id", value = "版本迭代id", dataTypeClass = Integer.class) - @GetMapping - public RespModel findById(@RequestParam(name = "id") int id) { - Versions versions = versionsService.findById(id); - if (versions != null) { - return new RespModel(RespEnum.SEARCH_OK, versions); - } else { - return new RespModel(RespEnum.ID_NOT_FOUND); - } - } -} +package org.cloud.sonic.controller.controller; + +import org.cloud.sonic.common.config.WebAspect; +import org.cloud.sonic.common.http.RespEnum; +import org.cloud.sonic.common.http.RespModel; +import org.cloud.sonic.controller.models.domain.Versions; +import org.cloud.sonic.controller.models.dto.VersionsDTO; +import org.cloud.sonic.controller.services.VersionsService; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiImplicitParam; +import io.swagger.annotations.ApiOperation; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +@Api(tags = "版本迭代相关") +@RestController +@RequestMapping("/versions") +public class VersionsController { + @Autowired + private VersionsService versionsService; + + @WebAspect + @ApiOperation(value = "更新版本迭代", notes = "新增或更改版本迭代信息") + @PutMapping + public RespModel save(@Validated @RequestBody VersionsDTO versionsDTO) { + versionsService.save(versionsDTO.convertTo()); + return new RespModel<>(RespEnum.UPDATE_OK); + } + + @WebAspect + @ApiOperation(value = "查询版本迭代列表", notes = "用于查询对应项目id下的版本迭代列表") + @ApiImplicitParam(name = "projectId", value = "项目id", dataTypeClass = Integer.class) + @GetMapping("/list") + public RespModel> findByProjectId(@RequestParam(name = "projectId") int projectId) { + return new RespModel<>(RespEnum.SEARCH_OK, versionsService.findByProjectId(projectId)); + } + + @WebAspect + @ApiOperation(value = "删除版本迭代", notes = "删除指定id的版本迭代") + @ApiImplicitParam(name = "id", value = "版本迭代id", dataTypeClass = Integer.class) + @DeleteMapping + public RespModel delete(@RequestParam(name = "id") int id) { + if (versionsService.delete(id)) { + return new RespModel<>(RespEnum.DELETE_OK); + } else { + return new RespModel<>(RespEnum.ID_NOT_FOUND); + } + } + + @WebAspect + @ApiOperation(value = "查询版本迭代信息", notes = "查询指定id的版本迭代的详细信息") + @ApiImplicitParam(name = "id", value = "版本迭代id", dataTypeClass = Integer.class) + @GetMapping + public RespModel findById(@RequestParam(name = "id") int id) { + Versions versions = versionsService.findById(id); + if (versions != null) { + return new RespModel<>(RespEnum.SEARCH_OK, versions); + } else { + return new RespModel<>(RespEnum.ID_NOT_FOUND); + } + } +} diff --git a/sonic-server-controller/src/main/java/com/sonic/controller/feign/TransportFeignClient.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/feign/TransportFeignClient.java similarity index 77% rename from sonic-server-controller/src/main/java/com/sonic/controller/feign/TransportFeignClient.java rename to sonic-server-controller/src/main/java/org/cloud/sonic/controller/feign/TransportFeignClient.java index d2c4dbcd..8ee404ea 100644 --- a/sonic-server-controller/src/main/java/com/sonic/controller/feign/TransportFeignClient.java +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/feign/TransportFeignClient.java @@ -1,20 +1,20 @@ -package com.sonic.controller.feign; - -import com.alibaba.fastjson.JSONObject; -import com.sonic.common.http.RespModel; -import com.sonic.controller.feign.fallback.TransportFeignClientFallBack; -import org.springframework.cloud.openfeign.FeignClient; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestBody; - -/** - * @author ZhouYiXun - * @des 通过feign负载均衡调用transport模块接口 - * @date 2021/8/21 16:51 - */ -@FeignClient(value = "sonic-server-transport", fallback = TransportFeignClientFallBack.class) -public interface TransportFeignClient { - - @PostMapping("/exchange/sendTestData") - RespModel sendTestData(@RequestBody JSONObject jsonObject); -} +package org.cloud.sonic.controller.feign; + +import com.alibaba.fastjson.JSONObject; +import org.cloud.sonic.common.http.RespModel; +import org.cloud.sonic.controller.feign.fallback.TransportFeignClientFallBack; +import org.springframework.cloud.openfeign.FeignClient; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; + +/** + * @author ZhouYiXun + * @des 通过feign负载均衡调用transport模块接口 + * @date 2021/8/21 16:51 + */ +@FeignClient(value = "sonic-server-transport", fallback = TransportFeignClientFallBack.class) +public interface TransportFeignClient { + + @PostMapping("/exchange/sendTestData") + RespModel sendTestData(@RequestBody JSONObject jsonObject); +} diff --git a/sonic-server-controller/src/main/java/com/sonic/controller/feign/fallback/TransportFeignClientFallBack.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/feign/fallback/TransportFeignClientFallBack.java similarity index 66% rename from sonic-server-controller/src/main/java/com/sonic/controller/feign/fallback/TransportFeignClientFallBack.java rename to sonic-server-controller/src/main/java/org/cloud/sonic/controller/feign/fallback/TransportFeignClientFallBack.java index 6d1f1194..363bca28 100644 --- a/sonic-server-controller/src/main/java/com/sonic/controller/feign/fallback/TransportFeignClientFallBack.java +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/feign/fallback/TransportFeignClientFallBack.java @@ -1,21 +1,21 @@ -package com.sonic.controller.feign.fallback; - -import com.alibaba.fastjson.JSONObject; -import com.sonic.common.http.RespEnum; -import com.sonic.common.http.RespModel; -import com.sonic.controller.feign.TransportFeignClient; -import org.springframework.stereotype.Component; - -/** - * @author ZhouYiXun - * @des 熔断降级类 - * @date 2021/8/21 16:51 - */ -@Component -public class TransportFeignClientFallBack implements TransportFeignClient { - - @Override - public RespModel sendTestData(JSONObject jsonObject) { - return new RespModel(RespEnum.SERVICE_NOT_FOUND); - } -} +package org.cloud.sonic.controller.feign.fallback; + +import com.alibaba.fastjson.JSONObject; +import org.cloud.sonic.common.http.RespEnum; +import org.cloud.sonic.common.http.RespModel; +import org.cloud.sonic.controller.feign.TransportFeignClient; +import org.springframework.stereotype.Component; + +/** + * @author ZhouYiXun + * @des 熔断降级类 + * @date 2021/8/21 16:51 + */ +@Component +public class TransportFeignClientFallBack implements TransportFeignClient { + + @Override + public RespModel sendTestData(JSONObject jsonObject) { + return new RespModel(RespEnum.SERVICE_NOT_FOUND); + } +} diff --git a/sonic-server-controller/src/main/java/org/cloud/sonic/controller/mapper/AgentsMapper.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/mapper/AgentsMapper.java new file mode 100644 index 00000000..9d98ba49 --- /dev/null +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/mapper/AgentsMapper.java @@ -0,0 +1,15 @@ +package org.cloud.sonic.controller.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import org.cloud.sonic.controller.models.domain.Agents; +import org.apache.ibatis.annotations.Mapper; + +/** + * Mapper 接口 + * @author JayWenStar + * @since 2021-12-17 + */ +@Mapper +public interface AgentsMapper extends BaseMapper { + +} diff --git a/sonic-server-controller/src/main/java/org/cloud/sonic/controller/mapper/DevicesMapper.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/mapper/DevicesMapper.java new file mode 100644 index 00000000..373f9965 --- /dev/null +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/mapper/DevicesMapper.java @@ -0,0 +1,34 @@ +package org.cloud.sonic.controller.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import org.cloud.sonic.controller.models.domain.Devices; +import org.cloud.sonic.controller.models.params.DevicesSearchParams; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; +import org.apache.ibatis.annotations.Select; +import org.springframework.lang.NonNull; + +import java.util.List; + +/** + * Mapper 接口 + * @author JayWenStar + * @since 2021-12-17 + */ +@Mapper +public interface DevicesMapper extends BaseMapper { + + @Select("select cpu from devices group by cpu") + List findCpuList(); + + @Select("select size from devices group by size") + List findSizeList(); + + @Select("select d.* from test_suites_devices tsd inner join devices d on d.id = tsd.devices_id where tsd.test_suites_id = #{TestSuitesId}") + List listByTestSuitesId(@Param("TestSuitesId") int TestSuitesId); + + Integer findTemper(@Param("ids") List ids); + + Page findByParams(@NonNull Page page, @Param("params") DevicesSearchParams params); +} diff --git a/sonic-server-controller/src/main/java/org/cloud/sonic/controller/mapper/ElementsMapper.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/mapper/ElementsMapper.java new file mode 100644 index 00000000..11a0fdf6 --- /dev/null +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/mapper/ElementsMapper.java @@ -0,0 +1,27 @@ +package org.cloud.sonic.controller.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import org.cloud.sonic.controller.models.domain.Elements; +import org.cloud.sonic.controller.models.dto.ElementsDTO; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; +import org.apache.ibatis.annotations.Select; + +import java.util.List; +import java.util.Set; + +/** + * Mapper 接口 + * @author JayWenStar + * @since 2021-12-17 + */ +@Mapper +public interface ElementsMapper extends BaseMapper { + + List listElementsByStepsIds(@Param("stepIds") Set stepIds); + + @Select("select e.* from steps_elements se " + + "inner join elements e on se.elements_id = e.id " + + "where se.steps_id = #{stepId}") + List listElementsByStepsId(@Param("stepId") Integer stepId); +} diff --git a/sonic-server-controller/src/main/java/org/cloud/sonic/controller/mapper/GlobalParamsMapper.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/mapper/GlobalParamsMapper.java new file mode 100644 index 00000000..61076ba4 --- /dev/null +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/mapper/GlobalParamsMapper.java @@ -0,0 +1,15 @@ +package org.cloud.sonic.controller.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import org.cloud.sonic.controller.models.domain.GlobalParams; +import org.apache.ibatis.annotations.Mapper; + +/** + * Mapper 接口 + * @author JayWenStar + * @since 2021-12-17 + */ +@Mapper +public interface GlobalParamsMapper extends BaseMapper { + +} diff --git a/sonic-server-controller/src/main/java/org/cloud/sonic/controller/mapper/ModulesMapper.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/mapper/ModulesMapper.java new file mode 100644 index 00000000..2dde4edb --- /dev/null +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/mapper/ModulesMapper.java @@ -0,0 +1,15 @@ +package org.cloud.sonic.controller.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import org.cloud.sonic.controller.models.domain.Modules; +import org.apache.ibatis.annotations.Mapper; + +/** + * Mapper 接口 + * @author JayWenStar + * @since 2021-12-17 + */ +@Mapper +public interface ModulesMapper extends BaseMapper { + +} diff --git a/sonic-server-controller/src/main/java/org/cloud/sonic/controller/mapper/ProjectsMapper.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/mapper/ProjectsMapper.java new file mode 100644 index 00000000..20ff9043 --- /dev/null +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/mapper/ProjectsMapper.java @@ -0,0 +1,15 @@ +package org.cloud.sonic.controller.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import org.cloud.sonic.controller.models.domain.Projects; +import org.apache.ibatis.annotations.Mapper; + +/** + * Mapper 接口 + * @author JayWenStar + * @since 2021-12-17 + */ +@Mapper +public interface ProjectsMapper extends BaseMapper { + +} diff --git a/sonic-server-controller/src/main/java/org/cloud/sonic/controller/mapper/PublicStepsMapper.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/mapper/PublicStepsMapper.java new file mode 100644 index 00000000..183a514a --- /dev/null +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/mapper/PublicStepsMapper.java @@ -0,0 +1,31 @@ +package org.cloud.sonic.controller.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import org.cloud.sonic.controller.models.domain.PublicSteps; +import org.cloud.sonic.controller.models.dto.StepsDTO; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; +import org.apache.ibatis.annotations.Select; + +import java.util.Collection; +import java.util.List; +import java.util.Map; + +/** + * Mapper 接口 + * @author JayWenStar + * @since 2021-12-17 + */ +@Mapper +public interface PublicStepsMapper extends BaseMapper { + + List listStepsByPublicStepsIds(@Param("publicStepsIds") Collection publicStepsIds); + + @Select("select ps.* from public_steps_steps pss " + + "inner join public_steps ps on ps.id = pss.public_steps_id " + + "where pss.steps_id = #{stepId}") + List listPubStepsByStepId(@Param("stepId") int stepId); + + @Select("select id,name from public_steps where project_id=#{projectId} and platform=#{platform} order by id desc") + List> findByProjectIdAndPlatform(@Param("projectId") int projectId, @Param("platform") int platform); +} diff --git a/sonic-server-controller/src/main/java/org/cloud/sonic/controller/mapper/PublicStepsStepsMapper.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/mapper/PublicStepsStepsMapper.java new file mode 100644 index 00000000..ab5af173 --- /dev/null +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/mapper/PublicStepsStepsMapper.java @@ -0,0 +1,15 @@ +package org.cloud.sonic.controller.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import org.cloud.sonic.controller.models.domain.PublicStepsSteps; +import org.apache.ibatis.annotations.Mapper; + +/** + * Mapper 接口 + * @author JayWenStar + * @since 2021-12-17 + */ +@Mapper +public interface PublicStepsStepsMapper extends BaseMapper { + +} diff --git a/sonic-server-controller/src/main/java/org/cloud/sonic/controller/mapper/ResultDetailMapper.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/mapper/ResultDetailMapper.java new file mode 100644 index 00000000..2e6c6f7c --- /dev/null +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/mapper/ResultDetailMapper.java @@ -0,0 +1,46 @@ +package org.cloud.sonic.controller.mapper; + +import com.alibaba.fastjson.JSONObject; +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import org.cloud.sonic.controller.models.domain.ResultDetail; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; +import org.apache.ibatis.annotations.Select; + +import java.util.List; + +/** + * Mapper 接口 + * @author JayWenStar + * @since 2021-12-17 + */ +@Mapper +public interface ResultDetailMapper extends BaseMapper { + + @Select("select case_id, max(time) as endTime,min(time) as startTime from result_detail " + + "where result_id=#{resultId} and type = 'step' group by case_id") + List findTimeByResultIdGroupByCaseId(@Param("resultId") int resultId); + + @Select("select t2.device_id, t2.case_id, IFNULL(t1.status,4) as status " + + "from (select case_id, device_id, status from result_detail where result_id=#{resultId} and type = 'status')t1" + + " right join" + + "(select case_id, device_id from result_detail where result_id=#{resultId} and type = 'step' group by case_id, device_id)t2" + + " on t1.device_id = t2.device_id and t1.case_id = t2.case_id") + List findStatusByResultIdGroupByCaseId(@Param("resultId") int resultId); + + @Select("select t.case_id,sum(t.diff) as total from (select case_id,result_id,TIMESTAMPDIFF(SECOND,min(time),max(time)) as diff " + + "from result_detail where result_id in " + + "(select id from results where end_time > #{startTime} and end_time <= #{endTime} and project_id=#{projectId}) " + + "and type='step' group by result_id,case_id)t group by t.case_id order by total desc limit 5") + List findTopCases(@Param("startTime") String startTime, + @Param("endTime") String endTime, + @Param("projectId") int projectId); + + @Select("select t.device_id,sum(t.diff) as total from (select device_id,case_id,result_id,TIMESTAMPDIFF(SECOND,min(time),max(time)) as diff " + + "from result_detail where result_id in " + + "(select id from results where end_time > #{startTime} and end_time <= #{endTime} and project_id = #{projectId}) " + + "and type='step' group by result_id,case_id,device_id)t group by t.device_id order by total desc limit 5") + List findTopDevices(@Param("startTime") String startTime, + @Param("endTime") String endTime, + @Param("projectId") int projectId); +} diff --git a/sonic-server-controller/src/main/java/org/cloud/sonic/controller/mapper/ResultsMapper.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/mapper/ResultsMapper.java new file mode 100644 index 00000000..a0f8e022 --- /dev/null +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/mapper/ResultsMapper.java @@ -0,0 +1,41 @@ +package org.cloud.sonic.controller.mapper; + +import com.alibaba.fastjson.JSONObject; +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import org.cloud.sonic.controller.models.domain.Results; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; +import org.apache.ibatis.annotations.Select; + +import java.util.List; + +/** + * Mapper 接口 + * @author JayWenStar + * @since 2021-12-17 + */ +@Mapper +public interface ResultsMapper extends BaseMapper { + + @Select("select t2.date,round(IFNULL((t1.count/t2.count),0)*100,2) as rate from " + + "(select DATE_FORMAT(end_time,'%Y-%m-%d') as date,count(status) as count from results where end_time > #{startTime} and end_time <= #{endTime} and project_id=#{projectId} and status=1 " + + "group by status,DATE_FORMAT(end_time,'%Y-%m-%d'))t1 " + + "right join" + + "(select DATE_FORMAT(end_time,'%Y-%m-%d') as date,count(status) as count from results where end_time > #{startTime} and end_time <= #{endTime} and project_id=#{projectId} " + + "group by DATE_FORMAT(end_time,'%Y-%m-%d'))t2 " + + "on t1.date = t2.date") + List findDayPassRate(@Param("startTime") String startTime, + @Param("endTime") String endTime, + @Param("projectId") int projectId); + + @Select("select status,count(*) as total from results where end_time > #{startTime} and end_time<= #{endTime} and project_id=#{projectId} group by status") + List findDayStatus(@Param("startTime") String startTime, + @Param("endTime") String endTime, + @Param("projectId") int projectId); + + @Select("select count(*) as total from results where end_time > #{startTime} and end_time <= #{endTime} and project_id=#{projectId}") + int findRunCount(@Param("startTime") String startTime, + @Param("endTime") String endTime, + @Param("projectId") int projectId); + +} diff --git a/sonic-server-controller/src/main/java/org/cloud/sonic/controller/mapper/StepsElementsMapper.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/mapper/StepsElementsMapper.java new file mode 100644 index 00000000..adc39eb6 --- /dev/null +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/mapper/StepsElementsMapper.java @@ -0,0 +1,15 @@ +package org.cloud.sonic.controller.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import org.cloud.sonic.controller.models.domain.StepsElements; +import org.apache.ibatis.annotations.Mapper; + +/** + * Mapper 接口 + * @author JayWenStar + * @since 2021-12-17 + */ +@Mapper +public interface StepsElementsMapper extends BaseMapper { + +} diff --git a/sonic-server-controller/src/main/java/org/cloud/sonic/controller/mapper/StepsMapper.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/mapper/StepsMapper.java new file mode 100644 index 00000000..4129c7a6 --- /dev/null +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/mapper/StepsMapper.java @@ -0,0 +1,30 @@ +package org.cloud.sonic.controller.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import org.cloud.sonic.controller.models.domain.Steps; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; +import org.apache.ibatis.annotations.Select; + +import java.util.List; + +/** + * Mapper 接口 + * @author JayWenStar + * @since 2021-12-17 + */ +@Mapper +public interface StepsMapper extends BaseMapper { + + @Select("select IFNULL(max(sort),0) from steps") + int findMaxSort(); + + @Select("select s.* from steps_elements as se inner join steps as s on se.steps_id = s.id where se.elements_id = #{elementsId}") + List listStepsByElementId(@Param("elementsId") int elementsId); + + @Select("select s.* from public_steps_steps pss " + + "inner join steps s on pss.steps_id = s.id " + + "where pss.public_steps_id = #{publicStepsId}") + List listByPublicStepsId(@Param("publicStepsId") int publicStepsId); + +} diff --git a/sonic-server-controller/src/main/java/org/cloud/sonic/controller/mapper/TestCasesMapper.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/mapper/TestCasesMapper.java new file mode 100644 index 00000000..f150b578 --- /dev/null +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/mapper/TestCasesMapper.java @@ -0,0 +1,23 @@ +package org.cloud.sonic.controller.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import org.cloud.sonic.controller.models.domain.TestCases; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; +import org.apache.ibatis.annotations.Select; + +import java.util.List; + +/** + * Mapper 接口 + * @author JayWenStar + * @since 2021-12-17 + */ +@Mapper +public interface TestCasesMapper extends BaseMapper { + + @Select("select tc.* from test_suites_test_cases tstc " + + "inner join test_cases tc on tc.id = tstc.test_cases_id " + + "where tstc.test_suites_id = #{suiteId}") + List listByTestSuitesId(@Param("suiteId") int suiteId); +} diff --git a/sonic-server-controller/src/main/java/org/cloud/sonic/controller/mapper/TestSuitesDevicesMapper.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/mapper/TestSuitesDevicesMapper.java new file mode 100644 index 00000000..9dd1ba7d --- /dev/null +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/mapper/TestSuitesDevicesMapper.java @@ -0,0 +1,15 @@ +package org.cloud.sonic.controller.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import org.cloud.sonic.controller.models.domain.TestSuitesDevices; +import org.apache.ibatis.annotations.Mapper; + +/** + * Mapper 接口 + * @author JayWenStar + * @since 2021-12-17 + */ +@Mapper +public interface TestSuitesDevicesMapper extends BaseMapper { + +} diff --git a/sonic-server-controller/src/main/java/org/cloud/sonic/controller/mapper/TestSuitesMapper.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/mapper/TestSuitesMapper.java new file mode 100644 index 00000000..c088687f --- /dev/null +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/mapper/TestSuitesMapper.java @@ -0,0 +1,15 @@ +package org.cloud.sonic.controller.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import org.cloud.sonic.controller.models.domain.TestSuites; +import org.apache.ibatis.annotations.Mapper; + +/** + * Mapper 接口 + * @author JayWenStar + * @since 2021-12-17 + */ +@Mapper +public interface TestSuitesMapper extends BaseMapper { + +} diff --git a/sonic-server-controller/src/main/java/org/cloud/sonic/controller/mapper/TestSuitesTestCasesMapper.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/mapper/TestSuitesTestCasesMapper.java new file mode 100644 index 00000000..3d6f09eb --- /dev/null +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/mapper/TestSuitesTestCasesMapper.java @@ -0,0 +1,23 @@ +package org.cloud.sonic.controller.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import org.cloud.sonic.controller.models.domain.TestSuites; +import org.cloud.sonic.controller.models.domain.TestSuitesTestCases; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; +import org.apache.ibatis.annotations.Select; + +import java.util.List; + +/** + * Mapper 接口 + * @author JayWenStar + * @since 2021-12-17 + */ +@Mapper +public interface TestSuitesTestCasesMapper extends BaseMapper { + + @Select("select ts.* from test_suites_test_cases tetc inner join test_suites ts on tetc.test_suites_id = ts.id where ts.id = #{testCasesId}") + List listTestSuitesByTestCasesId(@Param("testCasesId") int testCasesId); + +} diff --git a/sonic-server-controller/src/main/java/org/cloud/sonic/controller/mapper/UsersMapper.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/mapper/UsersMapper.java new file mode 100644 index 00000000..425a19c8 --- /dev/null +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/mapper/UsersMapper.java @@ -0,0 +1,15 @@ +package org.cloud.sonic.controller.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import org.cloud.sonic.controller.models.domain.Users; +import org.apache.ibatis.annotations.Mapper; + +/** + * Mapper 接口 + * @author JayWenStar + * @since 2021-12-17 + */ +@Mapper +public interface UsersMapper extends BaseMapper { + +} diff --git a/sonic-server-controller/src/main/java/org/cloud/sonic/controller/mapper/VersionsMapper.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/mapper/VersionsMapper.java new file mode 100644 index 00000000..5d57d1bf --- /dev/null +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/mapper/VersionsMapper.java @@ -0,0 +1,15 @@ +package org.cloud.sonic.controller.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import org.cloud.sonic.controller.models.domain.Versions; +import org.apache.ibatis.annotations.Mapper; + +/** + * Mapper 接口 + * @author JayWenStar + * @since 2021-12-17 + */ +@Mapper +public interface VersionsMapper extends BaseMapper { + +} diff --git a/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/base/CommentPage.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/base/CommentPage.java new file mode 100644 index 00000000..034d4087 --- /dev/null +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/base/CommentPage.java @@ -0,0 +1,66 @@ +package org.cloud.sonic.controller.models.base; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; + +/** + * 通用分页对象 + * + * @author JayWenStar + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +public class CommentPage implements Serializable { + + /** + * 页大小 + */ + private long size; + + /** + * 页内容 + */ + private List content; + + /** + * 当前页码 + */ + private long number; + + /** + * 页内容总个数 + */ + private long totalElements; + + /** + * 总页数 + */ + private long totalPages; + + public static CommentPage convertFrom(Page page) { + return new CommentPage<>( + page.getSize(), page.getRecords(), page.getCurrent() - 1, page.getTotal(), page.getPages() + ); + } + + /** + * Page的数据会被content替代 + */ + public static CommentPage convertFrom(Page page, List content) { + return new CommentPage<>( + page.getSize(), content, page.getCurrent() - 1, page.getTotal(), page.getPages() + ); + } + + + public static CommentPage emptyPage() { + return new CommentPage<>(0, new ArrayList<>(), 0, 0, 0); + } +} diff --git a/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/base/TypeConverter.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/base/TypeConverter.java new file mode 100644 index 00000000..0427a188 --- /dev/null +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/base/TypeConverter.java @@ -0,0 +1,74 @@ +package org.cloud.sonic.controller.models.base; + +import org.cloud.sonic.common.tools.BeanTool; +import org.cloud.sonic.common.tools.ReflectionTool; +import org.springframework.lang.NonNull; +import org.springframework.lang.Nullable; + +import java.lang.reflect.ParameterizedType; +import java.util.Objects; + +import static org.cloud.sonic.common.tools.BeanTool.updateProperties; + +/** + * 映射dto与domain关系 + * @param + * @param + */ + +public interface TypeConverter, TARGET> { + + /** + * Convert from target.(shallow) + * + * @param target target data + * @return converted current data + */ + @SuppressWarnings("unchecked") + @NonNull + default CURRENT convertFrom(@NonNull TARGET target) { + + updateProperties(target, this); + + return (CURRENT) this; + } + + /** + * Convert to target.(shallow) + * + * @return new target with same value(not null) + */ + @SuppressWarnings("unchecked") + default TARGET convertTo() { + // Get parameterized type + ParameterizedType currentType = parameterizedType(); + + // Assert not equal + Objects.requireNonNull(currentType, "Cannot fetch actual type because parameterized type is null"); + + Class domainClass = (Class) currentType.getActualTypeArguments()[1]; + + return BeanTool.transformFrom(this, domainClass); + } + + /** + * Update a target by current.(shallow) + * + * @param target updated target + */ + default void update(TARGET target) { + BeanTool.updateProperties(this, target); + } + + + /** + * Get parameterized type. + * + * @return parameterized type or null + */ + @Nullable + default ParameterizedType parameterizedType() { + return ReflectionTool.getParameterizedType(TypeConverter.class, this.getClass()); + } + +} diff --git a/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/domain/Agents.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/domain/Agents.java new file mode 100644 index 00000000..f0aa4d68 --- /dev/null +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/domain/Agents.java @@ -0,0 +1,68 @@ +package org.cloud.sonic.controller.models.domain; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import com.gitee.sunchenbin.mybatis.actable.annotation.*; +import com.gitee.sunchenbin.mybatis.actable.constants.MySqlCharsetConstant; +import com.gitee.sunchenbin.mybatis.actable.constants.MySqlEngineConstant; +import org.cloud.sonic.controller.models.base.TypeConverter; +import org.cloud.sonic.controller.models.dto.AgentsDTO; +import io.swagger.annotations.ApiModel; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; + +import java.io.Serializable; + +/** + * @author JayWenStar,Eason + * @since 2021-12-17 + */ +@ApiModel(value = "Agents对象", description = "") +@Data +@Accessors(chain = true) +@Builder +@NoArgsConstructor +@AllArgsConstructor +@TableName("agents") +@TableComment("agents表") +@TableCharset(MySqlCharsetConstant.DEFAULT) +@TableEngine(MySqlEngineConstant.InnoDB) +public class Agents implements Serializable, TypeConverter { + + @TableId(value = "id", type = IdType.AUTO) + @IsAutoIncrement + private Integer id; + + @TableField + @Column(isNull = false, comment = "agent的ip") + private String host; + + @TableField + @Column(isNull = false, comment = "agent name") + private String name; + + @TableField + @Column(isNull = false, comment = "agent的端口") + private Integer port; + + @TableField + @Column(value = "secret_key", comment = "agent的密钥", defaultValue = "") + private String secretKey; + + @TableField + @Column(isNull = false, comment = "agent的状态") + private Integer status; + + @TableField + @Column(value = "system_type", isNull = false, comment = "agent的系统类型") + private String systemType; + + @TableField + @Column(isNull = false, comment = "agent端代码版本", defaultValue = "") + private String version; +} diff --git a/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/domain/Devices.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/domain/Devices.java new file mode 100644 index 00000000..ea12f3ef --- /dev/null +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/domain/Devices.java @@ -0,0 +1,105 @@ +package org.cloud.sonic.controller.models.domain; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import com.gitee.sunchenbin.mybatis.actable.annotation.*; +import com.gitee.sunchenbin.mybatis.actable.constants.MySqlCharsetConstant; +import com.gitee.sunchenbin.mybatis.actable.constants.MySqlEngineConstant; +import org.cloud.sonic.controller.models.base.TypeConverter; +import org.cloud.sonic.controller.models.dto.DevicesDTO; +import io.swagger.annotations.ApiModel; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; + +import java.io.Serializable; + +/** + * @author JayWenStar + * @since 2021-12-17 + */ +@ApiModel(value = "Devices对象", description = "") +@Data +@Accessors(chain = true) +@Builder +@NoArgsConstructor +@AllArgsConstructor +@TableName("devices") +@TableComment("设备表") +@TableCharset(MySqlCharsetConstant.DEFAULT) +@TableEngine(MySqlEngineConstant.InnoDB) +public class Devices implements Serializable, TypeConverter { + + @TableId(value = "id", type = IdType.AUTO) + @IsAutoIncrement + private Integer id; + + @TableField + @Column(value = "agent_id", isNull = false, comment = "所属agent的id") + private Integer agentId; + + @TableField + @Column(comment = "cpu架构", defaultValue = "") + private String cpu; + + @TableField + @Column(value = "img_url", comment = "手机封面", defaultValue = "") + private String imgUrl; + + @TableField + @Column(comment = "制造商", defaultValue = "") + private String manufacturer; + + @TableField + @Column(comment = "手机型号", defaultValue = "") + private String model; + + @TableField + @Column(comment = "设备名称", defaultValue = "") + private String name; + + @TableField + @Column(comment = "设备安装app的密码", defaultValue = "") + private String password; + + @TableField + @Column(isNull = false, comment = "系统类型 1:android 2:ios") + private Integer platform; + + @TableField + @Column(comment = "设备分辨率", defaultValue = "") + private String size; + + @TableField + @Column(comment = "设备状态", defaultValue = "") + private String status; + + @TableField + @Column(value = "ud_id", comment = "设备序列号", defaultValue = "") + @Index(value = "IDX_UD_ID", columns = {"ud_id"}) + private String udId; + + @TableField + @Column(comment = "设备系统版本", defaultValue = "") + private String version; + + @TableField + @Column(value = "nick_name", comment = "设备备注", defaultValue = "") + private String nickName; + + @TableField + @Column(comment = "设备当前占用者", defaultValue = "") + private String user; + + @TableField + @Column(value = "chi_name", comment = "中文设备", defaultValue = "") + String chiName; + + @TableField + @Column(defaultValue = "0", comment = "设备温度") + Integer temperature; +} diff --git a/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/domain/Elements.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/domain/Elements.java new file mode 100644 index 00000000..b9c820f7 --- /dev/null +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/domain/Elements.java @@ -0,0 +1,58 @@ +package org.cloud.sonic.controller.models.domain; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import com.gitee.sunchenbin.mybatis.actable.annotation.*; +import com.gitee.sunchenbin.mybatis.actable.constants.MySqlCharsetConstant; +import com.gitee.sunchenbin.mybatis.actable.constants.MySqlEngineConstant; +import com.gitee.sunchenbin.mybatis.actable.constants.MySqlTypeConstant; +import org.cloud.sonic.controller.models.base.TypeConverter; +import org.cloud.sonic.controller.models.dto.ElementsDTO; +import io.swagger.annotations.ApiModel; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; + +import java.io.Serializable; + +/** + * @author JayWenStar + * @since 2021-12-17 + */ +@ApiModel(value = "Elements对象", description = "") +@Data +@Accessors(chain = true) +@Builder +@NoArgsConstructor +@AllArgsConstructor +@TableName("elements") +@TableComment("控件元素表") +@TableCharset(MySqlCharsetConstant.DEFAULT) +@TableEngine(MySqlEngineConstant.InnoDB) +public class Elements implements Serializable, TypeConverter { + + @TableId(value = "id", type = IdType.AUTO) + @IsAutoIncrement + private Integer id; + + @TableField + @Column(value = "ele_name", isNull = false, comment = "控件名称") + private String eleName; + + @TableField + @Column(value = "ele_type", isNull = false, comment = "控件类型") + private String eleType; + + @TableField + @Column(value = "ele_value", type = MySqlTypeConstant.LONGTEXT, comment = "控件内容") + private String eleValue; + + @TableField + @Column(value = "project_id", isNull = false, comment = "所属项目id") + @Index(value = "IDX_PROJECT_ID", columns = {"project_id"}) + private Integer projectId; +} diff --git a/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/domain/GlobalParams.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/domain/GlobalParams.java new file mode 100644 index 00000000..03029e94 --- /dev/null +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/domain/GlobalParams.java @@ -0,0 +1,53 @@ +package org.cloud.sonic.controller.models.domain; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import com.gitee.sunchenbin.mybatis.actable.annotation.*; +import com.gitee.sunchenbin.mybatis.actable.constants.MySqlCharsetConstant; +import com.gitee.sunchenbin.mybatis.actable.constants.MySqlEngineConstant; +import org.cloud.sonic.controller.models.base.TypeConverter; +import org.cloud.sonic.controller.models.dto.GlobalParamsDTO; +import io.swagger.annotations.ApiModel; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; + +import java.io.Serializable; + +/** + * @author JayWenStar + * @since 2021-12-17 + */ +@ApiModel(value = "GlobalParams对象", description = "") +@Data +@Accessors(chain = true) +@Builder +@NoArgsConstructor +@AllArgsConstructor +@TableName("global_params") +@TableComment("全局参数表") +@TableCharset(MySqlCharsetConstant.DEFAULT) +@TableEngine(MySqlEngineConstant.InnoDB) +public class GlobalParams implements Serializable, TypeConverter { + + @TableId(value = "id", type = IdType.AUTO) + @IsAutoIncrement + private Integer id; + + @TableField + @Column(value = "params_key", isNull = false, comment = "参数key") + private String paramsKey; + + @TableField + @Column(value = "params_value", isNull = false, comment = "参数value") + private String paramsValue; + + @TableField + @Column(value = "project_id", isNull = false, comment = "所属项目id") + @Index(value = "IDX_PROJECT_ID", columns = {"project_id"}) + private Integer projectId; +} diff --git a/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/domain/Modules.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/domain/Modules.java new file mode 100644 index 00000000..9ac446e7 --- /dev/null +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/domain/Modules.java @@ -0,0 +1,48 @@ +package org.cloud.sonic.controller.models.domain; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import com.gitee.sunchenbin.mybatis.actable.annotation.*; +import com.gitee.sunchenbin.mybatis.actable.constants.MySqlCharsetConstant; +import com.gitee.sunchenbin.mybatis.actable.constants.MySqlEngineConstant; +import org.cloud.sonic.controller.models.base.TypeConverter; +import org.cloud.sonic.controller.models.dto.ModulesDTO; +import io.swagger.annotations.ApiModel; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; + +import java.io.Serializable; + +/** + * @author JayWenStar + * @since 2021-12-17 + */ +@ApiModel(value = "Modules对象", description = "") +@Data +@Accessors(chain = true) +@Builder +@NoArgsConstructor +@AllArgsConstructor +@TableName("modules") +@TableComment("模块表") +@TableCharset(MySqlCharsetConstant.DEFAULT) +@TableEngine(MySqlEngineConstant.InnoDB) +public class Modules implements Serializable, TypeConverter { + + @TableId(value = "id", type = IdType.AUTO) + @IsAutoIncrement + private Integer id; + + @TableField + private String name; + + @TableField + @Column(value = "project_id", isNull = false, comment = "所属项目名称") + @Index(value = "IDX_PROJECT_ID", columns = {"project_id"}) + private Integer projectId; +} diff --git a/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/domain/Projects.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/domain/Projects.java new file mode 100644 index 00000000..733a8990 --- /dev/null +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/domain/Projects.java @@ -0,0 +1,69 @@ +package org.cloud.sonic.controller.models.domain; + +import com.baomidou.mybatisplus.annotation.*; +import com.fasterxml.jackson.annotation.JsonFormat; +import com.gitee.sunchenbin.mybatis.actable.annotation.*; +import com.gitee.sunchenbin.mybatis.actable.constants.MySqlCharsetConstant; +import com.gitee.sunchenbin.mybatis.actable.constants.MySqlEngineConstant; +import com.gitee.sunchenbin.mybatis.actable.constants.MySqlTypeConstant; +import org.cloud.sonic.controller.models.base.TypeConverter; +import org.cloud.sonic.controller.models.dto.ProjectsDTO; +import io.swagger.annotations.ApiModel; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; + +import java.io.Serializable; +import java.util.Date; + +/** + * @author JayWenStar + * @since 2021-12-17 + */ +@ApiModel(value = "Projects对象", description = "") +@Data +@Accessors(chain = true) +@Builder +@NoArgsConstructor +@AllArgsConstructor +@TableName("projects") +@TableComment("项目表") +@TableCharset(MySqlCharsetConstant.DEFAULT) +@TableEngine(MySqlEngineConstant.InnoDB) +public class Projects implements Serializable, TypeConverter { + + @TableId(value = "id", type = IdType.AUTO) + @IsAutoIncrement + private Integer id; + + @TableField(fill = FieldFill.INSERT_UPDATE) + @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") + @Column(value = "edit_time", type = MySqlTypeConstant.DATETIME, comment = "更改时间") + private Date editTime; + + @TableField + @Column(value = "project_des", isNull = false, comment = "项目描述") + private String projectDes; + + @TableField + @Column(value = "project_img", isNull = false, comment = "项目封面") + private String projectImg; + + @TableField + @Column(value = "project_name", isNull = false, comment = "项目名") + private String projectName; + + @TableField + @Column(value = "robot_secret", isNull = false, comment = "机器人秘钥") + private String robotSecret; + + @TableField + @Column(value = "robot_token", isNull = false, comment = "机器人token") + private String robotToken; + + @TableField + @Column(value = "robot_type", isNull = false, comment = "机器人类型") + private Integer robotType; +} diff --git a/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/domain/PublicSteps.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/domain/PublicSteps.java new file mode 100644 index 00000000..deae6396 --- /dev/null +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/domain/PublicSteps.java @@ -0,0 +1,53 @@ +package org.cloud.sonic.controller.models.domain; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import com.gitee.sunchenbin.mybatis.actable.annotation.*; +import com.gitee.sunchenbin.mybatis.actable.constants.MySqlCharsetConstant; +import com.gitee.sunchenbin.mybatis.actable.constants.MySqlEngineConstant; +import org.cloud.sonic.controller.models.base.TypeConverter; +import org.cloud.sonic.controller.models.dto.PublicStepsDTO; +import io.swagger.annotations.ApiModel; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; + +import java.io.Serializable; + +/** + * @author JayWenStar + * @since 2021-12-17 + */ +@ApiModel(value = "PublicSteps对象", description = "") +@Data +@Accessors(chain = true) +@Builder +@NoArgsConstructor +@AllArgsConstructor +@TableName("public_steps") +@TableComment("公共步骤表") +@TableCharset(MySqlCharsetConstant.DEFAULT) +@TableEngine(MySqlEngineConstant.InnoDB) +public class PublicSteps implements Serializable, TypeConverter { + + @TableId(value = "id", type = IdType.AUTO) + @IsAutoIncrement + private Integer id; + + @TableField + @Column(value = "name", isNull = false, comment = "公共步骤名称") + private String name; + + @TableField + @Column(value = "platform", isNull = false, comment = "公共步骤系统类型(android、ios...)") + private Integer platform; + + @TableField + @Column(value = "project_id", isNull = false, comment = "所属项目id") + @Index(value = "IDX_PROJECT_ID", columns = {"project_id"}) + private Integer projectId; +} diff --git a/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/domain/PublicStepsSteps.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/domain/PublicStepsSteps.java new file mode 100644 index 00000000..7e1aefb4 --- /dev/null +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/domain/PublicStepsSteps.java @@ -0,0 +1,45 @@ +package org.cloud.sonic.controller.models.domain; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableName; +import com.gitee.sunchenbin.mybatis.actable.annotation.Column; +import com.gitee.sunchenbin.mybatis.actable.annotation.TableCharset; +import com.gitee.sunchenbin.mybatis.actable.annotation.TableComment; +import com.gitee.sunchenbin.mybatis.actable.annotation.TableEngine; +import com.gitee.sunchenbin.mybatis.actable.constants.MySqlCharsetConstant; +import com.gitee.sunchenbin.mybatis.actable.constants.MySqlEngineConstant; +import org.cloud.sonic.controller.models.base.TypeConverter; +import org.cloud.sonic.controller.models.dto.PublicStepsStepsDTO; +import io.swagger.annotations.ApiModel; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; + +import java.io.Serializable; + +/** + * @author JayWenStar + * @since 2021-12-17 + */ +@ApiModel(value = "PublicStepsSteps对象", description = "") +@Data +@Accessors(chain = true) +@Builder +@NoArgsConstructor +@AllArgsConstructor +@TableName("public_steps_steps") +@TableComment("公共步骤 - 步骤 关系映射表") +@TableCharset(MySqlCharsetConstant.DEFAULT) +@TableEngine(MySqlEngineConstant.InnoDB) +public class PublicStepsSteps implements Serializable, TypeConverter { + + @TableField + @Column(value = "public_steps_id", isNull = false, comment = "公共步骤id") + private Integer publicStepsId; + + @TableField + @Column(value = "steps_id", isNull = false, comment = "步骤id") + private Integer stepsId; +} diff --git a/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/domain/ResultDetail.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/domain/ResultDetail.java new file mode 100644 index 00000000..bc6fd97f --- /dev/null +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/domain/ResultDetail.java @@ -0,0 +1,84 @@ +package org.cloud.sonic.controller.models.domain; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import com.fasterxml.jackson.annotation.JsonFormat; +import com.gitee.sunchenbin.mybatis.actable.annotation.*; +import com.gitee.sunchenbin.mybatis.actable.constants.MySqlCharsetConstant; +import com.gitee.sunchenbin.mybatis.actable.constants.MySqlEngineConstant; +import com.gitee.sunchenbin.mybatis.actable.constants.MySqlTypeConstant; +import org.cloud.sonic.controller.models.base.TypeConverter; +import org.cloud.sonic.controller.models.dto.ResultDetailDTO; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; + +import java.io.Serializable; +import java.util.Date; + +/** + * @author JayWenStar + * @since 2021-12-17 + */ +@ApiModel(value = "ResultDetail对象", description = "") +@Data +@Accessors(chain = true) +@Builder +@NoArgsConstructor +@AllArgsConstructor +@TableName("result_detail") +@TableComment("任务结果详情表") +@TableCharset(MySqlCharsetConstant.DEFAULT) +@TableEngine(MySqlEngineConstant.InnoDB) +public class ResultDetail implements Serializable, TypeConverter { + + @TableId(value = "id", type = IdType.AUTO) + @IsAutoIncrement + private Integer id; + + @TableField + @Column(value = "case_id", isNull = false, comment = "测试用例id") + private Integer caseId; + + @TableField + @Column(comment = "描述", defaultValue = "") + private String des; + + @TableField + @Column(value = "device_id", isNull = false, comment = "设备id") + private Integer deviceId; + + @TableField + @Column(type = MySqlTypeConstant.LONGTEXT, comment = "日志信息") + private String log; + + @TableField + @Column(value = "result_id", isNull = false, comment = "所属结果id") + @Index( + value = "IDX_RESULT_ID_CASE_ID_TYPE_DEVICE_ID", + columns = {"result_id", "case_id", "type", "device_id"} + ) + private Integer resultId; + + @TableField + @Column(isNull = false, comment = "步骤执行状态") + private Integer status; + + @ApiModelProperty(value = "时间", example = "16:00:00") + @JsonFormat(pattern = "HH:mm:ss", timezone = "GMT+8") + @TableField + @Column(type = MySqlTypeConstant.TIMESTAMP, isNull = false, comment = "步骤执行状态") + @Index(value = "IDX_TIME", columns = {"time"}) + private Date time; + + @TableField + @Column(comment = "测试结果详情类型", defaultValue = "") + @Index(value = "IDX_TYPE", columns = {"type"}) + private String type; +} diff --git a/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/domain/Results.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/domain/Results.java new file mode 100644 index 00000000..a9876734 --- /dev/null +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/domain/Results.java @@ -0,0 +1,82 @@ +package org.cloud.sonic.controller.models.domain; + +import com.baomidou.mybatisplus.annotation.*; +import com.fasterxml.jackson.annotation.JsonFormat; +import com.gitee.sunchenbin.mybatis.actable.annotation.*; +import com.gitee.sunchenbin.mybatis.actable.constants.MySqlCharsetConstant; +import com.gitee.sunchenbin.mybatis.actable.constants.MySqlEngineConstant; +import com.gitee.sunchenbin.mybatis.actable.constants.MySqlTypeConstant; +import org.cloud.sonic.controller.models.base.TypeConverter; +import org.cloud.sonic.controller.models.dto.ResultsDTO; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; + +import java.io.Serializable; +import java.util.Date; + +/** + * @author JayWenStar + * @since 2021-12-17 + */ +@ApiModel(value = "Results对象", description = "") +@Data +@Accessors(chain = true) +@Builder +@NoArgsConstructor +@AllArgsConstructor +@TableName("results") +@TableComment("测试结果表") +@TableCharset(MySqlCharsetConstant.DEFAULT) +@TableEngine(MySqlEngineConstant.InnoDB) +public class Results implements Serializable, TypeConverter { + + @TableId(value = "id", type = IdType.AUTO) + @IsAutoIncrement + private Integer id; + + @ApiModelProperty(value = "创建时间", example = "2021-08-15 11:36:00") + @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") + @TableField(fill = FieldFill.INSERT) + @Column(value = "create_time", type = MySqlTypeConstant.DATETIME, isNull = false, comment = "任务创建时间") + Date createTime; + + @ApiModelProperty(value = "结束时间", example = "2021-08-15 11:36:00") + @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") + @TableField(fill = FieldFill.INSERT_UPDATE) + @Column(value = "end_time", type = MySqlTypeConstant.DATETIME, comment = "任务结束时间") + Date endTime; + + @TableField + @Column(value = "project_id", isNull = false, comment = "所属项目id") + @Index(value = "IDX_PROJECT_ID", columns = {"project_id"}) + private Integer projectId; + + @TableField + @Column(value = "receive_msg_count", isNull = false, comment = "接受消息数量") + private Integer receiveMsgCount; + + @TableField + @Column(value = "send_msg_count", isNull = false, comment = "发送消息数量") + private Integer sendMsgCount; + + @TableField + @Column(isNull = false, comment = "结果状态") + private Integer status; + + @TableField + @Column(comment = "触发者", defaultValue = "") + private String strike; + + @TableField + @Column(value = "suite_id", isNull = false, comment = "测试套件id") + private Integer suiteId; + + @TableField + @Column(value = "suite_name", comment = "测试套件名字", defaultValue = "") + private String suiteName; +} diff --git a/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/domain/Steps.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/domain/Steps.java new file mode 100644 index 00000000..f3bd4383 --- /dev/null +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/domain/Steps.java @@ -0,0 +1,75 @@ +package org.cloud.sonic.controller.models.domain; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import com.gitee.sunchenbin.mybatis.actable.annotation.*; +import com.gitee.sunchenbin.mybatis.actable.constants.MySqlCharsetConstant; +import com.gitee.sunchenbin.mybatis.actable.constants.MySqlEngineConstant; +import com.gitee.sunchenbin.mybatis.actable.constants.MySqlTypeConstant; +import org.cloud.sonic.controller.models.base.TypeConverter; +import org.cloud.sonic.controller.models.dto.StepsDTO; +import io.swagger.annotations.ApiModel; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; + +import java.io.Serializable; + +/** + * @author JayWenStar + * @since 2021-12-17 + */ +@ApiModel(value = "Steps对象", description = "") +@Data +@Accessors(chain = true) +@Builder +@NoArgsConstructor +@AllArgsConstructor +@TableName("steps") +@TableComment("测试步骤表") +@TableCharset(MySqlCharsetConstant.DEFAULT) +@TableEngine(MySqlEngineConstant.InnoDB) +public class Steps implements Serializable, TypeConverter { + + @TableId(value = "id", type = IdType.AUTO) + @IsAutoIncrement + private Integer id; + + @TableField + @Column(value = "case_id", isNull = false, comment = "所属测试用例id") + @Index(value = "IDX_CASE_ID", columns = {"case_id"}) + private Integer caseId; + + @TableField + @Column(type = MySqlTypeConstant.LONGTEXT, isNull = false, comment = "输入文本") + private String content; + + @TableField + @Column(isNull = false, comment = "异常处理类型") + private Integer error; + + @TableField + @Column(isNull = false, comment = "设备系统类型") + private Integer platform; + + @TableField + @Column(value = "project_id", isNull = false, comment = "所属项目id") + @Index(value = "IDX_PROJECT_ID", columns = {"project_id"}) + private Integer projectId; + + @TableField + @Column(isNull = false, comment = "排序号") + private Integer sort; + + @TableField + @Column(value = "step_type", isNull = false, comment = "步骤类型") + private String stepType; + + @TableField + @Column(type = MySqlTypeConstant.LONGTEXT, isNull = false, comment = "其它信息") + private String text; +} diff --git a/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/domain/StepsElements.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/domain/StepsElements.java new file mode 100644 index 00000000..aea3b95a --- /dev/null +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/domain/StepsElements.java @@ -0,0 +1,45 @@ +package org.cloud.sonic.controller.models.domain; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableName; +import com.gitee.sunchenbin.mybatis.actable.annotation.Column; +import com.gitee.sunchenbin.mybatis.actable.annotation.TableCharset; +import com.gitee.sunchenbin.mybatis.actable.annotation.TableComment; +import com.gitee.sunchenbin.mybatis.actable.annotation.TableEngine; +import com.gitee.sunchenbin.mybatis.actable.constants.MySqlCharsetConstant; +import com.gitee.sunchenbin.mybatis.actable.constants.MySqlEngineConstant; +import org.cloud.sonic.controller.models.base.TypeConverter; +import org.cloud.sonic.controller.models.dto.StepsElementsDTO; +import io.swagger.annotations.ApiModel; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; + +import java.io.Serializable; + +/** + * @author JayWenStar + * @since 2021-12-17 + */ +@ApiModel(value = "StepsElements对象", description = "") +@Data +@Accessors(chain = true) +@Builder +@NoArgsConstructor +@AllArgsConstructor +@TableName("steps_elements") +@TableComment("步骤 - 控件 关系映射表") +@TableCharset(MySqlCharsetConstant.DEFAULT) +@TableEngine(MySqlEngineConstant.InnoDB) +public class StepsElements implements Serializable, TypeConverter { + + @TableField + @Column(value = "steps_id", isNull = false, comment = "步骤id") + private Integer stepsId; + + @TableField + @Column(value = "elements_id", isNull = false, comment = "控件id") + private Integer elementsId; +} diff --git a/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/domain/TestCases.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/domain/TestCases.java new file mode 100644 index 00000000..56cad85c --- /dev/null +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/domain/TestCases.java @@ -0,0 +1,76 @@ +package org.cloud.sonic.controller.models.domain; + +import com.baomidou.mybatisplus.annotation.*; +import com.fasterxml.jackson.annotation.JsonFormat; +import com.gitee.sunchenbin.mybatis.actable.annotation.*; +import com.gitee.sunchenbin.mybatis.actable.constants.MySqlCharsetConstant; +import com.gitee.sunchenbin.mybatis.actable.constants.MySqlEngineConstant; +import com.gitee.sunchenbin.mybatis.actable.constants.MySqlTypeConstant; +import org.cloud.sonic.controller.models.base.TypeConverter; +import org.cloud.sonic.controller.models.dto.TestCasesDTO; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; + +import java.io.Serializable; +import java.util.Date; + +/** + * @author JayWenStar + * @since 2021-12-17 + */ +@ApiModel(value = "TestCases对象", description = "") +@Data +@Accessors(chain = true) +@Builder +@NoArgsConstructor +@AllArgsConstructor +@TableName("test_cases") +@TableComment("测试用例表") +@TableCharset(MySqlCharsetConstant.DEFAULT) +@TableEngine(MySqlEngineConstant.InnoDB) +public class TestCases implements Serializable, TypeConverter { + + @TableId(value = "id", type = IdType.AUTO) + @IsAutoIncrement + private Integer id; + + @TableField + @Column(isNull = false, comment = "用例描述") + private String des; + + @TableField + @Column(isNull = false, comment = "用例设计人") + private String designer; + + @ApiModelProperty(value = "最后修改日期", required = true, example = "2021-08-15 11:10:00") + @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") + @TableField(fill = FieldFill.INSERT_UPDATE) + @Column(value = "edit_time", type = MySqlTypeConstant.DATETIME, isNull = false, comment = "最后修改日期") + private Date editTime; + + @TableField + @Column(isNull = false, comment = "所属模块") + private String module; + + @TableField + @Column(isNull = false, comment = "用例名称") + private String name; + + @TableField + @Column(isNull = false, comment = "设备系统类型") + private Integer platform; + + @TableField + @Column(value = "project_id", isNull = false, comment = "所属项目id") + @Index(value = "IDX_PROJECT_ID", columns = {"project_id"}) + private Integer projectId; + + @TableField + @Column(value = "version", isNull = false, comment = "版本号") + private String version; +} diff --git a/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/domain/TestSuites.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/domain/TestSuites.java new file mode 100644 index 00000000..39c1f5c4 --- /dev/null +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/domain/TestSuites.java @@ -0,0 +1,57 @@ +package org.cloud.sonic.controller.models.domain; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import com.gitee.sunchenbin.mybatis.actable.annotation.*; +import com.gitee.sunchenbin.mybatis.actable.constants.MySqlCharsetConstant; +import com.gitee.sunchenbin.mybatis.actable.constants.MySqlEngineConstant; +import org.cloud.sonic.controller.models.base.TypeConverter; +import org.cloud.sonic.controller.models.dto.TestSuitesDTO; +import io.swagger.annotations.ApiModel; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; + +import java.io.Serializable; + +/** + * @author JayWenStar + * @since 2021-12-17 + */ +@ApiModel(value = "TestSuites对象", description = "") +@Data +@Accessors(chain = true) +@Builder +@NoArgsConstructor +@AllArgsConstructor +@TableName("test_suites") +@TableComment("测试套件表") +@TableCharset(MySqlCharsetConstant.DEFAULT) +@TableEngine(MySqlEngineConstant.InnoDB) +public class TestSuites implements Serializable, TypeConverter { + + @TableId(value = "id", type = IdType.AUTO) + @IsAutoIncrement + private Integer id; + + @TableField + @Column(isNull = false, comment = "覆盖类型") + private Integer cover; + + @TableField + @Column(isNull = false, comment = "测试套件名字") + private String name; + + @TableField + @Column(isNull = false, comment = "测试套件系统类型(android、ios...)") + private Integer platform; + + @TableField + @Column(value = "project_id", isNull = false, comment = "覆盖类型") + @Index(value = "IDX_PROJECT_ID", columns = {"project_id"}) + private Integer projectId; +} diff --git a/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/domain/TestSuitesDevices.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/domain/TestSuitesDevices.java new file mode 100644 index 00000000..2b9feccf --- /dev/null +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/domain/TestSuitesDevices.java @@ -0,0 +1,43 @@ +package org.cloud.sonic.controller.models.domain; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableName; +import com.gitee.sunchenbin.mybatis.actable.annotation.*; +import com.gitee.sunchenbin.mybatis.actable.constants.MySqlCharsetConstant; +import com.gitee.sunchenbin.mybatis.actable.constants.MySqlEngineConstant; +import org.cloud.sonic.controller.models.base.TypeConverter; +import org.cloud.sonic.controller.models.dto.TestSuitesDevicesDTO; +import io.swagger.annotations.ApiModel; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; + +import java.io.Serializable; + +/** + * @author JayWenStar + * @since 2021-12-17 + */ +@ApiModel(value = "TestSuitesDevices对象", description = "") +@Data +@Accessors(chain = true) +@Builder +@NoArgsConstructor +@AllArgsConstructor +@TableName("test_suites_devices") +@TableComment("测试套件 - 设备 关系映射表") +@TableCharset(MySqlCharsetConstant.DEFAULT) +@TableEngine(MySqlEngineConstant.InnoDB) +public class TestSuitesDevices implements Serializable, TypeConverter { + + @TableField + @Column(value = "test_suites_id", isNull = false, comment = "测试套件id") + @Index(value = "idx_test_suites_id_devices_id", columns = {"test_suites_id", "devices_id"}) + private Integer testSuitesId; + + @TableField + @Column(value = "devices_id", isNull = false, comment = "设备id") + private Integer devicesId; +} diff --git a/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/domain/TestSuitesTestCases.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/domain/TestSuitesTestCases.java new file mode 100644 index 00000000..79bbaf9f --- /dev/null +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/domain/TestSuitesTestCases.java @@ -0,0 +1,45 @@ +package org.cloud.sonic.controller.models.domain; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableName; +import com.gitee.sunchenbin.mybatis.actable.annotation.Column; +import com.gitee.sunchenbin.mybatis.actable.annotation.TableCharset; +import com.gitee.sunchenbin.mybatis.actable.annotation.TableComment; +import com.gitee.sunchenbin.mybatis.actable.annotation.TableEngine; +import com.gitee.sunchenbin.mybatis.actable.constants.MySqlCharsetConstant; +import com.gitee.sunchenbin.mybatis.actable.constants.MySqlEngineConstant; +import org.cloud.sonic.controller.models.base.TypeConverter; +import org.cloud.sonic.controller.models.dto.TestSuitesTestCasesDTO; +import io.swagger.annotations.ApiModel; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; + +import java.io.Serializable; + +/** + * @author JayWenStar + * @since 2021-12-17 + */ +@ApiModel(value = "TestSuitesTestCases对象", description = "") +@Data +@Accessors(chain = true) +@Builder +@NoArgsConstructor +@AllArgsConstructor +@TableName("test_suites_test_cases") +@TableComment("测试套件 - 测试用例 关系映射表") +@TableCharset(MySqlCharsetConstant.DEFAULT) +@TableEngine(MySqlEngineConstant.InnoDB) +public class TestSuitesTestCases implements Serializable, TypeConverter { + + @TableField + @Column(value = "test_suites_id", isNull = false, comment = "测试套件id") + private Integer testSuitesId; + + @TableField + @Column(value = "test_cases_id", isNull = false, comment = "测试用例id") + private Integer testCasesId; +} diff --git a/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/domain/Users.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/domain/Users.java new file mode 100644 index 00000000..13dad7f8 --- /dev/null +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/domain/Users.java @@ -0,0 +1,53 @@ +package org.cloud.sonic.controller.models.domain; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import com.gitee.sunchenbin.mybatis.actable.annotation.*; +import com.gitee.sunchenbin.mybatis.actable.constants.MySqlCharsetConstant; +import com.gitee.sunchenbin.mybatis.actable.constants.MySqlEngineConstant; +import org.cloud.sonic.controller.models.base.TypeConverter; +import org.cloud.sonic.controller.models.dto.UsersDTO; +import io.swagger.annotations.ApiModel; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; + +import java.io.Serializable; + +/** + * @author JayWenStar + * @since 2021-12-17 + */ +@ApiModel(value = "Users对象", description = "") +@Data +@Accessors(chain = true) +@Builder +@NoArgsConstructor +@AllArgsConstructor +@TableName("users") +@TableComment("用户表") +@TableCharset(MySqlCharsetConstant.DEFAULT) +@TableEngine(MySqlEngineConstant.InnoDB) +public class Users implements Serializable, TypeConverter { + + @TableId(value = "id", type = IdType.AUTO) + @IsAutoIncrement + private Integer id; + + @TableField + @Column(isNull = false, comment = "密码") + private String password; + + @TableField + @Column(isNull = false, comment = "角色") + private Integer role; + + @TableField + @Column(value = "user_name", isNull = false, comment = "用户名") + @Unique(value = "UNI_USER_NAME", columns = "user_name") + private String userName; +} diff --git a/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/domain/Versions.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/domain/Versions.java new file mode 100644 index 00000000..042381e2 --- /dev/null +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/domain/Versions.java @@ -0,0 +1,55 @@ +package org.cloud.sonic.controller.models.domain; + +import com.baomidou.mybatisplus.annotation.*; +import com.fasterxml.jackson.annotation.JsonFormat; +import com.gitee.sunchenbin.mybatis.actable.annotation.*; +import com.gitee.sunchenbin.mybatis.actable.constants.MySqlCharsetConstant; +import com.gitee.sunchenbin.mybatis.actable.constants.MySqlEngineConstant; +import com.gitee.sunchenbin.mybatis.actable.constants.MySqlTypeConstant; +import org.cloud.sonic.controller.models.base.TypeConverter; +import org.cloud.sonic.controller.models.dto.VersionsDTO; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; + +import java.io.Serializable; +import java.util.Date; + +/** + * @author JayWenStar + * @since 2021-12-17 + */ +@ApiModel(value = "Versions对象", description = "") +@Data +@Accessors(chain = true) +@Builder +@NoArgsConstructor +@AllArgsConstructor +@TableName("versions") +@TableComment("版本表") +@TableCharset(MySqlCharsetConstant.DEFAULT) +@TableEngine(MySqlEngineConstant.InnoDB) +public class Versions implements Serializable, TypeConverter { + + @TableId(value = "id", type = IdType.AUTO) + @IsAutoIncrement + private Integer id; + + @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") + @ApiModelProperty(value = "日期", example = "2021-08-15T16:00:00.000+00:00") + @TableField(fill = FieldFill.INSERT) + @Column(value = "create_time", type = MySqlTypeConstant.DATETIME, isNull = false, comment = "创建时间内") + private Date createTime; + + @TableField + @Column(value = "project_id", isNull = false, comment = "所属项目id") + private Integer projectId; + + @TableField + @Column(value = "version_name", isNull = false, comment = "迭代名称") + private String versionName; +} diff --git a/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/dto/AgentsDTO.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/dto/AgentsDTO.java new file mode 100644 index 00000000..12bccb7f --- /dev/null +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/dto/AgentsDTO.java @@ -0,0 +1,53 @@ +package org.cloud.sonic.controller.models.dto; + +import org.cloud.sonic.controller.models.base.TypeConverter; +import org.cloud.sonic.controller.models.domain.Agents; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; + +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.NotNull; +import java.io.Serializable; + +@ApiModel("AgentDTO 端模型") +@Data +@Accessors(chain = true) +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class AgentsDTO implements Serializable, TypeConverter { + + @ApiModelProperty(value = "id", example = "1") + Integer id; + + @NotBlank + @ApiModelProperty(value = "Agent端名称", example = "本地Agent") + String name; + + @NotBlank + @ApiModelProperty(value = "Agent端系统类型", example = "Windows 10") + String systemType; + + @NotBlank + @ApiModelProperty(value = "Agent端版本号", example = "1.0.0") + String version; + + @NotBlank + @ApiModelProperty(value = "Agent端所在host", example = "127.0.0.1") + String host; + + @NotNull + @ApiModelProperty(value = "Agent端暴露web端口", example = "1234") + int port; + + @ApiModelProperty(value = "Agent端状态", example = "1") + int status; + + @ApiModelProperty(value = "Agent端密钥", example = "qwe") + String secretKey; +} diff --git a/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/dto/DevicesDTO.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/dto/DevicesDTO.java new file mode 100644 index 00000000..8d6d318a --- /dev/null +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/dto/DevicesDTO.java @@ -0,0 +1,85 @@ +package org.cloud.sonic.controller.models.dto; + +import com.alibaba.fastjson.annotation.JSONField; +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.cloud.sonic.controller.models.base.TypeConverter; +import org.cloud.sonic.controller.models.domain.Devices; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.*; +import lombok.experimental.Accessors; + +import java.io.Serializable; +import java.util.Set; + +@ApiModel("设备DTO 模型") +@Data +@Accessors(chain = true) +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class DevicesDTO implements Serializable, TypeConverter { + + @ApiModelProperty(value = "id", example = "1") + Integer id; + + @ApiModelProperty(value = "设备名称", example = "My HUAWEI") + String name; + + @ApiModelProperty(value = "设备备注", example = "My HUAWEI") + String nickName; + + @ApiModelProperty(value = "型号", example = "HUAWEI MATE 40") + String model; + + @ApiModelProperty(value = "序列号", example = "random") + String udId; + + @ApiModelProperty(value = "设备状态", example = "ONLINE") + String status; + + @ApiModelProperty(value = "所属Agent", example = "1") + Integer agentId; + + @ApiModelProperty(value = "设备系统", example = "1") + Integer platform; + + @ApiModelProperty(value = "分辨率", example = "1080x1920") + String size; + + @ApiModelProperty(value = "系统版本", example = "12") + String version; + + @ApiModelProperty(value = "cpu", example = "arm64") + String cpu; + + @ApiModelProperty(value = "制造商", example = "HUAWEI") + String manufacturer; + + @ApiModelProperty(value = "安装密码", example = "123456") + String password; + + @ApiModelProperty(value = "设备图片路径") + String imgUrl; + + @JsonIgnore + @JSONField(serialize = false) + Set testSuites; + + @ApiModelProperty(value = "设备占用者") + String user; + + @Getter(AccessLevel.NONE) + @ApiModelProperty(value = "设备温度", example = "33") + Integer temperature; + + @ApiModelProperty(value = "中文设备", example = "荣耀全网通") + String chiName; + + public float getTemperature() { + if (temperature == null) { + return 0F; + } + return temperature; + } +} diff --git a/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/dto/ElementsDTO.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/dto/ElementsDTO.java new file mode 100644 index 00000000..76efa320 --- /dev/null +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/dto/ElementsDTO.java @@ -0,0 +1,54 @@ +package org.cloud.sonic.controller.models.dto; + +import com.alibaba.fastjson.annotation.JSONField; +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.cloud.sonic.controller.models.base.TypeConverter; +import org.cloud.sonic.controller.models.domain.Elements; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; + +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.Positive; +import java.io.Serializable; +import java.util.List; + +@ApiModel("页面控件DTO 模型") +@Data +@Accessors(chain = true) +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class ElementsDTO implements Serializable, TypeConverter { + + @ApiModelProperty(value = "id", example = "1") + Integer id; + + @ApiModelProperty(value = "所属steps的id", example = "1") + Integer stepsId; + + @NotBlank + @ApiModelProperty(value = "控件名称", required = true, example = "首页底部按钮") + String eleName; + + @NotBlank + @ApiModelProperty(value = "控件类型", required = true, example = "xpath") + String eleType; + + @NotBlank + @ApiModelProperty(value = "控件值", required = true, example = "//@[text()='home']") + String eleValue; + + @Positive + @ApiModelProperty(value = "项目id", required = true, example = "1") + Integer projectId; + + //因为一个控件可以存在于多个步骤,也可以一个步骤有多个同样的控件,所以是多对多关系 + @JsonIgnore + @JSONField(serialize = false) + List steps; +} diff --git a/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/dto/GlobalParamsDTO.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/dto/GlobalParamsDTO.java new file mode 100644 index 00000000..b7ae01a2 --- /dev/null +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/dto/GlobalParamsDTO.java @@ -0,0 +1,39 @@ +package org.cloud.sonic.controller.models.dto; + +import org.cloud.sonic.controller.models.base.TypeConverter; +import org.cloud.sonic.controller.models.domain.GlobalParams; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; + +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.Positive; +import java.io.Serializable; + +@ApiModel("全局参数DTO 模型") +@Data +@Accessors(chain = true) +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class GlobalParamsDTO implements Serializable, TypeConverter { + + @ApiModelProperty(value = "id", example = "1") + Integer id; + + @Positive + @ApiModelProperty(value = "项目id", required = true, example = "1") + Integer projectId; + + @NotBlank + @ApiModelProperty(value = "参数名", required = true, example = "account") + String paramsKey; + + @NotBlank + @ApiModelProperty(value = "参数值", required = true, example = "123456789") + String paramsValue; +} diff --git a/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/dto/ModulesDTO.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/dto/ModulesDTO.java new file mode 100644 index 00000000..b7d731ce --- /dev/null +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/dto/ModulesDTO.java @@ -0,0 +1,35 @@ +package org.cloud.sonic.controller.models.dto; + +import org.cloud.sonic.controller.models.base.TypeConverter; +import org.cloud.sonic.controller.models.domain.Modules; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; + +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.Positive; +import java.io.Serializable; + +@ApiModel("模块模型") +@Data +@Accessors(chain = true) +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class ModulesDTO implements Serializable, TypeConverter { + + @ApiModelProperty(value = "id", example = "1") + Integer id; + + @Positive + @ApiModelProperty(value = "项目id", required = true, example = "1") + Integer projectId; + + @NotBlank + @ApiModelProperty(value = "模块名称", required = true, example = "首页") + String name; +} diff --git a/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/dto/ProjectsDTO.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/dto/ProjectsDTO.java new file mode 100644 index 00000000..23e6bbbe --- /dev/null +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/dto/ProjectsDTO.java @@ -0,0 +1,51 @@ +package org.cloud.sonic.controller.models.dto; + +import com.fasterxml.jackson.annotation.JsonFormat; +import org.cloud.sonic.controller.models.base.TypeConverter; +import org.cloud.sonic.controller.models.domain.Projects; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; + +import javax.validation.constraints.NotBlank; +import java.io.Serializable; +import java.util.Date; + +@ApiModel("项目DTO 模型") +@Data +@Accessors(chain = true) +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class ProjectsDTO implements Serializable, TypeConverter { + + @ApiModelProperty(value = "id", example = "1") + Integer id; + + @NotBlank + @ApiModelProperty(value = "项目名称", required = true, example = "test") + String projectName; + + @ApiModelProperty(value = "项目描述", required = true, example = "Sonic项目描述") + String projectDes; + + @ApiModelProperty(value = "机器人类型", required = true, example = "1") + Integer robotType; + + @ApiModelProperty(value = "机器人token", required = true, example = "http://dingTalk.com?token=*****") + String robotToken; + + @ApiModelProperty(value = "机器人加签密钥", required = true, example = "qwe***") + String robotSecret; + + @ApiModelProperty(value = "项目图标", required = true, example = "http://img.jpg") + String projectImg; + + @ApiModelProperty(value = "最后修改日期", example = "2021-08-15 11:23:00") + @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") + Date editTime; +} diff --git a/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/dto/PublicStepsDTO.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/dto/PublicStepsDTO.java new file mode 100644 index 00000000..31f51257 --- /dev/null +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/dto/PublicStepsDTO.java @@ -0,0 +1,43 @@ +package org.cloud.sonic.controller.models.dto; + +import org.cloud.sonic.controller.models.base.TypeConverter; +import org.cloud.sonic.controller.models.domain.PublicSteps; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; + +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.Positive; +import java.io.Serializable; +import java.util.List; + +@ApiModel("公共步骤模型") +@Data +@Accessors(chain = true) +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class PublicStepsDTO implements Serializable, TypeConverter { + + @ApiModelProperty(value = "id", example = "1") + Integer id; + + @Positive + @ApiModelProperty(value = "项目id", required = true, example = "1") + Integer projectId; + + @Positive + @ApiModelProperty(value = "平台", required = true, example = "1") + Integer platform; + + @NotBlank + @ApiModelProperty(value = "公共步骤名称", required = true, example = "登陆步骤") + String name; + + @ApiModelProperty(value = "包含操作步骤列表") + List steps; +} diff --git a/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/dto/PublicStepsStepsDTO.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/dto/PublicStepsStepsDTO.java new file mode 100644 index 00000000..15fc16c1 --- /dev/null +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/dto/PublicStepsStepsDTO.java @@ -0,0 +1,33 @@ +package org.cloud.sonic.controller.models.dto; + +import org.cloud.sonic.controller.models.base.TypeConverter; +import org.cloud.sonic.controller.models.domain.PublicStepsSteps; +import io.swagger.annotations.ApiModel; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; + +import java.io.Serializable; + +/** + *

+ * + *

+ * + * @author JayWenStar + * @since 2021-12-17 + */ +@ApiModel(value = "PublicStepsStepsDTO 对象", description = "") +@Data +@Accessors(chain = true) +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class PublicStepsStepsDTO implements Serializable, TypeConverter { + + private Integer publicStepsId; + + private Integer stepsId; +} diff --git a/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/dto/ResultDetailDTO.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/dto/ResultDetailDTO.java new file mode 100644 index 00000000..bfa2f2d5 --- /dev/null +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/dto/ResultDetailDTO.java @@ -0,0 +1,52 @@ +package org.cloud.sonic.controller.models.dto; + +import com.fasterxml.jackson.annotation.JsonFormat; +import org.cloud.sonic.controller.models.base.TypeConverter; +import org.cloud.sonic.controller.models.domain.ResultDetail; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; + +import java.io.Serializable; +import java.util.Date; + +@ApiModel("测试结果详情DTO 模型") +@Data +@Accessors(chain = true) +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class ResultDetailDTO implements Serializable, TypeConverter { + + @ApiModelProperty(value = "id", example = "1") + Integer id; + + @ApiModelProperty(value = "测试用例id", example = "1") + Integer caseId; + + @ApiModelProperty(value = "测试结果id", example = "1") + Integer resultId; + + @ApiModelProperty(value = "测试结果详情类型", example = "step") + String type; + + @ApiModelProperty(value = "测试结果详情描述", example = "点击xxx") + String des; + + @ApiModelProperty(value = "测试结果详情状态", example = "1") + Integer status; + + @ApiModelProperty(value = "设备id", example = "1") + Integer deviceId; + + @ApiModelProperty(value = "测试结果详情详细日志", example = "点击xpath://*[@text()='xxx']") + String log; + + @ApiModelProperty(value = "时间", example = "16:00:00") + @JsonFormat(pattern = "HH:mm:ss", timezone = "GMT+8") + Date time; +} diff --git a/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/dto/ResultsDTO.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/dto/ResultsDTO.java new file mode 100644 index 00000000..29fa61c3 --- /dev/null +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/dto/ResultsDTO.java @@ -0,0 +1,56 @@ +package org.cloud.sonic.controller.models.dto; + +import com.fasterxml.jackson.annotation.JsonFormat; +import org.cloud.sonic.controller.models.base.TypeConverter; +import org.cloud.sonic.controller.models.domain.Results; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; + +import java.io.Serializable; +import java.util.Date; + +@ApiModel("测试结果模型") +@Data +@Accessors(chain = true) +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class ResultsDTO implements Serializable, TypeConverter { + + @ApiModelProperty(value = "id", example = "1") + Integer id; + + @ApiModelProperty(value = "测试套件id", example = "1") + Integer suiteId; + + @ApiModelProperty(value = "测试套件名称", example = "测试套件A") + String suiteName; + + @ApiModelProperty(value = "项目id", example = "1") + Integer projectId; + + @ApiModelProperty(value = "触发者", example = "ZhouYiXun") + String strike; + + @ApiModelProperty(value = "发送的消息数量", example = "1") + Integer sendMsgCount; + + @ApiModelProperty(value = "接收的消息数量", example = "2") + Integer receiveMsgCount; + + @ApiModelProperty(value = "状态", example = "WARN") + Integer status; + + @ApiModelProperty(value = "创建时间", example = "2021-08-15 11:36:00") + @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") + Date createTime; + + @ApiModelProperty(value = "结束时间", example = "2021-08-15 11:36:00") + @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") + Date endTime; +} diff --git a/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/dto/StepsDTO.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/dto/StepsDTO.java new file mode 100644 index 00000000..b24755cf --- /dev/null +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/dto/StepsDTO.java @@ -0,0 +1,72 @@ +package org.cloud.sonic.controller.models.dto; + + +import com.alibaba.fastjson.annotation.JSONField; +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.cloud.sonic.controller.models.base.TypeConverter; +import org.cloud.sonic.controller.models.domain.Steps; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; + +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.Positive; +import java.io.Serializable; +import java.util.List; + +@ApiModel("运行步骤DTO 模型") +@Data +@Accessors(chain = true) +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class StepsDTO implements Serializable, TypeConverter { + + @ApiModelProperty(value = "id", example = "1") + Integer id; + + @Positive + @ApiModelProperty(value = "项目id", required = true, example = "1") + Integer projectId; + + @ApiModelProperty(value = "所属公共步骤id", required = true, example = "1") + Integer publicStepsId; + + @ApiModelProperty(value = "测试用例id", example = "1") + Integer caseId; + + @Positive + @ApiModelProperty(value = "类型", required = true, example = "1") + Integer platform; + + @NotBlank + @ApiModelProperty(value = "步骤类型", required = true, example = "click") + String stepType; + + @ApiModelProperty(value = "输入文本", required = true, example = "123") + String content; + + @ApiModelProperty(value = "其他信息", required = true, example = "456") + String text; + + @ApiModelProperty(value = "排序号", example = "123") + int sort; + + @Positive + @ApiModelProperty(value = "异常处理类型", required = true, example = "1") + int error; + + @ApiModelProperty(value = "包含元素列表") + List elements; + + @JsonIgnore + @JSONField(serialize = false) + List publicSteps; + + @ApiModelProperty(value = "所属测试用例") + TestCasesDTO testCasesDTO; +} diff --git a/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/dto/StepsElementsDTO.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/dto/StepsElementsDTO.java new file mode 100644 index 00000000..af7eedae --- /dev/null +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/dto/StepsElementsDTO.java @@ -0,0 +1,33 @@ +package org.cloud.sonic.controller.models.dto; + +import org.cloud.sonic.controller.models.base.TypeConverter; +import org.cloud.sonic.controller.models.domain.StepsElements; +import io.swagger.annotations.ApiModel; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; + +import java.io.Serializable; + +/** + *

+ * + *

+ * + * @author JayWenStar + * @since 2021-12-17 + */ +@ApiModel(value = "StepsElementsDTO 对象", description = "") +@Data +@Accessors(chain = true) +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class StepsElementsDTO implements Serializable, TypeConverter { + + private Integer stepsId; + + private Integer elementsId; +} diff --git a/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/dto/TestCasesDTO.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/dto/TestCasesDTO.java new file mode 100644 index 00000000..dd11e79a --- /dev/null +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/dto/TestCasesDTO.java @@ -0,0 +1,64 @@ +package org.cloud.sonic.controller.models.dto; + +import com.alibaba.fastjson.annotation.JSONField; +import com.fasterxml.jackson.annotation.JsonFormat; +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.cloud.sonic.controller.models.base.TypeConverter; +import org.cloud.sonic.controller.models.domain.TestCases; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; + +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.Positive; +import java.io.Serializable; +import java.util.Date; +import java.util.List; + +@ApiModel("测试用例模型") +@Data +@Accessors(chain = true) +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class TestCasesDTO implements Serializable, TypeConverter { + + @ApiModelProperty(value = "id", example = "1") + Integer id; + + @NotBlank + @ApiModelProperty(value = "用例名称", required = true, example = "测试用例") + String name; + + @Positive + @ApiModelProperty(value = "所属平台", required = true, example = "1") + Integer platform; + + @Positive + @ApiModelProperty(value = "项目id", required = true, example = "1") + Integer projectId; + + @ApiModelProperty(value = "模块名称", required = true, example = "xxx模块") + String module; + + @ApiModelProperty(value = "项目迭代名称", required = true, example = "v1.0.0需求增加") + String version; + + @ApiModelProperty(value = "用例描述", required = true, example = "xxx测试用例描述") + String des; + + @ApiModelProperty(value = "用例设计人", required = true, example = "YiXunZhou") + String designer; + + @ApiModelProperty(value = "最后修改日期", required = true, example = "2021-08-15 11:10:00") + @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") + Date editTime; + + @JsonIgnore + @JSONField(serialize = false) + List testSuites; +} diff --git a/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/dto/TestSuitesDTO.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/dto/TestSuitesDTO.java new file mode 100644 index 00000000..ac7e3a0b --- /dev/null +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/dto/TestSuitesDTO.java @@ -0,0 +1,50 @@ +package org.cloud.sonic.controller.models.dto; + +import org.cloud.sonic.controller.models.base.TypeConverter; +import org.cloud.sonic.controller.models.domain.TestSuites; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; + +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.Positive; +import java.io.Serializable; +import java.util.List; + +@ApiModel("测试套件DTO 模型") +@Data +@Accessors(chain = true) +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class TestSuitesDTO implements Serializable, TypeConverter { + + @ApiModelProperty(value = "id", example = "1") + Integer id; + + @NotBlank + @ApiModelProperty(value = "测试套件名称", required = true, example = "首页测试套件") + String name; + + @Positive + @ApiModelProperty(value = "测试套件平台类型", required = true, example = "1") + Integer platform; + + @Positive + @ApiModelProperty(value = "覆盖类型", required = true, example = "1") + Integer cover; + + @Positive + @ApiModelProperty(value = "项目id", required = true, example = "1") + Integer projectId; + + @ApiModelProperty(value = "包含的测试用例") + List testCases; + + @ApiModelProperty(value = "指定设备列表") + List devices; +} diff --git a/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/dto/TestSuitesDevicesDTO.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/dto/TestSuitesDevicesDTO.java new file mode 100644 index 00000000..aa06dbf4 --- /dev/null +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/dto/TestSuitesDevicesDTO.java @@ -0,0 +1,33 @@ +package org.cloud.sonic.controller.models.dto; + +import org.cloud.sonic.controller.models.base.TypeConverter; +import org.cloud.sonic.controller.models.domain.TestSuitesDevices; +import io.swagger.annotations.ApiModel; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; + +import java.io.Serializable; + +/** + *

+ * + *

+ * + * @author JayWenStar + * @since 2021-12-17 + */ +@ApiModel(value = "TestSuitesDevicesDTO 对象", description = "") +@Data +@Accessors(chain = true) +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class TestSuitesDevicesDTO implements Serializable, TypeConverter { + + private Integer testSuitesId; + + private Integer devicesId; +} diff --git a/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/dto/TestSuitesTestCasesDTO.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/dto/TestSuitesTestCasesDTO.java new file mode 100644 index 00000000..d9a1b3f7 --- /dev/null +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/dto/TestSuitesTestCasesDTO.java @@ -0,0 +1,34 @@ +package org.cloud.sonic.controller.models.dto; + +import org.cloud.sonic.controller.models.base.TypeConverter; +import org.cloud.sonic.controller.models.domain.TestSuitesTestCases; +import io.swagger.annotations.ApiModel; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; + +import java.io.Serializable; + +/** + *

+ * + *

+ * + * @author JayWenStar + * @since 2021-12-17 + */ +@ApiModel(value = "TestSuitesTestCasesDTO 对象", description = "") +@Data +@Accessors(chain = true) +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class TestSuitesTestCasesDTO implements Serializable, TypeConverter { + + + private Integer testSuitesId; + + private Integer testCasesId; +} diff --git a/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/dto/UsersDTO.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/dto/UsersDTO.java new file mode 100644 index 00000000..f78028d3 --- /dev/null +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/dto/UsersDTO.java @@ -0,0 +1,39 @@ +package org.cloud.sonic.controller.models.dto; + +import org.cloud.sonic.controller.models.base.TypeConverter; +import org.cloud.sonic.controller.models.domain.Users; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; + +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.Positive; +import java.io.Serializable; + +@ApiModel("用户DTO 模型") +@Data +@Accessors(chain = true) +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class UsersDTO implements Serializable, TypeConverter { + + @ApiModelProperty(value = "id", example = "1") + Integer id; + + @NotBlank + @ApiModelProperty(value = "用户名称", required = true, example = "ZhouYiXun") + String userName; + + @NotBlank + @ApiModelProperty(value = "用户密码", required = true, example = "123456") + String password; + + @Positive + @ApiModelProperty(value = "角色", required = true, example = "1") + Integer role; +} \ No newline at end of file diff --git a/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/dto/VersionsDTO.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/dto/VersionsDTO.java new file mode 100644 index 00000000..8a4c4a69 --- /dev/null +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/dto/VersionsDTO.java @@ -0,0 +1,43 @@ +package org.cloud.sonic.controller.models.dto; + +import com.fasterxml.jackson.annotation.JsonFormat; +import org.cloud.sonic.controller.models.base.TypeConverter; +import org.cloud.sonic.controller.models.domain.Versions; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; + +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Positive; +import java.io.Serializable; +import java.util.Date; + +@ApiModel("版本迭代DTO 模型") +@Data +@Accessors(chain = true) +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class VersionsDTO implements Serializable, TypeConverter { + + @ApiModelProperty(value = "id", example = "1") + Integer id; + + @Positive + @ApiModelProperty(value = "项目id", example = "1") + Integer projectId; + + @NotBlank + @ApiModelProperty(value = "迭代名称", example = "xxx迭代") + String versionName; + + @NotNull + @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") + @ApiModelProperty(value = "日期", example = "2021-08-15T16:00:00.000+00:00") + Date createTime; +} diff --git a/sonic-server-controller/src/main/java/com/sonic/controller/models/http/ChangePwd.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/http/ChangePwd.java similarity index 90% rename from sonic-server-controller/src/main/java/com/sonic/controller/models/http/ChangePwd.java rename to sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/http/ChangePwd.java index bd7b66ed..cba32a71 100644 --- a/sonic-server-controller/src/main/java/com/sonic/controller/models/http/ChangePwd.java +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/http/ChangePwd.java @@ -1,36 +1,36 @@ -package com.sonic.controller.models.http; - -import io.swagger.annotations.ApiModelProperty; - -import javax.validation.constraints.NotNull; - -/** - * @author ZhouYiXun - * @des - * @date 2021/10/13 18:45 - */ -public class ChangePwd { - @NotNull - @ApiModelProperty(value = "旧密码", required = true, example = "123456") - private String oldPwd; - - @NotNull - @ApiModelProperty(value = "新密码", required = true, example = "123456") - private String newPwd; - - public String getOldPwd() { - return oldPwd; - } - - public void setOldPwd(String oldPwd) { - this.oldPwd = oldPwd; - } - - public String getNewPwd() { - return newPwd; - } - - public void setNewPwd(String newPwd) { - this.newPwd = newPwd; - } -} +package org.cloud.sonic.controller.models.http; + +import io.swagger.annotations.ApiModelProperty; + +import javax.validation.constraints.NotNull; + +/** + * @author ZhouYiXun + * @des + * @date 2021/10/13 18:45 + */ +public class ChangePwd { + @NotNull + @ApiModelProperty(value = "旧密码", required = true, example = "123456") + private String oldPwd; + + @NotNull + @ApiModelProperty(value = "新密码", required = true, example = "123456") + private String newPwd; + + public String getOldPwd() { + return oldPwd; + } + + public void setOldPwd(String oldPwd) { + this.oldPwd = oldPwd; + } + + public String getNewPwd() { + return newPwd; + } + + public void setNewPwd(String newPwd) { + this.newPwd = newPwd; + } +} diff --git a/sonic-server-controller/src/main/java/com/sonic/controller/models/http/DeviceDetailChange.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/http/DeviceDetailChange.java similarity index 96% rename from sonic-server-controller/src/main/java/com/sonic/controller/models/http/DeviceDetailChange.java rename to sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/http/DeviceDetailChange.java index e1e3825b..da1cdfec 100644 --- a/sonic-server-controller/src/main/java/com/sonic/controller/models/http/DeviceDetailChange.java +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/http/DeviceDetailChange.java @@ -1,4 +1,4 @@ -package com.sonic.controller.models.http; +package org.cloud.sonic.controller.models.http; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; diff --git a/sonic-server-controller/src/main/java/com/sonic/controller/models/http/StepSort.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/http/StepSort.java similarity index 93% rename from sonic-server-controller/src/main/java/com/sonic/controller/models/http/StepSort.java rename to sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/http/StepSort.java index 70761996..5fb1704d 100644 --- a/sonic-server-controller/src/main/java/com/sonic/controller/models/http/StepSort.java +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/http/StepSort.java @@ -1,65 +1,65 @@ -package com.sonic.controller.models.http; - -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; - -import javax.validation.constraints.NotNull; -import javax.validation.constraints.Positive; - -@ApiModel("拖拽排序请求模型") -public class StepSort { - @Positive - @ApiModelProperty(value = "测试用例id", required = true, example = "1") - private int caseId; - @NotNull - @ApiModelProperty(value = "拖拽方向", required = true, example = "up | down") - private String direction; - @Positive - @ApiModelProperty(value = "移动后被影响的第一个步骤sort序号", required = true, example = "1") - private int startId; - @Positive - @ApiModelProperty(value = "移动后被影响的最后一个步骤sort序号", required = true, example = "9") - private int endId; - - public int getCaseId() { - return caseId; - } - - public void setCaseId(int caseId) { - this.caseId = caseId; - } - - public String getDirection() { - return direction; - } - - public void setDirection(String direction) { - this.direction = direction; - } - - public int getStartId() { - return startId; - } - - public void setStartId(int startId) { - this.startId = startId; - } - - public int getEndId() { - return endId; - } - - public void setEndId(int endId) { - this.endId = endId; - } - - @Override - public String toString() { - return "StepSort{" + - "caseId=" + caseId + - ", direction='" + direction + '\'' + - ", startId=" + startId + - ", endId=" + endId + - '}'; - } -} +package org.cloud.sonic.controller.models.http; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Positive; + +@ApiModel("拖拽排序请求模型") +public class StepSort { + @Positive + @ApiModelProperty(value = "测试用例id", required = true, example = "1") + private int caseId; + @NotNull + @ApiModelProperty(value = "拖拽方向", required = true, example = "up | down") + private String direction; + @Positive + @ApiModelProperty(value = "移动后被影响的第一个步骤sort序号", required = true, example = "1") + private int startId; + @Positive + @ApiModelProperty(value = "移动后被影响的最后一个步骤sort序号", required = true, example = "9") + private int endId; + + public int getCaseId() { + return caseId; + } + + public void setCaseId(int caseId) { + this.caseId = caseId; + } + + public String getDirection() { + return direction; + } + + public void setDirection(String direction) { + this.direction = direction; + } + + public int getStartId() { + return startId; + } + + public void setStartId(int startId) { + this.startId = startId; + } + + public int getEndId() { + return endId; + } + + public void setEndId(int endId) { + this.endId = endId; + } + + @Override + public String toString() { + return "StepSort{" + + "caseId=" + caseId + + ", direction='" + direction + '\'' + + ", startId=" + startId + + ", endId=" + endId + + '}'; + } +} diff --git a/sonic-server-controller/src/main/java/com/sonic/controller/models/http/UpdateDeviceImg.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/http/UpdateDeviceImg.java similarity index 95% rename from sonic-server-controller/src/main/java/com/sonic/controller/models/http/UpdateDeviceImg.java rename to sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/http/UpdateDeviceImg.java index cd4e8222..9ee09d29 100644 --- a/sonic-server-controller/src/main/java/com/sonic/controller/models/http/UpdateDeviceImg.java +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/http/UpdateDeviceImg.java @@ -1,4 +1,4 @@ -package com.sonic.controller.models.http; +package org.cloud.sonic.controller.models.http; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; diff --git a/sonic-server-controller/src/main/java/com/sonic/controller/models/http/UserInfo.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/http/UserInfo.java similarity index 90% rename from sonic-server-controller/src/main/java/com/sonic/controller/models/http/UserInfo.java rename to sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/http/UserInfo.java index 7c146cec..b0da2a4c 100644 --- a/sonic-server-controller/src/main/java/com/sonic/controller/models/http/UserInfo.java +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/http/UserInfo.java @@ -1,33 +1,33 @@ -package com.sonic.controller.models.http; - -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; - -import javax.validation.constraints.NotNull; - -@ApiModel("登录请求模型") -public class UserInfo { - @NotNull - @ApiModelProperty(value = "账户名", required = true, example = "ZhouYiXun") - private String userName; - - @NotNull - @ApiModelProperty(value = "密码", required = true, example = "123456") - private String password; - - public String getUserName() { - return userName; - } - - public void setUserName(String userName) { - this.userName = userName; - } - - public String getPassword() { - return password; - } - - public void setPassword(String password) { - this.password = password; - } -} +package org.cloud.sonic.controller.models.http; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +import javax.validation.constraints.NotNull; + +@ApiModel("登录请求模型") +public class UserInfo { + @NotNull + @ApiModelProperty(value = "账户名", required = true, example = "ZhouYiXun") + private String userName; + + @NotNull + @ApiModelProperty(value = "密码", required = true, example = "123456") + private String password; + + public String getUserName() { + return userName; + } + + public void setUserName(String userName) { + this.userName = userName; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } +} diff --git a/sonic-server-controller/src/main/java/com/sonic/controller/models/interfaces/AgentStatus.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/interfaces/AgentStatus.java similarity index 73% rename from sonic-server-controller/src/main/java/com/sonic/controller/models/interfaces/AgentStatus.java rename to sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/interfaces/AgentStatus.java index fb8f606a..b58c3757 100644 --- a/sonic-server-controller/src/main/java/com/sonic/controller/models/interfaces/AgentStatus.java +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/interfaces/AgentStatus.java @@ -1,10 +1,10 @@ -package com.sonic.controller.models.interfaces; -/** - * @author ZhouYiXun - * @des 定义Agent端状态类型 - * @date 2021/8/15 19:29 - */ -public interface AgentStatus { - int ONLINE = 1; - int OFFLINE = 2; -} +package org.cloud.sonic.controller.models.interfaces; +/** + * @author ZhouYiXun + * @des 定义Agent端状态类型 + * @date 2021/8/15 19:29 + */ +public interface AgentStatus { + int ONLINE = 1; + int OFFLINE = 2; +} diff --git a/sonic-server-controller/src/main/java/com/sonic/controller/models/interfaces/CoverType.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/interfaces/CoverType.java similarity index 56% rename from sonic-server-controller/src/main/java/com/sonic/controller/models/interfaces/CoverType.java rename to sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/interfaces/CoverType.java index 0f44d71d..c8da6734 100644 --- a/sonic-server-controller/src/main/java/com/sonic/controller/models/interfaces/CoverType.java +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/interfaces/CoverType.java @@ -1,6 +1,6 @@ -package com.sonic.controller.models.interfaces; - -public interface CoverType { - int CASE = 1; - int DEVICE = 2; -} +package org.cloud.sonic.controller.models.interfaces; + +public interface CoverType { + int CASE = 1; + int DEVICE = 2; +} diff --git a/sonic-server-controller/src/main/java/com/sonic/controller/models/interfaces/DeviceStatus.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/interfaces/DeviceStatus.java similarity index 84% rename from sonic-server-controller/src/main/java/com/sonic/controller/models/interfaces/DeviceStatus.java rename to sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/interfaces/DeviceStatus.java index 9b342b69..23db6984 100644 --- a/sonic-server-controller/src/main/java/com/sonic/controller/models/interfaces/DeviceStatus.java +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/interfaces/DeviceStatus.java @@ -1,16 +1,16 @@ -package com.sonic.controller.models.interfaces; - -/** - * @author ZhouYiXun - * @des 枚举设备状态 - * @date 2021/08/16 19:26 - */ -public interface DeviceStatus { - String ONLINE = "ONLINE"; - String OFFLINE = "OFFLINE"; - String TESTING = "TESTING"; - String DEBUGGING = "DEBUGGING"; - String ERROR = "ERROR"; - String UNAUTHORIZED = "UNAUTHORIZED"; - String DISCONNECTED = "DISCONNECTED"; -} +package org.cloud.sonic.controller.models.interfaces; + +/** + * @author ZhouYiXun + * @des 枚举设备状态 + * @date 2021/08/16 19:26 + */ +public interface DeviceStatus { + String ONLINE = "ONLINE"; + String OFFLINE = "OFFLINE"; + String TESTING = "TESTING"; + String DEBUGGING = "DEBUGGING"; + String ERROR = "ERROR"; + String UNAUTHORIZED = "UNAUTHORIZED"; + String DISCONNECTED = "DISCONNECTED"; +} diff --git a/sonic-server-controller/src/main/java/com/sonic/controller/models/interfaces/PlatformType.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/interfaces/PlatformType.java similarity index 77% rename from sonic-server-controller/src/main/java/com/sonic/controller/models/interfaces/PlatformType.java rename to sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/interfaces/PlatformType.java index 6ebab067..24b1008c 100644 --- a/sonic-server-controller/src/main/java/com/sonic/controller/models/interfaces/PlatformType.java +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/interfaces/PlatformType.java @@ -1,14 +1,14 @@ -package com.sonic.controller.models.interfaces; - -/** - * @author ZhouYiXun - * @des 定义全局平台类型 - * @date 2021/8/15 19:26 - */ -public interface PlatformType { - int ANDROID = 1; - int IOS = 2; - int WINDOWS = 3; - int MAC = 4; - int WEB = 5; -} +package org.cloud.sonic.controller.models.interfaces; + +/** + * @author ZhouYiXun + * @des 定义全局平台类型 + * @date 2021/8/15 19:26 + */ +public interface PlatformType { + int ANDROID = 1; + int IOS = 2; + int WINDOWS = 3; + int MAC = 4; + int WEB = 5; +} diff --git a/sonic-server-controller/src/main/java/com/sonic/controller/models/interfaces/ResultDetailStatus.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/interfaces/ResultDetailStatus.java similarity index 63% rename from sonic-server-controller/src/main/java/com/sonic/controller/models/interfaces/ResultDetailStatus.java rename to sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/interfaces/ResultDetailStatus.java index 5d24b58b..11a59fee 100644 --- a/sonic-server-controller/src/main/java/com/sonic/controller/models/interfaces/ResultDetailStatus.java +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/interfaces/ResultDetailStatus.java @@ -1,7 +1,7 @@ -package com.sonic.controller.models.interfaces; - -public interface ResultDetailStatus { - int PASS = 1; - int WARN = 2; - int FAIL = 3; -} +package org.cloud.sonic.controller.models.interfaces; + +public interface ResultDetailStatus { + int PASS = 1; + int WARN = 2; + int FAIL = 3; +} diff --git a/sonic-server-controller/src/main/java/com/sonic/controller/models/interfaces/ResultStatus.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/interfaces/ResultStatus.java similarity index 75% rename from sonic-server-controller/src/main/java/com/sonic/controller/models/interfaces/ResultStatus.java rename to sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/interfaces/ResultStatus.java index 73fd6edf..87a07e4c 100644 --- a/sonic-server-controller/src/main/java/com/sonic/controller/models/interfaces/ResultStatus.java +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/interfaces/ResultStatus.java @@ -1,13 +1,13 @@ -package com.sonic.controller.models.interfaces; - -/** - * @author ZhouYiXun - * @des 定义状态 - * @date 2021/8/15 19:50 - */ -public interface ResultStatus { - int RUNNING = 0; - int PASS = 1; - int WARNING = 2; - int FAIL = 3; -} +package org.cloud.sonic.controller.models.interfaces; + +/** + * @author ZhouYiXun + * @des 定义状态 + * @date 2021/8/15 19:50 + */ +public interface ResultStatus { + int RUNNING = 0; + int PASS = 1; + int WARNING = 2; + int FAIL = 3; +} diff --git a/sonic-server-controller/src/main/java/com/sonic/controller/models/interfaces/RobotType.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/interfaces/RobotType.java similarity index 68% rename from sonic-server-controller/src/main/java/com/sonic/controller/models/interfaces/RobotType.java rename to sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/interfaces/RobotType.java index af65e8d6..ed8da50c 100644 --- a/sonic-server-controller/src/main/java/com/sonic/controller/models/interfaces/RobotType.java +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/interfaces/RobotType.java @@ -1,4 +1,4 @@ -package com.sonic.controller.models.interfaces; +package org.cloud.sonic.controller.models.interfaces; public interface RobotType { int DingTalk = 1; diff --git a/sonic-server-controller/src/main/java/com/sonic/controller/models/interfaces/StepType.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/interfaces/StepType.java similarity index 75% rename from sonic-server-controller/src/main/java/com/sonic/controller/models/interfaces/StepType.java rename to sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/interfaces/StepType.java index 7dade672..12fbbec0 100644 --- a/sonic-server-controller/src/main/java/com/sonic/controller/models/interfaces/StepType.java +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/interfaces/StepType.java @@ -1,13 +1,13 @@ -package com.sonic.controller.models.interfaces; - -/** - * @author ZhouYiXun - * @des 定义log类型 - * @date 2021/8/15 19:26 - */ -public interface StepType { - int INFO = 1; - int PASS = 2; - int WARN = 3; - int ERROR = 4; +package org.cloud.sonic.controller.models.interfaces; + +/** + * @author ZhouYiXun + * @des 定义log类型 + * @date 2021/8/15 19:26 + */ +public interface StepType { + int INFO = 1; + int PASS = 2; + int WARN = 3; + int ERROR = 4; } \ No newline at end of file diff --git a/sonic-server-controller/src/main/java/com/sonic/controller/models/interfaces/UserRoles.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/interfaces/UserRoles.java similarity index 62% rename from sonic-server-controller/src/main/java/com/sonic/controller/models/interfaces/UserRoles.java rename to sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/interfaces/UserRoles.java index b5b3c0e2..f5dee55c 100644 --- a/sonic-server-controller/src/main/java/com/sonic/controller/models/interfaces/UserRoles.java +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/interfaces/UserRoles.java @@ -1,7 +1,7 @@ -package com.sonic.controller.models.interfaces; - -public interface UserRoles { - int MANAGER = 1; - int TEST = 2; - int DEVELOP = 3; -} +package org.cloud.sonic.controller.models.interfaces; + +public interface UserRoles { + int MANAGER = 1; + int TEST = 2; + int DEVELOP = 3; +} diff --git a/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/params/DevicesSearchParams.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/params/DevicesSearchParams.java new file mode 100644 index 00000000..d49f0acf --- /dev/null +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/params/DevicesSearchParams.java @@ -0,0 +1,48 @@ +package org.cloud.sonic.controller.models.params; + +import io.swagger.annotations.ApiModelProperty; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; + +import java.util.List; + +/** + * 设备搜索参数 + * + * @author JayWenStar + * @date 2021/12/22 9:56 下午 + */ +@Data +@Accessors(chain = true) +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class DevicesSearchParams { + + @ApiModelProperty("ios版本") + private List iOSVersion; + + @ApiModelProperty("android版本") + private List androidVersion; + + @ApiModelProperty("制造商") + private List manufacturer; + + @ApiModelProperty("cpu类型") + private List cpu; + + @ApiModelProperty("屏幕尺寸") + private List size; + + @ApiModelProperty("所在Agent") + private List agentId; + + @ApiModelProperty("当前状态") + private List status; + + @ApiModelProperty("设备udId等信息") + private String deviceInfo; +} diff --git a/sonic-server-controller/src/main/java/org/cloud/sonic/controller/services/AgentsService.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/services/AgentsService.java new file mode 100644 index 00000000..2aa09d07 --- /dev/null +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/services/AgentsService.java @@ -0,0 +1,32 @@ +package org.cloud.sonic.controller.services; + +import com.alibaba.fastjson.JSONObject; +import com.baomidou.mybatisplus.extension.service.IService; +import org.cloud.sonic.controller.models.domain.Agents; + +import java.util.List; + +/** + * @author ZhouYiXun + * @des Agent逻辑层 + * @date 2021/8/19 22:51 + */ +public interface AgentsService extends IService { + List findAgents(); + + void updateName(int id, String name); + + boolean offLine(int id); + + int auth(String key); + + String findKeyById(int id); + + Agents findById(int id); + + public void saveAgents(JSONObject jsonObject); + + public void saveAgents(Agents agents); + + public Agents findBySecretKey(String secretKey); +} \ No newline at end of file diff --git a/sonic-server-controller/src/main/java/com/sonic/controller/services/DevicesService.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/services/DevicesService.java similarity index 58% rename from sonic-server-controller/src/main/java/com/sonic/controller/services/DevicesService.java rename to sonic-server-controller/src/main/java/org/cloud/sonic/controller/services/DevicesService.java index aacfef9f..cc278eb7 100644 --- a/sonic-server-controller/src/main/java/com/sonic/controller/services/DevicesService.java +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/services/DevicesService.java @@ -1,45 +1,49 @@ -package com.sonic.controller.services; - -import com.alibaba.fastjson.JSONObject; -import com.sonic.controller.models.Devices; -import com.sonic.controller.models.http.DeviceDetailChange; -import com.sonic.controller.models.http.UpdateDeviceImg; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.Pageable; - -import java.util.List; - -/** - * @author ZhouYiXun - * @des 设备逻辑层 - * @date 2021/8/16 22:51 - */ -public interface DevicesService { - boolean saveDetail(DeviceDetailChange deviceDetailChange); - - void updateDevicesUser(JSONObject jsonObject); - - void updateImg(UpdateDeviceImg updateDeviceImg); - - void save(Devices devices); - - Page findAll(List iOSVersion, List androidVersion, List manufacturer, - List cpu, List size, List agentId, List status, - String deviceInfo, Pageable pageable); - - List findAll(int platform); - - List findByIdIn(List ids); - - Devices findByAgentIdAndUdId(int agentId, String udId); - - JSONObject getFilterOption(); - - void deviceStatus(JSONObject jsonObject); - - Devices findById(int id); - - Integer findTemper(); - - void refreshDevicesTemper(JSONObject jsonObject); -} +package org.cloud.sonic.controller.services; + +import com.alibaba.fastjson.JSONObject; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.baomidou.mybatisplus.extension.service.IService; +import org.cloud.sonic.controller.models.domain.Devices; +import org.cloud.sonic.controller.models.http.DeviceDetailChange; +import org.cloud.sonic.controller.models.http.UpdateDeviceImg; + +import java.io.IOException; +import java.util.List; + +/** + * @author ZhouYiXun + * @des 设备逻辑层 + * @date 2021/8/16 22:51 + */ +public interface DevicesService extends IService { + boolean saveDetail(DeviceDetailChange deviceDetailChange); + + void updateDevicesUser(JSONObject jsonObject); + + void updateImg(UpdateDeviceImg updateDeviceImg); + + Page findAll(List iOSVersion, List androidVersion, List manufacturer, + List cpu, List size, List agentId, List status, + String deviceInfo, Page pageable); + + List findAll(int platform); + + List findByIdIn(List ids); + + Devices findByAgentIdAndUdId(int agentId, String udId); + + + JSONObject getFilterOption(); + + void deviceStatus(JSONObject jsonObject); + + Devices findById(int id); + + List listByAgentId(int agentId); + + String getName(String model) throws IOException; + + void refreshDevicesTemper(JSONObject jsonObject); + + Integer findTemper(); +} diff --git a/sonic-server-controller/src/main/java/org/cloud/sonic/controller/services/ElementsService.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/services/ElementsService.java new file mode 100644 index 00000000..6fac3c09 --- /dev/null +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/services/ElementsService.java @@ -0,0 +1,21 @@ +package org.cloud.sonic.controller.services; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.baomidou.mybatisplus.extension.service.IService; +import org.cloud.sonic.common.http.RespModel; +import org.cloud.sonic.controller.models.domain.Elements; +import org.cloud.sonic.controller.models.dto.StepsDTO; + +import java.util.List; + +public interface ElementsService extends IService { + Page findAll(int projectId, String type, List eleTypes, String name, Page pageable); + + List findAllStepsByElementsId(int elementsId); + + RespModel delete(int id); + + Elements findById(int id); + + boolean deleteByProjectId(int projectId); +} diff --git a/sonic-server-controller/src/main/java/org/cloud/sonic/controller/services/GlobalParamsService.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/services/GlobalParamsService.java new file mode 100644 index 00000000..de620e9f --- /dev/null +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/services/GlobalParamsService.java @@ -0,0 +1,18 @@ +package org.cloud.sonic.controller.services; + +import com.baomidou.mybatisplus.extension.service.IService; +import org.cloud.sonic.controller.models.domain.GlobalParams; + +import java.util.List; + +public interface GlobalParamsService extends IService { + List findAll(int projectId); + + boolean delete(int id); + + GlobalParams findById(int id); + + boolean deleteByProjectId(int projectId); + + +} diff --git a/sonic-server-controller/src/main/java/org/cloud/sonic/controller/services/ModulesService.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/services/ModulesService.java new file mode 100644 index 00000000..ad7a2d61 --- /dev/null +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/services/ModulesService.java @@ -0,0 +1,17 @@ +package org.cloud.sonic.controller.services; + +import com.baomidou.mybatisplus.extension.service.IService; +import org.cloud.sonic.controller.models.domain.Modules; + +import java.util.List; + +public interface ModulesService extends IService { + + boolean delete(int id); + + List findByProjectId(int projectId); + + Modules findById(int id); + + boolean deleteByProjectId(int projectId); +} diff --git a/sonic-server-controller/src/main/java/org/cloud/sonic/controller/services/ProjectsService.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/services/ProjectsService.java new file mode 100644 index 00000000..aae2eb60 --- /dev/null +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/services/ProjectsService.java @@ -0,0 +1,21 @@ +package org.cloud.sonic.controller.services; + +import com.baomidou.mybatisplus.extension.service.IService; +import org.cloud.sonic.common.exception.SonicException; +import org.cloud.sonic.controller.models.domain.Projects; + +import java.util.List; + +/** + * @author ZhouYiXun + * @des 项目逻辑层 + * @date 2021/8/20 20:51 + */ +public interface ProjectsService extends IService { + + Projects findById(int id); + + List findAll(); + + void delete(int id) throws SonicException; +} diff --git a/sonic-server-controller/src/main/java/org/cloud/sonic/controller/services/PublicStepsService.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/services/PublicStepsService.java new file mode 100644 index 00000000..2100e5fa --- /dev/null +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/services/PublicStepsService.java @@ -0,0 +1,29 @@ +package org.cloud.sonic.controller.services; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.baomidou.mybatisplus.extension.service.IService; +import org.cloud.sonic.controller.models.base.CommentPage; +import org.cloud.sonic.controller.models.domain.PublicSteps; +import org.cloud.sonic.controller.models.dto.PublicStepsDTO; + +import java.util.List; +import java.util.Map; + +/** + * @author ZhouYiXun + * @des 公共步骤逻辑层 + * @date 2021/8/20 17:51 + */ +public interface PublicStepsService extends IService { + CommentPage findByProjectId(int projectId, Page pageable); + + List> findByProjectIdAndPlatform(int projectId, int platform); + + PublicStepsDTO savePublicSteps(PublicStepsDTO publicStepsDTO); + + boolean delete(int id); + + PublicStepsDTO findById(int id); + + boolean deleteByProjectId(int projectId); +} diff --git a/sonic-server-controller/src/main/java/org/cloud/sonic/controller/services/ResultDetailService.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/services/ResultDetailService.java new file mode 100644 index 00000000..bd089c20 --- /dev/null +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/services/ResultDetailService.java @@ -0,0 +1,32 @@ +package org.cloud.sonic.controller.services; + +import com.alibaba.fastjson.JSONObject; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.baomidou.mybatisplus.extension.service.IService; +import org.cloud.sonic.controller.models.domain.ResultDetail; + +import java.util.List; + +/** + * @author ZhouYiXun + * @des 测试结果详情逻辑层 + * @date 2021/8/21 16:08 + */ +public interface ResultDetailService extends IService { + + void saveByTransport(JSONObject jsonObject); + + Page findAll(int resultId, int caseId, String type, int deviceId, Page pageable); + + List findAll(int resultId, int caseId, String type, int deviceId); + + void deleteByResultId(int resultId); + + List findTimeByResultIdGroupByCaseId(int resultId); + + List findStatusByResultIdGroupByCaseId(int resultId); + + List findTopCases(String startTime, String endTime, int projectId); + + List findTopDevices(String startTime, String endTime, int projectId); +} diff --git a/sonic-server-controller/src/main/java/com/sonic/controller/services/ResultsService.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/services/ResultsService.java similarity index 50% rename from sonic-server-controller/src/main/java/com/sonic/controller/services/ResultsService.java rename to sonic-server-controller/src/main/java/org/cloud/sonic/controller/services/ResultsService.java index cd7bb02e..88d2c54f 100644 --- a/sonic-server-controller/src/main/java/com/sonic/controller/services/ResultsService.java +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/services/ResultsService.java @@ -1,36 +1,40 @@ -package com.sonic.controller.services; - -import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.JSONObject; -import com.sonic.controller.models.Results; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.Pageable; - -/** - * @author ZhouYiXun - * @des 测试结果逻辑层 - * @date 2021/8/21 16:08 - */ -public interface ResultsService { - Page findByProjectId(int projectId, Pageable pageable); - - boolean delete(int id); - - Results findById(int id); - - void save(Results results); - - void clean(int day); - - void suiteResult(int id); - - JSONArray findCaseStatus(int id); - - void subResultCount(int id); - - JSONObject chart(String startTime, String endTime, int projectId); - - void sendDayReport(); - - void sendWeekReport(); -} +package org.cloud.sonic.controller.services; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.baomidou.mybatisplus.extension.service.IService; +import org.cloud.sonic.controller.models.domain.Results; + +import java.util.List; + +/** + * @author ZhouYiXun + * @des 测试结果逻辑层 + * @date 2021/8/21 16:08 + */ +public interface ResultsService extends IService { + Page findByProjectId(int projectId, Page pageable); + + List findByProjectId(int projectId); + + boolean delete(int id); + + Results findById(int id); + + void clean(int day); + + void suiteResult(int id); + + JSONArray findCaseStatus(int id); + + void subResultCount(int id); + + JSONObject chart(String startTime, String endTime, int projectId); + + void sendDayReport(); + + void sendWeekReport(); + + void deleteByProjectId(int projectId); +} diff --git a/sonic-server-controller/src/main/java/org/cloud/sonic/controller/services/StepsService.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/services/StepsService.java new file mode 100644 index 00000000..15886cdb --- /dev/null +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/services/StepsService.java @@ -0,0 +1,40 @@ +package org.cloud.sonic.controller.services; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.baomidou.mybatisplus.extension.service.IService; +import org.cloud.sonic.controller.models.base.CommentPage; +import org.cloud.sonic.controller.models.domain.Steps; +import org.cloud.sonic.controller.models.dto.StepsDTO; +import org.cloud.sonic.controller.models.http.StepSort; + +import java.util.List; + +/** + * @author ZhouYiXun + * @des 测试步骤逻辑层 + * @date 2021/8/20 17:51 + */ +public interface StepsService extends IService { + List findByCaseIdOrderBySort(int caseId); + + boolean resetCaseId(int id); + + boolean delete(int id); + + void saveStep(StepsDTO operations); + + StepsDTO findById(int id); + + void sortSteps(StepSort stepSort); + + CommentPage findByProjectIdAndPlatform(int projectId, int platform, Page pageable); + + List listStepsByElementsId(int elementsId); + + boolean deleteByProjectId(int projectId); + + /** + * 获取公共步骤里面的步骤 + */ + List listByPublicStepsId(int publicStepsId); +} diff --git a/sonic-server-controller/src/main/java/org/cloud/sonic/controller/services/TestCasesService.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/services/TestCasesService.java new file mode 100644 index 00000000..5afde851 --- /dev/null +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/services/TestCasesService.java @@ -0,0 +1,31 @@ +package org.cloud.sonic.controller.services; + +import com.alibaba.fastjson.JSONObject; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.baomidou.mybatisplus.extension.service.IService; +import org.cloud.sonic.controller.models.domain.TestCases; + +import java.util.List; + +/** + * @author ZhouYiXun + * @des 测试用例逻辑层 + * @date 2021/8/20 17:51 + */ +public interface TestCasesService extends IService { + Page findAll(int projectId, int platform, String name, Page pageable); + + List findAll(int projectId, int platform); + + boolean delete(int id); + + TestCases findById(int id); + + JSONObject findSteps(int id); + + List findByIdIn(List ids); + + boolean deleteByProjectId(int projectId); + + List listByPublicStepsId(int publicStepsId); +} diff --git a/sonic-server-controller/src/main/java/org/cloud/sonic/controller/services/TestSuitesService.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/services/TestSuitesService.java new file mode 100644 index 00000000..6c9cf4ac --- /dev/null +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/services/TestSuitesService.java @@ -0,0 +1,35 @@ +package org.cloud.sonic.controller.services; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.baomidou.mybatisplus.extension.service.IService; +import org.cloud.sonic.common.http.RespModel; +import org.cloud.sonic.controller.models.base.CommentPage; +import org.cloud.sonic.controller.models.domain.TestSuites; +import org.cloud.sonic.controller.models.dto.TestSuitesDTO; + +import java.util.List; + +/** + * @author ZhouYiXun + * @des 测试套件逻辑层 + * @date 2021/8/20 17:51 + */ +public interface TestSuitesService extends IService { + RespModel runSuite(int id, String strike); + + RespModel forceStopSuite(int id, String strike); + + TestSuitesDTO findById(int id); + + boolean delete(int id); + + void saveTestSuites(TestSuitesDTO testSuitesDTO); + + CommentPage findByProjectId(int projectId, String name, Page pageable); + + List findByProjectId(int projectId); + + boolean deleteByProjectId(int projectId); + + List listTestSuitesByTestCasesId(int testCasesId); +} diff --git a/sonic-server-controller/src/main/java/org/cloud/sonic/controller/services/UsersService.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/services/UsersService.java new file mode 100644 index 00000000..08efbddc --- /dev/null +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/services/UsersService.java @@ -0,0 +1,20 @@ +package org.cloud.sonic.controller.services; + +import com.baomidou.mybatisplus.extension.service.IService; +import org.cloud.sonic.common.exception.SonicException; +import org.cloud.sonic.common.http.RespModel; +import org.cloud.sonic.controller.models.domain.Users; +import org.cloud.sonic.controller.models.http.ChangePwd; +import org.cloud.sonic.controller.models.http.UserInfo; + +public interface UsersService extends IService { + void register(Users users) throws SonicException; + + String login(UserInfo userInfo); + + Users getUserInfo(String token); + + RespModel resetPwd(String token, ChangePwd changePwd); + + Users findByUserName(String userName); +} diff --git a/sonic-server-controller/src/main/java/org/cloud/sonic/controller/services/VersionsService.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/services/VersionsService.java new file mode 100644 index 00000000..1d26b68b --- /dev/null +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/services/VersionsService.java @@ -0,0 +1,23 @@ +package org.cloud.sonic.controller.services; + + +import com.baomidou.mybatisplus.extension.service.IService; +import org.cloud.sonic.controller.models.domain.Versions; + +import java.util.List; + +/** + * @author ZhouYiXun + * @des 迭代逻辑层 + * @date 2021/8/16 22:54 + */ +public interface VersionsService extends IService { + + boolean delete(int id); + + List findByProjectId(int projectId); + + Versions findById(int id); + + void deleteByProjectId(int projectId); +} diff --git a/sonic-server-controller/src/main/java/com/sonic/controller/services/impl/AgentsServiceImpl.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/services/impl/AgentsServiceImpl.java similarity index 51% rename from sonic-server-controller/src/main/java/com/sonic/controller/services/impl/AgentsServiceImpl.java rename to sonic-server-controller/src/main/java/org/cloud/sonic/controller/services/impl/AgentsServiceImpl.java index 794c0231..6a44db9c 100644 --- a/sonic-server-controller/src/main/java/com/sonic/controller/services/impl/AgentsServiceImpl.java +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/services/impl/AgentsServiceImpl.java @@ -1,119 +1,125 @@ -package com.sonic.controller.services.impl; - -import com.alibaba.fastjson.JSONObject; -import com.sonic.controller.dao.AgentsRepository; -import com.sonic.controller.dao.DevicesRepository; -import com.sonic.controller.models.Agents; -import com.sonic.controller.models.Devices; -import com.sonic.controller.models.interfaces.AgentStatus; -import com.sonic.controller.models.interfaces.DeviceStatus; -import com.sonic.controller.services.AgentsService; -import org.aspectj.weaver.loadtime.Agent; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.cache.annotation.Cacheable; -import org.springframework.stereotype.Service; - -import java.util.List; -import java.util.UUID; - -@Service -public class AgentsServiceImpl implements AgentsService { - @Autowired - private AgentsRepository agentsRepository; - @Autowired - private DevicesRepository devicesRepository; - - @Override - public List findAgents() { - return agentsRepository.findAll(); - } - - @Override - public void updateName(int id, String name) { - if (id == 0) { - Agents agents = new Agents(); - agents.setName(name); - agents.setHost("未知"); - agents.setStatus(AgentStatus.OFFLINE); - agents.setVersion("未知"); - agents.setPort(0); - agents.setSystemType("未知"); - agents.setSecretKey(UUID.randomUUID().toString()); - agentsRepository.save(agents); - } else { - if (agentsRepository.existsById(id)) { - Agents a = agentsRepository.findById(id).get(); - a.setName(name); - agentsRepository.save(a); - } - } - } - - public void resetDevice(int id) { - List devicesList = devicesRepository.findByAgentId(id); - for (Devices devices : devicesList) { - if ((!devices.getStatus().equals(DeviceStatus.OFFLINE)) - && (!devices.getStatus().equals(DeviceStatus.DISCONNECTED))) { - devices.setStatus(DeviceStatus.OFFLINE); - devicesRepository.save(devices); - } - } - } - - @Override - public void save(JSONObject jsonObject) { - if (jsonObject.getInteger("agentId") != null && jsonObject.getInteger("agentId") != 0) { - if (agentsRepository.existsById(jsonObject.getInteger("agentId"))) { - Agents oldAgent = agentsRepository.findById(jsonObject.getInteger("agentId")).get(); - oldAgent.setStatus(AgentStatus.ONLINE); - oldAgent.setHost(jsonObject.getString("host")); - oldAgent.setPort(jsonObject.getInteger("port")); - oldAgent.setVersion(jsonObject.getString("version")); - oldAgent.setSystemType(jsonObject.getString("systemType")); - agentsRepository.save(oldAgent); - } - } - } - - @Override - public boolean offLine(int id) { - if (agentsRepository.existsById(id)) { - Agents agentOffLine = agentsRepository.findById(id).get(); - agentOffLine.setStatus(AgentStatus.OFFLINE); - agentsRepository.save(agentOffLine); - resetDevice(agentOffLine.getId()); - return true; - } else { - return false; - } - } - - @Override - public int auth(String key) { - Agents agents = agentsRepository.findBySecretKey(key); - if (agents == null) { - return 0; - } else { - resetDevice(agents.getId()); - return agents.getId(); - } - } - - @Override - public String findKeyById(int id) { - if (agentsRepository.existsById(id)) { - return agentsRepository.findById(id).get().getSecretKey(); - } else { - return null; - } - } - - @Override - public Agents findById(int id) { - if (agentsRepository.existsById(id)) { - return agentsRepository.findById(id).get(); - } else { - return null; - } - } -} +package org.cloud.sonic.controller.services.impl; + +import com.alibaba.fastjson.JSONObject; +import com.baomidou.mybatisplus.core.toolkit.ObjectUtils; +import org.cloud.sonic.controller.mapper.AgentsMapper; +import org.cloud.sonic.controller.models.domain.Agents; +import org.cloud.sonic.controller.models.domain.Devices; +import org.cloud.sonic.controller.models.interfaces.AgentStatus; +import org.cloud.sonic.controller.models.interfaces.DeviceStatus; +import org.cloud.sonic.controller.services.AgentsService; +import org.cloud.sonic.controller.services.DevicesService; +import org.cloud.sonic.controller.services.impl.base.SonicServiceImpl; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import javax.annotation.Resource; +import java.util.List; +import java.util.Optional; +import java.util.UUID; + +@Service +public class AgentsServiceImpl extends SonicServiceImpl implements AgentsService { + + @Autowired + private DevicesService devicesService; + @Resource + private AgentsMapper agentsMapper; + + @Override + public List findAgents() { + return list(); + } + + @Override + public void updateName(int id, String name) { + if (id == 0) { + Agents agents = new Agents(); + agents.setName(name); + agents.setHost("未知"); + agents.setStatus(AgentStatus.OFFLINE); + agents.setVersion("未知"); + agents.setPort(0); + agents.setSystemType("未知"); + agents.setSecretKey(UUID.randomUUID().toString()); + save(agents); + } else { + Agents ag = findById(id); + if (ObjectUtils.isNotEmpty(ag)) { + ag.setName(name); + save(ag); + } + } + } + + public void resetDevice(int id) { + List devicesList = devicesService.listByAgentId(id); + for (Devices devices : devicesList) { + if ((!devices.getStatus().equals(DeviceStatus.OFFLINE)) + && (!devices.getStatus().equals(DeviceStatus.DISCONNECTED))) { + devices.setStatus(DeviceStatus.OFFLINE); + devicesService.save(devices); + } + } + } + + @Override + public void saveAgents(JSONObject jsonObject) { + if (jsonObject.getInteger("agentId") != null && jsonObject.getInteger("agentId") != 0) { + if (existsById(jsonObject.getInteger("agentId"))) { + Agents oldAgent = findById(jsonObject.getInteger("agentId")); + oldAgent.setStatus(AgentStatus.ONLINE); + oldAgent.setHost(jsonObject.getString("host")); + oldAgent.setPort(jsonObject.getInteger("port")); + oldAgent.setVersion(jsonObject.getString("version")); + oldAgent.setSystemType(jsonObject.getString("systemType")); + save(oldAgent); + } + } + } + + @Override + public void saveAgents(Agents agents) { + save(agents); + } + + @Override + public boolean offLine(int id) { + if (existsById(id)) { + Agents agentOffLine = findById(id); + agentOffLine.setStatus(AgentStatus.OFFLINE); + save(agentOffLine); + resetDevice(agentOffLine.getId()); + return true; + } else { + return false; + } + } + + @Override + public int auth(String key) { + Agents agents = findBySecretKey(key); + if (agents == null) { + return 0; + } else { + resetDevice(agents.getId()); + return agents.getId(); + } + } + + @Override + public String findKeyById(int id) { + Optional agents = lambdaQuery().eq(Agents::getId, id).select(Agents::getSecretKey).oneOpt(); + return agents.map(Agents::getSecretKey).orElse(null); + } + + @Override + public Agents findById(int id) { + return baseMapper.selectById(id); + } + + @Override + public Agents findBySecretKey(String secretKey) { + return lambdaQuery().eq(Agents::getSecretKey, secretKey).one(); + } +} diff --git a/sonic-server-controller/src/main/java/org/cloud/sonic/controller/services/impl/DevicesServiceImpl.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/services/impl/DevicesServiceImpl.java new file mode 100644 index 00000000..77a3825d --- /dev/null +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/services/impl/DevicesServiceImpl.java @@ -0,0 +1,223 @@ +package org.cloud.sonic.controller.services.impl; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import org.cloud.sonic.controller.mapper.DevicesMapper; +import org.cloud.sonic.controller.models.domain.Devices; +import org.cloud.sonic.controller.models.domain.Users; +import org.cloud.sonic.controller.models.http.DeviceDetailChange; +import org.cloud.sonic.controller.models.http.UpdateDeviceImg; +import org.cloud.sonic.controller.models.interfaces.DeviceStatus; +import org.cloud.sonic.controller.models.params.DevicesSearchParams; +import org.cloud.sonic.controller.services.DevicesService; +import org.cloud.sonic.controller.services.UsersService; +import org.cloud.sonic.controller.services.impl.base.SonicServiceImpl; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.io.IOException; +import java.io.InputStream; +import java.util.Arrays; +import java.util.List; + +/** + * @author ZhouYiXun + * @des 设备逻辑层实现 + * @date 2021/8/16 22:51 + */ +@Service +public class DevicesServiceImpl extends SonicServiceImpl implements DevicesService { + + @Autowired + private DevicesMapper devicesMapper; + + @Autowired + private UsersService usersService; + + @Override + public boolean saveDetail(DeviceDetailChange deviceDetailChange) { + if (existsById(deviceDetailChange.getId())) { + Devices devices = findById(deviceDetailChange.getId()); + devices.setNickName(deviceDetailChange.getNickName()); + devices.setPassword(deviceDetailChange.getPassword()); + save(devices); + return true; + } else { + return false; + } + } + + @Override + public void updateDevicesUser(JSONObject jsonObject) { + Users users = usersService.getUserInfo(jsonObject.getString("token")); + Devices devices = findByAgentIdAndUdId(jsonObject.getInteger("agentId"), + jsonObject.getString("udId")); + devices.setUser(users.getUserName()); + save(devices); + } + + @Override + public void updateImg(UpdateDeviceImg updateDeviceImg) { + if (existsById(updateDeviceImg.getId())) { + Devices devices = findById(updateDeviceImg.getId()); + devices.setImgUrl(updateDeviceImg.getImgUrl()); + save(devices); + } + } + + @Override + public Page findAll(List iOSVersion, List androidVersion, List manufacturer, + List cpu, List size, List agentId, List status, + String deviceInfo, Page pageable) { + DevicesSearchParams params = new DevicesSearchParams() + .setIOSVersion(iOSVersion) + .setAndroidVersion(androidVersion) + .setManufacturer(manufacturer) + .setCpu(cpu) + .setSize(size) + .setAgentId(agentId) + .setStatus(status) + .setDeviceInfo(deviceInfo); + return devicesMapper.findByParams(pageable, params); + } + + @Override + public List findAll(int platform) { + return lambdaQuery().eq(Devices::getPlatform, platform).orderByDesc(Devices::getId).list(); + } + + @Override + public List findByIdIn(List ids) { + return lambdaQuery().in(Devices::getId, ids).list(); + } + + @Override + public Devices findByAgentIdAndUdId(int agentId, String udId) { + return lambdaQuery().eq(Devices::getAgentId, agentId).eq(Devices::getUdId, udId).one(); + } + + @Override + public JSONObject getFilterOption() { + JSONObject jsonObject = new JSONObject(); + List cpuList = devicesMapper.findCpuList(); + if (cpuList.contains("未知")) { + cpuList.remove("未知"); + cpuList.add("未知"); + } + jsonObject.put("cpu", cpuList); + List sizeList = devicesMapper.findSizeList(); + if (sizeList.contains("未知")) { + sizeList.remove("未知"); + sizeList.add("未知"); + } + jsonObject.put("size", sizeList); + return jsonObject; + } + + @Override + public void deviceStatus(JSONObject jsonMsg) { + Devices devices = findByAgentIdAndUdId(jsonMsg.getInteger("agentId") + , jsonMsg.getString("udId")); + if (devices == null) { + Devices newDevices = new Devices(); + newDevices.setUdId(jsonMsg.getString("udId")); + if (jsonMsg.getString("name") != null) { + newDevices.setName(jsonMsg.getString("name")); + } + if (jsonMsg.getString("model") != null) { + newDevices.setName(jsonMsg.getString("model")); + } + newDevices.setNickName(""); + newDevices.setUser(""); + newDevices.setPlatform(jsonMsg.getInteger("platform")); + newDevices.setVersion(jsonMsg.getString("version")); + newDevices.setCpu(jsonMsg.getString("cpu")); + newDevices.setSize(jsonMsg.getString("size")); + newDevices.setManufacturer(jsonMsg.getString("manufacturer")); + newDevices.setAgentId(jsonMsg.getInteger("agentId")); + newDevices.setStatus(jsonMsg.getString("status")); + newDevices.setPassword(""); + newDevices.setImgUrl(""); + newDevices.setTemperature(0); + save(newDevices); + } else { + devices.setAgentId(jsonMsg.getInteger("agentId")); + if (jsonMsg.getString("name") != null) { + if (!jsonMsg.getString("name").equals("未知")) { + devices.setName(jsonMsg.getString("name")); + } + } + if (jsonMsg.getString("model") != null) { + if (!jsonMsg.getString("model").equals("未知")) { + devices.setModel(jsonMsg.getString("model")); + } + } + if (jsonMsg.getString("version") != null) { + devices.setVersion(jsonMsg.getString("version")); + } + if (jsonMsg.getString("platform") != null) { + devices.setPlatform(jsonMsg.getInteger("platform")); + } + if (jsonMsg.getString("cpu") != null) { + devices.setCpu(jsonMsg.getString("cpu")); + } + if (jsonMsg.getString("size") != null) { + devices.setSize(jsonMsg.getString("size")); + } + if (jsonMsg.getString("manufacturer") != null) { + devices.setManufacturer(jsonMsg.getString("manufacturer")); + } + devices.setStatus(jsonMsg.getString("status")); + save(devices); + } + } + + @Override + public Devices findById(int id) { + return baseMapper.selectById(id); + } + + @Override + public List listByAgentId(int agentId) { + return lambdaQuery().eq(Devices::getAgentId, agentId).list(); + } + + @Override + public String getName(String model) { + InputStream config = getClass().getResourceAsStream("/result.json"); + JSONObject jsonObject = null; + try { + jsonObject = JSON.parseObject(config, JSONObject.class); + } catch (IOException e) { + e.printStackTrace(); + } finally { + try { + config.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + return jsonObject.getString(model) == null ? "" : jsonObject.getString(model); + } + + @Override + public void refreshDevicesTemper(JSONObject jsonObject) { + int agentId = jsonObject.getInteger("agentId"); + List deviceTemList = jsonObject.getJSONArray("detail").toJavaList(JSONObject.class); + for (JSONObject d : deviceTemList) { + Devices devices = findByAgentIdAndUdId(agentId, d.getString("udId")); + if (devices != null) { + devices.setTemperature(d.getInteger("tem")); + save(devices); + } + } + } + + @Override + public Integer findTemper() { + return devicesMapper.findTemper(Arrays.asList(DeviceStatus.ONLINE + ,DeviceStatus.DEBUGGING,DeviceStatus.TESTING)); + } + +} diff --git a/sonic-server-controller/src/main/java/org/cloud/sonic/controller/services/impl/ElementsServiceImpl.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/services/impl/ElementsServiceImpl.java new file mode 100644 index 00000000..f4eca4c1 --- /dev/null +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/services/impl/ElementsServiceImpl.java @@ -0,0 +1,95 @@ +package org.cloud.sonic.controller.services.impl; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import org.cloud.sonic.common.http.RespEnum; +import org.cloud.sonic.common.http.RespModel; +import org.cloud.sonic.controller.mapper.ElementsMapper; +import org.cloud.sonic.controller.models.domain.Elements; +import org.cloud.sonic.controller.models.dto.StepsDTO; +import org.cloud.sonic.controller.models.dto.TestCasesDTO; +import org.cloud.sonic.controller.services.ElementsService; +import org.cloud.sonic.controller.services.StepsService; +import org.cloud.sonic.controller.services.TestCasesService; +import org.cloud.sonic.controller.services.impl.base.SonicServiceImpl; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.List; +import java.util.stream.Collectors; + +@Service +public class ElementsServiceImpl extends SonicServiceImpl implements ElementsService { + + @Autowired + private ElementsMapper elementsMapper; + @Autowired + private StepsService stepsService; + @Autowired + private TestCasesService testCasesService; + + @Override + public Page findAll(int projectId, String type, List eleTypes, String name, Page pageable) { + LambdaQueryChainWrapper lambdaQuery = lambdaQuery(); + + if (type != null && type.length() > 0) { + switch (type) { + case "normal" -> lambdaQuery.and( + l -> l.ne(Elements::getEleType, "point").ne(Elements::getEleType, "image") + ); + case "point" -> lambdaQuery.eq(Elements::getEleType, "point"); + case "image" -> lambdaQuery.eq(Elements::getEleType, "image"); + } + } + + if (eleTypes != null) { + lambdaQuery.in(Elements::getEleType, eleTypes); + } + if (name != null && name.length() > 0) { + lambdaQuery.like(Elements::getEleName, name); + } + + lambdaQuery.eq(Elements::getProjectId, projectId); + lambdaQuery.orderByDesc(Elements::getId); + + return lambdaQuery.page(pageable); + } + + @Override + public List findAllStepsByElementsId(int elementsId) { + return stepsService.listStepsByElementsId(elementsId).stream().map(e -> { + StepsDTO stepsDTO = e.convertTo(); + if (0 == stepsDTO.getCaseId()) { + return stepsDTO.setTestCasesDTO(new TestCasesDTO().setId(0).setName("无所属用例")); + } + return stepsDTO.setTestCasesDTO(testCasesService.findById(stepsDTO.getCaseId()).convertTo()); + }).collect(Collectors.toList()); + } + + @Override + @Transactional(rollbackFor = Exception.class) + public RespModel delete(int id) { + if (existsById(id)) { + List stepsList = findAllStepsByElementsId(id); + for (StepsDTO steps : stepsList) { + stepsService.delete(steps.getId()); + } + baseMapper.deleteById(id); + return new RespModel<>(RespEnum.DELETE_OK); + } else { + return new RespModel<>(RespEnum.ID_NOT_FOUND); + } + } + + @Override + public Elements findById(int id) { + return baseMapper.selectById(id); + } + + @Override + public boolean deleteByProjectId(int projectId) { + return baseMapper.delete(new LambdaQueryWrapper().eq(Elements::getProjectId, projectId)) > 0; + } +} diff --git a/sonic-server-controller/src/main/java/org/cloud/sonic/controller/services/impl/GlobalParamsServiceImpl.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/services/impl/GlobalParamsServiceImpl.java new file mode 100644 index 00000000..80447e60 --- /dev/null +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/services/impl/GlobalParamsServiceImpl.java @@ -0,0 +1,43 @@ +package org.cloud.sonic.controller.services.impl; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import org.cloud.sonic.controller.mapper.GlobalParamsMapper; +import org.cloud.sonic.controller.models.domain.GlobalParams; +import org.cloud.sonic.controller.services.GlobalParamsService; +import org.cloud.sonic.controller.services.impl.base.SonicServiceImpl; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.List; + +/** + * @author ZhouYiXun + * @des + * @date 2021/10/9 23:28 + */ +@Service +public class GlobalParamsServiceImpl extends SonicServiceImpl implements GlobalParamsService { + + @Autowired + private GlobalParamsMapper globalParamsMapper; + + @Override + public List findAll(int projectId) { + return lambdaQuery().eq(GlobalParams::getProjectId, projectId).list(); + } + + @Override + public boolean delete(int id) { + return baseMapper.deleteById(id) > 0; + } + + @Override + public GlobalParams findById(int id) { + return baseMapper.selectById(id); + } + + @Override + public boolean deleteByProjectId(int projectId) { + return baseMapper.delete(new LambdaQueryWrapper().eq(GlobalParams::getProjectId, projectId)) > 0; + } +} diff --git a/sonic-server-controller/src/main/java/org/cloud/sonic/controller/services/impl/ModulesServiceImpl.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/services/impl/ModulesServiceImpl.java new file mode 100644 index 00000000..f4bf1a66 --- /dev/null +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/services/impl/ModulesServiceImpl.java @@ -0,0 +1,38 @@ +package org.cloud.sonic.controller.services.impl; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import org.cloud.sonic.controller.mapper.ModulesMapper; +import org.cloud.sonic.controller.models.domain.Modules; +import org.cloud.sonic.controller.services.ModulesService; +import org.cloud.sonic.controller.services.impl.base.SonicServiceImpl; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.List; + +@Service +public class ModulesServiceImpl extends SonicServiceImpl implements ModulesService { + + @Autowired + private ModulesMapper modulesMapper; + + @Override + public boolean delete(int id) { + return modulesMapper.deleteById(id) > 0; + } + + @Override + public List findByProjectId(int projectId) { + return lambdaQuery().eq(Modules::getProjectId, projectId).list(); + } + + @Override + public Modules findById(int id) { + return modulesMapper.selectById(id); + } + + @Override + public boolean deleteByProjectId(int projectId) { + return baseMapper.delete(new LambdaQueryWrapper().eq(Modules::getProjectId, projectId)) > 0; + } +} diff --git a/sonic-server-controller/src/main/java/org/cloud/sonic/controller/services/impl/ProjectsServiceImpl.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/services/impl/ProjectsServiceImpl.java new file mode 100644 index 00000000..d0f80ba3 --- /dev/null +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/services/impl/ProjectsServiceImpl.java @@ -0,0 +1,66 @@ +package org.cloud.sonic.controller.services.impl; + +import org.cloud.sonic.common.exception.SonicException; +import org.cloud.sonic.controller.mapper.ProjectsMapper; +import org.cloud.sonic.controller.models.domain.Projects; +import org.cloud.sonic.controller.models.domain.Results; +import org.cloud.sonic.controller.services.*; +import org.cloud.sonic.controller.services.impl.base.SonicServiceImpl; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.List; + +/** + * @author ZhouYiXun + * @des 项目逻辑实现 + * @date 2021/8/21 20:57 + */ +@Service +public class ProjectsServiceImpl extends SonicServiceImpl implements ProjectsService { + + @Autowired private ElementsService elementsService; + @Autowired private GlobalParamsService globalParamsService; + @Autowired private ModulesService modulesService; + @Autowired private VersionsService versionsService; + @Autowired private PublicStepsService publicStepsService; + @Autowired private ResultsService resultsService; + @Autowired private ResultDetailService resultDetailService; + @Autowired private StepsService stepsService; + @Autowired private TestSuitesService testSuitesService; + @Autowired private TestCasesService testCasesService; + + @Override + public Projects findById(int id) { + return baseMapper.selectById(id); + } + + @Override + public List findAll() { + return list(); + } + + @Override + @Transactional(rollbackFor = Exception.class) + public void delete(int id) throws SonicException { + try { + testSuitesService.deleteByProjectId(id); + publicStepsService.deleteByProjectId(id); + testCasesService.deleteByProjectId(id); + stepsService.deleteByProjectId(id); + elementsService.deleteByProjectId(id); + modulesService.deleteByProjectId(id); + globalParamsService.deleteByProjectId(id); + List resultsList = resultsService.findByProjectId(id); + for (Results results : resultsList) { + resultDetailService.deleteByResultId(results.getId()); + } + resultsService.deleteByProjectId(id); + versionsService.deleteByProjectId(id); + baseMapper.deleteById(id); + } catch (Exception e) { + throw new SonicException("删除出错!请联系管理员!"); + } + } +} diff --git a/sonic-server-controller/src/main/java/org/cloud/sonic/controller/services/impl/PublicStepsServiceImpl.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/services/impl/PublicStepsServiceImpl.java new file mode 100644 index 00000000..faf31e5a --- /dev/null +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/services/impl/PublicStepsServiceImpl.java @@ -0,0 +1,142 @@ +package org.cloud.sonic.controller.services.impl; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import org.cloud.sonic.controller.mapper.*; +import org.cloud.sonic.controller.models.base.CommentPage; +import org.cloud.sonic.controller.models.base.TypeConverter; +import org.cloud.sonic.controller.models.domain.PublicSteps; +import org.cloud.sonic.controller.models.domain.PublicStepsSteps; +import org.cloud.sonic.controller.models.domain.Steps; +import org.cloud.sonic.controller.models.dto.ElementsDTO; +import org.cloud.sonic.controller.models.dto.PublicStepsDTO; +import org.cloud.sonic.controller.models.dto.StepsDTO; +import org.cloud.sonic.controller.services.PublicStepsService; +import org.cloud.sonic.controller.services.impl.base.SonicServiceImpl; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.*; +import java.util.stream.Collectors; + +/** + * @author ZhouYiXun + * @des 公共步骤逻辑实现 + * @date 2021/8/20 17:51 + */ +@Service +public class PublicStepsServiceImpl extends SonicServiceImpl implements PublicStepsService { + + @Autowired private PublicStepsMapper publicStepsMapper; + @Autowired private ElementsMapper elementsMapper; + @Autowired private PublicStepsStepsMapper publicStepsStepsMapper; + @Autowired private StepsElementsMapper stepsElementsMapper; + @Autowired private StepsMapper stepsMapper; + + @Transactional + @Override + public CommentPage findByProjectId(int projectId, Page pageable) { + Page page = lambdaQuery().eq(PublicSteps::getProjectId, projectId) + .orderByDesc(PublicSteps::getId) + .page(pageable); + // 业务join,java层拼接结果,虽然麻烦一点,但sql性能确实能优化 + List publicStepsDTOList = page.getRecords() + .stream().map(TypeConverter::convertTo).collect(Collectors.toList()); + Set publicStepsIdSet = publicStepsDTOList.stream().map(PublicStepsDTO::getId).collect(Collectors.toSet()); + if (publicStepsIdSet.isEmpty()) { + return CommentPage.emptyPage(); + } + + // publicStepsId -> StepsDTO + Map> stepsDTOMap = publicStepsMapper.listStepsByPublicStepsIds(publicStepsIdSet) + .stream().collect(Collectors.groupingBy(StepsDTO::getPublicStepsId)); + Set stepIdSet = new HashSet<>(); + stepsDTOMap.values().forEach(vList -> { + vList.forEach(e -> stepIdSet.add(e.getId())); + }); + + // stepsId -> elementDTO + Map> elementDTOMap = new HashMap<>(); + if (!stepIdSet.isEmpty()) { + elementDTOMap = elementsMapper.listElementsByStepsIds(stepIdSet) + .stream().collect(Collectors.groupingBy(ElementsDTO::getStepsId)); + } + + // 将element填充到step + Map> finalElementDTOMap = elementDTOMap; + stepsDTOMap.forEach((k, v) -> { + v.forEach(e -> e.setElements(finalElementDTOMap.get(e.getId()))); + }); + // 将step填充到public step + publicStepsDTOList.forEach(e -> e.setSteps(stepsDTOMap.get(e.getId()))); + + return CommentPage.convertFrom(page, publicStepsDTOList); + } + + @Override + public List> findByProjectIdAndPlatform(int projectId, int platform) { + return publicStepsMapper.findByProjectIdAndPlatform(projectId, platform); + } + + @Override + @Transactional + public PublicStepsDTO savePublicSteps(PublicStepsDTO publicStepsDTO) { + PublicSteps publicSteps = publicStepsDTO.convertTo(); + save(publicSteps); + List steps = publicStepsDTO.getSteps(); + // 先删除旧的数据 + publicStepsStepsMapper.delete(new LambdaQueryWrapper() + .eq(PublicStepsSteps::getPublicStepsId, publicStepsDTO.getId())); + // 重新填充新数据 + for (StepsDTO step : steps) { + // 保存 public_step 与 step 映射关系 + publicStepsStepsMapper.insert( + new PublicStepsSteps() + .setPublicStepsId(publicSteps.getId()) + .setStepsId(step.getId()) + ); + } + return publicSteps.convertTo(); + } + + @Override + @Transactional(rollbackFor = Exception.class) + public boolean delete(int id) { + // 删除用例中的公共步骤 + stepsMapper.delete(new LambdaQueryWrapper().eq(Steps::getText, id)); + // 删除与步骤的映射关系 + publicStepsStepsMapper.delete(new LambdaQueryWrapper() + .eq(PublicStepsSteps::getPublicStepsId, id)); + return baseMapper.deleteById(id) > 0; + } + + @Override + @Transactional + public PublicStepsDTO findById(int id) { + PublicSteps publicSteps = lambdaQuery().eq(PublicSteps::getId, id) + .orderByDesc(PublicSteps::getId) + .one(); + + // 填充step + List steps = stepsMapper.listByPublicStepsId(publicSteps.getId()) + .stream().map(TypeConverter::convertTo).collect(Collectors.toList()); + + for (StepsDTO step : steps) { + step.setElements(elementsMapper.listElementsByStepsId(step.getId())); + } + + PublicStepsDTO publicStepsDTO = publicSteps.convertTo().setSteps(steps); + return publicStepsDTO.setSteps(steps); + + } + + @Override + @Transactional(rollbackFor = Exception.class) + public boolean deleteByProjectId(int projectId) { + PublicSteps publicSteps = lambdaQuery().eq(PublicSteps::getProjectId, projectId).one(); + publicStepsStepsMapper.delete(new LambdaQueryWrapper() + .eq(PublicStepsSteps::getPublicStepsId, publicSteps.getId())); + return delete(publicSteps.getId()); + } +} diff --git a/sonic-server-controller/src/main/java/org/cloud/sonic/controller/services/impl/ResultDetailServiceImpl.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/services/impl/ResultDetailServiceImpl.java new file mode 100644 index 00000000..4213e9be --- /dev/null +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/services/impl/ResultDetailServiceImpl.java @@ -0,0 +1,117 @@ +package org.cloud.sonic.controller.services.impl; + +import com.alibaba.fastjson.JSONObject; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import org.cloud.sonic.controller.mapper.ResultDetailMapper; +import org.cloud.sonic.controller.models.domain.Devices; +import org.cloud.sonic.controller.models.domain.ResultDetail; +import org.cloud.sonic.controller.services.DevicesService; +import org.cloud.sonic.controller.services.ResultDetailService; +import org.cloud.sonic.controller.services.ResultsService; +import org.cloud.sonic.controller.services.impl.base.SonicServiceImpl; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.List; + +/** + * @author ZhouYiXun + * @des 测试结果详情逻辑实现 + * @date 2021/8/21 20:55 + */ +@Service +public class ResultDetailServiceImpl extends SonicServiceImpl implements ResultDetailService { + + @Autowired private ResultDetailMapper resultDetailMapper; + @Autowired private DevicesService devicesService; + @Autowired private ResultsService resultsService; + + @Override + public void saveByTransport(JSONObject jsonMsg) { + Devices resultDevice = devicesService.findByAgentIdAndUdId(jsonMsg.getInteger("agentId") + , jsonMsg.getString("udId")); + ResultDetail resultInfo = new ResultDetail(); + resultInfo.setType(jsonMsg.getString("msg")); + resultInfo.setLog(jsonMsg.getString("log")); + resultInfo.setDes(jsonMsg.getString("des")); + resultInfo.setStatus(jsonMsg.getInteger("status")); + resultInfo.setResultId(jsonMsg.getInteger("rid")); + resultInfo.setCaseId(jsonMsg.getInteger("cid")); + resultInfo.setTime(jsonMsg.getDate("time")); + resultInfo.setDeviceId(resultDevice == null ? 0 : resultDevice.getId()); + save(resultInfo); + if (jsonMsg.getString("msg").equals("status")) { + resultsService.suiteResult(jsonMsg.getInteger("rid")); + } + } + + @Override + public Page findAll(int resultId, int caseId, String type, int deviceId, Page pageable) { + + LambdaQueryChainWrapper lambdaQuery = lambdaQuery(); + + if (resultId != 0) { + lambdaQuery.eq(ResultDetail::getResultId, resultId); + } + if (caseId != 0) { + lambdaQuery.eq(ResultDetail::getCaseId, caseId); + } + if (type != null && type.length() > 0) { + lambdaQuery.eq(ResultDetail::getType, type); + } + if (deviceId != 0) { + lambdaQuery.eq(ResultDetail::getDeviceId, deviceId); + } + + return lambdaQuery.orderByAsc(ResultDetail::getTime) + .page(pageable); + } + + @Override + public List findAll(int resultId, int caseId, String type, int deviceId) { + + LambdaQueryChainWrapper lambdaQuery = lambdaQuery(); + + if (resultId != 0) { + lambdaQuery.eq(ResultDetail::getResultId, resultId); + } + if (caseId != 0) { + lambdaQuery.eq(ResultDetail::getCaseId, caseId); + } + if (type != null && type.length() > 0) { + lambdaQuery.eq(ResultDetail::getType, type); + } + if (deviceId != 0) { + lambdaQuery.eq(ResultDetail::getDeviceId, deviceId); + } + return lambdaQuery.orderByAsc(ResultDetail::getTime).list(); + } + + + @Override + public void deleteByResultId(int resultId) { + baseMapper.delete(new QueryWrapper().eq("result_id", resultId)); + } + + @Override + public List findTimeByResultIdGroupByCaseId(int resultId) { + return resultDetailMapper.findTimeByResultIdGroupByCaseId(resultId); + } + + @Override + public List findStatusByResultIdGroupByCaseId(int resultId) { + return resultDetailMapper.findStatusByResultIdGroupByCaseId(resultId); + } + + @Override + public List findTopCases(String startTime, String endTime, int projectId) { + return resultDetailMapper.findTopCases(startTime, endTime, projectId); + } + + @Override + public List findTopDevices(String startTime, String endTime, int projectId) { + return resultDetailMapper.findTopDevices(startTime, endTime, projectId); + } +} diff --git a/sonic-server-controller/src/main/java/com/sonic/controller/services/impl/ResultsServiceImpl.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/services/impl/ResultsServiceImpl.java similarity index 75% rename from sonic-server-controller/src/main/java/com/sonic/controller/services/impl/ResultsServiceImpl.java rename to sonic-server-controller/src/main/java/org/cloud/sonic/controller/services/impl/ResultsServiceImpl.java index b70d7601..ab0c7227 100644 --- a/sonic-server-controller/src/main/java/com/sonic/controller/services/impl/ResultsServiceImpl.java +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/services/impl/ResultsServiceImpl.java @@ -1,327 +1,329 @@ -package com.sonic.controller.services.impl; - -import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.JSONObject; -import com.sonic.controller.dao.ResultDetailRepository; -import com.sonic.controller.dao.ResultsRepository; -import com.sonic.controller.dao.TestSuitesRepository; -import com.sonic.controller.models.*; -import com.sonic.controller.models.interfaces.ResultDetailStatus; -import com.sonic.controller.models.interfaces.ResultStatus; -import com.sonic.controller.services.*; -import com.sonic.controller.tools.RobotMsgTool; -import org.checkerframework.checker.units.qual.A; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.Pageable; -import org.springframework.stereotype.Service; - -import java.text.SimpleDateFormat; -import java.util.*; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.stream.Collector; -import java.util.stream.Collectors; - -/** - * @author ZhouYiXun - * @des 测试结果逻辑实现 - * @date 2021/8/21 16:09 - */ -@Service -public class ResultsServiceImpl implements ResultsService { - private final Logger logger = LoggerFactory.getLogger(ResultsServiceImpl.class); - ExecutorService cachedThreadPool = Executors.newCachedThreadPool(); - @Autowired - private ResultsRepository resultsRepository; - @Autowired - private ResultDetailService resultDetailService; - @Autowired - private ProjectsService projectsService; - @Autowired - private RobotMsgTool robotMsgTool; - @Autowired - private TestSuitesService testSuitesService; - @Autowired - private ResultDetailRepository resultDetailRepository; - @Autowired - private TestCasesService testCasesService; - - @Override - public Page findByProjectId(int projectId, Pageable pageable) { - return resultsRepository.findByProjectId(projectId, pageable); - } - - @Override - public boolean delete(int id) { - if (resultsRepository.existsById(id)) { - resultsRepository.deleteById(id); - resultDetailService.deleteByResultId(id); - return true; - } else { - return false; - } - } - - @Override - public Results findById(int id) { - if (resultsRepository.existsById(id)) { - return resultsRepository.findById(id).get(); - } else { - return null; - } - } - - @Override - public void save(Results results) { - resultsRepository.saveAndFlush(results); - } - - @Override - public void clean(int day) { - long timeMillis = Calendar.getInstance().getTimeInMillis(); - long time = timeMillis - day * 86400000L; - List resultsList = resultsRepository.findByCreateTimeBefore(new Date(time)); - cachedThreadPool.execute(() -> { - for (Results results : resultsList) { - logger.info("清理测试报告id:" + results.getId()); - delete(results.getId()); - try { - Thread.sleep(500); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - }); - } - - @Override - public void suiteResult(int id) { - Results results = findById(id); - if (results != null) { - results.setReceiveMsgCount(results.getReceiveMsgCount() + 1); - setStatus(results); - } - } - - @Override - public JSONArray findCaseStatus(int id) { - Results results = findById(id); - SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - if (results != null) { - TestSuites testSuites = testSuitesService.findById(results.getSuiteId()); - if (testSuites != null) { - JSONArray result = new JSONArray(); - List caseTimes = resultDetailRepository.findTimeByResultIdGroupByCaseId(results.getId()); - List ci = new ArrayList<>(); - for (JSONObject j : caseTimes) { - ci.add(j.getInteger("case_id")); - } - List testCasesList = testCasesService.findByIdIn(ci); - List statusList = resultDetailRepository.findStatusByResultIdGroupByCaseId(results.getId()); - for (TestCases testCases : testCasesList) { - JSONObject jsonObject = new JSONObject(); - jsonObject.put("case", testCases); - int status = 0; - for (int j = caseTimes.size() - 1; j >= 0; j--) { - if (caseTimes.get(j).getInteger("case_id") == testCases.getId()) { - jsonObject.put("startTime", sf.format(caseTimes.get(j).getDate("startTime"))); - jsonObject.put("endTime", sf.format(caseTimes.get(j).getDate("endTime"))); - caseTimes.remove(j); - break; - } - } - List device = new ArrayList<>(); - for (int i = statusList.size() - 1; i >= 0; i--) { - if (statusList.get(i).getInteger("case_id") == testCases.getId()) { - JSONObject deviceIdAndStatus = new JSONObject(); - deviceIdAndStatus.put("deviceId", statusList.get(i).getInteger("device_id")); - deviceIdAndStatus.put("status", statusList.get(i).getInteger("status")); - if (statusList.get(i).getInteger("status") > status) { - status = statusList.get(i).getInteger("status"); - } - device.add(deviceIdAndStatus); - statusList.remove(i); - } - } - jsonObject.put("status", status); - jsonObject.put("device", device); - result.add(jsonObject); - } - return result; - } else { - return null; - } - } else { - return null; - } - } - - @Override - public void subResultCount(int id) { - Results results = findById(id); - if (results != null) { - results.setSendMsgCount(results.getSendMsgCount() - 1); - setStatus(results); - } - } - - @Override - public JSONObject chart(String startTime, String endTime, int projectId) { - List dateList = getBetweenDate(startTime.substring(0, 10), endTime.substring(0, 10)); - JSONObject result = new JSONObject(); - result.put("case", resultDetailRepository.findTopCases(startTime, endTime, projectId)); - result.put("device", resultDetailRepository.findTopDevices(startTime, endTime, projectId)); - List rateList = resultsRepository.findDayPassRate(startTime, endTime, projectId); - List rateResult = new ArrayList<>(); - for (String date : dateList) { - JSONObject d = new JSONObject(); - d.put("date", date); - d.put("rate", 0); - for (Iterator ite = rateList.iterator(); ite.hasNext(); ) { - JSONObject s = ite.next(); - if (s.getString("date").equals(date)) { - d.put("rate", s.getFloat("rate")); - ite.remove(); - break; - } - } - rateResult.add(d); - } - result.put("pass", rateResult); - result.put("status", resultsRepository.findDayStatus(startTime, endTime, projectId)); - return result; - } - - @Override - public void sendDayReport() { - long timeMillis = Calendar.getInstance().getTimeInMillis(); - SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - List projectsList = projectsService.findAll(); - for (Projects projects : projectsList) { - Date yesterday = new Date(timeMillis - 86400000); - Date today = new Date(timeMillis); - List status = resultsRepository.findDayStatus(sf.format(yesterday), sf.format(today), projects.getId()); - int suc = 0; - int warn = 0; - int fail = 0; - for (JSONObject j : status) { - switch (j.getInteger("status")) { - case 1: - suc += j.getInteger("total"); - break; - case 2: - warn += j.getInteger("total"); - break; - case 3: - fail += j.getInteger("total"); - break; - } - } - if (projects.getRobotType() != 0 && projects.getRobotToken().length() > 0 && projects.getRobotSecret().length() > 0) { - robotMsgTool.sendDayReportMessage(projects.getRobotToken(), projects.getRobotSecret(), projects.getId() - , projects.getProjectName(), sf.format(yesterday), sf.format(today), suc, warn, fail, projects.getRobotType()); - } - } - } - - @Override - public void sendWeekReport() { - long timeMillis = Calendar.getInstance().getTimeInMillis(); - SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - List projectsList = projectsService.findAll(); - for (Projects projects : projectsList) { - Date lastWeek = new Date(timeMillis - 86400000 * 7L); - Date today = new Date(timeMillis); - List status = resultsRepository.findDayStatus(sf.format(lastWeek), sf.format(today), projects.getId()); - int count = resultsRepository.findRunCount(sf.format(lastWeek), sf.format(today), projects.getId()); - int suc = 0; - int warn = 0; - int fail = 0; - for (JSONObject j : status) { - switch (j.getInteger("status")) { - case 1: - suc += j.getInteger("total"); - break; - case 2: - warn += j.getInteger("total"); - break; - case 3: - fail += j.getInteger("total"); - break; - } - } - if (projects.getRobotType() != 0 && projects.getRobotToken().length() > 0 && projects.getRobotSecret().length() > 0) { - robotMsgTool.sendWeekReportMessage(projects.getRobotToken(), projects.getRobotSecret(), projects.getId() - , projects.getProjectName(), sf.format(lastWeek), sf.format(today), suc, warn, fail, count, projects.getRobotType()); - } - } - } - - public static List getBetweenDate(String begin, String end) { - SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); - List betweenList = new ArrayList(); - - try { - Calendar startDay = Calendar.getInstance(); - startDay.setTime(format.parse(begin)); - startDay.add(Calendar.DATE, -1); - - while (true) { - startDay.add(Calendar.DATE, 1); - Date newDate = startDay.getTime(); - String newend = format.format(newDate); - betweenList.add(newend); - if (end.equals(newend)) { - break; - } - } - } catch (Exception e) { - e.printStackTrace(); - } - return betweenList; - } - - public void setStatus(Results results) { - List resultDetailList = resultDetailService.findAll(results.getId(), 0, "status", 0); - int failCount = 0; - int sucCount = 0; - int warnCount = 0; - int status; - for (ResultDetail resultDetail : resultDetailList) { - if (resultDetail.getStatus() == ResultDetailStatus.FAIL) { - failCount++; - } else if (resultDetail.getStatus() == ResultDetailStatus.WARN) { - warnCount++; - } else { - sucCount++; - } - } - if (failCount > 0) { - status = ResultStatus.FAIL; - } else if (warnCount > 0) { - status = ResultStatus.WARNING; - } else { - status = ResultStatus.PASS; - } - //状态赋予等级最高的 - results.setStatus(status > results.getStatus() ? status : results.getStatus()); - if (results.getSendMsgCount() < 1 && sucCount == 0 && failCount == 0 && warnCount == 0) { - delete(results.getId()); - } else { - save(results); - //发收相同的话,表明测试结束了 - if (results.getReceiveMsgCount() == results.getSendMsgCount()) { - results.setEndTime(new Date()); - save(results); - Projects projects = projectsService.findById(results.getProjectId()); - if (projects != null && projects.getRobotType() != 0 && projects.getRobotToken().length() > 0 && projects.getRobotSecret().length() > 0) { - robotMsgTool.sendResultFinishReport(projects.getRobotToken(), projects.getRobotSecret(), - results.getSuiteName(), sucCount, warnCount, failCount, projects.getId(), results.getId(), projects.getRobotType()); - } - } - } - } -} +package org.cloud.sonic.controller.services.impl; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import org.cloud.sonic.controller.mapper.ResultsMapper; +import org.cloud.sonic.controller.models.domain.Projects; +import org.cloud.sonic.controller.models.domain.ResultDetail; +import org.cloud.sonic.controller.models.domain.Results; +import org.cloud.sonic.controller.models.domain.TestCases; +import org.cloud.sonic.controller.models.dto.TestSuitesDTO; +import org.cloud.sonic.controller.models.interfaces.ResultDetailStatus; +import org.cloud.sonic.controller.models.interfaces.ResultStatus; +import org.cloud.sonic.controller.services.*; +import org.cloud.sonic.controller.services.impl.base.SonicServiceImpl; +import org.cloud.sonic.controller.tools.RobotMsgTool; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.text.SimpleDateFormat; +import java.util.*; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +/** + * @author ZhouYiXun + * @des 测试结果逻辑实现 + * @date 2021/8/21 16:09 + */ +@Service +public class ResultsServiceImpl extends SonicServiceImpl implements ResultsService { + + private final Logger logger = LoggerFactory.getLogger(ResultsServiceImpl.class); + ExecutorService cachedThreadPool = Executors.newCachedThreadPool(); + + @Autowired private ResultsMapper resultsMapper; + @Autowired private ResultDetailService resultDetailService; + @Autowired private ProjectsService projectsService; + @Autowired private RobotMsgTool robotMsgTool; + @Autowired private TestSuitesService testSuitesService; + @Autowired private TestCasesService testCasesService; + + @Override + public Page findByProjectId(int projectId, Page pageable) { + return lambdaQuery().eq(Results::getProjectId, projectId) + .orderByDesc(Results::getId) + .page(pageable); + } + + @Override + public List findByProjectId(int projectId) { + return lambdaQuery().eq(Results::getProjectId, projectId).list(); + } + + @Override + @Transactional(rollbackFor = Exception.class) + public boolean delete(int id) { + int count = resultsMapper.deleteById(id); + resultDetailService.deleteByResultId(id); + return count > 0; + } + + @Override + public Results findById(int id) { + return baseMapper.selectById(id); + } + + @Override + public void clean(int day) { + long timeMillis = Calendar.getInstance().getTimeInMillis(); + long time = timeMillis - day * 86400000L; + List resultsList = lambdaQuery() + .lt(Results::getCreateTime, new Date(time)) + .list(); + cachedThreadPool.execute(() -> { + for (Results results : resultsList) { + logger.info("清理测试报告id:" + results.getId()); + delete(results.getId()); + try { + Thread.sleep(500); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + }); + } + + @Override + public void suiteResult(int id) { + Results results = findById(id); + if (results != null) { + results.setReceiveMsgCount(results.getReceiveMsgCount() + 1); + save(results); + setStatus(results); + } + } + + @Override + @Transactional + public JSONArray findCaseStatus(int id) { + Results results = findById(id); + SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + if (results != null) { + TestSuitesDTO testSuitesDTO = testSuitesService.findById(results.getSuiteId()); + if (testSuitesDTO != null) { + JSONArray result = new JSONArray(); + List caseTimes = resultDetailService.findTimeByResultIdGroupByCaseId(results.getId()); + List ci = new ArrayList<>(); + for (JSONObject j : caseTimes) { + ci.add(j.getInteger("case_id")); + } + List testCasesList = testCasesService.findByIdIn(ci); + List statusList = resultDetailService.findStatusByResultIdGroupByCaseId(results.getId()); + for (TestCases testCases : testCasesList) { + JSONObject jsonObject = new JSONObject(); + jsonObject.put("case", testCases); + int status = 0; + for (int j = caseTimes.size() - 1; j >= 0; j--) { + if (caseTimes.get(j).getInteger("case_id") == testCases.getId()) { + jsonObject.put("startTime", sf.format(caseTimes.get(j).getDate("startTime"))); + jsonObject.put("endTime", sf.format(caseTimes.get(j).getDate("endTime"))); + caseTimes.remove(j); + break; + } + } + List device = new ArrayList<>(); + for (int i = statusList.size() - 1; i >= 0; i--) { + if (statusList.get(i).getInteger("case_id") == testCases.getId()) { + JSONObject deviceIdAndStatus = new JSONObject(); + deviceIdAndStatus.put("deviceId", statusList.get(i).getInteger("device_id")); + deviceIdAndStatus.put("status", statusList.get(i).getInteger("status")); + if (statusList.get(i).getInteger("status") > status) { + status = statusList.get(i).getInteger("status"); + } + device.add(deviceIdAndStatus); + statusList.remove(i); + } + } + jsonObject.put("status", status); + jsonObject.put("device", device); + result.add(jsonObject); + } + return result; + } else { + return null; + } + } else { + return null; + } + } + + @Override + public void subResultCount(int id) { + Results results = findById(id); + if (results != null) { + results.setSendMsgCount(results.getSendMsgCount() - 1); + setStatus(results); + } + } + + @Transactional + @Override + public JSONObject chart(String startTime, String endTime, int projectId) { + List dateList = getBetweenDate(startTime.substring(0, 10), endTime.substring(0, 10)); + JSONObject result = new JSONObject(); + result.put("case", resultDetailService.findTopCases(startTime, endTime, projectId)); + result.put("device", resultDetailService.findTopDevices(startTime, endTime, projectId)); + List rateList = resultsMapper.findDayPassRate(startTime, endTime, projectId); + List rateResult = new ArrayList<>(); + for (String date : dateList) { + JSONObject d = new JSONObject(); + d.put("date", date); + d.put("rate", 0); + for (Iterator ite = rateList.iterator(); ite.hasNext(); ) { + JSONObject s = ite.next(); + if (s.getString("date").equals(date)) { + d.put("rate", s.getFloat("rate")); + ite.remove(); + break; + } + } + rateResult.add(d); + } + result.put("pass", rateResult); + result.put("status", resultsMapper.findDayStatus(startTime, endTime, projectId)); + return result; + } + + @Transactional + @Override + public void sendDayReport() { + long timeMillis = Calendar.getInstance().getTimeInMillis(); + SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + List projectsList = projectsService.findAll(); + for (Projects projects : projectsList) { + Date yesterday = new Date(timeMillis - 86400000); + Date today = new Date(timeMillis); + List status = resultsMapper.findDayStatus(sf.format(yesterday), sf.format(today), projects.getId()); + int suc = 0; + int warn = 0; + int fail = 0; + for (JSONObject j : status) { + switch (j.getInteger("status")) { + case 1: + suc += j.getInteger("total"); + break; + case 2: + warn += j.getInteger("total"); + break; + case 3: + fail += j.getInteger("total"); + break; + } + } + if (projects.getRobotType() != 0 && projects.getRobotToken().length() > 0 && projects.getRobotSecret().length() > 0) { + robotMsgTool.sendDayReportMessage(projects.getRobotToken(), projects.getRobotSecret(), projects.getId() + , projects.getProjectName(), sf.format(yesterday), sf.format(today), suc, warn, fail, projects.getRobotType()); + } + } + } + + @Transactional + @Override + public void sendWeekReport() { + long timeMillis = Calendar.getInstance().getTimeInMillis(); + SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + List projectsList = projectsService.findAll(); + for (Projects projects : projectsList) { + Date lastWeek = new Date(timeMillis - 86400000 * 7L); + Date today = new Date(timeMillis); + List status = resultsMapper.findDayStatus(sf.format(lastWeek), sf.format(today), projects.getId()); + int count = resultsMapper.findRunCount(sf.format(lastWeek), sf.format(today), projects.getId()); + int suc = 0; + int warn = 0; + int fail = 0; + for (JSONObject j : status) { + switch (j.getInteger("status")) { + case 1: + suc += j.getInteger("total"); + break; + case 2: + warn += j.getInteger("total"); + break; + case 3: + fail += j.getInteger("total"); + break; + } + } + if (projects.getRobotType() != 0 && projects.getRobotToken().length() > 0 && projects.getRobotSecret().length() > 0) { + robotMsgTool.sendWeekReportMessage(projects.getRobotToken(), projects.getRobotSecret(), projects.getId() + , projects.getProjectName(), sf.format(lastWeek), sf.format(today), suc, warn, fail, count, projects.getRobotType()); + } + } + } + + public static List getBetweenDate(String begin, String end) { + SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); + List betweenList = new ArrayList(); + + try { + Calendar startDay = Calendar.getInstance(); + startDay.setTime(format.parse(begin)); + startDay.add(Calendar.DATE, -1); + + while (true) { + startDay.add(Calendar.DATE, 1); + Date newDate = startDay.getTime(); + String newend = format.format(newDate); + betweenList.add(newend); + if (end.equals(newend)) { + break; + } + } + } catch (Exception e) { + e.printStackTrace(); + } + return betweenList; + } + + @Transactional(rollbackFor = Exception.class) + public void setStatus(Results results) { + List resultDetailList = resultDetailService.findAll(results.getId(), 0, "status", 0); + int failCount = 0; + int sucCount = 0; + int warnCount = 0; + int status; + for (ResultDetail resultDetail : resultDetailList) { + if (resultDetail.getStatus() == ResultDetailStatus.FAIL) { + failCount++; + } else if (resultDetail.getStatus() == ResultDetailStatus.WARN) { + warnCount++; + } else { + sucCount++; + } + } + if (failCount > 0) { + status = ResultStatus.FAIL; + } else if (warnCount > 0) { + status = ResultStatus.WARNING; + } else { + status = ResultStatus.PASS; + } + //状态赋予等级最高的 + results.setStatus(status > results.getStatus() ? status : results.getStatus()); + if (results.getSendMsgCount() < 1 && sucCount == 0 && failCount == 0 && warnCount == 0) { + delete(results.getId()); + } else { + //发收相同的话,表明测试结束了 + if (results.getReceiveMsgCount() == results.getSendMsgCount()) { + results.setEndTime(new Date()); + save(results); + Projects projects = projectsService.findById(results.getProjectId()); + if (projects != null && projects.getRobotType() != 0 && projects.getRobotToken().length() > 0 && projects.getRobotSecret().length() > 0) { + robotMsgTool.sendResultFinishReport(projects.getRobotToken(), projects.getRobotSecret(), + results.getSuiteName(), sucCount, warnCount, failCount, projects.getId(), results.getId(), projects.getRobotType()); + } + } + } + } + + @Override + public void deleteByProjectId(int projectId) { + baseMapper.delete(new LambdaQueryWrapper().eq(Results::getProjectId, projectId)); + } +} diff --git a/sonic-server-controller/src/main/java/org/cloud/sonic/controller/services/impl/StepsServiceImpl.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/services/impl/StepsServiceImpl.java new file mode 100644 index 00000000..7126306a --- /dev/null +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/services/impl/StepsServiceImpl.java @@ -0,0 +1,177 @@ +package org.cloud.sonic.controller.services.impl; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import org.cloud.sonic.controller.mapper.*; +import org.cloud.sonic.controller.models.base.CommentPage; +import org.cloud.sonic.controller.models.base.TypeConverter; +import org.cloud.sonic.controller.models.domain.PublicSteps; +import org.cloud.sonic.controller.models.domain.PublicStepsSteps; +import org.cloud.sonic.controller.models.domain.Steps; +import org.cloud.sonic.controller.models.domain.StepsElements; +import org.cloud.sonic.controller.models.dto.ElementsDTO; +import org.cloud.sonic.controller.models.dto.StepsDTO; +import org.cloud.sonic.controller.models.http.StepSort; +import org.cloud.sonic.controller.services.StepsService; +import org.cloud.sonic.controller.services.impl.base.SonicServiceImpl; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.List; +import java.util.stream.Collectors; + +/** + * @author ZhouYiXun + * @des 测试步骤实现 + * @date 2021/8/20 17:51 + */ +@Service +public class StepsServiceImpl extends SonicServiceImpl implements StepsService { + + @Autowired private StepsMapper stepsMapper; + @Autowired private ElementsMapper elementsMapper; + @Autowired private PublicStepsMapper publicStepsMapper; + @Autowired private PublicStepsStepsMapper publicStepsStepsMapper; + @Autowired private StepsElementsMapper stepsElementsMapper; + + @Override + public List findByCaseIdOrderBySort(int caseId) { + + List stepsDTOList = lambdaQuery().eq(Steps::getCaseId, caseId) + .orderByAsc(Steps::getSort) + .list() + // 转换成DTO + .stream().map(TypeConverter::convertTo).collect(Collectors.toList()); + // 填充elements + stepsDTOList.forEach(e -> e.setElements(elementsMapper.listElementsByStepsId(e.getId()))); + return stepsDTOList; + } + + @Override + public boolean resetCaseId(int id) { + if (existsById(id)) { + Steps steps = baseMapper.selectById(id); + steps.setCaseId(0); + save(steps); + return true; + } else { + return false; + } + } + + @Override + @Transactional(rollbackFor = Exception.class) + public boolean delete(int id) { + if (existsById(id)) { + Steps steps = baseMapper.selectById(id); + publicStepsStepsMapper.delete(new QueryWrapper().eq("steps_id", steps.getId())); + baseMapper.deleteById(id); + return true; + } else { + return false; + } + } + + @Override + @Transactional(rollbackFor = Exception.class) + public void saveStep(StepsDTO stepsDTO) { + if (stepsDTO.getStepType().equals("publicStep")) { + PublicSteps publicSteps = publicStepsMapper.selectById(Integer.parseInt(stepsDTO.getText())); + if (publicSteps != null) { + stepsDTO.setContent(publicSteps.getName()); + } else { + stepsDTO.setContent("未知"); + } + } + + // 设置排序为最后 + if (!existsById(stepsDTO.getId())) { + stepsDTO.setSort(stepsMapper.findMaxSort() + 1); + } + Steps steps = stepsDTO.convertTo(); + save(steps); + + // 删除旧关系 + stepsElementsMapper.delete(new LambdaQueryWrapper().eq(StepsElements::getStepsId, steps.getId())); + + // 保存element映射关系 + List elements = stepsDTO.getElements(); + for (ElementsDTO element : elements) { + stepsElementsMapper.insert(new StepsElements().setElementsId(element.getId()).setStepsId(steps.getId())); + } + } + + @Transactional + @Override + public StepsDTO findById(int id) { + + StepsDTO stepsDTO = baseMapper.selectById(id).convertTo(); + stepsDTO.setElements(elementsMapper.listElementsByStepsId(stepsDTO.getId())); + return stepsDTO; + } + + @Override + @Transactional(rollbackFor = Exception.class) + public void sortSteps(StepSort stepSort) { + + List stepsList = lambdaQuery().eq(Steps::getCaseId, stepSort.getCaseId()) + // <= + .le(Steps::getSort, stepSort.getStartId()) + // >= + .ge(Steps::getSort, stepSort.getEndId()) + .list(); + + if (stepSort.getDirection().equals("down")) { + for (int i = 0; i < stepsList.size() - 1; i++) { + int temp = stepsList.get(stepsList.size() - 1).getSort(); + stepsList.get(stepsList.size() - 1).setSort(stepsList.get(i).getSort()); + stepsList.get(i).setSort(temp); + } + } else { + for (int i = 0; i < stepsList.size() - 1; i++) { + int temp = stepsList.get(0).getSort(); + stepsList.get(0).setSort(stepsList.get(stepsList.size() - 1 - i).getSort()); + stepsList.get(stepsList.size() - 1 - i).setSort(temp); + } + } + saveOrUpdateBatch(stepsList); + } + + @Override + public CommentPage findByProjectIdAndPlatform(int projectId, int platform, Page pageable) { + + Page page = lambdaQuery().eq(Steps::getProjectId, projectId) + .eq(Steps::getPlatform, platform) + .orderByDesc(Steps::getId) + .page(pageable); + + List stepsDTOList = page.getRecords() + .stream().map(TypeConverter::convertTo).collect(Collectors.toList()); + + for (StepsDTO stepsDTO : stepsDTOList) { + stepsDTO.setElements(elementsMapper.listElementsByStepsId(stepsDTO.getId())); + } + + return CommentPage.convertFrom(page, stepsDTOList); + } + + @Override + public List listStepsByElementsId(int elementsId) { + return stepsMapper.listStepsByElementId(elementsId); + } + + @Override + public boolean deleteByProjectId(int projectId) { + return baseMapper.delete(new LambdaQueryWrapper().eq(Steps::getProjectId, projectId)) > 0; + } + + @Override + public List listByPublicStepsId(int publicStepsId) { + return stepsMapper.listByPublicStepsId(publicStepsId) + // 填充elements + .stream().map(e -> e.convertTo().setElements(elementsMapper.listElementsByStepsId(e.getId()))) + .collect(Collectors.toList()); + } +} diff --git a/sonic-server-controller/src/main/java/org/cloud/sonic/controller/services/impl/TestCasesServiceImpl.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/services/impl/TestCasesServiceImpl.java new file mode 100644 index 00000000..41f00f95 --- /dev/null +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/services/impl/TestCasesServiceImpl.java @@ -0,0 +1,175 @@ +package org.cloud.sonic.controller.services.impl; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import org.cloud.sonic.controller.mapper.PublicStepsMapper; +import org.cloud.sonic.controller.mapper.TestCasesMapper; +import org.cloud.sonic.controller.mapper.TestSuitesTestCasesMapper; +import org.cloud.sonic.controller.models.domain.*; +import org.cloud.sonic.controller.models.dto.StepsDTO; +import org.cloud.sonic.controller.services.GlobalParamsService; +import org.cloud.sonic.controller.services.StepsService; +import org.cloud.sonic.controller.services.TestCasesService; +import org.cloud.sonic.controller.services.impl.base.SonicServiceImpl; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.CollectionUtils; + +import java.util.*; +import java.util.stream.Collectors; + +/** + * @author ZhouYiXun + * @des 测试用例逻辑实现 + * @date 2021/8/20 17:51 + */ +@Service +public class TestCasesServiceImpl extends SonicServiceImpl implements TestCasesService { + + @Autowired private StepsService stepsService; + @Autowired private PublicStepsMapper publicStepsMapper; + @Autowired private GlobalParamsService globalParamsService; + @Autowired private TestSuitesTestCasesMapper testSuitesTestCasesMapper; + + @Override + public Page findAll(int projectId, int platform, String name, Page pageable) { + + LambdaQueryChainWrapper lambdaQuery = lambdaQuery(); + if (projectId != 0) { + lambdaQuery.eq(TestCases::getProjectId, projectId); + } + if (platform != 0) { + lambdaQuery.eq(TestCases::getPlatform, platform); + } + if (name != null && name.length() > 0) { + lambdaQuery.like(TestCases::getName, name); + } + + return lambdaQuery.orderByDesc(TestCases::getEditTime) + .page(pageable); + } + + @Override + public List findAll(int projectId, int platform) { + return lambdaQuery().eq(TestCases::getProjectId, projectId) + .eq(TestCases::getPlatform, platform) + .orderByDesc(TestCases::getEditTime) + .list(); + } + + @Transactional(rollbackFor = Exception.class) + @Override + public boolean delete(int id) { + if (existsById(id)) { + // 删除suite映射关系 + testSuitesTestCasesMapper.delete( + new LambdaQueryWrapper() + .eq(TestSuitesTestCases::getTestCasesId, id) + ); + + List stepsList = stepsService.findByCaseIdOrderBySort(id); + for (StepsDTO steps : stepsList) { + steps.setCaseId(0); + stepsService.updateById(steps.convertTo()); + } + baseMapper.deleteById(id); + return true; + } else { + return false; + } + } + + @Override + public TestCases findById(int id) { + return baseMapper.selectById(id); + } + + @Transactional + @Override + public JSONObject findSteps(int id) { + + if (existsById(id)) { + TestCases runStepCase = baseMapper.selectById(id); + JSONObject jsonDebug = new JSONObject(); + jsonDebug.put("pf", runStepCase.getPlatform()); + + JSONArray array = new JSONArray(); + List stepsList = stepsService.findByCaseIdOrderBySort(id); + for (StepsDTO steps : stepsList) { + array.add(getStep(steps)); + } + jsonDebug.put("steps", array); + List globalParamsList = globalParamsService.findAll(runStepCase.getProjectId()); + JSONObject gp = new JSONObject(); + Map> valueMap = new HashMap<>(); + for (GlobalParams g : globalParamsList) { + if (g.getParamsValue().contains("|")) { + List shuffle = Arrays.asList(g.getParamsValue().split("|")); + Collections.shuffle(shuffle); + valueMap.put(g.getParamsKey(), shuffle); + } else { + gp.put(g.getParamsKey(), g.getParamsValue()); + } + } + for (String k : valueMap.keySet()) { + if (valueMap.get(k).size() > 0) { + String v = valueMap.get(k).get(0); + gp.put(k, v); + } + } + jsonDebug.put("gp", gp); + return jsonDebug; + } else { + return null; + } + } + + @Override + public List findByIdIn(List ids) { + return listByIds(ids); + } + + /** + * @param steps + * @return com.alibaba.fastjson.JSONObject + * @author ZhouYiXun + * @des 递归获取步骤 + * @date 2021/8/20 17:50 + */ + private JSONObject getStep(StepsDTO steps) { + JSONObject step = new JSONObject(); + if (steps.getStepType().equals("publicStep")) { + PublicSteps publicSteps = publicStepsMapper.selectById(Integer.parseInt(steps.getText())); + + if (publicSteps != null) { + List stepsList = stepsService.listByPublicStepsId(publicSteps.getId()); + JSONArray publicStepsJson = new JSONArray(); + for (StepsDTO pubStep : stepsList) { + publicStepsJson.add(getStep(pubStep)); + } + step.put("pubSteps", publicStepsJson); + } + } + step.put("step", steps); + return step; + } + + @Override + public boolean deleteByProjectId(int projectId) { + return baseMapper.delete(new LambdaQueryWrapper<>()) > 0; + } + + @Override + public List listByPublicStepsId(int publicStepsId) { + List steps = stepsService.lambdaQuery().eq(Steps::getText, publicStepsId).list(); + if (CollectionUtils.isEmpty(steps)) { + return new ArrayList<>(); + } + Set caseIdSet = steps.stream().map(Steps::getCaseId).collect(Collectors.toSet()); + return lambdaQuery().in(TestCases::getId, caseIdSet).list(); + } +} diff --git a/sonic-server-controller/src/main/java/org/cloud/sonic/controller/services/impl/TestSuitesServiceImpl.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/services/impl/TestSuitesServiceImpl.java new file mode 100644 index 00000000..02b4b610 --- /dev/null +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/services/impl/TestSuitesServiceImpl.java @@ -0,0 +1,408 @@ +package org.cloud.sonic.controller.services.impl; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import org.cloud.sonic.common.http.RespEnum; +import org.cloud.sonic.common.http.RespModel; +import org.cloud.sonic.common.tools.BeanTool; +import org.cloud.sonic.controller.feign.TransportFeignClient; +import org.cloud.sonic.controller.mapper.*; +import org.cloud.sonic.controller.models.base.CommentPage; +import org.cloud.sonic.controller.models.base.TypeConverter; +import org.cloud.sonic.controller.models.domain.*; +import org.cloud.sonic.controller.models.dto.*; +import org.cloud.sonic.controller.models.interfaces.CoverType; +import org.cloud.sonic.controller.models.interfaces.DeviceStatus; +import org.cloud.sonic.controller.models.interfaces.ResultStatus; +import org.cloud.sonic.controller.services.*; +import org.cloud.sonic.controller.services.impl.base.SonicServiceImpl; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.ObjectUtils; + +import java.util.*; +import java.util.stream.Collectors; + +/** + * @author ZhouYiXun + * @des 测试套件逻辑实现 + * @date 2021/8/20 17:51 + */ +@Service +public class TestSuitesServiceImpl extends SonicServiceImpl implements TestSuitesService { + + @Autowired private TestCasesMapper testCasesMapper; + @Autowired private ElementsMapper elementsMapper; + @Autowired private DevicesMapper devicesMapper; + @Autowired private ResultsService resultsService; + @Autowired private GlobalParamsService globalParamsService; + @Autowired private StepsService stepsService; + @Autowired private PublicStepsService publicStepsService; + @Autowired private TestSuitesTestCasesMapper testSuitesTestCasesMapper; + @Autowired private TestSuitesDevicesMapper testSuitesDevicesMapper; + @Autowired private TransportFeignClient transportFeignClient; + + @Override + @Transactional(rollbackFor = Exception.class) + public RespModel runSuite(int suiteId, String strike) { + TestSuitesDTO testSuitesDTO; + if (existsById(suiteId)) { + testSuitesDTO = findById(suiteId); + } else { + return new RespModel<>(3001, "测试套件已删除!"); + } + + if (testSuitesDTO.getTestCases().size() == 0) { + return new RespModel<>(3002, "该测试套件内无测试用例!"); + } + + List devicesList = BeanTool.transformFromInBatch(testSuitesDTO.getDevices(), Devices.class); + if (devicesList.size() == 0) { + return new RespModel<>(3003, "所选设备暂无可用!"); + } + + // 初始化部分结果状态信息 + Results results = new Results(); + results.setStatus(ResultStatus.RUNNING); + results.setSuiteId(suiteId); + results.setSuiteName(testSuitesDTO.getName()); + results.setStrike(strike); + if (testSuitesDTO.getCover() == CoverType.CASE) { + results.setSendMsgCount(testSuitesDTO.getTestCases().size()); + } + if (testSuitesDTO.getCover() == CoverType.DEVICE) { + results.setSendMsgCount(testSuitesDTO.getTestCases().size() * testSuitesDTO.getDevices().size()); + } + results.setReceiveMsgCount(0); + results.setProjectId(testSuitesDTO.getProjectId()); + resultsService.save(results); + + //组装全局参数为json对象 + List globalParamsList = globalParamsService.findAll(testSuitesDTO.getProjectId()); + + //将包含|的拆开多个参数并打乱,去掉json对象多参数的字段 + Map> valueMap = new HashMap<>(); + JSONObject gp = new JSONObject(); + for (GlobalParams g : globalParamsList) { + if (g.getParamsValue().contains("|")) { + List shuffle = Arrays.asList(g.getParamsValue().split("\\|")); + Collections.shuffle(shuffle); + valueMap.put(g.getParamsKey(), shuffle); + } else { + gp.put(g.getParamsKey(), g.getParamsValue()); + } + } + int deviceIndex = 0; + if (testSuitesDTO.getCover() == CoverType.CASE) { + List suiteDetail = new ArrayList<>(); + Set agentIds = new HashSet<>(); + for (TestCasesDTO testCases : testSuitesDTO.getTestCases()) { + JSONObject suite = new JSONObject(); + List steps = new ArrayList<>(); + List stepsList = stepsService.findByCaseIdOrderBySort(testCases.getId()); + for (StepsDTO s : stepsList) { + steps.add(getStep(s)); + } + suite.put("steps", steps); + suite.put("cid", testCases.getId()); + Devices devices = devicesList.get(deviceIndex); + suite.put("device", List.of(devices)); + if (deviceIndex == devicesList.size() - 1) { + deviceIndex = 0; + } else { + deviceIndex++; + } + //如果该字段的多参数数组还有,放入对象。否则去掉字段 + for (String k : valueMap.keySet()) { + if (valueMap.get(k).size() > 0) { + String v = valueMap.get(k).get(0); + gp.put(k, v); + valueMap.get(k).remove(0); + } else { + valueMap.remove(k); + } + } + suite.put("gp", gp); + suite.put("rid", results.getId()); + agentIds.add(devices.getAgentId()); + suiteDetail.add(suite); + } + JSONObject result = new JSONObject(); + result.put("cases", suiteDetail); + for (Integer id : agentIds) { + result.put("id", id); + result.put("pf", testSuitesDTO.getPlatform()); + result.put("msg", "suite"); + transportFeignClient.sendTestData(result); + } + } + if (testSuitesDTO.getCover() == CoverType.DEVICE) { + List suiteDetail = new ArrayList<>(); + Set agentIds = new HashSet<>(); + for (TestCasesDTO testCases : testSuitesDTO.getTestCases()) { + JSONObject suite = new JSONObject(); + List steps = new ArrayList<>(); + List stepsList = stepsService.findByCaseIdOrderBySort(testCases.getId()); + for (StepsDTO s : stepsList) { + steps.add(getStep(s)); + } + for (Devices devices : devicesList) { + agentIds.add(devices.getAgentId()); + } + suite.put("steps", steps); + suite.put("cid", testCases.getId()); + suite.put("device", devicesList); + //如果该字段的多参数数组还有,放入对象。否则去掉字段 + for (String k : valueMap.keySet()) { + if (valueMap.get(k).size() > 0) { + String v = valueMap.get(k).get(0); + gp.put(k, v); + valueMap.get(k).remove(0); + } else { + valueMap.remove(k); + } + } + suite.put("gp", gp); + suite.put("rid", results.getId()); + suiteDetail.add(suite); + } + JSONObject result = new JSONObject(); + result.put("cases", suiteDetail); + for (Integer id : agentIds) { + result.put("id", id); + result.put("pf", testSuitesDTO.getPlatform()); + result.put("msg", "suite"); + transportFeignClient.sendTestData(result); + } + } + return new RespModel<>(RespEnum.HANDLE_OK); + } + + @Override + @Transactional(rollbackFor = Exception.class) + public RespModel forceStopSuite(int resultId, String strike) { + + Results results = resultsService.findById(resultId); + if (ObjectUtils.isEmpty(results)) { + return new RespModel<>(3001, "测试结果模板不存在!"); + } + int suiteId = results.getSuiteId(); + + TestSuitesDTO testSuitesDTO; + if (existsById(suiteId)) { + testSuitesDTO = findById(suiteId); + } else { + return new RespModel<>(3001, "测试套件已删除!"); + } + + if (testSuitesDTO.getTestCases().size() == 0) { + return new RespModel<>(3002, "该测试套件内无测试用例!"); + } + + List devicesList = BeanTool.transformFromInBatch(testSuitesDTO.getDevices(), Devices.class); + for (int i = devicesList.size() - 1; i >= 0; i--) { + if (devicesList.get(i).getStatus().equals(DeviceStatus.OFFLINE) || devicesList.get(i).getStatus().equals(DeviceStatus.DISCONNECTED)) { + devicesList.remove(devicesList.get(i)); + } + } + if (devicesList.size() == 0) { + return new RespModel<>(3003, "运行设备暂无法连接!"); + } + + results.setStatus(ResultStatus.FAIL); + results.setStrike(strike); + if (testSuitesDTO.getCover() == CoverType.CASE) { + results.setSendMsgCount(testSuitesDTO.getTestCases().size()); + } + if (testSuitesDTO.getCover() == CoverType.DEVICE) { + results.setSendMsgCount(testSuitesDTO.getTestCases().size() * testSuitesDTO.getDevices().size()); + } + results.setProjectId(testSuitesDTO.getProjectId()); + resultsService.save(results); + + + int deviceIndex = 0; + if (testSuitesDTO.getCover() == CoverType.CASE) { + List suiteDetail = new ArrayList<>(); + Set agentIds = new HashSet<>(); + for (TestCasesDTO testCases : testSuitesDTO.getTestCases()) { + JSONObject suite = new JSONObject(); + suite.put("cid", testCases.getId()); + Devices devices = devicesList.get(deviceIndex); + suite.put("device", List.of(devices)); + if (deviceIndex == devicesList.size() - 1) { + deviceIndex = 0; + } else { + deviceIndex++; + } + suite.put("rid", results.getId()); + agentIds.add(devices.getAgentId()); + suiteDetail.add(suite); + } + JSONObject result = new JSONObject(); + result.put("msg", "forceStopSuite"); + result.put("pf", testSuitesDTO.getPlatform()); + result.put("cases", suiteDetail); + for (Integer id : agentIds) { + result.put("id", id); + transportFeignClient.sendTestData(result); + } + } + if (testSuitesDTO.getCover() == CoverType.DEVICE) { + List suiteDetail = new ArrayList<>(); + Set agentIds = new HashSet<>(); + for (TestCasesDTO testCases : testSuitesDTO.getTestCases()) { + JSONObject suite = new JSONObject(); + for (Devices devices : devicesList) { + agentIds.add(devices.getAgentId()); + } + suite.put("cid", testCases.getId()); + suite.put("device", devicesList); + suite.put("rid", results.getId()); + suiteDetail.add(suite); + } + JSONObject result = new JSONObject(); + result.put("msg", "forceStopSuite"); + result.put("pf", testSuitesDTO.getPlatform()); + result.put("cases", suiteDetail); + for (Integer id : agentIds) { + result.put("id", id); + transportFeignClient.sendTestData(result); + } + } + return new RespModel<>(RespEnum.HANDLE_OK); + } + + @Override + @Transactional + public TestSuitesDTO findById(int id) { + if (existsById(id)) { + TestSuitesDTO testSuitesDTO = baseMapper.selectById(id).convertTo(); + int suiteId = testSuitesDTO.getId(); + + // 填充testcase + List testCasesDTOList = testCasesMapper.listByTestSuitesId(suiteId) + .stream().map(TypeConverter::convertTo).collect(Collectors.toList()); + testSuitesDTO.setTestCases(testCasesDTOList); + + // 填充devices + List devicesDTOList = devicesMapper.listByTestSuitesId(suiteId) + .stream().map(TypeConverter::convertTo).collect(Collectors.toList()); + testSuitesDTO.setDevices(devicesDTOList); + + return testSuitesDTO; + } else { + return null; + } + } + + /** + * @param steps + * @return com.alibaba.fastjson.JSONObject + * @author ZhouYiXun + * @des 递归获取步骤 + * @date 2021/8/20 17:50 + */ + @Transactional + public JSONObject getStep(StepsDTO steps) { + JSONObject step = new JSONObject(); + if (steps.getStepType().equals("publicStep")) { + PublicStepsDTO publicStepsDTO = publicStepsService.findById(Integer.parseInt(steps.getText())); + if (publicStepsDTO != null) { + JSONArray publicStepsJson = new JSONArray(); + for (StepsDTO pubStep : publicStepsDTO.getSteps()) { + publicStepsJson.add(getStep(pubStep)); + } + step.put("pubSteps", publicStepsJson); + } + } + step.put("step", steps); + return step; + } + + @Override + public boolean delete(int id) { + return baseMapper.deleteById(id) > 0; + } + + @Override + @Transactional(rollbackFor = Exception.class) + public void saveTestSuites(TestSuitesDTO testSuitesDTO) { + TestSuites testSuites = testSuitesDTO.convertTo(); + save(testSuites); + + Integer suiteId = testSuites.getId(); + testSuitesDTO.setId(suiteId); + + List testCases = testSuitesDTO.getTestCases(); + List devices = testSuitesDTO.getDevices(); + + // 删除旧数据 + testSuitesDevicesMapper.delete(new LambdaQueryWrapper() + .eq(TestSuitesDevices::getTestSuitesId, suiteId) + ); + testSuitesTestCasesMapper.delete(new LambdaQueryWrapper() + .eq(TestSuitesTestCases::getTestSuitesId, suiteId) + ); + + // 保存testcase映射 + for (TestCasesDTO testCase : testCases) { + testSuitesTestCasesMapper.insert( + new TestSuitesTestCases().setTestSuitesId(suiteId).setTestCasesId(testCase.getId()) + ); + } + + // 保存devices映射 + for (DevicesDTO device : devices) { + testSuitesDevicesMapper.insert( + new TestSuitesDevices().setTestSuitesId(suiteId).setDevicesId(device.getId()) + ); + } + } + + @Override + @Transactional + public CommentPage findByProjectId(int projectId, String name, Page pageable) { + + LambdaQueryChainWrapper lambdaQuery = lambdaQuery(); + + if (projectId != 0) { + lambdaQuery.eq(TestSuites::getProjectId, projectId); + } + if (name != null && name.length() > 0) { + lambdaQuery.like(TestSuites::getName, name); + } + + lambdaQuery.orderByDesc(TestSuites::getId); + Page page = lambdaQuery.page(pageable); + + List testSuitesDTOList = page.getRecords() + // 转换 + 填充 testcase 和 devices + .stream().map(e -> findById(e.getId())).collect(Collectors.toList()); + + return CommentPage.convertFrom(page, testSuitesDTOList); + } + + @Override + public List findByProjectId(int projectId) { + return lambdaQuery().eq(TestSuites::getProjectId, projectId) + .orderByDesc(TestSuites::getId) + .list() + // 转换 + 填充 testcase 和 devices + .stream().map(e -> findById(e.getId())).collect(Collectors.toList()); + } + + @Override + public boolean deleteByProjectId(int projectId) { + return baseMapper.delete(new LambdaQueryWrapper().eq(TestSuites::getProjectId, projectId)) > 0; + } + + @Override + public List listTestSuitesByTestCasesId(int testCasesId) { + return testSuitesTestCasesMapper.listTestSuitesByTestCasesId(testCasesId); + } +} \ No newline at end of file diff --git a/sonic-server-controller/src/main/java/com/sonic/controller/services/impl/UsersServiceImpl.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/services/impl/UsersServiceImpl.java similarity index 63% rename from sonic-server-controller/src/main/java/com/sonic/controller/services/impl/UsersServiceImpl.java rename to sonic-server-controller/src/main/java/org/cloud/sonic/controller/services/impl/UsersServiceImpl.java index 8306b038..9e21c47e 100644 --- a/sonic-server-controller/src/main/java/com/sonic/controller/services/impl/UsersServiceImpl.java +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/services/impl/UsersServiceImpl.java @@ -1,89 +1,99 @@ -package com.sonic.controller.services.impl; - -import com.sonic.common.exception.SonicException; -import com.sonic.common.http.RespEnum; -import com.sonic.common.http.RespModel; -import com.sonic.common.tools.JWTTokenTool; -import com.sonic.controller.dao.UsersRepository; -import com.sonic.controller.models.Users; -import com.sonic.controller.models.http.ChangePwd; -import com.sonic.controller.models.http.UserInfo; -import com.sonic.controller.services.UsersService; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; -import org.springframework.util.DigestUtils; - -/** - * @author ZhouYiXun - * @des - * @date 2021/10/13 11:26 - */ -@Service -public class UsersServiceImpl implements UsersService { - private final Logger logger = LoggerFactory.getLogger(UsersServiceImpl.class); - @Autowired - private UsersRepository usersRepository; - @Autowired - private JWTTokenTool jwtTokenTool; - - @Override - @Transactional(rollbackFor = SonicException.class) - public void register(Users users) throws SonicException { - try { - users.setPassword(DigestUtils.md5DigestAsHex(users.getPassword().getBytes())); - usersRepository.save(users); - } catch (Exception e) { - e.printStackTrace(); - throw new SonicException("注册失败!用户名已存在!"); - } - } - - @Override - public String login(UserInfo userInfo) { - Users users = usersRepository.findByUserName(userInfo.getUserName()); - if (users != null && DigestUtils.md5DigestAsHex(userInfo.getPassword().getBytes()).equals(users.getPassword())) { - String token = jwtTokenTool.getToken(users.getUserName()); - users.setPassword(""); - logger.info("用户:" + userInfo.getUserName() + "登入! token:" + token); - return token; - } else { - return null; - } - } - - @Override - public Users getUserInfo(String token) { - String name = jwtTokenTool.getUserName(token); - if (name != null) { - Users users = usersRepository.findByUserName(name); - users.setPassword(""); - return users; - } else { - return null; - } - } - - @Override - public RespModel resetPwd(String token, ChangePwd changePwd) { - String name = jwtTokenTool.getUserName(token); - if (name != null) { - Users users = usersRepository.findByUserName(name); - if (users != null) { - if (DigestUtils.md5DigestAsHex(changePwd.getOldPwd().getBytes()).equals(users.getPassword())) { - users.setPassword(DigestUtils.md5DigestAsHex(changePwd.getNewPwd().getBytes())); - usersRepository.save(users); - return new RespModel(2000, "修改密码成功!"); - } else { - return new RespModel(4001, "旧密码错误!"); - } - } else { - return new RespModel(RespEnum.UNAUTHORIZED); - } - } else { - return new RespModel(RespEnum.UNAUTHORIZED); - } - } -} +package org.cloud.sonic.controller.services.impl; + +import org.cloud.sonic.common.exception.SonicException; +import org.cloud.sonic.common.http.RespEnum; +import org.cloud.sonic.common.http.RespModel; +import org.cloud.sonic.common.tools.JWTTokenTool; +import org.cloud.sonic.controller.mapper.UsersMapper; +import org.cloud.sonic.controller.models.domain.Users; +import org.cloud.sonic.controller.models.http.ChangePwd; +import org.cloud.sonic.controller.models.http.UserInfo; +import org.cloud.sonic.controller.services.UsersService; +import org.cloud.sonic.controller.services.impl.base.SonicServiceImpl; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.Assert; +import org.springframework.util.DigestUtils; + +/** + * @author ZhouYiXun + * @des + * @date 2021/10/13 11:26 + */ +@Service +public class UsersServiceImpl extends SonicServiceImpl implements UsersService { + private final Logger logger = LoggerFactory.getLogger(UsersServiceImpl.class); + + @Autowired + private JWTTokenTool jwtTokenTool; + + @Autowired + private UsersMapper usersMapper; + + @Override + @Transactional(rollbackFor = Exception.class) + public void register(Users users) throws SonicException { + try { + users.setPassword(DigestUtils.md5DigestAsHex(users.getPassword().getBytes())); + save(users); + } catch (Exception e) { + e.printStackTrace(); + throw new SonicException("注册失败!用户名已存在!"); + } + } + + @Override + public String login(UserInfo userInfo) { + Users users = findByUserName(userInfo.getUserName()); + if (users != null && DigestUtils.md5DigestAsHex(userInfo.getPassword().getBytes()).equals(users.getPassword())) { + String token = jwtTokenTool.getToken(users.getUserName()); + users.setPassword(""); + logger.info("用户:" + userInfo.getUserName() + "登入! token:" + token); + return token; + } else { + return null; + } + } + + @Override + public Users getUserInfo(String token) { + String name = jwtTokenTool.getUserName(token); + if (name != null) { + Users users = findByUserName(name); + users.setPassword(""); + return users; + } else { + return null; + } + } + + @Override + public RespModel resetPwd(String token, ChangePwd changePwd) { + String name = jwtTokenTool.getUserName(token); + if (name != null) { + Users users = findByUserName(name); + if (users != null) { + if (DigestUtils.md5DigestAsHex(changePwd.getOldPwd().getBytes()).equals(users.getPassword())) { + users.setPassword(DigestUtils.md5DigestAsHex(changePwd.getNewPwd().getBytes())); + save(users); + return new RespModel(2000, "修改密码成功!"); + } else { + return new RespModel(4001, "旧密码错误!"); + } + } else { + return new RespModel(RespEnum.UNAUTHORIZED); + } + } else { + return new RespModel(RespEnum.UNAUTHORIZED); + } + } + + @Override + public Users findByUserName(String userName) { + Assert.hasText(userName, "userName must not be null"); + return lambdaQuery().eq(Users::getUserName, userName).one(); + } +} diff --git a/sonic-server-controller/src/main/java/org/cloud/sonic/controller/services/impl/VersionsServiceImpl.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/services/impl/VersionsServiceImpl.java new file mode 100644 index 00000000..b92c5604 --- /dev/null +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/services/impl/VersionsServiceImpl.java @@ -0,0 +1,45 @@ +package org.cloud.sonic.controller.services.impl; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import org.cloud.sonic.controller.mapper.VersionsMapper; +import org.cloud.sonic.controller.models.domain.Versions; +import org.cloud.sonic.controller.services.VersionsService; +import org.cloud.sonic.controller.services.impl.base.SonicServiceImpl; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.List; + +/** + * @author ZhouYiXun + * @des 迭代逻辑层实现 + * @date 2021/8/16 22:56 + */ +@Service +public class VersionsServiceImpl extends SonicServiceImpl implements VersionsService { + + @Autowired + private VersionsMapper versionsMapper; + + @Override + public boolean delete(int id) { + return baseMapper.deleteById(id) > 0; + } + + @Override + public List findByProjectId(int projectId) { + return lambdaQuery().eq(Versions::getProjectId, projectId) + .orderByDesc(Versions::getCreateTime) + .list(); + } + + @Override + public Versions findById(int id) { + return baseMapper.selectById(id); + } + + @Override + public void deleteByProjectId(int projectId) { + baseMapper.delete(new LambdaQueryWrapper().eq(Versions::getProjectId, projectId)); + } +} diff --git a/sonic-server-controller/src/main/java/org/cloud/sonic/controller/services/impl/base/SonicServiceImpl.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/services/impl/base/SonicServiceImpl.java new file mode 100644 index 00000000..cd8a49d9 --- /dev/null +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/services/impl/base/SonicServiceImpl.java @@ -0,0 +1,68 @@ +package org.cloud.sonic.controller.services.impl.base; + +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import org.cloud.sonic.common.exception.ServerErrorException; +import org.cloud.sonic.common.tools.ReflectionTool; +import lombok.extern.slf4j.Slf4j; + +import java.io.Serializable; +import java.lang.reflect.Field; +import java.lang.reflect.ParameterizedType; +import java.util.Objects; + +/** + * 主要是为了兼容原来jpa的一些语法 + * + * @author JayWenStar + * @date 2021/12/17 11:38 下午 + */ +@Slf4j +public class SonicServiceImpl, T> extends ServiceImpl { + + protected boolean existsById(Serializable id) { + Field idField = getIdField(getDomainClass()); + Objects.requireNonNull(idField, "对象没有 @TableId 注解标注的字段"); + return baseMapper.selectCount(new QueryWrapper().eq("id", id)) > 0; + } + + /** + * 如果id属性为空就insert,否则update + */ + @Override + public boolean save(T domain) { + try { + Field idField = getIdField(getDomainClass()); + Objects.requireNonNull(idField, "对象没有 @TableId 注解标注的字段"); + Integer id = (Integer) idField.get(domain); + // 如果id为0,则设置为null + if (id == null || id.equals(0)) { + idField.set(domain, null); + return baseMapper.insert(domain) > 0; + } + return baseMapper.updateById(domain) > 0; + } catch (IllegalAccessException e) { + throw new ServerErrorException("操作对象id属性失败"); + } + } + + @SuppressWarnings("unchecked") + private Class getDomainClass() { + ParameterizedType type = ReflectionTool.getParameterizedTypeBySuperClass(SonicServiceImpl.class, this.getClass()); + Objects.requireNonNull(type, "Cannot fetch actual type because parameterized type is null"); + return (Class) type.getActualTypeArguments()[1]; + } + + private Field getIdField(Class clazz) { + Field[] fields = clazz.getDeclaredFields(); + for (Field field : fields) { + field.setAccessible(true); + if (field.getAnnotation(TableId.class) != null) { + return field; + } + } + return null; + } +} diff --git a/sonic-server-controller/src/main/java/com/sonic/controller/tools/RobotMsgTool.java b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/tools/RobotMsgTool.java similarity index 97% rename from sonic-server-controller/src/main/java/com/sonic/controller/tools/RobotMsgTool.java rename to sonic-server-controller/src/main/java/org/cloud/sonic/controller/tools/RobotMsgTool.java index e09f36d6..63591d5f 100644 --- a/sonic-server-controller/src/main/java/com/sonic/controller/tools/RobotMsgTool.java +++ b/sonic-server-controller/src/main/java/org/cloud/sonic/controller/tools/RobotMsgTool.java @@ -1,319 +1,318 @@ -package com.sonic.controller.tools; - -import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.JSONObject; -import com.sonic.controller.models.interfaces.RobotType; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.http.ResponseEntity; -import org.springframework.stereotype.Component; -import org.springframework.util.Base64Utils; -import org.springframework.web.client.RestTemplate; - -import javax.crypto.Mac; -import javax.crypto.spec.SecretKeySpec; -import java.math.BigDecimal; -import java.math.RoundingMode; -import java.net.URLEncoder; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.List; - -/** - * @author ZhouYiXun - * @des 机器人推送相关工具类,可以参考 https://developers.dingtalk.com/document/app/push-robots - * @date 2021/8/15 18:20 - */ -@Component -public class RobotMsgTool { - private final Logger logger = LoggerFactory.getLogger(RobotMsgTool.class); - @Autowired - private RestTemplate restTemplate; - //从配置文件获取前端部署的host - @Value("${robot.client.host}") - private String clientHost; - //成功时的图片url - @Value("${robot.img.success}") - private String successUrl; - //警告时的图片url - @Value("${robot.img.warning}") - private String warningUrl; - //失败时的图片url - @Value("${robot.img.error}") - private String errorUrl; - - /** - * @param token 机器人token - * @param secret 机器人密钥 - * @param jsonObject 通知内容 - * @author ZhouYiXun - * @des 钉钉官方签名方法 - * @date 2021/8/20 18:20 - */ - private void signAndSend(String token, String secret, int type, JSONObject jsonObject) { - try { - switch (type) { - case RobotType.DingTalk: { - Long timestamp = System.currentTimeMillis(); - String stringToSign = timestamp + "\n" + secret; - Mac mac = Mac.getInstance("HmacSHA256"); - mac.init(new SecretKeySpec(secret.getBytes("UTF-8"), "HmacSHA256")); - byte[] signData = mac.doFinal(stringToSign.getBytes("UTF-8")); - String sign = URLEncoder.encode(new String(Base64Utils.encode(signData)), "UTF-8"); - ResponseEntity responseEntity = - restTemplate.postForEntity(token + "×tamp=" + timestamp + "&sign=" + sign - , jsonObject, JSONObject.class); - logger.info("机器人发送结果:" + responseEntity.getBody()); - break; - } - case RobotType.WeChat: - break; - case RobotType.FeiShu: { - String timestamp = String.valueOf(System.currentTimeMillis()).substring(0, 10); - String stringToSign = timestamp + "\n" + secret; - Mac mac = Mac.getInstance("HmacSHA256"); - mac.init(new SecretKeySpec(stringToSign.getBytes(StandardCharsets.UTF_8), "HmacSHA256")); - byte[] signData = mac.doFinal(new byte[]{}); - String sign = new String(Base64Utils.encode(signData)); - jsonObject.put("timestamp", timestamp); - jsonObject.put("sign", sign); - ResponseEntity responseEntity = - restTemplate.postForEntity(token, jsonObject, JSONObject.class); - logger.info("机器人发送结果:" + responseEntity.getBody()); - break; - } - case RobotType.YouSpace: - break; - } - } catch (Exception e) { - logger.info("机器人发送失败:" + e.getMessage()); - } - } - - /** - * @param token 机器人token - * @param secret 机器人密钥 - * @param suiteName 套件名称 - * @param pass 通过数量 - * @param warn 警告数量 - * @param fail 失败数量 - * @param projectId 项目id - * @param resultId 结果id - * @return void - * @author ZhouYiXun - * @des 发送每次测试结果到钉钉 - * @date 2021/8/20 18:29 - */ - public void sendResultFinishReport(String token, String secret, String suiteName, int pass, - int warn, int fail, int projectId, int resultId, int type) { - JSONObject jsonObject = new JSONObject(); - if (type == RobotType.DingTalk) { - JSONObject link = new JSONObject(); - link.put("text", "通过数:" + pass + - " \n异常数:" + warn + - " \n失败数:" + fail); - link.put("title", "测试套件: " + suiteName + " 运行完毕!"); - link.put("messageUrl", clientHost + "/Home/" + projectId + "/ResultDetail/" + resultId); - //判断测试结果,来决定显示什么图片 - if (fail > 0) { - link.put("picUrl", errorUrl); - } else if (warn > 0) { - link.put("picUrl", warningUrl); - } else { - link.put("picUrl", successUrl); - } - jsonObject.put("msgtype", "link"); - jsonObject.put("link", link); - } - if (type == RobotType.FeiShu) { - jsonObject.put("msg_type", "interactive"); - JSONObject card = new JSONObject(); - JSONObject config = new JSONObject(); - config.put("wide_screen_mode", true); - card.put("config", config); - JSONObject element = new JSONObject(); - element.put("tag", "markdown"); - List elementList = new ArrayList<>(); - element.put("content", "**测试套件: " + suiteName + " 运行完毕!**\n" + - "通过数:" + pass + " \n" + - "异常数:" + warn + " \n" + - "失败数:" + fail + "\n" + - "测试报告:[点击查看](" + clientHost + "/Home/" + projectId + "/ResultDetail/" + resultId + ")"); - elementList.add(element); - card.put("elements", elementList); - jsonObject.put("card", card); - } - signAndSend(token, secret, type, jsonObject); - } - - /** - * @param token 机器人token - * @param secret 机器人密钥 - * @param platform 平台 - * @param version 版本号 - * @param url 安装包链接 - * @param detail 具体安装情况 - * @return void - * @author ZhouYiXun - * @des 发送装包完毕通知 - * @date 2021/8/20 18:33 - */ -// public void sendInstallPackageFinishReport(String token, String secret, String platform, -// String version, String url, JSONArray detail) { -// JSONObject jsonObject = new JSONObject(); -// JSONObject markdown = new JSONObject(); -// String device = ""; -// //遍历详情里面的结果,组装成多条安装结果的markdown -// for (Object o : detail) { -// JSONObject deviceDetail = (JSONObject) o; -// String statusColor; -// if (deviceDetail.getString("status").equals("PASS")) { -// statusColor = "PASS"; -// } else { -// statusColor = "FAIL"; -// } -// device += ("> ###### " + deviceDetail.getString("name") + " --- " + statusColor + " \n"); -// } -// markdown.put("text", "#### **Sonic装包完成通知** \n" + -// " ###### 平台:" + platform + " \n" + -// " ###### 版本号:" + (version.length() == 0 ? "未知版本" : version) + " \n" + -// device + -// " ###### 安装地址:[点击查看](" + url + ")"); -// markdown.put("title", "Sonic装包完成通知"); -// jsonObject.put("msgtype", "markdown"); -// jsonObject.put("markdown", markdown); -// signAndSend(token, secret, jsonObject); -// } - - /** - * @param token 机器人token - * @param secret 机器人密钥 - * @param projectId 项目id - * @param projectName 项目名称 - * @param yesterday 昨天的起始时间 - * @param today 今天的起始时间 - * @return void - * @author ZhouYiXun - * @des 发送日报 - * @date 2021/8/20 18:42 - */ - public void sendDayReportMessage(String token, String secret, int projectId, String projectName, - String yesterday, String today, int passCount, int warnCount, int failCount, int type) { - JSONObject jsonObject = new JSONObject(); - if (type == RobotType.DingTalk) { - JSONObject markdown = new JSONObject(); - //根据三个数量来决定markdown的字体颜色 - String failColorString; - if (failCount == 0) { - failColorString = "" + failCount + ""; - } else { - failColorString = "" + failCount + ""; - } - String warnColorString; - if (warnCount == 0) { - warnColorString = "" + warnCount + ""; - } else { - warnColorString = "" + warnCount + ""; - } - int total = passCount + warnCount + failCount; - markdown.put("text", "### Sonic云真机测试平台日报 \n" + - "> ###### 项目:" + projectName + " \n" + - "> ###### 时间:" + yesterday + " ~ " + today + " \n" + - "> ###### 通过数:" + passCount + " \n" + - "> ###### 异常数:" + warnColorString + " \n" + - "> ###### 失败数:" + failColorString + " \n" + - "> ###### 测试通过率:" + (total > 0 ? - new BigDecimal((float) passCount / total).setScale(2, RoundingMode.HALF_UP).doubleValue() : 0) + "% \n" + - "> ###### 详细统计:[点击查看](" + clientHost + "/Home/" + projectId + ")"); - markdown.put("title", "Sonic云真机测试平台日报"); - jsonObject.put("msgtype", "markdown"); - jsonObject.put("markdown", markdown); - } - if (type == RobotType.FeiShu) { - jsonObject.put("msg_type", "interactive"); - JSONObject card = new JSONObject(); - JSONObject config = new JSONObject(); - config.put("wide_screen_mode", true); - card.put("config", config); - JSONObject element = new JSONObject(); - element.put("tag", "markdown"); - int total = passCount + warnCount + failCount; - List elementList = new ArrayList<>(); - element.put("content", "**Sonic云真机测试平台日报**\n" + - "项目:" + projectName + " \n" + - "时间:" + yesterday + " ~ " + today + " \n" + - "通过数:" + passCount + "\n" + - "异常数:" + warnCount + " \n" + - "失败数:" + failCount + " \n" + - "测试通过率:" + (total > 0 ? - new BigDecimal((float) passCount / total).setScale(2, RoundingMode.HALF_UP).doubleValue() : 0) + "% \n" + - "详细统计:[点击查看](" + clientHost + "/Home/" + projectId + ")"); - elementList.add(element); - card.put("elements", elementList); - jsonObject.put("card", card); - } - signAndSend(token, secret, type, jsonObject); - } - - public void sendWeekReportMessage(String token, String secret, int projectId, String projectName, - String yesterday, String today, int passCount, int warnCount, int failCount, int count, int type) { - JSONObject jsonObject = new JSONObject(); - if (type == RobotType.DingTalk) { - JSONObject markdown = new JSONObject(); - //根据三个数量来决定markdown的字体颜色 - String failColorString; - if (failCount == 0) { - failColorString = "" + failCount + ""; - } else { - failColorString = "" + failCount + ""; - } - String warnColorString; - if (warnCount == 0) { - warnColorString = "" + warnCount + ""; - } else { - warnColorString = "" + warnCount + ""; - } - int total = passCount + warnCount + failCount; - markdown.put("text", "### Sonic云真机测试平台周报 \n" + - "> ###### 项目:" + projectName + " \n" + - "> ###### 时间:" + yesterday + " ~ " + today + " \n" + - "> ###### 共测试:" + count + " 次\n" + - "> ###### 通过数:" + passCount + " \n" + - "> ###### 异常数:" + warnColorString + " \n" + - "> ###### 失败数:" + failColorString + " \n" + - "> ###### 测试通过率:" + (total > 0 ? - new BigDecimal((float) passCount / total).setScale(2, RoundingMode.HALF_UP).doubleValue() : 0) + "% \n" + - "> ###### 详细统计:[点击查看](" + clientHost + "/Home/" + projectId + ")"); - markdown.put("title", "Sonic云真机测试平台周报"); - jsonObject.put("msgtype", "markdown"); - jsonObject.put("markdown", markdown); - } - if (type == RobotType.FeiShu) { - jsonObject.put("msg_type", "interactive"); - JSONObject card = new JSONObject(); - JSONObject config = new JSONObject(); - config.put("wide_screen_mode", true); - card.put("config", config); - JSONObject element = new JSONObject(); - element.put("tag", "markdown"); - int total = passCount + warnCount + failCount; - List elementList = new ArrayList<>(); - element.put("content", "**Sonic云真机测试平台周报**\n" + - "项目:" + projectName + " \n" + - "时间:" + yesterday + " ~ " + today + " \n" + - "共测试:" + count + " 次\n" + - "通过数:" + passCount + " \n" + - "异常数:" + warnCount + " \n" + - "失败数:" + failCount + " \n" + - "测试通过率:" + (total > 0 ? - new BigDecimal((float) passCount / total).setScale(2, RoundingMode.HALF_UP).doubleValue() : 0) + "% \n" + - "详细统计:[点击查看](" + clientHost + "/Home/" + projectId + ")"); - elementList.add(element); - card.put("elements", elementList); - jsonObject.put("card", card); - } - signAndSend(token, secret, type, jsonObject); - } -} +package org.cloud.sonic.controller.tools; + +import com.alibaba.fastjson.JSONObject; +import org.cloud.sonic.controller.models.interfaces.RobotType; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Component; +import org.springframework.util.Base64Utils; +import org.springframework.web.client.RestTemplate; + +import javax.crypto.Mac; +import javax.crypto.spec.SecretKeySpec; +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; + +/** + * @author ZhouYiXun + * @des 机器人推送相关工具类,可以参考 https://developers.dingtalk.com/document/app/push-robots + * @date 2021/8/15 18:20 + */ +@Component +public class RobotMsgTool { + private final Logger logger = LoggerFactory.getLogger(RobotMsgTool.class); + @Autowired + private RestTemplate restTemplate; + //从配置文件获取前端部署的host + @Value("${robot.client.host}") + private String clientHost; + //成功时的图片url + @Value("${robot.img.success}") + private String successUrl; + //警告时的图片url + @Value("${robot.img.warning}") + private String warningUrl; + //失败时的图片url + @Value("${robot.img.error}") + private String errorUrl; + + /** + * @param token 机器人token + * @param secret 机器人密钥 + * @param jsonObject 通知内容 + * @author ZhouYiXun + * @des 钉钉官方签名方法 + * @date 2021/8/20 18:20 + */ + private void signAndSend(String token, String secret, int type, JSONObject jsonObject) { + try { + switch (type) { + case RobotType.DingTalk: { + Long timestamp = System.currentTimeMillis(); + String stringToSign = timestamp + "\n" + secret; + Mac mac = Mac.getInstance("HmacSHA256"); + mac.init(new SecretKeySpec(secret.getBytes("UTF-8"), "HmacSHA256")); + byte[] signData = mac.doFinal(stringToSign.getBytes("UTF-8")); + String sign = URLEncoder.encode(new String(Base64Utils.encode(signData)), "UTF-8"); + ResponseEntity responseEntity = + restTemplate.postForEntity(token + "×tamp=" + timestamp + "&sign=" + sign + , jsonObject, JSONObject.class); + logger.info("机器人发送结果:" + responseEntity.getBody()); + break; + } + case RobotType.WeChat: + break; + case RobotType.FeiShu: { + String timestamp = String.valueOf(System.currentTimeMillis()).substring(0, 10); + String stringToSign = timestamp + "\n" + secret; + Mac mac = Mac.getInstance("HmacSHA256"); + mac.init(new SecretKeySpec(stringToSign.getBytes(StandardCharsets.UTF_8), "HmacSHA256")); + byte[] signData = mac.doFinal(new byte[]{}); + String sign = new String(Base64Utils.encode(signData)); + jsonObject.put("timestamp", timestamp); + jsonObject.put("sign", sign); + ResponseEntity responseEntity = + restTemplate.postForEntity(token, jsonObject, JSONObject.class); + logger.info("机器人发送结果:" + responseEntity.getBody()); + break; + } + case RobotType.YouSpace: + break; + } + } catch (Exception e) { + logger.info("机器人发送失败:" + e.getMessage()); + } + } + + /** + * @param token 机器人token + * @param secret 机器人密钥 + * @param suiteName 套件名称 + * @param pass 通过数量 + * @param warn 警告数量 + * @param fail 失败数量 + * @param projectId 项目id + * @param resultId 结果id + * @return void + * @author ZhouYiXun + * @des 发送每次测试结果到钉钉 + * @date 2021/8/20 18:29 + */ + public void sendResultFinishReport(String token, String secret, String suiteName, int pass, + int warn, int fail, int projectId, int resultId, int type) { + JSONObject jsonObject = new JSONObject(); + if (type == RobotType.DingTalk) { + JSONObject link = new JSONObject(); + link.put("text", "通过数:" + pass + + " \n异常数:" + warn + + " \n失败数:" + fail); + link.put("title", "测试套件: " + suiteName + " 运行完毕!"); + link.put("messageUrl", clientHost + "/Home/" + projectId + "/ResultDetail/" + resultId); + //判断测试结果,来决定显示什么图片 + if (fail > 0) { + link.put("picUrl", errorUrl); + } else if (warn > 0) { + link.put("picUrl", warningUrl); + } else { + link.put("picUrl", successUrl); + } + jsonObject.put("msgtype", "link"); + jsonObject.put("link", link); + } + if (type == RobotType.FeiShu) { + jsonObject.put("msg_type", "interactive"); + JSONObject card = new JSONObject(); + JSONObject config = new JSONObject(); + config.put("wide_screen_mode", true); + card.put("config", config); + JSONObject element = new JSONObject(); + element.put("tag", "markdown"); + List elementList = new ArrayList<>(); + element.put("content", "**测试套件: " + suiteName + " 运行完毕!**\n" + + "通过数:" + pass + " \n" + + "异常数:" + warn + " \n" + + "失败数:" + fail + "\n" + + "测试报告:[点击查看](" + clientHost + "/Home/" + projectId + "/ResultDetail/" + resultId + ")"); + elementList.add(element); + card.put("elements", elementList); + jsonObject.put("card", card); + } + signAndSend(token, secret, type, jsonObject); + } + + /** + * @param token 机器人token + * @param secret 机器人密钥 + * @param platform 平台 + * @param version 版本号 + * @param url 安装包链接 + * @param detail 具体安装情况 + * @return void + * @author ZhouYiXun + * @des 发送装包完毕通知 + * @date 2021/8/20 18:33 + */ +// public void sendInstallPackageFinishReport(String token, String secret, String platform, +// String version, String url, JSONArray detail) { +// JSONObject jsonObject = new JSONObject(); +// JSONObject markdown = new JSONObject(); +// String device = ""; +// //遍历详情里面的结果,组装成多条安装结果的markdown +// for (Object o : detail) { +// JSONObject deviceDetail = (JSONObject) o; +// String statusColor; +// if (deviceDetail.getString("status").equals("PASS")) { +// statusColor = "PASS"; +// } else { +// statusColor = "FAIL"; +// } +// device += ("> ###### " + deviceDetail.getString("name") + " --- " + statusColor + " \n"); +// } +// markdown.put("text", "#### **Sonic装包完成通知** \n" + +// " ###### 平台:" + platform + " \n" + +// " ###### 版本号:" + (version.length() == 0 ? "未知版本" : version) + " \n" + +// device + +// " ###### 安装地址:[点击查看](" + url + ")"); +// markdown.put("title", "Sonic装包完成通知"); +// jsonObject.put("msgtype", "markdown"); +// jsonObject.put("markdown", markdown); +// signAndSend(token, secret, jsonObject); +// } + + /** + * @param token 机器人token + * @param secret 机器人密钥 + * @param projectId 项目id + * @param projectName 项目名称 + * @param yesterday 昨天的起始时间 + * @param today 今天的起始时间 + * @return void + * @author ZhouYiXun + * @des 发送日报 + * @date 2021/8/20 18:42 + */ + public void sendDayReportMessage(String token, String secret, int projectId, String projectName, + String yesterday, String today, int passCount, int warnCount, int failCount, int type) { + JSONObject jsonObject = new JSONObject(); + if (type == RobotType.DingTalk) { + JSONObject markdown = new JSONObject(); + //根据三个数量来决定markdown的字体颜色 + String failColorString; + if (failCount == 0) { + failColorString = "" + failCount + ""; + } else { + failColorString = "" + failCount + ""; + } + String warnColorString; + if (warnCount == 0) { + warnColorString = "" + warnCount + ""; + } else { + warnColorString = "" + warnCount + ""; + } + int total = passCount + warnCount + failCount; + markdown.put("text", "### Sonic云真机测试平台日报 \n" + + "> ###### 项目:" + projectName + " \n" + + "> ###### 时间:" + yesterday + " ~ " + today + " \n" + + "> ###### 通过数:" + passCount + " \n" + + "> ###### 异常数:" + warnColorString + " \n" + + "> ###### 失败数:" + failColorString + " \n" + + "> ###### 测试通过率:" + (total > 0 ? + new BigDecimal((float) passCount / total).setScale(2, RoundingMode.HALF_UP).doubleValue() : 0) + "% \n" + + "> ###### 详细统计:[点击查看](" + clientHost + "/Home/" + projectId + ")"); + markdown.put("title", "Sonic云真机测试平台日报"); + jsonObject.put("msgtype", "markdown"); + jsonObject.put("markdown", markdown); + } + if (type == RobotType.FeiShu) { + jsonObject.put("msg_type", "interactive"); + JSONObject card = new JSONObject(); + JSONObject config = new JSONObject(); + config.put("wide_screen_mode", true); + card.put("config", config); + JSONObject element = new JSONObject(); + element.put("tag", "markdown"); + int total = passCount + warnCount + failCount; + List elementList = new ArrayList<>(); + element.put("content", "**Sonic云真机测试平台日报**\n" + + "项目:" + projectName + " \n" + + "时间:" + yesterday + " ~ " + today + " \n" + + "通过数:" + passCount + "\n" + + "异常数:" + warnCount + " \n" + + "失败数:" + failCount + " \n" + + "测试通过率:" + (total > 0 ? + new BigDecimal((float) passCount / total).setScale(2, RoundingMode.HALF_UP).doubleValue() : 0) + "% \n" + + "详细统计:[点击查看](" + clientHost + "/Home/" + projectId + ")"); + elementList.add(element); + card.put("elements", elementList); + jsonObject.put("card", card); + } + signAndSend(token, secret, type, jsonObject); + } + + public void sendWeekReportMessage(String token, String secret, int projectId, String projectName, + String yesterday, String today, int passCount, int warnCount, int failCount, int count, int type) { + JSONObject jsonObject = new JSONObject(); + if (type == RobotType.DingTalk) { + JSONObject markdown = new JSONObject(); + //根据三个数量来决定markdown的字体颜色 + String failColorString; + if (failCount == 0) { + failColorString = "" + failCount + ""; + } else { + failColorString = "" + failCount + ""; + } + String warnColorString; + if (warnCount == 0) { + warnColorString = "" + warnCount + ""; + } else { + warnColorString = "" + warnCount + ""; + } + int total = passCount + warnCount + failCount; + markdown.put("text", "### Sonic云真机测试平台周报 \n" + + "> ###### 项目:" + projectName + " \n" + + "> ###### 时间:" + yesterday + " ~ " + today + " \n" + + "> ###### 共测试:" + count + " 次\n" + + "> ###### 通过数:" + passCount + " \n" + + "> ###### 异常数:" + warnColorString + " \n" + + "> ###### 失败数:" + failColorString + " \n" + + "> ###### 测试通过率:" + (total > 0 ? + new BigDecimal((float) passCount / total).setScale(2, RoundingMode.HALF_UP).doubleValue() : 0) + "% \n" + + "> ###### 详细统计:[点击查看](" + clientHost + "/Home/" + projectId + ")"); + markdown.put("title", "Sonic云真机测试平台周报"); + jsonObject.put("msgtype", "markdown"); + jsonObject.put("markdown", markdown); + } + if (type == RobotType.FeiShu) { + jsonObject.put("msg_type", "interactive"); + JSONObject card = new JSONObject(); + JSONObject config = new JSONObject(); + config.put("wide_screen_mode", true); + card.put("config", config); + JSONObject element = new JSONObject(); + element.put("tag", "markdown"); + int total = passCount + warnCount + failCount; + List elementList = new ArrayList<>(); + element.put("content", "**Sonic云真机测试平台周报**\n" + + "项目:" + projectName + " \n" + + "时间:" + yesterday + " ~ " + today + " \n" + + "共测试:" + count + " 次\n" + + "通过数:" + passCount + " \n" + + "异常数:" + warnCount + " \n" + + "失败数:" + failCount + " \n" + + "测试通过率:" + (total > 0 ? + new BigDecimal((float) passCount / total).setScale(2, RoundingMode.HALF_UP).doubleValue() : 0) + "% \n" + + "详细统计:[点击查看](" + clientHost + "/Home/" + projectId + ")"); + elementList.add(element); + card.put("elements", elementList); + jsonObject.put("card", card); + } + signAndSend(token, secret, type, jsonObject); + } +} diff --git a/sonic-server-controller/src/main/resources/bootstrap.yml b/sonic-server-controller/src/main/resources/bootstrap.yml index 74b982b8..57369259 100644 --- a/sonic-server-controller/src/main/resources/bootstrap.yml +++ b/sonic-server-controller/src/main/resources/bootstrap.yml @@ -19,3 +19,12 @@ eureka: client: service-url: defaultZone: ${EUREKA_URL:http://sonic:sonic@127.0.0.1:9090/eureka/} + +# 数据库自动生成表 +actable: + model: + pack: org.cloud.sonic.controller.models.domain + table: + auto: update + database: + type: mysql \ No newline at end of file diff --git a/sonic-server-controller/src/main/resources/data.sql b/sonic-server-controller/src/main/resources/data.sql new file mode 100644 index 00000000..1c8a0e79 --- /dev/null +++ b/sonic-server-controller/src/main/resources/data.sql @@ -0,0 +1 @@ +; \ No newline at end of file diff --git a/sonic-server-controller/src/main/resources/mapping/AgentsMapper.xml b/sonic-server-controller/src/main/resources/mapping/AgentsMapper.xml new file mode 100644 index 00000000..05ef78b2 --- /dev/null +++ b/sonic-server-controller/src/main/resources/mapping/AgentsMapper.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/sonic-server-controller/src/main/resources/mapping/DevicesMapper.xml b/sonic-server-controller/src/main/resources/mapping/DevicesMapper.xml new file mode 100644 index 00000000..bb873d17 --- /dev/null +++ b/sonic-server-controller/src/main/resources/mapping/DevicesMapper.xml @@ -0,0 +1,85 @@ + + + + + + + + + diff --git a/sonic-server-controller/src/main/resources/mapping/ElementsMapper.xml b/sonic-server-controller/src/main/resources/mapping/ElementsMapper.xml new file mode 100644 index 00000000..e1eff8ed --- /dev/null +++ b/sonic-server-controller/src/main/resources/mapping/ElementsMapper.xml @@ -0,0 +1,13 @@ + + + + + + diff --git a/sonic-server-controller/src/main/resources/mapping/GlobalParamsMapper.xml b/sonic-server-controller/src/main/resources/mapping/GlobalParamsMapper.xml new file mode 100644 index 00000000..a97a3c9e --- /dev/null +++ b/sonic-server-controller/src/main/resources/mapping/GlobalParamsMapper.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/sonic-server-controller/src/main/resources/mapping/ModulesMapper.xml b/sonic-server-controller/src/main/resources/mapping/ModulesMapper.xml new file mode 100644 index 00000000..c554d305 --- /dev/null +++ b/sonic-server-controller/src/main/resources/mapping/ModulesMapper.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/sonic-server-controller/src/main/resources/mapping/ProjectsMapper.xml b/sonic-server-controller/src/main/resources/mapping/ProjectsMapper.xml new file mode 100644 index 00000000..8038e29d --- /dev/null +++ b/sonic-server-controller/src/main/resources/mapping/ProjectsMapper.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/sonic-server-controller/src/main/resources/mapping/PublicStepsMapper.xml b/sonic-server-controller/src/main/resources/mapping/PublicStepsMapper.xml new file mode 100644 index 00000000..4505ff34 --- /dev/null +++ b/sonic-server-controller/src/main/resources/mapping/PublicStepsMapper.xml @@ -0,0 +1,13 @@ + + + + + + diff --git a/sonic-server-controller/src/main/resources/mapping/PublicStepsStepsMapper.xml b/sonic-server-controller/src/main/resources/mapping/PublicStepsStepsMapper.xml new file mode 100644 index 00000000..76080ced --- /dev/null +++ b/sonic-server-controller/src/main/resources/mapping/PublicStepsStepsMapper.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/sonic-server-controller/src/main/resources/mapping/ResultDetailMapper.xml b/sonic-server-controller/src/main/resources/mapping/ResultDetailMapper.xml new file mode 100644 index 00000000..5cbb3458 --- /dev/null +++ b/sonic-server-controller/src/main/resources/mapping/ResultDetailMapper.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/sonic-server-controller/src/main/resources/mapping/ResultsMapper.xml b/sonic-server-controller/src/main/resources/mapping/ResultsMapper.xml new file mode 100644 index 00000000..3b0a92ac --- /dev/null +++ b/sonic-server-controller/src/main/resources/mapping/ResultsMapper.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/sonic-server-controller/src/main/resources/mapping/StepsElementsMapper.xml b/sonic-server-controller/src/main/resources/mapping/StepsElementsMapper.xml new file mode 100644 index 00000000..4111f066 --- /dev/null +++ b/sonic-server-controller/src/main/resources/mapping/StepsElementsMapper.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/sonic-server-controller/src/main/resources/mapping/StepsMapper.xml b/sonic-server-controller/src/main/resources/mapping/StepsMapper.xml new file mode 100644 index 00000000..97b89c78 --- /dev/null +++ b/sonic-server-controller/src/main/resources/mapping/StepsMapper.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/sonic-server-controller/src/main/resources/mapping/TestCasesMapper.xml b/sonic-server-controller/src/main/resources/mapping/TestCasesMapper.xml new file mode 100644 index 00000000..ccc69cab --- /dev/null +++ b/sonic-server-controller/src/main/resources/mapping/TestCasesMapper.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/sonic-server-controller/src/main/resources/mapping/TestSuitesDevicesMapper.xml b/sonic-server-controller/src/main/resources/mapping/TestSuitesDevicesMapper.xml new file mode 100644 index 00000000..6a5d6638 --- /dev/null +++ b/sonic-server-controller/src/main/resources/mapping/TestSuitesDevicesMapper.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/sonic-server-controller/src/main/resources/mapping/TestSuitesMapper.xml b/sonic-server-controller/src/main/resources/mapping/TestSuitesMapper.xml new file mode 100644 index 00000000..739aee2e --- /dev/null +++ b/sonic-server-controller/src/main/resources/mapping/TestSuitesMapper.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/sonic-server-controller/src/main/resources/mapping/TestSuitesTestCasesMapper.xml b/sonic-server-controller/src/main/resources/mapping/TestSuitesTestCasesMapper.xml new file mode 100644 index 00000000..0ba2b6cf --- /dev/null +++ b/sonic-server-controller/src/main/resources/mapping/TestSuitesTestCasesMapper.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/sonic-server-controller/src/main/resources/mapping/UsersMapper.xml b/sonic-server-controller/src/main/resources/mapping/UsersMapper.xml new file mode 100644 index 00000000..7ef0b9cf --- /dev/null +++ b/sonic-server-controller/src/main/resources/mapping/UsersMapper.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/sonic-server-controller/src/main/resources/mapping/VersionsMapper.xml b/sonic-server-controller/src/main/resources/mapping/VersionsMapper.xml new file mode 100644 index 00000000..dbc12350 --- /dev/null +++ b/sonic-server-controller/src/main/resources/mapping/VersionsMapper.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/sonic-server-eureka/pom.xml b/sonic-server-eureka/pom.xml index e90887d0..3dd61917 100644 --- a/sonic-server-eureka/pom.xml +++ b/sonic-server-eureka/pom.xml @@ -4,13 +4,13 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> sonic-server - com.sonic + org.cloud.sonic 1.0.0 4.0.0 sonic-server-eureka - v1.2.0-release + v1.3.0-beta2 jar @@ -38,23 +38,23 @@ - - - - - org.springframework.boot - spring-boot-maven-plugin - - true - - - - com.spotify - docker-maven-plugin - - true - - - - + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/sonic-server-eureka/src/main/java/com/sonic/eureka/EurekaApplication.java b/sonic-server-eureka/src/main/java/org/cloud/sonic/eureka/EurekaApplication.java similarity index 91% rename from sonic-server-eureka/src/main/java/com/sonic/eureka/EurekaApplication.java rename to sonic-server-eureka/src/main/java/org/cloud/sonic/eureka/EurekaApplication.java index c0efcf34..f47e502d 100644 --- a/sonic-server-eureka/src/main/java/com/sonic/eureka/EurekaApplication.java +++ b/sonic-server-eureka/src/main/java/org/cloud/sonic/eureka/EurekaApplication.java @@ -1,13 +1,13 @@ -package com.sonic.eureka; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer; - -@SpringBootApplication -@EnableEurekaServer -public class EurekaApplication { - public static void main(String[] args) { - SpringApplication.run(EurekaApplication.class, args); - } +package org.cloud.sonic.eureka; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer; + +@SpringBootApplication +@EnableEurekaServer +public class EurekaApplication { + public static void main(String[] args) { + SpringApplication.run(EurekaApplication.class, args); + } } \ No newline at end of file diff --git a/sonic-server-eureka/src/main/java/com/sonic/eureka/config/WebSecurityConfig.java b/sonic-server-eureka/src/main/java/org/cloud/sonic/eureka/config/WebSecurityConfig.java similarity index 93% rename from sonic-server-eureka/src/main/java/com/sonic/eureka/config/WebSecurityConfig.java rename to sonic-server-eureka/src/main/java/org/cloud/sonic/eureka/config/WebSecurityConfig.java index 1e37d426..beb4af31 100644 --- a/sonic-server-eureka/src/main/java/com/sonic/eureka/config/WebSecurityConfig.java +++ b/sonic-server-eureka/src/main/java/org/cloud/sonic/eureka/config/WebSecurityConfig.java @@ -1,26 +1,26 @@ -package com.sonic.eureka.config; - -import org.springframework.security.config.annotation.web.builders.HttpSecurity; -import org.springframework.security.config.annotation.web.builders.WebSecurity; -import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; -import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; - -/** - * @author ZhouYiXun - * @des 配置需要加密的内容 - * @date 2021/8/19 15:26 - */ -@EnableWebSecurity -public class WebSecurityConfig extends WebSecurityConfigurerAdapter { - @Override - protected void configure(HttpSecurity http) throws Exception { - http.csrf().ignoringAntMatchers("/eureka/**"); - super.configure(http); - } - - @Override - public void init(WebSecurity web) throws Exception { - web.ignoring().antMatchers("/actuator/**"); - super.init(web); - } +package org.cloud.sonic.eureka.config; + +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.builders.WebSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; + +/** + * @author ZhouYiXun + * @des 配置需要加密的内容 + * @date 2021/8/19 15:26 + */ +@EnableWebSecurity +public class WebSecurityConfig extends WebSecurityConfigurerAdapter { + @Override + protected void configure(HttpSecurity http) throws Exception { + http.csrf().ignoringAntMatchers("/eureka/**"); + super.configure(http); + } + + @Override + public void init(WebSecurity web) throws Exception { + web.ignoring().antMatchers("/actuator/**"); + super.init(web); + } } \ No newline at end of file diff --git a/sonic-server-folder/pom.xml b/sonic-server-folder/pom.xml index 858f406a..b4e08b77 100644 --- a/sonic-server-folder/pom.xml +++ b/sonic-server-folder/pom.xml @@ -4,13 +4,13 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> sonic-server - com.sonic + org.cloud.sonic 1.0.0 4.0.0 sonic-server-folder - v1.2.0-release + v1.3.0-beta2 jar @@ -26,29 +26,63 @@ - com.sonic + org.cloud.sonic sonic-server-common 1.1.0 + + + org.bytedeco + javacv + 1.5.3 + + + org.bytedeco + openblas + 0.3.9-1.5.3 + + + org.bytedeco + opencv + 4.3.0-1.5.3 + + + org.bytedeco + javacpp + 1.5.3 + linux-x86_64 + + + org.bytedeco + opencv + 4.3.0-1.5.3 + linux-x86_64 + + + org.bytedeco + openblas + 0.3.9-1.5.3 + linux-x86_64 + - - - - - org.springframework.boot - spring-boot-maven-plugin - - true - - - - com.spotify - docker-maven-plugin - - true - - - - + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/sonic-server-folder/src/main/java/com/sonic/folder/controller/UploadController.java b/sonic-server-folder/src/main/java/com/sonic/folder/controller/UploadController.java deleted file mode 100644 index aadcba5a..00000000 --- a/sonic-server-folder/src/main/java/com/sonic/folder/controller/UploadController.java +++ /dev/null @@ -1,80 +0,0 @@ -package com.sonic.folder.controller; - -import com.sonic.common.config.WebAspect; -import com.sonic.common.http.RespEnum; -import com.sonic.common.http.RespModel; -import com.sonic.folder.tools.FileTool; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiImplicitParam; -import io.swagger.annotations.ApiImplicitParams; -import io.swagger.annotations.ApiOperation; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RestController; -import org.springframework.web.multipart.MultipartFile; - -import java.io.File; -import java.io.IOException; -import java.nio.file.FileAlreadyExistsException; - -@Api(tags = "文件上传") -@RestController -@RequestMapping("/upload") -public class UploadController { - @Autowired - private FileTool fileTool; - - @WebAspect - @ApiOperation(value = "上传文件", notes = "上传文件到服务器") - @ApiImplicitParams(value = { - @ApiImplicitParam(name = "file", value = "文件", dataTypeClass = MultipartFile.class), - @ApiImplicitParam(name = "type", value = "文件类型(只能为keepFiles、imageFiles、recordFiles、logFiles、packageFiles)", dataTypeClass = String.class), - }) - @PostMapping - public RespModel uploadFiles(@RequestParam(name = "file") MultipartFile file, - @RequestParam(name = "type") String type) throws IOException { - String url = fileTool.upload(type, file); - if (url != null) { - return new RespModel(RespEnum.UPLOAD_OK, url); - } else { - return new RespModel(RespEnum.UPLOAD_ERROR); - } - } - - @WebAspect - @ApiOperation(value = "上传文件(录像分段上传)", notes = "上传文件到服务器") - @ApiImplicitParams(value = { - @ApiImplicitParam(name = "file", value = "文件", dataTypeClass = MultipartFile.class), - @ApiImplicitParam(name = "uuid", value = "文件uuid", dataTypeClass = String.class), - @ApiImplicitParam(name = "index", value = "当前index", dataTypeClass = Integer.class), - @ApiImplicitParam(name = "total", value = "index总数", dataTypeClass = Integer.class), - }) - @PostMapping("/recordFiles") - public RespModel uploadRecord(@RequestParam(name = "file") MultipartFile file, - @RequestParam(name = "uuid") String uuid, - @RequestParam(name = "index") int index, - @RequestParam(name = "total") int total) throws IOException { - //先创建对应uuid的文件夹 - File uuidFolder = new File("recordFiles" + File.separator + uuid); - if (!uuidFolder.exists()) { - uuidFolder.mkdirs(); - } - String fileName = file.getOriginalFilename(); - String newName = fileName.substring(0, fileName.indexOf(".mp4")) + "-" + index + ".mp4"; - File local = new File(uuidFolder.getPath() + File.separator + newName); - RespModel responseModel; - try { - file.transferTo(local.getAbsoluteFile()); - responseModel = new RespModel(RespEnum.UPLOAD_OK); - } catch (FileAlreadyExistsException e) { - responseModel = new RespModel(RespEnum.UPLOAD_ERROR); - } - //如果当前是最后一个,就开始合并录像文件 - if (index == total - 1) { - responseModel.setData(fileTool.merge(uuid, file.getOriginalFilename(), total)); - } - return responseModel; - } -} diff --git a/sonic-server-folder/src/main/java/com/sonic/folder/FolderApplication.java b/sonic-server-folder/src/main/java/org/cloud/sonic/folder/FolderApplication.java similarity index 73% rename from sonic-server-folder/src/main/java/com/sonic/folder/FolderApplication.java rename to sonic-server-folder/src/main/java/org/cloud/sonic/folder/FolderApplication.java index d40bbbe9..6eb177c7 100644 --- a/sonic-server-folder/src/main/java/com/sonic/folder/FolderApplication.java +++ b/sonic-server-folder/src/main/java/org/cloud/sonic/folder/FolderApplication.java @@ -1,13 +1,13 @@ -package com.sonic.folder; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.cloud.netflix.eureka.EnableEurekaClient; - -@SpringBootApplication(scanBasePackages = {"com/sonic/folder", "com/sonic/common"}) -@EnableEurekaClient -public class FolderApplication { - public static void main(String[] args) { - SpringApplication.run(FolderApplication.class, args); - } +package org.cloud.sonic.folder; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.netflix.eureka.EnableEurekaClient; + +@SpringBootApplication(scanBasePackages = {"org/cloud/sonic/folder", "org/cloud/sonic/common"}) +@EnableEurekaClient +public class FolderApplication { + public static void main(String[] args) { + SpringApplication.run(FolderApplication.class, args); + } } \ No newline at end of file diff --git a/sonic-server-folder/src/main/java/com/sonic/folder/config/WebConfig.java b/sonic-server-folder/src/main/java/org/cloud/sonic/folder/config/WebConfig.java similarity index 95% rename from sonic-server-folder/src/main/java/com/sonic/folder/config/WebConfig.java rename to sonic-server-folder/src/main/java/org/cloud/sonic/folder/config/WebConfig.java index 550ee56d..ad97b97c 100644 --- a/sonic-server-folder/src/main/java/com/sonic/folder/config/WebConfig.java +++ b/sonic-server-folder/src/main/java/org/cloud/sonic/folder/config/WebConfig.java @@ -1,29 +1,29 @@ -package com.sonic.folder.config; - -import org.springframework.context.annotation.Configuration; -import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport; - -/** - * @author ZhouYiXun - * @des 静态资源重定向配置 - * @date 2021/8/18 20:26 - */ -@Configuration -public class WebConfig extends WebMvcConfigurationSupport { - - @Override - protected void addResourceHandlers(ResourceHandlerRegistry registry) { - registry.addResourceHandler("/keepFiles/**") - .addResourceLocations("file:///" + System.getProperty("user.dir") + "/keepFiles/"); - registry.addResourceHandler("/imageFiles/**") - .addResourceLocations("file:///" + System.getProperty("user.dir") + "/imageFiles/"); - registry.addResourceHandler("/recordFiles/**") - .addResourceLocations("file:///" + System.getProperty("user.dir") + "/recordFiles/"); - registry.addResourceHandler("/logFiles/**") - .addResourceLocations("file:///" + System.getProperty("user.dir") + "/logFiles/"); - registry.addResourceHandler("/packageFiles/**") - .addResourceLocations("file:///" + System.getProperty("user.dir") + "/packageFiles/"); - super.addResourceHandlers(registry); - } +package org.cloud.sonic.folder.config; + +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport; + +/** + * @author ZhouYiXun + * @des 静态资源重定向配置 + * @date 2021/8/18 20:26 + */ +@Configuration +public class WebConfig extends WebMvcConfigurationSupport { + + @Override + protected void addResourceHandlers(ResourceHandlerRegistry registry) { + registry.addResourceHandler("/keepFiles/**") + .addResourceLocations("file:///" + System.getProperty("user.dir") + "/keepFiles/"); + registry.addResourceHandler("/imageFiles/**") + .addResourceLocations("file:///" + System.getProperty("user.dir") + "/imageFiles/"); + registry.addResourceHandler("/recordFiles/**") + .addResourceLocations("file:///" + System.getProperty("user.dir") + "/recordFiles/"); + registry.addResourceHandler("/logFiles/**") + .addResourceLocations("file:///" + System.getProperty("user.dir") + "/logFiles/"); + registry.addResourceHandler("/packageFiles/**") + .addResourceLocations("file:///" + System.getProperty("user.dir") + "/packageFiles/"); + super.addResourceHandlers(registry); + } } \ No newline at end of file diff --git a/sonic-server-folder/src/main/java/com/sonic/folder/controller/FilesController.java b/sonic-server-folder/src/main/java/org/cloud/sonic/folder/controller/FilesController.java similarity index 88% rename from sonic-server-folder/src/main/java/com/sonic/folder/controller/FilesController.java rename to sonic-server-folder/src/main/java/org/cloud/sonic/folder/controller/FilesController.java index bfdf3c35..7f44aa33 100644 --- a/sonic-server-folder/src/main/java/com/sonic/folder/controller/FilesController.java +++ b/sonic-server-folder/src/main/java/org/cloud/sonic/folder/controller/FilesController.java @@ -1,60 +1,60 @@ -package com.sonic.folder.controller; - -import com.sonic.common.config.WebAspect; -import com.sonic.common.http.RespModel; -import com.sonic.folder.tools.FileTool; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.web.bind.annotation.*; - -import java.io.File; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.Arrays; -import java.util.Calendar; -import java.util.List; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; - -@RestController -@RequestMapping("/files") -public class FilesController { - private final Logger logger = LoggerFactory.getLogger(FilesController.class); - private ExecutorService cachedThreadPool = Executors.newCachedThreadPool(); - @Autowired - private FileTool fileTool; - - /** - * @param day 文件保留天数 - * @return com.sonic.common.http.RespModel - * @author ZhouYiXun - * @des 删除本地文件 - * @date 2021/8/21 21:47 - */ - @WebAspect - @DeleteMapping - public RespModel delete(@RequestParam(name = "day") int day) { - long timeMillis = Calendar.getInstance().getTimeInMillis(); - SimpleDateFormat sf = new SimpleDateFormat("yyyyMMdd"); - List fileList = Arrays.asList("imageFiles", "recordFiles", "logFiles", "packageFiles"); - cachedThreadPool.execute(() -> { - for (String fileType : fileList) { - File[] type = new File(fileType).listFiles(); - for (File dateFile : type) { - try { - if (timeMillis - sf.parse(dateFile.getName()).getTime() - > day * 86400000L) { - logger.info("开始清理:" + dateFile.getPath()); - fileTool.deleteDir(dateFile); - } - } catch (ParseException e) { - logger.info("文件名出错:" + dateFile.getPath()); - logger.error(e.getMessage()); - } - } - } - }); - return new RespModel(2000, "开始清理!"); - } -} +package org.cloud.sonic.folder.controller; + +import org.cloud.sonic.common.config.WebAspect; +import org.cloud.sonic.common.http.RespModel; +import org.cloud.sonic.folder.tools.FileTool; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import java.io.File; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Arrays; +import java.util.Calendar; +import java.util.List; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +@RestController +@RequestMapping("/files") +public class FilesController { + private final Logger logger = LoggerFactory.getLogger(FilesController.class); + private ExecutorService cachedThreadPool = Executors.newCachedThreadPool(); + @Autowired + private FileTool fileTool; + + /** + * @param day 文件保留天数 + * @return org.cloud.sonic.common.http.RespModel + * @author ZhouYiXun + * @des 删除本地文件 + * @date 2021/8/21 21:47 + */ + @WebAspect + @DeleteMapping + public RespModel delete(@RequestParam(name = "day") int day) { + long timeMillis = Calendar.getInstance().getTimeInMillis(); + SimpleDateFormat sf = new SimpleDateFormat("yyyyMMdd"); + List fileList = Arrays.asList("imageFiles", "recordFiles", "logFiles", "packageFiles"); + cachedThreadPool.execute(() -> { + for (String fileType : fileList) { + File[] type = new File(fileType).listFiles(); + for (File dateFile : type) { + try { + if (timeMillis - sf.parse(dateFile.getName()).getTime() + > day * 86400000L) { + logger.info("开始清理:" + dateFile.getPath()); + fileTool.deleteDir(dateFile); + } + } catch (ParseException e) { + logger.info("文件名出错:" + dateFile.getPath()); + logger.error(e.getMessage()); + } + } + } + }); + return new RespModel(2000, "开始清理!"); + } +} diff --git a/sonic-server-folder/src/main/java/org/cloud/sonic/folder/controller/UploadController.java b/sonic-server-folder/src/main/java/org/cloud/sonic/folder/controller/UploadController.java new file mode 100644 index 00000000..98980c7a --- /dev/null +++ b/sonic-server-folder/src/main/java/org/cloud/sonic/folder/controller/UploadController.java @@ -0,0 +1,160 @@ +package org.cloud.sonic.folder.controller; + +import lombok.extern.slf4j.Slf4j; +import org.cloud.sonic.common.config.WebAspect; +import org.cloud.sonic.common.http.RespEnum; +import org.cloud.sonic.common.http.RespModel; +import org.cloud.sonic.folder.cv.AKAZEFinder; +import org.cloud.sonic.folder.cv.SIFTFinder; +import org.cloud.sonic.folder.cv.SimilarityChecker; +import org.cloud.sonic.folder.cv.TemMatcher; +import org.cloud.sonic.folder.models.FindResult; +import org.cloud.sonic.folder.tools.FileTool; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiImplicitParam; +import io.swagger.annotations.ApiImplicitParams; +import io.swagger.annotations.ApiOperation; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.multipart.MultipartFile; + +import java.io.File; +import java.io.IOException; +import java.nio.file.FileAlreadyExistsException; +import java.util.UUID; + +@Api(tags = "文件上传") +@RestController +@RequestMapping("/upload") +@Slf4j +public class UploadController { + @Autowired + private FileTool fileTool; + @Autowired + private AKAZEFinder akazeFinder; + @Autowired + private SIFTFinder siftFinder; + @Autowired + private SimilarityChecker similarityChecker; + @Autowired + private TemMatcher temMatcher; + + @WebAspect + @ApiOperation(value = "上传文件", notes = "上传文件到服务器") + @ApiImplicitParams(value = { + @ApiImplicitParam(name = "file", value = "文件", dataTypeClass = MultipartFile.class), + @ApiImplicitParam(name = "type", value = "文件类型(只能为keepFiles、imageFiles、recordFiles、logFiles、packageFiles)", dataTypeClass = String.class), + }) + @PostMapping + public RespModel uploadFiles(@RequestParam(name = "file") MultipartFile file, + @RequestParam(name = "type") String type) throws IOException { + String url = fileTool.upload(type, file); + if (url != null) { + return new RespModel(RespEnum.UPLOAD_OK, url); + } else { + return new RespModel(RespEnum.UPLOAD_ERROR); + } + } + + @WebAspect + @ApiOperation(value = "上传文件(录像分段上传)", notes = "上传文件到服务器") + @ApiImplicitParams(value = { + @ApiImplicitParam(name = "file", value = "文件", dataTypeClass = MultipartFile.class), + @ApiImplicitParam(name = "uuid", value = "文件uuid", dataTypeClass = String.class), + @ApiImplicitParam(name = "index", value = "当前index", dataTypeClass = Integer.class), + @ApiImplicitParam(name = "total", value = "index总数", dataTypeClass = Integer.class), + }) + @PostMapping("/recordFiles") + public RespModel uploadRecord(@RequestParam(name = "file") MultipartFile file, + @RequestParam(name = "uuid") String uuid, + @RequestParam(name = "index") int index, + @RequestParam(name = "total") int total) throws IOException { + //先创建对应uuid的文件夹 + File uuidFolder = new File("recordFiles" + File.separator + uuid); + if (!uuidFolder.exists()) { + uuidFolder.mkdirs(); + } + String fileName = file.getOriginalFilename(); + String newName = fileName.substring(0, fileName.indexOf(".mp4")) + "-" + index + ".mp4"; + File local = new File(uuidFolder.getPath() + File.separator + newName); + RespModel responseModel; + try { + file.transferTo(local.getAbsoluteFile()); + responseModel = new RespModel<>(RespEnum.UPLOAD_OK); + } catch (FileAlreadyExistsException e) { + responseModel = new RespModel<>(RespEnum.UPLOAD_ERROR); + } + //如果当前是最后一个,就开始合并录像文件 + if (index == total - 1) { + responseModel.setData(fileTool.merge(uuid, file.getOriginalFilename(), total)); + } + return responseModel; + } + + @WebAspect + @ApiOperation(value = "cv定位", notes = "三种定位方式") + @ApiImplicitParams(value = { + @ApiImplicitParam(name = "file1", value = "模板文件", dataTypeClass = MultipartFile.class), + @ApiImplicitParam(name = "file2", value = "原文件", dataTypeClass = MultipartFile.class) + }) + @PostMapping("/cv") + public RespModel cv(@RequestParam(name = "file1") MultipartFile file1, + @RequestParam(name = "file2") MultipartFile file2, + @RequestParam(name = "type") String type) throws IOException { + File local1 = new File("imageFiles" + File.separator + + UUID.randomUUID() + file1.getOriginalFilename() + .substring(file1.getOriginalFilename().lastIndexOf("."))); + try { + file1.transferTo(local1.getAbsoluteFile()); + } catch (FileAlreadyExistsException e) { + log.error(e.getMessage()); + } + File local2 = new File("imageFiles" + File.separator + + UUID.randomUUID() + file2.getOriginalFilename() + .substring(file2.getOriginalFilename().lastIndexOf("."))); + try { + file2.transferTo(local2.getAbsoluteFile()); + } catch (FileAlreadyExistsException e) { + log.error(e.getMessage()); + } + switch (type) { + case "finder": { + FindResult findResult = null; + try { + findResult = siftFinder.getSIFTFindResult(local1, local2); + } catch (Exception e) { + log.info("SIFT图像算法出错,切换算法中..."); + } + if (findResult == null) { + try { + findResult = akazeFinder.getAKAZEFindResult(local1, local2); + } catch (Exception e) { + log.info("AKAZE图像算法出错,切换算法中..."); + } + if (findResult == null) { + try { + findResult = temMatcher.getTemMatchResult(local1, local2); + } catch (Exception e) { + log.info("模版匹配算法出错"); + } + } + } + if (findResult != null) { + return new RespModel(RespEnum.HANDLE_OK, findResult); + } else { + return new RespModel<>(RespEnum.UNKNOWN_ERROR); + } + } + case "checker": { + double score = similarityChecker.getSimilarMSSIMScore(local1, local2); + return new RespModel(RespEnum.SEARCH_OK, score); + } + default: { + return new RespModel(RespEnum.PARAMS_VIOLATE_ERROR); + } + } + } +} diff --git a/sonic-server-folder/src/main/java/org/cloud/sonic/folder/cv/AKAZEFinder.java b/sonic-server-folder/src/main/java/org/cloud/sonic/folder/cv/AKAZEFinder.java new file mode 100644 index 00000000..25b29865 --- /dev/null +++ b/sonic-server-folder/src/main/java/org/cloud/sonic/folder/cv/AKAZEFinder.java @@ -0,0 +1,338 @@ +package org.cloud.sonic.folder.cv; + +import org.bytedeco.opencv.opencv_core.*; +import org.bytedeco.opencv.opencv_features2d.AKAZE; +import org.bytedeco.opencv.opencv_flann.Index; +import org.bytedeco.opencv.opencv_flann.IndexParams; +import org.bytedeco.opencv.opencv_flann.LshIndexParams; +import org.bytedeco.opencv.opencv_flann.SearchParams; +import org.cloud.sonic.folder.models.FindResult; +import org.cloud.sonic.folder.tools.FileTool; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import java.io.File; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.FloatBuffer; +import java.nio.IntBuffer; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.UUID; +import java.util.concurrent.ThreadLocalRandom; + +import static org.bytedeco.opencv.global.opencv_calib3d.CV_RANSAC; +import static org.bytedeco.opencv.global.opencv_calib3d.findHomography; +import static org.bytedeco.opencv.global.opencv_core.*; +import static org.bytedeco.opencv.global.opencv_flann.FLANN_DIST_HAMMING; +import static org.bytedeco.opencv.global.opencv_imgcodecs.*; +import static org.bytedeco.opencv.global.opencv_imgproc.*; +import static org.bytedeco.opencv.helper.opencv_imgcodecs.cvLoadImage; +import static org.bytedeco.opencv.helper.opencv_imgcodecs.cvSaveImage; + +/** + * @author ZhouYiXun + * @des akaze算法 + * @date 2022/1/4 21:49 + */ +@Component +public class AKAZEFinder { + private final Logger logger = LoggerFactory.getLogger(AKAZEFinder.class); + IplImage objectImage = null; + AKAZE detector = AKAZE.create(); + double distanceThreshold = 0.6; + int matchesMin = 4; + double ransacReprojThreshold = 1.0; + boolean useFLANN = false; + KeyPointVector objectKeypoints = null, imageKeypoints = null; + Mat objectDescriptors = null, imageDescriptors = null; + Mat indicesMat, distsMat; + Index flannIndex = null; + IndexParams indexParams = null; + SearchParams searchParams = null; + Mat pt1 = null, pt2 = null, mask = null, H = null; + ArrayList ptpairs = null; + @Autowired + private FileTool fileTool; + + public void init() { + objectKeypoints = new KeyPointVector(); + objectDescriptors = new Mat(); + detector.detectAndCompute(cvarrToMat(objectImage), + new Mat(), objectKeypoints, objectDescriptors, false); + + int total = (int) objectKeypoints.size(); + if (useFLANN) { + indicesMat = new Mat(total, 2, CV_32SC1); + distsMat = new Mat(total, 2, CV_32FC1); + flannIndex = new Index(); + indexParams = new LshIndexParams(12, 20, 2); // using LSH Hamming distance + searchParams = new SearchParams(64, 0, true); // maximum number of leafs checked + searchParams.deallocate(false); // for some reason FLANN seems to do it for us + } + pt1 = new Mat(total, 1, CV_32FC2); + pt2 = new Mat(total, 1, CV_32FC2); + mask = new Mat(total, 1, CV_8UC1); + H = new Mat(3, 3, CV_64FC1); + ptpairs = new ArrayList(2 * objectDescriptors.rows()); + logger.info("模版图一共有" + total + "个特征点"); + } + + public double[] find(IplImage image) { + if (objectDescriptors.rows() < matchesMin) { + return null; + } + imageKeypoints = new KeyPointVector(); + imageDescriptors = new Mat(); + detector.detectAndCompute(cvarrToMat(image), + new Mat(), imageKeypoints, imageDescriptors, false); + if (imageDescriptors.rows() < matchesMin) { + return null; + } + + int total = (int) imageKeypoints.size(); + logger.info("原图一共有" + total + "个特征点"); + + int w = objectImage.width(); + int h = objectImage.height(); + double[] srcCorners = {0, 0, w, 0, w, h, 0, h}; + double[] dstCorners = locatePlanarObject(objectKeypoints, objectDescriptors, + imageKeypoints, imageDescriptors, srcCorners); + return dstCorners; + } + + private static final int[] bits = new int[256]; + + static { + for (int i = 0; i < bits.length; i++) { + for (int j = i; j != 0; j >>= 1) { + bits[i] += j & 0x1; + } + } + } + + private int compareDescriptors(ByteBuffer d1, ByteBuffer d2, int best) { + int totalCost = 0; + assert d1.limit() - d1.position() == d2.limit() - d2.position(); + while (d1.position() < d1.limit()) { + totalCost += bits[(d1.get() ^ d2.get()) & 0xFF]; + if (totalCost > best) + break; + } + return totalCost; + } + + private int naiveNearestNeighbor(ByteBuffer vec, ByteBuffer modelDescriptors) { + int neighbor = -1; + int d, dist1 = Integer.MAX_VALUE, dist2 = Integer.MAX_VALUE; + int size = vec.limit() - vec.position(); + + for (int i = 0; i * size < modelDescriptors.capacity(); i++) { + ByteBuffer mvec = (ByteBuffer) modelDescriptors.position(i * size).limit((i + 1) * size); + d = compareDescriptors((ByteBuffer) vec.reset(), mvec, dist2); + if (d < dist1) { + dist2 = dist1; + dist1 = d; + neighbor = i; + } else if (d < dist2) { + dist2 = d; + } + } + if (dist1 < distanceThreshold * dist2) + return neighbor; + return -1; + } + + private void findPairs(Mat objectDescriptors, Mat imageDescriptors) { + int size = imageDescriptors.cols(); + ByteBuffer objectBuf = objectDescriptors.createBuffer(); + ByteBuffer imageBuf = imageDescriptors.createBuffer(); + + for (int i = 0; i * size < objectBuf.capacity(); i++) { + ByteBuffer descriptor = (ByteBuffer) objectBuf.position(i * size).limit((i + 1) * size).mark(); + int nearestNeighbor = naiveNearestNeighbor(descriptor, imageBuf); + if (nearestNeighbor >= 0) { + ptpairs.add(i); + ptpairs.add(nearestNeighbor); + } + } + } + + private void flannFindPairs(Mat objectDescriptors, Mat imageDescriptors) { + int length = objectDescriptors.rows(); + flannIndex.build(imageDescriptors, indexParams, FLANN_DIST_HAMMING); + flannIndex.knnSearch(objectDescriptors, indicesMat, distsMat, 2, searchParams); + IntBuffer indicesBuf = indicesMat.createBuffer(); + IntBuffer distsBuf = distsMat.createBuffer(); + for (int i = 0; i < length; i++) { + if (distsBuf.get(2 * i) < distanceThreshold * distsBuf.get(2 * i + 1)) { + ptpairs.add(i); + ptpairs.add(indicesBuf.get(2 * i)); + } + } + } + + private double[] locatePlanarObject(KeyPointVector objectKeypoints, Mat objectDescriptors, + KeyPointVector imageKeypoints, Mat imageDescriptors, double[] srcCorners) { + ptpairs.clear(); + if (useFLANN) { + flannFindPairs(objectDescriptors, imageDescriptors); + } else { + findPairs(objectDescriptors, imageDescriptors); + } + int n = ptpairs.size() / 2; + logger.info("筛选后共有" + n + "个吻合点"); + if (n < matchesMin) { + return null; + } + + pt1.resize(n); + pt2.resize(n); + mask.resize(n); + FloatBuffer pt1Idx = pt1.createBuffer(); + FloatBuffer pt2Idx = pt2.createBuffer(); + for (int i = 0; i < n; i++) { + Point2f p1 = objectKeypoints.get(ptpairs.get(2 * i)).pt(); + pt1Idx.put(2 * i, p1.x()); + pt1Idx.put(2 * i + 1, p1.y()); + Point2f p2 = imageKeypoints.get(ptpairs.get(2 * i + 1)).pt(); + pt2Idx.put(2 * i, p2.x()); + pt2Idx.put(2 * i + 1, p2.y()); + } + + H = findHomography(pt1, pt2, CV_RANSAC, ransacReprojThreshold, mask, 2000, 0.995); + if (H.empty() || countNonZero(mask) < matchesMin) { + return null; + } + + double[] h = (double[]) H.createIndexer(false).array(); + double[] dstCorners = new double[srcCorners.length]; + for (int i = 0; i < srcCorners.length / 2; i++) { + double x = srcCorners[2 * i], y = srcCorners[2 * i + 1]; + double Z = 1 / (h[6] * x + h[7] * y + h[8]); + double X = (h[0] * x + h[1] * y + h[2]) * Z; + double Y = (h[3] * x + h[4] * y + h[5]) * Z; + dstCorners[2 * i] = X; + dstCorners[2 * i + 1] = Y; + } + return dstCorners; + } + + public static Scalar randColor() { + int b, g, r; + b = ThreadLocalRandom.current().nextInt(0, 255); + g = ThreadLocalRandom.current().nextInt(0, 255); + r = ThreadLocalRandom.current().nextInt(0, 255); + return new Scalar(b, g, r, 0); + } + + public FindResult getAKAZEFindResult(File temFile, File beforeFile) throws IOException { + IplImage object = cvLoadImage(temFile.getAbsolutePath(), IMREAD_GRAYSCALE); + IplImage image = cvLoadImage(beforeFile.getAbsolutePath(), IMREAD_GRAYSCALE); + logger.info("原图宽:" + image.width()); + logger.info("原图高:" + image.height()); + if (object == null || image == null) { + logger.error("读取图片失败!"); + temFile.delete(); + beforeFile.delete(); + return null; + } + + IplImage correspond = IplImage.create(image.width() + object.width(), image.height(), 8, 1); + cvSetImageROI(correspond, cvRect(0, 0, image.width(), correspond.height())); + cvCopy(image, correspond); + cvSetImageROI(correspond, cvRect(image.width(), 0, object.width(), object.height())); + cvCopy(object, correspond); + cvResetImageROI(correspond); + + objectImage = object; + useFLANN = true; + ransacReprojThreshold = 3; + init(); + + long start = System.currentTimeMillis(); + double[] dst_corners = find(image); + FindResult findResult = new FindResult(); + findResult.setTime((int) (System.currentTimeMillis() - start)); + logger.info("特征匹配时间: " + (System.currentTimeMillis() - start) + " ms"); + + IplImage correspondColor = IplImage.create(correspond.width(), correspond.height(), 8, 3); + cvCvtColor(correspond, correspondColor, CV_GRAY2BGR); + cvSetImageROI(correspondColor, cvRect(0, 0, image.width(), correspondColor.height())); + cvCopy(cvLoadImage(beforeFile.getAbsolutePath(), IMREAD_COLOR), correspondColor); + cvSetImageROI(correspondColor, cvRect(image.width(), 0, object.width(), object.height())); + cvCopy(cvLoadImage(temFile.getAbsolutePath(), IMREAD_COLOR), correspondColor); + cvResetImageROI(correspondColor); + + if (dst_corners != null) { + int resultX = 0; + int resultY = 0; + for (int i = 0; i < 4; i++) { + int j = (i + 1) % 4; + int x1 = (int) Math.round(dst_corners[2 * i]); + int y1 = (int) Math.round(dst_corners[2 * i + 1]); + int x2 = (int) Math.round(dst_corners[2 * j]); + int y2 = (int) Math.round(dst_corners[2 * j + 1]); + line(cvarrToMat(correspondColor), new Point(x1, y1), + new Point(x2, y2), + Scalar.RED, 2, CV_AA, 0); + if (i == 0) { + resultX = (x1 + x2) / 2; + } + if (i == 1) { + resultY = (y1 + y2) / 2; + } + } + if (resultX == 0 && resultY == 0) { + temFile.delete(); + beforeFile.delete(); + return null; + } + findResult.setX(resultX); + findResult.setY(resultY); + logger.info("结果坐标为(" + resultX + "," + resultY + ")"); + } + + if (objectKeypoints != null) { + for (int i = 0; i < objectKeypoints.size(); i++) { + KeyPoint r = objectKeypoints.get(i); + Point center = new Point(Math.round(r.pt().x()) + image.width(), Math.round(r.pt().y())); + int radius = Math.round(r.size() / 2); + circle(cvarrToMat(correspondColor), center, radius, randColor(), 1, CV_AA, 0); + } + } + + if (imageKeypoints != null) { + for (int i = 0; i < imageKeypoints.size(); i++) { + KeyPoint r = imageKeypoints.get(i); + Point center = new Point(Math.round(r.pt().x()), Math.round(r.pt().y())); + int radius = Math.round(r.size() / 2); + circle(cvarrToMat(correspondColor), center, radius, randColor(), 1, CV_AA, 0); + } + } + + for (int i = 0; i < ptpairs.size(); i += 2) { + Point2f pt1 = objectKeypoints.get(ptpairs.get(i)).pt(); + Point2f pt2 = imageKeypoints.get(ptpairs.get(i + 1)).pt(); + line(cvarrToMat(correspondColor), new Point(Math.round(pt1.x()) + image.width(), Math.round(pt1.y())), + new Point(Math.round(pt2.x()), Math.round(pt2.y())), + randColor(), 1, CV_AA, 0); + } + SimpleDateFormat sf = new SimpleDateFormat("yyyyMMdd"); + File folder = new File("imageFiles" + File.separator + + sf.format(Calendar.getInstance().getTimeInMillis())); + if (!folder.exists()) { + folder.mkdirs(); + } + File fileName = new File(folder.getPath() + File.separator + + UUID.randomUUID() + ".jpg"); + cvSaveImage(fileName.getAbsolutePath(), correspondColor); + findResult.setUrl(fileTool.upload(fileName)); + temFile.delete(); + beforeFile.delete(); + return findResult; + } +} \ No newline at end of file diff --git a/sonic-server-folder/src/main/java/org/cloud/sonic/folder/cv/SIFTFinder.java b/sonic-server-folder/src/main/java/org/cloud/sonic/folder/cv/SIFTFinder.java new file mode 100644 index 00000000..330a8f6c --- /dev/null +++ b/sonic-server-folder/src/main/java/org/cloud/sonic/folder/cv/SIFTFinder.java @@ -0,0 +1,118 @@ +package org.cloud.sonic.folder.cv; + +import org.bytedeco.opencv.opencv_core.*; +import org.bytedeco.opencv.opencv_features2d.FlannBasedMatcher; +import org.bytedeco.opencv.opencv_xfeatures2d.SIFT; +import org.cloud.sonic.folder.models.FindResult; +import org.cloud.sonic.folder.tools.FileTool; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import java.io.File; +import java.io.IOException; +import java.text.SimpleDateFormat; +import java.util.*; + +import static org.bytedeco.opencv.global.opencv_features2d.drawMatchesKnn; +import static org.bytedeco.opencv.global.opencv_imgcodecs.imread; +import static org.bytedeco.opencv.global.opencv_imgcodecs.imwrite; +import static org.bytedeco.opencv.global.opencv_imgproc.*; + +/** + * @author ZhouYiXun + * @des sift算法 + * @date 2022/1/4 21:49 + */ +@Component +public class SIFTFinder { + private final Logger logger = LoggerFactory.getLogger(SIFTFinder.class); + @Autowired + private FileTool fileTool; + + public FindResult getSIFTFindResult(File temFile, File beforeFile) throws IOException { + Mat image01 = imread(beforeFile.getAbsolutePath()); + Mat image02 = imread(temFile.getAbsolutePath()); + + Mat image1 = new Mat(); + Mat image2 = new Mat(); + cvtColor(image01, image1, COLOR_BGR2GRAY); + cvtColor(image02, image2, COLOR_BGR2GRAY); + + KeyPointVector keyPointVector1 = new KeyPointVector(); + KeyPointVector keyPointVector2 = new KeyPointVector(); + Mat image11 = new Mat(); + Mat image22 = new Mat(); + + long start = System.currentTimeMillis(); + SIFT sift = SIFT.create(); + sift.detectAndCompute(image1, image1, keyPointVector1, image11); + sift.detectAndCompute(image2, image2, keyPointVector2, image22); + + FlannBasedMatcher flannBasedMatcher = new FlannBasedMatcher(); + DMatchVectorVector matchPoints = new DMatchVectorVector(); + + flannBasedMatcher.knnMatch(image11, image22, matchPoints, 2); + logger.info("处理前共有匹配数:" + matchPoints.size()); + DMatchVectorVector goodMatches = new DMatchVectorVector(); + + List xs = new ArrayList<>(); + List ys = new ArrayList<>(); + for (long i = 0; i < matchPoints.size(); i++) { + if (matchPoints.get(i).size() >= 2) { + DMatch match1 = matchPoints.get(i).get(0); + DMatch match2 = matchPoints.get(i).get(1); + + if (match1.distance() <= 0.6 * match2.distance()) { + xs.add((int) keyPointVector1.get(match1.queryIdx()).pt().x()); + ys.add((int) keyPointVector1.get(match1.queryIdx()).pt().y()); + goodMatches.push_back(matchPoints.get(i)); + } + } + } + logger.info("处理后匹配数:" + goodMatches.size()); + if (goodMatches.size() <= 4) { + temFile.delete(); + beforeFile.delete(); + return null; + } + FindResult findResult = new FindResult(); + findResult.setTime((int) (System.currentTimeMillis() - start)); + Mat result = new Mat(); + + drawMatchesKnn(image01, keyPointVector1, image02, keyPointVector2, goodMatches, result); + + int resultX = majorityElement(xs); + int resultY = majorityElement(ys); + findResult.setX(resultX); + findResult.setY(resultY); + logger.info("结果坐标为(" + resultX + "," + resultY + ")"); + circle(result, new Point(resultX, resultY), 5, Scalar.RED, 10, CV_AA, 0); + SimpleDateFormat sf = new SimpleDateFormat("yyyyMMdd"); + File folder = new File("imageFiles" + File.separator + + sf.format(Calendar.getInstance().getTimeInMillis())); + if (!folder.exists()) { + folder.mkdirs(); + } + File fileName = new File(folder.getPath() + File.separator + + UUID.randomUUID() + ".jpg"); + imwrite(fileName.getAbsolutePath(), result); + findResult.setUrl(fileTool.upload(fileName)); + temFile.delete(); + beforeFile.delete(); + return findResult; + } + + public static int majorityElement(List nums) { + double j; + Collections.sort(nums); + int size = nums.size(); + if (size % 2 == 1) { + j = nums.get((size - 1) / 2); + } else { + j = (nums.get(size / 2 - 1) + nums.get(size / 2) + 0.0) / 2; + } + return (int) j; + } +} diff --git a/sonic-server-folder/src/main/java/org/cloud/sonic/folder/cv/SimilarityChecker.java b/sonic-server-folder/src/main/java/org/cloud/sonic/folder/cv/SimilarityChecker.java new file mode 100644 index 00000000..af2023ce --- /dev/null +++ b/sonic-server-folder/src/main/java/org/cloud/sonic/folder/cv/SimilarityChecker.java @@ -0,0 +1,75 @@ +package org.cloud.sonic.folder.cv; + +import org.bytedeco.opencv.global.opencv_core; +import org.bytedeco.opencv.opencv_core.Mat; +import org.bytedeco.opencv.opencv_core.Scalar; +import org.bytedeco.opencv.opencv_core.Size; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; + +import java.io.File; +import java.math.BigDecimal; +import java.math.RoundingMode; + +import static org.bytedeco.opencv.global.opencv_core.*; +import static org.bytedeco.opencv.global.opencv_imgcodecs.imread; +import static org.bytedeco.opencv.global.opencv_imgproc.GaussianBlur; + +/** + * @author ZhouYiXun + * @des 相似度比对 + * @date 2022/1/4 21:49 + */ +@Component +public class SimilarityChecker { + private final Logger logger = LoggerFactory.getLogger(SimilarityChecker.class); + + public double getSimilarMSSIMScore(File file1, File file2) { + synchronized (SimilarityChecker.class) { + Mat i1 = imread(file1.getAbsolutePath()); + Mat i2 = imread(file2.getAbsolutePath()); + if (i1.size().get() != i2.size().get()) { + return 0; + } + double C1 = 6.5025, C2 = 58.5225; + int d = opencv_core.CV_32F; + Mat I1 = new Mat(); + Mat I2 = new Mat(); + i1.convertTo(I1, d); + i2.convertTo(I2, d); + Mat I2_2 = I2.mul(I2).asMat(); + Mat I1_2 = I1.mul(I1).asMat(); + Mat I1_I2 = I1.mul(I2).asMat(); + Mat mu1 = new Mat(); + Mat mu2 = new Mat(); + GaussianBlur(I1, mu1, new Size(11, 11), 1.5); + GaussianBlur(I2, mu2, new Size(11, 11), 1.5); + Mat mu1_2 = mu1.mul(mu1).asMat(); + Mat mu2_2 = mu2.mul(mu2).asMat(); + Mat mu1_mu2 = mu1.mul(mu2).asMat(); + Mat sigma1_2 = new Mat(); + Mat sigma2_2 = new Mat(); + Mat sigma12 = new Mat(); + GaussianBlur(I1_2, sigma1_2, new Size(11, 11), 1.5); + sigma1_2 = subtract(sigma1_2, mu1_2).asMat(); + GaussianBlur(I2_2, sigma2_2, new Size(11, 11), 1.5); + sigma2_2 = subtract(sigma2_2, mu2_2).asMat(); + GaussianBlur(I1_I2, sigma12, new Size(11, 11), 1.5); + sigma12 = subtract(sigma12, mu1_mu2).asMat(); + Mat t1, t2, t3; + t1 = add(multiply(2, mu1_mu2), Scalar.all(C1)).asMat(); + t2 = add(multiply(2, sigma12), Scalar.all(C2)).asMat(); + t3 = t1.mul(t2).asMat(); + t1 = add(add(mu1_2, mu2_2), Scalar.all(C1)).asMat(); + t2 = add(add(sigma1_2, sigma2_2), Scalar.all(C2)).asMat(); + t1 = t1.mul(t2).asMat(); + Mat ssim_map = new Mat(); + divide(t3, t1, ssim_map); + Scalar mSsim = mean(ssim_map); + file1.delete(); + file2.delete(); + return new BigDecimal((mSsim.get(0) + mSsim.get(1) + mSsim.get(2)) / 3).setScale(2, RoundingMode.DOWN).doubleValue(); + } + } +} \ No newline at end of file diff --git a/sonic-server-folder/src/main/java/org/cloud/sonic/folder/cv/TemMatcher.java b/sonic-server-folder/src/main/java/org/cloud/sonic/folder/cv/TemMatcher.java new file mode 100644 index 00000000..b718ddf3 --- /dev/null +++ b/sonic-server-folder/src/main/java/org/cloud/sonic/folder/cv/TemMatcher.java @@ -0,0 +1,79 @@ +package org.cloud.sonic.folder.cv; + +import org.bytedeco.javacpp.DoublePointer; +import org.bytedeco.opencv.opencv_core.*; +import org.cloud.sonic.folder.models.FindResult; +import org.cloud.sonic.folder.tools.FileTool; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import java.io.File; +import java.io.IOException; +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.UUID; +import java.util.concurrent.ThreadLocalRandom; + +import static org.bytedeco.opencv.global.opencv_core.*; +import static org.bytedeco.opencv.global.opencv_imgcodecs.*; +import static org.bytedeco.opencv.global.opencv_imgproc.*; + +/** + * @author ZhouYiXun + * @des 模板匹配 + * @date 2022/1/4 21:49 + */ +@Component +public class TemMatcher { + private final Logger logger = LoggerFactory.getLogger(TemMatcher.class); + @Autowired + private FileTool fileTool; + + public FindResult getTemMatchResult(File temFile, File beforeFile) throws IOException { + try { + Mat sourceColor = imread(beforeFile.getAbsolutePath()); + Mat sourceGrey = new Mat(sourceColor.size(), CV_8UC1); + cvtColor(sourceColor, sourceGrey, COLOR_BGR2GRAY); + Mat template = imread(temFile.getAbsolutePath(), IMREAD_GRAYSCALE); + Size size = new Size(sourceGrey.cols() - template.cols() + 1, sourceGrey.rows() - template.rows() + 1); + Mat result = new Mat(size, CV_32FC1); + + long start = System.currentTimeMillis(); + matchTemplate(sourceGrey, template, result, TM_CCORR_NORMED); + DoublePointer minVal = new DoublePointer(); + DoublePointer maxVal = new DoublePointer(); + Point min = new Point(); + Point max = new Point(); + minMaxLoc(result, minVal, maxVal, min, max, null); + rectangle(sourceColor, new Rect(max.x(), max.y(), template.cols(), template.rows()), randColor(), 2, 0, 0); + FindResult findResult = new FindResult(); + findResult.setTime((int) (System.currentTimeMillis() - start)); + SimpleDateFormat sf = new SimpleDateFormat("yyyyMMdd"); + File folder = new File("imageFiles" + File.separator + + sf.format(Calendar.getInstance().getTimeInMillis())); + if (!folder.exists()) { + folder.mkdirs(); + } + File fileName = new File(folder.getPath() + File.separator + + UUID.randomUUID() + ".jpg"); + imwrite(fileName.getAbsolutePath(), sourceColor); + findResult.setX(max.x() + template.cols() / 2); + findResult.setY(max.y() + template.rows() / 2); + findResult.setUrl(fileTool.upload(fileName)); + return findResult; + } finally { + temFile.delete(); + beforeFile.delete(); + } + } + + public static Scalar randColor() { + int b, g, r; + b = ThreadLocalRandom.current().nextInt(0, 255 + 1); + g = ThreadLocalRandom.current().nextInt(0, 255 + 1); + r = ThreadLocalRandom.current().nextInt(0, 255 + 1); + return new Scalar(b, g, r, 0); + } +} \ No newline at end of file diff --git a/sonic-server-folder/src/main/java/org/cloud/sonic/folder/cv/TextReader.java b/sonic-server-folder/src/main/java/org/cloud/sonic/folder/cv/TextReader.java new file mode 100644 index 00000000..843a1a47 --- /dev/null +++ b/sonic-server-folder/src/main/java/org/cloud/sonic/folder/cv/TextReader.java @@ -0,0 +1,43 @@ +package org.cloud.sonic.folder.cv; + +import org.bytedeco.javacpp.BytePointer; +import org.bytedeco.leptonica.PIX; +import org.bytedeco.tesseract.TessBaseAPI; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; + +import java.io.File; + +import static org.bytedeco.leptonica.global.lept.pixRead; + +/** + * @author ZhouYiXun + * @des 文字识别(即将弃用) + * @date 2022/1/4 21:49 + */ +@Component +public class TextReader { + private final Logger logger = LoggerFactory.getLogger(TextReader.class); + + public String getTessResult(File file, String language) throws Exception { + BytePointer outText = null; + TessBaseAPI api = new TessBaseAPI(); + String result = ""; + if (api.Init("language", language) != 0) { + logger.info("找不到语言包!"); + return result; + } + try { + PIX image = pixRead(file.getAbsolutePath()); + api.SetImage(image); + outText = api.GetUTF8Text(); + result = outText.getString(); + } finally { + file.delete(); + api.End(); + outText.deallocate(); + } + return result; + } +} diff --git a/sonic-server-folder/src/main/java/org/cloud/sonic/folder/models/FindResult.java b/sonic-server-folder/src/main/java/org/cloud/sonic/folder/models/FindResult.java new file mode 100644 index 00000000..413a5dfe --- /dev/null +++ b/sonic-server-folder/src/main/java/org/cloud/sonic/folder/models/FindResult.java @@ -0,0 +1,57 @@ +package org.cloud.sonic.folder.models; + +public class FindResult { + private int x; + private int y; + private String url; + private int time; + + public FindResult() { + x = 0; + y = 0; + url = ""; + time = 0; + } + + public int getX() { + return x; + } + + public void setX(int x) { + this.x = x; + } + + public int getY() { + return y; + } + + public void setY(int y) { + this.y = y; + } + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + + public int getTime() { + return time; + } + + public void setTime(int time) { + this.time = time; + } + + @Override + public String toString() { + return "FindResult{" + + "x=" + x + + ", y=" + y + + ", url='" + url + '\'' + + ", time=" + time + + '}'; + } +} diff --git a/sonic-server-folder/src/main/java/com/sonic/folder/tools/FileTool.java b/sonic-server-folder/src/main/java/org/cloud/sonic/folder/tools/FileTool.java similarity index 94% rename from sonic-server-folder/src/main/java/com/sonic/folder/tools/FileTool.java rename to sonic-server-folder/src/main/java/org/cloud/sonic/folder/tools/FileTool.java index 2a8eb259..1acc0ac1 100644 --- a/sonic-server-folder/src/main/java/com/sonic/folder/tools/FileTool.java +++ b/sonic-server-folder/src/main/java/org/cloud/sonic/folder/tools/FileTool.java @@ -1,149 +1,160 @@ -package com.sonic.folder.tools; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.cloud.context.config.annotation.RefreshScope; -import org.springframework.stereotype.Component; -import org.springframework.web.multipart.MultipartFile; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.RandomAccessFile; -import java.nio.file.FileAlreadyExistsException; -import java.text.SimpleDateFormat; -import java.util.Calendar; -import java.util.UUID; - -/** - * @author ZhouYiXun - * @des 合并录像工具类 - * @date 2021/8/18 20:36 - */ -@Component -@RefreshScope -public class FileTool { - private final Logger logger = LoggerFactory.getLogger(FileTool.class); - @Value("${gateway.host}") - private String host; - - /** - * @param folderName 文件夹 - * @param file - * @return java.lang.String - * @author ZhouYiXun - * @des 上传 - * @date 2021/8/18 20:41 - */ - public String upload(String folderName, MultipartFile file) throws IOException { - SimpleDateFormat sf = new SimpleDateFormat("yyyyMMdd"); - File folder = new File(folderName + File.separator - + sf.format(Calendar.getInstance().getTimeInMillis())); - if (!folder.exists()) { - folder.mkdirs(); - } - //防止文件重名 - File local = new File(folder.getPath() + File.separator + - UUID.randomUUID() + file.getOriginalFilename() - .substring(file.getOriginalFilename().lastIndexOf("."))); - try { - file.transferTo(local.getAbsoluteFile()); - } catch (FileAlreadyExistsException e) { - logger.error(e.getMessage()); - } - return host + "/api/folder/" + local.getPath().replaceAll("\\\\", "/"); - } - - /** - * @param file - * @return void - * @author ZhouYiXun - * @des 删除文件 - * @date 2021/8/18 23:27 - */ - public void deleteDir(File file) { - if (!file.exists()) { - logger.info("文件不存在"); - return; - } - File[] files = file.listFiles(); - for (File f : files) { - if (f.isDirectory()) { - deleteDir(f); - } else { - f.delete(); - } - } - file.delete(); - } - - /** - * @param uuid - * @param fileName - * @param totalCount - * @return java.io.File - * @author ZhouYiXun - * @des - * @date 2021/8/18 20:14 - */ - public String merge(String uuid, String fileName, int totalCount) { - SimpleDateFormat sf = new SimpleDateFormat("yyyyMMdd"); - File files = new File("recordFiles" + File.separator - + sf.format(Calendar.getInstance().getTimeInMillis())); - if (!files.exists()) { - files.mkdirs(); - } - //结果file - File file = new File(files.getPath() + File.separator + fileName); - try { - RandomAccessFile target = new RandomAccessFile(file, "rw"); - //获取碎片文件夹 - File uuidFolder = new File("recordFiles" + File.separator + uuid); - int waitTime = 0; - int fileCount = uuidFolder.listFiles().length; - //如果碎片还没齐全,进行等待一段时间 - while (fileCount < totalCount && waitTime < 20) { - try { - Thread.sleep(500); - } catch (InterruptedException e) { - e.printStackTrace(); - } - waitTime++; - } - for (int i = 0; i < fileCount; i++) { - //开始读取碎片文件 - String newName = fileName.substring(0, fileName.indexOf(".mp4")) + "-" + i + ".mp4"; - File patchFile = new File(uuidFolder.getPath() + File.separator + newName); - if (!patchFile.exists()) { - continue; - } - RandomAccessFile readFile = new RandomAccessFile(patchFile, "r"); - long readSize = readFile.length(); - //每次读取字节数,不用设置太大,防止内存溢出 - byte[] bytes = new byte[1024]; - int len; - while ((len = readFile.read(bytes)) != -1) { - //如果文件长度大于本次读取,直接写入 - if (readSize > len) { - target.write(bytes, 0, len); - //读完要减去本次读取len - readSize -= len; - } else { - //小于本次读取说明是余数,直接写入剩余的readSize即可 - target.write(bytes, 0, (int) readSize); - } - } - readFile.close(); - patchFile.delete(); - } - target.close(); - uuidFolder.delete(); - } catch (FileNotFoundException e) { - logger.error(e.getMessage()); - } catch (IOException e) { - logger.error(e.getMessage()); - } - return host + "/api/folder/" + file.getPath(); - } -} +package org.cloud.sonic.folder.tools; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.cloud.context.config.annotation.RefreshScope; +import org.springframework.stereotype.Component; +import org.springframework.web.multipart.MultipartFile; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.RandomAccessFile; +import java.nio.file.FileAlreadyExistsException; +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.UUID; + +/** + * @author ZhouYiXun + * @des 合并录像工具类 + * @date 2021/8/18 20:36 + */ +@Component +@RefreshScope +public class FileTool { + private final Logger logger = LoggerFactory.getLogger(FileTool.class); + @Value("${gateway.host}") + private String host; + + /** + * @param folderName 文件夹 + * @param file + * @return java.lang.String + * @author ZhouYiXun + * @des 上传 + * @date 2021/8/18 20:41 + */ + public String upload(String folderName, MultipartFile file) throws IOException { + SimpleDateFormat sf = new SimpleDateFormat("yyyyMMdd"); + File folder = new File(folderName + File.separator + + sf.format(Calendar.getInstance().getTimeInMillis())); + if (!folder.exists()) { + folder.mkdirs(); + } + //防止文件重名 + File local = new File(folder.getPath() + File.separator + + UUID.randomUUID() + file.getOriginalFilename() + .substring(file.getOriginalFilename().lastIndexOf("."))); + try { + file.transferTo(local.getAbsoluteFile()); + } catch (FileAlreadyExistsException e) { + logger.error(e.getMessage()); + } + return host + "/api/folder/" + local.getPath().replaceAll("\\\\", "/"); + } + + /** + * @param file 文件夹 + * @return java.lang.String + * @author ZhouYiXun + * @des 上传 + * @date 2021/8/18 20:41 + */ + public String upload(File file) throws IOException { + return host + "/api/folder/" + file.getPath().replaceAll("\\\\", "/"); + } + + /** + * @param file + * @return void + * @author ZhouYiXun + * @des 删除文件 + * @date 2021/8/18 23:27 + */ + public void deleteDir(File file) { + if (!file.exists()) { + logger.info("文件不存在"); + return; + } + File[] files = file.listFiles(); + for (File f : files) { + if (f.isDirectory()) { + deleteDir(f); + } else { + f.delete(); + } + } + file.delete(); + } + + /** + * @param uuid + * @param fileName + * @param totalCount + * @return java.io.File + * @author ZhouYiXun + * @des + * @date 2021/8/18 20:14 + */ + public String merge(String uuid, String fileName, int totalCount) { + SimpleDateFormat sf = new SimpleDateFormat("yyyyMMdd"); + File files = new File("recordFiles" + File.separator + + sf.format(Calendar.getInstance().getTimeInMillis())); + if (!files.exists()) { + files.mkdirs(); + } + //结果file + File file = new File(files.getPath() + File.separator + fileName); + try { + RandomAccessFile target = new RandomAccessFile(file, "rw"); + //获取碎片文件夹 + File uuidFolder = new File("recordFiles" + File.separator + uuid); + int waitTime = 0; + int fileCount = uuidFolder.listFiles().length; + //如果碎片还没齐全,进行等待一段时间 + while (fileCount < totalCount && waitTime < 20) { + try { + Thread.sleep(500); + } catch (InterruptedException e) { + e.printStackTrace(); + } + waitTime++; + } + for (int i = 0; i < fileCount; i++) { + //开始读取碎片文件 + String newName = fileName.substring(0, fileName.indexOf(".mp4")) + "-" + i + ".mp4"; + File patchFile = new File(uuidFolder.getPath() + File.separator + newName); + if (!patchFile.exists()) { + continue; + } + RandomAccessFile readFile = new RandomAccessFile(patchFile, "r"); + long readSize = readFile.length(); + //每次读取字节数,不用设置太大,防止内存溢出 + byte[] bytes = new byte[1024]; + int len; + while ((len = readFile.read(bytes)) != -1) { + //如果文件长度大于本次读取,直接写入 + if (readSize > len) { + target.write(bytes, 0, len); + //读完要减去本次读取len + readSize -= len; + } else { + //小于本次读取说明是余数,直接写入剩余的readSize即可 + target.write(bytes, 0, (int) readSize); + } + } + readFile.close(); + patchFile.delete(); + } + target.close(); + uuidFolder.delete(); + } catch (FileNotFoundException e) { + logger.error(e.getMessage()); + } catch (IOException e) { + logger.error(e.getMessage()); + } + return host + "/api/folder/" + file.getPath(); + } +} diff --git a/sonic-server-gateway/pom.xml b/sonic-server-gateway/pom.xml index ffc49d87..734651a6 100644 --- a/sonic-server-gateway/pom.xml +++ b/sonic-server-gateway/pom.xml @@ -4,13 +4,13 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> sonic-server - com.sonic + org.cloud.sonic 1.0.0 4.0.0 sonic-server-gateway - v1.2.0-release + v1.3.0-beta2 jar @@ -37,7 +37,7 @@ - com.sonic + org.cloud.sonic sonic-server-common 1.1.0 @@ -49,23 +49,23 @@ - - - - - org.springframework.boot - spring-boot-maven-plugin - - true - - - - com.spotify - docker-maven-plugin - - true - - - - + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/sonic-server-gateway/src/main/java/com/sonic/gateway/GatewayApplication.java b/sonic-server-gateway/src/main/java/org/cloud/sonic/gateway/GatewayApplication.java similarity index 72% rename from sonic-server-gateway/src/main/java/com/sonic/gateway/GatewayApplication.java rename to sonic-server-gateway/src/main/java/org/cloud/sonic/gateway/GatewayApplication.java index 07a27e93..16b285d0 100644 --- a/sonic-server-gateway/src/main/java/com/sonic/gateway/GatewayApplication.java +++ b/sonic-server-gateway/src/main/java/org/cloud/sonic/gateway/GatewayApplication.java @@ -1,13 +1,13 @@ -package com.sonic.gateway; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.cloud.netflix.eureka.EnableEurekaClient; - -@SpringBootApplication(scanBasePackages = {"com/sonic/gateway", "com/sonic/common/tools"}) -@EnableEurekaClient -public class GatewayApplication { - public static void main(String[] args) { - SpringApplication.run(GatewayApplication.class, args); - } +package org.cloud.sonic.gateway; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.netflix.eureka.EnableEurekaClient; + +@SpringBootApplication(scanBasePackages = {"org/cloud/sonic/gateway", "org/cloud/sonic/common/tools"}) +@EnableEurekaClient +public class GatewayApplication { + public static void main(String[] args) { + SpringApplication.run(GatewayApplication.class, args); + } } \ No newline at end of file diff --git a/sonic-server-gateway/src/main/java/com/sonic/gateway/config/AuthFilter.java b/sonic-server-gateway/src/main/java/org/cloud/sonic/gateway/config/AuthFilter.java similarity index 90% rename from sonic-server-gateway/src/main/java/com/sonic/gateway/config/AuthFilter.java rename to sonic-server-gateway/src/main/java/org/cloud/sonic/gateway/config/AuthFilter.java index 20d10dcd..b83ed628 100644 --- a/sonic-server-gateway/src/main/java/com/sonic/gateway/config/AuthFilter.java +++ b/sonic-server-gateway/src/main/java/org/cloud/sonic/gateway/config/AuthFilter.java @@ -1,61 +1,61 @@ -package com.sonic.gateway.config; - -import com.alibaba.fastjson.JSONObject; -import com.sonic.common.http.RespEnum; -import com.sonic.common.http.RespModel; -import com.sonic.common.tools.JWTTokenTool; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.cloud.context.config.annotation.RefreshScope; -import org.springframework.cloud.gateway.filter.GatewayFilterChain; -import org.springframework.cloud.gateway.filter.GlobalFilter; -import org.springframework.core.Ordered; -import org.springframework.core.io.buffer.DataBuffer; -import org.springframework.http.HttpStatus; -import org.springframework.http.server.reactive.ServerHttpResponse; -import org.springframework.stereotype.Component; -import org.springframework.web.server.ServerWebExchange; -import reactor.core.publisher.Mono; - -import java.nio.charset.StandardCharsets; -import java.util.List; - -@Component -public class AuthFilter implements GlobalFilter, Ordered { - @Value("${filter.white-list}") - private List whiteList; - @Autowired - private JWTTokenTool jwtTokenTool; - - @Override - public Mono filter(ServerWebExchange exchange, GatewayFilterChain chain) { - for (String white : whiteList) { - if (exchange.getRequest().getURI().toString().contains(white)) { - return chain.filter(exchange); - } - } - String token = exchange.getRequest().getHeaders().getFirst("SonicToken"); - ServerHttpResponse response = exchange.getResponse(); - response.getHeaders().add("Content-Type", "text/plain;charset=UTF-8"); - DataBuffer buffer = sendResp(response); - if (token == null) { - return response.writeWith(Mono.just(buffer)); - } - // 验证 token - if (!jwtTokenTool.verify(token)) { - return response.writeWith(Mono.just(buffer)); - } - return chain.filter(exchange); - } - - @Override - public int getOrder() { - return -100; - } - - private DataBuffer sendResp(ServerHttpResponse response) { - JSONObject result = (JSONObject) JSONObject.toJSON(new RespModel(RespEnum.UNAUTHORIZED)); - DataBuffer buffer = response.bufferFactory().wrap(result.toJSONString().getBytes(StandardCharsets.UTF_8)); - return buffer; - } +package org.cloud.sonic.gateway.config; + +import com.alibaba.fastjson.JSONObject; +import org.cloud.sonic.common.http.RespEnum; +import org.cloud.sonic.common.http.RespModel; +import org.cloud.sonic.common.tools.JWTTokenTool; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.cloud.context.config.annotation.RefreshScope; +import org.springframework.cloud.gateway.filter.GatewayFilterChain; +import org.springframework.cloud.gateway.filter.GlobalFilter; +import org.springframework.core.Ordered; +import org.springframework.core.io.buffer.DataBuffer; +import org.springframework.http.HttpStatus; +import org.springframework.http.server.reactive.ServerHttpResponse; +import org.springframework.stereotype.Component; +import org.springframework.web.server.ServerWebExchange; +import reactor.core.publisher.Mono; + +import java.nio.charset.StandardCharsets; +import java.util.List; + +@Component +public class AuthFilter implements GlobalFilter, Ordered { + @Value("${filter.white-list}") + private List whiteList; + @Autowired + private JWTTokenTool jwtTokenTool; + + @Override + public Mono filter(ServerWebExchange exchange, GatewayFilterChain chain) { + for (String white : whiteList) { + if (exchange.getRequest().getURI().toString().contains(white)) { + return chain.filter(exchange); + } + } + String token = exchange.getRequest().getHeaders().getFirst("SonicToken"); + ServerHttpResponse response = exchange.getResponse(); + response.getHeaders().add("Content-Type", "text/plain;charset=UTF-8"); + DataBuffer buffer = sendResp(response); + if (token == null) { + return response.writeWith(Mono.just(buffer)); + } + // 验证 token + if (!jwtTokenTool.verify(token)) { + return response.writeWith(Mono.just(buffer)); + } + return chain.filter(exchange); + } + + @Override + public int getOrder() { + return -100; + } + + private DataBuffer sendResp(ServerHttpResponse response) { + JSONObject result = (JSONObject) JSONObject.toJSON(new RespModel(RespEnum.UNAUTHORIZED)); + DataBuffer buffer = response.bufferFactory().wrap(result.toJSONString().getBytes(StandardCharsets.UTF_8)); + return buffer; + } } \ No newline at end of file diff --git a/sonic-server-gateway/src/main/java/com/sonic/gateway/config/CORSConfig.java b/sonic-server-gateway/src/main/java/org/cloud/sonic/gateway/config/CORSConfig.java similarity index 94% rename from sonic-server-gateway/src/main/java/com/sonic/gateway/config/CORSConfig.java rename to sonic-server-gateway/src/main/java/org/cloud/sonic/gateway/config/CORSConfig.java index 73667959..d52e6c9b 100644 --- a/sonic-server-gateway/src/main/java/com/sonic/gateway/config/CORSConfig.java +++ b/sonic-server-gateway/src/main/java/org/cloud/sonic/gateway/config/CORSConfig.java @@ -1,23 +1,23 @@ -package com.sonic.gateway.config; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.web.cors.CorsConfiguration; -import org.springframework.web.cors.reactive.CorsWebFilter; -import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource; -import org.springframework.web.util.pattern.PathPatternParser; - -@Configuration -public class CORSConfig { - @Bean - public CorsWebFilter corsWebFilter() { - CorsConfiguration config = new CorsConfiguration(); - config.setAllowCredentials(true); - config.addAllowedOrigin("*"); - config.addAllowedHeader("*"); - config.addAllowedMethod("*"); - UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(new PathPatternParser()); - source.registerCorsConfiguration("/**", config); - return new CorsWebFilter(source); - } +package org.cloud.sonic.gateway.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.cors.CorsConfiguration; +import org.springframework.web.cors.reactive.CorsWebFilter; +import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource; +import org.springframework.web.util.pattern.PathPatternParser; + +@Configuration +public class CORSConfig { + @Bean + public CorsWebFilter corsWebFilter() { + CorsConfiguration config = new CorsConfiguration(); + config.setAllowCredentials(true); + config.addAllowedOrigin("*"); + config.addAllowedHeader("*"); + config.addAllowedMethod("*"); + UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(new PathPatternParser()); + source.registerCorsConfiguration("/**", config); + return new CorsWebFilter(source); + } } \ No newline at end of file diff --git a/sonic-server-gateway/src/main/java/com/sonic/gateway/config/SwaggerProvider.java b/sonic-server-gateway/src/main/java/org/cloud/sonic/gateway/config/SwaggerProvider.java similarity index 94% rename from sonic-server-gateway/src/main/java/com/sonic/gateway/config/SwaggerProvider.java rename to sonic-server-gateway/src/main/java/org/cloud/sonic/gateway/config/SwaggerProvider.java index 6a7146dc..229653a9 100644 --- a/sonic-server-gateway/src/main/java/com/sonic/gateway/config/SwaggerProvider.java +++ b/sonic-server-gateway/src/main/java/org/cloud/sonic/gateway/config/SwaggerProvider.java @@ -1,32 +1,32 @@ -package com.sonic.gateway.config; - -import org.springframework.context.annotation.Primary; -import org.springframework.stereotype.Component; -import springfox.documentation.swagger.web.SwaggerResource; -import springfox.documentation.swagger.web.SwaggerResourcesProvider; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -@Component -@Primary -public class SwaggerProvider implements SwaggerResourcesProvider { - - @Override - public List get() { - List resources = new ArrayList<>(); - List instanceList = Arrays.asList( - "sonic-server-controller", - "sonic-server-folder","sonic-server-task"); - instanceList.forEach(instance -> { - String url = "/api/" + instance.substring( - instance.lastIndexOf("-") + 1) + "/v2/api-docs"; - SwaggerResource swaggerResource = new SwaggerResource(); - swaggerResource.setUrl(url); - swaggerResource.setName(instance); - resources.add(swaggerResource); - }); - return resources; - } -} +package org.cloud.sonic.gateway.config; + +import org.springframework.context.annotation.Primary; +import org.springframework.stereotype.Component; +import springfox.documentation.swagger.web.SwaggerResource; +import springfox.documentation.swagger.web.SwaggerResourcesProvider; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +@Component +@Primary +public class SwaggerProvider implements SwaggerResourcesProvider { + + @Override + public List get() { + List resources = new ArrayList<>(); + List instanceList = Arrays.asList( + "sonic-server-controller", + "sonic-server-folder","sonic-server-task"); + instanceList.forEach(instance -> { + String url = "/api/" + instance.substring( + instance.lastIndexOf("-") + 1) + "/v2/api-docs"; + SwaggerResource swaggerResource = new SwaggerResource(); + swaggerResource.setUrl(url); + swaggerResource.setName(instance); + resources.add(swaggerResource); + }); + return resources; + } +} diff --git a/sonic-server-gateway/src/main/java/com/sonic/gateway/controller/SwaggerController.java b/sonic-server-gateway/src/main/java/org/cloud/sonic/gateway/controller/SwaggerController.java similarity index 95% rename from sonic-server-gateway/src/main/java/com/sonic/gateway/controller/SwaggerController.java rename to sonic-server-gateway/src/main/java/org/cloud/sonic/gateway/controller/SwaggerController.java index 03dba1f2..0a3b2b3c 100644 --- a/sonic-server-gateway/src/main/java/com/sonic/gateway/controller/SwaggerController.java +++ b/sonic-server-gateway/src/main/java/org/cloud/sonic/gateway/controller/SwaggerController.java @@ -1,46 +1,46 @@ -package com.sonic.gateway.controller; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RestController; -import reactor.core.publisher.Mono; -import springfox.documentation.swagger.web.*; - -import java.util.Optional; - -@RestController -public class SwaggerController { - - @Autowired(required = false) - private SecurityConfiguration securityConfiguration; - - @Autowired(required = false) - private UiConfiguration uiConfiguration; - - private final SwaggerResourcesProvider swaggerResources; - - @Autowired - public SwaggerController(SwaggerResourcesProvider swaggerResources) { - this.swaggerResources = swaggerResources; - } - - - @GetMapping("/swagger-resources/configuration/security") - public Mono> securityConfiguration() { - return Mono.just(new ResponseEntity<>( - Optional.ofNullable(securityConfiguration).orElse(SecurityConfigurationBuilder.builder().build()), HttpStatus.OK)); - } - - @GetMapping("/swagger-resources/configuration/ui") - public Mono> uiConfiguration() { - return Mono.just(new ResponseEntity<>( - Optional.ofNullable(uiConfiguration).orElse(UiConfigurationBuilder.builder().build()), HttpStatus.OK)); - } - - @GetMapping("/swagger-resources") - public Mono swaggerResources() { - return Mono.just((new ResponseEntity<>(swaggerResources.get(), HttpStatus.OK))); - } +package org.cloud.sonic.gateway.controller; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; +import reactor.core.publisher.Mono; +import springfox.documentation.swagger.web.*; + +import java.util.Optional; + +@RestController +public class SwaggerController { + + @Autowired(required = false) + private SecurityConfiguration securityConfiguration; + + @Autowired(required = false) + private UiConfiguration uiConfiguration; + + private final SwaggerResourcesProvider swaggerResources; + + @Autowired + public SwaggerController(SwaggerResourcesProvider swaggerResources) { + this.swaggerResources = swaggerResources; + } + + + @GetMapping("/swagger-resources/configuration/security") + public Mono> securityConfiguration() { + return Mono.just(new ResponseEntity<>( + Optional.ofNullable(securityConfiguration).orElse(SecurityConfigurationBuilder.builder().build()), HttpStatus.OK)); + } + + @GetMapping("/swagger-resources/configuration/ui") + public Mono> uiConfiguration() { + return Mono.just(new ResponseEntity<>( + Optional.ofNullable(uiConfiguration).orElse(UiConfigurationBuilder.builder().build()), HttpStatus.OK)); + } + + @GetMapping("/swagger-resources") + public Mono swaggerResources() { + return Mono.just((new ResponseEntity<>(swaggerResources.get(), HttpStatus.OK))); + } } \ No newline at end of file diff --git a/sonic-server-task/pom.xml b/sonic-server-task/pom.xml index d627ee03..c8b3bbe6 100644 --- a/sonic-server-task/pom.xml +++ b/sonic-server-task/pom.xml @@ -4,13 +4,13 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> sonic-server - com.sonic + org.cloud.sonic 1.0.0 4.0.0 sonic-server-task - v1.2.0-release + v1.3.0-beta2 jar @@ -29,11 +29,6 @@ org.springframework.boot spring-boot-starter-quartz - - - org.springframework.boot - spring-boot-starter-data-jpa - mysql @@ -50,9 +45,48 @@ org.springframework.boot spring-boot-starter-undertow + + + com.baomidou + mybatis-plus-boot-starter + 3.4.3.4 + + + + com.gitee.sunchenbin.mybatis.actable + mybatis-enhance-actable + 1.5.0.RELEASE + + + com.baomidou + mybatis-plus-annotation + + + org.springframework + spring-context + + + org.springframework + spring-tx + + + org.mybatis.scripting + mybatis-velocity + + + org.projectlombok + lombok + + + + + commons-lang + commons-lang + 2.6 + - com.sonic + org.cloud.sonic sonic-server-common 1.1.0 @@ -64,23 +98,23 @@ - - - - - org.springframework.boot - spring-boot-maven-plugin - - true - - - - com.spotify - docker-maven-plugin - - true - - - - + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/sonic-server-task/src/main/java/com/sonic/task/dao/JobsRepository.java b/sonic-server-task/src/main/java/com/sonic/task/dao/JobsRepository.java deleted file mode 100644 index 41f10d16..00000000 --- a/sonic-server-task/src/main/java/com/sonic/task/dao/JobsRepository.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.sonic.task.dao; - -import com.sonic.task.models.Jobs; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.Pageable; -import org.springframework.data.jpa.repository.JpaRepository; - -import java.util.List; - -/** - * @author ZhouYiXun - * @des Job数据库操作 - * @date 2021/8/22 11:29 - */ -public interface JobsRepository extends JpaRepository { - Page findByProjectId(int projectId, Pageable pageable); -} diff --git a/sonic-server-task/src/main/java/com/sonic/task/models/Jobs.java b/sonic-server-task/src/main/java/com/sonic/task/models/Jobs.java deleted file mode 100644 index 19aebd62..00000000 --- a/sonic-server-task/src/main/java/com/sonic/task/models/Jobs.java +++ /dev/null @@ -1,94 +0,0 @@ -package com.sonic.task.models; - -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; - -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.validation.constraints.NotNull; -import javax.validation.constraints.Positive; - -@Entity -@ApiModel("定时任务实体") -public class Jobs { - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - @ApiModelProperty(value = "id", example = "1") - int id; - @NotNull - @ApiModelProperty(value = "定时任务名称", required = true, example = "每周三跑一次") - String name; - @Positive - @ApiModelProperty(value = "套件id", required = true, example = "123") - int suiteId; - @Positive - @ApiModelProperty(value = "项目id", required = true, example = "1") - int projectId; - @ApiModelProperty(value = "状态(1为开启,2为关闭)", example = "1") - int status; - @NotNull - @ApiModelProperty(value = "cron表达式", required = true, example = "* 30 * * * ?") - String cronExpression; - - public int getId() { - return id; - } - - public void setId(int id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public int getSuiteId() { - return suiteId; - } - - public void setSuiteId(int suiteId) { - this.suiteId = suiteId; - } - - public int getProjectId() { - return projectId; - } - - public void setProjectId(int projectId) { - this.projectId = projectId; - } - - public int getStatus() { - return status; - } - - public void setStatus(int status) { - this.status = status; - } - - public String getCronExpression() { - return cronExpression; - } - - public void setCronExpression(String cronExpression) { - this.cronExpression = cronExpression; - } - - @Override - public String toString() { - return "Jobs{" + - "id=" + id + - ", name='" + name + '\'' + - ", suiteId=" + suiteId + - ", projectId=" + projectId + - ", status=" + status + - ", cronExpression='" + cronExpression + '\'' + - '}'; - } -} \ No newline at end of file diff --git a/sonic-server-task/src/main/java/com/sonic/task/service/JobsService.java b/sonic-server-task/src/main/java/com/sonic/task/service/JobsService.java deleted file mode 100644 index 7fe1e6b7..00000000 --- a/sonic-server-task/src/main/java/com/sonic/task/service/JobsService.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.sonic.task.service; - -import com.sonic.common.exception.SonicException; -import com.sonic.common.http.RespModel; -import com.sonic.task.models.Jobs; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.Pageable; - -/** - * @author ZhouYiXun - * @des 定时任务逻辑层 - * @date 2021/8/22 11:20 - */ -public interface JobsService { - RespModel save(Jobs jobs) throws SonicException; - - RespModel updateStatus(int id, int type); - - RespModel delete(int id); - - Page findByProjectId(int projectId, Pageable pageable); - - Jobs findById(int id); -} diff --git a/sonic-server-task/src/main/java/com/sonic/task/service/impl/JobsServiceImpl.java b/sonic-server-task/src/main/java/com/sonic/task/service/impl/JobsServiceImpl.java deleted file mode 100644 index f078ebe0..00000000 --- a/sonic-server-task/src/main/java/com/sonic/task/service/impl/JobsServiceImpl.java +++ /dev/null @@ -1,110 +0,0 @@ -package com.sonic.task.service.impl; - -import com.sonic.common.http.RespEnum; -import com.sonic.common.http.RespModel; -import com.sonic.task.dao.JobsRepository; -import com.sonic.common.exception.SonicException; -import com.sonic.task.models.Jobs; -import com.sonic.task.models.interfaces.JobStatus; -import com.sonic.task.quartz.QuartzHandler; -import com.sonic.task.service.JobsService; -import org.quartz.CronTrigger; -import org.quartz.SchedulerException; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.Pageable; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -/** - * @author ZhouYiXun - * @des 定时任务逻辑层实现 - * @date 2021/8/22 11:22 - */ -@Service -public class JobsServiceImpl implements JobsService { - @Autowired - private QuartzHandler quartzHandler; - @Autowired - private JobsRepository jobsRepository; - - @Override - @Transactional(rollbackFor = SonicException.class) - public RespModel save(Jobs jobs) throws SonicException { - jobs.setStatus(JobStatus.ENABLE); - jobsRepository.save(jobs); - CronTrigger trigger = quartzHandler.getTrigger(jobs); - try { - if (trigger != null) { - quartzHandler.updateScheduleJob(jobs); - } else { - quartzHandler.createScheduleJob(jobs); - } - return new RespModel(RespEnum.HANDLE_OK); - } catch (RuntimeException | SchedulerException e) { - e.printStackTrace(); - throw new SonicException("操作失败!请检查cron表达式是否无误!"); - } - } - - @Override - public RespModel updateStatus(int id, int type) { - if (jobsRepository.existsById(id)) { - try { - Jobs jobs = jobsRepository.findById(id).get(); - switch (type) { - case JobStatus.DISABLE: - quartzHandler.pauseScheduleJob(jobs); - jobs.setStatus(JobStatus.DISABLE); - jobsRepository.save(jobs); - return new RespModel(2000, "关闭成功!"); - case JobStatus.ENABLE: - quartzHandler.resumeScheduleJob(jobs); - jobs.setStatus(JobStatus.ENABLE); - jobsRepository.save(jobs); - return new RespModel(2000, "开启成功!"); - case JobStatus.ONCE: - quartzHandler.runScheduleJob(jobs); - return new RespModel(2000, "开始运行!"); - default: - return new RespModel(3000, "参数有误!"); - } - } catch (RuntimeException | SchedulerException e) { - e.printStackTrace(); - return new RespModel(3000, "操作失败!"); - } - } else { - return new RespModel(RespEnum.ID_NOT_FOUND); - } - } - - @Override - public RespModel delete(int id) { - if (jobsRepository.existsById(id)) { - Jobs jobs = jobsRepository.findById(id).get(); - try { - quartzHandler.deleteScheduleJob(jobs); - } catch (Exception e) { - return new RespModel(RespEnum.DELETE_ERROR); - } - jobsRepository.deleteById(id); - return new RespModel(RespEnum.DELETE_OK); - } else { - return new RespModel(RespEnum.ID_NOT_FOUND); - } - } - - @Override - public Page findByProjectId(int projectId, Pageable pageable) { - return jobsRepository.findByProjectId(projectId, pageable); - } - - @Override - public Jobs findById(int id) { - if (jobsRepository.existsById(id)) { - return jobsRepository.findById(id).get(); - } else { - return null; - } - } -} diff --git a/sonic-server-task/src/main/java/com/sonic/task/TaskApplication.java b/sonic-server-task/src/main/java/org/cloud/sonic/task/TaskApplication.java similarity index 53% rename from sonic-server-task/src/main/java/com/sonic/task/TaskApplication.java rename to sonic-server-task/src/main/java/org/cloud/sonic/task/TaskApplication.java index 70f09352..11353705 100644 --- a/sonic-server-task/src/main/java/com/sonic/task/TaskApplication.java +++ b/sonic-server-task/src/main/java/org/cloud/sonic/task/TaskApplication.java @@ -1,17 +1,28 @@ -package com.sonic.task; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.cloud.netflix.eureka.EnableEurekaClient; -import org.springframework.cloud.openfeign.EnableFeignClients; -import org.springframework.scheduling.annotation.EnableScheduling; - -@SpringBootApplication(scanBasePackages = {"com/sonic/task", "com/sonic/common"}) -@EnableEurekaClient -@EnableFeignClients -@EnableScheduling -public class TaskApplication { - public static void main(String[] args) { - SpringApplication.run(TaskApplication.class, args); - } -} +package org.cloud.sonic.task; + +import org.mybatis.spring.annotation.MapperScan; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.netflix.eureka.EnableEurekaClient; +import org.springframework.cloud.openfeign.EnableFeignClients; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.scheduling.annotation.EnableScheduling; + +@SpringBootApplication +@MapperScan(basePackages = { + "org.cloud.sonic.task.mapper", + "com.gitee.sunchenbin.mybatis.actable.dao.*" +}) +@ComponentScan(basePackages = { + "org.cloud.sonic.task.*", + "com.gitee.sunchenbin.mybatis.actable.manager.*", + "org.cloud.sonic.common.*" +}) +@EnableEurekaClient +@EnableFeignClients +@EnableScheduling +public class TaskApplication { + public static void main(String[] args) { + SpringApplication.run(TaskApplication.class, args); + } +} diff --git a/sonic-server-task/src/main/java/org/cloud/sonic/task/config/mybatis/MyBatisPlusConfig.java b/sonic-server-task/src/main/java/org/cloud/sonic/task/config/mybatis/MyBatisPlusConfig.java new file mode 100644 index 00000000..6c8bc2df --- /dev/null +++ b/sonic-server-task/src/main/java/org/cloud/sonic/task/config/mybatis/MyBatisPlusConfig.java @@ -0,0 +1,26 @@ +package org.cloud.sonic.task.config.mybatis; + +import com.baomidou.mybatisplus.annotation.DbType; +import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor; +import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.transaction.annotation.EnableTransactionManagement; + +/** + * mybatis-plus 分页插件 + * 参考:https://baomidou.com/pages/8f40ae/ + * + * @author JayWenStar + */ +@Configuration +@EnableTransactionManagement +public class MyBatisPlusConfig { + + @Bean + public MybatisPlusInterceptor mybatisPlusInterceptor() { + MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor(); + interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL)); + return interceptor; + } +} diff --git a/sonic-server-task/src/main/java/com/sonic/task/controller/JobsController.java b/sonic-server-task/src/main/java/org/cloud/sonic/task/controller/JobsController.java similarity index 65% rename from sonic-server-task/src/main/java/com/sonic/task/controller/JobsController.java rename to sonic-server-task/src/main/java/org/cloud/sonic/task/controller/JobsController.java index be108971..6fef1cad 100644 --- a/sonic-server-task/src/main/java/com/sonic/task/controller/JobsController.java +++ b/sonic-server-task/src/main/java/org/cloud/sonic/task/controller/JobsController.java @@ -1,86 +1,89 @@ -package com.sonic.task.controller; - -import com.sonic.common.config.WebAspect; -import com.sonic.common.exception.SonicException; -import com.sonic.common.http.RespEnum; -import com.sonic.common.http.RespModel; -import com.sonic.task.models.Jobs; -import com.sonic.task.service.JobsService; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiImplicitParam; -import io.swagger.annotations.ApiImplicitParams; -import io.swagger.annotations.ApiOperation; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.PageRequest; -import org.springframework.data.domain.Pageable; -import org.springframework.data.domain.Sort; -import org.springframework.validation.annotation.Validated; -import org.springframework.web.bind.annotation.*; - -/** - * @author ZhouYiXun - * @des 定时任务控制器 - * @date 2021/8/22 17:58 - */ -@Api(tags = "定时任务") -@RestController -@RequestMapping("/jobs") -public class JobsController { - @Autowired - private JobsService jobsService; - - @WebAspect - @ApiOperation(value = "更新定时任务信息", notes = "新增或更新定时任务的信息") - @PutMapping - public RespModel save(@Validated @RequestBody Jobs jobs) throws SonicException { - return jobsService.save(jobs); - } - - @WebAspect - @ApiOperation(value = "更改定时任务状态", notes = "更改定时任务的状态") - @ApiImplicitParams(value = { - @ApiImplicitParam(name = "id", value = "定时任务id", dataTypeClass = Integer.class), - @ApiImplicitParam(name = "type", value = "状态类型", dataTypeClass = Integer.class), - }) - @GetMapping("/updateStatus") - public RespModel updateStatus(@RequestParam(name = "id") int id, @RequestParam(name = "type") int type) { - return jobsService.updateStatus(id, type); - } - - @WebAspect - @ApiOperation(value = "删除定时任务", notes = "删除对应id的定时任务") - @ApiImplicitParam(name = "id", value = "定时任务id", dataTypeClass = Integer.class) - @DeleteMapping - public RespModel delete(@RequestParam(name = "id") int id) { - return jobsService.delete(id); - } - - @WebAspect - @ApiOperation(value = "查询定时任务列表", notes = "查找对应项目id的定时任务列表") - @ApiImplicitParams(value = { - @ApiImplicitParam(name = "projectId", value = "项目id", dataTypeClass = Integer.class), - @ApiImplicitParam(name = "page", value = "页码", dataTypeClass = Integer.class), - @ApiImplicitParam(name = "pageSize", value = "页数据大小", dataTypeClass = Integer.class) - }) - @GetMapping("/list") - public RespModel> findByProjectId(@RequestParam(name = "projectId") int projectId - , @RequestParam(name = "page") int page - , @RequestParam(name = "pageSize") int pageSize) { - Pageable pageable = PageRequest.of(page - 1, pageSize, Sort.by(Sort.Direction.DESC, "id")); - return new RespModel(RespEnum.SEARCH_OK, jobsService.findByProjectId(projectId, pageable)); - } - - @WebAspect - @ApiOperation(value = "查询定时任务详细信息", notes = "查找对应id的定时任务详细信息") - @ApiImplicitParam(name = "id", value = "定时任务id", dataTypeClass = Integer.class) - @GetMapping - public RespModel findById(@RequestParam(name = "id") int id) { - Jobs jobs = jobsService.findById(id); - if (jobs != null) { - return new RespModel(RespEnum.SEARCH_OK, jobs); - } else { - return new RespModel(RespEnum.ID_NOT_FOUND); - } - } -} +package org.cloud.sonic.task.controller; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import org.cloud.sonic.common.config.WebAspect; +import org.cloud.sonic.common.exception.SonicException; +import org.cloud.sonic.common.http.RespEnum; +import org.cloud.sonic.common.http.RespModel; +import org.cloud.sonic.task.models.base.CommentPage; +import org.cloud.sonic.task.models.domain.Jobs; +import org.cloud.sonic.task.models.dto.JobsDTO; +import org.cloud.sonic.task.service.JobsService; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiImplicitParam; +import io.swagger.annotations.ApiImplicitParams; +import io.swagger.annotations.ApiOperation; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.*; + +/** + * @author ZhouYiXun + * @des 定时任务控制器 + * @date 2021/8/22 17:58 + */ +@Api(tags = "定时任务") +@RestController +@RequestMapping("/jobs") +public class JobsController { + + @Autowired + private JobsService jobsService; + + @WebAspect + @ApiOperation(value = "更新定时任务信息", notes = "新增或更新定时任务的信息") + @PutMapping + public RespModel save(@Validated @RequestBody JobsDTO jobsDTO) throws SonicException { + return jobsService.saveJobs(jobsDTO.convertTo()); + } + + @WebAspect + @ApiOperation(value = "更改定时任务状态", notes = "更改定时任务的状态") + @ApiImplicitParams(value = { + @ApiImplicitParam(name = "id", value = "定时任务id", dataTypeClass = Integer.class), + @ApiImplicitParam(name = "type", value = "状态类型", dataTypeClass = Integer.class), + }) + @GetMapping("/updateStatus") + public RespModel updateStatus(@RequestParam(name = "id") int id, @RequestParam(name = "type") int type) { + return jobsService.updateStatus(id, type); + } + + @WebAspect + @ApiOperation(value = "删除定时任务", notes = "删除对应id的定时任务") + @ApiImplicitParam(name = "id", value = "定时任务id", dataTypeClass = Integer.class) + @DeleteMapping + public RespModel delete(@RequestParam(name = "id") int id) { + return jobsService.delete(id); + } + + @WebAspect + @ApiOperation(value = "查询定时任务列表", notes = "查找对应项目id的定时任务列表") + @ApiImplicitParams(value = { + @ApiImplicitParam(name = "projectId", value = "项目id", dataTypeClass = Integer.class), + @ApiImplicitParam(name = "page", value = "页码", dataTypeClass = Integer.class), + @ApiImplicitParam(name = "pageSize", value = "页数据大小", dataTypeClass = Integer.class) + }) + @GetMapping("/list") + public RespModel> findByProjectId(@RequestParam(name = "projectId") int projectId + , @RequestParam(name = "page") int page + , @RequestParam(name = "pageSize") int pageSize) { + Page pageable = new Page<>(page, pageSize); + return new RespModel<>( + RespEnum.SEARCH_OK, + CommentPage.convertFrom(jobsService.findByProjectId(projectId, pageable)) + ); + } + + @WebAspect + @ApiOperation(value = "查询定时任务详细信息", notes = "查找对应id的定时任务详细信息") + @ApiImplicitParam(name = "id", value = "定时任务id", dataTypeClass = Integer.class) + @GetMapping + public RespModel findById(@RequestParam(name = "id") int id) { + Jobs jobs = jobsService.findById(id); + if (jobs != null) { + return new RespModel<>(RespEnum.SEARCH_OK, jobs); + } else { + return new RespModel<>(RespEnum.ID_NOT_FOUND); + } + } +} diff --git a/sonic-server-task/src/main/java/com/sonic/task/feign/ControllerFeignClient.java b/sonic-server-task/src/main/java/org/cloud/sonic/task/feign/ControllerFeignClient.java similarity index 74% rename from sonic-server-task/src/main/java/com/sonic/task/feign/ControllerFeignClient.java rename to sonic-server-task/src/main/java/org/cloud/sonic/task/feign/ControllerFeignClient.java index 4756c3c8..5d10ae64 100644 --- a/sonic-server-task/src/main/java/com/sonic/task/feign/ControllerFeignClient.java +++ b/sonic-server-task/src/main/java/org/cloud/sonic/task/feign/ControllerFeignClient.java @@ -1,25 +1,22 @@ -package com.sonic.task.feign; - -import com.alibaba.fastjson.JSONObject; -import com.sonic.common.http.RespModel; -import com.sonic.task.feign.fallback.ControllerFeignClientFallBack; -import org.springframework.cloud.openfeign.FeignClient; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestParam; - -import java.util.List; - -@FeignClient(value = "sonic-server-controller", fallback = ControllerFeignClientFallBack.class) -public interface ControllerFeignClient { - @GetMapping("/testSuites/runSuite") - RespModel runSuite(@RequestParam(name = "id") int id); - - @GetMapping("/results/sendDayReport") - RespModel sendDayReport(); - - @GetMapping("/results/sendWeekReport") - RespModel sendWeekReport(); - - @GetMapping("/results/clean") - RespModel clean(@RequestParam(name = "day") int day); +package org.cloud.sonic.task.feign; + +import org.cloud.sonic.common.http.RespModel; +import org.cloud.sonic.task.feign.fallback.ControllerFeignClientFallBack; +import org.springframework.cloud.openfeign.FeignClient; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestParam; + +@FeignClient(value = "sonic-server-controller", fallback = ControllerFeignClientFallBack.class) +public interface ControllerFeignClient { + @GetMapping("/testSuites/runSuite") + RespModel runSuite(@RequestParam(name = "id") int id); + + @GetMapping("/results/sendDayReport") + RespModel sendDayReport(); + + @GetMapping("/results/sendWeekReport") + RespModel sendWeekReport(); + + @GetMapping("/results/clean") + RespModel clean(@RequestParam(name = "day") int day); } \ No newline at end of file diff --git a/sonic-server-task/src/main/java/com/sonic/task/feign/FolderFeignClient.java b/sonic-server-task/src/main/java/org/cloud/sonic/task/feign/FolderFeignClient.java similarity index 72% rename from sonic-server-task/src/main/java/com/sonic/task/feign/FolderFeignClient.java rename to sonic-server-task/src/main/java/org/cloud/sonic/task/feign/FolderFeignClient.java index 1a3be4bc..243ccc38 100644 --- a/sonic-server-task/src/main/java/com/sonic/task/feign/FolderFeignClient.java +++ b/sonic-server-task/src/main/java/org/cloud/sonic/task/feign/FolderFeignClient.java @@ -1,13 +1,13 @@ -package com.sonic.task.feign; - -import com.sonic.common.http.RespModel; -import com.sonic.task.feign.fallback.FolderFeignClientFallBack; -import org.springframework.cloud.openfeign.FeignClient; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestParam; - -@FeignClient(value = "sonic-server-folder", fallback = FolderFeignClientFallBack.class) -public interface FolderFeignClient { - @GetMapping("/files/delete") - RespModel delete(@RequestParam(name = "day") int day); -} +package org.cloud.sonic.task.feign; + +import org.cloud.sonic.common.http.RespModel; +import org.cloud.sonic.task.feign.fallback.FolderFeignClientFallBack; +import org.springframework.cloud.openfeign.FeignClient; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestParam; + +@FeignClient(value = "sonic-server-folder", fallback = FolderFeignClientFallBack.class) +public interface FolderFeignClient { + @GetMapping("/files/delete") + RespModel delete(@RequestParam(name = "day") int day); +} diff --git a/sonic-server-task/src/main/java/com/sonic/task/feign/fallback/ControllerFeignClientFallBack.java b/sonic-server-task/src/main/java/org/cloud/sonic/task/feign/fallback/ControllerFeignClientFallBack.java similarity index 69% rename from sonic-server-task/src/main/java/com/sonic/task/feign/fallback/ControllerFeignClientFallBack.java rename to sonic-server-task/src/main/java/org/cloud/sonic/task/feign/fallback/ControllerFeignClientFallBack.java index e9d31e29..7bd46891 100644 --- a/sonic-server-task/src/main/java/com/sonic/task/feign/fallback/ControllerFeignClientFallBack.java +++ b/sonic-server-task/src/main/java/org/cloud/sonic/task/feign/fallback/ControllerFeignClientFallBack.java @@ -1,33 +1,30 @@ -package com.sonic.task.feign.fallback; - -import com.alibaba.fastjson.JSONObject; -import com.sonic.common.http.RespEnum; -import com.sonic.common.http.RespModel; -import com.sonic.task.feign.ControllerFeignClient; -import org.springframework.stereotype.Component; - -import java.util.List; - -@Component -public class ControllerFeignClientFallBack implements ControllerFeignClient { - - @Override - public RespModel runSuite(int id) { - return new RespModel(RespEnum.SERVICE_NOT_FOUND); - } - - @Override - public RespModel sendDayReport() { - return new RespModel(RespEnum.SERVICE_NOT_FOUND); - } - - @Override - public RespModel sendWeekReport() { - return new RespModel(RespEnum.SERVICE_NOT_FOUND); - } - - @Override - public RespModel clean(int day) { - return new RespModel(RespEnum.SERVICE_NOT_FOUND); - } +package org.cloud.sonic.task.feign.fallback; + +import org.cloud.sonic.common.http.RespEnum; +import org.cloud.sonic.common.http.RespModel; +import org.cloud.sonic.task.feign.ControllerFeignClient; +import org.springframework.stereotype.Component; + +@Component +public class ControllerFeignClientFallBack implements ControllerFeignClient { + + @Override + public RespModel runSuite(int id) { + return new RespModel(RespEnum.SERVICE_NOT_FOUND); + } + + @Override + public RespModel sendDayReport() { + return new RespModel(RespEnum.SERVICE_NOT_FOUND); + } + + @Override + public RespModel sendWeekReport() { + return new RespModel(RespEnum.SERVICE_NOT_FOUND); + } + + @Override + public RespModel clean(int day) { + return new RespModel(RespEnum.SERVICE_NOT_FOUND); + } } \ No newline at end of file diff --git a/sonic-server-task/src/main/java/com/sonic/task/feign/fallback/FolderFeignClientFallBack.java b/sonic-server-task/src/main/java/org/cloud/sonic/task/feign/fallback/FolderFeignClientFallBack.java similarity index 57% rename from sonic-server-task/src/main/java/com/sonic/task/feign/fallback/FolderFeignClientFallBack.java rename to sonic-server-task/src/main/java/org/cloud/sonic/task/feign/fallback/FolderFeignClientFallBack.java index fc24e9d4..7179ac40 100644 --- a/sonic-server-task/src/main/java/com/sonic/task/feign/fallback/FolderFeignClientFallBack.java +++ b/sonic-server-task/src/main/java/org/cloud/sonic/task/feign/fallback/FolderFeignClientFallBack.java @@ -1,15 +1,15 @@ -package com.sonic.task.feign.fallback; - -import com.sonic.common.http.RespEnum; -import com.sonic.common.http.RespModel; -import com.sonic.task.feign.FolderFeignClient; -import org.springframework.stereotype.Component; - -@Component -public class FolderFeignClientFallBack implements FolderFeignClient { - - @Override - public RespModel delete(int day) { - return new RespModel(RespEnum.SERVICE_NOT_FOUND); - } +package org.cloud.sonic.task.feign.fallback; + +import org.cloud.sonic.common.http.RespEnum; +import org.cloud.sonic.common.http.RespModel; +import org.cloud.sonic.task.feign.FolderFeignClient; +import org.springframework.stereotype.Component; + +@Component +public class FolderFeignClientFallBack implements FolderFeignClient { + + @Override + public RespModel delete(int day) { + return new RespModel(RespEnum.SERVICE_NOT_FOUND); + } } \ No newline at end of file diff --git a/sonic-server-task/src/main/java/org/cloud/sonic/task/mapper/JobsMapper.java b/sonic-server-task/src/main/java/org/cloud/sonic/task/mapper/JobsMapper.java new file mode 100644 index 00000000..c0ed25cd --- /dev/null +++ b/sonic-server-task/src/main/java/org/cloud/sonic/task/mapper/JobsMapper.java @@ -0,0 +1,14 @@ +package org.cloud.sonic.task.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import org.cloud.sonic.task.models.domain.Jobs; +import org.apache.ibatis.annotations.Mapper; + +/** + * Mapper 接口 + * @author JayWenStar + */ +@Mapper +public interface JobsMapper extends BaseMapper { + +} diff --git a/sonic-server-task/src/main/java/org/cloud/sonic/task/models/base/CommentPage.java b/sonic-server-task/src/main/java/org/cloud/sonic/task/models/base/CommentPage.java new file mode 100644 index 00000000..927605c2 --- /dev/null +++ b/sonic-server-task/src/main/java/org/cloud/sonic/task/models/base/CommentPage.java @@ -0,0 +1,66 @@ +package org.cloud.sonic.task.models.base; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; + +/** + * 通用分页对象 + * + * @author JayWenStar + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +public class CommentPage implements Serializable { + + /** + * 页大小 + */ + private long size; + + /** + * 页内容 + */ + private List content; + + /** + * 当前页码 + */ + private long number; + + /** + * 页内容总个数 + */ + private long totalElements; + + /** + * 总页数 + */ + private long totalPages; + + public static CommentPage convertFrom(Page page) { + return new CommentPage<>( + page.getSize(), page.getRecords(), page.getCurrent() - 1, page.getTotal(), page.getPages() + ); + } + + /** + * Page的数据会被content替代 + */ + public static CommentPage convertFrom(Page page, List content) { + return new CommentPage<>( + page.getSize(), content, page.getCurrent() - 1, page.getTotal(), page.getPages() + ); + } + + + public static CommentPage emptyPage() { + return new CommentPage<>(0, new ArrayList<>(), 0, 0, 0); + } +} diff --git a/sonic-server-task/src/main/java/org/cloud/sonic/task/models/base/TypeConverter.java b/sonic-server-task/src/main/java/org/cloud/sonic/task/models/base/TypeConverter.java new file mode 100644 index 00000000..4121a976 --- /dev/null +++ b/sonic-server-task/src/main/java/org/cloud/sonic/task/models/base/TypeConverter.java @@ -0,0 +1,74 @@ +package org.cloud.sonic.task.models.base; + +import org.cloud.sonic.common.tools.BeanTool; +import org.cloud.sonic.common.tools.ReflectionTool; +import org.springframework.lang.NonNull; +import org.springframework.lang.Nullable; + +import java.lang.reflect.ParameterizedType; +import java.util.Objects; + +import static org.cloud.sonic.common.tools.BeanTool.updateProperties; + +/** + * 映射dto与domain关系 + * @param + * @param + */ + +public interface TypeConverter, TARGET> { + + /** + * Convert from target.(shallow) + * + * @param target target data + * @return converted current data + */ + @SuppressWarnings("unchecked") + @NonNull + default CURRENT convertFrom(@NonNull TARGET target) { + + updateProperties(target, this); + + return (CURRENT) this; + } + + /** + * Convert to target.(shallow) + * + * @return new target with same value(not null) + */ + @SuppressWarnings("unchecked") + default TARGET convertTo() { + // Get parameterized type + ParameterizedType currentType = parameterizedType(); + + // Assert not equal + Objects.requireNonNull(currentType, "Cannot fetch actual type because parameterized type is null"); + + Class domainClass = (Class) currentType.getActualTypeArguments()[1]; + + return BeanTool.transformFrom(this, domainClass); + } + + /** + * Update a target by current.(shallow) + * + * @param target updated target + */ + default void update(TARGET target) { + BeanTool.updateProperties(this, target); + } + + + /** + * Get parameterized type. + * + * @return parameterized type or null + */ + @Nullable + default ParameterizedType parameterizedType() { + return ReflectionTool.getParameterizedType(TypeConverter.class, this.getClass()); + } + +} diff --git a/sonic-server-task/src/main/java/org/cloud/sonic/task/models/domain/Jobs.java b/sonic-server-task/src/main/java/org/cloud/sonic/task/models/domain/Jobs.java new file mode 100644 index 00000000..bf830425 --- /dev/null +++ b/sonic-server-task/src/main/java/org/cloud/sonic/task/models/domain/Jobs.java @@ -0,0 +1,57 @@ +package org.cloud.sonic.task.models.domain; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import com.gitee.sunchenbin.mybatis.actable.annotation.*; +import com.gitee.sunchenbin.mybatis.actable.constants.MySqlCharsetConstant; +import com.gitee.sunchenbin.mybatis.actable.constants.MySqlEngineConstant; +import org.cloud.sonic.task.models.base.TypeConverter; +import org.cloud.sonic.task.models.dto.JobsDTO; +import io.swagger.annotations.ApiModel; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; + +import java.io.Serializable; + +@ApiModel(value = "Jobs对象", description = "") +@Data +@Accessors(chain = true) +@Builder +@NoArgsConstructor +@AllArgsConstructor +@TableName("jobs") +@TableComment("定时任务表") +@TableCharset(MySqlCharsetConstant.DEFAULT) +@TableEngine(MySqlEngineConstant.InnoDB) +public class Jobs implements Serializable, TypeConverter { + + @TableId(value = "id", type = IdType.AUTO) + @IsAutoIncrement + private Integer id; + + @TableField + @Column(value = "cron_expression", isNull = false, comment = "cron表达式") + private String cronExpression; + + @TableField + @Column(isNull = false, comment = "任务名称") + private String name; + + @TableField + @Column(value = "project_id", isNull = false, comment = "所属项目id") + @Index(value = "IDX_PROJECT_ID", columns = "project_id") + private Integer projectId; + + @TableField + @Column(isNull = false, comment = "任务状态 1:开启 2:关闭") + private Integer status; + + @TableField + @Column(value = "suite_id", isNull = false, comment = "测试套件id") + private Integer suiteId; +} diff --git a/sonic-server-task/src/main/java/org/cloud/sonic/task/models/dto/JobsDTO.java b/sonic-server-task/src/main/java/org/cloud/sonic/task/models/dto/JobsDTO.java new file mode 100644 index 00000000..82631366 --- /dev/null +++ b/sonic-server-task/src/main/java/org/cloud/sonic/task/models/dto/JobsDTO.java @@ -0,0 +1,46 @@ +package org.cloud.sonic.task.models.dto; + +import org.cloud.sonic.task.models.base.TypeConverter; +import org.cloud.sonic.task.models.domain.Jobs; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; + +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.Positive; +import java.io.Serializable; + +@ApiModel("定时任务DTO 实体") +@Data +@Accessors(chain = true) +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class JobsDTO implements Serializable, TypeConverter { + + @ApiModelProperty(value = "id", example = "1") + Integer id; + + @NotBlank + @ApiModelProperty(value = "定时任务名称", required = true, example = "每周三跑一次") + String name; + + @Positive + @ApiModelProperty(value = "套件id", required = true, example = "123") + Integer suiteId; + + @Positive + @ApiModelProperty(value = "项目id", required = true, example = "1") + Integer projectId; + + @ApiModelProperty(value = "状态(1为开启,2为关闭)", example = "1") + Integer status; + + @NotBlank + @ApiModelProperty(value = "cron表达式", required = true, example = "* 30 * * * ?") + String cronExpression; +} \ No newline at end of file diff --git a/sonic-server-task/src/main/java/com/sonic/task/models/interfaces/JobStatus.java b/sonic-server-task/src/main/java/org/cloud/sonic/task/models/interfaces/JobStatus.java similarity index 76% rename from sonic-server-task/src/main/java/com/sonic/task/models/interfaces/JobStatus.java rename to sonic-server-task/src/main/java/org/cloud/sonic/task/models/interfaces/JobStatus.java index a3a08dea..ffa2e007 100644 --- a/sonic-server-task/src/main/java/com/sonic/task/models/interfaces/JobStatus.java +++ b/sonic-server-task/src/main/java/org/cloud/sonic/task/models/interfaces/JobStatus.java @@ -1,12 +1,12 @@ -package com.sonic.task.models.interfaces; - -/** - * @author ZhouYiXun - * @des 定时任务状态 - * @date 2021/8/22 11:09 - */ -public interface JobStatus { - int ENABLE = 1; - int DISABLE = 2; - int ONCE = 3; -} +package org.cloud.sonic.task.models.interfaces; + +/** + * @author ZhouYiXun + * @des 定时任务状态 + * @date 2021/8/22 11:09 + */ +public interface JobStatus { + int ENABLE = 1; + int DISABLE = 2; + int ONCE = 3; +} diff --git a/sonic-server-task/src/main/java/com/sonic/task/models/interfaces/JobType.java b/sonic-server-task/src/main/java/org/cloud/sonic/task/models/interfaces/JobType.java similarity index 81% rename from sonic-server-task/src/main/java/com/sonic/task/models/interfaces/JobType.java rename to sonic-server-task/src/main/java/org/cloud/sonic/task/models/interfaces/JobType.java index d01177ef..21c8e007 100644 --- a/sonic-server-task/src/main/java/com/sonic/task/models/interfaces/JobType.java +++ b/sonic-server-task/src/main/java/org/cloud/sonic/task/models/interfaces/JobType.java @@ -1,14 +1,14 @@ -package com.sonic.task.models.interfaces; - -/** - * @author ZhouYiXun - * @des 定时任务类型 - * @date 2021/8/21 17:09 - */ -public interface JobType { - int TEST_JOB = 1; - int CLEAN_FILE_JOB = 2; - int CLEAN_RESULT_JOB = 3; - int SEND_DAY_REPORT = 4; - int SEND_WEEK_REPORT = 5; -} +package org.cloud.sonic.task.models.interfaces; + +/** + * @author ZhouYiXun + * @des 定时任务类型 + * @date 2021/8/21 17:09 + */ +public interface JobType { + int TEST_JOB = 1; + int CLEAN_FILE_JOB = 2; + int CLEAN_RESULT_JOB = 3; + int SEND_DAY_REPORT = 4; + int SEND_WEEK_REPORT = 5; +} diff --git a/sonic-server-task/src/main/java/com/sonic/task/quartz/QuartzHandler.java b/sonic-server-task/src/main/java/org/cloud/sonic/task/quartz/QuartzHandler.java similarity index 95% rename from sonic-server-task/src/main/java/com/sonic/task/quartz/QuartzHandler.java rename to sonic-server-task/src/main/java/org/cloud/sonic/task/quartz/QuartzHandler.java index f85f8d5d..b48bcec1 100644 --- a/sonic-server-task/src/main/java/com/sonic/task/quartz/QuartzHandler.java +++ b/sonic-server-task/src/main/java/org/cloud/sonic/task/quartz/QuartzHandler.java @@ -1,178 +1,178 @@ -package com.sonic.task.quartz; - -import com.sonic.task.models.Jobs; -import com.sonic.task.models.interfaces.JobType; -import org.quartz.*; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -/** - * @author ZhouYiXun - * @des quartz处理类 - * @date 2021/8/21 17:08 - */ -@Component -public class QuartzHandler { - private final Logger logger = LoggerFactory.getLogger(QuartzHandler.class); - @Autowired - private Scheduler scheduler; - - /** - * @param jobs - * @return void - * @author ZhouYiXun - * @des 创建定时任务 - * @date 2021/8/21 17:40 - */ - public void createScheduleJob(Jobs jobs) throws SchedulerException { - try { - Class jobClass = QuartzJob.class; - JobDetail jobDetail = JobBuilder.newJob(jobClass).withIdentity(jobs.getId() + "").build(); - jobDetail.getJobDataMap().put("id", jobs.getId()); - jobDetail.getJobDataMap().put("type", JobType.TEST_JOB); - CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(jobs.getCronExpression()) - .withMisfireHandlingInstructionDoNothing(); - CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(jobs.getId() + "").withSchedule(scheduleBuilder).build(); - scheduler.scheduleJob(jobDetail, trigger); - logger.info("创建定时任务成功"); - } catch (SchedulerException e) { - logger.error("创建定时任务出错:" + e.getMessage()); - throw e; - } - } - - /** - * @param jobs - * @return void - * @author ZhouYiXun - * @des 暂停定时任务 - * @date 2021/8/21 17:42 - */ - public void pauseScheduleJob(Jobs jobs) throws SchedulerException { - JobKey jobKey = JobKey.jobKey(jobs.getId() + ""); - try { - scheduler.pauseJob(jobKey); - logger.info("暂停定时任务成功"); - } catch (SchedulerException e) { - logger.error("暂停定时任务出错:" + e.getMessage()); - throw e; - } - } - - /** - * @param jobs - * @return void - * @author ZhouYiXun - * @des 重启定时任务 - * @date 2021/8/21 17:43 - */ - public void resumeScheduleJob(Jobs jobs) throws SchedulerException { - JobKey jobKey = JobKey.jobKey(jobs.getId() + ""); - try { - scheduler.resumeJob(jobKey); - logger.info("重启定时任务成功"); - } catch (SchedulerException e) { - logger.error("重启定时任务出错:" + e.getMessage()); - throw e; - } - } - - /** - * @param jobs - * @return void - * @author ZhouYiXun - * @des 执行定时任务 - * @date 2021/10/10 12:43 - */ - public void runScheduleJob(Jobs jobs) throws SchedulerException { - JobKey jobKey = JobKey.jobKey(jobs.getId() + ""); - try { - scheduler.triggerJob(jobKey); - logger.info("运行一次定时任务成功"); - } catch (SchedulerException e) { - logger.error("运行一次定时任务出错:" + e.getMessage()); - throw e; - } - } - - /** - * @param jobs - * @return void - * @author ZhouYiXun - * @des 更新定时任务 - * @date 2021/8/21 17:43 - */ - public void updateScheduleJob(Jobs jobs) throws SchedulerException { - try { - TriggerKey triggerKey = TriggerKey.triggerKey(jobs.getId() + ""); - CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey); - CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(jobs.getCronExpression()) - .withMisfireHandlingInstructionDoNothing(); - trigger = trigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(scheduleBuilder).build(); - scheduler.rescheduleJob(triggerKey, trigger); - logger.info("更新定时任务成功"); - } catch (SchedulerException e) { - logger.error("更新定时任务出错:" + e.getMessage()); - throw e; - } - } - - /** - * @param jobs - * @return void - * @author ZhouYiXun - * @des 删除定时任务 - * @date 2021/8/21 17:44 - */ - public void deleteScheduleJob(Jobs jobs) throws SchedulerException { - JobKey jobKey = JobKey.jobKey(jobs.getId() + ""); - TriggerKey triggerKey = TriggerKey.triggerKey(jobs.getId() + ""); - try { - scheduler.pauseTrigger(triggerKey); - scheduler.unscheduleJob(triggerKey); - scheduler.deleteJob(jobKey); - logger.info("删除定时任务成功"); - } catch (SchedulerException e) { - logger.error("删除定时任务出错:" + e.getMessage()); - throw e; - } - } - - public CronTrigger getTrigger(Jobs jobs) { - TriggerKey triggerKey = TriggerKey.triggerKey(jobs.getId() + ""); - CronTrigger trigger = null; - try { - trigger = (CronTrigger) scheduler.getTrigger(triggerKey); - } catch (SchedulerException e) { - e.printStackTrace(); - } - return trigger; - } - - public void createTrigger(String type, int typeCode, String cron) { - try { - TriggerKey triggerKey = TriggerKey.triggerKey(type); - CronTrigger hasTrigger = (CronTrigger) scheduler.getTrigger(triggerKey); - if (hasTrigger == null) { - Class jobClass = QuartzJob.class; - JobDetail jobDetail = JobBuilder.newJob(jobClass).withIdentity(type).build(); - jobDetail.getJobDataMap().put("type", typeCode); - CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(cron) - .withMisfireHandlingInstructionDoNothing(); - CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(type).withSchedule(scheduleBuilder).build(); - scheduler.scheduleJob(jobDetail, trigger); - logger.info("创建" + type + "系统定时任务成功"); - } else { - CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(cron) - .withMisfireHandlingInstructionDoNothing(); - hasTrigger = hasTrigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(scheduleBuilder).build(); - scheduler.rescheduleJob(triggerKey, hasTrigger); - logger.info(type + "系统定时任务已存在"); - } - } catch (SchedulerException e) { - logger.error("创建" + type + "定时任务出错:" + e.getMessage()); - } - } +package org.cloud.sonic.task.quartz; + +import org.cloud.sonic.task.models.domain.Jobs; +import org.cloud.sonic.task.models.interfaces.JobType; +import org.quartz.*; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +/** + * @author ZhouYiXun + * @des quartz处理类 + * @date 2021/8/21 17:08 + */ +@Component +public class QuartzHandler { + private final Logger logger = LoggerFactory.getLogger(QuartzHandler.class); + @Autowired + private Scheduler scheduler; + + /** + * @param jobs + * @return void + * @author ZhouYiXun + * @des 创建定时任务 + * @date 2021/8/21 17:40 + */ + public void createScheduleJob(Jobs jobs) throws SchedulerException { + try { + Class jobClass = QuartzJob.class; + JobDetail jobDetail = JobBuilder.newJob(jobClass).withIdentity(jobs.getId() + "").build(); + jobDetail.getJobDataMap().put("id", jobs.getId()); + jobDetail.getJobDataMap().put("type", JobType.TEST_JOB); + CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(jobs.getCronExpression()) + .withMisfireHandlingInstructionDoNothing(); + CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(jobs.getId() + "").withSchedule(scheduleBuilder).build(); + scheduler.scheduleJob(jobDetail, trigger); + logger.info("创建定时任务成功"); + } catch (SchedulerException e) { + logger.error("创建定时任务出错:" + e.getMessage()); + throw e; + } + } + + /** + * @param jobs + * @return void + * @author ZhouYiXun + * @des 暂停定时任务 + * @date 2021/8/21 17:42 + */ + public void pauseScheduleJob(Jobs jobs) throws SchedulerException { + JobKey jobKey = JobKey.jobKey(jobs.getId() + ""); + try { + scheduler.pauseJob(jobKey); + logger.info("暂停定时任务成功"); + } catch (SchedulerException e) { + logger.error("暂停定时任务出错:" + e.getMessage()); + throw e; + } + } + + /** + * @param jobs + * @return void + * @author ZhouYiXun + * @des 重启定时任务 + * @date 2021/8/21 17:43 + */ + public void resumeScheduleJob(Jobs jobs) throws SchedulerException { + JobKey jobKey = JobKey.jobKey(jobs.getId() + ""); + try { + scheduler.resumeJob(jobKey); + logger.info("重启定时任务成功"); + } catch (SchedulerException e) { + logger.error("重启定时任务出错:" + e.getMessage()); + throw e; + } + } + + /** + * @param jobs + * @return void + * @author ZhouYiXun + * @des 执行定时任务 + * @date 2021/10/10 12:43 + */ + public void runScheduleJob(Jobs jobs) throws SchedulerException { + JobKey jobKey = JobKey.jobKey(jobs.getId() + ""); + try { + scheduler.triggerJob(jobKey); + logger.info("运行一次定时任务成功"); + } catch (SchedulerException e) { + logger.error("运行一次定时任务出错:" + e.getMessage()); + throw e; + } + } + + /** + * @param jobs + * @return void + * @author ZhouYiXun + * @des 更新定时任务 + * @date 2021/8/21 17:43 + */ + public void updateScheduleJob(Jobs jobs) throws SchedulerException { + try { + TriggerKey triggerKey = TriggerKey.triggerKey(jobs.getId() + ""); + CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey); + CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(jobs.getCronExpression()) + .withMisfireHandlingInstructionDoNothing(); + trigger = trigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(scheduleBuilder).build(); + scheduler.rescheduleJob(triggerKey, trigger); + logger.info("更新定时任务成功"); + } catch (SchedulerException e) { + logger.error("更新定时任务出错:" + e.getMessage()); + throw e; + } + } + + /** + * @param jobs + * @return void + * @author ZhouYiXun + * @des 删除定时任务 + * @date 2021/8/21 17:44 + */ + public void deleteScheduleJob(Jobs jobs) throws SchedulerException { + JobKey jobKey = JobKey.jobKey(jobs.getId() + ""); + TriggerKey triggerKey = TriggerKey.triggerKey(jobs.getId() + ""); + try { + scheduler.pauseTrigger(triggerKey); + scheduler.unscheduleJob(triggerKey); + scheduler.deleteJob(jobKey); + logger.info("删除定时任务成功"); + } catch (SchedulerException e) { + logger.error("删除定时任务出错:" + e.getMessage()); + throw e; + } + } + + public CronTrigger getTrigger(Jobs jobs) { + TriggerKey triggerKey = TriggerKey.triggerKey(jobs.getId() + ""); + CronTrigger trigger = null; + try { + trigger = (CronTrigger) scheduler.getTrigger(triggerKey); + } catch (SchedulerException e) { + e.printStackTrace(); + } + return trigger; + } + + public void createTrigger(String type, int typeCode, String cron) { + try { + TriggerKey triggerKey = TriggerKey.triggerKey(type); + CronTrigger hasTrigger = (CronTrigger) scheduler.getTrigger(triggerKey); + if (hasTrigger == null) { + Class jobClass = QuartzJob.class; + JobDetail jobDetail = JobBuilder.newJob(jobClass).withIdentity(type).build(); + jobDetail.getJobDataMap().put("type", typeCode); + CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(cron) + .withMisfireHandlingInstructionDoNothing(); + CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(type).withSchedule(scheduleBuilder).build(); + scheduler.scheduleJob(jobDetail, trigger); + logger.info("创建" + type + "系统定时任务成功"); + } else { + CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(cron) + .withMisfireHandlingInstructionDoNothing(); + hasTrigger = hasTrigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(scheduleBuilder).build(); + scheduler.rescheduleJob(triggerKey, hasTrigger); + logger.info(type + "系统定时任务已存在"); + } + } catch (SchedulerException e) { + logger.error("创建" + type + "定时任务出错:" + e.getMessage()); + } + } } \ No newline at end of file diff --git a/sonic-server-task/src/main/java/com/sonic/task/quartz/QuartzJob.java b/sonic-server-task/src/main/java/org/cloud/sonic/task/quartz/QuartzJob.java similarity index 85% rename from sonic-server-task/src/main/java/com/sonic/task/quartz/QuartzJob.java rename to sonic-server-task/src/main/java/org/cloud/sonic/task/quartz/QuartzJob.java index 2a3a2630..b69ed16b 100644 --- a/sonic-server-task/src/main/java/com/sonic/task/quartz/QuartzJob.java +++ b/sonic-server-task/src/main/java/org/cloud/sonic/task/quartz/QuartzJob.java @@ -1,83 +1,80 @@ -package com.sonic.task.quartz; - -import com.alibaba.fastjson.JSON; -import com.alibaba.fastjson.JSONObject; -import com.sonic.common.http.RespModel; -import com.sonic.task.feign.ControllerFeignClient; -import com.sonic.task.feign.FolderFeignClient; -import com.sonic.task.models.Jobs; -import com.sonic.task.models.interfaces.JobType; -import com.sonic.task.service.JobsService; -import org.quartz.Job; -import org.quartz.JobDataMap; -import org.quartz.JobExecutionContext; -import org.quartz.JobExecutionException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.scheduling.quartz.QuartzJobBean; -import org.springframework.stereotype.Component; - -/** - * @author ZhouYiXun - * @des 任务实现类 - * @date 2021/8/21 17:44 - */ -@Component -public class QuartzJob extends QuartzJobBean implements Job { - private final Logger logger = LoggerFactory.getLogger(QuartzJob.class); - @Autowired - private JobsService jobsService; - @Autowired - private ControllerFeignClient controllerFeignClient; - @Autowired - private FolderFeignClient folderFeignClient; - @Value("${sonic.jobs.filesKeepDay}") - private int filesKeepDay; - @Value("${sonic.jobs.resultsKeepDay}") - private int resultsKeepDay; - - @Override - protected void executeInternal(JobExecutionContext jobExecutionContext) { - JobDataMap dataMap = jobExecutionContext.getJobDetail().getJobDataMap(); - int type = dataMap.getInt("type"); - switch (type) { - case JobType.TEST_JOB: { - Jobs jobs = jobsService.findById(dataMap.getInt("id")); - if (jobs != null) { - RespModel r = controllerFeignClient.runSuite(jobs.getSuiteId()); - if (r.getCode() == 3001) { - logger.info("测试套件" + jobs.getSuiteId() + " 已删除" + r); - jobsService.delete(dataMap.getInt("id")); - } else { - logger.info("定时任务开始执行:测试套件" + jobs.getSuiteId() + " " + r); - } - } else { - logger.info("定时任务id:" + dataMap.getInt("id") + "不存在!"); - } - break; - } - case JobType.CLEAN_FILE_JOB: { - RespModel r = folderFeignClient.delete(filesKeepDay); - logger.info("清理文件任务开始:" + r); - break; - } - case JobType.CLEAN_RESULT_JOB: { - RespModel r = controllerFeignClient.clean(resultsKeepDay); - logger.info("清理测试结果任务开始:" + r); - break; - } - case JobType.SEND_DAY_REPORT: { - RespModel r = controllerFeignClient.sendDayReport(); - logger.info("发送日报任务开始:" + r); - break; - } - case JobType.SEND_WEEK_REPORT: { - RespModel r = controllerFeignClient.sendWeekReport(); - logger.info("发送周报任务开始:" + r); - break; - } - } - } -} +package org.cloud.sonic.task.quartz; + +import org.cloud.sonic.common.http.RespModel; +import org.cloud.sonic.task.feign.ControllerFeignClient; +import org.cloud.sonic.task.feign.FolderFeignClient; +import org.cloud.sonic.task.models.domain.Jobs; +import org.cloud.sonic.task.models.interfaces.JobType; +import org.cloud.sonic.task.service.JobsService; +import org.quartz.Job; +import org.quartz.JobDataMap; +import org.quartz.JobExecutionContext; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.scheduling.quartz.QuartzJobBean; +import org.springframework.stereotype.Component; + +/** + * @author ZhouYiXun + * @des 任务实现类 + * @date 2021/8/21 17:44 + */ +@Component +public class QuartzJob extends QuartzJobBean implements Job { + private final Logger logger = LoggerFactory.getLogger(QuartzJob.class); + @Autowired + private JobsService jobsService; + @Autowired + private ControllerFeignClient controllerFeignClient; + @Autowired + private FolderFeignClient folderFeignClient; + @Value("${sonic.jobs.filesKeepDay}") + private int filesKeepDay; + @Value("${sonic.jobs.resultsKeepDay}") + private int resultsKeepDay; + + @Override + protected void executeInternal(JobExecutionContext jobExecutionContext) { + JobDataMap dataMap = jobExecutionContext.getJobDetail().getJobDataMap(); + int type = dataMap.getInt("type"); + switch (type) { + case JobType.TEST_JOB: { + Jobs jobs = jobsService.findById(dataMap.getInt("id")); + if (jobs != null) { + RespModel r = controllerFeignClient.runSuite(jobs.getSuiteId()); + if (r.getCode() == 3001) { + logger.info("测试套件" + jobs.getSuiteId() + " 已删除" + r); + jobsService.delete(dataMap.getInt("id")); + } else { + logger.info("定时任务开始执行:测试套件" + jobs.getSuiteId() + " " + r); + } + } else { + logger.info("定时任务id:" + dataMap.getInt("id") + "不存在!"); + } + break; + } + case JobType.CLEAN_FILE_JOB: { + RespModel r = folderFeignClient.delete(filesKeepDay); + logger.info("清理文件任务开始:" + r); + break; + } + case JobType.CLEAN_RESULT_JOB: { + RespModel r = controllerFeignClient.clean(resultsKeepDay); + logger.info("清理测试结果任务开始:" + r); + break; + } + case JobType.SEND_DAY_REPORT: { + RespModel r = controllerFeignClient.sendDayReport(); + logger.info("发送日报任务开始:" + r); + break; + } + case JobType.SEND_WEEK_REPORT: { + RespModel r = controllerFeignClient.sendWeekReport(); + logger.info("发送周报任务开始:" + r); + break; + } + } + } +} diff --git a/sonic-server-task/src/main/java/org/cloud/sonic/task/service/JobsService.java b/sonic-server-task/src/main/java/org/cloud/sonic/task/service/JobsService.java new file mode 100644 index 00000000..bbcf7c23 --- /dev/null +++ b/sonic-server-task/src/main/java/org/cloud/sonic/task/service/JobsService.java @@ -0,0 +1,24 @@ +package org.cloud.sonic.task.service; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.baomidou.mybatisplus.extension.service.IService; +import org.cloud.sonic.common.exception.SonicException; +import org.cloud.sonic.common.http.RespModel; +import org.cloud.sonic.task.models.domain.Jobs; + +/** + * @author ZhouYiXun + * @des 定时任务逻辑层 + * @date 2021/8/22 11:20 + */ +public interface JobsService extends IService { + RespModel saveJobs(Jobs jobs) throws SonicException; + + RespModel updateStatus(int id, int type); + + RespModel delete(int id); + + Page findByProjectId(int projectId, Page pageable); + + Jobs findById(int id); +} diff --git a/sonic-server-task/src/main/java/org/cloud/sonic/task/service/impl/JobsServiceImpl.java b/sonic-server-task/src/main/java/org/cloud/sonic/task/service/impl/JobsServiceImpl.java new file mode 100644 index 00000000..621dc44e --- /dev/null +++ b/sonic-server-task/src/main/java/org/cloud/sonic/task/service/impl/JobsServiceImpl.java @@ -0,0 +1,110 @@ +package org.cloud.sonic.task.service.impl; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import org.cloud.sonic.common.exception.SonicException; +import org.cloud.sonic.common.http.RespEnum; +import org.cloud.sonic.common.http.RespModel; +import org.cloud.sonic.task.mapper.JobsMapper; +import org.cloud.sonic.task.models.domain.Jobs; +import org.cloud.sonic.task.models.interfaces.JobStatus; +import org.cloud.sonic.task.quartz.QuartzHandler; +import org.cloud.sonic.task.service.JobsService; +import org.cloud.sonic.task.service.impl.base.SonicServiceImpl; +import org.quartz.CronTrigger; +import org.quartz.SchedulerException; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +/** + * @author ZhouYiXun + * @des 定时任务逻辑层实现 + * @date 2021/8/22 11:22 + */ +@Service +public class JobsServiceImpl extends SonicServiceImpl implements JobsService { + + @Autowired + private QuartzHandler quartzHandler; + @Autowired + private JobsMapper jobsMapper; + + @Override + @Transactional(rollbackFor = Exception.class) + public RespModel saveJobs(Jobs jobs) throws SonicException { + jobs.setStatus(JobStatus.ENABLE); + save(jobs); + CronTrigger trigger = quartzHandler.getTrigger(jobs); + try { + if (trigger != null) { + quartzHandler.updateScheduleJob(jobs); + } else { + quartzHandler.createScheduleJob(jobs); + } + return new RespModel<>(RespEnum.HANDLE_OK); + } catch (RuntimeException | SchedulerException e) { + e.printStackTrace(); + throw new SonicException("操作失败!请检查cron表达式是否无误!"); + } + } + + @Override + public RespModel updateStatus(int id, int type) { + if (existsById(id)) { + try { + Jobs jobs = findById(id); + switch (type) { + case JobStatus.DISABLE: + quartzHandler.pauseScheduleJob(jobs); + jobs.setStatus(JobStatus.DISABLE); + save(jobs); + return new RespModel<>(2000, "关闭成功!"); + case JobStatus.ENABLE: + quartzHandler.resumeScheduleJob(jobs); + jobs.setStatus(JobStatus.ENABLE); + save(jobs); + return new RespModel<>(2000, "开启成功!"); + case JobStatus.ONCE: + quartzHandler.runScheduleJob(jobs); + return new RespModel<>(2000, "开始运行!"); + default: + return new RespModel<>(3000, "参数有误!"); + } + } catch (RuntimeException | SchedulerException e) { + e.printStackTrace(); + return new RespModel<>(3000, "操作失败!"); + } + } else { + return new RespModel<>(RespEnum.ID_NOT_FOUND); + } + } + + @Transactional(rollbackFor = Exception.class) + @Override + public RespModel delete(int id) { + Jobs jobs = baseMapper.selectById(id); + try { + quartzHandler.deleteScheduleJob(jobs); + } catch (SchedulerException e) { + return new RespModel<>(RespEnum.DELETE_ERROR); + } + int count = baseMapper.deleteById(id); + if (count > 0) { + return new RespModel<>(RespEnum.DELETE_OK); + } + return new RespModel<>(RespEnum.ID_NOT_FOUND); + } + + @Override + public Page findByProjectId(int projectId, Page pageable) { + return lambdaQuery() + .eq(Jobs::getProjectId, projectId) + .orderByDesc(Jobs::getId) + .page(pageable); + } + + @Override + public Jobs findById(int id) { + return baseMapper.selectById(id); + } +} diff --git a/sonic-server-task/src/main/java/org/cloud/sonic/task/service/impl/base/SonicServiceImpl.java b/sonic-server-task/src/main/java/org/cloud/sonic/task/service/impl/base/SonicServiceImpl.java new file mode 100644 index 00000000..757a60c0 --- /dev/null +++ b/sonic-server-task/src/main/java/org/cloud/sonic/task/service/impl/base/SonicServiceImpl.java @@ -0,0 +1,68 @@ +package org.cloud.sonic.task.service.impl.base; + +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import org.cloud.sonic.common.exception.ServerErrorException; +import org.cloud.sonic.common.tools.ReflectionTool; +import lombok.extern.slf4j.Slf4j; + +import java.io.Serializable; +import java.lang.reflect.Field; +import java.lang.reflect.ParameterizedType; +import java.util.Objects; + +/** + * 主要是为了兼容原来jpa的一些语法 + * + * @author JayWenStar + * @date 2021/12/17 11:38 下午 + */ +@Slf4j +public class SonicServiceImpl, T> extends ServiceImpl { + + protected boolean existsById(Serializable id) { + Field idField = getIdField(getDomainClass()); + Objects.requireNonNull(idField, "对象没有 @TableId 注解标注的字段"); + return baseMapper.selectCount(new QueryWrapper().eq("id", id)) > 0; + } + + /** + * 如果id属性为空就insert,否则update + */ + @Override + public boolean save(T domain) { + try { + Field idField = getIdField(getDomainClass()); + Objects.requireNonNull(idField, "对象没有 @TableId 注解标注的字段"); + Integer id = (Integer) idField.get(domain); + // 如果id为0,则设置为null + if (id == null || id.equals(0)) { + idField.set(domain, null); + return baseMapper.insert(domain) > 0; + } + return baseMapper.updateById(domain) > 0; + } catch (IllegalAccessException e) { + throw new ServerErrorException("操作对象id属性失败"); + } + } + + @SuppressWarnings("unchecked") + private Class getDomainClass() { + ParameterizedType type = ReflectionTool.getParameterizedTypeBySuperClass(SonicServiceImpl.class, this.getClass()); + Objects.requireNonNull(type, "Cannot fetch actual type because parameterized type is null"); + return (Class) type.getActualTypeArguments()[1]; + } + + private Field getIdField(Class clazz) { + Field[] fields = clazz.getDeclaredFields(); + for (Field field : fields) { + field.setAccessible(true); + if (field.getAnnotation(TableId.class) != null) { + return field; + } + } + return null; + } +} diff --git a/sonic-server-task/src/main/java/com/sonic/task/tools/LaunchTool.java b/sonic-server-task/src/main/java/org/cloud/sonic/task/tools/LaunchTool.java similarity index 88% rename from sonic-server-task/src/main/java/com/sonic/task/tools/LaunchTool.java rename to sonic-server-task/src/main/java/org/cloud/sonic/task/tools/LaunchTool.java index 3f888d2d..e55e46ea 100644 --- a/sonic-server-task/src/main/java/com/sonic/task/tools/LaunchTool.java +++ b/sonic-server-task/src/main/java/org/cloud/sonic/task/tools/LaunchTool.java @@ -1,34 +1,34 @@ -package com.sonic.task.tools; - -import com.sonic.task.models.interfaces.JobType; -import com.sonic.task.quartz.QuartzHandler; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.boot.ApplicationArguments; -import org.springframework.boot.ApplicationRunner; -import org.springframework.stereotype.Component; - -@Component -public class LaunchTool implements ApplicationRunner { - private final Logger logger = LoggerFactory.getLogger(LaunchTool.class); - @Autowired - private QuartzHandler quartzHandler; - @Value("${sonic.jobs.fileCron}") - private String fileCron; - @Value("${sonic.jobs.resultCron}") - private String resultCron; - @Value("${sonic.jobs.dayReportCron}") - private String dayReportCron; - @Value("${sonic.jobs.weekReportCron}") - private String weekReportCron; - - @Override - public void run(ApplicationArguments args) { - quartzHandler.createTrigger("cleanFile", JobType.CLEAN_FILE_JOB, fileCron); - quartzHandler.createTrigger("cleanResult", JobType.CLEAN_RESULT_JOB, resultCron); - quartzHandler.createTrigger("sendDayReport", JobType.SEND_DAY_REPORT, dayReportCron); - quartzHandler.createTrigger("sendWeekReport", JobType.SEND_WEEK_REPORT, weekReportCron); - } -} +package org.cloud.sonic.task.tools; + +import org.cloud.sonic.task.models.interfaces.JobType; +import org.cloud.sonic.task.quartz.QuartzHandler; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.ApplicationArguments; +import org.springframework.boot.ApplicationRunner; +import org.springframework.stereotype.Component; + +@Component +public class LaunchTool implements ApplicationRunner { + private final Logger logger = LoggerFactory.getLogger(LaunchTool.class); + @Autowired + private QuartzHandler quartzHandler; + @Value("${sonic.jobs.fileCron}") + private String fileCron; + @Value("${sonic.jobs.resultCron}") + private String resultCron; + @Value("${sonic.jobs.dayReportCron}") + private String dayReportCron; + @Value("${sonic.jobs.weekReportCron}") + private String weekReportCron; + + @Override + public void run(ApplicationArguments args) { + quartzHandler.createTrigger("cleanFile", JobType.CLEAN_FILE_JOB, fileCron); + quartzHandler.createTrigger("cleanResult", JobType.CLEAN_RESULT_JOB, resultCron); + quartzHandler.createTrigger("sendDayReport", JobType.SEND_DAY_REPORT, dayReportCron); + quartzHandler.createTrigger("sendWeekReport", JobType.SEND_WEEK_REPORT, weekReportCron); + } +} diff --git a/sonic-server-task/src/main/resources/bootstrap.yml b/sonic-server-task/src/main/resources/bootstrap.yml index 54b3e9d2..c11a19c0 100644 --- a/sonic-server-task/src/main/resources/bootstrap.yml +++ b/sonic-server-task/src/main/resources/bootstrap.yml @@ -19,3 +19,12 @@ eureka: client: service-url: defaultZone: ${EUREKA_URL:http://sonic:sonic@127.0.0.1:9090/eureka/} + +# 数据库自动生成表 +actable: + model: + pack: org.cloud.sonic.task.models.domain + table: + auto: update + database: + type: mysql \ No newline at end of file diff --git a/sonic-server-task/src/main/resources/data.sql b/sonic-server-task/src/main/resources/data.sql index 9fedfd63..6476e6d0 100644 --- a/sonic-server-task/src/main/resources/data.sql +++ b/sonic-server-task/src/main/resources/data.sql @@ -1,5 +1,3 @@ -ALTER TABLE elements MODIFY COLUMN ele_value LONGTEXT; - CREATE TABLE IF NOT EXISTS QRTZ_JOB_DETAILS ( SCHED_NAME VARCHAR(120) NOT NULL, diff --git a/sonic-server-task/src/main/resources/mapping/JobsMapper.xml b/sonic-server-task/src/main/resources/mapping/JobsMapper.xml new file mode 100644 index 00000000..e2dae15f --- /dev/null +++ b/sonic-server-task/src/main/resources/mapping/JobsMapper.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/sonic-server-transport/pom.xml b/sonic-server-transport/pom.xml index 24c3fd3f..5247092c 100644 --- a/sonic-server-transport/pom.xml +++ b/sonic-server-transport/pom.xml @@ -4,13 +4,13 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> sonic-server - com.sonic + org.cloud.sonic 1.0.0 4.0.0 sonic-server-transport - v1.3.0-beta1 + v1.3.0-beta2 jar @@ -53,7 +53,7 @@ - com.sonic + org.cloud.sonic sonic-server-common 1.1.0 diff --git a/sonic-server-transport/src/main/java/com/sonic/transport/TransportApplication.java b/sonic-server-transport/src/main/java/org/cloud/sonic/transport/TransportApplication.java similarity index 73% rename from sonic-server-transport/src/main/java/com/sonic/transport/TransportApplication.java rename to sonic-server-transport/src/main/java/org/cloud/sonic/transport/TransportApplication.java index 7a80e4f7..853eb337 100644 --- a/sonic-server-transport/src/main/java/com/sonic/transport/TransportApplication.java +++ b/sonic-server-transport/src/main/java/org/cloud/sonic/transport/TransportApplication.java @@ -1,18 +1,18 @@ -package com.sonic.transport; - -import com.sonic.transport.tools.SpringTool; -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.cloud.netflix.eureka.EnableEurekaClient; -import org.springframework.cloud.openfeign.EnableFeignClients; -import org.springframework.context.annotation.Import; - -@SpringBootApplication(scanBasePackages = {"com/sonic/transport", "com/sonic/common"}) -@EnableEurekaClient -@EnableFeignClients -@Import(SpringTool.class) -public class TransportApplication { - public static void main(String[] args) { - SpringApplication.run(TransportApplication.class, args); - } +package org.cloud.sonic.transport; + +import org.cloud.sonic.transport.tools.SpringTool; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.netflix.eureka.EnableEurekaClient; +import org.springframework.cloud.openfeign.EnableFeignClients; +import org.springframework.context.annotation.Import; + +@SpringBootApplication(scanBasePackages = {"org/cloud/sonic/transport", "org/cloud/sonic/common"}) +@EnableEurekaClient +@EnableFeignClients +@Import(SpringTool.class) +public class TransportApplication { + public static void main(String[] args) { + SpringApplication.run(TransportApplication.class, args); + } } \ No newline at end of file diff --git a/sonic-server-transport/src/main/java/com/sonic/transport/controller/ExchangeController.java b/sonic-server-transport/src/main/java/org/cloud/sonic/transport/controller/ExchangeController.java similarity index 86% rename from sonic-server-transport/src/main/java/com/sonic/transport/controller/ExchangeController.java rename to sonic-server-transport/src/main/java/org/cloud/sonic/transport/controller/ExchangeController.java index 92f62f28..0273b965 100644 --- a/sonic-server-transport/src/main/java/com/sonic/transport/controller/ExchangeController.java +++ b/sonic-server-transport/src/main/java/org/cloud/sonic/transport/controller/ExchangeController.java @@ -1,50 +1,50 @@ -package com.sonic.transport.controller; - -import com.alibaba.fastjson.JSONObject; -import com.sonic.common.config.WebAspect; -import com.sonic.common.http.RespModel; -import com.sonic.transport.feign.ControllerFeignClient; -import com.sonic.transport.netty.NettyServer; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.web.bind.annotation.*; - -import java.util.LinkedHashMap; - -@RestController -@RequestMapping("/exchange") -public class ExchangeController { - @Autowired - private ControllerFeignClient controllerFeignClient; - - @WebAspect - @GetMapping("/reboot") - public RespModel reboot(@RequestParam(name = "id") int id) { - RespModel device = controllerFeignClient.findDeviceById(id); - if (device.getCode() == 2000) { - LinkedHashMap d = (LinkedHashMap) device.getData(); - RespModel agent = controllerFeignClient.findKeyById((Integer) d.get("agentId")); - if (agent.getCode() == 2000) { - JSONObject jsonObject = new JSONObject(); - jsonObject.put("msg", "reboot"); - jsonObject.put("udId", d.get("udId")); - jsonObject.put("platform", d.get("platform")); - LinkedHashMap a = (LinkedHashMap) agent.getData(); - NettyServer.getMap().get(a.get("id")).writeAndFlush(jsonObject.toJSONString()); - return new RespModel(2000, "发送成功!"); - } else { - return agent; - } - } else { - return device; - } - } - - @WebAspect - @PostMapping("/sendTestData") - public RespModel sendTestData(@RequestBody JSONObject jsonObject) { - if (jsonObject.getInteger("id") != null) { - NettyServer.getMap().get(jsonObject.getInteger("id")).writeAndFlush(jsonObject.toJSONString()); - } - return new RespModel(2000, "发送成功!"); - } -} +package org.cloud.sonic.transport.controller; + +import com.alibaba.fastjson.JSONObject; +import org.cloud.sonic.common.config.WebAspect; +import org.cloud.sonic.common.http.RespModel; +import org.cloud.sonic.transport.feign.ControllerFeignClient; +import org.cloud.sonic.transport.netty.NettyServer; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import java.util.LinkedHashMap; + +@RestController +@RequestMapping("/exchange") +public class ExchangeController { + @Autowired + private ControllerFeignClient controllerFeignClient; + + @WebAspect + @GetMapping("/reboot") + public RespModel reboot(@RequestParam(name = "id") int id) { + RespModel device = controllerFeignClient.findDeviceById(id); + if (device.getCode() == 2000) { + LinkedHashMap d = (LinkedHashMap) device.getData(); + RespModel agent = controllerFeignClient.findKeyById((Integer) d.get("agentId")); + if (agent.getCode() == 2000) { + JSONObject jsonObject = new JSONObject(); + jsonObject.put("msg", "reboot"); + jsonObject.put("udId", d.get("udId")); + jsonObject.put("platform", d.get("platform")); + LinkedHashMap a = (LinkedHashMap) agent.getData(); + NettyServer.getMap().get(a.get("id")).writeAndFlush(jsonObject.toJSONString()); + return new RespModel(2000, "发送成功!"); + } else { + return agent; + } + } else { + return device; + } + } + + @WebAspect + @PostMapping("/sendTestData") + public RespModel sendTestData(@RequestBody JSONObject jsonObject) { + if (jsonObject.getInteger("id") != null) { + NettyServer.getMap().get(jsonObject.getInteger("id")).writeAndFlush(jsonObject.toJSONString()); + } + return new RespModel(2000, "发送成功!"); + } +} diff --git a/sonic-server-transport/src/main/java/com/sonic/transport/feign/ControllerFeignClient.java b/sonic-server-transport/src/main/java/org/cloud/sonic/transport/feign/ControllerFeignClient.java similarity index 89% rename from sonic-server-transport/src/main/java/com/sonic/transport/feign/ControllerFeignClient.java rename to sonic-server-transport/src/main/java/org/cloud/sonic/transport/feign/ControllerFeignClient.java index 540e0d93..6ef42ceb 100644 --- a/sonic-server-transport/src/main/java/com/sonic/transport/feign/ControllerFeignClient.java +++ b/sonic-server-transport/src/main/java/org/cloud/sonic/transport/feign/ControllerFeignClient.java @@ -1,49 +1,49 @@ -package com.sonic.transport.feign; - -import com.alibaba.fastjson.JSONObject; -import com.sonic.common.http.RespModel; -import com.sonic.transport.feign.fallBack.ControllerFeignClientFallBack; -import org.springframework.cloud.openfeign.FeignClient; -import org.springframework.web.bind.annotation.*; - -@FeignClient(value = "sonic-server-controller", fallback = ControllerFeignClientFallBack.class) -public interface ControllerFeignClient { - @PutMapping("/devices/deviceStatus") - RespModel deviceStatus(@RequestBody JSONObject jsonObject); - - @PutMapping("/devices/updateDevicesUser") - RespModel updateUser(@RequestBody JSONObject jsonObject); - - @PutMapping("/devices/refreshDevicesTemper") - RespModel refreshDevicesTemper(@RequestBody JSONObject jsonObject); - - @PutMapping("/agents") - RespModel saveAgent(@RequestBody JSONObject agents); - - @GetMapping("/agents") - RespModel findAgentById(@RequestParam(name = "id") int id); - - @GetMapping("/agents/offLine") - RespModel offLine(@RequestParam(name = "id") int id); - - @PostMapping("/resultDetail") - RespModel saveResultDetail(@RequestBody JSONObject jsonObject); - - @PutMapping("/elapsedTime") - RespModel saveElapsed(@RequestBody JSONObject jsonObject); - - @GetMapping("/devices") - RespModel findDeviceById(@RequestParam(name = "id") int id); - - @GetMapping("/agents/auth") - RespModel auth(@RequestParam(name = "key") String key); - - @GetMapping("/agents/findKeyById") - RespModel findKeyById(@RequestParam(name = "id") int id); - - @GetMapping("/testCases/findSteps") - RespModel findSteps(@RequestParam(name = "id") int id); - - @GetMapping("/results/subResultCount") - RespModel subResultCount(@RequestParam(name = "id") int id); +package org.cloud.sonic.transport.feign; + +import com.alibaba.fastjson.JSONObject; +import org.cloud.sonic.common.http.RespModel; +import org.cloud.sonic.transport.feign.fallBack.ControllerFeignClientFallBack; +import org.springframework.cloud.openfeign.FeignClient; +import org.springframework.web.bind.annotation.*; + +@FeignClient(value = "sonic-server-controller", fallback = ControllerFeignClientFallBack.class) +public interface ControllerFeignClient { + @PutMapping("/devices/deviceStatus") + RespModel deviceStatus(@RequestBody JSONObject jsonObject); + + @PutMapping("/devices/updateDevicesUser") + RespModel updateUser(@RequestBody JSONObject jsonObject); + + @PutMapping("/devices/refreshDevicesTemper") + RespModel refreshDevicesTemper(@RequestBody JSONObject jsonObject); + + @PutMapping("/agents") + RespModel saveAgent(@RequestBody JSONObject agents); + + @GetMapping("/agents") + RespModel findAgentById(@RequestParam(name = "id") int id); + + @GetMapping("/agents/offLine") + RespModel offLine(@RequestParam(name = "id") int id); + + @PostMapping("/resultDetail") + RespModel saveResultDetail(@RequestBody JSONObject jsonObject); + + @PutMapping("/elapsedTime") + RespModel saveElapsed(@RequestBody JSONObject jsonObject); + + @GetMapping("/devices") + RespModel findDeviceById(@RequestParam(name = "id") int id); + + @GetMapping("/agents/auth") + RespModel auth(@RequestParam(name = "key") String key); + + @GetMapping("/agents/findKeyById") + RespModel findKeyById(@RequestParam(name = "id") int id); + + @GetMapping("/testCases/findSteps") + RespModel findSteps(@RequestParam(name = "id") int id); + + @GetMapping("/results/subResultCount") + RespModel subResultCount(@RequestParam(name = "id") int id); } \ No newline at end of file diff --git a/sonic-server-transport/src/main/java/com/sonic/transport/feign/fallBack/ControllerFeignClientFallBack.java b/sonic-server-transport/src/main/java/org/cloud/sonic/transport/feign/fallBack/ControllerFeignClientFallBack.java similarity index 88% rename from sonic-server-transport/src/main/java/com/sonic/transport/feign/fallBack/ControllerFeignClientFallBack.java rename to sonic-server-transport/src/main/java/org/cloud/sonic/transport/feign/fallBack/ControllerFeignClientFallBack.java index 2ca7a0ca..c3b38f47 100644 --- a/sonic-server-transport/src/main/java/com/sonic/transport/feign/fallBack/ControllerFeignClientFallBack.java +++ b/sonic-server-transport/src/main/java/org/cloud/sonic/transport/feign/fallBack/ControllerFeignClientFallBack.java @@ -1,75 +1,75 @@ -package com.sonic.transport.feign.fallBack; - -import com.alibaba.fastjson.JSONObject; -import com.sonic.common.http.RespEnum; -import com.sonic.common.http.RespModel; -import com.sonic.transport.feign.ControllerFeignClient; -import org.springframework.stereotype.Component; - -@Component -public class ControllerFeignClientFallBack implements ControllerFeignClient { - @Override - public RespModel deviceStatus(JSONObject jsonObject) { - return new RespModel(RespEnum.SERVICE_NOT_FOUND); - } - - @Override - public RespModel updateUser(JSONObject jsonObject) { - return new RespModel(RespEnum.SERVICE_NOT_FOUND); - } - - @Override - public RespModel refreshDevicesTemper(JSONObject jsonObject) { - return new RespModel(RespEnum.SERVICE_NOT_FOUND); - } - - @Override - public RespModel saveAgent(JSONObject agents) { - return new RespModel(RespEnum.SERVICE_NOT_FOUND); - } - - @Override - public RespModel findAgentById(int id) { - return new RespModel(RespEnum.SERVICE_NOT_FOUND); - } - - @Override - public RespModel offLine(int id) { - return new RespModel(RespEnum.SERVICE_NOT_FOUND); - } - - @Override - public RespModel saveResultDetail(JSONObject jsonObject) { - return new RespModel(RespEnum.SERVICE_NOT_FOUND); - } - - @Override - public RespModel saveElapsed(JSONObject jsonObject) { - return new RespModel(RespEnum.SERVICE_NOT_FOUND); - } - - @Override - public RespModel findDeviceById(int id) { - return new RespModel(RespEnum.SERVICE_NOT_FOUND); - } - - @Override - public RespModel auth(String key) { - return new RespModel(RespEnum.SERVICE_NOT_FOUND); - } - - @Override - public RespModel findKeyById(int id) { - return new RespModel(RespEnum.SERVICE_NOT_FOUND); - } - - @Override - public RespModel findSteps(int id) { - return new RespModel(RespEnum.SERVICE_NOT_FOUND); - } - - @Override - public RespModel subResultCount(int id) { - return new RespModel(RespEnum.SERVICE_NOT_FOUND); - } +package org.cloud.sonic.transport.feign.fallBack; + +import com.alibaba.fastjson.JSONObject; +import org.cloud.sonic.common.http.RespEnum; +import org.cloud.sonic.common.http.RespModel; +import org.cloud.sonic.transport.feign.ControllerFeignClient; +import org.springframework.stereotype.Component; + +@Component +public class ControllerFeignClientFallBack implements ControllerFeignClient { + @Override + public RespModel deviceStatus(JSONObject jsonObject) { + return new RespModel(RespEnum.SERVICE_NOT_FOUND); + } + + @Override + public RespModel updateUser(JSONObject jsonObject) { + return new RespModel(RespEnum.SERVICE_NOT_FOUND); + } + + @Override + public RespModel refreshDevicesTemper(JSONObject jsonObject) { + return new RespModel(RespEnum.SERVICE_NOT_FOUND); + } + + @Override + public RespModel saveAgent(JSONObject agents) { + return new RespModel(RespEnum.SERVICE_NOT_FOUND); + } + + @Override + public RespModel findAgentById(int id) { + return new RespModel(RespEnum.SERVICE_NOT_FOUND); + } + + @Override + public RespModel offLine(int id) { + return new RespModel(RespEnum.SERVICE_NOT_FOUND); + } + + @Override + public RespModel saveResultDetail(JSONObject jsonObject) { + return new RespModel(RespEnum.SERVICE_NOT_FOUND); + } + + @Override + public RespModel saveElapsed(JSONObject jsonObject) { + return new RespModel(RespEnum.SERVICE_NOT_FOUND); + } + + @Override + public RespModel findDeviceById(int id) { + return new RespModel(RespEnum.SERVICE_NOT_FOUND); + } + + @Override + public RespModel auth(String key) { + return new RespModel(RespEnum.SERVICE_NOT_FOUND); + } + + @Override + public RespModel findKeyById(int id) { + return new RespModel(RespEnum.SERVICE_NOT_FOUND); + } + + @Override + public RespModel findSteps(int id) { + return new RespModel(RespEnum.SERVICE_NOT_FOUND); + } + + @Override + public RespModel subResultCount(int id) { + return new RespModel(RespEnum.SERVICE_NOT_FOUND); + } } \ No newline at end of file diff --git a/sonic-server-transport/src/main/java/com/sonic/transport/netty/MarshallingCodeCFactory.java b/sonic-server-transport/src/main/java/org/cloud/sonic/transport/netty/MarshallingCodeCFactory.java similarity index 96% rename from sonic-server-transport/src/main/java/com/sonic/transport/netty/MarshallingCodeCFactory.java rename to sonic-server-transport/src/main/java/org/cloud/sonic/transport/netty/MarshallingCodeCFactory.java index 08836d1e..7f95da23 100644 --- a/sonic-server-transport/src/main/java/com/sonic/transport/netty/MarshallingCodeCFactory.java +++ b/sonic-server-transport/src/main/java/org/cloud/sonic/transport/netty/MarshallingCodeCFactory.java @@ -1,4 +1,4 @@ -package com.sonic.transport.netty; +package org.cloud.sonic.transport.netty; import io.netty.handler.codec.marshalling.*; import org.jboss.marshalling.MarshallerFactory; diff --git a/sonic-server-transport/src/main/java/com/sonic/transport/netty/NettyServer.java b/sonic-server-transport/src/main/java/org/cloud/sonic/transport/netty/NettyServer.java similarity index 98% rename from sonic-server-transport/src/main/java/com/sonic/transport/netty/NettyServer.java rename to sonic-server-transport/src/main/java/org/cloud/sonic/transport/netty/NettyServer.java index 58872301..86660e9a 100644 --- a/sonic-server-transport/src/main/java/com/sonic/transport/netty/NettyServer.java +++ b/sonic-server-transport/src/main/java/org/cloud/sonic/transport/netty/NettyServer.java @@ -1,4 +1,4 @@ -package com.sonic.transport.netty; +package org.cloud.sonic.transport.netty; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.*; diff --git a/sonic-server-transport/src/main/java/com/sonic/transport/netty/NettyServerHandler.java b/sonic-server-transport/src/main/java/org/cloud/sonic/transport/netty/NettyServerHandler.java similarity index 95% rename from sonic-server-transport/src/main/java/com/sonic/transport/netty/NettyServerHandler.java rename to sonic-server-transport/src/main/java/org/cloud/sonic/transport/netty/NettyServerHandler.java index 728d7cdb..64e9ecaf 100644 --- a/sonic-server-transport/src/main/java/com/sonic/transport/netty/NettyServerHandler.java +++ b/sonic-server-transport/src/main/java/org/cloud/sonic/transport/netty/NettyServerHandler.java @@ -1,10 +1,10 @@ -package com.sonic.transport.netty; +package org.cloud.sonic.transport.netty; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; -import com.sonic.common.http.RespModel; -import com.sonic.transport.feign.ControllerFeignClient; -import com.sonic.transport.tools.SpringTool; +import org.cloud.sonic.common.http.RespModel; +import org.cloud.sonic.transport.feign.ControllerFeignClient; +import org.cloud.sonic.transport.tools.SpringTool; import io.netty.channel.Channel; import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelHandlerContext; @@ -13,7 +13,6 @@ import io.netty.handler.timeout.IdleStateEvent; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; import java.util.LinkedHashMap; import java.util.Map; diff --git a/sonic-server-transport/src/main/java/com/sonic/transport/netty/NettyThreadPool.java b/sonic-server-transport/src/main/java/org/cloud/sonic/transport/netty/NettyThreadPool.java similarity index 90% rename from sonic-server-transport/src/main/java/com/sonic/transport/netty/NettyThreadPool.java rename to sonic-server-transport/src/main/java/org/cloud/sonic/transport/netty/NettyThreadPool.java index 25a1d84a..e9b9b488 100644 --- a/sonic-server-transport/src/main/java/com/sonic/transport/netty/NettyThreadPool.java +++ b/sonic-server-transport/src/main/java/org/cloud/sonic/transport/netty/NettyThreadPool.java @@ -1,4 +1,4 @@ -package com.sonic.transport.netty; +package org.cloud.sonic.transport.netty; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; diff --git a/sonic-server-transport/src/main/java/com/sonic/transport/netty/SecurityHandler.java b/sonic-server-transport/src/main/java/org/cloud/sonic/transport/netty/SecurityHandler.java similarity index 92% rename from sonic-server-transport/src/main/java/com/sonic/transport/netty/SecurityHandler.java rename to sonic-server-transport/src/main/java/org/cloud/sonic/transport/netty/SecurityHandler.java index 4a00e8f3..b4c71122 100644 --- a/sonic-server-transport/src/main/java/com/sonic/transport/netty/SecurityHandler.java +++ b/sonic-server-transport/src/main/java/org/cloud/sonic/transport/netty/SecurityHandler.java @@ -1,10 +1,10 @@ -package com.sonic.transport.netty; +package org.cloud.sonic.transport.netty; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; -import com.sonic.common.http.RespModel; -import com.sonic.transport.feign.ControllerFeignClient; -import com.sonic.transport.tools.SpringTool; +import org.cloud.sonic.common.http.RespModel; +import org.cloud.sonic.transport.feign.ControllerFeignClient; +import org.cloud.sonic.transport.tools.SpringTool; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import org.slf4j.Logger; diff --git a/sonic-server-transport/src/main/java/com/sonic/transport/tools/SpringTool.java b/sonic-server-transport/src/main/java/org/cloud/sonic/transport/tools/SpringTool.java similarity index 95% rename from sonic-server-transport/src/main/java/com/sonic/transport/tools/SpringTool.java rename to sonic-server-transport/src/main/java/org/cloud/sonic/transport/tools/SpringTool.java index 95d2334a..d615b6b6 100644 --- a/sonic-server-transport/src/main/java/com/sonic/transport/tools/SpringTool.java +++ b/sonic-server-transport/src/main/java/org/cloud/sonic/transport/tools/SpringTool.java @@ -1,4 +1,4 @@ -package com.sonic.transport.tools; +package org.cloud.sonic.transport.tools; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext;