diff --git a/pom.xml b/pom.xml index 6a59a5e1..75caac32 100644 --- a/pom.xml +++ b/pom.xml @@ -61,11 +61,20 @@ groovy 4.0.14 - + + org.apache.tika + tika-core + 2.9.0 + org.flywaydb flyway-core + + com.huaweicloud + esdk-obs-java-bundle + 3.23.5 + org.springframework.boot spring-boot-starter-actuator diff --git a/src/main/java/cn/lihongjie/coal/CoalApplication.java b/src/main/java/cn/lihongjie/coal/CoalApplication.java index 791d109a..4ccde5ed 100644 --- a/src/main/java/cn/lihongjie/coal/CoalApplication.java +++ b/src/main/java/cn/lihongjie/coal/CoalApplication.java @@ -8,7 +8,7 @@ import org.springframework.data.jpa.repository.config.EnableJpaRepositories; @EnableJpaRepositories public class CoalApplication { - public static void main(String[] args) { - SpringApplication.run(CoalApplication.class, args); - } + public static void main(String[] args) { + SpringApplication.run(CoalApplication.class, args); + } } diff --git a/src/main/java/cn/lihongjie/coal/Codegen.java b/src/main/java/cn/lihongjie/coal/Codegen.java index 555d5dab..3a484de9 100644 --- a/src/main/java/cn/lihongjie/coal/Codegen.java +++ b/src/main/java/cn/lihongjie/coal/Codegen.java @@ -12,16 +12,16 @@ import cn.lihongjie.coal.base.entity.OrgCommonEntity; import cn.lihongjie.coal.base.mapper.BaseMapper; import cn.lihongjie.coal.base.mapper.CommonMapper; import cn.lihongjie.coal.base.service.BaseService; + import com.google.common.base.CaseFormat; import com.squareup.javapoet.*; + import jakarta.persistence.Entity; -import java.nio.file.Path; -import java.util.Objects; -import java.util.Scanner; -import javax.lang.model.element.Modifier; + import lombok.Data; import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; + import org.apache.commons.lang3.StringUtils; import org.mapstruct.Mapper; import org.mapstruct.control.DeepClone; @@ -37,159 +37,175 @@ import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; +import java.nio.file.Path; +import java.util.Objects; +import java.util.Scanner; + +import javax.lang.model.element.Modifier; + public class Codegen { - public static final Path DIRECTORY = Path.of("src/main/java/"); + public static final Path DIRECTORY = Path.of("src/main/java/"); - @SneakyThrows - public static void main(String[] args) { - System.out.print("请输入模块名:"); - String moduleName = new Scanner(System.in).nextLine(); + @SneakyThrows + public static void main(String[] args) { + System.out.print("请输入模块名:"); + String moduleName = new Scanner(System.in).nextLine(); - System.out.print("请输入模块中文名:"); - String moduleCNName = new Scanner(System.in).nextLine(); + System.out.print("请输入模块中文名:"); + String moduleCNName = new Scanner(System.in).nextLine(); - System.out.print("机构数据[Y]:"); - boolean orgMode = - Objects.equals(StringUtils.defaultIfBlank(new Scanner(System.in).nextLine(), "Y"), "Y"); + System.out.print("机构数据[Y]:"); + boolean orgMode = + Objects.equals( + StringUtils.defaultIfBlank(new Scanner(System.in).nextLine(), "Y"), "Y"); - String lModuleName = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_CAMEL, moduleName); - String prefix = Codegen.class.getPackage().getName() + "." + lModuleName; - String entityPackage = prefix + ".entity"; - String dtoPackage = prefix + ".dto"; - String repoPackage = prefix + ".repository"; - String mapperPackage = prefix + ".mapper"; - String servicePackage = prefix + ".service"; - String controllerPackage = prefix + ".controller"; + String lModuleName = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_CAMEL, moduleName); + String prefix = Codegen.class.getPackage().getName() + "." + lModuleName; + String entityPackage = prefix + ".entity"; + String dtoPackage = prefix + ".dto"; + String repoPackage = prefix + ".repository"; + String mapperPackage = prefix + ".mapper"; + String servicePackage = prefix + ".service"; + String controllerPackage = prefix + ".controller"; - // 生成entity + // 生成entity - TypeSpec entity = - TypeSpec.classBuilder(StringUtils.capitalize(moduleName) + "Entity") - .addModifiers(Modifier.PUBLIC) - .superclass(orgMode ? OrgCommonEntity.class : CommonEntity.class) - .addAnnotation(Data.class) - .addAnnotation(Entity.class) - .build(); + TypeSpec entity = + TypeSpec.classBuilder(StringUtils.capitalize(moduleName) + "Entity") + .addModifiers(Modifier.PUBLIC) + .superclass(orgMode ? OrgCommonEntity.class : CommonEntity.class) + .addAnnotation(Data.class) + .addAnnotation(Entity.class) + .build(); - JavaFile.builder(entityPackage, entity).build().writeTo(DIRECTORY); + JavaFile.builder(entityPackage, entity).build().writeTo(DIRECTORY); - // 生成dto - TypeSpec dto = - TypeSpec.classBuilder(StringUtils.capitalize(moduleName) + "Dto") - .addModifiers(Modifier.PUBLIC) - .superclass(orgMode ? OrgCommonDto.class : CommonDto.class) - .addAnnotation(Data.class) - .build(); + // 生成dto + TypeSpec dto = + TypeSpec.classBuilder(StringUtils.capitalize(moduleName) + "Dto") + .addModifiers(Modifier.PUBLIC) + .superclass(orgMode ? OrgCommonDto.class : CommonDto.class) + .addAnnotation(Data.class) + .build(); - JavaFile.builder(dtoPackage, dto).build().writeTo(DIRECTORY); + JavaFile.builder(dtoPackage, dto).build().writeTo(DIRECTORY); - // 生成createDto - TypeSpec createDto = - TypeSpec.classBuilder("Create" + StringUtils.capitalize(moduleName) + "Dto") - .addModifiers(Modifier.PUBLIC) - .superclass(orgMode ? OrgCommonDto.class : CommonDto.class) - .addAnnotation(Data.class) - .build(); + // 生成createDto + TypeSpec createDto = + TypeSpec.classBuilder("Create" + StringUtils.capitalize(moduleName) + "Dto") + .addModifiers(Modifier.PUBLIC) + .superclass(orgMode ? OrgCommonDto.class : CommonDto.class) + .addAnnotation(Data.class) + .build(); - JavaFile.builder(dtoPackage, createDto).build().writeTo(DIRECTORY); + JavaFile.builder(dtoPackage, createDto).build().writeTo(DIRECTORY); - // 生成updateDto - TypeSpec updateDto = - TypeSpec.classBuilder("Update" + StringUtils.capitalize(moduleName) + "Dto") - .addModifiers(Modifier.PUBLIC) - .superclass(orgMode ? OrgCommonDto.class : CommonDto.class) - .addAnnotation(Data.class) - .build(); + // 生成updateDto + TypeSpec updateDto = + TypeSpec.classBuilder("Update" + StringUtils.capitalize(moduleName) + "Dto") + .addModifiers(Modifier.PUBLIC) + .superclass(orgMode ? OrgCommonDto.class : CommonDto.class) + .addAnnotation(Data.class) + .build(); - JavaFile.builder(dtoPackage, updateDto).build().writeTo(DIRECTORY); + JavaFile.builder(dtoPackage, updateDto).build().writeTo(DIRECTORY); - // 生成repository - TypeSpec repository = - TypeSpec.interfaceBuilder(StringUtils.capitalize(moduleName) + "Repository") - .addModifiers(Modifier.PUBLIC) - .addAnnotation(Repository.class) - .addSuperinterface( - ParameterizedTypeName.get( - ClassName.get(BaseRepository.class), ClassName.get(entityPackage, entity.name))) - .build(); + // 生成repository + TypeSpec repository = + TypeSpec.interfaceBuilder(StringUtils.capitalize(moduleName) + "Repository") + .addModifiers(Modifier.PUBLIC) + .addAnnotation(Repository.class) + .addSuperinterface( + ParameterizedTypeName.get( + ClassName.get(BaseRepository.class), + ClassName.get(entityPackage, entity.name))) + .build(); - JavaFile.builder(repoPackage, repository).build().writeTo(DIRECTORY); + JavaFile.builder(repoPackage, repository).build().writeTo(DIRECTORY); - // 生成mapper - TypeSpec mapper = - TypeSpec.interfaceBuilder(StringUtils.capitalize(moduleName) + "Mapper") - .addModifiers(Modifier.PUBLIC) - .addAnnotation( - AnnotationSpec.builder(Mapper.class) - .addMember( - "componentModel", - "org.mapstruct.MappingConstants.ComponentModel.SPRING", - "") - .addMember("uses", "{$T.class}", CommonMapper.class) - .addMember("mappingControl", "$T.class", DeepClone.class) - .build()) - .addSuperinterface( - ParameterizedTypeName.get( - ClassName.get(BaseMapper.class), - ClassName.get(entityPackage, entity.name), - ClassName.get(dtoPackage, dto.name), - ClassName.get(dtoPackage, createDto.name), - ClassName.get(dtoPackage, updateDto.name))) - .build(); + // 生成mapper + TypeSpec mapper = + TypeSpec.interfaceBuilder(StringUtils.capitalize(moduleName) + "Mapper") + .addModifiers(Modifier.PUBLIC) + .addAnnotation( + AnnotationSpec.builder(Mapper.class) + .addMember( + "componentModel", + "org.mapstruct.MappingConstants.ComponentModel.SPRING", + "") + .addMember("uses", "{$T.class}", CommonMapper.class) + .addMember("mappingControl", "$T.class", DeepClone.class) + .build()) + .addSuperinterface( + ParameterizedTypeName.get( + ClassName.get(BaseMapper.class), + ClassName.get(entityPackage, entity.name), + ClassName.get(dtoPackage, dto.name), + ClassName.get(dtoPackage, createDto.name), + ClassName.get(dtoPackage, updateDto.name))) + .build(); - JavaFile.builder(mapperPackage, mapper).build().writeTo(DIRECTORY); + JavaFile.builder(mapperPackage, mapper).build().writeTo(DIRECTORY); - // 生成service - TypeSpec service = - TypeSpec.classBuilder(StringUtils.capitalize(moduleName) + "Service") - .addModifiers(Modifier.PUBLIC) - .addAnnotation(Service.class) - .addAnnotation(Slf4j.class) - .superclass( - ParameterizedTypeName.get( - ClassName.get(BaseService.class), - ClassName.get(entityPackage, entity.name), - ClassName.get(repoPackage, repository.name))) - .addField( - FieldSpec.builder( - ClassName.get(repoPackage, repository.name), "repository", Modifier.PRIVATE) - .addAnnotation(Autowired.class) - .build()) - .addField( - FieldSpec.builder( - ClassName.get(mapperPackage, mapper.name), "mapper", Modifier.PRIVATE) - .addAnnotation(Autowired.class) - .build()) - .addField( - FieldSpec.builder( - ClassName.get(ConversionService.class), - "conversionService", - Modifier.PRIVATE) - .addAnnotation(Autowired.class) - .build()) - .addMethod( - MethodSpec.methodBuilder("create") - .addModifiers(Modifier.PUBLIC) - .returns(ClassName.get(dtoPackage, dto.name)) - .addParameter(ClassName.get(dtoPackage, createDto.name), "request") - .addStatement( - """ + // 生成service + TypeSpec service = + TypeSpec.classBuilder(StringUtils.capitalize(moduleName) + "Service") + .addModifiers(Modifier.PUBLIC) + .addAnnotation(Service.class) + .addAnnotation(Slf4j.class) + .superclass( + ParameterizedTypeName.get( + ClassName.get(BaseService.class), + ClassName.get(entityPackage, entity.name), + ClassName.get(repoPackage, repository.name))) + .addField( + FieldSpec.builder( + ClassName.get(repoPackage, repository.name), + "repository", + Modifier.PRIVATE) + .addAnnotation(Autowired.class) + .build()) + .addField( + FieldSpec.builder( + ClassName.get(mapperPackage, mapper.name), + "mapper", + Modifier.PRIVATE) + .addAnnotation(Autowired.class) + .build()) + .addField( + FieldSpec.builder( + ClassName.get(ConversionService.class), + "conversionService", + Modifier.PRIVATE) + .addAnnotation(Autowired.class) + .build()) + .addMethod( + MethodSpec.methodBuilder("create") + .addModifiers(Modifier.PUBLIC) + .returns(ClassName.get(dtoPackage, dto.name)) + .addParameter( + ClassName.get(dtoPackage, createDto.name), + "request") + .addStatement( + """ $T entity = mapper.toEntity(request); this.repository.save(entity); return getById(entity.getId()) """, - ClassName.get(entityPackage, entity.name)) - .build()) - .addMethod( - MethodSpec.methodBuilder("update") - .addModifiers(Modifier.PUBLIC) - .returns(ClassName.get(dtoPackage, dto.name)) - .addParameter(ClassName.get(dtoPackage, updateDto.name), "request") - .addStatement( - """ + ClassName.get(entityPackage, entity.name)) + .build()) + .addMethod( + MethodSpec.methodBuilder("update") + .addModifiers(Modifier.PUBLIC) + .returns(ClassName.get(dtoPackage, dto.name)) + .addParameter( + ClassName.get(dtoPackage, updateDto.name), + "request") + .addStatement( + """ $T entity = this.repository.get(request.getId()); this.mapper.updateEntity(entity, request); @@ -197,172 +213,186 @@ public class Codegen { return getById(entity.getId()) """, - ClassName.get(entityPackage, entity.name)) - .build()) - .addMethod( - MethodSpec.methodBuilder("delete") - .addModifiers(Modifier.PUBLIC) - .returns(void.class) - .addParameter(ClassName.get(IdRequest.class), "request") - .addStatement( - """ + ClassName.get(entityPackage, entity.name)) + .build()) + .addMethod( + MethodSpec.methodBuilder("delete") + .addModifiers(Modifier.PUBLIC) + .returns(void.class) + .addParameter(ClassName.get(IdRequest.class), "request") + .addStatement( + """ this.repository.deleteAllById(request.getIds()) """) - .build()) - .addMethod( - MethodSpec.methodBuilder("getById") - .addModifiers(Modifier.PUBLIC) - .returns(ClassName.get(dtoPackage, dto.name)) - .addParameter(ClassName.get(String.class), "id") - .addStatement( - """ + .build()) + .addMethod( + MethodSpec.methodBuilder("getById") + .addModifiers(Modifier.PUBLIC) + .returns(ClassName.get(dtoPackage, dto.name)) + .addParameter(ClassName.get(String.class), "id") + .addStatement( + """ $T entity = repository.get(id); return mapper.toDto(entity) """, - ClassName.get(entityPackage, entity.name)) - .build()) - .addMethod( - MethodSpec.methodBuilder("list") - .addModifiers(Modifier.PUBLIC) - .returns( - ParameterizedTypeName.get( - ClassName.get(Page.class), ClassName.get(dtoPackage, dto.name))) - .addParameter(ClassName.get(CommonQuery.class), "query") - .addStatement( - """ + ClassName.get(entityPackage, entity.name)) + .build()) + .addMethod( + MethodSpec.methodBuilder("list") + .addModifiers(Modifier.PUBLIC) + .returns( + ParameterizedTypeName.get( + ClassName.get(Page.class), + ClassName.get(dtoPackage, dto.name))) + .addParameter(ClassName.get(CommonQuery.class), "query") + .addStatement( + """ $T<$T> page = repository.findAll(query.specification(conversionService), $T.of(query.getPageNo(), query.getPageSize(), $T.by(query.getOrders()))); return page.map(this.mapper::toDto) """, - ClassName.get(Page.class), - ClassName.get(entityPackage, entity.name), - ClassName.get(PageRequest.class), - ClassName.get(Sort.class)) - .build()) - .build(); + ClassName.get(Page.class), + ClassName.get(entityPackage, entity.name), + ClassName.get(PageRequest.class), + ClassName.get(Sort.class)) + .build()) + .build(); - JavaFile.builder(servicePackage, service).build().writeTo(DIRECTORY); + JavaFile.builder(servicePackage, service).build().writeTo(DIRECTORY); - // 生成controller - TypeSpec.Builder controllerBuilder = - TypeSpec.classBuilder(StringUtils.capitalize(moduleName) + "Controller") - .addModifiers(Modifier.PUBLIC) - .addAnnotation(RestController.class) - .addAnnotation( - AnnotationSpec.builder(RequestMapping.class) - .addMember("value", "$S", "/" + lModuleName) - .build()) - .addAnnotation( - AnnotationSpec.builder(SysLog.class) - .addMember("module", "$S", StringUtils.defaultIfBlank(moduleCNName, "")) - .build()) - .addAnnotation(Slf4j.class); + // 生成controller + TypeSpec.Builder controllerBuilder = + TypeSpec.classBuilder(StringUtils.capitalize(moduleName) + "Controller") + .addModifiers(Modifier.PUBLIC) + .addAnnotation(RestController.class) + .addAnnotation( + AnnotationSpec.builder(RequestMapping.class) + .addMember("value", "$S", "/" + lModuleName) + .build()) + .addAnnotation( + AnnotationSpec.builder(SysLog.class) + .addMember( + "module", + "$S", + StringUtils.defaultIfBlank(moduleCNName, "")) + .build()) + .addAnnotation(Slf4j.class); - if (orgMode) { - controllerBuilder.addAnnotation(OrgScope.class); - } - controllerBuilder - .addField( - FieldSpec.builder( - ClassName.get(servicePackage, service.name), "service", Modifier.PRIVATE) - .addAnnotation(Autowired.class) - .build()) - .addMethod( - MethodSpec.methodBuilder("create") - .addModifiers(Modifier.PUBLIC) - .returns(ClassName.get(dtoPackage, dto.name)) - .addAnnotation( - AnnotationSpec.builder(PostMapping.class) - .addMember("value", "$S", "/create") - .build()) - .addParameter( - ParameterSpec.builder(ClassName.get(dtoPackage, createDto.name), "request") - .addAnnotation(RequestBody.class) - .build()) - .addStatement( - """ + if (orgMode) { + controllerBuilder.addAnnotation(OrgScope.class); + } + controllerBuilder + .addField( + FieldSpec.builder( + ClassName.get(servicePackage, service.name), + "service", + Modifier.PRIVATE) + .addAnnotation(Autowired.class) + .build()) + .addMethod( + MethodSpec.methodBuilder("create") + .addModifiers(Modifier.PUBLIC) + .returns(ClassName.get(dtoPackage, dto.name)) + .addAnnotation( + AnnotationSpec.builder(PostMapping.class) + .addMember("value", "$S", "/create") + .build()) + .addParameter( + ParameterSpec.builder( + ClassName.get(dtoPackage, createDto.name), + "request") + .addAnnotation(RequestBody.class) + .build()) + .addStatement( + """ return this.service.create(request) """) - .build()) - .addMethod( - MethodSpec.methodBuilder("update") - .addModifiers(Modifier.PUBLIC) - .returns(ClassName.get(dtoPackage, dto.name)) - .addAnnotation( - AnnotationSpec.builder(PostMapping.class) - .addMember("value", "$S", "/update") - .build()) - .addParameter( - ParameterSpec.builder(ClassName.get(dtoPackage, updateDto.name), "request") - .addAnnotation(RequestBody.class) - .build()) - .addStatement( - """ + .build()) + .addMethod( + MethodSpec.methodBuilder("update") + .addModifiers(Modifier.PUBLIC) + .returns(ClassName.get(dtoPackage, dto.name)) + .addAnnotation( + AnnotationSpec.builder(PostMapping.class) + .addMember("value", "$S", "/update") + .build()) + .addParameter( + ParameterSpec.builder( + ClassName.get(dtoPackage, updateDto.name), + "request") + .addAnnotation(RequestBody.class) + .build()) + .addStatement( + """ return this.service.update(request) """) - .build()) - .addMethod( - MethodSpec.methodBuilder("delete") - .addModifiers(Modifier.PUBLIC) - .returns(Object.class) - .addAnnotation( - AnnotationSpec.builder(PostMapping.class) - .addMember("value", "$S", "/delete") - .build()) - .addParameter( - ParameterSpec.builder(ClassName.get(IdRequest.class), "request") - .addAnnotation(RequestBody.class) - .build()) - .addStatement( - """ + .build()) + .addMethod( + MethodSpec.methodBuilder("delete") + .addModifiers(Modifier.PUBLIC) + .returns(Object.class) + .addAnnotation( + AnnotationSpec.builder(PostMapping.class) + .addMember("value", "$S", "/delete") + .build()) + .addParameter( + ParameterSpec.builder( + ClassName.get(IdRequest.class), "request") + .addAnnotation(RequestBody.class) + .build()) + .addStatement( + """ this.service.delete(request); return true """) - .build()) - .addMethod( - MethodSpec.methodBuilder("getById") - .addModifiers(Modifier.PUBLIC) - .returns(ClassName.get(dtoPackage, dto.name)) - .addAnnotation( - AnnotationSpec.builder(PostMapping.class) - .addMember("value", "$S", "/getById") - .build()) - .addParameter( - ParameterSpec.builder(ClassName.get(String.class), "request") - .addAnnotation(RequestBody.class) - .build()) - .addStatement( - """ + .build()) + .addMethod( + MethodSpec.methodBuilder("getById") + .addModifiers(Modifier.PUBLIC) + .returns(ClassName.get(dtoPackage, dto.name)) + .addAnnotation( + AnnotationSpec.builder(PostMapping.class) + .addMember("value", "$S", "/getById") + .build()) + .addParameter( + ParameterSpec.builder( + ClassName.get(String.class), "request") + .addAnnotation(RequestBody.class) + .build()) + .addStatement( + """ return this.service.getById(request) """) - .build()) - .addMethod( - MethodSpec.methodBuilder("list") - .addModifiers(Modifier.PUBLIC) - .returns( - ParameterizedTypeName.get( - ClassName.get(Page.class), ClassName.get(dtoPackage, dto.name))) - .addAnnotation( - AnnotationSpec.builder(PostMapping.class) - .addMember("value", "$S", "/list") - .build()) - .addParameter( - ParameterSpec.builder(ClassName.get(CommonQuery.class), "request") - .addAnnotation(RequestBody.class) - .build()) - .addStatement( - """ + .build()) + .addMethod( + MethodSpec.methodBuilder("list") + .addModifiers(Modifier.PUBLIC) + .returns( + ParameterizedTypeName.get( + ClassName.get(Page.class), + ClassName.get(dtoPackage, dto.name))) + .addAnnotation( + AnnotationSpec.builder(PostMapping.class) + .addMember("value", "$S", "/list") + .build()) + .addParameter( + ParameterSpec.builder( + ClassName.get(CommonQuery.class), "request") + .addAnnotation(RequestBody.class) + .build()) + .addStatement( + """ return this.service.list(request) """, - ClassName.get(Page.class), - ClassName.get(entityPackage, entity.name), - ClassName.get(PageRequest.class), - ClassName.get(Sort.class)) - .build()); + ClassName.get(Page.class), + ClassName.get(entityPackage, entity.name), + ClassName.get(PageRequest.class), + ClassName.get(Sort.class)) + .build()); - JavaFile.builder(controllerPackage, controllerBuilder.build()).build().writeTo(DIRECTORY); - } + JavaFile.builder(controllerPackage, controllerBuilder.build()).build().writeTo(DIRECTORY); + } } diff --git a/src/main/java/cn/lihongjie/coal/annotation/Anonymous.java b/src/main/java/cn/lihongjie/coal/annotation/Anonymous.java index 3f9b2d35..50d5099e 100644 --- a/src/main/java/cn/lihongjie/coal/annotation/Anonymous.java +++ b/src/main/java/cn/lihongjie/coal/annotation/Anonymous.java @@ -9,5 +9,5 @@ import java.lang.annotation.Target; @Target({ElementType.TYPE, ElementType.METHOD}) public @interface Anonymous { - boolean value() default true; + boolean value() default true; } diff --git a/src/main/java/cn/lihongjie/coal/annotation/OrgAdmin.java b/src/main/java/cn/lihongjie/coal/annotation/OrgAdmin.java index 0971d0d6..830dc07f 100644 --- a/src/main/java/cn/lihongjie/coal/annotation/OrgAdmin.java +++ b/src/main/java/cn/lihongjie/coal/annotation/OrgAdmin.java @@ -9,5 +9,5 @@ import java.lang.annotation.Target; @Target({ElementType.TYPE, ElementType.METHOD}) public @interface OrgAdmin { - boolean value() default true; + boolean value() default true; } diff --git a/src/main/java/cn/lihongjie/coal/annotation/OrgScope.java b/src/main/java/cn/lihongjie/coal/annotation/OrgScope.java index 345ff0dd..04547be8 100644 --- a/src/main/java/cn/lihongjie/coal/annotation/OrgScope.java +++ b/src/main/java/cn/lihongjie/coal/annotation/OrgScope.java @@ -9,5 +9,5 @@ import java.lang.annotation.Target; @Target({ElementType.TYPE, ElementType.METHOD}) public @interface OrgScope { - boolean value() default true; + boolean value() default true; } diff --git a/src/main/java/cn/lihongjie/coal/annotation/SysAdmin.java b/src/main/java/cn/lihongjie/coal/annotation/SysAdmin.java index 78f2b67e..7d34340a 100644 --- a/src/main/java/cn/lihongjie/coal/annotation/SysAdmin.java +++ b/src/main/java/cn/lihongjie/coal/annotation/SysAdmin.java @@ -9,5 +9,5 @@ import java.lang.annotation.Target; @Target({ElementType.TYPE, ElementType.METHOD}) public @interface SysAdmin { - boolean value() default true; + boolean value() default true; } diff --git a/src/main/java/cn/lihongjie/coal/annotation/SysLog.java b/src/main/java/cn/lihongjie/coal/annotation/SysLog.java index c7018438..5eb4562a 100644 --- a/src/main/java/cn/lihongjie/coal/annotation/SysLog.java +++ b/src/main/java/cn/lihongjie/coal/annotation/SysLog.java @@ -9,9 +9,9 @@ import java.lang.annotation.Target; @Target({ElementType.TYPE, ElementType.METHOD}) public @interface SysLog { - String module() default ""; + String module() default ""; - String action() default ""; + String action() default ""; - String message() default ""; + String message() default ""; } diff --git a/src/main/java/cn/lihongjie/coal/aop/ControllerAop.java b/src/main/java/cn/lihongjie/coal/aop/ControllerAop.java index 518f823b..e1142315 100644 --- a/src/main/java/cn/lihongjie/coal/aop/ControllerAop.java +++ b/src/main/java/cn/lihongjie/coal/aop/ControllerAop.java @@ -6,11 +6,12 @@ import cn.lihongjie.coal.ip.IpQueryService; import cn.lihongjie.coal.session.SessionService; import cn.lihongjie.coal.syslog.entity.SysLogEntity; import cn.lihongjie.coal.syslog.service.SysLogService; + import jakarta.servlet.http.HttpServletRequest; -import java.lang.reflect.Method; -import java.util.Arrays; + import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; + import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.exception.ExceptionUtils; import org.aspectj.lang.ProceedingJoinPoint; @@ -24,109 +25,113 @@ import org.springframework.stereotype.Component; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; +import java.lang.reflect.Method; +import java.util.Arrays; + @Aspect @Component @Slf4j public class ControllerAop { - @Pointcut("execution (* cn.lihongjie.coal.*.controller.*.*(..))") - public void controllerMethods() {} + @Autowired SessionService sessionService; + @Autowired IpQueryService ipQueryService; + @Autowired SysLogService sysLogService; - @Autowired SessionService sessionService; - - @SneakyThrows - @Around("controllerMethods()") - public Object call(ProceedingJoinPoint proceedingJoinPoint) { - - Method method = ((MethodSignature) proceedingJoinPoint.getSignature()).getMethod(); - HttpServletRequest request = - ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); - - long start = System.currentTimeMillis(); - SysLogEntity sysLogEntity = createSysLog(method, request); - try { - - return proceedingJoinPoint.proceed(); - - } catch (Throwable e) { - - logException(e, proceedingJoinPoint); - - updateSysLog(e, sysLogEntity); - - throw e; - - } finally { - - saveSysLog(sysLogEntity, System.currentTimeMillis(), start); - } - } - - private void saveSysLog(SysLogEntity sysLogEntity, long end, long start) { - if (sysLogEntity != null) { - sysLogEntity.setTimeCost((int) (end - start)); - - sysLogService.save(sysLogEntity); - } - } - - private static void updateSysLog(Throwable e, SysLogEntity sysLogEntity) { - if (sysLogEntity != null) { - sysLogEntity.setOptStatus("1"); - sysLogEntity.setStacktrace(ExceptionUtils.getStackTrace(e)); - } - } - - @Autowired IpQueryService ipQueryService; - - private SysLogEntity createSysLog(Method method, HttpServletRequest request) { - SysLog sysLog = AnnotationUtils.findAnnotation(method, SysLog.class); - - SysLogEntity sysLogEntity = null; - String module = ""; - if (sysLog != null) { - - module = sysLog.module(); - if (StringUtils.isEmpty(module)) { - SysLog classLog = AnnotationUtils.findAnnotation(method.getDeclaringClass(), SysLog.class); - if (classLog != null) { - - module = classLog.module(); + private static void updateSysLog(Throwable e, SysLogEntity sysLogEntity) { + if (sysLogEntity != null) { + sysLogEntity.setOptStatus("1"); + sysLogEntity.setStacktrace(ExceptionUtils.getStackTrace(e)); } - } - - sysLogEntity = new SysLogEntity(); - sysLogEntity.setModule(module); - sysLogEntity.setMessage(sysLog.message()); - sysLogEntity.setAction(sysLog.action()); - sysLogEntity.setIp(RequestUtils.getIp(request)); - sysLogEntity.setIpLocation(ipQueryService.query(sysLogEntity.getIp())); - sysLogEntity.setUrl(request.getRequestURI()); - sysLogEntity.setOptStatus("0"); - sysLogEntity.setTimeCost(0); - sysLogEntity.setUserAgent(RequestUtils.getUa(request)); } - return sysLogEntity; - } - @Autowired SysLogService sysLogService; + @Pointcut("execution (* cn.lihongjie.coal.*.controller.*.*(..))") + public void controllerMethods() {} - private void logException(Throwable ex, ProceedingJoinPoint proceedingJoinPoint) { - HttpServletRequest request = - ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); + @SneakyThrows + @Around("controllerMethods()") + public Object call(ProceedingJoinPoint proceedingJoinPoint) { - Object[] args = proceedingJoinPoint.getArgs(); - Method method = ((MethodSignature) proceedingJoinPoint.getSignature()).getMethod(); + Method method = ((MethodSignature) proceedingJoinPoint.getSignature()).getMethod(); + HttpServletRequest request = + ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()) + .getRequest(); - log.info( - "接口调用异常: {}\nurl:{} {}\nmethod: {}\nargs: {}", - ex.getMessage() == null ? "no message" : ex.getMessage(), - request.getMethod(), - request.getRequestURL(), - method, - Arrays.toString(args), - ex); + long start = System.currentTimeMillis(); + SysLogEntity sysLogEntity = createSysLog(method, request); + try { - request.setAttribute("__logged", true); - } + return proceedingJoinPoint.proceed(); + + } catch (Throwable e) { + + logException(e, proceedingJoinPoint); + + updateSysLog(e, sysLogEntity); + + throw e; + + } finally { + + saveSysLog(sysLogEntity, System.currentTimeMillis(), start); + } + } + + private void saveSysLog(SysLogEntity sysLogEntity, long end, long start) { + if (sysLogEntity != null) { + sysLogEntity.setTimeCost((int) (end - start)); + + sysLogService.save(sysLogEntity); + } + } + + private SysLogEntity createSysLog(Method method, HttpServletRequest request) { + SysLog sysLog = AnnotationUtils.findAnnotation(method, SysLog.class); + + SysLogEntity sysLogEntity = null; + String module = ""; + if (sysLog != null) { + + module = sysLog.module(); + if (StringUtils.isEmpty(module)) { + SysLog classLog = + AnnotationUtils.findAnnotation(method.getDeclaringClass(), SysLog.class); + if (classLog != null) { + + module = classLog.module(); + } + } + + sysLogEntity = new SysLogEntity(); + sysLogEntity.setModule(module); + sysLogEntity.setMessage(sysLog.message()); + sysLogEntity.setAction(sysLog.action()); + sysLogEntity.setIp(RequestUtils.getIp(request)); + sysLogEntity.setIpLocation(ipQueryService.query(sysLogEntity.getIp())); + sysLogEntity.setUrl(request.getRequestURI()); + sysLogEntity.setOptStatus("0"); + sysLogEntity.setTimeCost(0); + sysLogEntity.setUserAgent(RequestUtils.getUa(request)); + } + return sysLogEntity; + } + + private void logException(Throwable ex, ProceedingJoinPoint proceedingJoinPoint) { + HttpServletRequest request = + ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()) + .getRequest(); + + Object[] args = proceedingJoinPoint.getArgs(); + Method method = ((MethodSignature) proceedingJoinPoint.getSignature()).getMethod(); + + log.info( + "接口调用异常: {}\nurl:{} {}\nmethod: {}\nargs: {}", + ex.getMessage() == null ? "no message" : ex.getMessage(), + request.getMethod(), + request.getRequestURL(), + method, + Arrays.toString(args), + ex); + + request.setAttribute("__logged", true); + } } diff --git a/src/main/java/cn/lihongjie/coal/aop/OrgScopeAop.java b/src/main/java/cn/lihongjie/coal/aop/OrgScopeAop.java index 60523ec5..da948c71 100644 --- a/src/main/java/cn/lihongjie/coal/aop/OrgScopeAop.java +++ b/src/main/java/cn/lihongjie/coal/aop/OrgScopeAop.java @@ -3,11 +3,13 @@ package cn.lihongjie.coal.aop; import cn.lihongjie.coal.annotation.OrgScope; import cn.lihongjie.coal.common.Ctx; import cn.lihongjie.coal.exception.BizException; + import jakarta.persistence.EntityManager; import jakarta.persistence.PersistenceContext; -import java.lang.reflect.Method; + import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; + import org.apache.commons.lang3.StringUtils; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; @@ -19,68 +21,69 @@ import org.hibernate.Session; import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component; +import java.lang.reflect.Method; + @Aspect @Component @Slf4j @Order public class OrgScopeAop { - @PersistenceContext EntityManager entityManager; + private static final ThreadLocal orgScope = new ThreadLocal<>(); + @PersistenceContext EntityManager entityManager; - private static ThreadLocal orgScope = new ThreadLocal<>(); + @SneakyThrows + @Around( + value = + "@annotation(cn.lihongjie.coal.annotation.OrgScope) || @within(cn.lihongjie.coal.annotation.OrgScope)") + public Object beforeOrgScope(ProceedingJoinPoint pjp) { - @SneakyThrows - @Around( - value = - "@annotation(cn.lihongjie.coal.annotation.OrgScope) || @within(cn.lihongjie.coal.annotation.OrgScope)") - public Object beforeOrgScope(ProceedingJoinPoint pjp) { + Method method = ((MethodSignature) pjp.getSignature()).getMethod(); + OrgScope annotation = method.getAnnotation(OrgScope.class); - Method method = ((MethodSignature) pjp.getSignature()).getMethod(); - OrgScope annotation = method.getAnnotation(OrgScope.class); - - if (annotation == null) { - annotation = method.getDeclaringClass().getAnnotation(OrgScope.class); - } - - if (annotation != null) { - boolean enabled = annotation.value(); - - Session session = entityManager.unwrap(Session.class); - - if (enabled) { - - if (StringUtils.isEmpty(Ctx.currentUser().getOrganizationId())) { - throw new BizException("当前用户未绑定机构, 无法进行机构数据过滤"); + if (annotation == null) { + annotation = method.getDeclaringClass().getAnnotation(OrgScope.class); } - if (session.getEnabledFilter("orgFilter") == null) { + if (annotation != null) { + boolean enabled = annotation.value(); - Filter orgFilter = session.enableFilter("orgFilter"); + Session session = entityManager.unwrap(Session.class); - orgFilter.setParameter("organizationId", Ctx.currentUser().getOrganizationId()); - } else { - log.debug("当前session {} orgFilter已经启用, 忽略....", session.toString()); + if (enabled) { + + if (StringUtils.isEmpty(Ctx.currentUser().getOrganizationId())) { + throw new BizException("当前用户未绑定机构, 无法进行机构数据过滤"); + } + + if (session.getEnabledFilter("orgFilter") == null) { + + Filter orgFilter = session.enableFilter("orgFilter"); + + orgFilter.setParameter("organizationId", Ctx.currentUser().getOrganizationId()); + } else { + log.debug("当前session {} orgFilter已经启用, 忽略....", session); + } + } else { + + if (session.getEnabledFilter("orgFilter") != null) { + + session.disableFilter("orgFilter"); + + } else { + log.debug("当前session {} orgFilter已经禁用, 忽略....", session); + } + } } - } else { + return pjp.proceed(); + } - if (session.getEnabledFilter("orgFilter") != null) { + @Before(value = "@annotation(org.springframework.transaction.annotation.Transactional))") + public void beforeTransactionMethod() { - session.disableFilter("orgFilter"); + if (orgScope.get() != null) { - } else { - log.debug("当前session {} orgFilter已经禁用, 忽略....", session.toString()); + Session session = entityManager.unwrap(Session.class); } - } } - return pjp.proceed(); - } - - @Before(value = "@annotation(org.springframework.transaction.annotation.Transactional))") - public void beforeTransactionMethod() { - - if (orgScope.get() != null) { - - Session session = entityManager.unwrap(Session.class); - } - } } diff --git a/src/main/java/cn/lihongjie/coal/base/controller/BaseController.java b/src/main/java/cn/lihongjie/coal/base/controller/BaseController.java index 7e7991f8..6925eee3 100644 --- a/src/main/java/cn/lihongjie/coal/base/controller/BaseController.java +++ b/src/main/java/cn/lihongjie/coal/base/controller/BaseController.java @@ -1,6 +1,7 @@ package cn.lihongjie.coal.base.controller; import cn.lihongjie.coal.annotation.OrgScope; + import org.springframework.transaction.annotation.Transactional; import org.springframework.web.bind.annotation.RestController; diff --git a/src/main/java/cn/lihongjie/coal/base/dao/BaseRepository.java b/src/main/java/cn/lihongjie/coal/base/dao/BaseRepository.java index 574da9a3..36c4bc2c 100644 --- a/src/main/java/cn/lihongjie/coal/base/dao/BaseRepository.java +++ b/src/main/java/cn/lihongjie/coal/base/dao/BaseRepository.java @@ -1,30 +1,31 @@ package cn.lihongjie.coal.base.dao; import jakarta.persistence.criteria.Path; -import java.util.List; + import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.repository.NoRepositoryBean; +import java.util.List; + @NoRepositoryBean public interface BaseRepository extends JpaRepository, JpaSpecificationExecutor { - public default T get(String id) { + default T get(String id) { - return findById(id).orElseThrow(() -> new RuntimeException("数据不存在: " + id)); - } + return findById(id).orElseThrow(() -> new RuntimeException("数据不存在: " + id)); + } - public default List findByOrganizationId(String organizationId) { - return findAll( - (root, query, cb) -> { - try { + default List findByOrganizationId(String organizationId) { + return findAll( + (root, query, cb) -> { + try { - Path path = root.get("organizationId"); - return cb.equal(path, organizationId); - } catch (Exception e) { - return cb.and(); - } - }); - } - ; + Path path = root.get("organizationId"); + return cb.equal(path, organizationId); + } catch (Exception e) { + return cb.and(); + } + }); + } } diff --git a/src/main/java/cn/lihongjie/coal/base/dto/BaseDto.java b/src/main/java/cn/lihongjie/coal/base/dto/BaseDto.java index 446bd70d..89ae0f06 100644 --- a/src/main/java/cn/lihongjie/coal/base/dto/BaseDto.java +++ b/src/main/java/cn/lihongjie/coal/base/dto/BaseDto.java @@ -1,23 +1,24 @@ package cn.lihongjie.coal.base.dto; -import java.time.LocalDateTime; import lombok.Getter; import lombok.Setter; +import java.time.LocalDateTime; + @Getter @Setter public abstract class BaseDto { - private String id; + private String id; - private String createUserId; + private String createUserId; - private String createUserName; + private String createUserName; - private LocalDateTime createTime; + private LocalDateTime createTime; - private String updateUserId; - private String updateUserName; + private String updateUserId; + private String updateUserName; - private LocalDateTime updateTime; + private LocalDateTime updateTime; } diff --git a/src/main/java/cn/lihongjie/coal/base/dto/CommonDto.java b/src/main/java/cn/lihongjie/coal/base/dto/CommonDto.java index 698d599d..4bcd5643 100644 --- a/src/main/java/cn/lihongjie/coal/base/dto/CommonDto.java +++ b/src/main/java/cn/lihongjie/coal/base/dto/CommonDto.java @@ -2,24 +2,25 @@ package cn.lihongjie.coal.base.dto; import lombok.Getter; import lombok.Setter; + import org.hibernate.annotations.Comment; @Getter @Setter public class CommonDto extends BaseDto { - @Comment("名称") - private String name; + @Comment("名称") + private String name; - @Comment("编码") - private String code; + @Comment("编码") + private String code; - @Comment("备注") - private String remarks; + @Comment("备注") + private String remarks; - @Comment("排序键") - private Integer sortKey; + @Comment("排序键") + private Integer sortKey; - @Comment("常用状态 0 禁用 1 启用") - private String status; + @Comment("常用状态 0 禁用 1 启用") + private String status; } diff --git a/src/main/java/cn/lihongjie/coal/base/dto/CommonQuery.java b/src/main/java/cn/lihongjie/coal/base/dto/CommonQuery.java index 3f785e43..85510a76 100644 --- a/src/main/java/cn/lihongjie/coal/base/dto/CommonQuery.java +++ b/src/main/java/cn/lihongjie/coal/base/dto/CommonQuery.java @@ -1,748 +1,805 @@ package cn.lihongjie.coal.base.dto; import cn.lihongjie.coal.exception.BizException; + import com.google.common.base.Splitter; + import io.vavr.Function4; import io.vavr.Tuple; import io.vavr.Tuple2; + import jakarta.persistence.criteria.*; import jakarta.persistence.metamodel.Attribute; import jakarta.persistence.metamodel.EntityType; -import java.math.BigDecimal; -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.util.*; -import java.util.stream.Collectors; + import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.With; + import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.springframework.core.convert.ConversionService; import org.springframework.data.domain.Sort; import org.springframework.data.jpa.domain.Specification; +import java.math.BigDecimal; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.util.*; +import java.util.stream.Collectors; + @Data public class CommonQuery { - private List items; + public static Map< + Tuple2, + Function4> + map = new HashMap<>(); - private Integer pageNo = 0; + static { + map.put( + Tuple.of("like", String.class), + (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { + return criteriaBuilder.like( + parseKey(root, x.key), "%" + c.convert(x.value, String.class) + "%"); + }); - private Integer pageSize = Integer.MAX_VALUE; + map.put( + Tuple.of("nlike", String.class), + (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { + return criteriaBuilder.notLike( + parseKey(root, x.key), "%" + c.convert(x.value, String.class) + "%"); + }); - private List orders; + map.put( + Tuple.of("null", String.class), + (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { + return criteriaBuilder.isNull(parseKey(root, x.key)); + }); - @Data - public static class Order { + map.put( + Tuple.of("null", Integer.class), + (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { + return criteriaBuilder.isNull(parseKey(root, x.key)); + }); - private final Sort.Direction direction; - private final String property; - } + map.put( + Tuple.of("null", Long.class), + (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { + return criteriaBuilder.isNull(parseKey(root, x.key)); + }); - public List getOrders() { + map.put( + Tuple.of("null", Double.class), + (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { + return criteriaBuilder.isNull(parseKey(root, x.key)); + }); + map.put( + Tuple.of("null", BigDecimal.class), + (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { + return criteriaBuilder.isNull(parseKey(root, x.key)); + }); - if (orders == null) { - return new ArrayList<>(); + map.put( + Tuple.of("null", LocalDate.class), + (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { + return criteriaBuilder.isNull(parseKey(root, x.key)); + }); + map.put( + Tuple.of("null", LocalDateTime.class), + (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { + return criteriaBuilder.isNull(parseKey(root, x.key)); + }); + + map.put( + Tuple.of("nnull", String.class), + (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { + return criteriaBuilder.isNotNull(parseKey(root, x.key)); + }); + + map.put( + Tuple.of("nnull", Integer.class), + (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { + return criteriaBuilder.isNotNull(parseKey(root, x.key)); + }); + + map.put( + Tuple.of("nnull", Long.class), + (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { + return criteriaBuilder.isNotNull(parseKey(root, x.key)); + }); + + map.put( + Tuple.of("nnull", Double.class), + (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { + return criteriaBuilder.isNotNull(parseKey(root, x.key)); + }); + map.put( + Tuple.of("nnull", BigDecimal.class), + (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { + return criteriaBuilder.isNotNull(parseKey(root, x.key)); + }); + + map.put( + Tuple.of("nnull", LocalDate.class), + (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { + return criteriaBuilder.isNotNull(parseKey(root, x.key)); + }); + map.put( + Tuple.of("nnull", LocalDateTime.class), + (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { + return criteriaBuilder.isNotNull(parseKey(root, x.key)); + }); + + map.put( + Tuple.of("eq", String.class), + (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { + return criteriaBuilder.equal( + parseKey(root, x.key), c.convert(x.value, String.class)); + }); + + map.put( + Tuple.of("eq", Integer.class), + (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { + return criteriaBuilder.equal( + parseKey(root, x.key), c.convert(x.value, Integer.class)); + }); + + map.put( + Tuple.of("eq", Long.class), + (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { + return criteriaBuilder.equal( + parseKey(root, x.key), c.convert(x.value, Long.class)); + }); + + map.put( + Tuple.of("eq", Double.class), + (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { + return criteriaBuilder.equal( + parseKey(root, x.key), c.convert(x.value, Double.class)); + }); + map.put( + Tuple.of("eq", BigDecimal.class), + (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { + return criteriaBuilder.equal( + parseKey(root, x.key), c.convert(x.value, BigDecimal.class)); + }); + + map.put( + Tuple.of("eq", LocalDate.class), + (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { + return criteriaBuilder.equal( + parseKey(root, x.key), c.convert(x.value, LocalDate.class)); + }); + map.put( + Tuple.of("eq", LocalDateTime.class), + (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { + return criteriaBuilder.equal( + parseKey(root, x.key), c.convert(x.value, LocalDateTime.class)); + }); + + map.put( + Tuple.of("neq", String.class), + (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { + return criteriaBuilder.notEqual( + parseKey(root, x.key), c.convert(x.value, String.class)); + }); + + map.put( + Tuple.of("neq", Integer.class), + (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { + return criteriaBuilder.notEqual( + parseKey(root, x.key), c.convert(x.value, Integer.class)); + }); + + map.put( + Tuple.of("neq", Long.class), + (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { + return criteriaBuilder.notEqual( + parseKey(root, x.key), c.convert(x.value, Long.class)); + }); + + map.put( + Tuple.of("neq", Double.class), + (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { + return criteriaBuilder.notEqual( + parseKey(root, x.key), c.convert(x.value, Double.class)); + }); + map.put( + Tuple.of("neq", BigDecimal.class), + (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { + return criteriaBuilder.notEqual( + parseKey(root, x.key), c.convert(x.value, BigDecimal.class)); + }); + + map.put( + Tuple.of("neq", LocalDate.class), + (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { + return criteriaBuilder.notEqual( + parseKey(root, x.key), c.convert(x.value, LocalDate.class)); + }); + map.put( + Tuple.of("neq", LocalDateTime.class), + (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { + return criteriaBuilder.notEqual( + parseKey(root, x.key), c.convert(x.value, LocalDateTime.class)); + }); + + map.put( + Tuple.of("between", String.class), + (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { + return criteriaBuilder.between( + parseKey(root, x.key), + c.convert(x.min, String.class), + c.convert(x.max, String.class)); + }); + + map.put( + Tuple.of("between", Integer.class), + (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { + return criteriaBuilder.between( + parseKey(root, x.key), + c.convert(x.min, Integer.class), + c.convert(x.max, Integer.class)); + }); + + map.put( + Tuple.of("between", Long.class), + (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { + return criteriaBuilder.between( + parseKey(root, x.key), + c.convert(x.min, Long.class), + c.convert(x.max, Long.class)); + }); + + map.put( + Tuple.of("between", Double.class), + (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { + return criteriaBuilder.between( + parseKey(root, x.key), + c.convert(x.min, Double.class), + c.convert(x.max, Double.class)); + }); + map.put( + Tuple.of("between", BigDecimal.class), + (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { + return criteriaBuilder.between( + parseKey(root, x.key), + c.convert(x.min, BigDecimal.class), + c.convert(x.max, BigDecimal.class)); + }); + + map.put( + Tuple.of("between", LocalDate.class), + (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { + return criteriaBuilder.between( + parseKey(root, x.key), + c.convert(x.min, LocalDate.class), + c.convert(x.max, LocalDate.class)); + }); + map.put( + Tuple.of("between", LocalDateTime.class), + (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { + return criteriaBuilder.between( + parseKey(root, x.key), + c.convert(x.min, LocalDateTime.class), + c.convert(x.max, LocalDateTime.class)); + }); + + map.put( + Tuple.of("lt", String.class), + (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { + return criteriaBuilder.lessThan( + parseKey(root, x.key), c.convert(x.value, String.class)); + }); + + map.put( + Tuple.of("lt", Integer.class), + (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { + return criteriaBuilder.lessThan( + parseKey(root, x.key), c.convert(x.value, Integer.class)); + }); + + map.put( + Tuple.of("lt", Long.class), + (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { + return criteriaBuilder.lessThan( + parseKey(root, x.key), c.convert(x.value, Long.class)); + }); + + map.put( + Tuple.of("lt", Double.class), + (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { + return criteriaBuilder.lessThan( + parseKey(root, x.key), c.convert(x.value, Double.class)); + }); + map.put( + Tuple.of("lt", BigDecimal.class), + (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { + return criteriaBuilder.lessThan( + parseKey(root, x.key), c.convert(x.value, BigDecimal.class)); + }); + + map.put( + Tuple.of("lt", LocalDate.class), + (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { + return criteriaBuilder.lessThan( + parseKey(root, x.key), c.convert(x.value, LocalDate.class)); + }); + map.put( + Tuple.of("lt", LocalDateTime.class), + (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { + return criteriaBuilder.lessThan( + parseKey(root, x.key), c.convert(x.value, LocalDateTime.class)); + }); + + map.put( + Tuple.of("le", String.class), + (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { + return criteriaBuilder.lessThanOrEqualTo( + parseKey(root, x.key), c.convert(x.value, String.class)); + }); + + map.put( + Tuple.of("le", Integer.class), + (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { + return criteriaBuilder.lessThanOrEqualTo( + parseKey(root, x.key), c.convert(x.value, Integer.class)); + }); + + map.put( + Tuple.of("le", Long.class), + (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { + return criteriaBuilder.lessThanOrEqualTo( + parseKey(root, x.key), c.convert(x.value, Long.class)); + }); + + map.put( + Tuple.of("le", Double.class), + (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { + return criteriaBuilder.lessThanOrEqualTo( + parseKey(root, x.key), c.convert(x.value, Double.class)); + }); + map.put( + Tuple.of("le", BigDecimal.class), + (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { + return criteriaBuilder.lessThanOrEqualTo( + parseKey(root, x.key), c.convert(x.value, BigDecimal.class)); + }); + + map.put( + Tuple.of("le", LocalDate.class), + (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { + return criteriaBuilder.lessThanOrEqualTo( + parseKey(root, x.key), c.convert(x.value, LocalDate.class)); + }); + map.put( + Tuple.of("le", LocalDateTime.class), + (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { + return criteriaBuilder.lessThanOrEqualTo( + parseKey(root, x.key), c.convert(x.value, LocalDateTime.class)); + }); + + map.put( + Tuple.of("gt", String.class), + (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { + return criteriaBuilder.greaterThan( + parseKey(root, x.key), c.convert(x.value, String.class)); + }); + + map.put( + Tuple.of("gt", Integer.class), + (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { + return criteriaBuilder.greaterThan( + parseKey(root, x.key), c.convert(x.value, Integer.class)); + }); + + map.put( + Tuple.of("gt", Long.class), + (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { + return criteriaBuilder.greaterThan( + parseKey(root, x.key), c.convert(x.value, Long.class)); + }); + + map.put( + Tuple.of("gt", Double.class), + (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { + return criteriaBuilder.greaterThan( + parseKey(root, x.key), c.convert(x.value, Double.class)); + }); + map.put( + Tuple.of("gt", BigDecimal.class), + (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { + return criteriaBuilder.greaterThan( + parseKey(root, x.key), c.convert(x.value, BigDecimal.class)); + }); + + map.put( + Tuple.of("gt", LocalDate.class), + (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { + return criteriaBuilder.greaterThan( + parseKey(root, x.key), c.convert(x.value, LocalDate.class)); + }); + map.put( + Tuple.of("gt", LocalDateTime.class), + (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { + return criteriaBuilder.greaterThan( + parseKey(root, x.key), c.convert(x.value, LocalDateTime.class)); + }); + + map.put( + Tuple.of("ge", String.class), + (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { + return criteriaBuilder.greaterThanOrEqualTo( + parseKey(root, x.key), c.convert(x.value, String.class)); + }); + + map.put( + Tuple.of("ge", Integer.class), + (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { + return criteriaBuilder.greaterThanOrEqualTo( + parseKey(root, x.key), c.convert(x.value, Integer.class)); + }); + + map.put( + Tuple.of("ge", Long.class), + (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { + return criteriaBuilder.greaterThanOrEqualTo( + parseKey(root, x.key), c.convert(x.value, Long.class)); + }); + + map.put( + Tuple.of("ge", Double.class), + (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { + return criteriaBuilder.greaterThanOrEqualTo( + parseKey(root, x.key), c.convert(x.value, Double.class)); + }); + map.put( + Tuple.of("ge", BigDecimal.class), + (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { + return criteriaBuilder.greaterThanOrEqualTo( + parseKey(root, x.key), c.convert(x.value, BigDecimal.class)); + }); + + map.put( + Tuple.of("ge", LocalDate.class), + (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { + return criteriaBuilder.greaterThanOrEqualTo( + parseKey(root, x.key), c.convert(x.value, LocalDate.class)); + }); + map.put( + Tuple.of("ge", LocalDateTime.class), + (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { + return criteriaBuilder.greaterThanOrEqualTo( + parseKey(root, x.key), c.convert(x.value, LocalDateTime.class)); + }); + + map.put( + Tuple.of("empty", List.class), + (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { + return criteriaBuilder.isEmpty(parseKey(root, x.key)); + }); + + map.put( + Tuple.of("nempty", List.class), + (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { + return criteriaBuilder.isNotEmpty(parseKey(root, x.key)); + }); + + map.put( + Tuple.of("in", String.class), + (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { + return criteriaBuilder + .in(parseKey(root, x.key)) + .in( + Arrays.stream(x.value.split(",")) + .map(i -> c.convert(i, String.class)) + .toList()); + }); + + map.put( + Tuple.of("in", Integer.class), + (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { + return criteriaBuilder + .in(parseKey(root, x.key)) + .in( + Arrays.stream(x.value.split(",")) + .map(i -> c.convert(i, Integer.class)) + .toList()); + }); + + map.put( + Tuple.of("in", Long.class), + (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { + return criteriaBuilder + .in(parseKey(root, x.key)) + .in( + Arrays.stream(x.value.split(",")) + .map(i -> c.convert(i, Long.class)) + .toList()); + }); + + map.put( + Tuple.of("in", Double.class), + (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { + return criteriaBuilder + .in(parseKey(root, x.key)) + .in( + Arrays.stream(x.value.split(",")) + .map(i -> c.convert(i, Double.class)) + .toList()); + }); + map.put( + Tuple.of("in", BigDecimal.class), + (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { + return criteriaBuilder + .in(parseKey(root, x.key)) + .in( + Arrays.stream(x.value.split(",")) + .map(i -> c.convert(i, BigDecimal.class)) + .toList()); + }); + + map.put( + Tuple.of("in", LocalDate.class), + (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { + return criteriaBuilder + .in(parseKey(root, x.key)) + .in( + Arrays.stream(x.value.split(",")) + .map(i -> c.convert(i, LocalDate.class)) + .toList()); + }); + map.put( + Tuple.of("in", LocalDateTime.class), + (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { + return criteriaBuilder + .in(parseKey(root, x.key)) + .in( + Arrays.stream(x.value.split(",")) + .map(i -> c.convert(i, LocalDateTime.class)) + .toList()); + }); + + map.put( + Tuple.of("nin", String.class), + (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { + return criteriaBuilder + .in(parseKey(root, x.key)) + .in( + Arrays.stream(x.value.split(",")) + .map(i -> c.convert(i, String.class)) + .toList()) + .not(); + }); + + map.put( + Tuple.of("nin", Integer.class), + (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { + return criteriaBuilder + .in(parseKey(root, x.key)) + .in( + Arrays.stream(x.value.split(",")) + .map(i -> c.convert(i, Integer.class)) + .toList()) + .not(); + }); + + map.put( + Tuple.of("nin", Long.class), + (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { + return criteriaBuilder + .in(parseKey(root, x.key)) + .in( + Arrays.stream(x.value.split(",")) + .map(i -> c.convert(i, Long.class)) + .toList()) + .not(); + }); + + map.put( + Tuple.of("nin", Double.class), + (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { + return criteriaBuilder + .in(parseKey(root, x.key)) + .in( + Arrays.stream(x.value.split(",")) + .map(i -> c.convert(i, Double.class)) + .toList()) + .not(); + }); + map.put( + Tuple.of("nin", BigDecimal.class), + (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { + return criteriaBuilder + .in(parseKey(root, x.key)) + .in( + Arrays.stream(x.value.split(",")) + .map(i -> c.convert(i, BigDecimal.class)) + .toList()) + .not(); + }); + + map.put( + Tuple.of("nin", LocalDate.class), + (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { + return criteriaBuilder + .in(parseKey(root, x.key)) + .in( + Arrays.stream(x.value.split(",")) + .map(i -> c.convert(i, LocalDate.class)) + .toList()) + .not(); + }); + map.put( + Tuple.of("nin", LocalDateTime.class), + (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { + return criteriaBuilder + .in(parseKey(root, x.key)) + .in( + Arrays.stream(x.value.split(",")) + .map(i -> c.convert(i, LocalDateTime.class)) + .toList()) + .not(); + }); } - return orders.stream().map(x -> new Sort.Order(x.direction, x.property)).toList(); - } - - @Data - @With - @AllArgsConstructor - public static class QueryItem { - private String key; - private String opt; - private String value; - @Builder.Default private String group = "default"; - private String min; - private String max; - } - - public static Path parseKey(Root root, String key) { - Iterable parts = Splitter.on(".").trimResults().omitEmptyStrings().split(key); - - Path p = null; - for (String part : parts) { - if (p == null) { - p = root.get(part); - } else { - p = p.get(part); - } - } - return p; - } - - public static Map< - Tuple2, - Function4> - map = new HashMap<>(); - - static { - map.put( - Tuple.of("like", String.class), - (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { - return criteriaBuilder.like( - parseKey(root, x.key), "%" + c.convert(x.value, String.class) + "%"); - }); - - map.put( - Tuple.of("nlike", String.class), - (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { - return criteriaBuilder.notLike( - parseKey(root, x.key), "%" + c.convert(x.value, String.class) + "%"); - }); - - map.put( - Tuple.of("null", String.class), - (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { - return criteriaBuilder.isNull(parseKey(root, x.key)); - }); - - map.put( - Tuple.of("null", Integer.class), - (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { - return criteriaBuilder.isNull(parseKey(root, x.key)); - }); - - map.put( - Tuple.of("null", Long.class), - (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { - return criteriaBuilder.isNull(parseKey(root, x.key)); - }); - - map.put( - Tuple.of("null", Double.class), - (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { - return criteriaBuilder.isNull(parseKey(root, x.key)); - }); - map.put( - Tuple.of("null", BigDecimal.class), - (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { - return criteriaBuilder.isNull(parseKey(root, x.key)); - }); - - map.put( - Tuple.of("null", LocalDate.class), - (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { - return criteriaBuilder.isNull(parseKey(root, x.key)); - }); - map.put( - Tuple.of("null", LocalDateTime.class), - (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { - return criteriaBuilder.isNull(parseKey(root, x.key)); - }); - - map.put( - Tuple.of("nnull", String.class), - (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { - return criteriaBuilder.isNotNull(parseKey(root, x.key)); - }); - - map.put( - Tuple.of("nnull", Integer.class), - (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { - return criteriaBuilder.isNotNull(parseKey(root, x.key)); - }); - - map.put( - Tuple.of("nnull", Long.class), - (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { - return criteriaBuilder.isNotNull(parseKey(root, x.key)); - }); - - map.put( - Tuple.of("nnull", Double.class), - (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { - return criteriaBuilder.isNotNull(parseKey(root, x.key)); - }); - map.put( - Tuple.of("nnull", BigDecimal.class), - (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { - return criteriaBuilder.isNotNull(parseKey(root, x.key)); - }); - - map.put( - Tuple.of("nnull", LocalDate.class), - (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { - return criteriaBuilder.isNotNull(parseKey(root, x.key)); - }); - map.put( - Tuple.of("nnull", LocalDateTime.class), - (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { - return criteriaBuilder.isNotNull(parseKey(root, x.key)); - }); - - map.put( - Tuple.of("eq", String.class), - (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { - return criteriaBuilder.equal(parseKey(root, x.key), c.convert(x.value, String.class)); - }); - - map.put( - Tuple.of("eq", Integer.class), - (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { - return criteriaBuilder.equal(parseKey(root, x.key), c.convert(x.value, Integer.class)); - }); - - map.put( - Tuple.of("eq", Long.class), - (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { - return criteriaBuilder.equal(parseKey(root, x.key), c.convert(x.value, Long.class)); - }); - - map.put( - Tuple.of("eq", Double.class), - (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { - return criteriaBuilder.equal(parseKey(root, x.key), c.convert(x.value, Double.class)); - }); - map.put( - Tuple.of("eq", BigDecimal.class), - (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { - return criteriaBuilder.equal(parseKey(root, x.key), c.convert(x.value, BigDecimal.class)); - }); - - map.put( - Tuple.of("eq", LocalDate.class), - (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { - return criteriaBuilder.equal(parseKey(root, x.key), c.convert(x.value, LocalDate.class)); - }); - map.put( - Tuple.of("eq", LocalDateTime.class), - (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { - return criteriaBuilder.equal( - parseKey(root, x.key), c.convert(x.value, LocalDateTime.class)); - }); - - map.put( - Tuple.of("neq", String.class), - (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { - return criteriaBuilder.notEqual(parseKey(root, x.key), c.convert(x.value, String.class)); - }); - - map.put( - Tuple.of("neq", Integer.class), - (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { - return criteriaBuilder.notEqual(parseKey(root, x.key), c.convert(x.value, Integer.class)); - }); - - map.put( - Tuple.of("neq", Long.class), - (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { - return criteriaBuilder.notEqual(parseKey(root, x.key), c.convert(x.value, Long.class)); - }); - - map.put( - Tuple.of("neq", Double.class), - (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { - return criteriaBuilder.notEqual(parseKey(root, x.key), c.convert(x.value, Double.class)); - }); - map.put( - Tuple.of("neq", BigDecimal.class), - (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { - return criteriaBuilder.notEqual( - parseKey(root, x.key), c.convert(x.value, BigDecimal.class)); - }); - - map.put( - Tuple.of("neq", LocalDate.class), - (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { - return criteriaBuilder.notEqual( - parseKey(root, x.key), c.convert(x.value, LocalDate.class)); - }); - map.put( - Tuple.of("neq", LocalDateTime.class), - (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { - return criteriaBuilder.notEqual( - parseKey(root, x.key), c.convert(x.value, LocalDateTime.class)); - }); - - map.put( - Tuple.of("between", String.class), - (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { - return criteriaBuilder.between( - parseKey(root, x.key), - c.convert(x.min, String.class), - c.convert(x.max, String.class)); - }); - - map.put( - Tuple.of("between", Integer.class), - (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { - return criteriaBuilder.between( - parseKey(root, x.key), - c.convert(x.min, Integer.class), - c.convert(x.max, Integer.class)); - }); - - map.put( - Tuple.of("between", Long.class), - (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { - return criteriaBuilder.between( - parseKey(root, x.key), c.convert(x.min, Long.class), c.convert(x.max, Long.class)); - }); - - map.put( - Tuple.of("between", Double.class), - (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { - return criteriaBuilder.between( - parseKey(root, x.key), - c.convert(x.min, Double.class), - c.convert(x.max, Double.class)); - }); - map.put( - Tuple.of("between", BigDecimal.class), - (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { - return criteriaBuilder.between( - parseKey(root, x.key), - c.convert(x.min, BigDecimal.class), - c.convert(x.max, BigDecimal.class)); - }); - - map.put( - Tuple.of("between", LocalDate.class), - (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { - return criteriaBuilder.between( - parseKey(root, x.key), - c.convert(x.min, LocalDate.class), - c.convert(x.max, LocalDate.class)); - }); - map.put( - Tuple.of("between", LocalDateTime.class), - (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { - return criteriaBuilder.between( - parseKey(root, x.key), - c.convert(x.min, LocalDateTime.class), - c.convert(x.max, LocalDateTime.class)); - }); - - map.put( - Tuple.of("lt", String.class), - (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { - return criteriaBuilder.lessThan(parseKey(root, x.key), c.convert(x.value, String.class)); - }); - - map.put( - Tuple.of("lt", Integer.class), - (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { - return criteriaBuilder.lessThan(parseKey(root, x.key), c.convert(x.value, Integer.class)); - }); - - map.put( - Tuple.of("lt", Long.class), - (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { - return criteriaBuilder.lessThan(parseKey(root, x.key), c.convert(x.value, Long.class)); - }); - - map.put( - Tuple.of("lt", Double.class), - (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { - return criteriaBuilder.lessThan(parseKey(root, x.key), c.convert(x.value, Double.class)); - }); - map.put( - Tuple.of("lt", BigDecimal.class), - (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { - return criteriaBuilder.lessThan( - parseKey(root, x.key), c.convert(x.value, BigDecimal.class)); - }); - - map.put( - Tuple.of("lt", LocalDate.class), - (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { - return criteriaBuilder.lessThan( - parseKey(root, x.key), c.convert(x.value, LocalDate.class)); - }); - map.put( - Tuple.of("lt", LocalDateTime.class), - (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { - return criteriaBuilder.lessThan( - parseKey(root, x.key), c.convert(x.value, LocalDateTime.class)); - }); - - map.put( - Tuple.of("le", String.class), - (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { - return criteriaBuilder.lessThanOrEqualTo( - parseKey(root, x.key), c.convert(x.value, String.class)); - }); - - map.put( - Tuple.of("le", Integer.class), - (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { - return criteriaBuilder.lessThanOrEqualTo( - parseKey(root, x.key), c.convert(x.value, Integer.class)); - }); - - map.put( - Tuple.of("le", Long.class), - (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { - return criteriaBuilder.lessThanOrEqualTo( - parseKey(root, x.key), c.convert(x.value, Long.class)); - }); - - map.put( - Tuple.of("le", Double.class), - (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { - return criteriaBuilder.lessThanOrEqualTo( - parseKey(root, x.key), c.convert(x.value, Double.class)); - }); - map.put( - Tuple.of("le", BigDecimal.class), - (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { - return criteriaBuilder.lessThanOrEqualTo( - parseKey(root, x.key), c.convert(x.value, BigDecimal.class)); - }); - - map.put( - Tuple.of("le", LocalDate.class), - (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { - return criteriaBuilder.lessThanOrEqualTo( - parseKey(root, x.key), c.convert(x.value, LocalDate.class)); - }); - map.put( - Tuple.of("le", LocalDateTime.class), - (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { - return criteriaBuilder.lessThanOrEqualTo( - parseKey(root, x.key), c.convert(x.value, LocalDateTime.class)); - }); - - map.put( - Tuple.of("gt", String.class), - (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { - return criteriaBuilder.greaterThan( - parseKey(root, x.key), c.convert(x.value, String.class)); - }); - - map.put( - Tuple.of("gt", Integer.class), - (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { - return criteriaBuilder.greaterThan( - parseKey(root, x.key), c.convert(x.value, Integer.class)); - }); - - map.put( - Tuple.of("gt", Long.class), - (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { - return criteriaBuilder.greaterThan(parseKey(root, x.key), c.convert(x.value, Long.class)); - }); - - map.put( - Tuple.of("gt", Double.class), - (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { - return criteriaBuilder.greaterThan( - parseKey(root, x.key), c.convert(x.value, Double.class)); - }); - map.put( - Tuple.of("gt", BigDecimal.class), - (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { - return criteriaBuilder.greaterThan( - parseKey(root, x.key), c.convert(x.value, BigDecimal.class)); - }); - - map.put( - Tuple.of("gt", LocalDate.class), - (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { - return criteriaBuilder.greaterThan( - parseKey(root, x.key), c.convert(x.value, LocalDate.class)); - }); - map.put( - Tuple.of("gt", LocalDateTime.class), - (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { - return criteriaBuilder.greaterThan( - parseKey(root, x.key), c.convert(x.value, LocalDateTime.class)); - }); - - map.put( - Tuple.of("ge", String.class), - (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { - return criteriaBuilder.greaterThanOrEqualTo( - parseKey(root, x.key), c.convert(x.value, String.class)); - }); - - map.put( - Tuple.of("ge", Integer.class), - (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { - return criteriaBuilder.greaterThanOrEqualTo( - parseKey(root, x.key), c.convert(x.value, Integer.class)); - }); - - map.put( - Tuple.of("ge", Long.class), - (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { - return criteriaBuilder.greaterThanOrEqualTo( - parseKey(root, x.key), c.convert(x.value, Long.class)); - }); - - map.put( - Tuple.of("ge", Double.class), - (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { - return criteriaBuilder.greaterThanOrEqualTo( - parseKey(root, x.key), c.convert(x.value, Double.class)); - }); - map.put( - Tuple.of("ge", BigDecimal.class), - (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { - return criteriaBuilder.greaterThanOrEqualTo( - parseKey(root, x.key), c.convert(x.value, BigDecimal.class)); - }); - - map.put( - Tuple.of("ge", LocalDate.class), - (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { - return criteriaBuilder.greaterThanOrEqualTo( - parseKey(root, x.key), c.convert(x.value, LocalDate.class)); - }); - map.put( - Tuple.of("ge", LocalDateTime.class), - (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { - return criteriaBuilder.greaterThanOrEqualTo( - parseKey(root, x.key), c.convert(x.value, LocalDateTime.class)); - }); - - map.put( - Tuple.of("empty", List.class), - (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { - return criteriaBuilder.isEmpty(parseKey(root, x.key)); - }); - - map.put( - Tuple.of("nempty", List.class), - (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { - return criteriaBuilder.isNotEmpty(parseKey(root, x.key)); - }); - - map.put( - Tuple.of("in", String.class), - (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { - return criteriaBuilder - .in(parseKey(root, x.key)) - .in(Arrays.stream(x.value.split(",")).map(i -> c.convert(i, String.class)).toList()); - }); - - map.put( - Tuple.of("in", Integer.class), - (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { - return criteriaBuilder - .in(parseKey(root, x.key)) - .in(Arrays.stream(x.value.split(",")).map(i -> c.convert(i, Integer.class)).toList()); - }); - - map.put( - Tuple.of("in", Long.class), - (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { - return criteriaBuilder - .in(parseKey(root, x.key)) - .in(Arrays.stream(x.value.split(",")).map(i -> c.convert(i, Long.class)).toList()); - }); - - map.put( - Tuple.of("in", Double.class), - (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { - return criteriaBuilder - .in(parseKey(root, x.key)) - .in(Arrays.stream(x.value.split(",")).map(i -> c.convert(i, Double.class)).toList()); - }); - map.put( - Tuple.of("in", BigDecimal.class), - (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { - return criteriaBuilder - .in(parseKey(root, x.key)) - .in( - Arrays.stream(x.value.split(",")) - .map(i -> c.convert(i, BigDecimal.class)) - .toList()); - }); - - map.put( - Tuple.of("in", LocalDate.class), - (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { - return criteriaBuilder - .in(parseKey(root, x.key)) - .in( - Arrays.stream(x.value.split(",")) - .map(i -> c.convert(i, LocalDate.class)) - .toList()); - }); - map.put( - Tuple.of("in", LocalDateTime.class), - (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { - return criteriaBuilder - .in(parseKey(root, x.key)) - .in( - Arrays.stream(x.value.split(",")) - .map(i -> c.convert(i, LocalDateTime.class)) - .toList()); - }); - - map.put( - Tuple.of("nin", String.class), - (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { - return criteriaBuilder - .in(parseKey(root, x.key)) - .in(Arrays.stream(x.value.split(",")).map(i -> c.convert(i, String.class)).toList()) - .not(); - }); - - map.put( - Tuple.of("nin", Integer.class), - (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { - return criteriaBuilder - .in(parseKey(root, x.key)) - .in(Arrays.stream(x.value.split(",")).map(i -> c.convert(i, Integer.class)).toList()) - .not(); - }); - - map.put( - Tuple.of("nin", Long.class), - (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { - return criteriaBuilder - .in(parseKey(root, x.key)) - .in(Arrays.stream(x.value.split(",")).map(i -> c.convert(i, Long.class)).toList()) - .not(); - }); - - map.put( - Tuple.of("nin", Double.class), - (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { - return criteriaBuilder - .in(parseKey(root, x.key)) - .in(Arrays.stream(x.value.split(",")).map(i -> c.convert(i, Double.class)).toList()) - .not(); - }); - map.put( - Tuple.of("nin", BigDecimal.class), - (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { - return criteriaBuilder - .in(parseKey(root, x.key)) - .in( - Arrays.stream(x.value.split(",")) - .map(i -> c.convert(i, BigDecimal.class)) - .toList()) - .not(); - }); - - map.put( - Tuple.of("nin", LocalDate.class), - (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { - return criteriaBuilder - .in(parseKey(root, x.key)) - .in( - Arrays.stream(x.value.split(",")) - .map(i -> c.convert(i, LocalDate.class)) - .toList()) - .not(); - }); - map.put( - Tuple.of("nin", LocalDateTime.class), - (Root root, CriteriaBuilder criteriaBuilder, QueryItem x, ConversionService c) -> { - return criteriaBuilder - .in(parseKey(root, x.key)) - .in( - Arrays.stream(x.value.split(",")) - .map(i -> c.convert(i, LocalDateTime.class)) - .toList()) - .not(); - }); - } - - public Specification specification(ConversionService conversionService) { - - return new Specification() { - @Override - public Predicate toPredicate( - Root root, CriteriaQuery query, CriteriaBuilder criteriaBuilder) { - - if (CollectionUtils.isNotEmpty(items)) { - - items.forEach(x -> x.setGroup(StringUtils.defaultIfBlank(x.getGroup(), "default"))); - - Map> group = - items.stream().collect(Collectors.groupingBy(i -> i.group)); - - List orPredicates = new ArrayList<>(); - for (List queryItems : group.values()) { - - Predicate[] predicates = - queryItems.stream() - .map(y -> getPredicate(root, criteriaBuilder, y, conversionService)) - .toArray(Predicate[]::new); - - orPredicates.add(criteriaBuilder.and(predicates)); - } - - return criteriaBuilder.or(orPredicates.toArray(new Predicate[0])); - - } else { - - return criteriaBuilder.equal(criteriaBuilder.literal(1), 1); + private List items; + private Integer pageNo = 0; + private Integer pageSize = Integer.MAX_VALUE; + private List orders; + + public static Path parseKey(Root root, String key) { + Iterable parts = Splitter.on(".").trimResults().omitEmptyStrings().split(key); + + Path p = null; + for (String part : parts) { + if (p == null) { + p = root.get(part); + } else { + p = p.get(part); + } } - } - }; - } - - private static Predicate getPredicate( - Root root, - CriteriaBuilder criteriaBuilder, - QueryItem x, - ConversionService conversionService) { - - if (x.key.contains(".")) { - - Function4 function4 = - map.get(Tuple.of(x.opt, String.class)); - - if (function4 == null) { - throw new RuntimeException("无法识别的查询 " + x); - } - - return function4.apply(root, criteriaBuilder, x, conversionService); + return p; } - EntityType entityType = root.getModel(); + private static Predicate getPredicate( + Root root, + CriteriaBuilder criteriaBuilder, + QueryItem x, + ConversionService conversionService) { - Attribute attribute = entityType.getAttribute(x.key); - switch (attribute.getPersistentAttributeType()) { - case BASIC -> { - Class javaType = attribute.getJavaType(); + if (x.key.contains(".")) { - Function4 function4 = - map.get(Tuple.of(x.opt, javaType)); + Function4 function4 = + map.get(Tuple.of(x.opt, String.class)); - if (function4 == null) { - throw new RuntimeException("无法识别的查询 " + x); + if (function4 == null) { + throw new RuntimeException("无法识别的查询 " + x); + } + + return function4.apply(root, criteriaBuilder, x, conversionService); } - return function4.apply(root, criteriaBuilder, x, conversionService); - } - case ONE_TO_ONE -> { - Function4 function4 = - map.get(Tuple.of(x.opt, String.class)); + EntityType entityType = root.getModel(); - if (function4 == null) { - throw new RuntimeException("无法识别的查询 " + x); + Attribute attribute = entityType.getAttribute(x.key); + switch (attribute.getPersistentAttributeType()) { + case BASIC -> { + Class javaType = attribute.getJavaType(); + + Function4 + function4 = map.get(Tuple.of(x.opt, javaType)); + + if (function4 == null) { + throw new RuntimeException("无法识别的查询 " + x); + } + + return function4.apply(root, criteriaBuilder, x, conversionService); + } + case ONE_TO_ONE -> { + Function4 + function4 = map.get(Tuple.of(x.opt, String.class)); + + if (function4 == null) { + throw new RuntimeException("无法识别的查询 " + x); + } + + return function4.apply( + root, + criteriaBuilder, + x.withKey(x.getKey() + "." + "id"), + conversionService); + } + case MANY_TO_ONE -> { + Function4 + function4 = map.get(Tuple.of(x.opt, String.class)); + + if (function4 == null) { + throw new RuntimeException("无法识别的查询 " + x); + } + + return function4.apply( + root, + criteriaBuilder, + x.withKey(x.getKey() + "." + "id"), + conversionService); + } + + default -> { + throw new BizException("不支持的持久化类型查询 " + attribute.getPersistentAttributeType()); + } } - - return function4.apply( - root, criteriaBuilder, x.withKey(x.getKey() + "." + "id"), conversionService); - } - case MANY_TO_ONE -> { - Function4 function4 = - map.get(Tuple.of(x.opt, String.class)); - - if (function4 == null) { - throw new RuntimeException("无法识别的查询 " + x); - } - - return function4.apply( - root, criteriaBuilder, x.withKey(x.getKey() + "." + "id"), conversionService); - } - - default -> { - throw new BizException("不支持的持久化类型查询 " + attribute.getPersistentAttributeType()); - } } - } + + public List getOrders() { + + if (orders == null) { + return new ArrayList<>(); + } + + return orders.stream().map(x -> new Sort.Order(x.direction, x.property)).toList(); + } + + public Specification specification(ConversionService conversionService) { + + return new Specification() { + @Override + public Predicate toPredicate( + Root root, CriteriaQuery query, CriteriaBuilder criteriaBuilder) { + + if (CollectionUtils.isNotEmpty(items)) { + + items.forEach( + x -> x.setGroup(StringUtils.defaultIfBlank(x.getGroup(), "default"))); + + Map> group = + items.stream().collect(Collectors.groupingBy(i -> i.group)); + + List orPredicates = new ArrayList<>(); + for (List queryItems : group.values()) { + + Predicate[] predicates = + queryItems.stream() + .map( + y -> + getPredicate( + root, + criteriaBuilder, + y, + conversionService)) + .toArray(Predicate[]::new); + + orPredicates.add(criteriaBuilder.and(predicates)); + } + + return criteriaBuilder.or(orPredicates.toArray(new Predicate[0])); + + } else { + + return criteriaBuilder.equal(criteriaBuilder.literal(1), 1); + } + } + }; + } + + @Data + public static class Order { + + private final Sort.Direction direction; + private final String property; + } + + @Data + @With + @AllArgsConstructor + public static class QueryItem { + private String key; + private String opt; + private String value; + @Builder.Default private String group = "default"; + private String min; + private String max; + } } diff --git a/src/main/java/cn/lihongjie/coal/base/dto/IdRequest.java b/src/main/java/cn/lihongjie/coal/base/dto/IdRequest.java index e998976c..50402ab7 100644 --- a/src/main/java/cn/lihongjie/coal/base/dto/IdRequest.java +++ b/src/main/java/cn/lihongjie/coal/base/dto/IdRequest.java @@ -1,29 +1,32 @@ package cn.lihongjie.coal.base.dto; +import lombok.Data; + +import org.apache.commons.collections4.CollectionUtils; +import org.apache.commons.lang3.StringUtils; + import java.util.ArrayList; import java.util.Arrays; +import java.util.Collections; import java.util.List; -import lombok.Data; -import org.apache.commons.collections4.CollectionUtils; -import org.apache.commons.lang3.StringUtils; @Data public class IdRequest { - private String id; - private List ids; + private String id; + private List ids; - public List getIds() { + public List getIds() { - if (StringUtils.isEmpty(id)) { - return ids; - } else if (CollectionUtils.isEmpty(ids)) { - return Arrays.asList(id); - } else { + if (StringUtils.isEmpty(id)) { + return ids; + } else if (CollectionUtils.isEmpty(ids)) { + return Collections.singletonList(id); + } else { - ArrayList dup = new ArrayList<>(ids); - dup.add(id); - return dup; + ArrayList dup = new ArrayList<>(ids); + dup.add(id); + return dup; + } } - } } diff --git a/src/main/java/cn/lihongjie/coal/base/dto/OrgCommonDto.java b/src/main/java/cn/lihongjie/coal/base/dto/OrgCommonDto.java index f2f9604a..405ee316 100644 --- a/src/main/java/cn/lihongjie/coal/base/dto/OrgCommonDto.java +++ b/src/main/java/cn/lihongjie/coal/base/dto/OrgCommonDto.java @@ -6,5 +6,5 @@ import lombok.Setter; @Getter @Setter public class OrgCommonDto extends CommonDto { - private String organizationId; + private String organizationId; } diff --git a/src/main/java/cn/lihongjie/coal/base/dto/R.java b/src/main/java/cn/lihongjie/coal/base/dto/R.java index 0fbceed8..0032e57b 100644 --- a/src/main/java/cn/lihongjie/coal/base/dto/R.java +++ b/src/main/java/cn/lihongjie/coal/base/dto/R.java @@ -2,50 +2,51 @@ package cn.lihongjie.coal.base.dto; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; + import lombok.Data; @Data public class R { - private T data; + private T data; - private String code; + private String code; - private String msg; + private String msg; - @JsonInclude(Include.NON_NULL) - private Integer pageNo; + @JsonInclude(Include.NON_NULL) + private Integer pageNo; - @JsonInclude(Include.NON_NULL) - private Integer pageSize; + @JsonInclude(Include.NON_NULL) + private Integer pageSize; - @JsonInclude(Include.NON_NULL) - private Integer totalPage; + @JsonInclude(Include.NON_NULL) + private Integer totalPage; - @JsonInclude(Include.NON_NULL) - private Integer totalCount; + @JsonInclude(Include.NON_NULL) + private Integer totalCount; - public R(T data, String code, String msg) { - this.data = data; - this.code = code; - this.msg = msg; - } + public R(T data, String code, String msg) { + this.data = data; + this.code = code; + this.msg = msg; + } - public R() {} + public R() {} - public static R success() { - return success(null); - } + public static R success() { + return success(null); + } - public static R success(T data) { - return create(data, "ok", ""); - } + public static R success(T data) { + return create(data, "ok", ""); + } - public static R fail(String code, String msg) { - return create(null, code, msg); - } + public static R fail(String code, String msg) { + return create(null, code, msg); + } - public static R create(T data, String code, String msg) { + public static R create(T data, String code, String msg) { - return new R<>(data, code, msg); - } + return new R<>(data, code, msg); + } } diff --git a/src/main/java/cn/lihongjie/coal/base/dto/TreeDto.java b/src/main/java/cn/lihongjie/coal/base/dto/TreeDto.java index 934418c9..21fc35b2 100644 --- a/src/main/java/cn/lihongjie/coal/base/dto/TreeDto.java +++ b/src/main/java/cn/lihongjie/coal/base/dto/TreeDto.java @@ -5,159 +5,163 @@ import cn.lihongjie.coal.base.entity.CommonEntity; import cn.lihongjie.coal.common.ReflectUtils; import cn.lihongjie.coal.dictionary.dto.DictionaryItemDto; import cn.lihongjie.coal.dictionary.entity.DictionaryItemEntity; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.stream.Stream; -import java.util.stream.StreamSupport; + import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.stream.Stream; +import java.util.stream.StreamSupport; + @Data @AllArgsConstructor @NoArgsConstructor public class TreeDto { - private String id; + private String id; - private String code; + private String code; - private String name; + private String name; - private List children; + private List children; - public static List buildList(Object object, boolean flatten) { + public static List buildList(Object object, boolean flatten) { - List ans; + List ans; - if (object instanceof Iterable) { + if (object instanceof Iterable) { - ans = buildList0((Iterable) object); - } else { + ans = buildList0((Iterable) object); + } else { - ans = buildList0(Arrays.asList(object)); + ans = buildList0(Collections.singletonList(object)); + } + + if (flatten) { + ans = flatten(ans); + } + return ans; } - if (flatten) { - ans = flatten(ans); - } - return ans; - } + private static List flatten(List ans) { - private static List flatten(List ans) { + return ans.stream() + .flatMap( + x -> { + if (x == null) { + return Stream.empty(); + } - return ans.stream() - .flatMap( - x -> { - if (x == null) { - return Stream.empty(); - } + if (x.getChildren() != null) { - if (x.getChildren() != null) { - - return Stream.concat(Stream.of(x), flatten(x.getChildren()).stream()); - } else { - return Stream.of(x); - } - }) - .toList(); - } - - private static List buildList0(Iterable object) { - - return StreamSupport.stream(object.spliterator(), false).map(x -> buildTree(x)).toList(); - } - - public static TreeDto buildTree(Object x) { - - if (x == null) { - return null; + return Stream.concat( + Stream.of(x), flatten(x.getChildren()).stream()); + } else { + return Stream.of(x); + } + }) + .toList(); } - TreeDto dto = new TreeDto(); + private static List buildList0(Iterable object) { - dto.setId(getId(x)); - dto.setName(getName(x)); - dto.setCode(getCode(x)); - dto.setChildren(getChildren(x)); - return dto; - } - - private static List getChildren(Object x) { - - if (x instanceof TreeDto) { - return ((TreeDto) x).getChildren().stream().map(TreeDto::buildTree).toList(); + return StreamSupport.stream(object.spliterator(), false).map(x -> buildTree(x)).toList(); } - Object c = ReflectUtils.getFieldValue(x, "children"); + public static TreeDto buildTree(Object x) { - if (c == null) { - return new ArrayList<>(); + if (x == null) { + return null; + } + + TreeDto dto = new TreeDto(); + + dto.setId(getId(x)); + dto.setName(getName(x)); + dto.setCode(getCode(x)); + dto.setChildren(getChildren(x)); + return dto; } - if (c instanceof Iterable) { - return buildList0((Iterable) c); + private static List getChildren(Object x) { + + if (x instanceof TreeDto) { + return ((TreeDto) x).getChildren().stream().map(TreeDto::buildTree).toList(); + } + + Object c = ReflectUtils.getFieldValue(x, "children"); + + if (c == null) { + return new ArrayList<>(); + } + + if (c instanceof Iterable) { + return buildList0((Iterable) c); + } + + return buildList0(List.of(c)); } - return buildList0(Arrays.asList(c)); - } + private static String getCode(Object x) { + if (x instanceof CommonEntity) { + return ((CommonEntity) x).getCode(); + } - private static String getCode(Object x) { - if (x instanceof CommonEntity) { - return ((CommonEntity) x).getCode(); + if (x instanceof CommonDto) { + return ((CommonDto) x).getCode(); + } + + if (x instanceof TreeDto) { + return ((TreeDto) x).getCode(); + } + + return ReflectUtils.getFieldValue(x, "code") + ""; } - if (x instanceof CommonDto) { - return ((CommonDto) x).getCode(); + private static String getName(Object x) { + + if (x instanceof CommonEntity) { + return ((CommonEntity) x).getName(); + } + + if (x instanceof CommonDto) { + return ((CommonDto) x).getName(); + } + + if (x instanceof TreeDto) { + return ((TreeDto) x).getName(); + } + + return ReflectUtils.getFieldValue(x, "name") + ""; } - if (x instanceof TreeDto) { - return ((TreeDto) x).getCode(); + private static String getId(Object x) { + + if (x instanceof DictionaryItemEntity) { + return ((DictionaryItemEntity) x).getCode(); + } + + if (x instanceof DictionaryItemDto) { + return ((DictionaryItemDto) x).getCode(); + } + + if (x instanceof BaseEntity) { + return ((BaseEntity) x).getId(); + } + + if (x instanceof BaseDto) { + return ((BaseDto) x).getId(); + } + + if (x instanceof TreeDto) { + return ((TreeDto) x).getId(); + } + + return ReflectUtils.getFieldValue(x, "id") + ""; } - - return ReflectUtils.getFieldValue(x, "code") + ""; - } - - private static String getName(Object x) { - - if (x instanceof CommonEntity) { - return ((CommonEntity) x).getName(); - } - - if (x instanceof CommonDto) { - return ((CommonDto) x).getName(); - } - - if (x instanceof TreeDto) { - return ((TreeDto) x).getName(); - } - - return ReflectUtils.getFieldValue(x, "name") + ""; - } - - private static String getId(Object x) { - - if (x instanceof DictionaryItemEntity) { - return ((DictionaryItemEntity) x).getCode(); - } - - if (x instanceof DictionaryItemDto) { - return ((DictionaryItemDto) x).getCode(); - } - - if (x instanceof BaseEntity) { - return ((BaseEntity) x).getId(); - } - - if (x instanceof BaseDto) { - return ((BaseDto) x).getId(); - } - - if (x instanceof TreeDto) { - return ((TreeDto) x).getId(); - } - - return ReflectUtils.getFieldValue(x, "id") + ""; - } } diff --git a/src/main/java/cn/lihongjie/coal/base/entity/BaseEntity.java b/src/main/java/cn/lihongjie/coal/base/entity/BaseEntity.java index a82030c2..a95c5b25 100644 --- a/src/main/java/cn/lihongjie/coal/base/entity/BaseEntity.java +++ b/src/main/java/cn/lihongjie/coal/base/entity/BaseEntity.java @@ -1,60 +1,64 @@ package cn.lihongjie.coal.base.entity; import cn.lihongjie.coal.common.Ctx; + import jakarta.persistence.*; -import java.time.LocalDateTime; + import lombok.Getter; import lombok.Setter; + import org.apache.commons.lang3.StringUtils; import org.hibernate.annotations.*; +import java.time.LocalDateTime; + @MappedSuperclass @Getter @Setter @DynamicUpdate public class BaseEntity { - @Id - @GeneratedValue(strategy = GenerationType.UUID) - private String id; + @Id + @GeneratedValue(strategy = GenerationType.UUID) + private String id; - @Comment("创建用户ID") - private String createUserId; + @Comment("创建用户ID") + private String createUserId; - @Formula("(select tu.name from t_user tu where tu.id = create_user_id)") - private String createUserName; + @Formula("(select tu.name from t_user tu where tu.id = create_user_id)") + private String createUserName; - @Comment("创建时间") - @CreationTimestamp(source = SourceType.VM) - private LocalDateTime createTime; + @Comment("创建时间") + @CreationTimestamp(source = SourceType.VM) + private LocalDateTime createTime; - @Comment("更新用户ID") - private String updateUserId; + @Comment("更新用户ID") + private String updateUserId; - @Formula("((select tu.name from t_user tu where tu.id = create_user_id))") - private String updateUserName; + @Formula("((select tu.name from t_user tu where tu.id = create_user_id))") + private String updateUserName; - @Comment("更新时间") - @UpdateTimestamp(source = SourceType.VM) - private LocalDateTime updateTime; + @Comment("更新时间") + @UpdateTimestamp(source = SourceType.VM) + private LocalDateTime updateTime; - @PrePersist - public void prePersist() { - if (StringUtils.isEmpty(this.createUserId)) { + @PrePersist + public void prePersist() { + if (StringUtils.isEmpty(this.createUserId)) { - this.createUserId = Ctx.isLoggedIn() ? Ctx.getUserId() : ""; + this.createUserId = Ctx.isLoggedIn() ? Ctx.getUserId() : ""; + } + + if (this.createTime == null) { + this.createTime = LocalDateTime.now(); + } } - if (this.createTime == null) { - this.createTime = LocalDateTime.now(); + @PreUpdate + public void preUpdate() { + + this.updateUserId = Ctx.isLoggedIn() ? Ctx.getUserId() : ""; + + this.updateTime = LocalDateTime.now(); } - } - - @PreUpdate - public void preUpdate() { - - this.updateUserId = Ctx.isLoggedIn() ? Ctx.getUserId() : ""; - - this.updateTime = LocalDateTime.now(); - } } diff --git a/src/main/java/cn/lihongjie/coal/base/entity/CommonEntity.java b/src/main/java/cn/lihongjie/coal/base/entity/CommonEntity.java index cedb735c..7b3ab7a6 100644 --- a/src/main/java/cn/lihongjie/coal/base/entity/CommonEntity.java +++ b/src/main/java/cn/lihongjie/coal/base/entity/CommonEntity.java @@ -1,44 +1,47 @@ package cn.lihongjie.coal.base.entity; import jakarta.persistence.MappedSuperclass; -import java.util.Objects; + import lombok.Getter; import lombok.Setter; + import org.hibernate.annotations.Comment; +import java.util.Objects; + @MappedSuperclass @Getter @Setter public class CommonEntity extends BaseEntity { - @Comment("名称") - private String name; + @Comment("名称") + private String name; - @Comment("编码") - private String code; + @Comment("编码") + private String code; - @Comment("备注") - private String remarks; + @Comment("备注") + private String remarks; - @Comment("排序键") - private Integer sortKey; + @Comment("排序键") + private Integer sortKey; - @Comment("常用状态 0 禁用 1 启用") - private Integer status; + @Comment("常用状态 0 禁用 1 启用") + private Integer status; - public boolean isDisabled() { - return Objects.equals(status, 0); - } + public boolean isDisabled() { + return Objects.equals(status, 0); + } - @Override - public void prePersist() { - this.status = this.status == null ? 1 : this.status; - super.prePersist(); - } + @Override + public void prePersist() { + this.status = this.status == null ? 1 : this.status; + super.prePersist(); + } - @Override - public void preUpdate() { - this.status = this.status == null ? 1 : this.status; - super.preUpdate(); - } + @Override + public void preUpdate() { + this.status = this.status == null ? 1 : this.status; + super.preUpdate(); + } } diff --git a/src/main/java/cn/lihongjie/coal/base/entity/OrgBaseEntity.java b/src/main/java/cn/lihongjie/coal/base/entity/OrgBaseEntity.java index 8d0973cc..6d760cb5 100644 --- a/src/main/java/cn/lihongjie/coal/base/entity/OrgBaseEntity.java +++ b/src/main/java/cn/lihongjie/coal/base/entity/OrgBaseEntity.java @@ -1,9 +1,12 @@ package cn.lihongjie.coal.base.entity; import cn.lihongjie.coal.common.Ctx; + import jakarta.persistence.*; + import lombok.Getter; import lombok.Setter; + import org.apache.commons.lang3.StringUtils; @MappedSuperclass @@ -11,20 +14,20 @@ import org.apache.commons.lang3.StringUtils; @Setter public class OrgBaseEntity extends BaseEntity { - private String organizationId; + private String organizationId; - @Override - public void prePersist() { - if (StringUtils.isEmpty(organizationId)) { + @Override + public void prePersist() { + if (StringUtils.isEmpty(organizationId)) { - this.organizationId = - Ctx.isLoggedIn() ? Ctx.currentUser().getOrganizationId() : organizationId; + this.organizationId = + Ctx.isLoggedIn() ? Ctx.currentUser().getOrganizationId() : organizationId; + } + super.prePersist(); } - super.prePersist(); - } - @Override - public void preUpdate() { - super.preUpdate(); - } + @Override + public void preUpdate() { + super.preUpdate(); + } } diff --git a/src/main/java/cn/lihongjie/coal/base/entity/OrgCommonEntity.java b/src/main/java/cn/lihongjie/coal/base/entity/OrgCommonEntity.java index 5c825a64..2f6f64c1 100644 --- a/src/main/java/cn/lihongjie/coal/base/entity/OrgCommonEntity.java +++ b/src/main/java/cn/lihongjie/coal/base/entity/OrgCommonEntity.java @@ -1,9 +1,12 @@ package cn.lihongjie.coal.base.entity; import cn.lihongjie.coal.common.Ctx; + import jakarta.persistence.MappedSuperclass; + import lombok.Getter; import lombok.Setter; + import org.apache.commons.lang3.StringUtils; import org.hibernate.annotations.Filter; import org.hibernate.annotations.FilterDef; @@ -16,20 +19,20 @@ import org.hibernate.annotations.ParamDef; @Filter(name = "orgFilter", condition = "organization_id = :organizationId") public class OrgCommonEntity extends CommonEntity { - private String organizationId; + private String organizationId; - @Override - public void prePersist() { - if (StringUtils.isEmpty(organizationId)) { + @Override + public void prePersist() { + if (StringUtils.isEmpty(organizationId)) { - this.organizationId = - Ctx.isLoggedIn() ? Ctx.currentUser().getOrganizationId() : organizationId; + this.organizationId = + Ctx.isLoggedIn() ? Ctx.currentUser().getOrganizationId() : organizationId; + } + super.prePersist(); } - super.prePersist(); - } - @Override - public void preUpdate() { - super.preUpdate(); - } + @Override + public void preUpdate() { + super.preUpdate(); + } } diff --git a/src/main/java/cn/lihongjie/coal/base/mapper/BaseMapper.java b/src/main/java/cn/lihongjie/coal/base/mapper/BaseMapper.java index 30dd221b..917833da 100644 --- a/src/main/java/cn/lihongjie/coal/base/mapper/BaseMapper.java +++ b/src/main/java/cn/lihongjie/coal/base/mapper/BaseMapper.java @@ -3,13 +3,13 @@ package cn.lihongjie.coal.base.mapper; import org.mapstruct.MappingTarget; public interface BaseMapper { - Entity copy(Entity i); + Entity copy(Entity i); - Dto copyDto(Dto i); + Dto copyDto(Dto i); - Dto toDto(Entity user); + Dto toDto(Entity user); - Entity toEntity(Create request); + Entity toEntity(Create request); - void updateEntity(@MappingTarget Entity entity, Update dto); + void updateEntity(@MappingTarget Entity entity, Update dto); } diff --git a/src/main/java/cn/lihongjie/coal/base/mapper/CommonMapper.java b/src/main/java/cn/lihongjie/coal/base/mapper/CommonMapper.java index 85583a37..2fe7d940 100644 --- a/src/main/java/cn/lihongjie/coal/base/mapper/CommonMapper.java +++ b/src/main/java/cn/lihongjie/coal/base/mapper/CommonMapper.java @@ -13,150 +13,151 @@ import cn.lihongjie.coal.script.entity.ScriptEntity; import cn.lihongjie.coal.supplier.entity.SupplierEntity; import cn.lihongjie.coal.syslog.entity.SysLogEntity; import cn.lihongjie.coal.user.entity.UserEntity; + import org.apache.commons.lang3.StringUtils; import org.mapstruct.Mapper; @Mapper(componentModel = "spring") public interface CommonMapper { - public default Integer toInt(String s) { - try { + default Integer toInt(String s) { + try { - return Integer.valueOf(s); - } catch (Exception e) { - return null; + return Integer.valueOf(s); + } catch (Exception e) { + return null; + } } - } - public default UserEntity createUser(String id) { + default UserEntity createUser(String id) { - if (StringUtils.isEmpty(id)) { - return null; + if (StringUtils.isEmpty(id)) { + return null; + } + UserEntity user = new UserEntity(); + + user.setId(id); + + return user; } - UserEntity user = new UserEntity(); - user.setId(id); + default DictionaryEntity createDictionary(String id) { - return user; - } - - public default DictionaryEntity createDictionary(String id) { - - if (StringUtils.isEmpty(id)) { - return null; + if (StringUtils.isEmpty(id)) { + return null; + } + DictionaryEntity e = new DictionaryEntity(); + e.setId(id); + return e; } - DictionaryEntity e = new DictionaryEntity(); - e.setId(id); - return e; - } - public default DictionaryItemEntity createDictionaryItem(String id) { + default DictionaryItemEntity createDictionaryItem(String id) { - if (StringUtils.isEmpty(id)) { - return null; + if (StringUtils.isEmpty(id)) { + return null; + } + DictionaryItemEntity e = new DictionaryItemEntity(); + e.setId(id); + return e; } - DictionaryItemEntity e = new DictionaryItemEntity(); - e.setId(id); - return e; - } - public default SysLogEntity createOperat(String id) { + default SysLogEntity createOperat(String id) { - if (StringUtils.isEmpty(id)) { - return null; + if (StringUtils.isEmpty(id)) { + return null; + } + SysLogEntity e = new SysLogEntity(); + e.setId(id); + return e; } - SysLogEntity e = new SysLogEntity(); - e.setId(id); - return e; - } - public default OrganizationEntity createOrganization(String id) { + default OrganizationEntity createOrganization(String id) { - if (StringUtils.isEmpty(id)) { - return null; + if (StringUtils.isEmpty(id)) { + return null; + } + OrganizationEntity e = new OrganizationEntity(); + e.setId(id); + return e; } - OrganizationEntity e = new OrganizationEntity(); - e.setId(id); - return e; - } - public default PermissionEntity createPermission(String id) { + default PermissionEntity createPermission(String id) { - if (StringUtils.isEmpty(id)) { - return null; + if (StringUtils.isEmpty(id)) { + return null; + } + PermissionEntity e = new PermissionEntity(); + e.setId(id); + return e; } - PermissionEntity e = new PermissionEntity(); - e.setId(id); - return e; - } - public default ResourceEntity createResource(String id) { + default ResourceEntity createResource(String id) { - if (StringUtils.isEmpty(id)) { - return null; + if (StringUtils.isEmpty(id)) { + return null; + } + ResourceEntity e = new ResourceEntity(); + e.setId(id); + return e; } - ResourceEntity e = new ResourceEntity(); - e.setId(id); - return e; - } - public default RoleEntity createRole(String id) { + default RoleEntity createRole(String id) { - if (StringUtils.isEmpty(id)) { + if (StringUtils.isEmpty(id)) { - return null; + return null; + } + RoleEntity e = new RoleEntity(); + e.setId(id); + return e; } - RoleEntity e = new RoleEntity(); - e.setId(id); - return e; - } - public default ScriptEntity createScript(String id) { + default ScriptEntity createScript(String id) { - if (StringUtils.isEmpty(id)) { + if (StringUtils.isEmpty(id)) { - return null; + return null; + } + ScriptEntity e = new ScriptEntity(); + e.setId(id); + return e; } - ScriptEntity e = new ScriptEntity(); - e.setId(id); - return e; - } - public default SupplierEntity createSupplier(String id) { + default SupplierEntity createSupplier(String id) { - if (StringUtils.isEmpty(id)) { + if (StringUtils.isEmpty(id)) { - return null; + return null; + } + SupplierEntity e = new SupplierEntity(); + e.setId(id); + return e; } - SupplierEntity e = new SupplierEntity(); - e.setId(id); - return e; - } - public default CoalInfoEntity createCoalInfo(String id) { + default CoalInfoEntity createCoalInfo(String id) { - if (StringUtils.isEmpty(id)) { + if (StringUtils.isEmpty(id)) { - return null; + return null; + } + CoalInfoEntity e = new CoalInfoEntity(); + e.setId(id); + return e; } - CoalInfoEntity e = new CoalInfoEntity(); - e.setId(id); - return e; - } - public default String toString(Object o) { + default String toString(Object o) { - if (o == null) { - return null; - } else if (o instanceof String) { - return ((String) o); - } else if (o instanceof BaseEntity) { - return ((BaseEntity) o).getId(); + if (o == null) { + return null; + } else if (o instanceof String) { + return ((String) o); + } else if (o instanceof BaseEntity) { + return ((BaseEntity) o).getId(); - } else if (o instanceof BaseDto) { - return ((BaseDto) o).getId(); - } else { - return o.toString(); + } else if (o instanceof BaseDto) { + return ((BaseDto) o).getId(); + } else { + return o.toString(); + } } - } } diff --git a/src/main/java/cn/lihongjie/coal/base/service/BaseService.java b/src/main/java/cn/lihongjie/coal/base/service/BaseService.java index b34e8428..feb4bb49 100644 --- a/src/main/java/cn/lihongjie/coal/base/service/BaseService.java +++ b/src/main/java/cn/lihongjie/coal/base/service/BaseService.java @@ -2,52 +2,54 @@ package cn.lihongjie.coal.base.service; import cn.lihongjie.coal.base.dao.BaseRepository; import cn.lihongjie.coal.base.entity.BaseEntity; -import java.util.List; + 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 java.util.List; + public abstract class BaseService< - Entity extends BaseEntity, Repository extends BaseRepository> { + Entity extends BaseEntity, Repository extends BaseRepository> { - @Autowired Repository dao; + @Autowired Repository dao; - public Entity get(String id) { + public Entity get(String id) { - return dao.get(id); - } + return dao.get(id); + } - public void save(Entity entity) { + public void save(Entity entity) { - dao.save(entity); - } + dao.save(entity); + } - public void delete(String id) { - dao.deleteById(id); - } + public void delete(String id) { + dao.deleteById(id); + } - public void delete(List id) { - dao.deleteAllById(id); - } + public void delete(List id) { + dao.deleteAllById(id); + } - public Page findAll(Specification spec, Pageable page) { - return dao.findAll(spec, page); - } + public Page findAll(Specification spec, Pageable page) { + return dao.findAll(spec, page); + } - public List findAll(Specification spec) { - return dao.findAll(spec); - } + public List findAll(Specification spec) { + return dao.findAll(spec); + } - public List findAll() { - return dao.findAll(); - } + public List findAll() { + return dao.findAll(); + } - public Long count(Specification spec) { - return dao.count(spec); - } + public Long count(Specification spec) { + return dao.count(spec); + } - public Long count() { - return dao.count(); - } + public Long count() { + return dao.count(); + } } diff --git a/src/main/java/cn/lihongjie/coal/coal/CoalConstraint.java b/src/main/java/cn/lihongjie/coal/coal/CoalConstraint.java index 593a9432..d5cc8ea2 100644 --- a/src/main/java/cn/lihongjie/coal/coal/CoalConstraint.java +++ b/src/main/java/cn/lihongjie/coal/coal/CoalConstraint.java @@ -5,9 +5,9 @@ import lombok.Data; @Data public class CoalConstraint { - private String code; - private Double min; - private Double max; - private Integer priority; - private Integer order; + private String code; + private Double min; + private Double max; + private Integer priority; + private Integer order; } diff --git a/src/main/java/cn/lihongjie/coal/coal/CoalController.java b/src/main/java/cn/lihongjie/coal/coal/CoalController.java index e4ff5c4a..2a375c8c 100644 --- a/src/main/java/cn/lihongjie/coal/coal/CoalController.java +++ b/src/main/java/cn/lihongjie/coal/coal/CoalController.java @@ -4,29 +4,31 @@ import cn.lihongjie.coal.annotation.Anonymous; import cn.lihongjie.coal.base.controller.BaseController; import cn.lihongjie.coal.coalBlend.dto.CoalBlendRequest; import cn.lihongjie.coal.coalBlend.dto.CoalBlendResult; -import java.util.List; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; +import java.util.List; + @RestController @RequestMapping("/coal") @Anonymous public class CoalController extends BaseController { - @Autowired CoalService coalService; + @Autowired CoalService coalService; - @PostMapping("/blend") - public CoalBlendResult blend(@RequestBody CoalBlendRequest request) { + @PostMapping("/blend") + public CoalBlendResult blend(@RequestBody CoalBlendRequest request) { - return coalService.blend(request); - } + return coalService.blend(request); + } - @PostMapping("/params") - public List params() { + @PostMapping("/params") + public List params() { - return coalService.paramDefs(); - } + return coalService.paramDefs(); + } } diff --git a/src/main/java/cn/lihongjie/coal/coal/CoalInfo.java b/src/main/java/cn/lihongjie/coal/coal/CoalInfo.java index 367934b4..ac6fa089 100644 --- a/src/main/java/cn/lihongjie/coal/coal/CoalInfo.java +++ b/src/main/java/cn/lihongjie/coal/coal/CoalInfo.java @@ -1,61 +1,67 @@ package cn.lihongjie.coal.coal; import com.fasterxml.jackson.annotation.JsonIgnore; + +import lombok.Data; + import java.util.List; import java.util.Map; import java.util.stream.Collectors; -import lombok.Data; @Data public class CoalInfo { - private String id; + private String id; - private String name; + private String name; - /** 配煤比例明细 */ - private List percents; + /** 配煤比例明细 */ + private List percents; - private Integer min = 1; - private Integer max = 99; + private Integer min = 1; + private Integer max = 99; - private List parameters; + private List parameters; - @JsonIgnore private Map parameterMap; + @JsonIgnore private Map parameterMap; - public Map getParameterMap() { + public Map getParameterMap() { - if (parameterMap == null) { + if (parameterMap == null) { - parameterMap = parameters.stream().collect(Collectors.toMap(e -> e.getCode(), e -> e)); + parameterMap = parameters.stream().collect(Collectors.toMap(e -> e.getCode(), e -> e)); + } + + return parameterMap; } - return parameterMap; - } + public Double getParamVal(String code) { - public Double getParamVal(String code) { + CoalParameter coalParameter = getParameterMap().get(code); + return coalParameter == null ? null : coalParameter.getValue(); + } - CoalParameter coalParameter = getParameterMap().get(code); - return coalParameter == null ? null : coalParameter.getValue(); - } + public String rowString() { - public String rowString() { + String percentString = + percents.stream() + .map( + x -> + String.format( + "%5s %-3s(%1s)", + x.getName(), x.getPercent(), x.getPercent2())) + .collect(Collectors.joining("\t")); + String paramString = + parameters.stream() + .map(x -> String.format("%5s:%-6.2f", x.getCode(), x.getValue())) + .collect(Collectors.joining("\t")); - String percentString = - percents.stream() - .map(x -> String.format("%5s %-3s(%1s)", x.getName(), x.getPercent(), x.getPercent2())) - .collect(Collectors.joining("\t")); - String paramString = - parameters.stream() - .map(x -> String.format("%5s:%-6.2f", x.getCode(), x.getValue())) - .collect(Collectors.joining("\t")); + return String.format("%s\t%20s\t%s", name, percentString, paramString); + } - return String.format("%s\t%20s\t%s", name, percentString, paramString); - } + public void calPercent2() { - public void calPercent2() { + // percents.stream().reduce(x -> x.) - // percents.stream().reduce(x -> x.) - - } + } } diff --git a/src/main/java/cn/lihongjie/coal/coal/CoalParameter.java b/src/main/java/cn/lihongjie/coal/coal/CoalParameter.java index be822202..aa6b1085 100644 --- a/src/main/java/cn/lihongjie/coal/coal/CoalParameter.java +++ b/src/main/java/cn/lihongjie/coal/coal/CoalParameter.java @@ -5,7 +5,7 @@ import lombok.Data; @Data public class CoalParameter { - private String code; + private String code; - private Double value; + private Double value; } diff --git a/src/main/java/cn/lihongjie/coal/coal/CoalParameterDef.java b/src/main/java/cn/lihongjie/coal/coal/CoalParameterDef.java index 523895cd..4d022928 100644 --- a/src/main/java/cn/lihongjie/coal/coal/CoalParameterDef.java +++ b/src/main/java/cn/lihongjie/coal/coal/CoalParameterDef.java @@ -4,9 +4,9 @@ import lombok.Data; @Data public class CoalParameterDef { - private String code; - private String name; - private String desc; - private Integer status; - private Integer order; + private String code; + private String name; + private String desc; + private Integer status; + private Integer order; } diff --git a/src/main/java/cn/lihongjie/coal/coal/CoalPercent.java b/src/main/java/cn/lihongjie/coal/coal/CoalPercent.java index 15b35ab7..9c3329c5 100644 --- a/src/main/java/cn/lihongjie/coal/coal/CoalPercent.java +++ b/src/main/java/cn/lihongjie/coal/coal/CoalPercent.java @@ -4,12 +4,12 @@ import lombok.Data; @Data public class CoalPercent { - private String id; + private String id; - private String name; + private String name; - private Long percent; + private Long percent; - /** gcd之后的比例 */ - private Long percent2; + /** gcd之后的比例 */ + private Long percent2; } diff --git a/src/main/java/cn/lihongjie/coal/coal/CoalService.java b/src/main/java/cn/lihongjie/coal/coal/CoalService.java index 103babd8..efeeafab 100644 --- a/src/main/java/cn/lihongjie/coal/coal/CoalService.java +++ b/src/main/java/cn/lihongjie/coal/coal/CoalService.java @@ -3,11 +3,21 @@ package cn.lihongjie.coal.coal; import cn.lihongjie.coal.coalBlend.dto.CoalBlendRequest; import cn.lihongjie.coal.coalBlend.dto.CoalBlendResult; import cn.lihongjie.coal.exception.BizException; + import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.ortools.Loader; import com.google.ortools.sat.*; + +import lombok.SneakyThrows; +import lombok.extern.slf4j.Slf4j; + +import org.apache.commons.collections.CollectionUtils; +import org.apache.commons.lang3.StringUtils; +import org.springframework.core.io.ClassPathResource; +import org.springframework.stereotype.Service; + import java.io.InputStream; import java.math.BigDecimal; import java.math.RoundingMode; @@ -15,338 +25,342 @@ import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.stream.Collectors; -import lombok.SneakyThrows; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.collections.CollectionUtils; -import org.apache.commons.lang3.StringUtils; -import org.springframework.core.io.ClassPathResource; -import org.springframework.stereotype.Service; @Slf4j @Service public class CoalService { - /** - * 配煤 - * - * @return - */ - public CoalBlendResult blend(CoalBlendRequest request) { + private static List createPercentVars(CoalBlendRequest request, CpModel model) { + int index = 0; - if (CollectionUtils.isEmpty(request.getCoals())) { - throw new BizException("煤不能为空"); + List vars = new ArrayList<>(); + for (CoalInfo coal : request.getCoals()) { + IntVar x = + model.newIntVar( + Math.max(coal.getMin(), 0), + Math.min(coal.getMax(), 100), + "x" + index++); + vars.add(x); + } + return vars; } - if (CollectionUtils.isEmpty(request.getConstraints())) { - throw new BizException("参数配置不能为空"); - } + /** + * 配煤 + * + * @return + */ + public CoalBlendResult blend(CoalBlendRequest request) { - Loader.loadNativeLibraries(); - CoalBlendResult result = new CoalBlendResult(); - - CpModel model = new CpModel(); - - List vars = createPercentVars(request, model); - - // 添加各种约束条件 - addConstrains(request, model, vars); - - // 初始化求解器 - CpSolver cpSolver = new CpSolver(); - cpSolver.setLogCallback(x -> log.info(x)); - SatParameters.Builder parameters = cpSolver.getParameters(); - parameters.setEnumerateAllSolutions(false); - parameters.setMaxTimeInSeconds(request.getMaxTime()); - parameters.setLogSearchProgress(false); - parameters.setFillAdditionalSolutionsInResponse(true); - - // 开始求最优解 - - List sorted = - request.getConstraints().stream() - .filter(x -> x.getPriority() != null) - .sorted(Comparator.comparing(CoalConstraint::getPriority)) - .toList(); - - for (CoalConstraint constraint : sorted) { - - log.info("使用约束 {}", constraint); - - LinearExpr weightedSum = - LinearExpr.weightedSum( - vars.toArray(new IntVar[0]), - request.getCoals().stream() - .mapToLong(x -> (long) (x.getParamVal(constraint.getCode()) * 100)) - .toArray()); - if (constraint.getOrder() == -1) { - model.maximize(weightedSum); - - } else { - model.minimize(weightedSum); - } - - CpSolverStatus status = cpSolver.solve(model); - - if (status == CpSolverStatus.FEASIBLE || status == CpSolverStatus.OPTIMAL) { - - double constrainVal = cpSolver.objectiveValue(); - - // model.clearHints(); - // - // for (IntVar var : vars) { - // model.addHint(var, cpSolver.value(var)); - // - // } - if (constraint.getOrder() == -1) { - model.addLessOrEqual(weightedSum, (long) constrainVal); - log.info("添加新的条件 sum({}) <= {}", constraint.getCode(), constrainVal); - } else { - model.addGreaterOrEqual(weightedSum, (long) constrainVal); - log.info("添加新的条件 sum({}) >= {}", constraint.getCode(), constrainVal); + if (CollectionUtils.isEmpty(request.getCoals())) { + throw new BizException("煤不能为空"); } - String validate = model.validate(); - log.info(validate); + if (CollectionUtils.isEmpty(request.getConstraints())) { + throw new BizException("参数配置不能为空"); + } - } else { - log.warn("无法求解: " + status); - } - } + Loader.loadNativeLibraries(); + CoalBlendResult result = new CoalBlendResult(); - // 记录结果 + CpModel model = new CpModel(); - // - cpSolver.getParameters().setEnumerateAllSolutions(true); - CpSolverStatus solverStatus = - cpSolver.solve( - model, - new CpSolverSolutionCallback() { - @Override - public void onSolutionCallback() { + List vars = createPercentVars(request, model); - CoalInfo solution = new CoalInfo(); - List gcdVals = new ArrayList<>(); + // 添加各种约束条件 + addConstrains(request, model, vars); - solution.setPercents(new ArrayList<>()); - solution.setParameters(new ArrayList<>()); - for (int i = 0; i < vars.size(); i++) { + // 初始化求解器 + CpSolver cpSolver = new CpSolver(); + cpSolver.setLogCallback(x -> log.info(x)); + SatParameters.Builder parameters = cpSolver.getParameters(); + parameters.setEnumerateAllSolutions(false); + parameters.setMaxTimeInSeconds(request.getMaxTime()); + parameters.setLogSearchProgress(false); + parameters.setFillAdditionalSolutionsInResponse(true); - long percent = this.value(vars.get(i)); + // 开始求最优解 - CoalInfo coal = request.getCoals().get(i); - // 累加 - try { + List sorted = + request.getConstraints().stream() + .filter(x -> x.getPriority() != null) + .sorted(Comparator.comparing(CoalConstraint::getPriority)) + .toList(); - acc(solution, percent, coal); - } catch (Exception e) { - e.printStackTrace(); - } + for (CoalConstraint constraint : sorted) { - CoalPercent e = new CoalPercent(); - e.setId(coal.getId()); - e.setName(coal.getName()); - e.setPercent(percent); - if (CollectionUtils.isNotEmpty(gcdVals)) { - e.setPercent2(gcdVals.get(i)); - } - solution.getPercents().add(e); + log.info("使用约束 {}", constraint); + + LinearExpr weightedSum = + LinearExpr.weightedSum( + vars.toArray(new IntVar[0]), + request.getCoals().stream() + .mapToLong( + x -> (long) (x.getParamVal(constraint.getCode()) * 100)) + .toArray()); + if (constraint.getOrder() == -1) { + model.maximize(weightedSum); + + } else { + model.minimize(weightedSum); + } + + CpSolverStatus status = cpSolver.solve(model); + + if (status == CpSolverStatus.FEASIBLE || status == CpSolverStatus.OPTIMAL) { + + double constrainVal = cpSolver.objectiveValue(); + + // model.clearHints(); + // + // for (IntVar var : vars) { + // model.addHint(var, cpSolver.value(var)); + // + // } + if (constraint.getOrder() == -1) { + model.addLessOrEqual(weightedSum, (long) constrainVal); + log.info("添加新的条件 sum({}) <= {}", constraint.getCode(), constrainVal); + } else { + model.addGreaterOrEqual(weightedSum, (long) constrainVal); + log.info("添加新的条件 sum({}) >= {}", constraint.getCode(), constrainVal); } - // 四舍五入 + String validate = model.validate(); + log.info(validate); - round(solution); - - result.getCoals().add(solution); - } - }); - - sortAndSelect(request, result); - - return result; - } - - private static List createPercentVars(CoalBlendRequest request, CpModel model) { - int index = 0; - - List vars = new ArrayList<>(); - for (CoalInfo coal : request.getCoals()) { - IntVar x = - model.newIntVar(Math.max(coal.getMin(), 0), Math.min(coal.getMax(), 100), "x" + index++); - vars.add(x); - } - return vars; - } - - private void sortAndSelect(CoalBlendRequest request, CoalBlendResult result) { - - List list = - request.getConstraints().stream() - .filter(x -> x.getPriority() != null) - .sorted(Comparator.comparing(x -> x.getPriority())) - .collect(Collectors.toList()); - - Comparator c = Comparator.comparing(x -> 1); - if (!list.isEmpty()) { - - for (CoalConstraint constraint : list) { - - if (constraint.getOrder() == null || constraint.getOrder() == 1) { - c = - c.thenComparing( - Comparator.comparing(x -> x.getParamVal(constraint.getCode()))); - } else { - - c = - c.thenComparing( - Comparator.comparing(x -> x.getParamVal(constraint.getCode())) - .reversed()); + } else { + log.warn("无法求解: " + status); + } } - } + + // 记录结果 + + // + cpSolver.getParameters().setEnumerateAllSolutions(true); + CpSolverStatus solverStatus = + cpSolver.solve( + model, + new CpSolverSolutionCallback() { + @Override + public void onSolutionCallback() { + + CoalInfo solution = new CoalInfo(); + List gcdVals = new ArrayList<>(); + + solution.setPercents(new ArrayList<>()); + solution.setParameters(new ArrayList<>()); + for (int i = 0; i < vars.size(); i++) { + + long percent = this.value(vars.get(i)); + + CoalInfo coal = request.getCoals().get(i); + // 累加 + try { + + acc(solution, percent, coal); + } catch (Exception e) { + e.printStackTrace(); + } + + CoalPercent e = new CoalPercent(); + e.setId(coal.getId()); + e.setName(coal.getName()); + e.setPercent(percent); + if (CollectionUtils.isNotEmpty(gcdVals)) { + e.setPercent2(gcdVals.get(i)); + } + solution.getPercents().add(e); + } + + // 四舍五入 + + round(solution); + + result.getCoals().add(solution); + } + }); + + sortAndSelect(request, result); + + return result; } - result.setCoals( - result.getCoals().stream() - .sorted(c) - .limit(request.getCount()) - .collect(Collectors.toList())); - result.getCoals().forEach(x -> x.calPercent2()); - } + private void sortAndSelect(CoalBlendRequest request, CoalBlendResult result) { - private void round(CoalInfo solution) { + List list = + request.getConstraints().stream() + .filter(x -> x.getPriority() != null) + .sorted(Comparator.comparing(x -> x.getPriority())) + .collect(Collectors.toList()); - solution - .getParameters() - .forEach( - x -> - x.setValue( - x.getValue() == null - ? x.getValue() - : BigDecimal.valueOf(x.getValue()) - .setScale(2, RoundingMode.HALF_UP) - .doubleValue())); - } + Comparator c = Comparator.comparing(x -> 1); + if (!list.isEmpty()) { - private void acc(CoalInfo solution, long percent, CoalInfo coal) { + for (CoalConstraint constraint : list) { - for (CoalParameter parameter : coal.getParameters()) { + if (constraint.getOrder() == null || constraint.getOrder() == 1) { + c = + c.thenComparing( + Comparator.comparing( + x -> x.getParamVal(constraint.getCode()))); + } else { - boolean found = false; - - for (CoalParameter solutionParameter : solution.getParameters()) { - - if (StringUtils.equalsIgnoreCase(parameter.getCode(), solutionParameter.getCode())) { - - solutionParameter.setValue( - solutionParameter.getValue() + (parameter.getValue() * percent / 100.0)); - found = true; - break; + c = + c.thenComparing( + Comparator.comparing( + x -> x.getParamVal(constraint.getCode())) + .reversed()); + } + } } - } + result.setCoals( + result.getCoals().stream() + .sorted(c) + .limit(request.getCount()) + .collect(Collectors.toList())); - if (!found) { - CoalParameter e = new CoalParameter(); - e.setCode(parameter.getCode()); - e.setValue(parameter.getValue() * percent / 100.0); - solution.getParameters().add(e); - } - } - } - - private void addConstrains(CoalBlendRequest request, CpModel model, List vars) { - // 各种煤比例之和为 100 - - model.addEquality(LinearExpr.sum(vars.toArray(new LinearArgument[0])), 100); - - if (request.getType() == 2) { - - IntVar gcd = model.newIntVar(1, 100, "gcd"); - - List varGcdList = new ArrayList<>(); - for (IntVar var : vars) { - - model.addModuloEquality(model.newConstant(0), var, gcd); - - // 定义一个变量,表示 percent / gcd - IntVar varGcd = model.newIntVar(1, 100, var.getName() + "_gcd"); - // 约束这个变量 - model.addDivisionEquality(varGcd, var, gcd); - varGcdList.add(varGcd); - } - - // 约束 sum(percent / gcd) < request.getPercent2Sum() - model.addLessOrEqual( - LinearExpr.sum(varGcdList.toArray(new IntVar[0])), request.getPercent2Sum()); + result.getCoals().forEach(x -> x.calPercent2()); } - for (CoalConstraint constrain : request.getConstraints()) { + private void round(CoalInfo solution) { - if (StringUtils.isBlank(constrain.getCode())) { - continue; - } + solution.getParameters() + .forEach( + x -> + x.setValue( + x.getValue() == null + ? x.getValue() + : BigDecimal.valueOf(x.getValue()) + .setScale(2, RoundingMode.HALF_UP) + .doubleValue())); + } - if (constrain.getMin() == null && constrain.getMax() == null) { - continue; - } - - long[] paramsOfEachCoal = new long[request.getCoals().size()]; - int index = 0; - for (CoalInfo coal : request.getCoals()) { - - boolean found = false; + private void acc(CoalInfo solution, long percent, CoalInfo coal) { for (CoalParameter parameter : coal.getParameters()) { - if (StringUtils.equalsIgnoreCase(parameter.getCode(), constrain.getCode())) { + boolean found = false; - paramsOfEachCoal[index++] = (long) (parameter.getValue() * 100); - found = true; - break; - } + for (CoalParameter solutionParameter : solution.getParameters()) { + + if (StringUtils.equalsIgnoreCase( + parameter.getCode(), solutionParameter.getCode())) { + + solutionParameter.setValue( + solutionParameter.getValue() + + (parameter.getValue() * percent / 100.0)); + found = true; + break; + } + } + + if (!found) { + CoalParameter e = new CoalParameter(); + e.setCode(parameter.getCode()); + e.setValue(parameter.getValue() * percent / 100.0); + solution.getParameters().add(e); + } } - - if (!found) { - - throw new RuntimeException( - String.format( - "煤 %s 没有找到指标 %s, 但是存在条件 %s <= %s <= %s", - coal.getName(), - constrain.getCode(), - constrain.getMin(), - constrain.getCode(), - constrain.getMax())); - } - } - - if (constrain.getMin() != null) { - - model.addGreaterOrEqual( - LinearExpr.weightedSum(vars.toArray(new LinearArgument[0]), paramsOfEachCoal), - (long) ((constrain.getMin()) * 10000)); - } - - if (constrain.getMax() != null) { - - model.addLessOrEqual( - LinearExpr.weightedSum(vars.toArray(new LinearArgument[0]), paramsOfEachCoal), - (long) ((constrain.getMax()) * 10000)); - } - } - } - - @SneakyThrows - public List paramDefs() { - - ClassPathResource classPathResource = new ClassPathResource("/config/CoalParameterDef.json"); - - ObjectMapper mapper = new ObjectMapper(); - mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); - - List coalParameterDefs; - try (InputStream inputStream = classPathResource.getInputStream()) { - coalParameterDefs = - mapper.readValue(inputStream, new TypeReference>() {}); } - return coalParameterDefs; - } + private void addConstrains(CoalBlendRequest request, CpModel model, List vars) { + // 各种煤比例之和为 100 + + model.addEquality(LinearExpr.sum(vars.toArray(new LinearArgument[0])), 100); + + if (request.getType() == 2) { + + IntVar gcd = model.newIntVar(1, 100, "gcd"); + + List varGcdList = new ArrayList<>(); + for (IntVar var : vars) { + + model.addModuloEquality(model.newConstant(0), var, gcd); + + // 定义一个变量,表示 percent / gcd + IntVar varGcd = model.newIntVar(1, 100, var.getName() + "_gcd"); + // 约束这个变量 + model.addDivisionEquality(varGcd, var, gcd); + varGcdList.add(varGcd); + } + + // 约束 sum(percent / gcd) < request.getPercent2Sum() + model.addLessOrEqual( + LinearExpr.sum(varGcdList.toArray(new IntVar[0])), request.getPercent2Sum()); + } + + for (CoalConstraint constrain : request.getConstraints()) { + + if (StringUtils.isBlank(constrain.getCode())) { + continue; + } + + if (constrain.getMin() == null && constrain.getMax() == null) { + continue; + } + + long[] paramsOfEachCoal = new long[request.getCoals().size()]; + int index = 0; + for (CoalInfo coal : request.getCoals()) { + + boolean found = false; + + for (CoalParameter parameter : coal.getParameters()) { + + if (StringUtils.equalsIgnoreCase(parameter.getCode(), constrain.getCode())) { + + paramsOfEachCoal[index++] = (long) (parameter.getValue() * 100); + found = true; + break; + } + } + + if (!found) { + + throw new RuntimeException( + String.format( + "煤 %s 没有找到指标 %s, 但是存在条件 %s <= %s <= %s", + coal.getName(), + constrain.getCode(), + constrain.getMin(), + constrain.getCode(), + constrain.getMax())); + } + } + + if (constrain.getMin() != null) { + + model.addGreaterOrEqual( + LinearExpr.weightedSum( + vars.toArray(new LinearArgument[0]), paramsOfEachCoal), + (long) ((constrain.getMin()) * 10000)); + } + + if (constrain.getMax() != null) { + + model.addLessOrEqual( + LinearExpr.weightedSum( + vars.toArray(new LinearArgument[0]), paramsOfEachCoal), + (long) ((constrain.getMax()) * 10000)); + } + } + } + + @SneakyThrows + public List paramDefs() { + + ClassPathResource classPathResource = + new ClassPathResource("/config/CoalParameterDef.json"); + + ObjectMapper mapper = new ObjectMapper(); + mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); + + List coalParameterDefs; + try (InputStream inputStream = classPathResource.getInputStream()) { + coalParameterDefs = + mapper.readValue(inputStream, new TypeReference>() {}); + } + + return coalParameterDefs; + } } diff --git a/src/main/java/cn/lihongjie/coal/coalAnalysis/controller/CoalAnalysisController.java b/src/main/java/cn/lihongjie/coal/coalAnalysis/controller/CoalAnalysisController.java index cc4b38ce..c96c9c49 100644 --- a/src/main/java/cn/lihongjie/coal/coalAnalysis/controller/CoalAnalysisController.java +++ b/src/main/java/cn/lihongjie/coal/coalAnalysis/controller/CoalAnalysisController.java @@ -8,7 +8,9 @@ import cn.lihongjie.coal.coalAnalysis.dto.CoalAnalysisDto; import cn.lihongjie.coal.coalAnalysis.dto.CreateCoalAnalysisDto; import cn.lihongjie.coal.coalAnalysis.dto.UpdateCoalAnalysisDto; import cn.lihongjie.coal.coalAnalysis.service.CoalAnalysisService; + import lombok.extern.slf4j.Slf4j; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.web.bind.annotation.PostMapping; @@ -22,36 +24,36 @@ import org.springframework.web.bind.annotation.RestController; @Slf4j @OrgScope public class CoalAnalysisController { - @Autowired private CoalAnalysisService service; + @Autowired private CoalAnalysisService service; - @PostMapping("/create") - public CoalAnalysisDto create(@RequestBody CreateCoalAnalysisDto request) { - return this.service.create(request); - } + @PostMapping("/create") + public CoalAnalysisDto create(@RequestBody CreateCoalAnalysisDto request) { + return this.service.create(request); + } - @PostMapping("/calculate") - public CoalAnalysisDto calculate(@RequestBody CoalAnalysisDto request) { - return this.service.calculate(request); - } + @PostMapping("/calculate") + public CoalAnalysisDto calculate(@RequestBody CoalAnalysisDto request) { + return this.service.calculate(request); + } - @PostMapping("/update") - public CoalAnalysisDto update(@RequestBody UpdateCoalAnalysisDto request) { - return this.service.update(request); - } + @PostMapping("/update") + public CoalAnalysisDto update(@RequestBody UpdateCoalAnalysisDto request) { + return this.service.update(request); + } - @PostMapping("/delete") - public Object delete(@RequestBody IdRequest request) { - this.service.delete(request); - return true; - } + @PostMapping("/delete") + public Object delete(@RequestBody IdRequest request) { + this.service.delete(request); + return true; + } - @PostMapping("/getById") - public CoalAnalysisDto getById(@RequestBody String request) { - return this.service.getById(request); - } + @PostMapping("/getById") + public CoalAnalysisDto getById(@RequestBody String request) { + return this.service.getById(request); + } - @PostMapping("/list") - public Page list(@RequestBody CommonQuery request) { - return this.service.list(request); - } + @PostMapping("/list") + public Page list(@RequestBody CommonQuery request) { + return this.service.list(request); + } } diff --git a/src/main/java/cn/lihongjie/coal/coalAnalysis/dto/CoalAnalysisDto.java b/src/main/java/cn/lihongjie/coal/coalAnalysis/dto/CoalAnalysisDto.java index 744f9752..2a5caced 100644 --- a/src/main/java/cn/lihongjie/coal/coalAnalysis/dto/CoalAnalysisDto.java +++ b/src/main/java/cn/lihongjie/coal/coalAnalysis/dto/CoalAnalysisDto.java @@ -2,146 +2,150 @@ package cn.lihongjie.coal.coalAnalysis.dto; import cn.lihongjie.coal.base.dto.OrgCommonDto; import cn.lihongjie.coal.coalInfo.entity.CoalInfoEntity; + import jakarta.validation.constraints.DecimalMin; + +import lombok.Data; + +import org.hibernate.annotations.Comment; + import java.util.HashMap; import java.util.Map; -import lombok.Data; -import org.hibernate.annotations.Comment; @Data public class CoalAnalysisDto extends OrgCommonDto { - @Comment("关联的煤源信息") - private CoalInfoEntity coalInfo; + @Comment("关联的煤源信息") + private CoalInfoEntity coalInfo; - @Comment("参数 1 ") - @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") - private Double param1; + @Comment("参数 1 ") + @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") + private Double param1; - @Comment("参数 2 ") - @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") - private Double param2; + @Comment("参数 2 ") + @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") + private Double param2; - @Comment("参数 3 ") - @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") - private Double param3; + @Comment("参数 3 ") + @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") + private Double param3; - @Comment("参数 4 ") - @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") - private Double param4; + @Comment("参数 4 ") + @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") + private Double param4; - @Comment("参数 5 ") - @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") - private Double param5; + @Comment("参数 5 ") + @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") + private Double param5; - @Comment("参数 6 ") - @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") - private Double param6; + @Comment("参数 6 ") + @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") + private Double param6; - @Comment("参数 7 ") - @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") - private Double param7; + @Comment("参数 7 ") + @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") + private Double param7; - @Comment("参数 8 ") - @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") - private Double param8; + @Comment("参数 8 ") + @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") + private Double param8; - @Comment("参数 9 ") - @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") - private Double param9; + @Comment("参数 9 ") + @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") + private Double param9; - @Comment("参数 10 ") - @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") - private Double param10; + @Comment("参数 10 ") + @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") + private Double param10; - @Comment("参数 11 ") - @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") - private Double param11; + @Comment("参数 11 ") + @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") + private Double param11; - @Comment("参数 12 ") - @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") - private Double param12; + @Comment("参数 12 ") + @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") + private Double param12; - @Comment("参数 13 ") - @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") - private Double param13; + @Comment("参数 13 ") + @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") + private Double param13; - @Comment("参数 14 ") - @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") - private Double param14; + @Comment("参数 14 ") + @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") + private Double param14; - @Comment("参数 15 ") - @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") - private Double param15; + @Comment("参数 15 ") + @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") + private Double param15; - @Comment("参数 16 ") - @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") - private Double param16; + @Comment("参数 16 ") + @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") + private Double param16; - @Comment("参数 17 ") - @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") - private Double param17; + @Comment("参数 17 ") + @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") + private Double param17; - @Comment("参数 18 ") - @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") - private Double param18; + @Comment("参数 18 ") + @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") + private Double param18; - @Comment("参数 19 ") - @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") - private Double param19; + @Comment("参数 19 ") + @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") + private Double param19; - @Comment("参数 20 ") - @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") - private Double param20; + @Comment("参数 20 ") + @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") + private Double param20; - public Map toMap() { + public Map toMap() { - HashMap ma = new HashMap<>(); + HashMap ma = new HashMap<>(); - ma.put("param1", param1); - ma.put("param2", param2); - ma.put("param3", param3); - ma.put("param4", param4); - ma.put("param5", param5); - ma.put("param6", param6); - ma.put("param7", param7); - ma.put("param8", param8); - ma.put("param9", param9); - ma.put("param10", param10); - ma.put("param11", param11); - ma.put("param12", param12); - ma.put("param13", param13); - ma.put("param14", param14); - ma.put("param15", param15); - ma.put("param16", param16); - ma.put("param17", param17); - ma.put("param18", param18); - ma.put("param19", param19); - ma.put("param20", param20); + ma.put("param1", param1); + ma.put("param2", param2); + ma.put("param3", param3); + ma.put("param4", param4); + ma.put("param5", param5); + ma.put("param6", param6); + ma.put("param7", param7); + ma.put("param8", param8); + ma.put("param9", param9); + ma.put("param10", param10); + ma.put("param11", param11); + ma.put("param12", param12); + ma.put("param13", param13); + ma.put("param14", param14); + ma.put("param15", param15); + ma.put("param16", param16); + ma.put("param17", param17); + ma.put("param18", param18); + ma.put("param19", param19); + ma.put("param20", param20); - return ma; - } + return ma; + } - public void updateFromMap(Map map) { + public void updateFromMap(Map map) { - this.param1 = (Double) map.getOrDefault("param1", null); - this.param2 = (Double) map.getOrDefault("param2", null); - this.param3 = (Double) map.getOrDefault("param3", null); - this.param4 = (Double) map.getOrDefault("param4", null); - this.param5 = (Double) map.getOrDefault("param5", null); - this.param6 = (Double) map.getOrDefault("param6", null); - this.param7 = (Double) map.getOrDefault("param7", null); - this.param8 = (Double) map.getOrDefault("param8", null); - this.param9 = (Double) map.getOrDefault("param9", null); - this.param10 = (Double) map.getOrDefault("param10", null); - this.param11 = (Double) map.getOrDefault("param11", null); - this.param12 = (Double) map.getOrDefault("param12", null); - this.param13 = (Double) map.getOrDefault("param13", null); - this.param14 = (Double) map.getOrDefault("param14", null); - this.param15 = (Double) map.getOrDefault("param15", null); - this.param16 = (Double) map.getOrDefault("param16", null); - this.param17 = (Double) map.getOrDefault("param17", null); - this.param18 = (Double) map.getOrDefault("param18", null); - this.param19 = (Double) map.getOrDefault("param19", null); - this.param20 = (Double) map.getOrDefault("param20", null); - } + this.param1 = (Double) map.getOrDefault("param1", null); + this.param2 = (Double) map.getOrDefault("param2", null); + this.param3 = (Double) map.getOrDefault("param3", null); + this.param4 = (Double) map.getOrDefault("param4", null); + this.param5 = (Double) map.getOrDefault("param5", null); + this.param6 = (Double) map.getOrDefault("param6", null); + this.param7 = (Double) map.getOrDefault("param7", null); + this.param8 = (Double) map.getOrDefault("param8", null); + this.param9 = (Double) map.getOrDefault("param9", null); + this.param10 = (Double) map.getOrDefault("param10", null); + this.param11 = (Double) map.getOrDefault("param11", null); + this.param12 = (Double) map.getOrDefault("param12", null); + this.param13 = (Double) map.getOrDefault("param13", null); + this.param14 = (Double) map.getOrDefault("param14", null); + this.param15 = (Double) map.getOrDefault("param15", null); + this.param16 = (Double) map.getOrDefault("param16", null); + this.param17 = (Double) map.getOrDefault("param17", null); + this.param18 = (Double) map.getOrDefault("param18", null); + this.param19 = (Double) map.getOrDefault("param19", null); + this.param20 = (Double) map.getOrDefault("param20", null); + } } diff --git a/src/main/java/cn/lihongjie/coal/coalAnalysis/dto/CreateCoalAnalysisDto.java b/src/main/java/cn/lihongjie/coal/coalAnalysis/dto/CreateCoalAnalysisDto.java index 69c61a15..083ce05b 100644 --- a/src/main/java/cn/lihongjie/coal/coalAnalysis/dto/CreateCoalAnalysisDto.java +++ b/src/main/java/cn/lihongjie/coal/coalAnalysis/dto/CreateCoalAnalysisDto.java @@ -1,92 +1,95 @@ package cn.lihongjie.coal.coalAnalysis.dto; import cn.lihongjie.coal.base.dto.OrgCommonDto; + import jakarta.validation.constraints.DecimalMin; + import lombok.Data; + import org.hibernate.annotations.Comment; @Data public class CreateCoalAnalysisDto extends OrgCommonDto { - @Comment("关联的煤源信息") - private String coalInfo; + @Comment("关联的煤源信息") + private String coalInfo; - @Comment("参数 1 ") - @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") - private Double param1; + @Comment("参数 1 ") + @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") + private Double param1; - @Comment("参数 2 ") - @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") - private Double param2; + @Comment("参数 2 ") + @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") + private Double param2; - @Comment("参数 3 ") - @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") - private Double param3; + @Comment("参数 3 ") + @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") + private Double param3; - @Comment("参数 4 ") - @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") - private Double param4; + @Comment("参数 4 ") + @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") + private Double param4; - @Comment("参数 5 ") - @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") - private Double param5; + @Comment("参数 5 ") + @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") + private Double param5; - @Comment("参数 6 ") - @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") - private Double param6; + @Comment("参数 6 ") + @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") + private Double param6; - @Comment("参数 7 ") - @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") - private Double param7; + @Comment("参数 7 ") + @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") + private Double param7; - @Comment("参数 8 ") - @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") - private Double param8; + @Comment("参数 8 ") + @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") + private Double param8; - @Comment("参数 9 ") - @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") - private Double param9; + @Comment("参数 9 ") + @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") + private Double param9; - @Comment("参数 10 ") - @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") - private Double param10; + @Comment("参数 10 ") + @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") + private Double param10; - @Comment("参数 11 ") - @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") - private Double param11; + @Comment("参数 11 ") + @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") + private Double param11; - @Comment("参数 12 ") - @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") - private Double param12; + @Comment("参数 12 ") + @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") + private Double param12; - @Comment("参数 13 ") - @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") - private Double param13; + @Comment("参数 13 ") + @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") + private Double param13; - @Comment("参数 14 ") - @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") - private Double param14; + @Comment("参数 14 ") + @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") + private Double param14; - @Comment("参数 15 ") - @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") - private Double param15; + @Comment("参数 15 ") + @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") + private Double param15; - @Comment("参数 16 ") - @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") - private Double param16; + @Comment("参数 16 ") + @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") + private Double param16; - @Comment("参数 17 ") - @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") - private Double param17; + @Comment("参数 17 ") + @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") + private Double param17; - @Comment("参数 18 ") - @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") - private Double param18; + @Comment("参数 18 ") + @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") + private Double param18; - @Comment("参数 19 ") - @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") - private Double param19; + @Comment("参数 19 ") + @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") + private Double param19; - @Comment("参数 20 ") - @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") - private Double param20; + @Comment("参数 20 ") + @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") + private Double param20; } diff --git a/src/main/java/cn/lihongjie/coal/coalAnalysis/dto/UpdateCoalAnalysisDto.java b/src/main/java/cn/lihongjie/coal/coalAnalysis/dto/UpdateCoalAnalysisDto.java index a4e028ed..7ed0eae4 100644 --- a/src/main/java/cn/lihongjie/coal/coalAnalysis/dto/UpdateCoalAnalysisDto.java +++ b/src/main/java/cn/lihongjie/coal/coalAnalysis/dto/UpdateCoalAnalysisDto.java @@ -1,92 +1,95 @@ package cn.lihongjie.coal.coalAnalysis.dto; import cn.lihongjie.coal.base.dto.OrgCommonDto; + import jakarta.validation.constraints.DecimalMin; + import lombok.Data; + import org.hibernate.annotations.Comment; @Data public class UpdateCoalAnalysisDto extends OrgCommonDto { - @Comment("关联的煤源信息") - private String coalInfo; + @Comment("关联的煤源信息") + private String coalInfo; - @Comment("参数 1 ") - @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") - private Double param1; + @Comment("参数 1 ") + @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") + private Double param1; - @Comment("参数 2 ") - @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") - private Double param2; + @Comment("参数 2 ") + @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") + private Double param2; - @Comment("参数 3 ") - @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") - private Double param3; + @Comment("参数 3 ") + @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") + private Double param3; - @Comment("参数 4 ") - @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") - private Double param4; + @Comment("参数 4 ") + @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") + private Double param4; - @Comment("参数 5 ") - @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") - private Double param5; + @Comment("参数 5 ") + @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") + private Double param5; - @Comment("参数 6 ") - @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") - private Double param6; + @Comment("参数 6 ") + @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") + private Double param6; - @Comment("参数 7 ") - @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") - private Double param7; + @Comment("参数 7 ") + @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") + private Double param7; - @Comment("参数 8 ") - @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") - private Double param8; + @Comment("参数 8 ") + @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") + private Double param8; - @Comment("参数 9 ") - @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") - private Double param9; + @Comment("参数 9 ") + @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") + private Double param9; - @Comment("参数 10 ") - @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") - private Double param10; + @Comment("参数 10 ") + @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") + private Double param10; - @Comment("参数 11 ") - @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") - private Double param11; + @Comment("参数 11 ") + @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") + private Double param11; - @Comment("参数 12 ") - @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") - private Double param12; + @Comment("参数 12 ") + @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") + private Double param12; - @Comment("参数 13 ") - @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") - private Double param13; + @Comment("参数 13 ") + @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") + private Double param13; - @Comment("参数 14 ") - @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") - private Double param14; + @Comment("参数 14 ") + @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") + private Double param14; - @Comment("参数 15 ") - @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") - private Double param15; + @Comment("参数 15 ") + @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") + private Double param15; - @Comment("参数 16 ") - @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") - private Double param16; + @Comment("参数 16 ") + @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") + private Double param16; - @Comment("参数 17 ") - @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") - private Double param17; + @Comment("参数 17 ") + @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") + private Double param17; - @Comment("参数 18 ") - @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") - private Double param18; + @Comment("参数 18 ") + @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") + private Double param18; - @Comment("参数 19 ") - @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") - private Double param19; + @Comment("参数 19 ") + @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") + private Double param19; - @Comment("参数 20 ") - @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") - private Double param20; + @Comment("参数 20 ") + @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") + private Double param20; } diff --git a/src/main/java/cn/lihongjie/coal/coalAnalysis/entity/CoalAnalysisEntity.java b/src/main/java/cn/lihongjie/coal/coalAnalysis/entity/CoalAnalysisEntity.java index ad15ce26..ab595b5a 100644 --- a/src/main/java/cn/lihongjie/coal/coalAnalysis/entity/CoalAnalysisEntity.java +++ b/src/main/java/cn/lihongjie/coal/coalAnalysis/entity/CoalAnalysisEntity.java @@ -2,96 +2,99 @@ package cn.lihongjie.coal.coalAnalysis.entity; import cn.lihongjie.coal.base.entity.OrgCommonEntity; import cn.lihongjie.coal.coalInfo.entity.CoalInfoEntity; + import jakarta.persistence.Entity; import jakarta.persistence.ManyToOne; import jakarta.validation.constraints.DecimalMin; + import lombok.Data; + import org.hibernate.annotations.Comment; @Data @Entity public class CoalAnalysisEntity extends OrgCommonEntity { - @ManyToOne - @Comment("关联的煤源信息") - private CoalInfoEntity coalInfo; + @ManyToOne + @Comment("关联的煤源信息") + private CoalInfoEntity coalInfo; - @Comment("参数 1 ") - @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") - private Double param1; + @Comment("参数 1 ") + @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") + private Double param1; - @Comment("参数 2 ") - @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") - private Double param2; + @Comment("参数 2 ") + @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") + private Double param2; - @Comment("参数 3 ") - @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") - private Double param3; + @Comment("参数 3 ") + @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") + private Double param3; - @Comment("参数 4 ") - @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") - private Double param4; + @Comment("参数 4 ") + @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") + private Double param4; - @Comment("参数 5 ") - @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") - private Double param5; + @Comment("参数 5 ") + @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") + private Double param5; - @Comment("参数 6 ") - @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") - private Double param6; + @Comment("参数 6 ") + @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") + private Double param6; - @Comment("参数 7 ") - @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") - private Double param7; + @Comment("参数 7 ") + @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") + private Double param7; - @Comment("参数 8 ") - @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") - private Double param8; + @Comment("参数 8 ") + @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") + private Double param8; - @Comment("参数 9 ") - @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") - private Double param9; + @Comment("参数 9 ") + @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") + private Double param9; - @Comment("参数 10 ") - @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") - private Double param10; + @Comment("参数 10 ") + @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") + private Double param10; - @Comment("参数 11 ") - @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") - private Double param11; + @Comment("参数 11 ") + @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") + private Double param11; - @Comment("参数 12 ") - @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") - private Double param12; + @Comment("参数 12 ") + @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") + private Double param12; - @Comment("参数 13 ") - @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") - private Double param13; + @Comment("参数 13 ") + @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") + private Double param13; - @Comment("参数 14 ") - @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") - private Double param14; + @Comment("参数 14 ") + @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") + private Double param14; - @Comment("参数 15 ") - @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") - private Double param15; + @Comment("参数 15 ") + @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") + private Double param15; - @Comment("参数 16 ") - @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") - private Double param16; + @Comment("参数 16 ") + @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") + private Double param16; - @Comment("参数 17 ") - @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") - private Double param17; + @Comment("参数 17 ") + @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") + private Double param17; - @Comment("参数 18 ") - @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") - private Double param18; + @Comment("参数 18 ") + @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") + private Double param18; - @Comment("参数 19 ") - @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") - private Double param19; + @Comment("参数 19 ") + @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") + private Double param19; - @Comment("参数 20 ") - @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") - private Double param20; + @Comment("参数 20 ") + @DecimalMin(value = "0.1", inclusive = true, message = "参数不能小于0.1") + private Double param20; } diff --git a/src/main/java/cn/lihongjie/coal/coalAnalysis/mapper/CoalAnalysisMapper.java b/src/main/java/cn/lihongjie/coal/coalAnalysis/mapper/CoalAnalysisMapper.java index d71ae7e2..b30d0f3b 100644 --- a/src/main/java/cn/lihongjie/coal/coalAnalysis/mapper/CoalAnalysisMapper.java +++ b/src/main/java/cn/lihongjie/coal/coalAnalysis/mapper/CoalAnalysisMapper.java @@ -10,9 +10,12 @@ import org.mapstruct.Mapper; import org.mapstruct.control.DeepClone; @Mapper( - componentModel = org.mapstruct.MappingConstants.ComponentModel.SPRING, - uses = {CommonMapper.class}, - mappingControl = DeepClone.class) + componentModel = org.mapstruct.MappingConstants.ComponentModel.SPRING, + uses = {CommonMapper.class}, + mappingControl = DeepClone.class) public interface CoalAnalysisMapper - extends BaseMapper< - CoalAnalysisEntity, CoalAnalysisDto, CreateCoalAnalysisDto, UpdateCoalAnalysisDto> {} + extends BaseMapper< + CoalAnalysisEntity, + CoalAnalysisDto, + CreateCoalAnalysisDto, + UpdateCoalAnalysisDto> {} diff --git a/src/main/java/cn/lihongjie/coal/coalAnalysis/repository/CoalAnalysisRepository.java b/src/main/java/cn/lihongjie/coal/coalAnalysis/repository/CoalAnalysisRepository.java index 8ce95e98..80903b48 100644 --- a/src/main/java/cn/lihongjie/coal/coalAnalysis/repository/CoalAnalysisRepository.java +++ b/src/main/java/cn/lihongjie/coal/coalAnalysis/repository/CoalAnalysisRepository.java @@ -2,6 +2,7 @@ package cn.lihongjie.coal.coalAnalysis.repository; import cn.lihongjie.coal.base.dao.BaseRepository; import cn.lihongjie.coal.coalAnalysis.entity.CoalAnalysisEntity; + import org.springframework.stereotype.Repository; @Repository diff --git a/src/main/java/cn/lihongjie/coal/coalAnalysis/service/CoalAnalysisService.java b/src/main/java/cn/lihongjie/coal/coalAnalysis/service/CoalAnalysisService.java index c5259ce7..cb07996a 100644 --- a/src/main/java/cn/lihongjie/coal/coalAnalysis/service/CoalAnalysisService.java +++ b/src/main/java/cn/lihongjie/coal/coalAnalysis/service/CoalAnalysisService.java @@ -14,12 +14,9 @@ import cn.lihongjie.coal.coalParameterDef.repository.CoalParameterDefRepository; import cn.lihongjie.coal.common.Ctx; import cn.lihongjie.coal.common.GroovyScriptUtils; import cn.lihongjie.coal.exception.BizException; -import java.math.BigDecimal; -import java.util.Comparator; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; + import lombok.extern.slf4j.Slf4j; + import org.apache.commons.lang3.ObjectUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.math.NumberUtils; @@ -30,82 +27,95 @@ import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Sort; import org.springframework.stereotype.Service; +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.util.Comparator; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + @Service @Slf4j public class CoalAnalysisService extends BaseService { - @Autowired private CoalAnalysisRepository repository; + @Autowired CoalParameterDefRepository coalParameterDefRepository; + @Autowired private CoalAnalysisRepository repository; + @Autowired private CoalAnalysisMapper mapper; + @Autowired private ConversionService conversionService; - @Autowired private CoalAnalysisMapper mapper; + public CoalAnalysisDto create(CreateCoalAnalysisDto request) { + CoalAnalysisEntity entity = mapper.toEntity(request); - @Autowired private ConversionService conversionService; - - public CoalAnalysisDto create(CreateCoalAnalysisDto request) { - CoalAnalysisEntity entity = mapper.toEntity(request); - - this.repository.save(entity); - return getById(entity.getId()); - } - - @Autowired CoalParameterDefRepository coalParameterDefRepository; - - public CoalAnalysisDto calculate(CoalAnalysisDto dto) { - - List parameters = - coalParameterDefRepository.findByOrganizationId(Ctx.currentUser().getOrganizationId()); - - List toCalculate = - parameters.stream() - .filter(x -> StringUtils.equalsIgnoreCase(x.getInputType(), "1")) - .sorted(Comparator.comparing(x -> ObjectUtils.defaultIfNull(x.getPriority(), -1))) - .collect(Collectors.toList()); - - Map map = dto.toMap(); - - for (CoalParameterDefEntity def : toCalculate) { - - Object exec = GroovyScriptUtils.exec(def.getFormula0(), map); - - if (exec != null && !(exec instanceof Number)) { - throw new BizException("计算结果不是数字"); - } - - Double value = exec != null ? NumberUtils.toDouble(exec + "") : null; - if (value != null) { - value = BigDecimal.valueOf(value).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue(); - } - map.put(def.getCode(), value); + this.repository.save(entity); + return getById(entity.getId()); } - dto.updateFromMap(map); + public CoalAnalysisDto calculate(CoalAnalysisDto dto) { - return dto; - } + List parameters = + coalParameterDefRepository.findByOrganizationId( + Ctx.currentUser().getOrganizationId()); - public CoalAnalysisDto update(UpdateCoalAnalysisDto request) { - CoalAnalysisEntity entity = this.repository.get(request.getId()); - this.mapper.updateEntity(entity, request); + List toCalculate = + parameters.stream() + .filter(x -> StringUtils.equalsIgnoreCase(x.getInputType(), "1")) + .sorted( + Comparator.comparing( + x -> ObjectUtils.defaultIfNull(x.getPriority(), -1))) + .collect(Collectors.toList()); - this.repository.save(entity); + Map map = dto.toMap(); - return getById(entity.getId()); - } + for (CoalParameterDefEntity def : toCalculate) { - public void delete(IdRequest request) { - this.repository.deleteAllById(request.getIds()); - } + Object exec = GroovyScriptUtils.exec(def.getFormula0(), map); - public CoalAnalysisDto getById(String id) { - CoalAnalysisEntity entity = repository.get(id); + if (exec != null && !(exec instanceof Number)) { + throw new BizException("计算结果不是数字"); + } - return mapper.toDto(entity); - } + Double value = exec != null ? NumberUtils.toDouble(exec + "") : null; + if (value != null) { + value = + BigDecimal.valueOf(value) + .setScale(2, RoundingMode.HALF_UP) + .doubleValue(); + } + map.put(def.getCode(), value); + } - public Page list(CommonQuery query) { - Page page = - repository.findAll( - query.specification(conversionService), - PageRequest.of(query.getPageNo(), query.getPageSize(), Sort.by(query.getOrders()))); + dto.updateFromMap(map); - return page.map(this.mapper::toDto); - } + return dto; + } + + public CoalAnalysisDto update(UpdateCoalAnalysisDto request) { + CoalAnalysisEntity entity = this.repository.get(request.getId()); + this.mapper.updateEntity(entity, request); + + this.repository.save(entity); + + return getById(entity.getId()); + } + + public void delete(IdRequest request) { + this.repository.deleteAllById(request.getIds()); + } + + public CoalAnalysisDto getById(String id) { + CoalAnalysisEntity entity = repository.get(id); + + return mapper.toDto(entity); + } + + public Page list(CommonQuery query) { + Page page = + repository.findAll( + query.specification(conversionService), + PageRequest.of( + query.getPageNo(), + query.getPageSize(), + Sort.by(query.getOrders()))); + + return page.map(this.mapper::toDto); + } } diff --git a/src/main/java/cn/lihongjie/coal/coalBlend/controller/CoalBlendController.java b/src/main/java/cn/lihongjie/coal/coalBlend/controller/CoalBlendController.java index cf5d2ed3..151df11e 100644 --- a/src/main/java/cn/lihongjie/coal/coalBlend/controller/CoalBlendController.java +++ b/src/main/java/cn/lihongjie/coal/coalBlend/controller/CoalBlendController.java @@ -9,6 +9,7 @@ import cn.lihongjie.coal.coalBlend.dto.CoalBlendDto; import cn.lihongjie.coal.coalBlend.dto.CreateCoalBlendDto; import cn.lihongjie.coal.coalBlend.dto.UpdateCoalBlendDto; import cn.lihongjie.coal.coalBlend.service.CoalBlendService; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.web.bind.annotation.PostMapping; @@ -22,40 +23,40 @@ import org.springframework.web.bind.annotation.RestController; @Anonymous public class CoalBlendController extends BaseController { - @Autowired CoalBlendService service; + @Autowired CoalBlendService service; - @PostMapping("/blend") - @SysLog(action = "配煤") - public CoalBlendDto blend(@RequestBody CreateCoalBlendDto dto) { - return this.service.blend(dto); - } + @PostMapping("/blend") + @SysLog(action = "配煤") + public CoalBlendDto blend(@RequestBody CreateCoalBlendDto dto) { + return this.service.blend(dto); + } - @PostMapping("/create") - @SysLog(action = "新增") - public CoalBlendDto create(@RequestBody CreateCoalBlendDto dto) { - return this.service.create(dto); - } + @PostMapping("/create") + @SysLog(action = "新增") + public CoalBlendDto create(@RequestBody CreateCoalBlendDto dto) { + return this.service.create(dto); + } - @PostMapping("/update") - @SysLog(action = "编辑") - public CoalBlendDto update(@RequestBody UpdateCoalBlendDto dto) { - return this.service.update(dto); - } + @PostMapping("/update") + @SysLog(action = "编辑") + public CoalBlendDto update(@RequestBody UpdateCoalBlendDto dto) { + return this.service.update(dto); + } - @PostMapping("/delete") - @SysLog(action = "删除") - public Object delete(@RequestBody IdRequest dto) { - this.service.delete(dto); - return true; - } + @PostMapping("/delete") + @SysLog(action = "删除") + public Object delete(@RequestBody IdRequest dto) { + this.service.delete(dto); + return true; + } - @PostMapping("/list") - public Page list(@RequestBody CommonQuery dto) { - return this.service.list(dto); - } + @PostMapping("/list") + public Page list(@RequestBody CommonQuery dto) { + return this.service.list(dto); + } - @PostMapping("/getById") - public CoalBlendDto getById(@RequestBody IdRequest dto) { - return this.service.getById(dto.getId()); - } + @PostMapping("/getById") + public CoalBlendDto getById(@RequestBody IdRequest dto) { + return this.service.getById(dto.getId()); + } } diff --git a/src/main/java/cn/lihongjie/coal/coalBlend/dto/CoalBlendCoalInfoDto.java b/src/main/java/cn/lihongjie/coal/coalBlend/dto/CoalBlendCoalInfoDto.java index bc391520..cfcd0652 100644 --- a/src/main/java/cn/lihongjie/coal/coalBlend/dto/CoalBlendCoalInfoDto.java +++ b/src/main/java/cn/lihongjie/coal/coalBlend/dto/CoalBlendCoalInfoDto.java @@ -2,12 +2,15 @@ package cn.lihongjie.coal.coalBlend.dto; import cn.lihongjie.coal.base.dto.OrgCommonDto; import cn.lihongjie.coal.coalBlend.entity.CoalBlendEntity; + import jakarta.validation.constraints.DecimalMin; import jakarta.validation.constraints.NotEmpty; + import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import lombok.SneakyThrows; + import org.apache.commons.lang3.reflect.FieldUtils; import org.hibernate.annotations.Comment; import org.hibernate.validator.constraints.Range; @@ -17,179 +20,179 @@ import org.hibernate.validator.constraints.Range; @NoArgsConstructor public class CoalBlendCoalInfoDto extends OrgCommonDto { - @NotEmpty(message = "煤名称不能为空") - private String name; + @NotEmpty(message = "煤名称不能为空") + private String name; - @Comment("比例最小值") - @Range(groups = CoalBlendEntity.BlendGroup.class, min = 0, max = 100, message = "无效的比例") - private Integer minPercent; + @Comment("比例最小值") + @Range(groups = CoalBlendEntity.BlendGroup.class, min = 0, max = 100, message = "无效的比例") + private Integer minPercent; - @Comment("比例最大值") - @Range(groups = CoalBlendEntity.BlendGroup.class, min = 0, max = 100, message = "无效的比例") - private Integer maxPercent; + @Comment("比例最大值") + @Range(groups = CoalBlendEntity.BlendGroup.class, min = 0, max = 100, message = "无效的比例") + private Integer maxPercent; - @Comment("参数 1 ") - @DecimalMin( - groups = CoalBlendEntity.BlendGroup.class, - value = "0.1", - inclusive = true, - message = "参数不能小于0.1") - private Double param1; + @Comment("参数 1 ") + @DecimalMin( + groups = CoalBlendEntity.BlendGroup.class, + value = "0.1", + inclusive = true, + message = "参数不能小于0.1") + private Double param1; - @Comment("参数 2 ") - @DecimalMin( - groups = CoalBlendEntity.BlendGroup.class, - value = "0.1", - inclusive = true, - message = "参数不能小于0.1") - private Double param2; + @Comment("参数 2 ") + @DecimalMin( + groups = CoalBlendEntity.BlendGroup.class, + value = "0.1", + inclusive = true, + message = "参数不能小于0.1") + private Double param2; - @Comment("参数 3 ") - @DecimalMin( - groups = CoalBlendEntity.BlendGroup.class, - value = "0.1", - inclusive = true, - message = "参数不能小于0.1") - private Double param3; + @Comment("参数 3 ") + @DecimalMin( + groups = CoalBlendEntity.BlendGroup.class, + value = "0.1", + inclusive = true, + message = "参数不能小于0.1") + private Double param3; - @Comment("参数 4 ") - @DecimalMin( - groups = CoalBlendEntity.BlendGroup.class, - value = "0.1", - inclusive = true, - message = "参数不能小于0.1") - private Double param4; + @Comment("参数 4 ") + @DecimalMin( + groups = CoalBlendEntity.BlendGroup.class, + value = "0.1", + inclusive = true, + message = "参数不能小于0.1") + private Double param4; - @Comment("参数 5 ") - @DecimalMin( - groups = CoalBlendEntity.BlendGroup.class, - value = "0.1", - inclusive = true, - message = "参数不能小于0.1") - private Double param5; + @Comment("参数 5 ") + @DecimalMin( + groups = CoalBlendEntity.BlendGroup.class, + value = "0.1", + inclusive = true, + message = "参数不能小于0.1") + private Double param5; - @Comment("参数 6 ") - @DecimalMin( - groups = CoalBlendEntity.BlendGroup.class, - value = "0.1", - inclusive = true, - message = "参数不能小于0.1") - private Double param6; + @Comment("参数 6 ") + @DecimalMin( + groups = CoalBlendEntity.BlendGroup.class, + value = "0.1", + inclusive = true, + message = "参数不能小于0.1") + private Double param6; - @Comment("参数 7 ") - @DecimalMin( - groups = CoalBlendEntity.BlendGroup.class, - value = "0.1", - inclusive = true, - message = "参数不能小于0.1") - private Double param7; + @Comment("参数 7 ") + @DecimalMin( + groups = CoalBlendEntity.BlendGroup.class, + value = "0.1", + inclusive = true, + message = "参数不能小于0.1") + private Double param7; - @Comment("参数 8 ") - @DecimalMin( - groups = CoalBlendEntity.BlendGroup.class, - value = "0.1", - inclusive = true, - message = "参数不能小于0.1") - private Double param8; + @Comment("参数 8 ") + @DecimalMin( + groups = CoalBlendEntity.BlendGroup.class, + value = "0.1", + inclusive = true, + message = "参数不能小于0.1") + private Double param8; - @Comment("参数 9 ") - @DecimalMin( - groups = CoalBlendEntity.BlendGroup.class, - value = "0.1", - inclusive = true, - message = "参数不能小于0.1") - private Double param9; + @Comment("参数 9 ") + @DecimalMin( + groups = CoalBlendEntity.BlendGroup.class, + value = "0.1", + inclusive = true, + message = "参数不能小于0.1") + private Double param9; - @Comment("参数 10 ") - @DecimalMin( - groups = CoalBlendEntity.BlendGroup.class, - value = "0.1", - inclusive = true, - message = "参数不能小于0.1") - private Double param10; + @Comment("参数 10 ") + @DecimalMin( + groups = CoalBlendEntity.BlendGroup.class, + value = "0.1", + inclusive = true, + message = "参数不能小于0.1") + private Double param10; - @Comment("参数 11 ") - @DecimalMin( - groups = CoalBlendEntity.BlendGroup.class, - value = "0.1", - inclusive = true, - message = "参数不能小于0.1") - private Double param11; + @Comment("参数 11 ") + @DecimalMin( + groups = CoalBlendEntity.BlendGroup.class, + value = "0.1", + inclusive = true, + message = "参数不能小于0.1") + private Double param11; - @Comment("参数 12 ") - @DecimalMin( - groups = CoalBlendEntity.BlendGroup.class, - value = "0.1", - inclusive = true, - message = "参数不能小于0.1") - private Double param12; + @Comment("参数 12 ") + @DecimalMin( + groups = CoalBlendEntity.BlendGroup.class, + value = "0.1", + inclusive = true, + message = "参数不能小于0.1") + private Double param12; - @Comment("参数 13 ") - @DecimalMin( - groups = CoalBlendEntity.BlendGroup.class, - value = "0.1", - inclusive = true, - message = "参数不能小于0.1") - private Double param13; + @Comment("参数 13 ") + @DecimalMin( + groups = CoalBlendEntity.BlendGroup.class, + value = "0.1", + inclusive = true, + message = "参数不能小于0.1") + private Double param13; - @Comment("参数 14 ") - @DecimalMin( - groups = CoalBlendEntity.BlendGroup.class, - value = "0.1", - inclusive = true, - message = "参数不能小于0.1") - private Double param14; + @Comment("参数 14 ") + @DecimalMin( + groups = CoalBlendEntity.BlendGroup.class, + value = "0.1", + inclusive = true, + message = "参数不能小于0.1") + private Double param14; - @Comment("参数 15 ") - @DecimalMin( - groups = CoalBlendEntity.BlendGroup.class, - value = "0.1", - inclusive = true, - message = "参数不能小于0.1") - private Double param15; + @Comment("参数 15 ") + @DecimalMin( + groups = CoalBlendEntity.BlendGroup.class, + value = "0.1", + inclusive = true, + message = "参数不能小于0.1") + private Double param15; - @Comment("参数 16 ") - @DecimalMin( - groups = CoalBlendEntity.BlendGroup.class, - value = "0.1", - inclusive = true, - message = "参数不能小于0.1") - private Double param16; + @Comment("参数 16 ") + @DecimalMin( + groups = CoalBlendEntity.BlendGroup.class, + value = "0.1", + inclusive = true, + message = "参数不能小于0.1") + private Double param16; - @Comment("参数 17 ") - @DecimalMin( - groups = CoalBlendEntity.BlendGroup.class, - value = "0.1", - inclusive = true, - message = "参数不能小于0.1") - private Double param17; + @Comment("参数 17 ") + @DecimalMin( + groups = CoalBlendEntity.BlendGroup.class, + value = "0.1", + inclusive = true, + message = "参数不能小于0.1") + private Double param17; - @Comment("参数 18 ") - @DecimalMin( - groups = CoalBlendEntity.BlendGroup.class, - value = "0.1", - inclusive = true, - message = "参数不能小于0.1") - private Double param18; + @Comment("参数 18 ") + @DecimalMin( + groups = CoalBlendEntity.BlendGroup.class, + value = "0.1", + inclusive = true, + message = "参数不能小于0.1") + private Double param18; - @Comment("参数 19 ") - @DecimalMin( - groups = CoalBlendEntity.BlendGroup.class, - value = "0.1", - inclusive = true, - message = "参数不能小于0.1") - private Double param19; + @Comment("参数 19 ") + @DecimalMin( + groups = CoalBlendEntity.BlendGroup.class, + value = "0.1", + inclusive = true, + message = "参数不能小于0.1") + private Double param19; - @Comment("参数 20 ") - @DecimalMin( - groups = CoalBlendEntity.BlendGroup.class, - value = "0.1", - inclusive = true, - message = "参数不能小于0.1") - private Double param20; + @Comment("参数 20 ") + @DecimalMin( + groups = CoalBlendEntity.BlendGroup.class, + value = "0.1", + inclusive = true, + message = "参数不能小于0.1") + private Double param20; - @SneakyThrows - public Double getParam(String param) { - return (Double) FieldUtils.getField(this.getClass(), param, true).get(this); - } + @SneakyThrows + public Double getParam(String param) { + return (Double) FieldUtils.getField(this.getClass(), param, true).get(this); + } } diff --git a/src/main/java/cn/lihongjie/coal/coalBlend/dto/CoalBlendDto.java b/src/main/java/cn/lihongjie/coal/coalBlend/dto/CoalBlendDto.java index da77c7a4..43ea7fd4 100644 --- a/src/main/java/cn/lihongjie/coal/coalBlend/dto/CoalBlendDto.java +++ b/src/main/java/cn/lihongjie/coal/coalBlend/dto/CoalBlendDto.java @@ -3,44 +3,48 @@ package cn.lihongjie.coal.coalBlend.dto; import cn.lihongjie.coal.base.dto.OrgCommonDto; import cn.lihongjie.coal.coalBlend.entity.CoalBlendConstrainVo; import cn.lihongjie.coal.coalBlend.entity.CoalParameterDefVo; + import jakarta.validation.constraints.NotEmpty; import jakarta.validation.constraints.NotNull; import jakarta.validation.constraints.Size; -import java.util.List; + import lombok.Data; + import org.hibernate.annotations.Comment; +import java.util.List; + @Data @Comment("配煤记录") public class CoalBlendDto extends OrgCommonDto { - @NotEmpty(message = "煤参数定义不能为空") - private List parameterDefs; + @NotEmpty(message = "煤参数定义不能为空") + private List parameterDefs; - @NotEmpty(message = "煤不能为空") - @Size(message = "至少需要两种煤", min = 2) - private List coals; + @NotEmpty(message = "煤不能为空") + @Size(message = "至少需要两种煤", min = 2) + private List coals; - @NotNull(message = "约束条件不能为空") - private CoalBlendConstrainVo constrains; + @NotNull(message = "约束条件不能为空") + private CoalBlendConstrainVo constrains; - private List results; + private List results; - private String blendTypeName; - private String blendType; + private String blendTypeName; + private String blendType; - @Comment("结果个数") - private Integer count = 20; + @Comment("结果个数") + private Integer count = 20; - @Comment("最长等待时间") - private Integer maxTime = 10; + @Comment("最长等待时间") + private Integer maxTime = 10; - @Comment("铲车配煤 配比之和 最大值") - private Integer type2PercentSum = 10; + @Comment("铲车配煤 配比之和 最大值") + private Integer type2PercentSum = 10; - @Comment("目标参数, 比如: param1 param2") - private String targetParam = ""; + @Comment("目标参数, 比如: param1 param2") + private String targetParam = ""; - @Comment("求目标参数最大值 -1, 最小值 1") - private Integer targetOrder = -1; + @Comment("求目标参数最大值 -1, 最小值 1") + private Integer targetOrder = -1; } diff --git a/src/main/java/cn/lihongjie/coal/coalBlend/dto/CoalBlendRequest.java b/src/main/java/cn/lihongjie/coal/coalBlend/dto/CoalBlendRequest.java index f100f0ee..0c2446be 100644 --- a/src/main/java/cn/lihongjie/coal/coalBlend/dto/CoalBlendRequest.java +++ b/src/main/java/cn/lihongjie/coal/coalBlend/dto/CoalBlendRequest.java @@ -2,40 +2,43 @@ package cn.lihongjie.coal.coalBlend.dto; import cn.lihongjie.coal.coal.CoalConstraint; import cn.lihongjie.coal.coal.CoalInfo; + import com.fasterxml.jackson.annotation.JsonIgnore; + +import lombok.Data; + import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; -import lombok.Data; @Data public class CoalBlendRequest { - private List coals; + private List coals; - private List constraints; - @JsonIgnore private Map constraintMap; + private List constraints; + @JsonIgnore private Map constraintMap; - /** 1 高精度 2 低精度(用于铲车配煤 类似 1:3 整比例) */ - private Integer type = 1; - /** 低精度配比之和最大值 */ - private int percent2Sum = 10; + /** 1 高精度 2 低精度(用于铲车配煤 类似 1:3 整比例) */ + private Integer type = 1; - public Map getConstraintMap() { - if (constraintMap == null) { - if (constraints != null) { + /** 低精度配比之和最大值 */ + private int percent2Sum = 10; + /** 结果个数 */ + private Long count = 10L; + /** 最长等待时间 */ + private Long maxTime = 10L; - constraintMap = constraints.stream().collect(Collectors.toMap(e -> e.getCode(), e -> e)); - } else { - constraintMap = new HashMap<>(); - } + public Map getConstraintMap() { + if (constraintMap == null) { + if (constraints != null) { + + constraintMap = + constraints.stream().collect(Collectors.toMap(e -> e.getCode(), e -> e)); + } else { + constraintMap = new HashMap<>(); + } + } + return constraintMap; } - return constraintMap; - } - - /** 结果个数 */ - private Long count = 10L; - - /** 最长等待时间 */ - private Long maxTime = 10L; } diff --git a/src/main/java/cn/lihongjie/coal/coalBlend/dto/CoalBlendResult.java b/src/main/java/cn/lihongjie/coal/coalBlend/dto/CoalBlendResult.java index 56f36d69..1a087402 100644 --- a/src/main/java/cn/lihongjie/coal/coalBlend/dto/CoalBlendResult.java +++ b/src/main/java/cn/lihongjie/coal/coalBlend/dto/CoalBlendResult.java @@ -1,27 +1,29 @@ package cn.lihongjie.coal.coalBlend.dto; import cn.lihongjie.coal.coal.CoalInfo; + +import lombok.Data; + import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; -import lombok.Data; @Data public class CoalBlendResult { - private long numBranches = 0; - private long numConflicts = 0; - private long wallTime = 0; - private long userTime = 0; - private List coals = new ArrayList<>(); - private int totalCount; + private long numBranches = 0; + private long numConflicts = 0; + private long wallTime = 0; + private long userTime = 0; + private List coals = new ArrayList<>(); + private int totalCount; - public String tableString() { + public String tableString() { - String headerLine = - String.format( - "totalCount %s numBranches %s numConflicts %s wallTime %s userTime %s \n", - totalCount, numBranches, numConflicts, wallTime, userTime); - String collect = coals.stream().map(x -> x.rowString()).collect(Collectors.joining("\n")); - return headerLine + collect; - } + String headerLine = + String.format( + "totalCount %s numBranches %s numConflicts %s wallTime %s userTime %s \n", + totalCount, numBranches, numConflicts, wallTime, userTime); + String collect = coals.stream().map(x -> x.rowString()).collect(Collectors.joining("\n")); + return headerLine + collect; + } } diff --git a/src/main/java/cn/lihongjie/coal/coalBlend/dto/CoalBlendResultInfoDto.java b/src/main/java/cn/lihongjie/coal/coalBlend/dto/CoalBlendResultInfoDto.java index 045b35fa..e4e4b3f3 100644 --- a/src/main/java/cn/lihongjie/coal/coalBlend/dto/CoalBlendResultInfoDto.java +++ b/src/main/java/cn/lihongjie/coal/coalBlend/dto/CoalBlendResultInfoDto.java @@ -3,198 +3,202 @@ package cn.lihongjie.coal.coalBlend.dto; import cn.lihongjie.coal.base.dto.OrgCommonDto; import cn.lihongjie.coal.coalBlend.entity.CoalBlendEntity; import cn.lihongjie.coal.coalBlend.entity.CoalPercentVo; + import jakarta.validation.constraints.DecimalMin; import jakarta.validation.constraints.NotEmpty; -import java.util.Arrays; -import java.util.Comparator; -import java.util.List; + import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import lombok.SneakyThrows; + import org.apache.commons.lang3.reflect.FieldUtils; import org.hibernate.annotations.Comment; +import java.util.Arrays; +import java.util.Comparator; +import java.util.List; + @Data @AllArgsConstructor @NoArgsConstructor public class CoalBlendResultInfoDto extends OrgCommonDto { - @NotEmpty(message = "煤名称不能为空") - private String name; + @NotEmpty(message = "煤名称不能为空") + private String name; - private List percentInfos; + private List percentInfos; - @Comment("参数 1 ") - @DecimalMin( - groups = CoalBlendEntity.BlendGroup.class, - value = "0.1", - inclusive = true, - message = "参数不能小于0.1") - private Double param1; + @Comment("参数 1 ") + @DecimalMin( + groups = CoalBlendEntity.BlendGroup.class, + value = "0.1", + inclusive = true, + message = "参数不能小于0.1") + private Double param1; - @Comment("参数 2 ") - @DecimalMin( - groups = CoalBlendEntity.BlendGroup.class, - value = "0.1", - inclusive = true, - message = "参数不能小于0.1") - private Double param2; + @Comment("参数 2 ") + @DecimalMin( + groups = CoalBlendEntity.BlendGroup.class, + value = "0.1", + inclusive = true, + message = "参数不能小于0.1") + private Double param2; - @Comment("参数 3 ") - @DecimalMin( - groups = CoalBlendEntity.BlendGroup.class, - value = "0.1", - inclusive = true, - message = "参数不能小于0.1") - private Double param3; + @Comment("参数 3 ") + @DecimalMin( + groups = CoalBlendEntity.BlendGroup.class, + value = "0.1", + inclusive = true, + message = "参数不能小于0.1") + private Double param3; - @Comment("参数 4 ") - @DecimalMin( - groups = CoalBlendEntity.BlendGroup.class, - value = "0.1", - inclusive = true, - message = "参数不能小于0.1") - private Double param4; + @Comment("参数 4 ") + @DecimalMin( + groups = CoalBlendEntity.BlendGroup.class, + value = "0.1", + inclusive = true, + message = "参数不能小于0.1") + private Double param4; - @Comment("参数 5 ") - @DecimalMin( - groups = CoalBlendEntity.BlendGroup.class, - value = "0.1", - inclusive = true, - message = "参数不能小于0.1") - private Double param5; + @Comment("参数 5 ") + @DecimalMin( + groups = CoalBlendEntity.BlendGroup.class, + value = "0.1", + inclusive = true, + message = "参数不能小于0.1") + private Double param5; - @Comment("参数 6 ") - @DecimalMin( - groups = CoalBlendEntity.BlendGroup.class, - value = "0.1", - inclusive = true, - message = "参数不能小于0.1") - private Double param6; + @Comment("参数 6 ") + @DecimalMin( + groups = CoalBlendEntity.BlendGroup.class, + value = "0.1", + inclusive = true, + message = "参数不能小于0.1") + private Double param6; - @Comment("参数 7 ") - @DecimalMin( - groups = CoalBlendEntity.BlendGroup.class, - value = "0.1", - inclusive = true, - message = "参数不能小于0.1") - private Double param7; + @Comment("参数 7 ") + @DecimalMin( + groups = CoalBlendEntity.BlendGroup.class, + value = "0.1", + inclusive = true, + message = "参数不能小于0.1") + private Double param7; - @Comment("参数 8 ") - @DecimalMin( - groups = CoalBlendEntity.BlendGroup.class, - value = "0.1", - inclusive = true, - message = "参数不能小于0.1") - private Double param8; + @Comment("参数 8 ") + @DecimalMin( + groups = CoalBlendEntity.BlendGroup.class, + value = "0.1", + inclusive = true, + message = "参数不能小于0.1") + private Double param8; - @Comment("参数 9 ") - @DecimalMin( - groups = CoalBlendEntity.BlendGroup.class, - value = "0.1", - inclusive = true, - message = "参数不能小于0.1") - private Double param9; + @Comment("参数 9 ") + @DecimalMin( + groups = CoalBlendEntity.BlendGroup.class, + value = "0.1", + inclusive = true, + message = "参数不能小于0.1") + private Double param9; - @Comment("参数 10 ") - @DecimalMin( - groups = CoalBlendEntity.BlendGroup.class, - value = "0.1", - inclusive = true, - message = "参数不能小于0.1") - private Double param10; + @Comment("参数 10 ") + @DecimalMin( + groups = CoalBlendEntity.BlendGroup.class, + value = "0.1", + inclusive = true, + message = "参数不能小于0.1") + private Double param10; - @Comment("参数 11 ") - @DecimalMin( - groups = CoalBlendEntity.BlendGroup.class, - value = "0.1", - inclusive = true, - message = "参数不能小于0.1") - private Double param11; + @Comment("参数 11 ") + @DecimalMin( + groups = CoalBlendEntity.BlendGroup.class, + value = "0.1", + inclusive = true, + message = "参数不能小于0.1") + private Double param11; - @Comment("参数 12 ") - @DecimalMin( - groups = CoalBlendEntity.BlendGroup.class, - value = "0.1", - inclusive = true, - message = "参数不能小于0.1") - private Double param12; + @Comment("参数 12 ") + @DecimalMin( + groups = CoalBlendEntity.BlendGroup.class, + value = "0.1", + inclusive = true, + message = "参数不能小于0.1") + private Double param12; - @Comment("参数 13 ") - @DecimalMin( - groups = CoalBlendEntity.BlendGroup.class, - value = "0.1", - inclusive = true, - message = "参数不能小于0.1") - private Double param13; + @Comment("参数 13 ") + @DecimalMin( + groups = CoalBlendEntity.BlendGroup.class, + value = "0.1", + inclusive = true, + message = "参数不能小于0.1") + private Double param13; - @Comment("参数 14 ") - @DecimalMin( - groups = CoalBlendEntity.BlendGroup.class, - value = "0.1", - inclusive = true, - message = "参数不能小于0.1") - private Double param14; + @Comment("参数 14 ") + @DecimalMin( + groups = CoalBlendEntity.BlendGroup.class, + value = "0.1", + inclusive = true, + message = "参数不能小于0.1") + private Double param14; - @Comment("参数 15 ") - @DecimalMin( - groups = CoalBlendEntity.BlendGroup.class, - value = "0.1", - inclusive = true, - message = "参数不能小于0.1") - private Double param15; + @Comment("参数 15 ") + @DecimalMin( + groups = CoalBlendEntity.BlendGroup.class, + value = "0.1", + inclusive = true, + message = "参数不能小于0.1") + private Double param15; - @Comment("参数 16 ") - @DecimalMin( - groups = CoalBlendEntity.BlendGroup.class, - value = "0.1", - inclusive = true, - message = "参数不能小于0.1") - private Double param16; + @Comment("参数 16 ") + @DecimalMin( + groups = CoalBlendEntity.BlendGroup.class, + value = "0.1", + inclusive = true, + message = "参数不能小于0.1") + private Double param16; - @Comment("参数 17 ") - @DecimalMin( - groups = CoalBlendEntity.BlendGroup.class, - value = "0.1", - inclusive = true, - message = "参数不能小于0.1") - private Double param17; + @Comment("参数 17 ") + @DecimalMin( + groups = CoalBlendEntity.BlendGroup.class, + value = "0.1", + inclusive = true, + message = "参数不能小于0.1") + private Double param17; - @Comment("参数 18 ") - @DecimalMin( - groups = CoalBlendEntity.BlendGroup.class, - value = "0.1", - inclusive = true, - message = "参数不能小于0.1") - private Double param18; + @Comment("参数 18 ") + @DecimalMin( + groups = CoalBlendEntity.BlendGroup.class, + value = "0.1", + inclusive = true, + message = "参数不能小于0.1") + private Double param18; - @Comment("参数 19 ") - @DecimalMin( - groups = CoalBlendEntity.BlendGroup.class, - value = "0.1", - inclusive = true, - message = "参数不能小于0.1") - private Double param19; + @Comment("参数 19 ") + @DecimalMin( + groups = CoalBlendEntity.BlendGroup.class, + value = "0.1", + inclusive = true, + message = "参数不能小于0.1") + private Double param19; - @Comment("参数 20 ") - @DecimalMin( - groups = CoalBlendEntity.BlendGroup.class, - value = "0.1", - inclusive = true, - message = "参数不能小于0.1") - private Double param20; + @Comment("参数 20 ") + @DecimalMin( + groups = CoalBlendEntity.BlendGroup.class, + value = "0.1", + inclusive = true, + message = "参数不能小于0.1") + private Double param20; - @SneakyThrows - public Double getParam(String param) { - return (Double) FieldUtils.getField(this.getClass(), param, true).get(this); - } + @SneakyThrows + public Double getParam(String param) { + return (Double) FieldUtils.getField(this.getClass(), param, true).get(this); + } - public long getHashKey() { + public long getHashKey() { - return Arrays.hashCode( - this.getPercentInfos().stream() - .sorted(Comparator.comparing(x -> x.getPercent())) - .toArray(CoalPercentVo[]::new)); - } + return Arrays.hashCode( + this.getPercentInfos().stream() + .sorted(Comparator.comparing(x -> x.getPercent())) + .toArray(CoalPercentVo[]::new)); + } } diff --git a/src/main/java/cn/lihongjie/coal/coalBlend/dto/CreateCoalBlendDto.java b/src/main/java/cn/lihongjie/coal/coalBlend/dto/CreateCoalBlendDto.java index f7cdd76a..7d30a53e 100644 --- a/src/main/java/cn/lihongjie/coal/coalBlend/dto/CreateCoalBlendDto.java +++ b/src/main/java/cn/lihongjie/coal/coalBlend/dto/CreateCoalBlendDto.java @@ -3,44 +3,48 @@ package cn.lihongjie.coal.coalBlend.dto; import cn.lihongjie.coal.base.dto.OrgCommonDto; import cn.lihongjie.coal.coalBlend.entity.CoalBlendConstrainVo; import cn.lihongjie.coal.coalBlend.entity.CoalParameterDefVo; + import jakarta.validation.constraints.NotEmpty; import jakarta.validation.constraints.NotNull; import jakarta.validation.constraints.Size; -import java.util.List; + import lombok.Data; + import org.hibernate.annotations.Comment; +import java.util.List; + @Data @Comment("配煤记录") public class CreateCoalBlendDto extends OrgCommonDto { - @NotEmpty(message = "煤参数定义不能为空") - private List parameterDefs; + @NotEmpty(message = "煤参数定义不能为空") + private List parameterDefs; - @NotEmpty(message = "煤不能为空") - @Size(message = "至少需要两种煤", min = 2) - private List coals; + @NotEmpty(message = "煤不能为空") + @Size(message = "至少需要两种煤", min = 2) + private List coals; - @NotNull(message = "约束条件不能为空") - private CoalBlendConstrainVo constrains; + @NotNull(message = "约束条件不能为空") + private CoalBlendConstrainVo constrains; - private List results; + private List results; - private String blendTypeName; - private String blendType; + private String blendTypeName; + private String blendType; - @Comment("结果个数") - private Integer count = 20; + @Comment("结果个数") + private Integer count = 20; - @Comment("最长等待时间") - private Integer maxTime = 10; + @Comment("最长等待时间") + private Integer maxTime = 10; - @Comment("铲车配煤 配比之和 最大值") - private Integer type2PercentSum = 10; + @Comment("铲车配煤 配比之和 最大值") + private Integer type2PercentSum = 10; - @Comment("目标参数, 比如: param1 param2") - private String targetParam = ""; + @Comment("目标参数, 比如: param1 param2") + private String targetParam = ""; - @Comment("求目标参数最大值 -1, 最小值 1") - private Integer targetOrder = -1; + @Comment("求目标参数最大值 -1, 最小值 1") + private Integer targetOrder = -1; } diff --git a/src/main/java/cn/lihongjie/coal/coalBlend/dto/UpdateCoalBlendDto.java b/src/main/java/cn/lihongjie/coal/coalBlend/dto/UpdateCoalBlendDto.java index 0784ca85..5cc0ab53 100644 --- a/src/main/java/cn/lihongjie/coal/coalBlend/dto/UpdateCoalBlendDto.java +++ b/src/main/java/cn/lihongjie/coal/coalBlend/dto/UpdateCoalBlendDto.java @@ -3,43 +3,47 @@ package cn.lihongjie.coal.coalBlend.dto; import cn.lihongjie.coal.base.dto.OrgCommonDto; import cn.lihongjie.coal.coalBlend.entity.CoalBlendConstrainVo; import cn.lihongjie.coal.coalBlend.entity.CoalParameterDefVo; + import jakarta.validation.constraints.NotEmpty; import jakarta.validation.constraints.NotNull; import jakarta.validation.constraints.Size; -import java.util.List; + import lombok.Data; + import org.hibernate.annotations.Comment; +import java.util.List; + @Data @Comment("配煤记录") public class UpdateCoalBlendDto extends OrgCommonDto { - @NotEmpty(message = "煤参数定义不能为空") - private List parameterDefs; + @NotEmpty(message = "煤参数定义不能为空") + private List parameterDefs; - @NotEmpty(message = "煤不能为空") - @Size(message = "至少需要两种煤", min = 2) - private List coals; + @NotEmpty(message = "煤不能为空") + @Size(message = "至少需要两种煤", min = 2) + private List coals; - @NotNull(message = "约束条件不能为空") - private CoalBlendConstrainVo constrains; + @NotNull(message = "约束条件不能为空") + private CoalBlendConstrainVo constrains; - private List results; - private String blendTypeName; - private String blendType; + private List results; + private String blendTypeName; + private String blendType; - @Comment("结果个数") - private Integer count = 20; + @Comment("结果个数") + private Integer count = 20; - @Comment("最长等待时间") - private Integer maxTime = 10; + @Comment("最长等待时间") + private Integer maxTime = 10; - @Comment("铲车配煤 配比之和 最大值") - private Integer type2PercentSum = 10; + @Comment("铲车配煤 配比之和 最大值") + private Integer type2PercentSum = 10; - @Comment("目标参数, 比如: param1 param2") - private String targetParam = ""; + @Comment("目标参数, 比如: param1 param2") + private String targetParam = ""; - @Comment("求目标参数最大值 -1, 最小值 1") - private Integer targetOrder = -1; + @Comment("求目标参数最大值 -1, 最小值 1") + private Integer targetOrder = -1; } diff --git a/src/main/java/cn/lihongjie/coal/coalBlend/entity/CoalBlendCoalInfoEntity.java b/src/main/java/cn/lihongjie/coal/coalBlend/entity/CoalBlendCoalInfoEntity.java index 587ae00c..d4ac1893 100644 --- a/src/main/java/cn/lihongjie/coal/coalBlend/entity/CoalBlendCoalInfoEntity.java +++ b/src/main/java/cn/lihongjie/coal/coalBlend/entity/CoalBlendCoalInfoEntity.java @@ -1,11 +1,14 @@ package cn.lihongjie.coal.coalBlend.entity; import cn.lihongjie.coal.base.entity.OrgCommonEntity; + import jakarta.persistence.Entity; import jakarta.persistence.ManyToOne; import jakarta.validation.constraints.DecimalMin; import jakarta.validation.constraints.NotEmpty; + import lombok.*; + import org.apache.commons.lang3.reflect.FieldUtils; import org.hibernate.annotations.Comment; import org.hibernate.validator.constraints.Range; @@ -17,181 +20,181 @@ import org.hibernate.validator.constraints.Range; @Entity public class CoalBlendCoalInfoEntity extends OrgCommonEntity { - @NotEmpty(message = "煤名称不能为空") - private String name; + @NotEmpty(message = "煤名称不能为空") + private String name; - @ManyToOne() private CoalBlendEntity coal; + @ManyToOne() private CoalBlendEntity coal; - @Comment("比例最小值") - @Range(groups = CoalBlendEntity.BlendGroup.class, min = 0, max = 100, message = "无效的比例") - private Integer minPercent; + @Comment("比例最小值") + @Range(groups = CoalBlendEntity.BlendGroup.class, min = 0, max = 100, message = "无效的比例") + private Integer minPercent; - @Comment("比例最大值") - @Range(groups = CoalBlendEntity.BlendGroup.class, min = 0, max = 100, message = "无效的比例") - private Integer maxPercent; + @Comment("比例最大值") + @Range(groups = CoalBlendEntity.BlendGroup.class, min = 0, max = 100, message = "无效的比例") + private Integer maxPercent; - @Comment("参数 1 ") - @DecimalMin( - groups = CoalBlendEntity.BlendGroup.class, - value = "0.1", - inclusive = true, - message = "参数不能小于0.1") - private Double param1; + @Comment("参数 1 ") + @DecimalMin( + groups = CoalBlendEntity.BlendGroup.class, + value = "0.1", + inclusive = true, + message = "参数不能小于0.1") + private Double param1; - @Comment("参数 2 ") - @DecimalMin( - groups = CoalBlendEntity.BlendGroup.class, - value = "0.1", - inclusive = true, - message = "参数不能小于0.1") - private Double param2; + @Comment("参数 2 ") + @DecimalMin( + groups = CoalBlendEntity.BlendGroup.class, + value = "0.1", + inclusive = true, + message = "参数不能小于0.1") + private Double param2; - @Comment("参数 3 ") - @DecimalMin( - groups = CoalBlendEntity.BlendGroup.class, - value = "0.1", - inclusive = true, - message = "参数不能小于0.1") - private Double param3; + @Comment("参数 3 ") + @DecimalMin( + groups = CoalBlendEntity.BlendGroup.class, + value = "0.1", + inclusive = true, + message = "参数不能小于0.1") + private Double param3; - @Comment("参数 4 ") - @DecimalMin( - groups = CoalBlendEntity.BlendGroup.class, - value = "0.1", - inclusive = true, - message = "参数不能小于0.1") - private Double param4; + @Comment("参数 4 ") + @DecimalMin( + groups = CoalBlendEntity.BlendGroup.class, + value = "0.1", + inclusive = true, + message = "参数不能小于0.1") + private Double param4; - @Comment("参数 5 ") - @DecimalMin( - groups = CoalBlendEntity.BlendGroup.class, - value = "0.1", - inclusive = true, - message = "参数不能小于0.1") - private Double param5; + @Comment("参数 5 ") + @DecimalMin( + groups = CoalBlendEntity.BlendGroup.class, + value = "0.1", + inclusive = true, + message = "参数不能小于0.1") + private Double param5; - @Comment("参数 6 ") - @DecimalMin( - groups = CoalBlendEntity.BlendGroup.class, - value = "0.1", - inclusive = true, - message = "参数不能小于0.1") - private Double param6; + @Comment("参数 6 ") + @DecimalMin( + groups = CoalBlendEntity.BlendGroup.class, + value = "0.1", + inclusive = true, + message = "参数不能小于0.1") + private Double param6; - @Comment("参数 7 ") - @DecimalMin( - groups = CoalBlendEntity.BlendGroup.class, - value = "0.1", - inclusive = true, - message = "参数不能小于0.1") - private Double param7; + @Comment("参数 7 ") + @DecimalMin( + groups = CoalBlendEntity.BlendGroup.class, + value = "0.1", + inclusive = true, + message = "参数不能小于0.1") + private Double param7; - @Comment("参数 8 ") - @DecimalMin( - groups = CoalBlendEntity.BlendGroup.class, - value = "0.1", - inclusive = true, - message = "参数不能小于0.1") - private Double param8; + @Comment("参数 8 ") + @DecimalMin( + groups = CoalBlendEntity.BlendGroup.class, + value = "0.1", + inclusive = true, + message = "参数不能小于0.1") + private Double param8; - @Comment("参数 9 ") - @DecimalMin( - groups = CoalBlendEntity.BlendGroup.class, - value = "0.1", - inclusive = true, - message = "参数不能小于0.1") - private Double param9; + @Comment("参数 9 ") + @DecimalMin( + groups = CoalBlendEntity.BlendGroup.class, + value = "0.1", + inclusive = true, + message = "参数不能小于0.1") + private Double param9; - @Comment("参数 10 ") - @DecimalMin( - groups = CoalBlendEntity.BlendGroup.class, - value = "0.1", - inclusive = true, - message = "参数不能小于0.1") - private Double param10; + @Comment("参数 10 ") + @DecimalMin( + groups = CoalBlendEntity.BlendGroup.class, + value = "0.1", + inclusive = true, + message = "参数不能小于0.1") + private Double param10; - @Comment("参数 11 ") - @DecimalMin( - groups = CoalBlendEntity.BlendGroup.class, - value = "0.1", - inclusive = true, - message = "参数不能小于0.1") - private Double param11; + @Comment("参数 11 ") + @DecimalMin( + groups = CoalBlendEntity.BlendGroup.class, + value = "0.1", + inclusive = true, + message = "参数不能小于0.1") + private Double param11; - @Comment("参数 12 ") - @DecimalMin( - groups = CoalBlendEntity.BlendGroup.class, - value = "0.1", - inclusive = true, - message = "参数不能小于0.1") - private Double param12; + @Comment("参数 12 ") + @DecimalMin( + groups = CoalBlendEntity.BlendGroup.class, + value = "0.1", + inclusive = true, + message = "参数不能小于0.1") + private Double param12; - @Comment("参数 13 ") - @DecimalMin( - groups = CoalBlendEntity.BlendGroup.class, - value = "0.1", - inclusive = true, - message = "参数不能小于0.1") - private Double param13; + @Comment("参数 13 ") + @DecimalMin( + groups = CoalBlendEntity.BlendGroup.class, + value = "0.1", + inclusive = true, + message = "参数不能小于0.1") + private Double param13; - @Comment("参数 14 ") - @DecimalMin( - groups = CoalBlendEntity.BlendGroup.class, - value = "0.1", - inclusive = true, - message = "参数不能小于0.1") - private Double param14; + @Comment("参数 14 ") + @DecimalMin( + groups = CoalBlendEntity.BlendGroup.class, + value = "0.1", + inclusive = true, + message = "参数不能小于0.1") + private Double param14; - @Comment("参数 15 ") - @DecimalMin( - groups = CoalBlendEntity.BlendGroup.class, - value = "0.1", - inclusive = true, - message = "参数不能小于0.1") - private Double param15; + @Comment("参数 15 ") + @DecimalMin( + groups = CoalBlendEntity.BlendGroup.class, + value = "0.1", + inclusive = true, + message = "参数不能小于0.1") + private Double param15; - @Comment("参数 16 ") - @DecimalMin( - groups = CoalBlendEntity.BlendGroup.class, - value = "0.1", - inclusive = true, - message = "参数不能小于0.1") - private Double param16; + @Comment("参数 16 ") + @DecimalMin( + groups = CoalBlendEntity.BlendGroup.class, + value = "0.1", + inclusive = true, + message = "参数不能小于0.1") + private Double param16; - @Comment("参数 17 ") - @DecimalMin( - groups = CoalBlendEntity.BlendGroup.class, - value = "0.1", - inclusive = true, - message = "参数不能小于0.1") - private Double param17; + @Comment("参数 17 ") + @DecimalMin( + groups = CoalBlendEntity.BlendGroup.class, + value = "0.1", + inclusive = true, + message = "参数不能小于0.1") + private Double param17; - @Comment("参数 18 ") - @DecimalMin( - groups = CoalBlendEntity.BlendGroup.class, - value = "0.1", - inclusive = true, - message = "参数不能小于0.1") - private Double param18; + @Comment("参数 18 ") + @DecimalMin( + groups = CoalBlendEntity.BlendGroup.class, + value = "0.1", + inclusive = true, + message = "参数不能小于0.1") + private Double param18; - @Comment("参数 19 ") - @DecimalMin( - groups = CoalBlendEntity.BlendGroup.class, - value = "0.1", - inclusive = true, - message = "参数不能小于0.1") - private Double param19; + @Comment("参数 19 ") + @DecimalMin( + groups = CoalBlendEntity.BlendGroup.class, + value = "0.1", + inclusive = true, + message = "参数不能小于0.1") + private Double param19; - @Comment("参数 20 ") - @DecimalMin( - groups = CoalBlendEntity.BlendGroup.class, - value = "0.1", - inclusive = true, - message = "参数不能小于0.1") - private Double param20; + @Comment("参数 20 ") + @DecimalMin( + groups = CoalBlendEntity.BlendGroup.class, + value = "0.1", + inclusive = true, + message = "参数不能小于0.1") + private Double param20; - @SneakyThrows - public Double getParam(String param) { - return (Double) FieldUtils.getField(this.getClass(), param, true).get(this); - } + @SneakyThrows + public Double getParam(String param) { + return (Double) FieldUtils.getField(this.getClass(), param, true).get(this); + } } diff --git a/src/main/java/cn/lihongjie/coal/coalBlend/entity/CoalBlendConstrainVo.java b/src/main/java/cn/lihongjie/coal/coalBlend/entity/CoalBlendConstrainVo.java index 53104649..730d4810 100644 --- a/src/main/java/cn/lihongjie/coal/coalBlend/entity/CoalBlendConstrainVo.java +++ b/src/main/java/cn/lihongjie/coal/coalBlend/entity/CoalBlendConstrainVo.java @@ -3,210 +3,212 @@ package cn.lihongjie.coal.coalBlend.entity; import jakarta.persistence.Embeddable; import jakarta.validation.constraints.DecimalMax; import jakarta.validation.constraints.DecimalMin; + import lombok.Data; + import org.hibernate.annotations.Comment; @Embeddable @Data public class CoalBlendConstrainVo { - @Comment("参数1最大值") - @DecimalMax(groups = CoalBlendEntity.BlendGroup.class, value = "10000", message = "最大值无效") - @DecimalMin(groups = CoalBlendEntity.BlendGroup.class, value = "0.1", message = "最小值无效") - private Double param1Max; + @Comment("参数1最大值") + @DecimalMax(groups = CoalBlendEntity.BlendGroup.class, value = "10000", message = "最大值无效") + @DecimalMin(groups = CoalBlendEntity.BlendGroup.class, value = "0.1", message = "最小值无效") + private Double param1Max; - @Comment("参数1最小值") - @DecimalMax(groups = CoalBlendEntity.BlendGroup.class, value = "10000", message = "最大值无效") - @DecimalMin(groups = CoalBlendEntity.BlendGroup.class, value = "0.1", message = "最小值无效") - private Double param1Min; + @Comment("参数1最小值") + @DecimalMax(groups = CoalBlendEntity.BlendGroup.class, value = "10000", message = "最大值无效") + @DecimalMin(groups = CoalBlendEntity.BlendGroup.class, value = "0.1", message = "最小值无效") + private Double param1Min; - @Comment("参数2最小值") - @DecimalMax(groups = CoalBlendEntity.BlendGroup.class, value = "10000", message = "最大值无效") - @DecimalMin(groups = CoalBlendEntity.BlendGroup.class, value = "0.1", message = "最小值无效") - private Double param2Min; + @Comment("参数2最小值") + @DecimalMax(groups = CoalBlendEntity.BlendGroup.class, value = "10000", message = "最大值无效") + @DecimalMin(groups = CoalBlendEntity.BlendGroup.class, value = "0.1", message = "最小值无效") + private Double param2Min; - @Comment("参数2最大值") - @DecimalMax(groups = CoalBlendEntity.BlendGroup.class, value = "10000", message = "最大值无效") - @DecimalMin(groups = CoalBlendEntity.BlendGroup.class, value = "0.1", message = "最小值无效") - private Double param2Max; + @Comment("参数2最大值") + @DecimalMax(groups = CoalBlendEntity.BlendGroup.class, value = "10000", message = "最大值无效") + @DecimalMin(groups = CoalBlendEntity.BlendGroup.class, value = "0.1", message = "最小值无效") + private Double param2Max; - @Comment("参数3最小值") - @DecimalMax(groups = CoalBlendEntity.BlendGroup.class, value = "10000", message = "最大值无效") - @DecimalMin(groups = CoalBlendEntity.BlendGroup.class, value = "0.1", message = "最小值无效") - private Double param3Min; + @Comment("参数3最小值") + @DecimalMax(groups = CoalBlendEntity.BlendGroup.class, value = "10000", message = "最大值无效") + @DecimalMin(groups = CoalBlendEntity.BlendGroup.class, value = "0.1", message = "最小值无效") + private Double param3Min; - @Comment("参数3最大值") - @DecimalMax(groups = CoalBlendEntity.BlendGroup.class, value = "10000", message = "最大值无效") - @DecimalMin(groups = CoalBlendEntity.BlendGroup.class, value = "0.1", message = "最小值无效") - private Double param3Max; + @Comment("参数3最大值") + @DecimalMax(groups = CoalBlendEntity.BlendGroup.class, value = "10000", message = "最大值无效") + @DecimalMin(groups = CoalBlendEntity.BlendGroup.class, value = "0.1", message = "最小值无效") + private Double param3Max; - @Comment("参数4最小值") - @DecimalMax(groups = CoalBlendEntity.BlendGroup.class, value = "10000", message = "最大值无效") - @DecimalMin(groups = CoalBlendEntity.BlendGroup.class, value = "0.1", message = "最小值无效") - private Double param4Min; + @Comment("参数4最小值") + @DecimalMax(groups = CoalBlendEntity.BlendGroup.class, value = "10000", message = "最大值无效") + @DecimalMin(groups = CoalBlendEntity.BlendGroup.class, value = "0.1", message = "最小值无效") + private Double param4Min; - @Comment("参数4最大值") - @DecimalMax(groups = CoalBlendEntity.BlendGroup.class, value = "10000", message = "最大值无效") - @DecimalMin(groups = CoalBlendEntity.BlendGroup.class, value = "0.1", message = "最小值无效") - private Double param4Max; + @Comment("参数4最大值") + @DecimalMax(groups = CoalBlendEntity.BlendGroup.class, value = "10000", message = "最大值无效") + @DecimalMin(groups = CoalBlendEntity.BlendGroup.class, value = "0.1", message = "最小值无效") + private Double param4Max; - @Comment("参数5最小值") - @DecimalMax(groups = CoalBlendEntity.BlendGroup.class, value = "10000", message = "最大值无效") - @DecimalMin(groups = CoalBlendEntity.BlendGroup.class, value = "0.1", message = "最小值无效") - private Double param5Min; + @Comment("参数5最小值") + @DecimalMax(groups = CoalBlendEntity.BlendGroup.class, value = "10000", message = "最大值无效") + @DecimalMin(groups = CoalBlendEntity.BlendGroup.class, value = "0.1", message = "最小值无效") + private Double param5Min; - @Comment("参数5最大值") - @DecimalMax(groups = CoalBlendEntity.BlendGroup.class, value = "10000", message = "最大值无效") - @DecimalMin(groups = CoalBlendEntity.BlendGroup.class, value = "0.1", message = "最小值无效") - private Double param5Max; + @Comment("参数5最大值") + @DecimalMax(groups = CoalBlendEntity.BlendGroup.class, value = "10000", message = "最大值无效") + @DecimalMin(groups = CoalBlendEntity.BlendGroup.class, value = "0.1", message = "最小值无效") + private Double param5Max; - @Comment("参数6最小值") - @DecimalMax(groups = CoalBlendEntity.BlendGroup.class, value = "10000", message = "最大值无效") - @DecimalMin(groups = CoalBlendEntity.BlendGroup.class, value = "0.1", message = "最小值无效") - private Double param6Min; + @Comment("参数6最小值") + @DecimalMax(groups = CoalBlendEntity.BlendGroup.class, value = "10000", message = "最大值无效") + @DecimalMin(groups = CoalBlendEntity.BlendGroup.class, value = "0.1", message = "最小值无效") + private Double param6Min; - @Comment("参数6最大值") - @DecimalMax(groups = CoalBlendEntity.BlendGroup.class, value = "10000", message = "最大值无效") - @DecimalMin(groups = CoalBlendEntity.BlendGroup.class, value = "0.1", message = "最小值无效") - private Double param6Max; + @Comment("参数6最大值") + @DecimalMax(groups = CoalBlendEntity.BlendGroup.class, value = "10000", message = "最大值无效") + @DecimalMin(groups = CoalBlendEntity.BlendGroup.class, value = "0.1", message = "最小值无效") + private Double param6Max; - @Comment("参数7最小值") - @DecimalMax(groups = CoalBlendEntity.BlendGroup.class, value = "10000", message = "最大值无效") - @DecimalMin(groups = CoalBlendEntity.BlendGroup.class, value = "0.1", message = "最小值无效") - private Double param7Min; + @Comment("参数7最小值") + @DecimalMax(groups = CoalBlendEntity.BlendGroup.class, value = "10000", message = "最大值无效") + @DecimalMin(groups = CoalBlendEntity.BlendGroup.class, value = "0.1", message = "最小值无效") + private Double param7Min; - @Comment("参数7最大值") - @DecimalMax(groups = CoalBlendEntity.BlendGroup.class, value = "10000", message = "最大值无效") - @DecimalMin(groups = CoalBlendEntity.BlendGroup.class, value = "0.1", message = "最小值无效") - private Double param7Max; + @Comment("参数7最大值") + @DecimalMax(groups = CoalBlendEntity.BlendGroup.class, value = "10000", message = "最大值无效") + @DecimalMin(groups = CoalBlendEntity.BlendGroup.class, value = "0.1", message = "最小值无效") + private Double param7Max; - @Comment("参数8最小值") - @DecimalMax(groups = CoalBlendEntity.BlendGroup.class, value = "10000", message = "最大值无效") - @DecimalMin(groups = CoalBlendEntity.BlendGroup.class, value = "0.1", message = "最小值无效") - private Double param8Min; + @Comment("参数8最小值") + @DecimalMax(groups = CoalBlendEntity.BlendGroup.class, value = "10000", message = "最大值无效") + @DecimalMin(groups = CoalBlendEntity.BlendGroup.class, value = "0.1", message = "最小值无效") + private Double param8Min; - @Comment("参数8最大值") - @DecimalMax(groups = CoalBlendEntity.BlendGroup.class, value = "10000", message = "最大值无效") - @DecimalMin(groups = CoalBlendEntity.BlendGroup.class, value = "0.1", message = "最小值无效") - private Double param8Max; + @Comment("参数8最大值") + @DecimalMax(groups = CoalBlendEntity.BlendGroup.class, value = "10000", message = "最大值无效") + @DecimalMin(groups = CoalBlendEntity.BlendGroup.class, value = "0.1", message = "最小值无效") + private Double param8Max; - @Comment("参数9最小值") - @DecimalMax(groups = CoalBlendEntity.BlendGroup.class, value = "10000", message = "最大值无效") - @DecimalMin(groups = CoalBlendEntity.BlendGroup.class, value = "0.1", message = "最小值无效") - private Double param9Min; + @Comment("参数9最小值") + @DecimalMax(groups = CoalBlendEntity.BlendGroup.class, value = "10000", message = "最大值无效") + @DecimalMin(groups = CoalBlendEntity.BlendGroup.class, value = "0.1", message = "最小值无效") + private Double param9Min; - @Comment("参数9最大值") - @DecimalMax(groups = CoalBlendEntity.BlendGroup.class, value = "10000", message = "最大值无效") - @DecimalMin(groups = CoalBlendEntity.BlendGroup.class, value = "0.1", message = "最小值无效") - private Double param9Max; + @Comment("参数9最大值") + @DecimalMax(groups = CoalBlendEntity.BlendGroup.class, value = "10000", message = "最大值无效") + @DecimalMin(groups = CoalBlendEntity.BlendGroup.class, value = "0.1", message = "最小值无效") + private Double param9Max; - @Comment("参数10最小值") - @DecimalMax(groups = CoalBlendEntity.BlendGroup.class, value = "10000", message = "最大值无效") - @DecimalMin(groups = CoalBlendEntity.BlendGroup.class, value = "0.1", message = "最小值无效") - private Double param10Min; + @Comment("参数10最小值") + @DecimalMax(groups = CoalBlendEntity.BlendGroup.class, value = "10000", message = "最大值无效") + @DecimalMin(groups = CoalBlendEntity.BlendGroup.class, value = "0.1", message = "最小值无效") + private Double param10Min; - @Comment("参数10最大值") - @DecimalMax(groups = CoalBlendEntity.BlendGroup.class, value = "10000", message = "最大值无效") - @DecimalMin(groups = CoalBlendEntity.BlendGroup.class, value = "0.1", message = "最小值无效") - private Double param10Max; + @Comment("参数10最大值") + @DecimalMax(groups = CoalBlendEntity.BlendGroup.class, value = "10000", message = "最大值无效") + @DecimalMin(groups = CoalBlendEntity.BlendGroup.class, value = "0.1", message = "最小值无效") + private Double param10Max; - @Comment("参数11最小值") - @DecimalMax(groups = CoalBlendEntity.BlendGroup.class, value = "10000", message = "最大值无效") - @DecimalMin(groups = CoalBlendEntity.BlendGroup.class, value = "0.1", message = "最小值无效") - private Double param11Min; + @Comment("参数11最小值") + @DecimalMax(groups = CoalBlendEntity.BlendGroup.class, value = "10000", message = "最大值无效") + @DecimalMin(groups = CoalBlendEntity.BlendGroup.class, value = "0.1", message = "最小值无效") + private Double param11Min; - @Comment("参数11最大值") - @DecimalMax(groups = CoalBlendEntity.BlendGroup.class, value = "10000", message = "最大值无效") - @DecimalMin(groups = CoalBlendEntity.BlendGroup.class, value = "0.1", message = "最小值无效") - private Double param11Max; + @Comment("参数11最大值") + @DecimalMax(groups = CoalBlendEntity.BlendGroup.class, value = "10000", message = "最大值无效") + @DecimalMin(groups = CoalBlendEntity.BlendGroup.class, value = "0.1", message = "最小值无效") + private Double param11Max; - @Comment("参数12最小值") - @DecimalMax(groups = CoalBlendEntity.BlendGroup.class, value = "10000", message = "最大值无效") - @DecimalMin(groups = CoalBlendEntity.BlendGroup.class, value = "0.1", message = "最小值无效") - private Double param12Min; + @Comment("参数12最小值") + @DecimalMax(groups = CoalBlendEntity.BlendGroup.class, value = "10000", message = "最大值无效") + @DecimalMin(groups = CoalBlendEntity.BlendGroup.class, value = "0.1", message = "最小值无效") + private Double param12Min; - @Comment("参数12最大值") - @DecimalMax(groups = CoalBlendEntity.BlendGroup.class, value = "10000", message = "最大值无效") - @DecimalMin(groups = CoalBlendEntity.BlendGroup.class, value = "0.1", message = "最小值无效") - private Double param12Max; + @Comment("参数12最大值") + @DecimalMax(groups = CoalBlendEntity.BlendGroup.class, value = "10000", message = "最大值无效") + @DecimalMin(groups = CoalBlendEntity.BlendGroup.class, value = "0.1", message = "最小值无效") + private Double param12Max; - @Comment("参数13最小值") - @DecimalMax(groups = CoalBlendEntity.BlendGroup.class, value = "10000", message = "最大值无效") - @DecimalMin(groups = CoalBlendEntity.BlendGroup.class, value = "0.1", message = "最小值无效") - private Double param13Min; + @Comment("参数13最小值") + @DecimalMax(groups = CoalBlendEntity.BlendGroup.class, value = "10000", message = "最大值无效") + @DecimalMin(groups = CoalBlendEntity.BlendGroup.class, value = "0.1", message = "最小值无效") + private Double param13Min; - @Comment("参数13最大值") - @DecimalMax(groups = CoalBlendEntity.BlendGroup.class, value = "10000", message = "最大值无效") - @DecimalMin(groups = CoalBlendEntity.BlendGroup.class, value = "0.1", message = "最小值无效") - private Double param13Max; + @Comment("参数13最大值") + @DecimalMax(groups = CoalBlendEntity.BlendGroup.class, value = "10000", message = "最大值无效") + @DecimalMin(groups = CoalBlendEntity.BlendGroup.class, value = "0.1", message = "最小值无效") + private Double param13Max; - @Comment("参数14最小值") - @DecimalMax(groups = CoalBlendEntity.BlendGroup.class, value = "10000", message = "最大值无效") - @DecimalMin(groups = CoalBlendEntity.BlendGroup.class, value = "0.1", message = "最小值无效") - private Double param14Min; + @Comment("参数14最小值") + @DecimalMax(groups = CoalBlendEntity.BlendGroup.class, value = "10000", message = "最大值无效") + @DecimalMin(groups = CoalBlendEntity.BlendGroup.class, value = "0.1", message = "最小值无效") + private Double param14Min; - @Comment("参数14最大值") - @DecimalMax(groups = CoalBlendEntity.BlendGroup.class, value = "10000", message = "最大值无效") - @DecimalMin(groups = CoalBlendEntity.BlendGroup.class, value = "0.1", message = "最小值无效") - private Double param14Max; + @Comment("参数14最大值") + @DecimalMax(groups = CoalBlendEntity.BlendGroup.class, value = "10000", message = "最大值无效") + @DecimalMin(groups = CoalBlendEntity.BlendGroup.class, value = "0.1", message = "最小值无效") + private Double param14Max; - @Comment("参数15最小值") - @DecimalMax(groups = CoalBlendEntity.BlendGroup.class, value = "10000", message = "最大值无效") - @DecimalMin(groups = CoalBlendEntity.BlendGroup.class, value = "0.1", message = "最小值无效") - private Double param15Min; + @Comment("参数15最小值") + @DecimalMax(groups = CoalBlendEntity.BlendGroup.class, value = "10000", message = "最大值无效") + @DecimalMin(groups = CoalBlendEntity.BlendGroup.class, value = "0.1", message = "最小值无效") + private Double param15Min; - @Comment("参数15最大值") - @DecimalMax(groups = CoalBlendEntity.BlendGroup.class, value = "10000", message = "最大值无效") - @DecimalMin(groups = CoalBlendEntity.BlendGroup.class, value = "0.1", message = "最小值无效") - private Double param15Max; + @Comment("参数15最大值") + @DecimalMax(groups = CoalBlendEntity.BlendGroup.class, value = "10000", message = "最大值无效") + @DecimalMin(groups = CoalBlendEntity.BlendGroup.class, value = "0.1", message = "最小值无效") + private Double param15Max; - @Comment("参数16最小值") - @DecimalMax(groups = CoalBlendEntity.BlendGroup.class, value = "10000", message = "最大值无效") - @DecimalMin(groups = CoalBlendEntity.BlendGroup.class, value = "0.1", message = "最小值无效") - private Double param16Min; + @Comment("参数16最小值") + @DecimalMax(groups = CoalBlendEntity.BlendGroup.class, value = "10000", message = "最大值无效") + @DecimalMin(groups = CoalBlendEntity.BlendGroup.class, value = "0.1", message = "最小值无效") + private Double param16Min; - @Comment("参数16最大值") - @DecimalMax(groups = CoalBlendEntity.BlendGroup.class, value = "10000", message = "最大值无效") - @DecimalMin(groups = CoalBlendEntity.BlendGroup.class, value = "0.1", message = "最小值无效") - private Double param16Max; + @Comment("参数16最大值") + @DecimalMax(groups = CoalBlendEntity.BlendGroup.class, value = "10000", message = "最大值无效") + @DecimalMin(groups = CoalBlendEntity.BlendGroup.class, value = "0.1", message = "最小值无效") + private Double param16Max; - @Comment("参数17最小值") - @DecimalMax(groups = CoalBlendEntity.BlendGroup.class, value = "10000", message = "最大值无效") - @DecimalMin(groups = CoalBlendEntity.BlendGroup.class, value = "0.1", message = "最小值无效") - private Double param17Min; + @Comment("参数17最小值") + @DecimalMax(groups = CoalBlendEntity.BlendGroup.class, value = "10000", message = "最大值无效") + @DecimalMin(groups = CoalBlendEntity.BlendGroup.class, value = "0.1", message = "最小值无效") + private Double param17Min; - @Comment("参数17最大值") - @DecimalMax(groups = CoalBlendEntity.BlendGroup.class, value = "10000", message = "最大值无效") - @DecimalMin(groups = CoalBlendEntity.BlendGroup.class, value = "0.1", message = "最小值无效") - private Double param17Max; + @Comment("参数17最大值") + @DecimalMax(groups = CoalBlendEntity.BlendGroup.class, value = "10000", message = "最大值无效") + @DecimalMin(groups = CoalBlendEntity.BlendGroup.class, value = "0.1", message = "最小值无效") + private Double param17Max; - @Comment("参数18最小值") - @DecimalMax(groups = CoalBlendEntity.BlendGroup.class, value = "10000", message = "最大值无效") - @DecimalMin(groups = CoalBlendEntity.BlendGroup.class, value = "0.1", message = "最小值无效") - private Double param18Min; + @Comment("参数18最小值") + @DecimalMax(groups = CoalBlendEntity.BlendGroup.class, value = "10000", message = "最大值无效") + @DecimalMin(groups = CoalBlendEntity.BlendGroup.class, value = "0.1", message = "最小值无效") + private Double param18Min; - @Comment("参数18最大值") - @DecimalMax(groups = CoalBlendEntity.BlendGroup.class, value = "10000", message = "最大值无效") - @DecimalMin(groups = CoalBlendEntity.BlendGroup.class, value = "0.1", message = "最小值无效") - private Double param18Max; + @Comment("参数18最大值") + @DecimalMax(groups = CoalBlendEntity.BlendGroup.class, value = "10000", message = "最大值无效") + @DecimalMin(groups = CoalBlendEntity.BlendGroup.class, value = "0.1", message = "最小值无效") + private Double param18Max; - @Comment("参数19最小值") - @DecimalMax(groups = CoalBlendEntity.BlendGroup.class, value = "10000", message = "最大值无效") - @DecimalMin(groups = CoalBlendEntity.BlendGroup.class, value = "0.1", message = "最小值无效") - private Double param19Min; + @Comment("参数19最小值") + @DecimalMax(groups = CoalBlendEntity.BlendGroup.class, value = "10000", message = "最大值无效") + @DecimalMin(groups = CoalBlendEntity.BlendGroup.class, value = "0.1", message = "最小值无效") + private Double param19Min; - @Comment("参数19最大值") - @DecimalMax(groups = CoalBlendEntity.BlendGroup.class, value = "10000", message = "最大值无效") - @DecimalMin(groups = CoalBlendEntity.BlendGroup.class, value = "0.1", message = "最小值无效") - private Double param19Max; + @Comment("参数19最大值") + @DecimalMax(groups = CoalBlendEntity.BlendGroup.class, value = "10000", message = "最大值无效") + @DecimalMin(groups = CoalBlendEntity.BlendGroup.class, value = "0.1", message = "最小值无效") + private Double param19Max; - @Comment("参数20最小值") - @DecimalMax(groups = CoalBlendEntity.BlendGroup.class, value = "10000", message = "最大值无效") - @DecimalMin(groups = CoalBlendEntity.BlendGroup.class, value = "0.1", message = "最小值无效") - private Double param20Min; + @Comment("参数20最小值") + @DecimalMax(groups = CoalBlendEntity.BlendGroup.class, value = "10000", message = "最大值无效") + @DecimalMin(groups = CoalBlendEntity.BlendGroup.class, value = "0.1", message = "最小值无效") + private Double param20Min; - @Comment("参数20最大值") - @DecimalMax(groups = CoalBlendEntity.BlendGroup.class, value = "10000", message = "最大值无效") - @DecimalMin(groups = CoalBlendEntity.BlendGroup.class, value = "0.1", message = "最小值无效") - private Double param20Max; + @Comment("参数20最大值") + @DecimalMax(groups = CoalBlendEntity.BlendGroup.class, value = "10000", message = "最大值无效") + @DecimalMin(groups = CoalBlendEntity.BlendGroup.class, value = "0.1", message = "最小值无效") + private Double param20Max; } diff --git a/src/main/java/cn/lihongjie/coal/coalBlend/entity/CoalBlendEntity.java b/src/main/java/cn/lihongjie/coal/coalBlend/entity/CoalBlendEntity.java index ee7d5258..3f1408c4 100644 --- a/src/main/java/cn/lihongjie/coal/coalBlend/entity/CoalBlendEntity.java +++ b/src/main/java/cn/lihongjie/coal/coalBlend/entity/CoalBlendEntity.java @@ -2,24 +2,30 @@ package cn.lihongjie.coal.coalBlend.entity; import cn.lihongjie.coal.base.entity.OrgCommonEntity; import cn.lihongjie.coal.exception.BizException; + import com.google.ortools.Loader; import com.google.ortools.sat.*; + import io.vavr.collection.Stream; + import jakarta.persistence.*; import jakarta.validation.constraints.NotEmpty; import jakarta.validation.constraints.NotNull; import jakarta.validation.constraints.Size; + +import lombok.Data; +import lombok.extern.slf4j.Slf4j; + +import org.apache.commons.lang3.StringUtils; +import org.hibernate.annotations.Comment; +import org.hibernate.annotations.Formula; +import org.springframework.util.StopWatch; + import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Objects; import java.util.concurrent.atomic.AtomicBoolean; -import lombok.Data; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; -import org.hibernate.annotations.Comment; -import org.hibernate.annotations.Formula; -import org.springframework.util.StopWatch; @Entity @Data @@ -27,911 +33,1039 @@ import org.springframework.util.StopWatch; @Slf4j public class CoalBlendEntity extends OrgCommonEntity { - @ElementCollection - @NotEmpty(message = "煤参数定义不能为空") - private List parameterDefs; + @ElementCollection + @NotEmpty(message = "煤参数定义不能为空") + private List parameterDefs; - @NotEmpty(message = "煤不能为空") - @Size(message = "至少需要两种煤", min = 2) - @OneToMany(mappedBy = "coal", cascade = CascadeType.ALL, orphanRemoval = true) - private List coals; + @NotEmpty(message = "煤不能为空") + @Size(message = "至少需要两种煤", min = 2) + @OneToMany(mappedBy = "coal", cascade = CascadeType.ALL, orphanRemoval = true) + private List coals; - @NotNull(message = "约束条件不能为空") - private CoalBlendConstrainVo constrains; + @NotNull(message = "约束条件不能为空") + private CoalBlendConstrainVo constrains; - @OneToMany(mappedBy = "coal", cascade = CascadeType.ALL, orphanRemoval = true) - private List results; + @OneToMany(mappedBy = "coal", cascade = CascadeType.ALL, orphanRemoval = true) + private List results; - @Comment("配煤类型") - private String blendType; + @Comment("配煤类型") + private String blendType; - @Formula( - "(select i.name\n" - + "from t_dictionary d,\n" - + " t_dictionary_item i\n" - + "where d.id = i.dictionary_id\n" - + " and d.code = 'coal.blendType'\n" - + " and i.code = blend_type)") - private String blendTypeName; + @Formula( + "(select i.name\n" + + "from t_dictionary d,\n" + + " t_dictionary_item i\n" + + "where d.id = i.dictionary_id\n" + + " and d.code = 'coal.blendType'\n" + + " and i.code = blend_type)") + private String blendTypeName; - @Comment("结果个数") - private Integer count = 20; + @Comment("结果个数") + private Integer count = 20; - @Comment("最长等待时间") - private Integer maxTime = 10; + @Comment("最长等待时间") + private Integer maxTime = 10; - @Comment("铲车配煤 配比之和 最大值") - private Integer type2PercentSum = 10; + @Comment("铲车配煤 配比之和 最大值") + private Integer type2PercentSum = 10; + + @Comment("目标参数, 比如: param1 param2") + private String targetParam = ""; - @Comment("目标参数, 比如: param1 param2") - private String targetParam = ""; + @Comment("求目标参数最大值 -1, 最小值 1") + private Integer targetOrder = -1; - @Comment("求目标参数最大值 -1, 最小值 1") - private Integer targetOrder = -1; - - public static class BlendGroup {} - - public void blend() { - - StopWatch stopWatch = new StopWatch(); - - this.results = new ArrayList<>(); - - stopWatch.start("check 1"); - long count1 = 0; - count1 = coals.stream().map(x1 -> x1.getParam1()).filter(Objects::nonNull).count(); - - AtomicBoolean param1 = new AtomicBoolean(false); - if (count1 > 0 && count1 != coals.size()) { - throw new BizException("煤的参数不可以留空"); - } else { - - param1.set(count1 > 0); - } - count1 = coals.stream().map(x1 -> x1.getParam2()).filter(Objects::nonNull).count(); - - AtomicBoolean param2 = new AtomicBoolean(false); - if (count1 > 0 && count1 != coals.size()) { - throw new BizException("煤的参数不可以留空"); - } else { - - param2.set(count1 > 0); - } - count1 = coals.stream().map(x1 -> x1.getParam3()).filter(Objects::nonNull).count(); - - AtomicBoolean param3 = new AtomicBoolean(false); - if (count1 > 0 && count1 != coals.size()) { - throw new BizException("煤的参数不可以留空"); - } else { - - param3.set(count1 > 0); - } - count1 = coals.stream().map(x1 -> x1.getParam4()).filter(Objects::nonNull).count(); - - AtomicBoolean param4 = new AtomicBoolean(false); - if (count1 > 0 && count1 != coals.size()) { - throw new BizException("煤的参数不可以留空"); - } else { - - param4.set(count1 > 0); - } - count1 = coals.stream().map(x1 -> x1.getParam5()).filter(Objects::nonNull).count(); - - AtomicBoolean param5 = new AtomicBoolean(false); - if (count1 > 0 && count1 != coals.size()) { - throw new BizException("煤的参数不可以留空"); - } else { - - param5.set(count1 > 0); - } - count1 = coals.stream().map(x1 -> x1.getParam6()).filter(Objects::nonNull).count(); - - AtomicBoolean param6 = new AtomicBoolean(false); - if (count1 > 0 && count1 != coals.size()) { - throw new BizException("煤的参数不可以留空"); - } else { - - param6.set(count1 > 0); - } - count1 = coals.stream().map(x1 -> x1.getParam7()).filter(Objects::nonNull).count(); - - AtomicBoolean param7 = new AtomicBoolean(false); - if (count1 > 0 && count1 != coals.size()) { - throw new BizException("煤的参数不可以留空"); - } else { - - param7.set(count1 > 0); - } - count1 = coals.stream().map(x1 -> x1.getParam8()).filter(Objects::nonNull).count(); - - AtomicBoolean param8 = new AtomicBoolean(false); - if (count1 > 0 && count1 != coals.size()) { - throw new BizException("煤的参数不可以留空"); - } else { - - param8.set(count1 > 0); - } - count1 = coals.stream().map(x1 -> x1.getParam9()).filter(Objects::nonNull).count(); - - AtomicBoolean param9 = new AtomicBoolean(false); - if (count1 > 0 && count1 != coals.size()) { - throw new BizException("煤的参数不可以留空"); - } else { - - param9.set(count1 > 0); - } - count1 = coals.stream().map(x1 -> x1.getParam10()).filter(Objects::nonNull).count(); - - AtomicBoolean param10 = new AtomicBoolean(false); - if (count1 > 0 && count1 != coals.size()) { - throw new BizException("煤的参数不可以留空"); - } else { - - param10.set(count1 > 0); - } - count1 = coals.stream().map(x1 -> x1.getParam11()).filter(Objects::nonNull).count(); - - AtomicBoolean param11 = new AtomicBoolean(false); - if (count1 > 0 && count1 != coals.size()) { - throw new BizException("煤的参数不可以留空"); - } else { - - param11.set(count1 > 0); - } - count1 = coals.stream().map(x1 -> x1.getParam12()).filter(Objects::nonNull).count(); - - AtomicBoolean param12 = new AtomicBoolean(false); - if (count1 > 0 && count1 != coals.size()) { - throw new BizException("煤的参数不可以留空"); - } else { - - param12.set(count1 > 0); - } - count1 = coals.stream().map(x1 -> x1.getParam13()).filter(Objects::nonNull).count(); - - AtomicBoolean param13 = new AtomicBoolean(false); - if (count1 > 0 && count1 != coals.size()) { - throw new BizException("煤的参数不可以留空"); - } else { - - param13.set(count1 > 0); - } - count1 = coals.stream().map(x1 -> x1.getParam14()).filter(Objects::nonNull).count(); - - AtomicBoolean param14 = new AtomicBoolean(false); - if (count1 > 0 && count1 != coals.size()) { - throw new BizException("煤的参数不可以留空"); - } else { - - param14.set(count1 > 0); - } - count1 = coals.stream().map(x1 -> x1.getParam15()).filter(Objects::nonNull).count(); - - AtomicBoolean param15 = new AtomicBoolean(false); - if (count1 > 0 && count1 != coals.size()) { - throw new BizException("煤的参数不可以留空"); - } else { - - param15.set(count1 > 0); - } - count1 = coals.stream().map(x1 -> x1.getParam16()).filter(Objects::nonNull).count(); - - AtomicBoolean param16 = new AtomicBoolean(false); - if (count1 > 0 && count1 != coals.size()) { - throw new BizException("煤的参数不可以留空"); - } else { - - param16.set(count1 > 0); - } - count1 = coals.stream().map(x1 -> x1.getParam17()).filter(Objects::nonNull).count(); - - AtomicBoolean param17 = new AtomicBoolean(false); - if (count1 > 0 && count1 != coals.size()) { - throw new BizException("煤的参数不可以留空"); - } else { - - param17.set(count1 > 0); - } - count1 = coals.stream().map(x1 -> x1.getParam18()).filter(Objects::nonNull).count(); - - AtomicBoolean param18 = new AtomicBoolean(false); - if (count1 > 0 && count1 != coals.size()) { - throw new BizException("煤的参数不可以留空"); - } else { - - param18.set(count1 > 0); - } - count1 = coals.stream().map(x1 -> x1.getParam19()).filter(Objects::nonNull).count(); - - AtomicBoolean param19 = new AtomicBoolean(false); - if (count1 > 0 && count1 != coals.size()) { - throw new BizException("煤的参数不可以留空"); - } else { - - param19.set(count1 > 0); - } - count1 = coals.stream().map(x1 -> x1.getParam20()).filter(Objects::nonNull).count(); - - AtomicBoolean param20 = new AtomicBoolean(false); - if (count1 > 0 && count1 != coals.size()) { - throw new BizException("煤的参数不可以留空"); - } else { - - param20.set(count1 > 0); - } - - stopWatch.stop(); - stopWatch.start("loadNativeLibraries"); - - Loader.loadNativeLibraries(); - - stopWatch.stop(); - stopWatch.start("CpModel"); - CpModel model = new CpModel(); - - Stream percentVal = - Stream.ofAll(coals) - .zipWithIndex( - (c, i) -> { - return model.newIntVar(c.getMinPercent(), c.getMaxPercent(), "x" + i); - }); - - IntVar[] percentValArr = percentVal.toJavaArray(IntVar[]::new); - // 各个煤累加和 100 - model.addEquality(LinearExpr.sum(percentValArr), 100); - addBaseConstrain(model, percentValArr); - - IntVar gcd = model.newIntVar(2, 100, "gcd"); - Stream gcdVal = null; - - if (Objects.equals(blendType, "2")) { - - gcdVal = - Stream.ofAll(coals) - .zipWithIndex( - (c, i) -> model.newIntVar(c.getMinPercent(), c.getMaxPercent(), "gcdX" + i)); - percentVal.zip(gcdVal).forEach(t -> model.addDivisionEquality(t._2, t._1, gcd)); - percentVal - .zip(gcdVal) - .forEach(t -> model.addModuloEquality(LinearExpr.constant(0), t._1, gcd)); - - model.addLessOrEqual(LinearExpr.sum(gcdVal.toJavaArray(IntVar[]::new)), type2PercentSum); - } - - if (StringUtils.isNotEmpty(targetParam)) { - if (targetOrder == -1) { - - model.maximize( - LinearExpr.weightedSum( - percentValArr, - coals.stream().mapToLong(x -> (long) (x.getParam(targetParam) * 100)).toArray())); - - } else { - - model.minimize( - LinearExpr.weightedSum( - percentValArr, - coals.stream().mapToLong(x -> (long) (x.getParam(targetParam) * 100)).toArray())); - } - } - stopWatch.stop(); - stopWatch.start("CpSolver"); - - // 初始化求解器 - CpSolver cpSolver = new CpSolver(); - SatParameters.Builder parameters = cpSolver.getParameters(); - parameters.setEnumerateAllSolutions(true); - parameters.setMaxTimeInSeconds(this.getMaxTime()); - parameters.setLogSearchProgress(true); - - cpSolver.setLogCallback((x) -> {}); - parameters.setFillAdditionalSolutionsInResponse(false); - HashSet seen = new HashSet<>(); - Stream finalGcdVal = gcdVal; - try { - - cpSolver.solve( - model, - new CpSolverSolutionCallback() { - - @Override - public void onSolutionCallback() { - - CoalBlendResultInfoEntity vo = new CoalBlendResultInfoEntity(); - - if (finalGcdVal != null) { - - vo.setPercentInfos( - Stream.ofAll(coals) - .zip(percentVal) - .zip(finalGcdVal) - .map( - t -> - new CoalPercentVo( - t._1._1.getName(), - ((double) (value(t._1._2))), - (double) value(t._2))) - .toJavaList()); - } else { - vo.setPercentInfos( - Stream.ofAll(coals) - .zip(percentVal) - .zip(percentVal) - .map( - t -> - new CoalPercentVo( - t._1._1.getName(), - ((double) (value(t._1._2))), - (double) value(t._2))) - .toJavaList()); - } - if (!seen.add(vo.getHashKey())) { - return; - } - - if (param1.get()) - vo.setParam1( - value( - LinearExpr.weightedSum( - percentValArr, - coals.stream() - .mapToLong(x -> (long) (x.getParam1() * 100)) - .toArray())) - / 10000.0); - if (param2.get()) - vo.setParam2( - value( - LinearExpr.weightedSum( - percentValArr, - coals.stream() - .mapToLong(x -> (long) (x.getParam2() * 100)) - .toArray())) - / 10000.0); - if (param3.get()) - vo.setParam3( - value( - LinearExpr.weightedSum( - percentValArr, - coals.stream() - .mapToLong(x -> (long) (x.getParam3() * 100)) - .toArray())) - / 10000.0); - if (param4.get()) - vo.setParam4( - value( - LinearExpr.weightedSum( - percentValArr, - coals.stream() - .mapToLong(x -> (long) (x.getParam4() * 100)) - .toArray())) - / 10000.0); - if (param5.get()) - vo.setParam5( - value( - LinearExpr.weightedSum( - percentValArr, - coals.stream() - .mapToLong(x -> (long) (x.getParam5() * 100)) - .toArray())) - / 10000.0); - if (param6.get()) - vo.setParam6( - value( - LinearExpr.weightedSum( - percentValArr, - coals.stream() - .mapToLong(x -> (long) (x.getParam6() * 100)) - .toArray())) - / 10000.0); - if (param7.get()) - vo.setParam7( - value( - LinearExpr.weightedSum( - percentValArr, - coals.stream() - .mapToLong(x -> (long) (x.getParam7() * 100)) - .toArray())) - / 10000.0); - if (param8.get()) - vo.setParam8( - value( - LinearExpr.weightedSum( - percentValArr, - coals.stream() - .mapToLong(x -> (long) (x.getParam8() * 100)) - .toArray())) - / 10000.0); - if (param9.get()) - vo.setParam9( - value( - LinearExpr.weightedSum( - percentValArr, - coals.stream() - .mapToLong(x -> (long) (x.getParam9() * 100)) - .toArray())) - / 10000.0); - if (param10.get()) - vo.setParam10( - value( - LinearExpr.weightedSum( - percentValArr, - coals.stream() - .mapToLong(x -> (long) (x.getParam10() * 100)) - .toArray())) - / 10000.0); - if (param11.get()) - vo.setParam11( - value( - LinearExpr.weightedSum( - percentValArr, - coals.stream() - .mapToLong(x -> (long) (x.getParam11() * 100)) - .toArray())) - / 10000.0); - if (param12.get()) - vo.setParam12( - value( - LinearExpr.weightedSum( - percentValArr, - coals.stream() - .mapToLong(x -> (long) (x.getParam12() * 100)) - .toArray())) - / 10000.0); - if (param13.get()) - vo.setParam13( - value( - LinearExpr.weightedSum( - percentValArr, - coals.stream() - .mapToLong(x -> (long) (x.getParam13() * 100)) - .toArray())) - / 10000.0); - if (param14.get()) - vo.setParam14( - value( - LinearExpr.weightedSum( - percentValArr, - coals.stream() - .mapToLong(x -> (long) (x.getParam14() * 100)) - .toArray())) - / 10000.0); - if (param15.get()) - vo.setParam15( - value( - LinearExpr.weightedSum( - percentValArr, - coals.stream() - .mapToLong(x -> (long) (x.getParam15() * 100)) - .toArray())) - / 10000.0); - if (param16.get()) - vo.setParam16( - value( - LinearExpr.weightedSum( - percentValArr, - coals.stream() - .mapToLong(x -> (long) (x.getParam16() * 100)) - .toArray())) - / 10000.0); - if (param17.get()) - vo.setParam17( - value( - LinearExpr.weightedSum( - percentValArr, - coals.stream() - .mapToLong(x -> (long) (x.getParam17() * 100)) - .toArray())) - / 10000.0); - if (param18.get()) - vo.setParam18( - value( - LinearExpr.weightedSum( - percentValArr, - coals.stream() - .mapToLong(x -> (long) (x.getParam18() * 100)) - .toArray())) - / 10000.0); - if (param19.get()) - vo.setParam19( - value( - LinearExpr.weightedSum( - percentValArr, - coals.stream() - .mapToLong(x -> (long) (x.getParam19() * 100)) - .toArray())) - / 10000.0); - if (param20.get()) - vo.setParam20( - value( - LinearExpr.weightedSum( - percentValArr, - coals.stream() - .mapToLong(x -> (long) (x.getParam20() * 100)) - .toArray())) - / 10000.0); - - CoalBlendEntity.this.results.add(vo); - - if (CoalBlendEntity.this.results.size() >= CoalBlendEntity.this.count) { - stopSearch(); - } - } - }); - - } catch (Throwable e) { - log.error("{}", e); - - } finally { - - if (stopWatch.isRunning()) { + public void blend() { + + StopWatch stopWatch = new StopWatch(); + + this.results = new ArrayList<>(); + + stopWatch.start("check 1"); + long count1 = 0; + count1 = coals.stream().map(x1 -> x1.getParam1()).filter(Objects::nonNull).count(); + + AtomicBoolean param1 = new AtomicBoolean(false); + if (count1 > 0 && count1 != coals.size()) { + throw new BizException("煤的参数不可以留空"); + } else { + + param1.set(count1 > 0); + } + count1 = coals.stream().map(x1 -> x1.getParam2()).filter(Objects::nonNull).count(); + + AtomicBoolean param2 = new AtomicBoolean(false); + if (count1 > 0 && count1 != coals.size()) { + throw new BizException("煤的参数不可以留空"); + } else { + + param2.set(count1 > 0); + } + count1 = coals.stream().map(x1 -> x1.getParam3()).filter(Objects::nonNull).count(); + + AtomicBoolean param3 = new AtomicBoolean(false); + if (count1 > 0 && count1 != coals.size()) { + throw new BizException("煤的参数不可以留空"); + } else { + + param3.set(count1 > 0); + } + count1 = coals.stream().map(x1 -> x1.getParam4()).filter(Objects::nonNull).count(); + + AtomicBoolean param4 = new AtomicBoolean(false); + if (count1 > 0 && count1 != coals.size()) { + throw new BizException("煤的参数不可以留空"); + } else { + + param4.set(count1 > 0); + } + count1 = coals.stream().map(x1 -> x1.getParam5()).filter(Objects::nonNull).count(); + + AtomicBoolean param5 = new AtomicBoolean(false); + if (count1 > 0 && count1 != coals.size()) { + throw new BizException("煤的参数不可以留空"); + } else { + + param5.set(count1 > 0); + } + count1 = coals.stream().map(x1 -> x1.getParam6()).filter(Objects::nonNull).count(); + + AtomicBoolean param6 = new AtomicBoolean(false); + if (count1 > 0 && count1 != coals.size()) { + throw new BizException("煤的参数不可以留空"); + } else { + + param6.set(count1 > 0); + } + count1 = coals.stream().map(x1 -> x1.getParam7()).filter(Objects::nonNull).count(); + + AtomicBoolean param7 = new AtomicBoolean(false); + if (count1 > 0 && count1 != coals.size()) { + throw new BizException("煤的参数不可以留空"); + } else { + + param7.set(count1 > 0); + } + count1 = coals.stream().map(x1 -> x1.getParam8()).filter(Objects::nonNull).count(); + + AtomicBoolean param8 = new AtomicBoolean(false); + if (count1 > 0 && count1 != coals.size()) { + throw new BizException("煤的参数不可以留空"); + } else { + + param8.set(count1 > 0); + } + count1 = coals.stream().map(x1 -> x1.getParam9()).filter(Objects::nonNull).count(); + + AtomicBoolean param9 = new AtomicBoolean(false); + if (count1 > 0 && count1 != coals.size()) { + throw new BizException("煤的参数不可以留空"); + } else { + + param9.set(count1 > 0); + } + count1 = coals.stream().map(x1 -> x1.getParam10()).filter(Objects::nonNull).count(); + + AtomicBoolean param10 = new AtomicBoolean(false); + if (count1 > 0 && count1 != coals.size()) { + throw new BizException("煤的参数不可以留空"); + } else { + + param10.set(count1 > 0); + } + count1 = coals.stream().map(x1 -> x1.getParam11()).filter(Objects::nonNull).count(); + + AtomicBoolean param11 = new AtomicBoolean(false); + if (count1 > 0 && count1 != coals.size()) { + throw new BizException("煤的参数不可以留空"); + } else { + + param11.set(count1 > 0); + } + count1 = coals.stream().map(x1 -> x1.getParam12()).filter(Objects::nonNull).count(); + + AtomicBoolean param12 = new AtomicBoolean(false); + if (count1 > 0 && count1 != coals.size()) { + throw new BizException("煤的参数不可以留空"); + } else { + + param12.set(count1 > 0); + } + count1 = coals.stream().map(x1 -> x1.getParam13()).filter(Objects::nonNull).count(); + + AtomicBoolean param13 = new AtomicBoolean(false); + if (count1 > 0 && count1 != coals.size()) { + throw new BizException("煤的参数不可以留空"); + } else { + + param13.set(count1 > 0); + } + count1 = coals.stream().map(x1 -> x1.getParam14()).filter(Objects::nonNull).count(); + + AtomicBoolean param14 = new AtomicBoolean(false); + if (count1 > 0 && count1 != coals.size()) { + throw new BizException("煤的参数不可以留空"); + } else { + + param14.set(count1 > 0); + } + count1 = coals.stream().map(x1 -> x1.getParam15()).filter(Objects::nonNull).count(); + + AtomicBoolean param15 = new AtomicBoolean(false); + if (count1 > 0 && count1 != coals.size()) { + throw new BizException("煤的参数不可以留空"); + } else { + + param15.set(count1 > 0); + } + count1 = coals.stream().map(x1 -> x1.getParam16()).filter(Objects::nonNull).count(); + + AtomicBoolean param16 = new AtomicBoolean(false); + if (count1 > 0 && count1 != coals.size()) { + throw new BizException("煤的参数不可以留空"); + } else { + + param16.set(count1 > 0); + } + count1 = coals.stream().map(x1 -> x1.getParam17()).filter(Objects::nonNull).count(); + + AtomicBoolean param17 = new AtomicBoolean(false); + if (count1 > 0 && count1 != coals.size()) { + throw new BizException("煤的参数不可以留空"); + } else { + + param17.set(count1 > 0); + } + count1 = coals.stream().map(x1 -> x1.getParam18()).filter(Objects::nonNull).count(); + + AtomicBoolean param18 = new AtomicBoolean(false); + if (count1 > 0 && count1 != coals.size()) { + throw new BizException("煤的参数不可以留空"); + } else { + + param18.set(count1 > 0); + } + count1 = coals.stream().map(x1 -> x1.getParam19()).filter(Objects::nonNull).count(); + + AtomicBoolean param19 = new AtomicBoolean(false); + if (count1 > 0 && count1 != coals.size()) { + throw new BizException("煤的参数不可以留空"); + } else { + + param19.set(count1 > 0); + } + count1 = coals.stream().map(x1 -> x1.getParam20()).filter(Objects::nonNull).count(); + + AtomicBoolean param20 = new AtomicBoolean(false); + if (count1 > 0 && count1 != coals.size()) { + throw new BizException("煤的参数不可以留空"); + } else { + + param20.set(count1 > 0); + } stopWatch.stop(); - } - log.info(stopWatch.prettyPrint()); - } - } + stopWatch.start("loadNativeLibraries"); - /** - * 添加参数依赖 - * - * @param model - * @param percentValArr - */ - private void addBaseConstrain(CpModel model, IntVar[] percentValArr) { - Double val = null; + Loader.loadNativeLibraries(); - val = constrains.getParam1Min(); + stopWatch.stop(); + stopWatch.start("CpModel"); + CpModel model = new CpModel(); - if (val != null) { - model.addGreaterOrEqual( - LinearExpr.weightedSum( - percentValArr, coals.stream().mapToLong(x -> (long) (x.getParam1() * 100)).toArray()), - (long) (val * 10000)); + Stream percentVal = + Stream.ofAll(coals) + .zipWithIndex( + (c, i) -> { + return model.newIntVar( + c.getMinPercent(), c.getMaxPercent(), "x" + i); + }); + + IntVar[] percentValArr = percentVal.toJavaArray(IntVar[]::new); + // 各个煤累加和 100 + model.addEquality(LinearExpr.sum(percentValArr), 100); + addBaseConstrain(model, percentValArr); + + IntVar gcd = model.newIntVar(2, 100, "gcd"); + Stream gcdVal = null; + + if (Objects.equals(blendType, "2")) { + + gcdVal = + Stream.ofAll(coals) + .zipWithIndex( + (c, i) -> + model.newIntVar( + c.getMinPercent(), + c.getMaxPercent(), + "gcdX" + i)); + percentVal.zip(gcdVal).forEach(t -> model.addDivisionEquality(t._2, t._1, gcd)); + percentVal + .zip(gcdVal) + .forEach(t -> model.addModuloEquality(LinearExpr.constant(0), t._1, gcd)); + + model.addLessOrEqual( + LinearExpr.sum(gcdVal.toJavaArray(IntVar[]::new)), type2PercentSum); + } + + if (StringUtils.isNotEmpty(targetParam)) { + if (targetOrder == -1) { + + model.maximize( + LinearExpr.weightedSum( + percentValArr, + coals.stream() + .mapToLong(x -> (long) (x.getParam(targetParam) * 100)) + .toArray())); + + } else { + + model.minimize( + LinearExpr.weightedSum( + percentValArr, + coals.stream() + .mapToLong(x -> (long) (x.getParam(targetParam) * 100)) + .toArray())); + } + } + stopWatch.stop(); + stopWatch.start("CpSolver"); + + // 初始化求解器 + CpSolver cpSolver = new CpSolver(); + SatParameters.Builder parameters = cpSolver.getParameters(); + parameters.setEnumerateAllSolutions(true); + parameters.setMaxTimeInSeconds(this.getMaxTime()); + parameters.setLogSearchProgress(true); + + cpSolver.setLogCallback((x) -> {}); + parameters.setFillAdditionalSolutionsInResponse(false); + HashSet seen = new HashSet<>(); + Stream finalGcdVal = gcdVal; + try { + + cpSolver.solve( + model, + new CpSolverSolutionCallback() { + + @Override + public void onSolutionCallback() { + + CoalBlendResultInfoEntity vo = new CoalBlendResultInfoEntity(); + + if (finalGcdVal != null) { + + vo.setPercentInfos( + Stream.ofAll(coals) + .zip(percentVal) + .zip(finalGcdVal) + .map( + t -> + new CoalPercentVo( + t._1._1.getName(), + ((double) (value(t._1._2))), + (double) value(t._2))) + .toJavaList()); + } else { + vo.setPercentInfos( + Stream.ofAll(coals) + .zip(percentVal) + .zip(percentVal) + .map( + t -> + new CoalPercentVo( + t._1._1.getName(), + ((double) (value(t._1._2))), + (double) value(t._2))) + .toJavaList()); + } + if (!seen.add(vo.getHashKey())) { + return; + } + + if (param1.get()) + vo.setParam1( + value( + LinearExpr.weightedSum( + percentValArr, + coals.stream() + .mapToLong( + x -> + (long) + (x + .getParam1() + * 100)) + .toArray())) + / 10000.0); + if (param2.get()) + vo.setParam2( + value( + LinearExpr.weightedSum( + percentValArr, + coals.stream() + .mapToLong( + x -> + (long) + (x + .getParam2() + * 100)) + .toArray())) + / 10000.0); + if (param3.get()) + vo.setParam3( + value( + LinearExpr.weightedSum( + percentValArr, + coals.stream() + .mapToLong( + x -> + (long) + (x + .getParam3() + * 100)) + .toArray())) + / 10000.0); + if (param4.get()) + vo.setParam4( + value( + LinearExpr.weightedSum( + percentValArr, + coals.stream() + .mapToLong( + x -> + (long) + (x + .getParam4() + * 100)) + .toArray())) + / 10000.0); + if (param5.get()) + vo.setParam5( + value( + LinearExpr.weightedSum( + percentValArr, + coals.stream() + .mapToLong( + x -> + (long) + (x + .getParam5() + * 100)) + .toArray())) + / 10000.0); + if (param6.get()) + vo.setParam6( + value( + LinearExpr.weightedSum( + percentValArr, + coals.stream() + .mapToLong( + x -> + (long) + (x + .getParam6() + * 100)) + .toArray())) + / 10000.0); + if (param7.get()) + vo.setParam7( + value( + LinearExpr.weightedSum( + percentValArr, + coals.stream() + .mapToLong( + x -> + (long) + (x + .getParam7() + * 100)) + .toArray())) + / 10000.0); + if (param8.get()) + vo.setParam8( + value( + LinearExpr.weightedSum( + percentValArr, + coals.stream() + .mapToLong( + x -> + (long) + (x + .getParam8() + * 100)) + .toArray())) + / 10000.0); + if (param9.get()) + vo.setParam9( + value( + LinearExpr.weightedSum( + percentValArr, + coals.stream() + .mapToLong( + x -> + (long) + (x + .getParam9() + * 100)) + .toArray())) + / 10000.0); + if (param10.get()) + vo.setParam10( + value( + LinearExpr.weightedSum( + percentValArr, + coals.stream() + .mapToLong( + x -> + (long) + (x + .getParam10() + * 100)) + .toArray())) + / 10000.0); + if (param11.get()) + vo.setParam11( + value( + LinearExpr.weightedSum( + percentValArr, + coals.stream() + .mapToLong( + x -> + (long) + (x + .getParam11() + * 100)) + .toArray())) + / 10000.0); + if (param12.get()) + vo.setParam12( + value( + LinearExpr.weightedSum( + percentValArr, + coals.stream() + .mapToLong( + x -> + (long) + (x + .getParam12() + * 100)) + .toArray())) + / 10000.0); + if (param13.get()) + vo.setParam13( + value( + LinearExpr.weightedSum( + percentValArr, + coals.stream() + .mapToLong( + x -> + (long) + (x + .getParam13() + * 100)) + .toArray())) + / 10000.0); + if (param14.get()) + vo.setParam14( + value( + LinearExpr.weightedSum( + percentValArr, + coals.stream() + .mapToLong( + x -> + (long) + (x + .getParam14() + * 100)) + .toArray())) + / 10000.0); + if (param15.get()) + vo.setParam15( + value( + LinearExpr.weightedSum( + percentValArr, + coals.stream() + .mapToLong( + x -> + (long) + (x + .getParam15() + * 100)) + .toArray())) + / 10000.0); + if (param16.get()) + vo.setParam16( + value( + LinearExpr.weightedSum( + percentValArr, + coals.stream() + .mapToLong( + x -> + (long) + (x + .getParam16() + * 100)) + .toArray())) + / 10000.0); + if (param17.get()) + vo.setParam17( + value( + LinearExpr.weightedSum( + percentValArr, + coals.stream() + .mapToLong( + x -> + (long) + (x + .getParam17() + * 100)) + .toArray())) + / 10000.0); + if (param18.get()) + vo.setParam18( + value( + LinearExpr.weightedSum( + percentValArr, + coals.stream() + .mapToLong( + x -> + (long) + (x + .getParam18() + * 100)) + .toArray())) + / 10000.0); + if (param19.get()) + vo.setParam19( + value( + LinearExpr.weightedSum( + percentValArr, + coals.stream() + .mapToLong( + x -> + (long) + (x + .getParam19() + * 100)) + .toArray())) + / 10000.0); + if (param20.get()) + vo.setParam20( + value( + LinearExpr.weightedSum( + percentValArr, + coals.stream() + .mapToLong( + x -> + (long) + (x + .getParam20() + * 100)) + .toArray())) + / 10000.0); + + CoalBlendEntity.this.results.add(vo); + + if (CoalBlendEntity.this.results.size() >= CoalBlendEntity.this.count) { + stopSearch(); + } + } + }); + + } catch (Throwable e) { + log.error("{}", e); + + } finally { + + if (stopWatch.isRunning()) { + + stopWatch.stop(); + } + log.info(stopWatch.prettyPrint()); + } } - val = constrains.getParam2Min(); + /** + * 添加参数依赖 + * + * @param model + * @param percentValArr + */ + private void addBaseConstrain(CpModel model, IntVar[] percentValArr) { + Double val = null; - if (val != null) { - model.addGreaterOrEqual( - LinearExpr.weightedSum( - percentValArr, coals.stream().mapToLong(x -> (long) (x.getParam2() * 100)).toArray()), - (long) (val * 10000)); + val = constrains.getParam1Min(); + + if (val != null) { + model.addGreaterOrEqual( + LinearExpr.weightedSum( + percentValArr, + coals.stream().mapToLong(x -> (long) (x.getParam1() * 100)).toArray()), + (long) (val * 10000)); + } + + val = constrains.getParam2Min(); + + if (val != null) { + model.addGreaterOrEqual( + LinearExpr.weightedSum( + percentValArr, + coals.stream().mapToLong(x -> (long) (x.getParam2() * 100)).toArray()), + (long) (val * 10000)); + } + + val = constrains.getParam3Min(); + + if (val != null) { + model.addGreaterOrEqual( + LinearExpr.weightedSum( + percentValArr, + coals.stream().mapToLong(x -> (long) (x.getParam3() * 100)).toArray()), + (long) (val * 10000)); + } + + val = constrains.getParam4Min(); + + if (val != null) { + model.addGreaterOrEqual( + LinearExpr.weightedSum( + percentValArr, + coals.stream().mapToLong(x -> (long) (x.getParam4() * 100)).toArray()), + (long) (val * 10000)); + } + + val = constrains.getParam5Min(); + + if (val != null) { + model.addGreaterOrEqual( + LinearExpr.weightedSum( + percentValArr, + coals.stream().mapToLong(x -> (long) (x.getParam5() * 100)).toArray()), + (long) (val * 10000)); + } + + val = constrains.getParam6Min(); + + if (val != null) { + model.addGreaterOrEqual( + LinearExpr.weightedSum( + percentValArr, + coals.stream().mapToLong(x -> (long) (x.getParam6() * 100)).toArray()), + (long) (val * 10000)); + } + val = constrains.getParam7Min(); + + if (val != null) { + model.addGreaterOrEqual( + LinearExpr.weightedSum( + percentValArr, + coals.stream().mapToLong(x -> (long) (x.getParam7() * 100)).toArray()), + (long) (val * 10000)); + } + val = constrains.getParam8Min(); + + if (val != null) { + model.addGreaterOrEqual( + LinearExpr.weightedSum( + percentValArr, + coals.stream().mapToLong(x -> (long) (x.getParam8() * 100)).toArray()), + (long) (val * 10000)); + } + val = constrains.getParam9Min(); + + if (val != null) { + model.addGreaterOrEqual( + LinearExpr.weightedSum( + percentValArr, + coals.stream().mapToLong(x -> (long) (x.getParam9() * 100)).toArray()), + (long) (val * 10000)); + } + val = constrains.getParam10Min(); + + if (val != null) { + model.addGreaterOrEqual( + LinearExpr.weightedSum( + percentValArr, + coals.stream().mapToLong(x -> (long) (x.getParam10() * 100)).toArray()), + (long) (val * 10000)); + } + val = constrains.getParam11Min(); + + if (val != null) { + model.addGreaterOrEqual( + LinearExpr.weightedSum( + percentValArr, + coals.stream().mapToLong(x -> (long) (x.getParam11() * 100)).toArray()), + (long) (val * 10000)); + } + val = constrains.getParam12Min(); + + if (val != null) { + model.addGreaterOrEqual( + LinearExpr.weightedSum( + percentValArr, + coals.stream().mapToLong(x -> (long) (x.getParam12() * 100)).toArray()), + (long) (val * 10000)); + } + val = constrains.getParam13Min(); + + if (val != null) { + model.addGreaterOrEqual( + LinearExpr.weightedSum( + percentValArr, + coals.stream().mapToLong(x -> (long) (x.getParam13() * 100)).toArray()), + (long) (val * 10000)); + } + val = constrains.getParam14Min(); + + if (val != null) { + model.addGreaterOrEqual( + LinearExpr.weightedSum( + percentValArr, + coals.stream().mapToLong(x -> (long) (x.getParam14() * 100)).toArray()), + (long) (val * 10000)); + } + val = constrains.getParam15Min(); + + if (val != null) { + model.addGreaterOrEqual( + LinearExpr.weightedSum( + percentValArr, + coals.stream().mapToLong(x -> (long) (x.getParam15() * 100)).toArray()), + (long) (val * 10000)); + } + val = constrains.getParam16Min(); + + if (val != null) { + model.addGreaterOrEqual( + LinearExpr.weightedSum( + percentValArr, + coals.stream().mapToLong(x -> (long) (x.getParam16() * 100)).toArray()), + (long) (val * 10000)); + } + val = constrains.getParam17Min(); + + if (val != null) { + model.addGreaterOrEqual( + LinearExpr.weightedSum( + percentValArr, + coals.stream().mapToLong(x -> (long) (x.getParam17() * 100)).toArray()), + (long) (val * 10000)); + } + val = constrains.getParam18Min(); + + if (val != null) { + model.addGreaterOrEqual( + LinearExpr.weightedSum( + percentValArr, + coals.stream().mapToLong(x -> (long) (x.getParam18() * 100)).toArray()), + (long) (val * 10000)); + } + val = constrains.getParam19Min(); + + if (val != null) { + model.addGreaterOrEqual( + LinearExpr.weightedSum( + percentValArr, + coals.stream().mapToLong(x -> (long) (x.getParam19() * 100)).toArray()), + (long) (val * 10000)); + } + val = constrains.getParam20Min(); + + if (val != null) { + model.addGreaterOrEqual( + LinearExpr.weightedSum( + percentValArr, + coals.stream().mapToLong(x -> (long) (x.getParam20() * 100)).toArray()), + (long) (val * 10000)); + } + + val = constrains.getParam1Max(); + + if (val != null) { + model.addLessOrEqual( + LinearExpr.weightedSum( + percentValArr, + coals.stream().mapToLong(x -> (long) (x.getParam1() * 100)).toArray()), + (long) (val * 10000)); + } + + val = constrains.getParam2Max(); + + if (val != null) { + model.addLessOrEqual( + LinearExpr.weightedSum( + percentValArr, + coals.stream().mapToLong(x -> (long) (x.getParam2() * 100)).toArray()), + (long) (val * 10000)); + } + + val = constrains.getParam3Max(); + + if (val != null) { + model.addLessOrEqual( + LinearExpr.weightedSum( + percentValArr, + coals.stream().mapToLong(x -> (long) (x.getParam3() * 100)).toArray()), + (long) (val * 10000)); + } + + val = constrains.getParam4Max(); + + if (val != null) { + model.addLessOrEqual( + LinearExpr.weightedSum( + percentValArr, + coals.stream().mapToLong(x -> (long) (x.getParam4() * 100)).toArray()), + (long) (val * 10000)); + } + + val = constrains.getParam5Max(); + + if (val != null) { + model.addLessOrEqual( + LinearExpr.weightedSum( + percentValArr, + coals.stream().mapToLong(x -> (long) (x.getParam5() * 100)).toArray()), + (long) (val * 10000)); + } + + val = constrains.getParam6Max(); + + if (val != null) { + model.addLessOrEqual( + LinearExpr.weightedSum( + percentValArr, + coals.stream().mapToLong(x -> (long) (x.getParam6() * 100)).toArray()), + (long) (val * 10000)); + } + val = constrains.getParam7Max(); + + if (val != null) { + model.addLessOrEqual( + LinearExpr.weightedSum( + percentValArr, + coals.stream().mapToLong(x -> (long) (x.getParam7() * 100)).toArray()), + (long) (val * 10000)); + } + val = constrains.getParam8Max(); + + if (val != null) { + model.addLessOrEqual( + LinearExpr.weightedSum( + percentValArr, + coals.stream().mapToLong(x -> (long) (x.getParam8() * 100)).toArray()), + (long) (val * 10000)); + } + val = constrains.getParam9Max(); + + if (val != null) { + model.addLessOrEqual( + LinearExpr.weightedSum( + percentValArr, + coals.stream().mapToLong(x -> (long) (x.getParam9() * 100)).toArray()), + (long) (val * 10000)); + } + val = constrains.getParam10Max(); + + if (val != null) { + model.addLessOrEqual( + LinearExpr.weightedSum( + percentValArr, + coals.stream().mapToLong(x -> (long) (x.getParam10() * 100)).toArray()), + (long) (val * 10000)); + } + val = constrains.getParam11Max(); + + if (val != null) { + model.addLessOrEqual( + LinearExpr.weightedSum( + percentValArr, + coals.stream().mapToLong(x -> (long) (x.getParam11() * 100)).toArray()), + (long) (val * 10000)); + } + val = constrains.getParam12Max(); + + if (val != null) { + model.addLessOrEqual( + LinearExpr.weightedSum( + percentValArr, + coals.stream().mapToLong(x -> (long) (x.getParam12() * 100)).toArray()), + (long) (val * 10000)); + } + val = constrains.getParam13Max(); + + if (val != null) { + model.addLessOrEqual( + LinearExpr.weightedSum( + percentValArr, + coals.stream().mapToLong(x -> (long) (x.getParam13() * 100)).toArray()), + (long) (val * 10000)); + } + val = constrains.getParam14Max(); + + if (val != null) { + model.addLessOrEqual( + LinearExpr.weightedSum( + percentValArr, + coals.stream().mapToLong(x -> (long) (x.getParam14() * 100)).toArray()), + (long) (val * 10000)); + } + val = constrains.getParam15Max(); + + if (val != null) { + model.addLessOrEqual( + LinearExpr.weightedSum( + percentValArr, + coals.stream().mapToLong(x -> (long) (x.getParam15() * 100)).toArray()), + (long) (val * 10000)); + } + val = constrains.getParam16Max(); + + if (val != null) { + model.addLessOrEqual( + LinearExpr.weightedSum( + percentValArr, + coals.stream().mapToLong(x -> (long) (x.getParam16() * 100)).toArray()), + (long) (val * 10000)); + } + val = constrains.getParam17Max(); + + if (val != null) { + model.addLessOrEqual( + LinearExpr.weightedSum( + percentValArr, + coals.stream().mapToLong(x -> (long) (x.getParam17() * 100)).toArray()), + (long) (val * 10000)); + } + val = constrains.getParam18Max(); + + if (val != null) { + model.addLessOrEqual( + LinearExpr.weightedSum( + percentValArr, + coals.stream().mapToLong(x -> (long) (x.getParam18() * 100)).toArray()), + (long) (val * 10000)); + } + val = constrains.getParam19Max(); + + if (val != null) { + model.addLessOrEqual( + LinearExpr.weightedSum( + percentValArr, + coals.stream().mapToLong(x -> (long) (x.getParam19() * 100)).toArray()), + (long) (val * 10000)); + } + val = constrains.getParam20Max(); + + if (val != null) { + model.addLessOrEqual( + LinearExpr.weightedSum( + percentValArr, + coals.stream().mapToLong(x -> (long) (x.getParam20() * 100)).toArray()), + (long) (val * 10000)); + } } - val = constrains.getParam3Min(); - - if (val != null) { - model.addGreaterOrEqual( - LinearExpr.weightedSum( - percentValArr, coals.stream().mapToLong(x -> (long) (x.getParam3() * 100)).toArray()), - (long) (val * 10000)); - } - - val = constrains.getParam4Min(); - - if (val != null) { - model.addGreaterOrEqual( - LinearExpr.weightedSum( - percentValArr, coals.stream().mapToLong(x -> (long) (x.getParam4() * 100)).toArray()), - (long) (val * 10000)); - } - - val = constrains.getParam5Min(); - - if (val != null) { - model.addGreaterOrEqual( - LinearExpr.weightedSum( - percentValArr, coals.stream().mapToLong(x -> (long) (x.getParam5() * 100)).toArray()), - (long) (val * 10000)); - } - - val = constrains.getParam6Min(); - - if (val != null) { - model.addGreaterOrEqual( - LinearExpr.weightedSum( - percentValArr, coals.stream().mapToLong(x -> (long) (x.getParam6() * 100)).toArray()), - (long) (val * 10000)); - } - val = constrains.getParam7Min(); - - if (val != null) { - model.addGreaterOrEqual( - LinearExpr.weightedSum( - percentValArr, coals.stream().mapToLong(x -> (long) (x.getParam7() * 100)).toArray()), - (long) (val * 10000)); - } - val = constrains.getParam8Min(); - - if (val != null) { - model.addGreaterOrEqual( - LinearExpr.weightedSum( - percentValArr, coals.stream().mapToLong(x -> (long) (x.getParam8() * 100)).toArray()), - (long) (val * 10000)); - } - val = constrains.getParam9Min(); - - if (val != null) { - model.addGreaterOrEqual( - LinearExpr.weightedSum( - percentValArr, coals.stream().mapToLong(x -> (long) (x.getParam9() * 100)).toArray()), - (long) (val * 10000)); - } - val = constrains.getParam10Min(); - - if (val != null) { - model.addGreaterOrEqual( - LinearExpr.weightedSum( - percentValArr, - coals.stream().mapToLong(x -> (long) (x.getParam10() * 100)).toArray()), - (long) (val * 10000)); - } - val = constrains.getParam11Min(); - - if (val != null) { - model.addGreaterOrEqual( - LinearExpr.weightedSum( - percentValArr, - coals.stream().mapToLong(x -> (long) (x.getParam11() * 100)).toArray()), - (long) (val * 10000)); - } - val = constrains.getParam12Min(); - - if (val != null) { - model.addGreaterOrEqual( - LinearExpr.weightedSum( - percentValArr, - coals.stream().mapToLong(x -> (long) (x.getParam12() * 100)).toArray()), - (long) (val * 10000)); - } - val = constrains.getParam13Min(); - - if (val != null) { - model.addGreaterOrEqual( - LinearExpr.weightedSum( - percentValArr, - coals.stream().mapToLong(x -> (long) (x.getParam13() * 100)).toArray()), - (long) (val * 10000)); - } - val = constrains.getParam14Min(); - - if (val != null) { - model.addGreaterOrEqual( - LinearExpr.weightedSum( - percentValArr, - coals.stream().mapToLong(x -> (long) (x.getParam14() * 100)).toArray()), - (long) (val * 10000)); - } - val = constrains.getParam15Min(); - - if (val != null) { - model.addGreaterOrEqual( - LinearExpr.weightedSum( - percentValArr, - coals.stream().mapToLong(x -> (long) (x.getParam15() * 100)).toArray()), - (long) (val * 10000)); - } - val = constrains.getParam16Min(); - - if (val != null) { - model.addGreaterOrEqual( - LinearExpr.weightedSum( - percentValArr, - coals.stream().mapToLong(x -> (long) (x.getParam16() * 100)).toArray()), - (long) (val * 10000)); - } - val = constrains.getParam17Min(); - - if (val != null) { - model.addGreaterOrEqual( - LinearExpr.weightedSum( - percentValArr, - coals.stream().mapToLong(x -> (long) (x.getParam17() * 100)).toArray()), - (long) (val * 10000)); - } - val = constrains.getParam18Min(); - - if (val != null) { - model.addGreaterOrEqual( - LinearExpr.weightedSum( - percentValArr, - coals.stream().mapToLong(x -> (long) (x.getParam18() * 100)).toArray()), - (long) (val * 10000)); - } - val = constrains.getParam19Min(); - - if (val != null) { - model.addGreaterOrEqual( - LinearExpr.weightedSum( - percentValArr, - coals.stream().mapToLong(x -> (long) (x.getParam19() * 100)).toArray()), - (long) (val * 10000)); - } - val = constrains.getParam20Min(); - - if (val != null) { - model.addGreaterOrEqual( - LinearExpr.weightedSum( - percentValArr, - coals.stream().mapToLong(x -> (long) (x.getParam20() * 100)).toArray()), - (long) (val * 10000)); - } - - val = constrains.getParam1Max(); - - if (val != null) { - model.addLessOrEqual( - LinearExpr.weightedSum( - percentValArr, coals.stream().mapToLong(x -> (long) (x.getParam1() * 100)).toArray()), - (long) (val * 10000)); - } - - val = constrains.getParam2Max(); - - if (val != null) { - model.addLessOrEqual( - LinearExpr.weightedSum( - percentValArr, coals.stream().mapToLong(x -> (long) (x.getParam2() * 100)).toArray()), - (long) (val * 10000)); - } - - val = constrains.getParam3Max(); - - if (val != null) { - model.addLessOrEqual( - LinearExpr.weightedSum( - percentValArr, coals.stream().mapToLong(x -> (long) (x.getParam3() * 100)).toArray()), - (long) (val * 10000)); - } - - val = constrains.getParam4Max(); - - if (val != null) { - model.addLessOrEqual( - LinearExpr.weightedSum( - percentValArr, coals.stream().mapToLong(x -> (long) (x.getParam4() * 100)).toArray()), - (long) (val * 10000)); - } - - val = constrains.getParam5Max(); - - if (val != null) { - model.addLessOrEqual( - LinearExpr.weightedSum( - percentValArr, coals.stream().mapToLong(x -> (long) (x.getParam5() * 100)).toArray()), - (long) (val * 10000)); - } - - val = constrains.getParam6Max(); - - if (val != null) { - model.addLessOrEqual( - LinearExpr.weightedSum( - percentValArr, coals.stream().mapToLong(x -> (long) (x.getParam6() * 100)).toArray()), - (long) (val * 10000)); - } - val = constrains.getParam7Max(); - - if (val != null) { - model.addLessOrEqual( - LinearExpr.weightedSum( - percentValArr, coals.stream().mapToLong(x -> (long) (x.getParam7() * 100)).toArray()), - (long) (val * 10000)); - } - val = constrains.getParam8Max(); - - if (val != null) { - model.addLessOrEqual( - LinearExpr.weightedSum( - percentValArr, coals.stream().mapToLong(x -> (long) (x.getParam8() * 100)).toArray()), - (long) (val * 10000)); - } - val = constrains.getParam9Max(); - - if (val != null) { - model.addLessOrEqual( - LinearExpr.weightedSum( - percentValArr, coals.stream().mapToLong(x -> (long) (x.getParam9() * 100)).toArray()), - (long) (val * 10000)); - } - val = constrains.getParam10Max(); - - if (val != null) { - model.addLessOrEqual( - LinearExpr.weightedSum( - percentValArr, - coals.stream().mapToLong(x -> (long) (x.getParam10() * 100)).toArray()), - (long) (val * 10000)); - } - val = constrains.getParam11Max(); - - if (val != null) { - model.addLessOrEqual( - LinearExpr.weightedSum( - percentValArr, - coals.stream().mapToLong(x -> (long) (x.getParam11() * 100)).toArray()), - (long) (val * 10000)); - } - val = constrains.getParam12Max(); - - if (val != null) { - model.addLessOrEqual( - LinearExpr.weightedSum( - percentValArr, - coals.stream().mapToLong(x -> (long) (x.getParam12() * 100)).toArray()), - (long) (val * 10000)); - } - val = constrains.getParam13Max(); - - if (val != null) { - model.addLessOrEqual( - LinearExpr.weightedSum( - percentValArr, - coals.stream().mapToLong(x -> (long) (x.getParam13() * 100)).toArray()), - (long) (val * 10000)); - } - val = constrains.getParam14Max(); - - if (val != null) { - model.addLessOrEqual( - LinearExpr.weightedSum( - percentValArr, - coals.stream().mapToLong(x -> (long) (x.getParam14() * 100)).toArray()), - (long) (val * 10000)); - } - val = constrains.getParam15Max(); - - if (val != null) { - model.addLessOrEqual( - LinearExpr.weightedSum( - percentValArr, - coals.stream().mapToLong(x -> (long) (x.getParam15() * 100)).toArray()), - (long) (val * 10000)); - } - val = constrains.getParam16Max(); - - if (val != null) { - model.addLessOrEqual( - LinearExpr.weightedSum( - percentValArr, - coals.stream().mapToLong(x -> (long) (x.getParam16() * 100)).toArray()), - (long) (val * 10000)); - } - val = constrains.getParam17Max(); - - if (val != null) { - model.addLessOrEqual( - LinearExpr.weightedSum( - percentValArr, - coals.stream().mapToLong(x -> (long) (x.getParam17() * 100)).toArray()), - (long) (val * 10000)); - } - val = constrains.getParam18Max(); - - if (val != null) { - model.addLessOrEqual( - LinearExpr.weightedSum( - percentValArr, - coals.stream().mapToLong(x -> (long) (x.getParam18() * 100)).toArray()), - (long) (val * 10000)); - } - val = constrains.getParam19Max(); - - if (val != null) { - model.addLessOrEqual( - LinearExpr.weightedSum( - percentValArr, - coals.stream().mapToLong(x -> (long) (x.getParam19() * 100)).toArray()), - (long) (val * 10000)); - } - val = constrains.getParam20Max(); - - if (val != null) { - model.addLessOrEqual( - LinearExpr.weightedSum( - percentValArr, - coals.stream().mapToLong(x -> (long) (x.getParam20() * 100)).toArray()), - (long) (val * 10000)); - } - } + public static class BlendGroup {} } diff --git a/src/main/java/cn/lihongjie/coal/coalBlend/entity/CoalBlendResultInfoEntity.java b/src/main/java/cn/lihongjie/coal/coalBlend/entity/CoalBlendResultInfoEntity.java index 7f475163..c365cef3 100644 --- a/src/main/java/cn/lihongjie/coal/coalBlend/entity/CoalBlendResultInfoEntity.java +++ b/src/main/java/cn/lihongjie/coal/coalBlend/entity/CoalBlendResultInfoEntity.java @@ -1,16 +1,20 @@ package cn.lihongjie.coal.coalBlend.entity; import cn.lihongjie.coal.base.entity.OrgCommonEntity; + import jakarta.persistence.ElementCollection; import jakarta.persistence.Entity; import jakarta.persistence.ManyToOne; import jakarta.validation.constraints.DecimalMin; + +import lombok.*; + +import org.apache.commons.lang3.reflect.FieldUtils; +import org.hibernate.annotations.Comment; + import java.util.Arrays; import java.util.Comparator; import java.util.List; -import lombok.*; -import org.apache.commons.lang3.reflect.FieldUtils; -import org.hibernate.annotations.Comment; @Data @AllArgsConstructor @@ -19,182 +23,182 @@ import org.hibernate.annotations.Comment; @Entity public class CoalBlendResultInfoEntity extends OrgCommonEntity { - private String name; + private String name; - @ElementCollection private List percentInfos; + @ElementCollection private List percentInfos; - @ManyToOne private CoalBlendEntity coal; + @ManyToOne private CoalBlendEntity coal; - @Comment("参数 1 ") - @DecimalMin( - groups = CoalBlendEntity.BlendGroup.class, - value = "0.1", - inclusive = true, - message = "参数不能小于0.1") - private Double param1; + @Comment("参数 1 ") + @DecimalMin( + groups = CoalBlendEntity.BlendGroup.class, + value = "0.1", + inclusive = true, + message = "参数不能小于0.1") + private Double param1; - @Comment("参数 2 ") - @DecimalMin( - groups = CoalBlendEntity.BlendGroup.class, - value = "0.1", - inclusive = true, - message = "参数不能小于0.1") - private Double param2; + @Comment("参数 2 ") + @DecimalMin( + groups = CoalBlendEntity.BlendGroup.class, + value = "0.1", + inclusive = true, + message = "参数不能小于0.1") + private Double param2; - @Comment("参数 3 ") - @DecimalMin( - groups = CoalBlendEntity.BlendGroup.class, - value = "0.1", - inclusive = true, - message = "参数不能小于0.1") - private Double param3; + @Comment("参数 3 ") + @DecimalMin( + groups = CoalBlendEntity.BlendGroup.class, + value = "0.1", + inclusive = true, + message = "参数不能小于0.1") + private Double param3; - @Comment("参数 4 ") - @DecimalMin( - groups = CoalBlendEntity.BlendGroup.class, - value = "0.1", - inclusive = true, - message = "参数不能小于0.1") - private Double param4; + @Comment("参数 4 ") + @DecimalMin( + groups = CoalBlendEntity.BlendGroup.class, + value = "0.1", + inclusive = true, + message = "参数不能小于0.1") + private Double param4; - @Comment("参数 5 ") - @DecimalMin( - groups = CoalBlendEntity.BlendGroup.class, - value = "0.1", - inclusive = true, - message = "参数不能小于0.1") - private Double param5; + @Comment("参数 5 ") + @DecimalMin( + groups = CoalBlendEntity.BlendGroup.class, + value = "0.1", + inclusive = true, + message = "参数不能小于0.1") + private Double param5; - @Comment("参数 6 ") - @DecimalMin( - groups = CoalBlendEntity.BlendGroup.class, - value = "0.1", - inclusive = true, - message = "参数不能小于0.1") - private Double param6; + @Comment("参数 6 ") + @DecimalMin( + groups = CoalBlendEntity.BlendGroup.class, + value = "0.1", + inclusive = true, + message = "参数不能小于0.1") + private Double param6; - @Comment("参数 7 ") - @DecimalMin( - groups = CoalBlendEntity.BlendGroup.class, - value = "0.1", - inclusive = true, - message = "参数不能小于0.1") - private Double param7; + @Comment("参数 7 ") + @DecimalMin( + groups = CoalBlendEntity.BlendGroup.class, + value = "0.1", + inclusive = true, + message = "参数不能小于0.1") + private Double param7; - @Comment("参数 8 ") - @DecimalMin( - groups = CoalBlendEntity.BlendGroup.class, - value = "0.1", - inclusive = true, - message = "参数不能小于0.1") - private Double param8; + @Comment("参数 8 ") + @DecimalMin( + groups = CoalBlendEntity.BlendGroup.class, + value = "0.1", + inclusive = true, + message = "参数不能小于0.1") + private Double param8; - @Comment("参数 9 ") - @DecimalMin( - groups = CoalBlendEntity.BlendGroup.class, - value = "0.1", - inclusive = true, - message = "参数不能小于0.1") - private Double param9; + @Comment("参数 9 ") + @DecimalMin( + groups = CoalBlendEntity.BlendGroup.class, + value = "0.1", + inclusive = true, + message = "参数不能小于0.1") + private Double param9; - @Comment("参数 10 ") - @DecimalMin( - groups = CoalBlendEntity.BlendGroup.class, - value = "0.1", - inclusive = true, - message = "参数不能小于0.1") - private Double param10; + @Comment("参数 10 ") + @DecimalMin( + groups = CoalBlendEntity.BlendGroup.class, + value = "0.1", + inclusive = true, + message = "参数不能小于0.1") + private Double param10; - @Comment("参数 11 ") - @DecimalMin( - groups = CoalBlendEntity.BlendGroup.class, - value = "0.1", - inclusive = true, - message = "参数不能小于0.1") - private Double param11; + @Comment("参数 11 ") + @DecimalMin( + groups = CoalBlendEntity.BlendGroup.class, + value = "0.1", + inclusive = true, + message = "参数不能小于0.1") + private Double param11; - @Comment("参数 12 ") - @DecimalMin( - groups = CoalBlendEntity.BlendGroup.class, - value = "0.1", - inclusive = true, - message = "参数不能小于0.1") - private Double param12; + @Comment("参数 12 ") + @DecimalMin( + groups = CoalBlendEntity.BlendGroup.class, + value = "0.1", + inclusive = true, + message = "参数不能小于0.1") + private Double param12; - @Comment("参数 13 ") - @DecimalMin( - groups = CoalBlendEntity.BlendGroup.class, - value = "0.1", - inclusive = true, - message = "参数不能小于0.1") - private Double param13; + @Comment("参数 13 ") + @DecimalMin( + groups = CoalBlendEntity.BlendGroup.class, + value = "0.1", + inclusive = true, + message = "参数不能小于0.1") + private Double param13; - @Comment("参数 14 ") - @DecimalMin( - groups = CoalBlendEntity.BlendGroup.class, - value = "0.1", - inclusive = true, - message = "参数不能小于0.1") - private Double param14; + @Comment("参数 14 ") + @DecimalMin( + groups = CoalBlendEntity.BlendGroup.class, + value = "0.1", + inclusive = true, + message = "参数不能小于0.1") + private Double param14; - @Comment("参数 15 ") - @DecimalMin( - groups = CoalBlendEntity.BlendGroup.class, - value = "0.1", - inclusive = true, - message = "参数不能小于0.1") - private Double param15; + @Comment("参数 15 ") + @DecimalMin( + groups = CoalBlendEntity.BlendGroup.class, + value = "0.1", + inclusive = true, + message = "参数不能小于0.1") + private Double param15; - @Comment("参数 16 ") - @DecimalMin( - groups = CoalBlendEntity.BlendGroup.class, - value = "0.1", - inclusive = true, - message = "参数不能小于0.1") - private Double param16; + @Comment("参数 16 ") + @DecimalMin( + groups = CoalBlendEntity.BlendGroup.class, + value = "0.1", + inclusive = true, + message = "参数不能小于0.1") + private Double param16; - @Comment("参数 17 ") - @DecimalMin( - groups = CoalBlendEntity.BlendGroup.class, - value = "0.1", - inclusive = true, - message = "参数不能小于0.1") - private Double param17; + @Comment("参数 17 ") + @DecimalMin( + groups = CoalBlendEntity.BlendGroup.class, + value = "0.1", + inclusive = true, + message = "参数不能小于0.1") + private Double param17; - @Comment("参数 18 ") - @DecimalMin( - groups = CoalBlendEntity.BlendGroup.class, - value = "0.1", - inclusive = true, - message = "参数不能小于0.1") - private Double param18; + @Comment("参数 18 ") + @DecimalMin( + groups = CoalBlendEntity.BlendGroup.class, + value = "0.1", + inclusive = true, + message = "参数不能小于0.1") + private Double param18; - @Comment("参数 19 ") - @DecimalMin( - groups = CoalBlendEntity.BlendGroup.class, - value = "0.1", - inclusive = true, - message = "参数不能小于0.1") - private Double param19; + @Comment("参数 19 ") + @DecimalMin( + groups = CoalBlendEntity.BlendGroup.class, + value = "0.1", + inclusive = true, + message = "参数不能小于0.1") + private Double param19; - @Comment("参数 20 ") - @DecimalMin( - groups = CoalBlendEntity.BlendGroup.class, - value = "0.1", - inclusive = true, - message = "参数不能小于0.1") - private Double param20; + @Comment("参数 20 ") + @DecimalMin( + groups = CoalBlendEntity.BlendGroup.class, + value = "0.1", + inclusive = true, + message = "参数不能小于0.1") + private Double param20; - @SneakyThrows - public Double getParam(String param) { - return (Double) FieldUtils.getField(this.getClass(), param, true).get(this); - } + @SneakyThrows + public Double getParam(String param) { + return (Double) FieldUtils.getField(this.getClass(), param, true).get(this); + } - public long getHashKey() { + public long getHashKey() { - return Arrays.hashCode( - this.getPercentInfos().stream() - .sorted(Comparator.comparing(x -> x.getPercent())) - .toArray(CoalPercentVo[]::new)); - } + return Arrays.hashCode( + this.getPercentInfos().stream() + .sorted(Comparator.comparing(x -> x.getPercent())) + .toArray(CoalPercentVo[]::new)); + } } diff --git a/src/main/java/cn/lihongjie/coal/coalBlend/entity/CoalBlendType.java b/src/main/java/cn/lihongjie/coal/coalBlend/entity/CoalBlendType.java index 2289a771..41afd06c 100644 --- a/src/main/java/cn/lihongjie/coal/coalBlend/entity/CoalBlendType.java +++ b/src/main/java/cn/lihongjie/coal/coalBlend/entity/CoalBlendType.java @@ -1,6 +1,6 @@ package cn.lihongjie.coal.coalBlend.entity; public enum CoalBlendType { - TYPE1, - TYPE2 + TYPE1, + TYPE2 } diff --git a/src/main/java/cn/lihongjie/coal/coalBlend/entity/CoalParameterDefVo.java b/src/main/java/cn/lihongjie/coal/coalBlend/entity/CoalParameterDefVo.java index 0fb195c8..8c6975ab 100644 --- a/src/main/java/cn/lihongjie/coal/coalBlend/entity/CoalParameterDefVo.java +++ b/src/main/java/cn/lihongjie/coal/coalBlend/entity/CoalParameterDefVo.java @@ -1,29 +1,31 @@ package cn.lihongjie.coal.coalBlend.entity; import jakarta.persistence.Embeddable; + import lombok.Data; + import org.hibernate.annotations.Comment; @Embeddable @Data public class CoalParameterDefVo { - @Comment("名称") - private String name; + @Comment("名称") + private String name; - @Comment("编码") - private String code; + @Comment("编码") + private String code; - @Comment("备注") - private String remarks; + @Comment("备注") + private String remarks; - @Comment("备注") - private String parentName; + @Comment("备注") + private String parentName; - @Comment("排序键") - private Integer sortKey; + @Comment("排序键") + private Integer sortKey; - @Comment("常用状态 0 禁用 1 启用") - private Integer status; + @Comment("常用状态 0 禁用 1 启用") + private Integer status; - private String id; + private String id; } diff --git a/src/main/java/cn/lihongjie/coal/coalBlend/entity/CoalPercentVo.java b/src/main/java/cn/lihongjie/coal/coalBlend/entity/CoalPercentVo.java index 1b6a3557..643da31c 100644 --- a/src/main/java/cn/lihongjie/coal/coalBlend/entity/CoalPercentVo.java +++ b/src/main/java/cn/lihongjie/coal/coalBlend/entity/CoalPercentVo.java @@ -1,9 +1,11 @@ package cn.lihongjie.coal.coalBlend.entity; import jakarta.persistence.Embeddable; + import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; + import org.hibernate.annotations.Comment; @Data @@ -12,12 +14,12 @@ import org.hibernate.annotations.Comment; @NoArgsConstructor public class CoalPercentVo { - @Comment("煤名称") - private String name; + @Comment("煤名称") + private String name; - @Comment("煤的精确比例") - private Double percent; + @Comment("煤的精确比例") + private Double percent; - @Comment("煤的铲车配煤比例") - private Double type2Percent; + @Comment("煤的铲车配煤比例") + private Double type2Percent; } diff --git a/src/main/java/cn/lihongjie/coal/coalBlend/mapper/CoalBlendMapper.java b/src/main/java/cn/lihongjie/coal/coalBlend/mapper/CoalBlendMapper.java index e83bfb17..a8042767 100644 --- a/src/main/java/cn/lihongjie/coal/coalBlend/mapper/CoalBlendMapper.java +++ b/src/main/java/cn/lihongjie/coal/coalBlend/mapper/CoalBlendMapper.java @@ -6,6 +6,7 @@ import cn.lihongjie.coal.coalBlend.dto.CoalBlendDto; import cn.lihongjie.coal.coalBlend.dto.CreateCoalBlendDto; import cn.lihongjie.coal.coalBlend.dto.UpdateCoalBlendDto; import cn.lihongjie.coal.coalBlend.entity.CoalBlendEntity; + import org.apache.commons.collections4.CollectionUtils; import org.mapstruct.AfterMapping; import org.mapstruct.Mapper; @@ -14,24 +15,24 @@ import org.mapstruct.MappingTarget; import org.mapstruct.control.DeepClone; @Mapper( - componentModel = MappingConstants.ComponentModel.SPRING, - uses = {CommonMapper.class}, - mappingControl = DeepClone.class) + componentModel = MappingConstants.ComponentModel.SPRING, + uses = {CommonMapper.class}, + mappingControl = DeepClone.class) public interface CoalBlendMapper - extends BaseMapper { + extends BaseMapper { - @AfterMapping - public default void convertNameToUpperCase( - CreateCoalBlendDto dto, @MappingTarget CoalBlendEntity entity) { - if (CollectionUtils.isNotEmpty(entity.getCoals())) { + @AfterMapping + default void convertNameToUpperCase( + CreateCoalBlendDto dto, @MappingTarget CoalBlendEntity entity) { + if (CollectionUtils.isNotEmpty(entity.getCoals())) { - entity.getCoals().forEach(x -> x.setId(null)); + entity.getCoals().forEach(x -> x.setId(null)); - entity.getCoals().forEach(x -> x.setCoal(entity)); + entity.getCoals().forEach(x -> x.setCoal(entity)); + } + if (CollectionUtils.isNotEmpty(entity.getResults())) { + + entity.getResults().forEach(x -> x.setCoal(entity)); + } } - if (CollectionUtils.isNotEmpty(entity.getResults())) { - - entity.getResults().forEach(x -> x.setCoal(entity)); - } - } } diff --git a/src/main/java/cn/lihongjie/coal/coalBlend/repository/CoalBlendRepository.java b/src/main/java/cn/lihongjie/coal/coalBlend/repository/CoalBlendRepository.java index 310f8a6b..d98d0216 100644 --- a/src/main/java/cn/lihongjie/coal/coalBlend/repository/CoalBlendRepository.java +++ b/src/main/java/cn/lihongjie/coal/coalBlend/repository/CoalBlendRepository.java @@ -2,6 +2,7 @@ package cn.lihongjie.coal.coalBlend.repository; import cn.lihongjie.coal.base.dao.BaseRepository; import cn.lihongjie.coal.coalBlend.entity.CoalBlendEntity; + import org.springframework.stereotype.Repository; @Repository diff --git a/src/main/java/cn/lihongjie/coal/coalBlend/service/CoalBlendService.java b/src/main/java/cn/lihongjie/coal/coalBlend/service/CoalBlendService.java index 9b2ef5ce..85facfaf 100644 --- a/src/main/java/cn/lihongjie/coal/coalBlend/service/CoalBlendService.java +++ b/src/main/java/cn/lihongjie/coal/coalBlend/service/CoalBlendService.java @@ -10,8 +10,11 @@ import cn.lihongjie.coal.coalBlend.entity.CoalBlendEntity; import cn.lihongjie.coal.coalBlend.mapper.CoalBlendMapper; import cn.lihongjie.coal.coalBlend.repository.CoalBlendRepository; import cn.lihongjie.coal.coalWashingDailyAnalysis.mapper.RoundMapper; + import jakarta.annotation.PostConstruct; + import lombok.extern.slf4j.Slf4j; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.convert.ConversionService; import org.springframework.data.domain.Page; @@ -24,73 +27,74 @@ import org.springframework.util.StopWatch; @Slf4j public class CoalBlendService extends BaseService { - @Autowired CoalBlendRepository repository; + @Autowired CoalBlendRepository repository; - @Autowired CoalBlendMapper mapper; + @Autowired CoalBlendMapper mapper; + @Autowired ConversionService conversionService; + @Autowired RoundMapper roundMapper; - @PostConstruct - public void init() {} + @PostConstruct + public void init() {} - public CoalBlendDto create(CreateCoalBlendDto request) { - request.getCoals().forEach(x -> x.setId(null)); + public CoalBlendDto create(CreateCoalBlendDto request) { + request.getCoals().forEach(x -> x.setId(null)); - CoalBlendEntity entity = mapper.toEntity(request); + CoalBlendEntity entity = mapper.toEntity(request); - this.repository.save(entity); - return getById(entity.getId()); - } + this.repository.save(entity); + return getById(entity.getId()); + } - public CoalBlendDto update(UpdateCoalBlendDto request) { - CoalBlendEntity entity = this.repository.get(request.getId()); - this.mapper.updateEntity(entity, request); + public CoalBlendDto update(UpdateCoalBlendDto request) { + CoalBlendEntity entity = this.repository.get(request.getId()); + this.mapper.updateEntity(entity, request); - this.repository.save(entity); + this.repository.save(entity); - return getById(entity.getId()); - } + return getById(entity.getId()); + } - public void delete(IdRequest request) { + public void delete(IdRequest request) { - this.repository.deleteAllById(request.getIds()); - } + this.repository.deleteAllById(request.getIds()); + } - public CoalBlendDto getById(String id) { + public CoalBlendDto getById(String id) { - CoalBlendEntity entity = repository.get(id); + CoalBlendEntity entity = repository.get(id); - return mapper.toDto(entity); - } + return mapper.toDto(entity); + } - @Autowired ConversionService conversionService; + public Page list(CommonQuery query) { - public Page list(CommonQuery query) { + Page page = + repository.findAll( + query.specification(conversionService), + PageRequest.of( + query.getPageNo(), + query.getPageSize(), + Sort.by(query.getOrders()))); - Page page = - repository.findAll( - query.specification(conversionService), - PageRequest.of(query.getPageNo(), query.getPageSize(), Sort.by(query.getOrders()))); + return page.map(this.mapper::toDto); + } - return page.map(this.mapper::toDto); - } + public CoalBlendDto blend(CreateCoalBlendDto dto) { - @Autowired RoundMapper roundMapper; + StopWatch stopWatch = new StopWatch(); - public CoalBlendDto blend(CreateCoalBlendDto dto) { + stopWatch.start("toEntity"); + CoalBlendEntity entity = this.mapper.toEntity(dto); + stopWatch.stop(); + stopWatch.start("blend"); + entity.blend(); + stopWatch.stop(); + stopWatch.start("toDto"); + CoalBlendDto blendDto = this.mapper.toDto(entity); - StopWatch stopWatch = new StopWatch(); + stopWatch.stop(); - stopWatch.start("toEntity"); - CoalBlendEntity entity = this.mapper.toEntity(dto); - stopWatch.stop(); - stopWatch.start("blend"); - entity.blend(); - stopWatch.stop(); - stopWatch.start("toDto"); - CoalBlendDto blendDto = this.mapper.toDto(entity); - - stopWatch.stop(); - - log.info(stopWatch.prettyPrint()); - return roundMapper.round(blendDto); - } + log.info(stopWatch.prettyPrint()); + return roundMapper.round(blendDto); + } } diff --git a/src/main/java/cn/lihongjie/coal/coalInfo/controller/CoalInfoController.java b/src/main/java/cn/lihongjie/coal/coalInfo/controller/CoalInfoController.java index 848c2171..b2ba90e2 100644 --- a/src/main/java/cn/lihongjie/coal/coalInfo/controller/CoalInfoController.java +++ b/src/main/java/cn/lihongjie/coal/coalInfo/controller/CoalInfoController.java @@ -8,7 +8,9 @@ import cn.lihongjie.coal.coalInfo.dto.CoalInfoDto; import cn.lihongjie.coal.coalInfo.dto.CreateCoalInfoDto; import cn.lihongjie.coal.coalInfo.dto.UpdateCoalInfoDto; import cn.lihongjie.coal.coalInfo.service.CoalInfoService; + import lombok.extern.slf4j.Slf4j; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.web.bind.annotation.PostMapping; @@ -22,31 +24,31 @@ import org.springframework.web.bind.annotation.RestController; @Slf4j @OrgScope public class CoalInfoController { - @Autowired private CoalInfoService service; + @Autowired private CoalInfoService service; - @PostMapping("/create") - public CoalInfoDto create(@RequestBody CreateCoalInfoDto request) { - return this.service.create(request); - } + @PostMapping("/create") + public CoalInfoDto create(@RequestBody CreateCoalInfoDto request) { + return this.service.create(request); + } - @PostMapping("/update") - public CoalInfoDto update(@RequestBody UpdateCoalInfoDto request) { - return this.service.update(request); - } + @PostMapping("/update") + public CoalInfoDto update(@RequestBody UpdateCoalInfoDto request) { + return this.service.update(request); + } - @PostMapping("/delete") - public Object delete(@RequestBody IdRequest request) { - this.service.delete(request); - return true; - } + @PostMapping("/delete") + public Object delete(@RequestBody IdRequest request) { + this.service.delete(request); + return true; + } - @PostMapping("/getById") - public CoalInfoDto getById(@RequestBody String request) { - return this.service.getById(request); - } + @PostMapping("/getById") + public CoalInfoDto getById(@RequestBody String request) { + return this.service.getById(request); + } - @PostMapping("/list") - public Page list(@RequestBody CommonQuery request) { - return this.service.list(request); - } + @PostMapping("/list") + public Page list(@RequestBody CommonQuery request) { + return this.service.list(request); + } } diff --git a/src/main/java/cn/lihongjie/coal/coalInfo/dto/CoalInfoDto.java b/src/main/java/cn/lihongjie/coal/coalInfo/dto/CoalInfoDto.java index 071574a6..0714b467 100644 --- a/src/main/java/cn/lihongjie/coal/coalInfo/dto/CoalInfoDto.java +++ b/src/main/java/cn/lihongjie/coal/coalInfo/dto/CoalInfoDto.java @@ -1,20 +1,22 @@ package cn.lihongjie.coal.coalInfo.dto; import cn.lihongjie.coal.base.dto.OrgCommonDto; + import lombok.Data; + import org.hibernate.annotations.Comment; @Data public class CoalInfoDto extends OrgCommonDto { - @Comment("供应商") - private String supplier; + @Comment("供应商") + private String supplier; - private String supplierName; + private String supplierName; - private String coalTypeName; - private String coalType; + private String coalTypeName; + private String coalType; - @Comment("初始报价") - private Double initPrice; + @Comment("初始报价") + private Double initPrice; } diff --git a/src/main/java/cn/lihongjie/coal/coalInfo/dto/CreateCoalInfoDto.java b/src/main/java/cn/lihongjie/coal/coalInfo/dto/CreateCoalInfoDto.java index c31eeafc..75354f67 100644 --- a/src/main/java/cn/lihongjie/coal/coalInfo/dto/CreateCoalInfoDto.java +++ b/src/main/java/cn/lihongjie/coal/coalInfo/dto/CreateCoalInfoDto.java @@ -1,17 +1,19 @@ package cn.lihongjie.coal.coalInfo.dto; import cn.lihongjie.coal.base.dto.OrgCommonDto; + import lombok.Data; + import org.hibernate.annotations.Comment; @Data public class CreateCoalInfoDto extends OrgCommonDto { - @Comment("供应商") - private String supplier; + @Comment("供应商") + private String supplier; - private String coalType; + private String coalType; - @Comment("初始报价") - private Double initPrice; + @Comment("初始报价") + private Double initPrice; } diff --git a/src/main/java/cn/lihongjie/coal/coalInfo/dto/UpdateCoalInfoDto.java b/src/main/java/cn/lihongjie/coal/coalInfo/dto/UpdateCoalInfoDto.java index da870f14..e8573b33 100644 --- a/src/main/java/cn/lihongjie/coal/coalInfo/dto/UpdateCoalInfoDto.java +++ b/src/main/java/cn/lihongjie/coal/coalInfo/dto/UpdateCoalInfoDto.java @@ -1,16 +1,18 @@ package cn.lihongjie.coal.coalInfo.dto; import cn.lihongjie.coal.base.dto.OrgCommonDto; + import lombok.Data; + import org.hibernate.annotations.Comment; @Data public class UpdateCoalInfoDto extends OrgCommonDto { - @Comment("供应商") - private String supplier; + @Comment("供应商") + private String supplier; - private String coalType; + private String coalType; - @Comment("初始报价") - private Double initPrice; + @Comment("初始报价") + private Double initPrice; } diff --git a/src/main/java/cn/lihongjie/coal/coalInfo/entity/CoalInfoEntity.java b/src/main/java/cn/lihongjie/coal/coalInfo/entity/CoalInfoEntity.java index 94e592f8..9565b063 100644 --- a/src/main/java/cn/lihongjie/coal/coalInfo/entity/CoalInfoEntity.java +++ b/src/main/java/cn/lihongjie/coal/coalInfo/entity/CoalInfoEntity.java @@ -2,9 +2,12 @@ package cn.lihongjie.coal.coalInfo.entity; import cn.lihongjie.coal.base.entity.OrgCommonEntity; import cn.lihongjie.coal.supplier.entity.SupplierEntity; + import jakarta.persistence.Entity; import jakarta.persistence.ManyToOne; + import lombok.Data; + import org.hibernate.annotations.Comment; import org.hibernate.annotations.Formula; @@ -12,32 +15,32 @@ import org.hibernate.annotations.Formula; @Entity public class CoalInfoEntity extends OrgCommonEntity { - @ManyToOne - @Comment("供应商") - private SupplierEntity supplier; + @ManyToOne + @Comment("供应商") + private SupplierEntity supplier; - @Comment("煤源类型") - private String coalType; + @Comment("煤源类型") + private String coalType; - @Formula( - "(select i.name\n" - + "from t_dictionary d,\n" - + " t_dictionary_item i\n" - + "where d.id = i.dictionary_id\n" - + " and d.code = 'coal.type'\n" - + " and i.code = coal_type)") - private String coalTypeName; + @Formula( + "(select i.name\n" + + "from t_dictionary d,\n" + + " t_dictionary_item i\n" + + "where d.id = i.dictionary_id\n" + + " and d.code = 'coal.type'\n" + + " and i.code = coal_type)") + private String coalTypeName; - @Comment("初始报价") - private Double initPrice; + @Comment("初始报价") + private Double initPrice; - public String getSupplierName() { + public String getSupplierName() { - if (supplier != null) { + if (supplier != null) { - return supplier.getName(); - } else { - return ""; + return supplier.getName(); + } else { + return ""; + } } - } } diff --git a/src/main/java/cn/lihongjie/coal/coalInfo/mapper/CoalInfoMapper.java b/src/main/java/cn/lihongjie/coal/coalInfo/mapper/CoalInfoMapper.java index 6e72175b..497cab9d 100644 --- a/src/main/java/cn/lihongjie/coal/coalInfo/mapper/CoalInfoMapper.java +++ b/src/main/java/cn/lihongjie/coal/coalInfo/mapper/CoalInfoMapper.java @@ -6,15 +6,16 @@ import cn.lihongjie.coal.coalInfo.dto.CoalInfoDto; import cn.lihongjie.coal.coalInfo.dto.CreateCoalInfoDto; import cn.lihongjie.coal.coalInfo.dto.UpdateCoalInfoDto; import cn.lihongjie.coal.coalInfo.entity.CoalInfoEntity; + import org.mapstruct.Mapper; import org.mapstruct.control.DeepClone; @Mapper( - componentModel = org.mapstruct.MappingConstants.ComponentModel.SPRING, - uses = {CommonMapper.class}, - mappingControl = DeepClone.class) + componentModel = org.mapstruct.MappingConstants.ComponentModel.SPRING, + uses = {CommonMapper.class}, + mappingControl = DeepClone.class) public interface CoalInfoMapper - extends BaseMapper { - @Override - CoalInfoDto toDto(CoalInfoEntity user); + extends BaseMapper { + @Override + CoalInfoDto toDto(CoalInfoEntity user); } diff --git a/src/main/java/cn/lihongjie/coal/coalInfo/repository/CoalInfoRepository.java b/src/main/java/cn/lihongjie/coal/coalInfo/repository/CoalInfoRepository.java index fcdb2bdc..38b76841 100644 --- a/src/main/java/cn/lihongjie/coal/coalInfo/repository/CoalInfoRepository.java +++ b/src/main/java/cn/lihongjie/coal/coalInfo/repository/CoalInfoRepository.java @@ -2,6 +2,7 @@ package cn.lihongjie.coal.coalInfo.repository; import cn.lihongjie.coal.base.dao.BaseRepository; import cn.lihongjie.coal.coalInfo.entity.CoalInfoEntity; + import org.springframework.stereotype.Repository; @Repository diff --git a/src/main/java/cn/lihongjie/coal/coalInfo/service/CoalInfoService.java b/src/main/java/cn/lihongjie/coal/coalInfo/service/CoalInfoService.java index e28175c8..72c35248 100644 --- a/src/main/java/cn/lihongjie/coal/coalInfo/service/CoalInfoService.java +++ b/src/main/java/cn/lihongjie/coal/coalInfo/service/CoalInfoService.java @@ -11,8 +11,9 @@ import cn.lihongjie.coal.coalInfo.mapper.CoalInfoMapper; import cn.lihongjie.coal.coalInfo.repository.CoalInfoRepository; import cn.lihongjie.coal.coalPrice.entity.CoalPriceEntity; import cn.lihongjie.coal.coalPrice.service.CoalPriceService; -import java.util.Objects; + import lombok.extern.slf4j.Slf4j; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.convert.ConversionService; import org.springframework.data.domain.Page; @@ -20,63 +21,65 @@ import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Sort; import org.springframework.stereotype.Service; +import java.util.Objects; + @Service @Slf4j public class CoalInfoService extends BaseService { - @Autowired private CoalInfoRepository repository; + @Autowired CoalPriceService coalPriceService; + @Autowired private CoalInfoRepository repository; + @Autowired private CoalInfoMapper mapper; + @Autowired private ConversionService conversionService; - @Autowired private CoalInfoMapper mapper; + public CoalInfoDto create(CreateCoalInfoDto request) { + CoalInfoEntity entity = mapper.toEntity(request); - @Autowired private ConversionService conversionService; + this.repository.save(entity); - @Autowired CoalPriceService coalPriceService; - - public CoalInfoDto create(CreateCoalInfoDto request) { - CoalInfoEntity entity = mapper.toEntity(request); - - this.repository.save(entity); - - updatePrice(entity); - return getById(entity.getId()); - } - - private void updatePrice(CoalInfoEntity entity) { - CoalPriceEntity coalPrice = new CoalPriceEntity(); - coalPrice.setCoalInfo(entity); - coalPrice.setPrice(entity.getInitPrice()); - - coalPriceService.save(coalPrice); - } - - public CoalInfoDto update(UpdateCoalInfoDto request) { - CoalInfoEntity entity = this.repository.get(request.getId()); - Double old = entity.getInitPrice(); - this.mapper.updateEntity(entity, request); - - this.repository.save(entity); - if (!Objects.equals(old, request.getInitPrice())) { - - updatePrice(entity); + updatePrice(entity); + return getById(entity.getId()); } - return getById(entity.getId()); - } - public void delete(IdRequest request) { - this.repository.deleteAllById(request.getIds()); - } + private void updatePrice(CoalInfoEntity entity) { + CoalPriceEntity coalPrice = new CoalPriceEntity(); + coalPrice.setCoalInfo(entity); + coalPrice.setPrice(entity.getInitPrice()); - public CoalInfoDto getById(String id) { - CoalInfoEntity entity = repository.get(id); + coalPriceService.save(coalPrice); + } - return mapper.toDto(entity); - } + public CoalInfoDto update(UpdateCoalInfoDto request) { + CoalInfoEntity entity = this.repository.get(request.getId()); + Double old = entity.getInitPrice(); + this.mapper.updateEntity(entity, request); - public Page list(CommonQuery query) { - Page page = - repository.findAll( - query.specification(conversionService), - PageRequest.of(query.getPageNo(), query.getPageSize(), Sort.by(query.getOrders()))); + this.repository.save(entity); + if (!Objects.equals(old, request.getInitPrice())) { - return page.map(this.mapper::toDto); - } + updatePrice(entity); + } + return getById(entity.getId()); + } + + public void delete(IdRequest request) { + this.repository.deleteAllById(request.getIds()); + } + + public CoalInfoDto getById(String id) { + CoalInfoEntity entity = repository.get(id); + + return mapper.toDto(entity); + } + + public Page list(CommonQuery query) { + Page page = + repository.findAll( + query.specification(conversionService), + PageRequest.of( + query.getPageNo(), + query.getPageSize(), + Sort.by(query.getOrders()))); + + return page.map(this.mapper::toDto); + } } diff --git a/src/main/java/cn/lihongjie/coal/coalParameterDef/controller/CoalParameterDefController.java b/src/main/java/cn/lihongjie/coal/coalParameterDef/controller/CoalParameterDefController.java index 6f26e865..a722774d 100644 --- a/src/main/java/cn/lihongjie/coal/coalParameterDef/controller/CoalParameterDefController.java +++ b/src/main/java/cn/lihongjie/coal/coalParameterDef/controller/CoalParameterDefController.java @@ -10,6 +10,7 @@ import cn.lihongjie.coal.coalParameterDef.dto.CoalParameterDefDto; import cn.lihongjie.coal.coalParameterDef.dto.CreateCoalParameterDefDto; import cn.lihongjie.coal.coalParameterDef.dto.UpdateCoalParameterDefDto; import cn.lihongjie.coal.coalParameterDef.service.CoalParameterDefService; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.web.bind.annotation.PostMapping; @@ -24,34 +25,34 @@ import org.springframework.web.bind.annotation.RestController; @OrgScope public class CoalParameterDefController extends BaseController { - @Autowired CoalParameterDefService service; + @Autowired CoalParameterDefService service; - @PostMapping("/create") - @SysLog(action = "新增") - public CoalParameterDefDto create(@RequestBody CreateCoalParameterDefDto dto) { - return this.service.create(dto); - } + @PostMapping("/create") + @SysLog(action = "新增") + public CoalParameterDefDto create(@RequestBody CreateCoalParameterDefDto dto) { + return this.service.create(dto); + } - @PostMapping("/update") - @SysLog(action = "编辑") - public CoalParameterDefDto update(@RequestBody UpdateCoalParameterDefDto dto) { - return this.service.update(dto); - } + @PostMapping("/update") + @SysLog(action = "编辑") + public CoalParameterDefDto update(@RequestBody UpdateCoalParameterDefDto dto) { + return this.service.update(dto); + } - @PostMapping("/delete") - @SysLog(action = "删除") - public Object delete(@RequestBody IdRequest dto) { - this.service.delete(dto); - return true; - } + @PostMapping("/delete") + @SysLog(action = "删除") + public Object delete(@RequestBody IdRequest dto) { + this.service.delete(dto); + return true; + } - @PostMapping("/list") - public Page list(@RequestBody CommonQuery dto) { - return this.service.list(dto); - } + @PostMapping("/list") + public Page list(@RequestBody CommonQuery dto) { + return this.service.list(dto); + } - @PostMapping("/getById") - public CoalParameterDefDto getById(@RequestBody IdRequest dto) { - return this.service.getById(dto.getId()); - } + @PostMapping("/getById") + public CoalParameterDefDto getById(@RequestBody IdRequest dto) { + return this.service.getById(dto.getId()); + } } diff --git a/src/main/java/cn/lihongjie/coal/coalParameterDef/dto/CoalParameterDefDto.java b/src/main/java/cn/lihongjie/coal/coalParameterDef/dto/CoalParameterDefDto.java index 12d9ad20..76cdfa0a 100644 --- a/src/main/java/cn/lihongjie/coal/coalParameterDef/dto/CoalParameterDefDto.java +++ b/src/main/java/cn/lihongjie/coal/coalParameterDef/dto/CoalParameterDefDto.java @@ -1,20 +1,22 @@ package cn.lihongjie.coal.coalParameterDef.dto; import cn.lihongjie.coal.base.dto.OrgCommonDto; + import lombok.Data; + import org.hibernate.annotations.Comment; @Data public class CoalParameterDefDto extends OrgCommonDto { - @Comment("上级名称") - private String parentName; + @Comment("上级名称") + private String parentName; - @Comment("类型 0 手动输入 1 自动计算") - private String inputType; + @Comment("类型 0 手动输入 1 自动计算") + private String inputType; - private String inputTypeName; + private String inputTypeName; - @Comment("计算公式") - private String formula; + @Comment("计算公式") + private String formula; } diff --git a/src/main/java/cn/lihongjie/coal/coalParameterDef/dto/CreateCoalParameterDefDto.java b/src/main/java/cn/lihongjie/coal/coalParameterDef/dto/CreateCoalParameterDefDto.java index 8376b41c..b69d94c5 100644 --- a/src/main/java/cn/lihongjie/coal/coalParameterDef/dto/CreateCoalParameterDefDto.java +++ b/src/main/java/cn/lihongjie/coal/coalParameterDef/dto/CreateCoalParameterDefDto.java @@ -1,18 +1,20 @@ package cn.lihongjie.coal.coalParameterDef.dto; import cn.lihongjie.coal.base.dto.OrgCommonDto; + import lombok.Data; + import org.hibernate.annotations.Comment; @Data public class CreateCoalParameterDefDto extends OrgCommonDto { - @Comment("上级名称") - private String parentName; + @Comment("上级名称") + private String parentName; - @Comment("类型 0 手动输入 1 自动计算") - private String inputType; + @Comment("类型 0 手动输入 1 自动计算") + private String inputType; - @Comment("计算公式") - private String formula; + @Comment("计算公式") + private String formula; } diff --git a/src/main/java/cn/lihongjie/coal/coalParameterDef/dto/UpdateCoalParameterDefDto.java b/src/main/java/cn/lihongjie/coal/coalParameterDef/dto/UpdateCoalParameterDefDto.java index b28ee9b1..324d1576 100644 --- a/src/main/java/cn/lihongjie/coal/coalParameterDef/dto/UpdateCoalParameterDefDto.java +++ b/src/main/java/cn/lihongjie/coal/coalParameterDef/dto/UpdateCoalParameterDefDto.java @@ -1,18 +1,20 @@ package cn.lihongjie.coal.coalParameterDef.dto; import cn.lihongjie.coal.base.dto.OrgCommonDto; + import lombok.Data; + import org.hibernate.annotations.Comment; @Data public class UpdateCoalParameterDefDto extends OrgCommonDto { - @Comment("上级名称") - private String parentName; + @Comment("上级名称") + private String parentName; - @Comment("类型 0 手动输入 1 自动计算") - private String inputType; + @Comment("类型 0 手动输入 1 自动计算") + private String inputType; - @Comment("计算公式") - private String formula; + @Comment("计算公式") + private String formula; } diff --git a/src/main/java/cn/lihongjie/coal/coalParameterDef/entity/CoalParameterDefEntity.java b/src/main/java/cn/lihongjie/coal/coalParameterDef/entity/CoalParameterDefEntity.java index 57f9c465..0be33620 100644 --- a/src/main/java/cn/lihongjie/coal/coalParameterDef/entity/CoalParameterDefEntity.java +++ b/src/main/java/cn/lihongjie/coal/coalParameterDef/entity/CoalParameterDefEntity.java @@ -1,8 +1,11 @@ package cn.lihongjie.coal.coalParameterDef.entity; import cn.lihongjie.coal.base.entity.OrgCommonEntity; + import jakarta.persistence.Entity; + import lombok.Data; + import org.hibernate.annotations.Comment; import org.hibernate.annotations.Formula; @@ -10,30 +13,30 @@ import org.hibernate.annotations.Formula; @Data public class CoalParameterDefEntity extends OrgCommonEntity { - @Comment("上级名称") - private String parentName; + @Comment("上级名称") + private String parentName; - @Comment("类型 0 手动输入 1 自动计算") - private String inputType; + @Comment("类型 0 手动输入 1 自动计算") + private String inputType; - @Formula( - "(select i.name\n" - + "from t_dictionary d,\n" - + " t_dictionary_item i\n" - + "where d.id = i.dictionary_id\n" - + " and d.code = 'coalParameter.inputType'\n" - + " and i.code = input_type)") - private String inputTypeName; + @Formula( + "(select i.name\n" + + "from t_dictionary d,\n" + + " t_dictionary_item i\n" + + "where d.id = i.dictionary_id\n" + + " and d.code = 'coalParameter.inputType'\n" + + " and i.code = input_type)") + private String inputTypeName; - @Comment("计算公式") - private String formula; + @Comment("计算公式") + private String formula; - @Comment("解析后的公式") - private String formula0; + @Comment("解析后的公式") + private String formula0; - @Comment("依赖的字段") - private String dependents; + @Comment("依赖的字段") + private String dependents; - @Comment("计算优先级") - private Integer priority; + @Comment("计算优先级") + private Integer priority; } diff --git a/src/main/java/cn/lihongjie/coal/coalParameterDef/mapper/CoalParameterDefMapper.java b/src/main/java/cn/lihongjie/coal/coalParameterDef/mapper/CoalParameterDefMapper.java index 8198a875..eb08e0ca 100644 --- a/src/main/java/cn/lihongjie/coal/coalParameterDef/mapper/CoalParameterDefMapper.java +++ b/src/main/java/cn/lihongjie/coal/coalParameterDef/mapper/CoalParameterDefMapper.java @@ -11,12 +11,12 @@ import org.mapstruct.MappingConstants; import org.mapstruct.control.DeepClone; @Mapper( - componentModel = MappingConstants.ComponentModel.SPRING, - uses = {CommonMapper.class}, - mappingControl = DeepClone.class) + componentModel = MappingConstants.ComponentModel.SPRING, + uses = {CommonMapper.class}, + mappingControl = DeepClone.class) public interface CoalParameterDefMapper - extends BaseMapper< - CoalParameterDefEntity, - CoalParameterDefDto, - CreateCoalParameterDefDto, - UpdateCoalParameterDefDto> {} + extends BaseMapper< + CoalParameterDefEntity, + CoalParameterDefDto, + CreateCoalParameterDefDto, + UpdateCoalParameterDefDto> {} diff --git a/src/main/java/cn/lihongjie/coal/coalParameterDef/repository/CoalParameterDefRepository.java b/src/main/java/cn/lihongjie/coal/coalParameterDef/repository/CoalParameterDefRepository.java index d1834e97..c9dfef16 100644 --- a/src/main/java/cn/lihongjie/coal/coalParameterDef/repository/CoalParameterDefRepository.java +++ b/src/main/java/cn/lihongjie/coal/coalParameterDef/repository/CoalParameterDefRepository.java @@ -6,5 +6,5 @@ import org.springframework.stereotype.Repository; @Repository public interface CoalParameterDefRepository extends BaseRepository { - long countByOrganizationId(String organizationId); + long countByOrganizationId(String organizationId); } diff --git a/src/main/java/cn/lihongjie/coal/coalParameterDef/service/CoalParameterDefService.java b/src/main/java/cn/lihongjie/coal/coalParameterDef/service/CoalParameterDefService.java index 811e3a49..a7e90d8f 100644 --- a/src/main/java/cn/lihongjie/coal/coalParameterDef/service/CoalParameterDefService.java +++ b/src/main/java/cn/lihongjie/coal/coalParameterDef/service/CoalParameterDefService.java @@ -12,16 +12,17 @@ import cn.lihongjie.coal.coalParameterDef.repository.CoalParameterDefRepository; import cn.lihongjie.coal.common.Ctx; import cn.lihongjie.coal.common.GroovyScriptUtils; import cn.lihongjie.coal.organization.service.OrganizationService; + import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.base.Splitter; + import jakarta.annotation.PostConstruct; -import java.io.InputStream; -import java.util.List; -import java.util.Optional; + import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; + import org.apache.commons.lang3.StringUtils; import org.jgrapht.graph.DefaultDirectedGraph; import org.jgrapht.graph.DefaultEdge; @@ -34,153 +35,167 @@ import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Sort; import org.springframework.stereotype.Service; +import java.io.InputStream; +import java.util.List; +import java.util.Optional; + @Service @Slf4j public class CoalParameterDefService - extends BaseService { + extends BaseService { - @Autowired CoalParameterDefRepository repository; + @Autowired CoalParameterDefRepository repository; - @Autowired CoalParameterDefMapper mapper; + @Autowired CoalParameterDefMapper mapper; + @Autowired ConversionService conversionService; + @Autowired OrganizationService organizationService; - @PostConstruct - public void init() {} + @PostConstruct + public void init() {} - public CoalParameterDefDto create(CreateCoalParameterDefDto request) { + public CoalParameterDefDto create(CreateCoalParameterDefDto request) { - CoalParameterDefEntity entity = mapper.toEntity(request); + CoalParameterDefEntity entity = mapper.toEntity(request); - if (StringUtils.equalsIgnoreCase(entity.getInputType(), "1")) { - GroovyScriptUtils.validate(entity.getFormula()); - } - - this.repository.save(entity); - - updateFormula(entity); - - return getById(entity.getId()); - } - - private void updateFormula(CoalParameterDefEntity entity) { - - DefaultDirectedGraph graph = new DefaultDirectedGraph<>(DefaultEdge.class); - List all = - this.repository.findByOrganizationId(entity.getOrganizationId()); - - String formula = entity.getFormula(); - - entity.setFormula0(formula); - - entity.setDependents(StringUtils.join(GroovyScriptUtils.variables(formula), ",")); - - for (CoalParameterDefEntity def : all) { - - if (StringUtils.equalsIgnoreCase(def.getInputType(), "1")) { - - Iterable dependents = - Splitter.on(",").trimResults().omitEmptyStrings().split(def.getDependents()); - - for (String d : dependents) { - - graph.addVertex(def.getCode()); - graph.addVertex(d); - - graph.addEdge(d, def.getCode()); + if (StringUtils.equalsIgnoreCase(entity.getInputType(), "1")) { + GroovyScriptUtils.validate(entity.getFormula()); } - } + + this.repository.save(entity); + + updateFormula(entity); + + return getById(entity.getId()); } - TopologicalOrderIterator iterator = new TopologicalOrderIterator<>(graph); + private void updateFormula(CoalParameterDefEntity entity) { - int order = 0; - while (iterator.hasNext()) { - Object next = (String) iterator.next(); + DefaultDirectedGraph graph = + new DefaultDirectedGraph<>(DefaultEdge.class); + List all = + this.repository.findByOrganizationId(entity.getOrganizationId()); - for (CoalParameterDefEntity coalParameterDefEntity : all) { + String formula = entity.getFormula(); - if (StringUtils.equalsIgnoreCase(coalParameterDefEntity.getCode(), next + "")) { - coalParameterDefEntity.setPriority(order++); - break; + entity.setFormula0(formula); + + entity.setDependents(StringUtils.join(GroovyScriptUtils.variables(formula), ",")); + + for (CoalParameterDefEntity def : all) { + + if (StringUtils.equalsIgnoreCase(def.getInputType(), "1")) { + + Iterable dependents = + Splitter.on(",") + .trimResults() + .omitEmptyStrings() + .split(def.getDependents()); + + for (String d : dependents) { + + graph.addVertex(def.getCode()); + graph.addVertex(d); + + graph.addEdge(d, def.getCode()); + } + } } - } + + TopologicalOrderIterator iterator = + new TopologicalOrderIterator<>(graph); + + int order = 0; + while (iterator.hasNext()) { + Object next = iterator.next(); + + for (CoalParameterDefEntity coalParameterDefEntity : all) { + + if (StringUtils.equalsIgnoreCase(coalParameterDefEntity.getCode(), next + "")) { + coalParameterDefEntity.setPriority(order++); + break; + } + } + } + + this.repository.saveAll(all); } - this.repository.saveAll(all); - } + public CoalParameterDefDto update(UpdateCoalParameterDefDto request) { + CoalParameterDefEntity entity = this.repository.get(request.getId()); + this.mapper.updateEntity(entity, request); - public CoalParameterDefDto update(UpdateCoalParameterDefDto request) { - CoalParameterDefEntity entity = this.repository.get(request.getId()); - this.mapper.updateEntity(entity, request); + if (StringUtils.equalsIgnoreCase(entity.getInputType(), "1")) { + GroovyScriptUtils.validate(entity.getFormula()); + } - if (StringUtils.equalsIgnoreCase(entity.getInputType(), "1")) { - GroovyScriptUtils.validate(entity.getFormula()); + this.repository.save(entity); + updateFormula(entity); + return getById(entity.getId()); } - this.repository.save(entity); - updateFormula(entity); - return getById(entity.getId()); - } + public void delete(IdRequest request) { - public void delete(IdRequest request) { + this.repository.deleteAllById(request.getIds()); - this.repository.deleteAllById(request.getIds()); + List allDef = + this.repository.findByOrganizationId(Ctx.currentUser().getOrganizationId()); - List allDef = - this.repository.findByOrganizationId(Ctx.currentUser().getOrganizationId()); + Optional type1 = + allDef.stream() + .filter(x -> StringUtils.equalsIgnoreCase(x.getInputType(), "1")) + .findAny(); - Optional type1 = - allDef.stream().filter(x -> StringUtils.equalsIgnoreCase(x.getInputType(), "1")).findAny(); - - type1.ifPresent(this::updateFormula); - } - - public CoalParameterDefDto getById(String id) { - - CoalParameterDefEntity entity = repository.get(id); - - return mapper.toDto(entity); - } - - @Autowired ConversionService conversionService; - - public Page list(CommonQuery query) { - - Page page = - repository.findAll( - query.specification(conversionService), - PageRequest.of(query.getPageNo(), query.getPageSize(), Sort.by(query.getOrders()))); - - return page.map(this.mapper::toDto); - } - - @Autowired OrganizationService organizationService; - - public void initDefault() { - - organizationService - .findAll() - .forEach(organizationEntity -> initDefault(organizationEntity.getId())); - } - - @SneakyThrows - public void initDefault(String orgId) { - - if (repository.countByOrganizationId(orgId) == 0) { - - ClassPathResource classPathResource = new ClassPathResource("/config/CoalParameterDef.json"); - - ObjectMapper mapper = new ObjectMapper(); - mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); - - List coalParameterDefs; - try (InputStream inputStream = classPathResource.getInputStream()) { - coalParameterDefs = - mapper.readValue(inputStream, new TypeReference>() {}); - - coalParameterDefs.forEach(x -> x.setOrganizationId(orgId)); - - this.repository.saveAll(coalParameterDefs); - } + type1.ifPresent(this::updateFormula); + } + + public CoalParameterDefDto getById(String id) { + + CoalParameterDefEntity entity = repository.get(id); + + return mapper.toDto(entity); + } + + public Page list(CommonQuery query) { + + Page page = + repository.findAll( + query.specification(conversionService), + PageRequest.of( + query.getPageNo(), + query.getPageSize(), + Sort.by(query.getOrders()))); + + return page.map(this.mapper::toDto); + } + + public void initDefault() { + + organizationService + .findAll() + .forEach(organizationEntity -> initDefault(organizationEntity.getId())); + } + + @SneakyThrows + public void initDefault(String orgId) { + + if (repository.countByOrganizationId(orgId) == 0) { + + ClassPathResource classPathResource = + new ClassPathResource("/config/CoalParameterDef.json"); + + ObjectMapper mapper = new ObjectMapper(); + mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); + + List coalParameterDefs; + try (InputStream inputStream = classPathResource.getInputStream()) { + coalParameterDefs = + mapper.readValue( + inputStream, new TypeReference>() {}); + + coalParameterDefs.forEach(x -> x.setOrganizationId(orgId)); + + this.repository.saveAll(coalParameterDefs); + } + } } - } } diff --git a/src/main/java/cn/lihongjie/coal/coalPrice/controller/CoalPriceController.java b/src/main/java/cn/lihongjie/coal/coalPrice/controller/CoalPriceController.java index eec6a798..61e130d7 100644 --- a/src/main/java/cn/lihongjie/coal/coalPrice/controller/CoalPriceController.java +++ b/src/main/java/cn/lihongjie/coal/coalPrice/controller/CoalPriceController.java @@ -8,7 +8,9 @@ import cn.lihongjie.coal.coalPrice.dto.CoalPriceDto; import cn.lihongjie.coal.coalPrice.dto.CreateCoalPriceDto; import cn.lihongjie.coal.coalPrice.dto.UpdateCoalPriceDto; import cn.lihongjie.coal.coalPrice.service.CoalPriceService; + import lombok.extern.slf4j.Slf4j; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.web.bind.annotation.PostMapping; @@ -22,31 +24,31 @@ import org.springframework.web.bind.annotation.RestController; @Slf4j @OrgScope public class CoalPriceController { - @Autowired private CoalPriceService service; + @Autowired private CoalPriceService service; - @PostMapping("/create") - public CoalPriceDto create(@RequestBody CreateCoalPriceDto request) { - return this.service.create(request); - } + @PostMapping("/create") + public CoalPriceDto create(@RequestBody CreateCoalPriceDto request) { + return this.service.create(request); + } - @PostMapping("/update") - public CoalPriceDto update(@RequestBody UpdateCoalPriceDto request) { - return this.service.update(request); - } + @PostMapping("/update") + public CoalPriceDto update(@RequestBody UpdateCoalPriceDto request) { + return this.service.update(request); + } - @PostMapping("/delete") - public Object delete(@RequestBody IdRequest request) { - this.service.delete(request); - return true; - } + @PostMapping("/delete") + public Object delete(@RequestBody IdRequest request) { + this.service.delete(request); + return true; + } - @PostMapping("/getById") - public CoalPriceDto getById(@RequestBody String request) { - return this.service.getById(request); - } + @PostMapping("/getById") + public CoalPriceDto getById(@RequestBody String request) { + return this.service.getById(request); + } - @PostMapping("/list") - public Page list(@RequestBody CommonQuery request) { - return this.service.list(request); - } + @PostMapping("/list") + public Page list(@RequestBody CommonQuery request) { + return this.service.list(request); + } } diff --git a/src/main/java/cn/lihongjie/coal/coalPrice/dto/CoalPriceDto.java b/src/main/java/cn/lihongjie/coal/coalPrice/dto/CoalPriceDto.java index 5c28e8cb..679ce9b3 100644 --- a/src/main/java/cn/lihongjie/coal/coalPrice/dto/CoalPriceDto.java +++ b/src/main/java/cn/lihongjie/coal/coalPrice/dto/CoalPriceDto.java @@ -2,14 +2,16 @@ package cn.lihongjie.coal.coalPrice.dto; import cn.lihongjie.coal.base.dto.OrgCommonDto; import cn.lihongjie.coal.coalInfo.entity.CoalInfoEntity; + import lombok.Data; + import org.hibernate.annotations.Comment; @Data public class CoalPriceDto extends OrgCommonDto { - @Comment("煤源") - private CoalInfoEntity coalInfo; + @Comment("煤源") + private CoalInfoEntity coalInfo; - @Comment("价格") - private Double price; + @Comment("价格") + private Double price; } diff --git a/src/main/java/cn/lihongjie/coal/coalPrice/dto/CreateCoalPriceDto.java b/src/main/java/cn/lihongjie/coal/coalPrice/dto/CreateCoalPriceDto.java index c274b996..d6f08844 100644 --- a/src/main/java/cn/lihongjie/coal/coalPrice/dto/CreateCoalPriceDto.java +++ b/src/main/java/cn/lihongjie/coal/coalPrice/dto/CreateCoalPriceDto.java @@ -1,14 +1,16 @@ package cn.lihongjie.coal.coalPrice.dto; import cn.lihongjie.coal.base.dto.OrgCommonDto; + import lombok.Data; + import org.hibernate.annotations.Comment; @Data public class CreateCoalPriceDto extends OrgCommonDto { - @Comment("煤源") - private String coalInfo; + @Comment("煤源") + private String coalInfo; - @Comment("价格") - private Double price; + @Comment("价格") + private Double price; } diff --git a/src/main/java/cn/lihongjie/coal/coalPrice/dto/UpdateCoalPriceDto.java b/src/main/java/cn/lihongjie/coal/coalPrice/dto/UpdateCoalPriceDto.java index 42b27fee..50cb5c18 100644 --- a/src/main/java/cn/lihongjie/coal/coalPrice/dto/UpdateCoalPriceDto.java +++ b/src/main/java/cn/lihongjie/coal/coalPrice/dto/UpdateCoalPriceDto.java @@ -1,14 +1,16 @@ package cn.lihongjie.coal.coalPrice.dto; import cn.lihongjie.coal.base.dto.OrgCommonDto; + import lombok.Data; + import org.hibernate.annotations.Comment; @Data public class UpdateCoalPriceDto extends OrgCommonDto { - @Comment("煤源") - private String coalInfo; + @Comment("煤源") + private String coalInfo; - @Comment("价格") - private Double price; + @Comment("价格") + private Double price; } diff --git a/src/main/java/cn/lihongjie/coal/coalPrice/entity/CoalPriceEntity.java b/src/main/java/cn/lihongjie/coal/coalPrice/entity/CoalPriceEntity.java index 8488b69b..b86212a4 100644 --- a/src/main/java/cn/lihongjie/coal/coalPrice/entity/CoalPriceEntity.java +++ b/src/main/java/cn/lihongjie/coal/coalPrice/entity/CoalPriceEntity.java @@ -2,19 +2,22 @@ package cn.lihongjie.coal.coalPrice.entity; import cn.lihongjie.coal.base.entity.OrgCommonEntity; import cn.lihongjie.coal.coalInfo.entity.CoalInfoEntity; + import jakarta.persistence.Entity; import jakarta.persistence.ManyToOne; + import lombok.Data; + import org.hibernate.annotations.Comment; @Data @Entity public class CoalPriceEntity extends OrgCommonEntity { - @Comment("煤源") - @ManyToOne - private CoalInfoEntity coalInfo; + @Comment("煤源") + @ManyToOne + private CoalInfoEntity coalInfo; - @Comment("价格") - private Double price; + @Comment("价格") + private Double price; } diff --git a/src/main/java/cn/lihongjie/coal/coalPrice/mapper/CoalPriceMapper.java b/src/main/java/cn/lihongjie/coal/coalPrice/mapper/CoalPriceMapper.java index 1a581ecb..fbf22a79 100644 --- a/src/main/java/cn/lihongjie/coal/coalPrice/mapper/CoalPriceMapper.java +++ b/src/main/java/cn/lihongjie/coal/coalPrice/mapper/CoalPriceMapper.java @@ -6,12 +6,13 @@ import cn.lihongjie.coal.coalPrice.dto.CoalPriceDto; import cn.lihongjie.coal.coalPrice.dto.CreateCoalPriceDto; import cn.lihongjie.coal.coalPrice.dto.UpdateCoalPriceDto; import cn.lihongjie.coal.coalPrice.entity.CoalPriceEntity; + import org.mapstruct.Mapper; import org.mapstruct.control.DeepClone; @Mapper( - componentModel = org.mapstruct.MappingConstants.ComponentModel.SPRING, - uses = {CommonMapper.class}, - mappingControl = DeepClone.class) + componentModel = org.mapstruct.MappingConstants.ComponentModel.SPRING, + uses = {CommonMapper.class}, + mappingControl = DeepClone.class) public interface CoalPriceMapper - extends BaseMapper {} + extends BaseMapper {} diff --git a/src/main/java/cn/lihongjie/coal/coalPrice/repository/CoalPriceRepository.java b/src/main/java/cn/lihongjie/coal/coalPrice/repository/CoalPriceRepository.java index 1c65c473..263dad8f 100644 --- a/src/main/java/cn/lihongjie/coal/coalPrice/repository/CoalPriceRepository.java +++ b/src/main/java/cn/lihongjie/coal/coalPrice/repository/CoalPriceRepository.java @@ -2,6 +2,7 @@ package cn.lihongjie.coal.coalPrice.repository; import cn.lihongjie.coal.base.dao.BaseRepository; import cn.lihongjie.coal.coalPrice.entity.CoalPriceEntity; + import org.springframework.stereotype.Repository; @Repository diff --git a/src/main/java/cn/lihongjie/coal/coalPrice/service/CoalPriceService.java b/src/main/java/cn/lihongjie/coal/coalPrice/service/CoalPriceService.java index cf967f06..7f0d712b 100644 --- a/src/main/java/cn/lihongjie/coal/coalPrice/service/CoalPriceService.java +++ b/src/main/java/cn/lihongjie/coal/coalPrice/service/CoalPriceService.java @@ -9,7 +9,9 @@ import cn.lihongjie.coal.coalPrice.dto.UpdateCoalPriceDto; import cn.lihongjie.coal.coalPrice.entity.CoalPriceEntity; import cn.lihongjie.coal.coalPrice.mapper.CoalPriceMapper; import cn.lihongjie.coal.coalPrice.repository.CoalPriceRepository; + import lombok.extern.slf4j.Slf4j; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.convert.ConversionService; import org.springframework.data.domain.Page; @@ -20,44 +22,47 @@ import org.springframework.stereotype.Service; @Service @Slf4j public class CoalPriceService extends BaseService { - @Autowired private CoalPriceRepository repository; + @Autowired private CoalPriceRepository repository; - @Autowired private CoalPriceMapper mapper; + @Autowired private CoalPriceMapper mapper; - @Autowired private ConversionService conversionService; + @Autowired private ConversionService conversionService; - public CoalPriceDto create(CreateCoalPriceDto request) { - CoalPriceEntity entity = mapper.toEntity(request); + public CoalPriceDto create(CreateCoalPriceDto request) { + CoalPriceEntity entity = mapper.toEntity(request); - this.repository.save(entity); - return getById(entity.getId()); - } + this.repository.save(entity); + return getById(entity.getId()); + } - public CoalPriceDto update(UpdateCoalPriceDto request) { - CoalPriceEntity entity = this.repository.get(request.getId()); - this.mapper.updateEntity(entity, request); + public CoalPriceDto update(UpdateCoalPriceDto request) { + CoalPriceEntity entity = this.repository.get(request.getId()); + this.mapper.updateEntity(entity, request); - this.repository.save(entity); + this.repository.save(entity); - return getById(entity.getId()); - } + return getById(entity.getId()); + } - public void delete(IdRequest request) { - this.repository.deleteAllById(request.getIds()); - } + public void delete(IdRequest request) { + this.repository.deleteAllById(request.getIds()); + } - public CoalPriceDto getById(String id) { - CoalPriceEntity entity = repository.get(id); + public CoalPriceDto getById(String id) { + CoalPriceEntity entity = repository.get(id); - return mapper.toDto(entity); - } + return mapper.toDto(entity); + } - public Page list(CommonQuery query) { - Page page = - repository.findAll( - query.specification(conversionService), - PageRequest.of(query.getPageNo(), query.getPageSize(), Sort.by(query.getOrders()))); + public Page list(CommonQuery query) { + Page page = + repository.findAll( + query.specification(conversionService), + PageRequest.of( + query.getPageNo(), + query.getPageSize(), + Sort.by(query.getOrders()))); - return page.map(this.mapper::toDto); - } + return page.map(this.mapper::toDto); + } } diff --git a/src/main/java/cn/lihongjie/coal/coalWashingDailyAnalysis/controller/CoalWashingDailyAnalysisController.java b/src/main/java/cn/lihongjie/coal/coalWashingDailyAnalysis/controller/CoalWashingDailyAnalysisController.java index 91087065..bee48200 100644 --- a/src/main/java/cn/lihongjie/coal/coalWashingDailyAnalysis/controller/CoalWashingDailyAnalysisController.java +++ b/src/main/java/cn/lihongjie/coal/coalWashingDailyAnalysis/controller/CoalWashingDailyAnalysisController.java @@ -9,6 +9,7 @@ import cn.lihongjie.coal.coalWashingDailyAnalysis.dto.CoalWashingDailyAnalysisDt import cn.lihongjie.coal.coalWashingDailyAnalysis.dto.CreateCoalWashingDailyAnalysisDto; import cn.lihongjie.coal.coalWashingDailyAnalysis.dto.UpdateCoalWashingDailyAnalysisDto; import cn.lihongjie.coal.coalWashingDailyAnalysis.service.CoalWashingDailyAnalysisService; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.web.bind.annotation.PostMapping; @@ -22,40 +23,41 @@ import org.springframework.web.bind.annotation.RestController; @Anonymous public class CoalWashingDailyAnalysisController extends BaseController { - @Autowired CoalWashingDailyAnalysisService service; + @Autowired CoalWashingDailyAnalysisService service; - @PostMapping("/calculate") - @SysLog(action = "计算") - public CoalWashingDailyAnalysisDto calculate(@RequestBody CreateCoalWashingDailyAnalysisDto dto) { - return this.service.calculate(dto); - } + @PostMapping("/calculate") + @SysLog(action = "计算") + public CoalWashingDailyAnalysisDto calculate( + @RequestBody CreateCoalWashingDailyAnalysisDto dto) { + return this.service.calculate(dto); + } - @PostMapping("/create") - @SysLog(action = "新增") - public CoalWashingDailyAnalysisDto create(@RequestBody CreateCoalWashingDailyAnalysisDto dto) { - return this.service.create(dto); - } + @PostMapping("/create") + @SysLog(action = "新增") + public CoalWashingDailyAnalysisDto create(@RequestBody CreateCoalWashingDailyAnalysisDto dto) { + return this.service.create(dto); + } - @PostMapping("/update") - @SysLog(action = "编辑") - public CoalWashingDailyAnalysisDto update(@RequestBody UpdateCoalWashingDailyAnalysisDto dto) { - return this.service.update(dto); - } + @PostMapping("/update") + @SysLog(action = "编辑") + public CoalWashingDailyAnalysisDto update(@RequestBody UpdateCoalWashingDailyAnalysisDto dto) { + return this.service.update(dto); + } - @PostMapping("/delete") - @SysLog(action = "删除") - public Object delete(@RequestBody IdRequest dto) { - this.service.delete(dto); - return true; - } + @PostMapping("/delete") + @SysLog(action = "删除") + public Object delete(@RequestBody IdRequest dto) { + this.service.delete(dto); + return true; + } - @PostMapping("/list") - public Page list(@RequestBody CommonQuery dto) { - return this.service.list(dto); - } + @PostMapping("/list") + public Page list(@RequestBody CommonQuery dto) { + return this.service.list(dto); + } - @PostMapping("/getById") - public CoalWashingDailyAnalysisDto getById(@RequestBody IdRequest dto) { - return this.service.getById(dto.getId()); - } + @PostMapping("/getById") + public CoalWashingDailyAnalysisDto getById(@RequestBody IdRequest dto) { + return this.service.getById(dto.getId()); + } } diff --git a/src/main/java/cn/lihongjie/coal/coalWashingDailyAnalysis/dto/CoalWashingDailyAnalysisDto.java b/src/main/java/cn/lihongjie/coal/coalWashingDailyAnalysis/dto/CoalWashingDailyAnalysisDto.java index 901cf309..b5cbea34 100644 --- a/src/main/java/cn/lihongjie/coal/coalWashingDailyAnalysis/dto/CoalWashingDailyAnalysisDto.java +++ b/src/main/java/cn/lihongjie/coal/coalWashingDailyAnalysis/dto/CoalWashingDailyAnalysisDto.java @@ -2,48 +2,52 @@ package cn.lihongjie.coal.coalWashingDailyAnalysis.dto; import cn.lihongjie.coal.base.dto.OrgCommonDto; import cn.lihongjie.coal.coalWashingDailyAnalysis.entity.CoalWashingDailyAnalysisItemVo; + import jakarta.persistence.CollectionTable; import jakarta.persistence.ConstraintMode; import jakarta.persistence.ElementCollection; import jakarta.persistence.ForeignKey; + +import lombok.Data; + +import org.hibernate.annotations.Comment; + import java.time.LocalDate; import java.util.List; -import lombok.Data; -import org.hibernate.annotations.Comment; /** */ @Data @Comment("洗煤报告表") public class CoalWashingDailyAnalysisDto extends OrgCommonDto { - @Comment("日期") - private LocalDate date; + @Comment("日期") + private LocalDate date; - @ElementCollection - @Comment("用户手动录入的记录") - @CollectionTable(foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT)) - private List inputItems; + @ElementCollection + @Comment("用户手动录入的记录") + @CollectionTable(foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT)) + private List inputItems; - @ElementCollection - @Comment("连续平均值") - @CollectionTable(foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT)) - private List rollingAvgItems; + @ElementCollection + @Comment("连续平均值") + @CollectionTable(foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT)) + private List rollingAvgItems; - @Comment("目标大堆 灰") - private Double ddp1; + @Comment("目标大堆 灰") + private Double ddp1; - @Comment("目标大堆 硫") - private Double ddp2; + @Comment("目标大堆 硫") + private Double ddp2; - @Comment("目标大堆 挥发") - private Double ddp3; + @Comment("目标大堆 挥发") + private Double ddp3; - @Comment("目标大堆 粘结") - private Double ddp4; + @Comment("目标大堆 粘结") + private Double ddp4; - @Comment("目标大堆 备用") - private Double ddp5; + @Comment("目标大堆 备用") + private Double ddp5; - @Comment("产量初始值") - private Double initTotalNumber = 0.0; + @Comment("产量初始值") + private Double initTotalNumber = 0.0; } diff --git a/src/main/java/cn/lihongjie/coal/coalWashingDailyAnalysis/dto/CreateCoalWashingDailyAnalysisDto.java b/src/main/java/cn/lihongjie/coal/coalWashingDailyAnalysis/dto/CreateCoalWashingDailyAnalysisDto.java index a4536e6c..054ef84c 100644 --- a/src/main/java/cn/lihongjie/coal/coalWashingDailyAnalysis/dto/CreateCoalWashingDailyAnalysisDto.java +++ b/src/main/java/cn/lihongjie/coal/coalWashingDailyAnalysis/dto/CreateCoalWashingDailyAnalysisDto.java @@ -2,48 +2,52 @@ package cn.lihongjie.coal.coalWashingDailyAnalysis.dto; import cn.lihongjie.coal.base.dto.OrgCommonDto; import cn.lihongjie.coal.coalWashingDailyAnalysis.entity.CoalWashingDailyAnalysisItemVo; + import jakarta.persistence.CollectionTable; import jakarta.persistence.ConstraintMode; import jakarta.persistence.ElementCollection; import jakarta.persistence.ForeignKey; + +import lombok.Data; + +import org.hibernate.annotations.Comment; + import java.time.LocalDate; import java.util.List; -import lombok.Data; -import org.hibernate.annotations.Comment; /** */ @Data @Comment("洗煤报告表") public class CreateCoalWashingDailyAnalysisDto extends OrgCommonDto { - @Comment("日期") - private LocalDate date; + @Comment("日期") + private LocalDate date; - @ElementCollection - @Comment("用户手动录入的记录") - @CollectionTable(foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT)) - private List inputItems; + @ElementCollection + @Comment("用户手动录入的记录") + @CollectionTable(foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT)) + private List inputItems; - @ElementCollection - @Comment("连续平均值") - @CollectionTable(foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT)) - private List rollingAvgItems; + @ElementCollection + @Comment("连续平均值") + @CollectionTable(foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT)) + private List rollingAvgItems; - @Comment("目标大堆 灰") - private Double ddp1; + @Comment("目标大堆 灰") + private Double ddp1; - @Comment("目标大堆 硫") - private Double ddp2; + @Comment("目标大堆 硫") + private Double ddp2; - @Comment("目标大堆 挥发") - private Double ddp3; + @Comment("目标大堆 挥发") + private Double ddp3; - @Comment("目标大堆 粘结") - private Double ddp4; + @Comment("目标大堆 粘结") + private Double ddp4; - @Comment("目标大堆 备用") - private Double ddp5; + @Comment("目标大堆 备用") + private Double ddp5; - @Comment("产量初始值") - private Double initTotalNumber = 0.0; + @Comment("产量初始值") + private Double initTotalNumber = 0.0; } diff --git a/src/main/java/cn/lihongjie/coal/coalWashingDailyAnalysis/dto/UpdateCoalWashingDailyAnalysisDto.java b/src/main/java/cn/lihongjie/coal/coalWashingDailyAnalysis/dto/UpdateCoalWashingDailyAnalysisDto.java index 810e5a7a..d198d818 100644 --- a/src/main/java/cn/lihongjie/coal/coalWashingDailyAnalysis/dto/UpdateCoalWashingDailyAnalysisDto.java +++ b/src/main/java/cn/lihongjie/coal/coalWashingDailyAnalysis/dto/UpdateCoalWashingDailyAnalysisDto.java @@ -2,48 +2,52 @@ package cn.lihongjie.coal.coalWashingDailyAnalysis.dto; import cn.lihongjie.coal.base.dto.OrgCommonDto; import cn.lihongjie.coal.coalWashingDailyAnalysis.entity.CoalWashingDailyAnalysisItemVo; + import jakarta.persistence.CollectionTable; import jakarta.persistence.ConstraintMode; import jakarta.persistence.ElementCollection; import jakarta.persistence.ForeignKey; + +import lombok.Data; + +import org.hibernate.annotations.Comment; + import java.time.LocalDate; import java.util.List; -import lombok.Data; -import org.hibernate.annotations.Comment; /** */ @Data @Comment("洗煤报告表") public class UpdateCoalWashingDailyAnalysisDto extends OrgCommonDto { - @Comment("日期") - private LocalDate date; + @Comment("日期") + private LocalDate date; - @ElementCollection - @Comment("用户手动录入的记录") - @CollectionTable(foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT)) - private List inputItems; + @ElementCollection + @Comment("用户手动录入的记录") + @CollectionTable(foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT)) + private List inputItems; - @ElementCollection - @Comment("连续平均值") - @CollectionTable(foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT)) - private List rollingAvgItems; + @ElementCollection + @Comment("连续平均值") + @CollectionTable(foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT)) + private List rollingAvgItems; - @Comment("目标大堆 灰") - private Double ddp1; + @Comment("目标大堆 灰") + private Double ddp1; - @Comment("目标大堆 硫") - private Double ddp2; + @Comment("目标大堆 硫") + private Double ddp2; - @Comment("目标大堆 挥发") - private Double ddp3; + @Comment("目标大堆 挥发") + private Double ddp3; - @Comment("目标大堆 粘结") - private Double ddp4; + @Comment("目标大堆 粘结") + private Double ddp4; - @Comment("目标大堆 备用") - private Double ddp5; + @Comment("目标大堆 备用") + private Double ddp5; - @Comment("产量初始值") - private Double initTotalNumber = 0.0; + @Comment("产量初始值") + private Double initTotalNumber = 0.0; } diff --git a/src/main/java/cn/lihongjie/coal/coalWashingDailyAnalysis/entity/CoalWashingDailyAnalysisEntity.java b/src/main/java/cn/lihongjie/coal/coalWashingDailyAnalysis/entity/CoalWashingDailyAnalysisEntity.java index c079a437..e4923432 100644 --- a/src/main/java/cn/lihongjie/coal/coalWashingDailyAnalysis/entity/CoalWashingDailyAnalysisEntity.java +++ b/src/main/java/cn/lihongjie/coal/coalWashingDailyAnalysis/entity/CoalWashingDailyAnalysisEntity.java @@ -1,16 +1,20 @@ package cn.lihongjie.coal.coalWashingDailyAnalysis.entity; import cn.lihongjie.coal.base.entity.OrgCommonEntity; + import jakarta.persistence.*; + +import lombok.Data; + +import org.apache.commons.collections4.CollectionUtils; +import org.apache.commons.lang3.ObjectUtils; +import org.hibernate.annotations.Comment; + import java.time.LocalDate; import java.time.LocalTime; import java.util.ArrayList; import java.util.Comparator; import java.util.List; -import lombok.Data; -import org.apache.commons.collections4.CollectionUtils; -import org.apache.commons.lang3.ObjectUtils; -import org.hibernate.annotations.Comment; /** */ @Entity @@ -18,261 +22,262 @@ import org.hibernate.annotations.Comment; @Comment("洗煤报告表") public class CoalWashingDailyAnalysisEntity extends OrgCommonEntity { - @Comment("日期") - private LocalDate date; + @Comment("日期") + private LocalDate date; - @ElementCollection - @Comment("用户手动录入的记录") - @CollectionTable(foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT)) - private List inputItems; + @ElementCollection + @Comment("用户手动录入的记录") + @CollectionTable(foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT)) + private List inputItems; - @ElementCollection - @Comment("连续平均值") - @CollectionTable(foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT)) - private List rollingAvgItems; + @ElementCollection + @Comment("连续平均值") + @CollectionTable(foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT)) + private List rollingAvgItems; - @Comment("目标大堆 灰") - private Double ddp1; + @Comment("目标大堆 灰") + private Double ddp1; - @Comment("目标大堆 硫") - private Double ddp2; + @Comment("目标大堆 硫") + private Double ddp2; - @Comment("目标大堆 挥发") - private Double ddp3; + @Comment("目标大堆 挥发") + private Double ddp3; - @Comment("目标大堆 粘结") - private Double ddp4; + @Comment("目标大堆 粘结") + private Double ddp4; - @Comment("目标大堆 备用") - private Double ddp5; + @Comment("目标大堆 备用") + private Double ddp5; - @Comment("产量初始值") - private Double initTotalNumber = 0.0; + @Comment("产量初始值") + private Double initTotalNumber = 0.0; - public void rollingAvg() { + public void rollingAvg() { - rollingAvgItems = new ArrayList<>(); + rollingAvgItems = new ArrayList<>(); - if (CollectionUtils.isEmpty(inputItems)) { - return; - } - inputItems.sort( - Comparator.comparing(x -> ObjectUtils.defaultIfNull(x.getTime(), LocalTime.MIN))); - inputItems.forEach(x -> x.calculate()); - - for (int i = 0; i < inputItems.size(); i++) { - - List current = inputItems.subList(0, i + 1); - rollingAvgItems.add(rollingAvg(current)); - } - } - - private CoalWashingDailyAnalysisItemVo rollingAvg(List current) { - - CoalWashingDailyAnalysisItemVo vo = new CoalWashingDailyAnalysisItemVo(); - int size = current.size(); - vo.setTime(current.get(size - 1).getTime()); - vo.setTotalNumber(current.get(size - 1).getTotalNumber()); - - vo.setC0p0(current.get(size - 1).getC0p0()); - - vo.setC1p0(current.get(size - 1).getC1p0()); - - vo.setC2p0(current.get(size - 1).getC2p0()); - - vo.setC3p0(current.get(size - 1).getC3p0()); - - vo.setC4p0(current.get(size - 1).getC4p0()); - - vo.setC5p0(current.get(size - 1).getC5p0()); - - vo.setC6p0(current.get(size - 1).getC6p0()); - - vo.setC7p0(current.get(size - 1).getC7p0()); - - vo.setC8p0(current.get(size - 1).getC8p0()); - - vo.setC9p0(current.get(size - 1).getC9p0()); - - for (int i = 0; i < size; i++) { - var c = current.get(i); - var p = i == 0 ? c.withTotalNumber(initTotalNumber) : current.get(i - 1); - double diff = c.getTotalNumber() - p.getTotalNumber(); - if (vo.getC0p0() != null && vo.getC0p0() > 0) { - vo.setC0p1(ObjectUtils.defaultIfNull(vo.getC0p1(), 0.0) + diff * c.getC0p1()); - vo.setC0p2(ObjectUtils.defaultIfNull(vo.getC0p2(), 0.0) + diff * c.getC0p1()); - if (i == size - 1) { - vo.setC0p1(vo.getC0p1() / c.getTotalNumber()); - vo.setC0p2(vo.getC0p2() / c.getTotalNumber()); + if (CollectionUtils.isEmpty(inputItems)) { + return; } - } - if (vo.getC1p0() != null && vo.getC1p0() > 0) { - vo.setC1p1(ObjectUtils.defaultIfNull(vo.getC1p1(), 0.0) + diff * c.getC1p1()); - vo.setC1p2(ObjectUtils.defaultIfNull(vo.getC1p2(), 0.0) + diff * c.getC1p1()); - if (i == size - 1) { - vo.setC1p1(vo.getC1p1() / c.getTotalNumber()); - vo.setC1p2(vo.getC1p2() / c.getTotalNumber()); - } - } - if (vo.getC2p0() != null && vo.getC2p0() > 0) { - vo.setC2p1(ObjectUtils.defaultIfNull(vo.getC2p1(), 0.0) + diff * c.getC2p1()); - vo.setC2p2(ObjectUtils.defaultIfNull(vo.getC2p2(), 0.0) + diff * c.getC2p1()); - if (i == size - 1) { - vo.setC2p1(vo.getC2p1() / c.getTotalNumber()); - vo.setC2p2(vo.getC2p2() / c.getTotalNumber()); - } - } - if (vo.getC3p0() != null && vo.getC3p0() > 0) { - vo.setC3p1(ObjectUtils.defaultIfNull(vo.getC3p1(), 0.0) + diff * c.getC3p1()); - vo.setC3p2(ObjectUtils.defaultIfNull(vo.getC3p2(), 0.0) + diff * c.getC3p1()); - if (i == size - 1) { - vo.setC3p1(vo.getC3p1() / c.getTotalNumber()); - vo.setC3p2(vo.getC3p2() / c.getTotalNumber()); - } - } - if (vo.getC4p0() != null && vo.getC4p0() > 0) { - vo.setC4p1(ObjectUtils.defaultIfNull(vo.getC4p1(), 0.0) + diff * c.getC4p1()); - vo.setC4p2(ObjectUtils.defaultIfNull(vo.getC4p2(), 0.0) + diff * c.getC4p1()); - if (i == size - 1) { - vo.setC4p1(vo.getC4p1() / c.getTotalNumber()); - vo.setC4p2(vo.getC4p2() / c.getTotalNumber()); - } - } - if (vo.getC5p0() != null && vo.getC5p0() > 0) { - vo.setC5p1(ObjectUtils.defaultIfNull(vo.getC5p1(), 0.0) + diff * c.getC5p1()); - vo.setC5p2(ObjectUtils.defaultIfNull(vo.getC5p2(), 0.0) + diff * c.getC5p1()); - if (i == size - 1) { - vo.setC5p1(vo.getC5p1() / c.getTotalNumber()); - vo.setC5p2(vo.getC5p2() / c.getTotalNumber()); - } - } - if (vo.getC6p0() != null && vo.getC6p0() > 0) { - vo.setC6p1(ObjectUtils.defaultIfNull(vo.getC6p1(), 0.0) + diff * c.getC6p1()); - vo.setC6p2(ObjectUtils.defaultIfNull(vo.getC6p2(), 0.0) + diff * c.getC6p1()); - if (i == size - 1) { - vo.setC6p1(vo.getC6p1() / c.getTotalNumber()); - vo.setC6p2(vo.getC6p2() / c.getTotalNumber()); - } - } - if (vo.getC7p0() != null && vo.getC7p0() > 0) { - vo.setC7p1(ObjectUtils.defaultIfNull(vo.getC7p1(), 0.0) + diff * c.getC7p1()); - vo.setC7p2(ObjectUtils.defaultIfNull(vo.getC7p2(), 0.0) + diff * c.getC7p1()); - if (i == size - 1) { - vo.setC7p1(vo.getC7p1() / c.getTotalNumber()); - vo.setC7p2(vo.getC7p2() / c.getTotalNumber()); - } - } - if (vo.getC8p0() != null && vo.getC8p0() > 0) { - vo.setC8p1(ObjectUtils.defaultIfNull(vo.getC8p1(), 0.0) + diff * c.getC8p1()); - vo.setC8p2(ObjectUtils.defaultIfNull(vo.getC8p2(), 0.0) + diff * c.getC8p1()); - if (i == size - 1) { - vo.setC8p1(vo.getC8p1() / c.getTotalNumber()); - vo.setC8p2(vo.getC8p2() / c.getTotalNumber()); - } - } - if (vo.getC9p0() != null && vo.getC9p0() > 0) { - vo.setC9p1(ObjectUtils.defaultIfNull(vo.getC9p1(), 0.0) + diff * c.getC9p1()); - vo.setC9p2(ObjectUtils.defaultIfNull(vo.getC9p2(), 0.0) + diff * c.getC9p1()); - if (i == size - 1) { - vo.setC9p1(vo.getC9p1() / c.getTotalNumber()); - vo.setC9p2(vo.getC9p2() / c.getTotalNumber()); - } - } + inputItems.sort( + Comparator.comparing(x -> ObjectUtils.defaultIfNull(x.getTime(), LocalTime.MIN))); + inputItems.forEach(x -> x.calculate()); - vo.setDdp1( - ObjectUtils.defaultIfNull(vo.getDdp1(), 0.0) - + diff * ObjectUtils.defaultIfNull(c.getDdp1(), 0.0)); - if (i == size - 1) { - vo.setDdp1(vo.getDdp1() / c.getTotalNumber()); - } - vo.setDdp2( - ObjectUtils.defaultIfNull(vo.getDdp2(), 0.0) - + diff * ObjectUtils.defaultIfNull(c.getDdp2(), 0.0)); - if (i == size - 1) { - vo.setDdp2(vo.getDdp2() / c.getTotalNumber()); - } - vo.setDdp3( - ObjectUtils.defaultIfNull(vo.getDdp3(), 0.0) - + diff * ObjectUtils.defaultIfNull(c.getDdp3(), 0.0)); - if (i == size - 1) { - vo.setDdp3(vo.getDdp3() / c.getTotalNumber()); - } - vo.setDdp4( - ObjectUtils.defaultIfNull(vo.getDdp4(), 0.0) - + diff * ObjectUtils.defaultIfNull(c.getDdp4(), 0.0)); - if (i == size - 1) { - vo.setDdp4(vo.getDdp4() / c.getTotalNumber()); - } - vo.setDdp5( - ObjectUtils.defaultIfNull(vo.getDdp5(), 0.0) - + diff * ObjectUtils.defaultIfNull(c.getDdp5(), 0.0)); - if (i == size - 1) { - vo.setDdp5(vo.getDdp5() / c.getTotalNumber()); - } + for (int i = 0; i < inputItems.size(); i++) { - vo.setSysDdp1( - ObjectUtils.defaultIfNull(vo.getSysDdp1(), 0.0) - + diff * ObjectUtils.defaultIfNull(c.getSysDdp1(), 0.0)); - if (i == size - 1) { - vo.setSysDdp1(vo.getSysDdp1() / c.getTotalNumber()); - } - vo.setSysDdp2( - ObjectUtils.defaultIfNull(vo.getSysDdp2(), 0.0) - + diff * ObjectUtils.defaultIfNull(c.getSysDdp2(), 0.0)); - if (i == size - 1) { - vo.setSysDdp2(vo.getSysDdp2() / c.getTotalNumber()); - } - vo.setSysDdp3( - ObjectUtils.defaultIfNull(vo.getSysDdp3(), 0.0) - + diff * ObjectUtils.defaultIfNull(c.getSysDdp3(), 0.0)); - if (i == size - 1) { - vo.setSysDdp3(vo.getSysDdp3() / c.getTotalNumber()); - } - vo.setSysDdp4( - ObjectUtils.defaultIfNull(vo.getSysDdp4(), 0.0) - + diff * ObjectUtils.defaultIfNull(c.getSysDdp4(), 0.0)); - if (i == size - 1) { - vo.setSysDdp4(vo.getSysDdp4() / c.getTotalNumber()); - } - vo.setSysDdp5( - ObjectUtils.defaultIfNull(vo.getSysDdp5(), 0.0) - + diff * ObjectUtils.defaultIfNull(c.getSysDdp5(), 0.0)); - if (i == size - 1) { - vo.setSysDdp5(vo.getSysDdp5() / c.getTotalNumber()); - } - - vo.setAvgDdp1( - ObjectUtils.defaultIfNull(vo.getAvgDdp1(), 0.0) - + diff * ObjectUtils.defaultIfNull(c.getAvgDdp1(), 0.0)); - if (i == size - 1) { - vo.setAvgDdp1(vo.getAvgDdp1() / c.getTotalNumber()); - } - vo.setAvgDdp2( - ObjectUtils.defaultIfNull(vo.getAvgDdp2(), 0.0) - + diff * ObjectUtils.defaultIfNull(c.getAvgDdp2(), 0.0)); - if (i == size - 1) { - vo.setAvgDdp2(vo.getAvgDdp2() / c.getTotalNumber()); - } - vo.setAvgDdp3( - ObjectUtils.defaultIfNull(vo.getAvgDdp3(), 0.0) - + diff * ObjectUtils.defaultIfNull(c.getAvgDdp3(), 0.0)); - if (i == size - 1) { - vo.setAvgDdp3(vo.getAvgDdp3() / c.getTotalNumber()); - } - vo.setAvgDdp4( - ObjectUtils.defaultIfNull(vo.getAvgDdp4(), 0.0) - + diff * ObjectUtils.defaultIfNull(c.getAvgDdp4(), 0.0)); - if (i == size - 1) { - vo.setAvgDdp4(vo.getAvgDdp4() / c.getTotalNumber()); - } - vo.setAvgDdp5( - ObjectUtils.defaultIfNull(vo.getAvgDdp5(), 0.0) - + diff * ObjectUtils.defaultIfNull(c.getAvgDdp5(), 0.0)); - if (i == size - 1) { - vo.setAvgDdp5(vo.getAvgDdp5() / c.getTotalNumber()); - } + List current = inputItems.subList(0, i + 1); + rollingAvgItems.add(rollingAvg(current)); + } } - return vo; - } + private CoalWashingDailyAnalysisItemVo rollingAvg( + List current) { + + CoalWashingDailyAnalysisItemVo vo = new CoalWashingDailyAnalysisItemVo(); + int size = current.size(); + vo.setTime(current.get(size - 1).getTime()); + vo.setTotalNumber(current.get(size - 1).getTotalNumber()); + + vo.setC0p0(current.get(size - 1).getC0p0()); + + vo.setC1p0(current.get(size - 1).getC1p0()); + + vo.setC2p0(current.get(size - 1).getC2p0()); + + vo.setC3p0(current.get(size - 1).getC3p0()); + + vo.setC4p0(current.get(size - 1).getC4p0()); + + vo.setC5p0(current.get(size - 1).getC5p0()); + + vo.setC6p0(current.get(size - 1).getC6p0()); + + vo.setC7p0(current.get(size - 1).getC7p0()); + + vo.setC8p0(current.get(size - 1).getC8p0()); + + vo.setC9p0(current.get(size - 1).getC9p0()); + + for (int i = 0; i < size; i++) { + var c = current.get(i); + var p = i == 0 ? c.withTotalNumber(initTotalNumber) : current.get(i - 1); + double diff = c.getTotalNumber() - p.getTotalNumber(); + if (vo.getC0p0() != null && vo.getC0p0() > 0) { + vo.setC0p1(ObjectUtils.defaultIfNull(vo.getC0p1(), 0.0) + diff * c.getC0p1()); + vo.setC0p2(ObjectUtils.defaultIfNull(vo.getC0p2(), 0.0) + diff * c.getC0p1()); + if (i == size - 1) { + vo.setC0p1(vo.getC0p1() / c.getTotalNumber()); + vo.setC0p2(vo.getC0p2() / c.getTotalNumber()); + } + } + if (vo.getC1p0() != null && vo.getC1p0() > 0) { + vo.setC1p1(ObjectUtils.defaultIfNull(vo.getC1p1(), 0.0) + diff * c.getC1p1()); + vo.setC1p2(ObjectUtils.defaultIfNull(vo.getC1p2(), 0.0) + diff * c.getC1p1()); + if (i == size - 1) { + vo.setC1p1(vo.getC1p1() / c.getTotalNumber()); + vo.setC1p2(vo.getC1p2() / c.getTotalNumber()); + } + } + if (vo.getC2p0() != null && vo.getC2p0() > 0) { + vo.setC2p1(ObjectUtils.defaultIfNull(vo.getC2p1(), 0.0) + diff * c.getC2p1()); + vo.setC2p2(ObjectUtils.defaultIfNull(vo.getC2p2(), 0.0) + diff * c.getC2p1()); + if (i == size - 1) { + vo.setC2p1(vo.getC2p1() / c.getTotalNumber()); + vo.setC2p2(vo.getC2p2() / c.getTotalNumber()); + } + } + if (vo.getC3p0() != null && vo.getC3p0() > 0) { + vo.setC3p1(ObjectUtils.defaultIfNull(vo.getC3p1(), 0.0) + diff * c.getC3p1()); + vo.setC3p2(ObjectUtils.defaultIfNull(vo.getC3p2(), 0.0) + diff * c.getC3p1()); + if (i == size - 1) { + vo.setC3p1(vo.getC3p1() / c.getTotalNumber()); + vo.setC3p2(vo.getC3p2() / c.getTotalNumber()); + } + } + if (vo.getC4p0() != null && vo.getC4p0() > 0) { + vo.setC4p1(ObjectUtils.defaultIfNull(vo.getC4p1(), 0.0) + diff * c.getC4p1()); + vo.setC4p2(ObjectUtils.defaultIfNull(vo.getC4p2(), 0.0) + diff * c.getC4p1()); + if (i == size - 1) { + vo.setC4p1(vo.getC4p1() / c.getTotalNumber()); + vo.setC4p2(vo.getC4p2() / c.getTotalNumber()); + } + } + if (vo.getC5p0() != null && vo.getC5p0() > 0) { + vo.setC5p1(ObjectUtils.defaultIfNull(vo.getC5p1(), 0.0) + diff * c.getC5p1()); + vo.setC5p2(ObjectUtils.defaultIfNull(vo.getC5p2(), 0.0) + diff * c.getC5p1()); + if (i == size - 1) { + vo.setC5p1(vo.getC5p1() / c.getTotalNumber()); + vo.setC5p2(vo.getC5p2() / c.getTotalNumber()); + } + } + if (vo.getC6p0() != null && vo.getC6p0() > 0) { + vo.setC6p1(ObjectUtils.defaultIfNull(vo.getC6p1(), 0.0) + diff * c.getC6p1()); + vo.setC6p2(ObjectUtils.defaultIfNull(vo.getC6p2(), 0.0) + diff * c.getC6p1()); + if (i == size - 1) { + vo.setC6p1(vo.getC6p1() / c.getTotalNumber()); + vo.setC6p2(vo.getC6p2() / c.getTotalNumber()); + } + } + if (vo.getC7p0() != null && vo.getC7p0() > 0) { + vo.setC7p1(ObjectUtils.defaultIfNull(vo.getC7p1(), 0.0) + diff * c.getC7p1()); + vo.setC7p2(ObjectUtils.defaultIfNull(vo.getC7p2(), 0.0) + diff * c.getC7p1()); + if (i == size - 1) { + vo.setC7p1(vo.getC7p1() / c.getTotalNumber()); + vo.setC7p2(vo.getC7p2() / c.getTotalNumber()); + } + } + if (vo.getC8p0() != null && vo.getC8p0() > 0) { + vo.setC8p1(ObjectUtils.defaultIfNull(vo.getC8p1(), 0.0) + diff * c.getC8p1()); + vo.setC8p2(ObjectUtils.defaultIfNull(vo.getC8p2(), 0.0) + diff * c.getC8p1()); + if (i == size - 1) { + vo.setC8p1(vo.getC8p1() / c.getTotalNumber()); + vo.setC8p2(vo.getC8p2() / c.getTotalNumber()); + } + } + if (vo.getC9p0() != null && vo.getC9p0() > 0) { + vo.setC9p1(ObjectUtils.defaultIfNull(vo.getC9p1(), 0.0) + diff * c.getC9p1()); + vo.setC9p2(ObjectUtils.defaultIfNull(vo.getC9p2(), 0.0) + diff * c.getC9p1()); + if (i == size - 1) { + vo.setC9p1(vo.getC9p1() / c.getTotalNumber()); + vo.setC9p2(vo.getC9p2() / c.getTotalNumber()); + } + } + + vo.setDdp1( + ObjectUtils.defaultIfNull(vo.getDdp1(), 0.0) + + diff * ObjectUtils.defaultIfNull(c.getDdp1(), 0.0)); + if (i == size - 1) { + vo.setDdp1(vo.getDdp1() / c.getTotalNumber()); + } + vo.setDdp2( + ObjectUtils.defaultIfNull(vo.getDdp2(), 0.0) + + diff * ObjectUtils.defaultIfNull(c.getDdp2(), 0.0)); + if (i == size - 1) { + vo.setDdp2(vo.getDdp2() / c.getTotalNumber()); + } + vo.setDdp3( + ObjectUtils.defaultIfNull(vo.getDdp3(), 0.0) + + diff * ObjectUtils.defaultIfNull(c.getDdp3(), 0.0)); + if (i == size - 1) { + vo.setDdp3(vo.getDdp3() / c.getTotalNumber()); + } + vo.setDdp4( + ObjectUtils.defaultIfNull(vo.getDdp4(), 0.0) + + diff * ObjectUtils.defaultIfNull(c.getDdp4(), 0.0)); + if (i == size - 1) { + vo.setDdp4(vo.getDdp4() / c.getTotalNumber()); + } + vo.setDdp5( + ObjectUtils.defaultIfNull(vo.getDdp5(), 0.0) + + diff * ObjectUtils.defaultIfNull(c.getDdp5(), 0.0)); + if (i == size - 1) { + vo.setDdp5(vo.getDdp5() / c.getTotalNumber()); + } + + vo.setSysDdp1( + ObjectUtils.defaultIfNull(vo.getSysDdp1(), 0.0) + + diff * ObjectUtils.defaultIfNull(c.getSysDdp1(), 0.0)); + if (i == size - 1) { + vo.setSysDdp1(vo.getSysDdp1() / c.getTotalNumber()); + } + vo.setSysDdp2( + ObjectUtils.defaultIfNull(vo.getSysDdp2(), 0.0) + + diff * ObjectUtils.defaultIfNull(c.getSysDdp2(), 0.0)); + if (i == size - 1) { + vo.setSysDdp2(vo.getSysDdp2() / c.getTotalNumber()); + } + vo.setSysDdp3( + ObjectUtils.defaultIfNull(vo.getSysDdp3(), 0.0) + + diff * ObjectUtils.defaultIfNull(c.getSysDdp3(), 0.0)); + if (i == size - 1) { + vo.setSysDdp3(vo.getSysDdp3() / c.getTotalNumber()); + } + vo.setSysDdp4( + ObjectUtils.defaultIfNull(vo.getSysDdp4(), 0.0) + + diff * ObjectUtils.defaultIfNull(c.getSysDdp4(), 0.0)); + if (i == size - 1) { + vo.setSysDdp4(vo.getSysDdp4() / c.getTotalNumber()); + } + vo.setSysDdp5( + ObjectUtils.defaultIfNull(vo.getSysDdp5(), 0.0) + + diff * ObjectUtils.defaultIfNull(c.getSysDdp5(), 0.0)); + if (i == size - 1) { + vo.setSysDdp5(vo.getSysDdp5() / c.getTotalNumber()); + } + + vo.setAvgDdp1( + ObjectUtils.defaultIfNull(vo.getAvgDdp1(), 0.0) + + diff * ObjectUtils.defaultIfNull(c.getAvgDdp1(), 0.0)); + if (i == size - 1) { + vo.setAvgDdp1(vo.getAvgDdp1() / c.getTotalNumber()); + } + vo.setAvgDdp2( + ObjectUtils.defaultIfNull(vo.getAvgDdp2(), 0.0) + + diff * ObjectUtils.defaultIfNull(c.getAvgDdp2(), 0.0)); + if (i == size - 1) { + vo.setAvgDdp2(vo.getAvgDdp2() / c.getTotalNumber()); + } + vo.setAvgDdp3( + ObjectUtils.defaultIfNull(vo.getAvgDdp3(), 0.0) + + diff * ObjectUtils.defaultIfNull(c.getAvgDdp3(), 0.0)); + if (i == size - 1) { + vo.setAvgDdp3(vo.getAvgDdp3() / c.getTotalNumber()); + } + vo.setAvgDdp4( + ObjectUtils.defaultIfNull(vo.getAvgDdp4(), 0.0) + + diff * ObjectUtils.defaultIfNull(c.getAvgDdp4(), 0.0)); + if (i == size - 1) { + vo.setAvgDdp4(vo.getAvgDdp4() / c.getTotalNumber()); + } + vo.setAvgDdp5( + ObjectUtils.defaultIfNull(vo.getAvgDdp5(), 0.0) + + diff * ObjectUtils.defaultIfNull(c.getAvgDdp5(), 0.0)); + if (i == size - 1) { + vo.setAvgDdp5(vo.getAvgDdp5() / c.getTotalNumber()); + } + } + + return vo; + } } diff --git a/src/main/java/cn/lihongjie/coal/coalWashingDailyAnalysis/entity/CoalWashingDailyAnalysisItemVo.java b/src/main/java/cn/lihongjie/coal/coalWashingDailyAnalysis/entity/CoalWashingDailyAnalysisItemVo.java index 78650ea2..417e7e59 100644 --- a/src/main/java/cn/lihongjie/coal/coalWashingDailyAnalysis/entity/CoalWashingDailyAnalysisItemVo.java +++ b/src/main/java/cn/lihongjie/coal/coalWashingDailyAnalysis/entity/CoalWashingDailyAnalysisItemVo.java @@ -1,279 +1,284 @@ package cn.lihongjie.coal.coalWashingDailyAnalysis.entity; import cn.lihongjie.coal.exception.BizException; + import io.vavr.collection.Stream; + import jakarta.persistence.Embeddable; -import java.time.LocalTime; -import java.util.Objects; + import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import lombok.With; + import org.hibernate.annotations.Comment; +import java.time.LocalTime; +import java.util.Objects; + @Data @Embeddable @NoArgsConstructor @AllArgsConstructor public class CoalWashingDailyAnalysisItemVo { - @Comment("时间") - private LocalTime time; + @Comment("时间") + private LocalTime time; - @Comment("产量") - @With - private Double totalNumber; + @Comment("产量") + @With + private Double totalNumber; - @Comment("成分0 比例") - private Double c0p0; + @Comment("成分0 比例") + private Double c0p0; - @Comment("成分0 灰") - private Double c0p1; + @Comment("成分0 灰") + private Double c0p1; - @Comment("成分0 硫") - private Double c0p2; + @Comment("成分0 硫") + private Double c0p2; - @Comment("成分1 比例") - private Double c1p0; + @Comment("成分1 比例") + private Double c1p0; - @Comment("成分1 灰") - private Double c1p1; + @Comment("成分1 灰") + private Double c1p1; - @Comment("成分1 硫") - private Double c1p2; + @Comment("成分1 硫") + private Double c1p2; - @Comment("成分2 比例") - private Double c2p0; + @Comment("成分2 比例") + private Double c2p0; - @Comment("成分2 灰") - private Double c2p1; + @Comment("成分2 灰") + private Double c2p1; - @Comment("成分2 硫") - private Double c2p2; + @Comment("成分2 硫") + private Double c2p2; - @Comment("成分3 比例") - private Double c3p0; + @Comment("成分3 比例") + private Double c3p0; - @Comment("成分3 灰") - private Double c3p1; + @Comment("成分3 灰") + private Double c3p1; - @Comment("成分3 硫") - private Double c3p2; + @Comment("成分3 硫") + private Double c3p2; - @Comment("成分4 比例") - private Double c4p0; + @Comment("成分4 比例") + private Double c4p0; - @Comment("成分4 灰") - private Double c4p1; + @Comment("成分4 灰") + private Double c4p1; - @Comment("成分4 硫") - private Double c4p2; + @Comment("成分4 硫") + private Double c4p2; - @Comment("成分5 比例") - private Double c5p0; + @Comment("成分5 比例") + private Double c5p0; - @Comment("成分5 灰") - private Double c5p1; + @Comment("成分5 灰") + private Double c5p1; - @Comment("成分5 硫") - private Double c5p2; + @Comment("成分5 硫") + private Double c5p2; - @Comment("成分6 比例") - private Double c6p0; + @Comment("成分6 比例") + private Double c6p0; - @Comment("成分6 灰") - private Double c6p1; + @Comment("成分6 灰") + private Double c6p1; - @Comment("成分6 硫") - private Double c6p2; + @Comment("成分6 硫") + private Double c6p2; - @Comment("成分7 比例") - private Double c7p0; + @Comment("成分7 比例") + private Double c7p0; - @Comment("成分7 灰") - private Double c7p1; + @Comment("成分7 灰") + private Double c7p1; - @Comment("成分7 硫") - private Double c7p2; + @Comment("成分7 硫") + private Double c7p2; - @Comment("成分8 比例") - private Double c8p0; + @Comment("成分8 比例") + private Double c8p0; - @Comment("成分8 灰") - private Double c8p1; + @Comment("成分8 灰") + private Double c8p1; - @Comment("成分8 硫") - private Double c8p2; + @Comment("成分8 硫") + private Double c8p2; - @Comment("成分9 比例") - private Double c9p0; + @Comment("成分9 比例") + private Double c9p0; - @Comment("成分9 灰") - private Double c9p1; + @Comment("成分9 灰") + private Double c9p1; - @Comment("成分9 硫") - private Double c9p2; + @Comment("成分9 硫") + private Double c9p2; - @Comment("用户输入 大堆 灰") - private Double ddp1; + @Comment("用户输入 大堆 灰") + private Double ddp1; - @Comment("用户输入 大堆 硫") - private Double ddp2; + @Comment("用户输入 大堆 硫") + private Double ddp2; - @Comment("用户输入 大堆 挥发") - private Double ddp3; + @Comment("用户输入 大堆 挥发") + private Double ddp3; - @Comment("用户输入 大堆 粘结") - private Double ddp4; + @Comment("用户输入 大堆 粘结") + private Double ddp4; - @Comment("用户输入 大堆 备用") - private Double ddp5; + @Comment("用户输入 大堆 备用") + private Double ddp5; - @Comment("用户输入 翻大堆 灰") - private Double fddp1; + @Comment("用户输入 翻大堆 灰") + private Double fddp1; - @Comment("用户输入 翻大堆 硫") - private Double fddp2; + @Comment("用户输入 翻大堆 硫") + private Double fddp2; - @Comment("用户输入 翻大堆 挥发") - private Double fddp3; + @Comment("用户输入 翻大堆 挥发") + private Double fddp3; - @Comment("用户输入 翻大堆 粘结") - private Double fddp4; + @Comment("用户输入 翻大堆 粘结") + private Double fddp4; - @Comment("用户输入 翻大堆 备用") - private Double fddp5; + @Comment("用户输入 翻大堆 备用") + private Double fddp5; - @Comment("系统计算 大堆 灰") - private Double sysDdp1; + @Comment("系统计算 大堆 灰") + private Double sysDdp1; - @Comment("系统计算 大堆 硫") - private Double sysDdp2; + @Comment("系统计算 大堆 硫") + private Double sysDdp2; - @Comment("系统计算 大堆 挥发") - private Double sysDdp3; + @Comment("系统计算 大堆 挥发") + private Double sysDdp3; - @Comment("系统计算 大堆 粘结") - private Double sysDdp4; + @Comment("系统计算 大堆 粘结") + private Double sysDdp4; - @Comment("系统计算 大堆 备用") - private Double sysDdp5; + @Comment("系统计算 大堆 备用") + private Double sysDdp5; - @Comment("用户输入与系统计算的平均值 大堆 灰") - private Double avgDdp1; + @Comment("用户输入与系统计算的平均值 大堆 灰") + private Double avgDdp1; - @Comment("用户输入与系统计算的平均值 大堆 硫") - private Double avgDdp2; + @Comment("用户输入与系统计算的平均值 大堆 硫") + private Double avgDdp2; - @Comment("用户输入与系统计算的平均值 大堆 挥发") - private Double avgDdp3; + @Comment("用户输入与系统计算的平均值 大堆 挥发") + private Double avgDdp3; - @Comment("用户输入与系统计算的平均值 大堆 粘结") - private Double avgDdp4; + @Comment("用户输入与系统计算的平均值 大堆 粘结") + private Double avgDdp4; - @Comment("用户输入与系统计算的平均值 大堆 备用") - private Double avgDdp5; + @Comment("用户输入与系统计算的平均值 大堆 备用") + private Double avgDdp5; - public void calculate() { + public void calculate() { - if (Stream.of(c0p0, c1p0, c2p0, c3p0, c4p0, c5p0, c6p0, c7p0, c8p0, c9p0) - .filter(Objects::nonNull) - .sum() - .doubleValue() - != 100) throw new BizException("比例相加应该等于100!"); + if (Stream.of(c0p0, c1p0, c2p0, c3p0, c4p0, c5p0, c6p0, c7p0, c8p0, c9p0) + .filter(Objects::nonNull) + .sum() + .doubleValue() + != 100) throw new BizException("比例相加应该等于100!"); - sysDdp1 = 0.0; - sysDdp2 = 0.0; - int count1 = 0; - int count2 = 0; - if (c0p0 != null && c0p1 != null) { - sysDdp1 += c0p1 * c0p0 / 100.00; - count1++; + sysDdp1 = 0.0; + sysDdp2 = 0.0; + int count1 = 0; + int count2 = 0; + if (c0p0 != null && c0p1 != null) { + sysDdp1 += c0p1 * c0p0 / 100.00; + count1++; + } + if (c0p0 != null && c0p2 != null) { + sysDdp2 += c0p2 * c0p0 / 100.00; + count2++; + } + if (c1p0 != null && c1p1 != null) { + sysDdp1 += c1p1 * c1p0 / 100.00; + count1++; + } + if (c1p0 != null && c1p2 != null) { + sysDdp2 += c1p2 * c1p0 / 100.00; + count2++; + } + if (c2p0 != null && c2p1 != null) { + sysDdp1 += c2p1 * c2p0 / 100.00; + count1++; + } + if (c2p0 != null && c2p2 != null) { + sysDdp2 += c2p2 * c2p0 / 100.00; + count2++; + } + if (c3p0 != null && c3p1 != null) { + sysDdp1 += c3p1 * c3p0 / 100.00; + count1++; + } + if (c3p0 != null && c3p2 != null) { + sysDdp2 += c3p2 * c3p0 / 100.00; + count2++; + } + if (c4p0 != null && c4p1 != null) { + sysDdp1 += c4p1 * c4p0 / 100.00; + count1++; + } + if (c4p0 != null && c4p2 != null) { + sysDdp2 += c4p2 * c4p0 / 100.00; + count2++; + } + if (c5p0 != null && c5p1 != null) { + sysDdp1 += c5p1 * c5p0 / 100.00; + count1++; + } + if (c5p0 != null && c5p2 != null) { + sysDdp2 += c5p2 * c5p0 / 100.00; + count2++; + } + if (c6p0 != null && c6p1 != null) { + sysDdp1 += c6p1 * c6p0 / 100.00; + count1++; + } + if (c6p0 != null && c6p2 != null) { + sysDdp2 += c6p2 * c6p0 / 100.00; + count2++; + } + if (c7p0 != null && c7p1 != null) { + sysDdp1 += c7p1 * c7p0 / 100.00; + count1++; + } + if (c7p0 != null && c7p2 != null) { + sysDdp2 += c7p2 * c7p0 / 100.00; + count2++; + } + if (c8p0 != null && c8p1 != null) { + sysDdp1 += c8p1 * c8p0 / 100.00; + count1++; + } + if (c8p0 != null && c8p2 != null) { + sysDdp2 += c8p2 * c8p0 / 100.00; + count2++; + } + if (c9p0 != null && c9p1 != null) { + sysDdp1 += c9p1 * c9p0 / 100.00; + count1++; + } + if (c9p0 != null && c9p2 != null) { + sysDdp2 += c9p2 * c9p0 / 100.00; + count2++; + } + + if (count1 == 0) sysDdp1 = null; + if (count2 == 0) sysDdp2 = null; + + if (ddp1 != null && sysDdp1 != null) avgDdp1 = (ddp1 + sysDdp1) / 2.0; + if (ddp2 != null && sysDdp2 != null) avgDdp2 = (ddp2 + sysDdp2) / 2.0; + if (ddp3 != null && sysDdp3 != null) avgDdp3 = (ddp3 + sysDdp3) / 2.0; + if (ddp4 != null && sysDdp4 != null) avgDdp4 = (ddp4 + sysDdp4) / 2.0; + if (ddp5 != null && sysDdp5 != null) avgDdp5 = (ddp5 + sysDdp5) / 2.0; } - if (c0p0 != null && c0p2 != null) { - sysDdp2 += c0p2 * c0p0 / 100.00; - count2++; - } - if (c1p0 != null && c1p1 != null) { - sysDdp1 += c1p1 * c1p0 / 100.00; - count1++; - } - if (c1p0 != null && c1p2 != null) { - sysDdp2 += c1p2 * c1p0 / 100.00; - count2++; - } - if (c2p0 != null && c2p1 != null) { - sysDdp1 += c2p1 * c2p0 / 100.00; - count1++; - } - if (c2p0 != null && c2p2 != null) { - sysDdp2 += c2p2 * c2p0 / 100.00; - count2++; - } - if (c3p0 != null && c3p1 != null) { - sysDdp1 += c3p1 * c3p0 / 100.00; - count1++; - } - if (c3p0 != null && c3p2 != null) { - sysDdp2 += c3p2 * c3p0 / 100.00; - count2++; - } - if (c4p0 != null && c4p1 != null) { - sysDdp1 += c4p1 * c4p0 / 100.00; - count1++; - } - if (c4p0 != null && c4p2 != null) { - sysDdp2 += c4p2 * c4p0 / 100.00; - count2++; - } - if (c5p0 != null && c5p1 != null) { - sysDdp1 += c5p1 * c5p0 / 100.00; - count1++; - } - if (c5p0 != null && c5p2 != null) { - sysDdp2 += c5p2 * c5p0 / 100.00; - count2++; - } - if (c6p0 != null && c6p1 != null) { - sysDdp1 += c6p1 * c6p0 / 100.00; - count1++; - } - if (c6p0 != null && c6p2 != null) { - sysDdp2 += c6p2 * c6p0 / 100.00; - count2++; - } - if (c7p0 != null && c7p1 != null) { - sysDdp1 += c7p1 * c7p0 / 100.00; - count1++; - } - if (c7p0 != null && c7p2 != null) { - sysDdp2 += c7p2 * c7p0 / 100.00; - count2++; - } - if (c8p0 != null && c8p1 != null) { - sysDdp1 += c8p1 * c8p0 / 100.00; - count1++; - } - if (c8p0 != null && c8p2 != null) { - sysDdp2 += c8p2 * c8p0 / 100.00; - count2++; - } - if (c9p0 != null && c9p1 != null) { - sysDdp1 += c9p1 * c9p0 / 100.00; - count1++; - } - if (c9p0 != null && c9p2 != null) { - sysDdp2 += c9p2 * c9p0 / 100.00; - count2++; - } - - if (count1 == 0) sysDdp1 = null; - if (count2 == 0) sysDdp2 = null; - - if (ddp1 != null && sysDdp1 != null) avgDdp1 = (ddp1 + sysDdp1) / 2.0; - if (ddp2 != null && sysDdp2 != null) avgDdp2 = (ddp2 + sysDdp2) / 2.0; - if (ddp3 != null && sysDdp3 != null) avgDdp3 = (ddp3 + sysDdp3) / 2.0; - if (ddp4 != null && sysDdp4 != null) avgDdp4 = (ddp4 + sysDdp4) / 2.0; - if (ddp5 != null && sysDdp5 != null) avgDdp5 = (ddp5 + sysDdp5) / 2.0; - } } diff --git a/src/main/java/cn/lihongjie/coal/coalWashingDailyAnalysis/mapper/CoalWashingDailyAnalysisMapper.java b/src/main/java/cn/lihongjie/coal/coalWashingDailyAnalysis/mapper/CoalWashingDailyAnalysisMapper.java index cc6a058b..95044274 100644 --- a/src/main/java/cn/lihongjie/coal/coalWashingDailyAnalysis/mapper/CoalWashingDailyAnalysisMapper.java +++ b/src/main/java/cn/lihongjie/coal/coalWashingDailyAnalysis/mapper/CoalWashingDailyAnalysisMapper.java @@ -6,17 +6,18 @@ import cn.lihongjie.coal.coalWashingDailyAnalysis.dto.CoalWashingDailyAnalysisDt import cn.lihongjie.coal.coalWashingDailyAnalysis.dto.CreateCoalWashingDailyAnalysisDto; import cn.lihongjie.coal.coalWashingDailyAnalysis.dto.UpdateCoalWashingDailyAnalysisDto; import cn.lihongjie.coal.coalWashingDailyAnalysis.entity.CoalWashingDailyAnalysisEntity; + import org.mapstruct.Mapper; import org.mapstruct.MappingConstants; import org.mapstruct.control.DeepClone; @Mapper( - componentModel = MappingConstants.ComponentModel.SPRING, - uses = {CommonMapper.class}, - mappingControl = DeepClone.class) + componentModel = MappingConstants.ComponentModel.SPRING, + uses = {CommonMapper.class}, + mappingControl = DeepClone.class) public interface CoalWashingDailyAnalysisMapper - extends BaseMapper< - CoalWashingDailyAnalysisEntity, - CoalWashingDailyAnalysisDto, - CreateCoalWashingDailyAnalysisDto, - UpdateCoalWashingDailyAnalysisDto> {} + extends BaseMapper< + CoalWashingDailyAnalysisEntity, + CoalWashingDailyAnalysisDto, + CreateCoalWashingDailyAnalysisDto, + UpdateCoalWashingDailyAnalysisDto> {} diff --git a/src/main/java/cn/lihongjie/coal/coalWashingDailyAnalysis/mapper/RoundMapper.java b/src/main/java/cn/lihongjie/coal/coalWashingDailyAnalysis/mapper/RoundMapper.java index 6240f011..3a8ae367 100644 --- a/src/main/java/cn/lihongjie/coal/coalWashingDailyAnalysis/mapper/RoundMapper.java +++ b/src/main/java/cn/lihongjie/coal/coalWashingDailyAnalysis/mapper/RoundMapper.java @@ -4,30 +4,32 @@ import cn.lihongjie.coal.base.mapper.CommonMapper; import cn.lihongjie.coal.coalBlend.dto.CoalBlendDto; import cn.lihongjie.coal.coalWashingDailyAnalysis.entity.CoalWashingDailyAnalysisEntity; import cn.lihongjie.coal.coalWashingDailyAnalysis.entity.CoalWashingDailyAnalysisItemVo; -import java.math.BigDecimal; -import java.math.RoundingMode; + import org.mapstruct.Mapper; import org.mapstruct.MappingConstants; import org.mapstruct.control.DeepClone; +import java.math.BigDecimal; +import java.math.RoundingMode; + @Mapper( - componentModel = MappingConstants.ComponentModel.SPRING, - uses = {CommonMapper.class}, - mappingControl = DeepClone.class) + componentModel = MappingConstants.ComponentModel.SPRING, + uses = {CommonMapper.class}, + mappingControl = DeepClone.class) public interface RoundMapper { - CoalWashingDailyAnalysisEntity round(CoalWashingDailyAnalysisEntity entity); + CoalWashingDailyAnalysisEntity round(CoalWashingDailyAnalysisEntity entity); - CoalWashingDailyAnalysisItemVo round(CoalWashingDailyAnalysisItemVo entity); + CoalWashingDailyAnalysisItemVo round(CoalWashingDailyAnalysisItemVo entity); - CoalBlendDto round(CoalBlendDto entity); + CoalBlendDto round(CoalBlendDto entity); - default Double formatDouble(Double d) { + default Double formatDouble(Double d) { - if (d == null) { - return d; + if (d == null) { + return d; + } + + return new BigDecimal(d).setScale(2, RoundingMode.HALF_UP).doubleValue(); } - - return new BigDecimal(d).setScale(2, RoundingMode.HALF_UP).doubleValue(); - } } diff --git a/src/main/java/cn/lihongjie/coal/coalWashingDailyAnalysis/repository/CoalWashingDailyAnalysisRepository.java b/src/main/java/cn/lihongjie/coal/coalWashingDailyAnalysis/repository/CoalWashingDailyAnalysisRepository.java index a6514d65..9d8d06bc 100644 --- a/src/main/java/cn/lihongjie/coal/coalWashingDailyAnalysis/repository/CoalWashingDailyAnalysisRepository.java +++ b/src/main/java/cn/lihongjie/coal/coalWashingDailyAnalysis/repository/CoalWashingDailyAnalysisRepository.java @@ -2,8 +2,9 @@ package cn.lihongjie.coal.coalWashingDailyAnalysis.repository; import cn.lihongjie.coal.base.dao.BaseRepository; import cn.lihongjie.coal.coalWashingDailyAnalysis.entity.CoalWashingDailyAnalysisEntity; + import org.springframework.stereotype.Repository; @Repository public interface CoalWashingDailyAnalysisRepository - extends BaseRepository {} + extends BaseRepository {} diff --git a/src/main/java/cn/lihongjie/coal/coalWashingDailyAnalysis/service/CoalWashingDailyAnalysisService.java b/src/main/java/cn/lihongjie/coal/coalWashingDailyAnalysis/service/CoalWashingDailyAnalysisService.java index e80ef10f..3893c243 100644 --- a/src/main/java/cn/lihongjie/coal/coalWashingDailyAnalysis/service/CoalWashingDailyAnalysisService.java +++ b/src/main/java/cn/lihongjie/coal/coalWashingDailyAnalysis/service/CoalWashingDailyAnalysisService.java @@ -10,8 +10,11 @@ import cn.lihongjie.coal.coalWashingDailyAnalysis.entity.CoalWashingDailyAnalysi import cn.lihongjie.coal.coalWashingDailyAnalysis.mapper.CoalWashingDailyAnalysisMapper; import cn.lihongjie.coal.coalWashingDailyAnalysis.mapper.RoundMapper; import cn.lihongjie.coal.coalWashingDailyAnalysis.repository.CoalWashingDailyAnalysisRepository; + import jakarta.annotation.PostConstruct; + import lombok.extern.slf4j.Slf4j; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.convert.ConversionService; import org.springframework.data.domain.Page; @@ -22,64 +25,66 @@ import org.springframework.stereotype.Service; @Service @Slf4j public class CoalWashingDailyAnalysisService - extends BaseService { + extends BaseService { - @Autowired CoalWashingDailyAnalysisRepository repository; + @Autowired CoalWashingDailyAnalysisRepository repository; - @Autowired CoalWashingDailyAnalysisMapper mapper; + @Autowired CoalWashingDailyAnalysisMapper mapper; - @Autowired RoundMapper roundMapper; + @Autowired RoundMapper roundMapper; + @Autowired ConversionService conversionService; - @PostConstruct - public void init() {} + @PostConstruct + public void init() {} - public CoalWashingDailyAnalysisDto create(CreateCoalWashingDailyAnalysisDto request) { + public CoalWashingDailyAnalysisDto create(CreateCoalWashingDailyAnalysisDto request) { - CoalWashingDailyAnalysisEntity entity = mapper.toEntity(request); + CoalWashingDailyAnalysisEntity entity = mapper.toEntity(request); - this.repository.save(entity); - return getById(entity.getId()); - } + this.repository.save(entity); + return getById(entity.getId()); + } - public CoalWashingDailyAnalysisDto calculate(CreateCoalWashingDailyAnalysisDto request) { + public CoalWashingDailyAnalysisDto calculate(CreateCoalWashingDailyAnalysisDto request) { - CoalWashingDailyAnalysisEntity entity = mapper.toEntity(request); + CoalWashingDailyAnalysisEntity entity = mapper.toEntity(request); - entity.rollingAvg(); + entity.rollingAvg(); - return mapper.toDto(roundMapper.round(entity)); - } + return mapper.toDto(roundMapper.round(entity)); + } - public CoalWashingDailyAnalysisDto update(UpdateCoalWashingDailyAnalysisDto request) { - CoalWashingDailyAnalysisEntity entity = this.repository.get(request.getId()); - this.mapper.updateEntity(entity, request); + public CoalWashingDailyAnalysisDto update(UpdateCoalWashingDailyAnalysisDto request) { + CoalWashingDailyAnalysisEntity entity = this.repository.get(request.getId()); + this.mapper.updateEntity(entity, request); - this.repository.save(entity); + this.repository.save(entity); - return getById(entity.getId()); - } + return getById(entity.getId()); + } - public void delete(IdRequest request) { + public void delete(IdRequest request) { - this.repository.deleteAllById(request.getIds()); - } + this.repository.deleteAllById(request.getIds()); + } - public CoalWashingDailyAnalysisDto getById(String id) { + public CoalWashingDailyAnalysisDto getById(String id) { - CoalWashingDailyAnalysisEntity entity = repository.get(id); + CoalWashingDailyAnalysisEntity entity = repository.get(id); - return mapper.toDto(entity); - } + return mapper.toDto(entity); + } - @Autowired ConversionService conversionService; + public Page list(CommonQuery query) { - public Page list(CommonQuery query) { + Page page = + repository.findAll( + query.specification(conversionService), + PageRequest.of( + query.getPageNo(), + query.getPageSize(), + Sort.by(query.getOrders()))); - Page page = - repository.findAll( - query.specification(conversionService), - PageRequest.of(query.getPageNo(), query.getPageSize(), Sort.by(query.getOrders()))); - - return page.map(this.mapper::toDto); - } + return page.map(this.mapper::toDto); + } } diff --git a/src/main/java/cn/lihongjie/coal/common/CollectionUtils.java b/src/main/java/cn/lihongjie/coal/common/CollectionUtils.java index 27231d63..e0d8f6b8 100644 --- a/src/main/java/cn/lihongjie/coal/common/CollectionUtils.java +++ b/src/main/java/cn/lihongjie/coal/common/CollectionUtils.java @@ -1,99 +1,107 @@ package cn.lihongjie.coal.common; import io.vavr.Tuple2; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Map; + +import lombok.experimental.UtilityClass; + +import org.apache.commons.lang3.ObjectUtils; + +import java.util.*; import java.util.function.BiFunction; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.Stream; import java.util.stream.StreamSupport; -import lombok.experimental.UtilityClass; -import org.apache.commons.lang3.ObjectUtils; @UtilityClass public class CollectionUtils { - public static List map(Iterable data, Function fn) { + public static List map(Iterable data, Function fn) { - return StreamSupport.stream(data.spliterator(), false) - .map(fn) - .collect(java.util.stream.Collectors.toList()); - } - - public static List> innerHashJoin( - Iterable a, Iterable b, Function ak, Function bk) { - Map> aMap = newStream(a).collect(Collectors.groupingBy(ak)); - Map> bMap = newStream(b).collect(Collectors.groupingBy(bk)); - return aMap.keySet().stream() - .flatMap( - k -> - aMap.getOrDefault(k, new ArrayList<>()).stream() - .flatMap( - av -> - bMap.getOrDefault(k, new ArrayList<>()).stream() - .map(bv -> new Tuple2<>(av, bv)))) - .collect(java.util.stream.Collectors.toList()); - } - - public static List> innerNestJoin( - Iterable a, Iterable b, BiFunction test) { - a = ObjectUtils.defaultIfNull(a, new ArrayList<>()); - b = ObjectUtils.defaultIfNull(b, new ArrayList<>()); - - List> ans = new ArrayList<>(); - - for (A a1 : a) { - for (B b1 : b) { - if (test.apply(a1, b1)) { - ans.add(new Tuple2<>(a1, b1)); - } - } + return StreamSupport.stream(data.spliterator(), false) + .map(fn) + .collect(java.util.stream.Collectors.toList()); } - return ans; - } - public static List> leftHashJoin( - Iterable a, Iterable b, Function ak, Function bk) { - Map> aMap = newStream(a).collect(Collectors.groupingBy(ak)); - Map> bMap = newStream(b).collect(Collectors.groupingBy(bk)); - return aMap.keySet().stream() - .flatMap( - k -> - aMap.getOrDefault(k, new ArrayList<>()).stream() - .flatMap( - av -> - bMap.getOrDefault(k, new ArrayList<>(Arrays.asList((B) null))).stream() - .map(bv -> new Tuple2<>(av, bv)))) - .collect(java.util.stream.Collectors.toList()); - } - - public static List> leftNestJoin( - Iterable a, Iterable b, BiFunction test) { - a = ObjectUtils.defaultIfNull(a, new ArrayList<>()); - b = ObjectUtils.defaultIfNull(b, new ArrayList<>()); - - List> ans = new ArrayList<>(); - - for (A a1 : a) { - boolean find = false; - for (B b1 : b) { - if (test.apply(a1, b1)) { - ans.add(new Tuple2<>(a1, b1)); - find = true; - } - } - if (!find) { - ans.add(new Tuple2<>(a1, null)); - } + public static List> innerHashJoin( + Iterable a, Iterable b, Function ak, Function bk) { + Map> aMap = newStream(a).collect(Collectors.groupingBy(ak)); + Map> bMap = newStream(b).collect(Collectors.groupingBy(bk)); + return aMap.keySet().stream() + .flatMap( + k -> + aMap.getOrDefault(k, new ArrayList<>()).stream() + .flatMap( + av -> + bMap + .getOrDefault(k, new ArrayList<>()) + .stream() + .map(bv -> new Tuple2<>(av, bv)))) + .collect(java.util.stream.Collectors.toList()); } - return ans; - } - private static Stream newStream(Iterable a) { - return StreamSupport.stream( - a == null ? new ArrayList().spliterator() : a.spliterator(), false); - } + public static List> innerNestJoin( + Iterable a, Iterable b, BiFunction test) { + a = ObjectUtils.defaultIfNull(a, new ArrayList<>()); + b = ObjectUtils.defaultIfNull(b, new ArrayList<>()); + + List> ans = new ArrayList<>(); + + for (A a1 : a) { + for (B b1 : b) { + if (test.apply(a1, b1)) { + ans.add(new Tuple2<>(a1, b1)); + } + } + } + return ans; + } + + public static List> leftHashJoin( + Iterable a, Iterable b, Function ak, Function bk) { + Map> aMap = newStream(a).collect(Collectors.groupingBy(ak)); + Map> bMap = newStream(b).collect(Collectors.groupingBy(bk)); + return aMap.keySet().stream() + .flatMap( + k -> + aMap.getOrDefault(k, new ArrayList<>()).stream() + .flatMap( + av -> + bMap + .getOrDefault( + k, + new ArrayList<>( + Collections.singletonList( + (B) null))) + .stream() + .map(bv -> new Tuple2<>(av, bv)))) + .collect(java.util.stream.Collectors.toList()); + } + + public static List> leftNestJoin( + Iterable a, Iterable b, BiFunction test) { + a = ObjectUtils.defaultIfNull(a, new ArrayList<>()); + b = ObjectUtils.defaultIfNull(b, new ArrayList<>()); + + List> ans = new ArrayList<>(); + + for (A a1 : a) { + boolean find = false; + for (B b1 : b) { + if (test.apply(a1, b1)) { + ans.add(new Tuple2<>(a1, b1)); + find = true; + } + } + if (!find) { + ans.add(new Tuple2<>(a1, null)); + } + } + return ans; + } + + private static Stream newStream(Iterable a) { + return StreamSupport.stream( + a == null ? new ArrayList().spliterator() : a.spliterator(), false); + } } diff --git a/src/main/java/cn/lihongjie/coal/common/Constants.java b/src/main/java/cn/lihongjie/coal/common/Constants.java index 9ae246d8..812ec134 100644 --- a/src/main/java/cn/lihongjie/coal/common/Constants.java +++ b/src/main/java/cn/lihongjie/coal/common/Constants.java @@ -3,5 +3,5 @@ package cn.lihongjie.coal.common; import java.util.*; public class Constants { - public static String SYSCONFIG_ENABLE_CAPTCHA = "enable_captcha"; + public static String SYSCONFIG_ENABLE_CAPTCHA = "enable_captcha"; } diff --git a/src/main/java/cn/lihongjie/coal/common/Ctx.java b/src/main/java/cn/lihongjie/coal/common/Ctx.java index 5478de19..fa374598 100644 --- a/src/main/java/cn/lihongjie/coal/common/Ctx.java +++ b/src/main/java/cn/lihongjie/coal/common/Ctx.java @@ -2,40 +2,43 @@ package cn.lihongjie.coal.common; import cn.lihongjie.coal.session.SessionService; import cn.lihongjie.coal.user.entity.UserEntity; + import lombok.experimental.UtilityClass; + import org.springframework.security.core.context.SecurityContextHolder; @UtilityClass public class Ctx { - public static String getUserId() { - return getAuthentication().getUser().getId(); - } + public static String getUserId() { + return getAuthentication().getUser().getId(); + } - public static boolean isLoggedIn() { + public static boolean isLoggedIn() { - return getAuthentication() != null && getAuthentication().isAuthenticated(); - } + return getAuthentication() != null && getAuthentication().isAuthenticated(); + } - public static String getSessionId() { - return getAuthentication().getSessionId(); - } + public static String getSessionId() { + return getAuthentication().getSessionId(); + } - private static SessionService.MyAuthentication getAuthentication() { - return (SessionService.MyAuthentication) SecurityContextHolder.getContext().getAuthentication(); - } + private static SessionService.MyAuthentication getAuthentication() { + return (SessionService.MyAuthentication) + SecurityContextHolder.getContext().getAuthentication(); + } - public static boolean isOrgAdmin() { + public static boolean isOrgAdmin() { - return getAuthentication().getUser().getOrgAdmin(); - } + return getAuthentication().getUser().getOrgAdmin(); + } - public static boolean isSysAdmin() { + public static boolean isSysAdmin() { - return getAuthentication().getUser().getSysAdmin(); - } + return getAuthentication().getUser().getSysAdmin(); + } - public static UserEntity currentUser() { - return getAuthentication().getUser(); - } + public static UserEntity currentUser() { + return getAuthentication().getUser(); + } } diff --git a/src/main/java/cn/lihongjie/coal/common/GroovyScriptUtils.java b/src/main/java/cn/lihongjie/coal/common/GroovyScriptUtils.java index 437c4214..02cb20b3 100644 --- a/src/main/java/cn/lihongjie/coal/common/GroovyScriptUtils.java +++ b/src/main/java/cn/lihongjie/coal/common/GroovyScriptUtils.java @@ -1,65 +1,70 @@ package cn.lihongjie.coal.common; import cn.lihongjie.coal.exception.BizException; + import groovy.lang.Binding; import groovy.lang.GroovyShell; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; + import lombok.experimental.UtilityClass; import lombok.extern.slf4j.Slf4j; + import org.apache.commons.lang3.StringUtils; import org.codehaus.groovy.ast.ASTNode; import org.codehaus.groovy.ast.GroovyCodeVisitorAdapter; import org.codehaus.groovy.ast.builder.AstStringCompiler; import org.codehaus.groovy.ast.expr.VariableExpression; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + @UtilityClass @Slf4j public class GroovyScriptUtils { - public static void validate(String formula) { - if (StringUtils.isEmpty(formula)) { - return; - } - AstStringCompiler compiler = new AstStringCompiler(); - try { + public static void validate(String formula) { + if (StringUtils.isEmpty(formula)) { + return; + } + AstStringCompiler compiler = new AstStringCompiler(); + try { - List astNodes = compiler.compile(formula); - } catch (Exception e) { - log.info(formula, e); - throw new BizException("无效的计算公式"); - } - } - - public static List variables(String formula) { - if (StringUtils.isEmpty(formula)) { - return new ArrayList<>(); + List astNodes = compiler.compile(formula); + } catch (Exception e) { + log.info(formula, e); + throw new BizException("无效的计算公式"); + } } - AstStringCompiler compiler = new AstStringCompiler(); + public static List variables(String formula) { + if (StringUtils.isEmpty(formula)) { + return new ArrayList<>(); + } - return compiler.compile(formula).stream() - .flatMap( - x -> { - ArrayList ans = new ArrayList<>(); - x.visit( - new GroovyCodeVisitorAdapter() { - @Override - public void visitVariableExpression(VariableExpression expression) { - ans.add(expression.getName()); - } - }); + AstStringCompiler compiler = new AstStringCompiler(); - return ans.stream(); - }) - .collect(Collectors.toList()); - } + return compiler.compile(formula).stream() + .flatMap( + x -> { + ArrayList ans = new ArrayList<>(); + x.visit( + new GroovyCodeVisitorAdapter() { + @Override + public void visitVariableExpression( + VariableExpression expression) { + ans.add(expression.getName()); + } + }); - public static Object exec(String formula0, Map map) { + return ans.stream(); + }) + .collect(Collectors.toList()); + } - GroovyShell shell = new GroovyShell(new Binding(map)); + public static Object exec(String formula0, Map map) { - return shell.evaluate(formula0); - } + GroovyShell shell = new GroovyShell(new Binding(map)); + + return shell.evaluate(formula0); + } } diff --git a/src/main/java/cn/lihongjie/coal/common/ReflectUtils.java b/src/main/java/cn/lihongjie/coal/common/ReflectUtils.java index a9c28784..44cefce4 100644 --- a/src/main/java/cn/lihongjie/coal/common/ReflectUtils.java +++ b/src/main/java/cn/lihongjie/coal/common/ReflectUtils.java @@ -8,21 +8,21 @@ import org.springframework.util.ReflectionUtils; @UtilityClass public class ReflectUtils { - public static Object getFieldValue(Object object, String fieldName) { + public static Object getFieldValue(Object object, String fieldName) { - if (object == null) { - return null; - } + if (object == null) { + return null; + } - if (StringUtils.isEmpty(fieldName)) { - return null; - } + if (StringUtils.isEmpty(fieldName)) { + return null; + } - Field field = ReflectionUtils.findField(object.getClass(), fieldName); - if (field != null) { - field.setAccessible(true); - return ReflectionUtils.getField(field, object); + Field field = ReflectionUtils.findField(object.getClass(), fieldName); + if (field != null) { + field.setAccessible(true); + return ReflectionUtils.getField(field, object); + } + return null; } - return null; - } } diff --git a/src/main/java/cn/lihongjie/coal/common/RequestUtils.java b/src/main/java/cn/lihongjie/coal/common/RequestUtils.java index 28386124..4c86f4a0 100644 --- a/src/main/java/cn/lihongjie/coal/common/RequestUtils.java +++ b/src/main/java/cn/lihongjie/coal/common/RequestUtils.java @@ -4,64 +4,67 @@ import eu.bitwalker.useragentutils.Browser; import eu.bitwalker.useragentutils.OperatingSystem; import eu.bitwalker.useragentutils.UserAgent; import eu.bitwalker.useragentutils.Version; + import jakarta.servlet.http.HttpServletRequest; + import lombok.experimental.UtilityClass; + import org.apache.commons.lang3.StringUtils; @UtilityClass public class RequestUtils { - private static final String[] HEADERS_TO_TRY = { - "X-Forwarded-For", - "Proxy-Client-IP", - "WL-Proxy-Client-IP", - "HTTP_X_FORWARDED_FOR", - "HTTP_X_FORWARDED", - "HTTP_X_CLUSTER_CLIENT_IP", - "HTTP_CLIENT_IP", - "HTTP_FORWARDED_FOR", - "HTTP_FORWARDED", - "HTTP_VIA", - "REMOTE_ADDR" - }; + private static final String[] HEADERS_TO_TRY = { + "X-Forwarded-For", + "Proxy-Client-IP", + "WL-Proxy-Client-IP", + "HTTP_X_FORWARDED_FOR", + "HTTP_X_FORWARDED", + "HTTP_X_CLUSTER_CLIENT_IP", + "HTTP_CLIENT_IP", + "HTTP_FORWARDED_FOR", + "HTTP_FORWARDED", + "HTTP_VIA", + "REMOTE_ADDR" + }; - private String getClientIpAddress(HttpServletRequest request) { - for (String header : HEADERS_TO_TRY) { - String ip = request.getHeader(header); - if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) { - return ip; - } + private String getClientIpAddress(HttpServletRequest request) { + for (String header : HEADERS_TO_TRY) { + String ip = request.getHeader(header); + if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) { + return ip; + } + } + + return request.getRemoteAddr(); } - return request.getRemoteAddr(); - } - - public static String getIp(HttpServletRequest request) { - return getClientIpAddress(request); - } - - public static String getUa(HttpServletRequest request) { - - try { - - String header = request.getHeader("User-Agent"); - if (StringUtils.isEmpty(header)) { - return ""; - } - UserAgent userAgent = UserAgent.parseUserAgentString(header); - Browser browser = userAgent.getBrowser(); - - String browserName = browser.getName(); - // or - // String browserName = browser.getGroup().getName(); - Version browserVersion = userAgent.getBrowserVersion(); - - OperatingSystem os = userAgent.getOperatingSystem(); - - return os.getName() + " " + browserName + browserVersion.toString(); - - } catch (Exception e) { - return ""; + public static String getIp(HttpServletRequest request) { + return getClientIpAddress(request); + } + + public static String getUa(HttpServletRequest request) { + + try { + + String header = request.getHeader("User-Agent"); + if (StringUtils.isEmpty(header)) { + return ""; + } + UserAgent userAgent = UserAgent.parseUserAgentString(header); + Browser browser = userAgent.getBrowser(); + + String browserName = browser.getName(); + // or + // String browserName = browser.getGroup().getName(); + Version browserVersion = userAgent.getBrowserVersion(); + + OperatingSystem os = userAgent.getOperatingSystem(); + + return os.getName() + " " + browserName + browserVersion.toString(); + + } catch (Exception e) { + return ""; + } } - } } diff --git a/src/main/java/cn/lihongjie/coal/department/controller/DepartmentController.java b/src/main/java/cn/lihongjie/coal/department/controller/DepartmentController.java index d23468ea..d223ff56 100644 --- a/src/main/java/cn/lihongjie/coal/department/controller/DepartmentController.java +++ b/src/main/java/cn/lihongjie/coal/department/controller/DepartmentController.java @@ -8,6 +8,7 @@ import cn.lihongjie.coal.department.dto.CreateDepartmentDto; import cn.lihongjie.coal.department.dto.DepartmentDto; import cn.lihongjie.coal.department.dto.UpdateDepartmentDto; import cn.lihongjie.coal.department.service.DepartmentService; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.web.bind.annotation.PostMapping; @@ -21,34 +22,34 @@ import org.springframework.web.bind.annotation.RestController; @OrgScope public class DepartmentController { - @Autowired DepartmentService service; + @Autowired DepartmentService service; - @PostMapping("/create") - @SysLog(action = "新增") - public DepartmentDto create(@RequestBody CreateDepartmentDto dto) { - return this.service.create(dto); - } + @PostMapping("/create") + @SysLog(action = "新增") + public DepartmentDto create(@RequestBody CreateDepartmentDto dto) { + return this.service.create(dto); + } - @PostMapping("/update") - @SysLog(action = "编辑") - public DepartmentDto update(@RequestBody UpdateDepartmentDto dto) { - return this.service.update(dto); - } + @PostMapping("/update") + @SysLog(action = "编辑") + public DepartmentDto update(@RequestBody UpdateDepartmentDto dto) { + return this.service.update(dto); + } - @PostMapping("/delete") - @SysLog(action = "删除") - public Object delete(@RequestBody IdRequest dto) { - this.service.delete(dto); - return true; - } + @PostMapping("/delete") + @SysLog(action = "删除") + public Object delete(@RequestBody IdRequest dto) { + this.service.delete(dto); + return true; + } - @PostMapping("/list") - public Page list(@RequestBody CommonQuery dto) { - return this.service.list(dto); - } + @PostMapping("/list") + public Page list(@RequestBody CommonQuery dto) { + return this.service.list(dto); + } - @PostMapping("/getById") - public DepartmentDto getById(@RequestBody IdRequest dto) { - return this.service.getById(dto.getId()); - } + @PostMapping("/getById") + public DepartmentDto getById(@RequestBody IdRequest dto) { + return this.service.getById(dto.getId()); + } } diff --git a/src/main/java/cn/lihongjie/coal/department/dto/CreateDepartmentDto.java b/src/main/java/cn/lihongjie/coal/department/dto/CreateDepartmentDto.java index 59c33742..f99c37e6 100644 --- a/src/main/java/cn/lihongjie/coal/department/dto/CreateDepartmentDto.java +++ b/src/main/java/cn/lihongjie/coal/department/dto/CreateDepartmentDto.java @@ -1,6 +1,7 @@ package cn.lihongjie.coal.department.dto; import cn.lihongjie.coal.base.dto.OrgCommonDto; + import lombok.Data; @Data diff --git a/src/main/java/cn/lihongjie/coal/department/dto/DepartmentDto.java b/src/main/java/cn/lihongjie/coal/department/dto/DepartmentDto.java index 1e3d9996..82f7f4d6 100644 --- a/src/main/java/cn/lihongjie/coal/department/dto/DepartmentDto.java +++ b/src/main/java/cn/lihongjie/coal/department/dto/DepartmentDto.java @@ -1,6 +1,7 @@ package cn.lihongjie.coal.department.dto; import cn.lihongjie.coal.base.dto.OrgCommonDto; + import lombok.Data; @Data diff --git a/src/main/java/cn/lihongjie/coal/department/dto/UpdateDepartmentDto.java b/src/main/java/cn/lihongjie/coal/department/dto/UpdateDepartmentDto.java index 8da13c91..252ca7ac 100644 --- a/src/main/java/cn/lihongjie/coal/department/dto/UpdateDepartmentDto.java +++ b/src/main/java/cn/lihongjie/coal/department/dto/UpdateDepartmentDto.java @@ -1,6 +1,7 @@ package cn.lihongjie.coal.department.dto; import cn.lihongjie.coal.base.dto.OrgCommonDto; + import lombok.Data; @Data diff --git a/src/main/java/cn/lihongjie/coal/department/entity/DepartmentEntity.java b/src/main/java/cn/lihongjie/coal/department/entity/DepartmentEntity.java index de2ba139..bf1cd3be 100644 --- a/src/main/java/cn/lihongjie/coal/department/entity/DepartmentEntity.java +++ b/src/main/java/cn/lihongjie/coal/department/entity/DepartmentEntity.java @@ -1,9 +1,12 @@ package cn.lihongjie.coal.department.entity; import cn.lihongjie.coal.base.entity.OrgCommonEntity; + import jakarta.persistence.Entity; + import lombok.Getter; import lombok.Setter; + import org.hibernate.annotations.Comment; @Entity diff --git a/src/main/java/cn/lihongjie/coal/department/mapper/DepartmentMapper.java b/src/main/java/cn/lihongjie/coal/department/mapper/DepartmentMapper.java index b8cb3647..456719d4 100644 --- a/src/main/java/cn/lihongjie/coal/department/mapper/DepartmentMapper.java +++ b/src/main/java/cn/lihongjie/coal/department/mapper/DepartmentMapper.java @@ -11,8 +11,9 @@ import org.mapstruct.MappingConstants; import org.mapstruct.control.DeepClone; @Mapper( - componentModel = MappingConstants.ComponentModel.SPRING, - uses = {CommonMapper.class}, - mappingControl = DeepClone.class) + componentModel = MappingConstants.ComponentModel.SPRING, + uses = {CommonMapper.class}, + mappingControl = DeepClone.class) public interface DepartmentMapper - extends BaseMapper {} + extends BaseMapper< + DepartmentEntity, DepartmentDto, CreateDepartmentDto, UpdateDepartmentDto> {} diff --git a/src/main/java/cn/lihongjie/coal/department/repository/DepartmentRepository.java b/src/main/java/cn/lihongjie/coal/department/repository/DepartmentRepository.java index c0485c1c..76dac28e 100644 --- a/src/main/java/cn/lihongjie/coal/department/repository/DepartmentRepository.java +++ b/src/main/java/cn/lihongjie/coal/department/repository/DepartmentRepository.java @@ -2,6 +2,7 @@ package cn.lihongjie.coal.department.repository; import cn.lihongjie.coal.base.dao.BaseRepository; import cn.lihongjie.coal.department.entity.DepartmentEntity; + import org.springframework.stereotype.Repository; @Repository diff --git a/src/main/java/cn/lihongjie/coal/department/service/DepartmentService.java b/src/main/java/cn/lihongjie/coal/department/service/DepartmentService.java index bcddb4fa..70de1548 100644 --- a/src/main/java/cn/lihongjie/coal/department/service/DepartmentService.java +++ b/src/main/java/cn/lihongjie/coal/department/service/DepartmentService.java @@ -9,8 +9,11 @@ import cn.lihongjie.coal.department.dto.UpdateDepartmentDto; import cn.lihongjie.coal.department.entity.DepartmentEntity; import cn.lihongjie.coal.department.mapper.DepartmentMapper; import cn.lihongjie.coal.department.repository.DepartmentRepository; + import jakarta.annotation.PostConstruct; + import lombok.extern.slf4j.Slf4j; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.convert.ConversionService; import org.springframework.data.domain.Page; @@ -22,51 +25,53 @@ import org.springframework.stereotype.Service; @Slf4j public class DepartmentService extends BaseService { - @Autowired DepartmentRepository repository; + @Autowired DepartmentRepository repository; - @Autowired DepartmentMapper mapper; + @Autowired DepartmentMapper mapper; + @Autowired ConversionService conversionService; - @PostConstruct - public void init() {} + @PostConstruct + public void init() {} - public DepartmentDto create(CreateDepartmentDto request) { + public DepartmentDto create(CreateDepartmentDto request) { - DepartmentEntity entity = mapper.toEntity(request); + DepartmentEntity entity = mapper.toEntity(request); - this.repository.save(entity); - return getById(entity.getId()); - } + this.repository.save(entity); + return getById(entity.getId()); + } - public DepartmentDto update(UpdateDepartmentDto request) { - DepartmentEntity entity = this.repository.get(request.getId()); - this.mapper.updateEntity(entity, request); + public DepartmentDto update(UpdateDepartmentDto request) { + DepartmentEntity entity = this.repository.get(request.getId()); + this.mapper.updateEntity(entity, request); - this.repository.save(entity); + this.repository.save(entity); - return getById(entity.getId()); - } + return getById(entity.getId()); + } - public void delete(IdRequest request) { + public void delete(IdRequest request) { - this.repository.deleteAllById(request.getIds()); - } + this.repository.deleteAllById(request.getIds()); + } - public DepartmentDto getById(String id) { + public DepartmentDto getById(String id) { - DepartmentEntity entity = repository.get(id); + DepartmentEntity entity = repository.get(id); - return mapper.toDto(entity); - } + return mapper.toDto(entity); + } - @Autowired ConversionService conversionService; + public Page list(CommonQuery query) { - public Page list(CommonQuery query) { + Page page = + repository.findAll( + query.specification(conversionService), + PageRequest.of( + query.getPageNo(), + query.getPageSize(), + Sort.by(query.getOrders()))); - Page page = - repository.findAll( - query.specification(conversionService), - PageRequest.of(query.getPageNo(), query.getPageSize(), Sort.by(query.getOrders()))); - - return page.map(this.mapper::toDto); - } + return page.map(this.mapper::toDto); + } } diff --git a/src/main/java/cn/lihongjie/coal/dictionary/controller/DictionaryController.java b/src/main/java/cn/lihongjie/coal/dictionary/controller/DictionaryController.java index 0bc3620c..f7bb4aad 100644 --- a/src/main/java/cn/lihongjie/coal/dictionary/controller/DictionaryController.java +++ b/src/main/java/cn/lihongjie/coal/dictionary/controller/DictionaryController.java @@ -6,6 +6,7 @@ import cn.lihongjie.coal.base.dto.CommonQuery; import cn.lihongjie.coal.base.dto.IdRequest; import cn.lihongjie.coal.dictionary.dto.*; import cn.lihongjie.coal.dictionary.service.DictionaryService; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.web.bind.annotation.PostMapping; @@ -18,44 +19,44 @@ import org.springframework.web.bind.annotation.RestController; @SysLog(module = "数据字典管理") public class DictionaryController extends BaseController { - @Autowired DictionaryService service; + @Autowired DictionaryService service; - @PostMapping("/create") - @SysLog(action = "新增") - public DictionaryDto create(@RequestBody CreateDictionaryDto dto) { - return this.service.create(dto); - } + @PostMapping("/create") + @SysLog(action = "新增") + public DictionaryDto create(@RequestBody CreateDictionaryDto dto) { + return this.service.create(dto); + } - @PostMapping("/update") - @SysLog(action = "编辑") - public DictionaryDto update(@RequestBody UpdateDictionaryDto dto) { - return this.service.update(dto); - } + @PostMapping("/update") + @SysLog(action = "编辑") + public DictionaryDto update(@RequestBody UpdateDictionaryDto dto) { + return this.service.update(dto); + } - @PostMapping("/delete") - @SysLog(action = "删除") - public Object delete(@RequestBody IdRequest dto) { - this.service.delete(dto); - return true; - } + @PostMapping("/delete") + @SysLog(action = "删除") + public Object delete(@RequestBody IdRequest dto) { + this.service.delete(dto); + return true; + } - @PostMapping("/tree") - public DictionaryTreeDto tree(@RequestBody DictTreeRequest dto) { - return this.service.tree(dto); - } + @PostMapping("/tree") + public DictionaryTreeDto tree(@RequestBody DictTreeRequest dto) { + return this.service.tree(dto); + } - @PostMapping("/list") - public Page list(@RequestBody CommonQuery dto) { - return this.service.list(dto); - } + @PostMapping("/list") + public Page list(@RequestBody CommonQuery dto) { + return this.service.list(dto); + } - @PostMapping("/getById") - public DictionaryDto getById(@RequestBody IdRequest dto) { - return this.service.getById(dto.getId()); - } + @PostMapping("/getById") + public DictionaryDto getById(@RequestBody IdRequest dto) { + return this.service.getById(dto.getId()); + } - @PostMapping("/getByIdDetailed") - public DictionaryDetailedDto getByIdDetailed(@RequestBody IdRequest dto) { - return this.service.getByIdDetailed(dto.getId()); - } + @PostMapping("/getByIdDetailed") + public DictionaryDetailedDto getByIdDetailed(@RequestBody IdRequest dto) { + return this.service.getByIdDetailed(dto.getId()); + } } diff --git a/src/main/java/cn/lihongjie/coal/dictionary/controller/DictionaryItemController.java b/src/main/java/cn/lihongjie/coal/dictionary/controller/DictionaryItemController.java index 0455be7a..a7806420 100644 --- a/src/main/java/cn/lihongjie/coal/dictionary/controller/DictionaryItemController.java +++ b/src/main/java/cn/lihongjie/coal/dictionary/controller/DictionaryItemController.java @@ -7,6 +7,7 @@ import cn.lihongjie.coal.dictionary.dto.CreateDictionaryItemDto; import cn.lihongjie.coal.dictionary.dto.DictionaryItemDto; import cn.lihongjie.coal.dictionary.dto.UpdateDictionaryItemDto; import cn.lihongjie.coal.dictionary.service.DictionaryItemService; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.web.bind.annotation.PostMapping; @@ -19,34 +20,34 @@ import org.springframework.web.bind.annotation.RestController; @SysLog(module = "数据字典项") public class DictionaryItemController { - @Autowired DictionaryItemService service; + @Autowired DictionaryItemService service; - @PostMapping("/create") - @SysLog(action = "新增") - public DictionaryItemDto create(@RequestBody CreateDictionaryItemDto dto) { - return this.service.create(dto); - } + @PostMapping("/create") + @SysLog(action = "新增") + public DictionaryItemDto create(@RequestBody CreateDictionaryItemDto dto) { + return this.service.create(dto); + } - @PostMapping("/update") - @SysLog(action = "编辑") - public DictionaryItemDto update(@RequestBody UpdateDictionaryItemDto dto) { - return this.service.update(dto); - } + @PostMapping("/update") + @SysLog(action = "编辑") + public DictionaryItemDto update(@RequestBody UpdateDictionaryItemDto dto) { + return this.service.update(dto); + } - @PostMapping("/delete") - @SysLog(action = "删除") - public Object delete(@RequestBody IdRequest dto) { - this.service.delete(dto); - return true; - } + @PostMapping("/delete") + @SysLog(action = "删除") + public Object delete(@RequestBody IdRequest dto) { + this.service.delete(dto); + return true; + } - @PostMapping("/list") - public Page list(@RequestBody CommonQuery dto) { - return this.service.list(dto); - } + @PostMapping("/list") + public Page list(@RequestBody CommonQuery dto) { + return this.service.list(dto); + } - @PostMapping("/getById") - public DictionaryItemDto getById(@RequestBody IdRequest dto) { - return this.service.getById(dto.getId()); - } + @PostMapping("/getById") + public DictionaryItemDto getById(@RequestBody IdRequest dto) { + return this.service.getById(dto.getId()); + } } diff --git a/src/main/java/cn/lihongjie/coal/dictionary/dto/CreateDictionaryDto.java b/src/main/java/cn/lihongjie/coal/dictionary/dto/CreateDictionaryDto.java index 33e71f7e..87e1ff2c 100644 --- a/src/main/java/cn/lihongjie/coal/dictionary/dto/CreateDictionaryDto.java +++ b/src/main/java/cn/lihongjie/coal/dictionary/dto/CreateDictionaryDto.java @@ -1,31 +1,35 @@ package cn.lihongjie.coal.dictionary.dto; import cn.lihongjie.coal.base.dto.CommonDto; + import jakarta.persistence.OneToOne; -import java.util.List; + import lombok.Data; + import org.hibernate.annotations.Comment; +import java.util.List; + @Data public class CreateDictionaryDto extends CommonDto { - private String componentType; - private String componentTypeName; + private String componentType; + private String componentTypeName; - @Comment("字典类型 1 静态字典 2 动态字典") - private String dictType; + @Comment("字典类型 1 静态字典 2 动态字典") + private String dictType; - @OneToOne - @Comment("动态字典关联的脚本") - private String script; + @OneToOne + @Comment("动态字典关联的脚本") + private String script; - private List item; + private List item; - @Data - public static class DictionaryItemDto extends CommonDto { + @Data + public static class DictionaryItemDto extends CommonDto { - private List children; + private List children; - private String parent; - } + private String parent; + } } diff --git a/src/main/java/cn/lihongjie/coal/dictionary/dto/CreateDictionaryItemDto.java b/src/main/java/cn/lihongjie/coal/dictionary/dto/CreateDictionaryItemDto.java index fe327794..5d883410 100644 --- a/src/main/java/cn/lihongjie/coal/dictionary/dto/CreateDictionaryItemDto.java +++ b/src/main/java/cn/lihongjie/coal/dictionary/dto/CreateDictionaryItemDto.java @@ -5,6 +5,6 @@ import lombok.Data; @Data public class CreateDictionaryItemDto extends CommonDto { - private String parent; - private String dictionary; + private String parent; + private String dictionary; } diff --git a/src/main/java/cn/lihongjie/coal/dictionary/dto/DictTreeRequest.java b/src/main/java/cn/lihongjie/coal/dictionary/dto/DictTreeRequest.java index 349b41ff..4284594e 100644 --- a/src/main/java/cn/lihongjie/coal/dictionary/dto/DictTreeRequest.java +++ b/src/main/java/cn/lihongjie/coal/dictionary/dto/DictTreeRequest.java @@ -1,11 +1,12 @@ package cn.lihongjie.coal.dictionary.dto; import com.fasterxml.jackson.databind.JsonNode; + import lombok.Data; @Data public class DictTreeRequest { - private String code; + private String code; - private JsonNode params; + private JsonNode params; } diff --git a/src/main/java/cn/lihongjie/coal/dictionary/dto/DictionaryDetailedDto.java b/src/main/java/cn/lihongjie/coal/dictionary/dto/DictionaryDetailedDto.java index c3bd2b15..011df28c 100644 --- a/src/main/java/cn/lihongjie/coal/dictionary/dto/DictionaryDetailedDto.java +++ b/src/main/java/cn/lihongjie/coal/dictionary/dto/DictionaryDetailedDto.java @@ -7,12 +7,12 @@ import lombok.Data; @Data public class DictionaryDetailedDto extends DictionaryDto { - private List item; + private List item; - @Data - public static class DictionaryItemDto extends CommonDto { + @Data + public static class DictionaryItemDto extends CommonDto { - private String parent; - private List children; - } + private String parent; + private List children; + } } diff --git a/src/main/java/cn/lihongjie/coal/dictionary/dto/DictionaryDto.java b/src/main/java/cn/lihongjie/coal/dictionary/dto/DictionaryDto.java index c7c45191..8840eebf 100644 --- a/src/main/java/cn/lihongjie/coal/dictionary/dto/DictionaryDto.java +++ b/src/main/java/cn/lihongjie/coal/dictionary/dto/DictionaryDto.java @@ -7,10 +7,10 @@ import lombok.Data; @Data public class DictionaryDto extends CommonDto { - private String dictType; - private String dictTypeName; + private String dictType; + private String dictTypeName; - private String componentType; - private String componentTypeName; - private ScriptEntity script; + private String componentType; + private String componentTypeName; + private ScriptEntity script; } diff --git a/src/main/java/cn/lihongjie/coal/dictionary/dto/DictionaryItemDto.java b/src/main/java/cn/lihongjie/coal/dictionary/dto/DictionaryItemDto.java index ae2b2bc6..ab21c699 100644 --- a/src/main/java/cn/lihongjie/coal/dictionary/dto/DictionaryItemDto.java +++ b/src/main/java/cn/lihongjie/coal/dictionary/dto/DictionaryItemDto.java @@ -1,10 +1,11 @@ package cn.lihongjie.coal.dictionary.dto; import cn.lihongjie.coal.base.dto.CommonDto; + import lombok.Data; @Data public class DictionaryItemDto extends CommonDto { - private String parent; - private String dictionary; + private String parent; + private String dictionary; } diff --git a/src/main/java/cn/lihongjie/coal/dictionary/dto/DictionaryTreeDto.java b/src/main/java/cn/lihongjie/coal/dictionary/dto/DictionaryTreeDto.java index ba3559d6..82ba5d14 100644 --- a/src/main/java/cn/lihongjie/coal/dictionary/dto/DictionaryTreeDto.java +++ b/src/main/java/cn/lihongjie/coal/dictionary/dto/DictionaryTreeDto.java @@ -7,5 +7,5 @@ import lombok.Data; @Data public class DictionaryTreeDto extends DictionaryDto { - private List tree; + private List tree; } diff --git a/src/main/java/cn/lihongjie/coal/dictionary/dto/UpdateDictionaryDto.java b/src/main/java/cn/lihongjie/coal/dictionary/dto/UpdateDictionaryDto.java index 1ee01af2..f3331469 100644 --- a/src/main/java/cn/lihongjie/coal/dictionary/dto/UpdateDictionaryDto.java +++ b/src/main/java/cn/lihongjie/coal/dictionary/dto/UpdateDictionaryDto.java @@ -1,30 +1,34 @@ package cn.lihongjie.coal.dictionary.dto; import cn.lihongjie.coal.base.dto.CommonDto; + import jakarta.persistence.OneToOne; -import java.util.List; + import lombok.Data; + import org.hibernate.annotations.Comment; +import java.util.List; + @Data public class UpdateDictionaryDto extends CommonDto { - private String componentType; - private String componentTypeName; + private String componentType; + private String componentTypeName; - private String dictType; + private String dictType; - @OneToOne - @Comment("动态字典关联的脚本") - private String script; + @OneToOne + @Comment("动态字典关联的脚本") + private String script; - private List item; + private List item; - @Data - public static class DictionaryItemDto extends CommonDto { + @Data + public static class DictionaryItemDto extends CommonDto { - private List children; + private List children; - private String parent; - } + private String parent; + } } diff --git a/src/main/java/cn/lihongjie/coal/dictionary/dto/UpdateDictionaryItemDto.java b/src/main/java/cn/lihongjie/coal/dictionary/dto/UpdateDictionaryItemDto.java index cf839ef3..c0b33648 100644 --- a/src/main/java/cn/lihongjie/coal/dictionary/dto/UpdateDictionaryItemDto.java +++ b/src/main/java/cn/lihongjie/coal/dictionary/dto/UpdateDictionaryItemDto.java @@ -6,6 +6,6 @@ import lombok.Data; @Data public class UpdateDictionaryItemDto extends CommonDto { - private String parent; - private String dictionary; + private String parent; + private String dictionary; } diff --git a/src/main/java/cn/lihongjie/coal/dictionary/entity/DictionaryEntity.java b/src/main/java/cn/lihongjie/coal/dictionary/entity/DictionaryEntity.java index 8da22a6c..aac4b7db 100644 --- a/src/main/java/cn/lihongjie/coal/dictionary/entity/DictionaryEntity.java +++ b/src/main/java/cn/lihongjie/coal/dictionary/entity/DictionaryEntity.java @@ -2,86 +2,89 @@ package cn.lihongjie.coal.dictionary.entity; import cn.lihongjie.coal.base.entity.CommonEntity; import cn.lihongjie.coal.script.entity.ScriptEntity; + import jakarta.persistence.CascadeType; import jakarta.persistence.Entity; import jakarta.persistence.OneToMany; import jakarta.persistence.OneToOne; -import java.util.ArrayList; -import java.util.List; + import lombok.Getter; import lombok.Setter; + import org.apache.commons.lang3.StringUtils; import org.hibernate.annotations.Comment; import org.hibernate.annotations.Formula; +import java.util.ArrayList; +import java.util.List; + @Entity @Comment("数据字典主表") @Getter @Setter public class DictionaryEntity extends CommonEntity { - @OneToMany(mappedBy = "dictionary", cascade = CascadeType.ALL) - private List item; + @OneToMany(mappedBy = "dictionary", cascade = CascadeType.ALL) + private List item; - @Comment("字典类型 1 静态字典 2 动态字典") - private String dictType; + @Comment("字典类型 1 静态字典 2 动态字典") + private String dictType; - @Formula( - "(select i.name\n" - + "from t_dictionary d,\n" - + " t_dictionary_item i\n" - + "where d.id = i.dictionary_id\n" - + " and d.code = 'dict.type'\n" - + " and i.code = dict_type)") - private String dictTypeName; + @Formula( + "(select i.name\n" + + "from t_dictionary d,\n" + + " t_dictionary_item i\n" + + "where d.id = i.dictionary_id\n" + + " and d.code = 'dict.type'\n" + + " and i.code = dict_type)") + private String dictTypeName; - @Comment("字典类型 1 枚举 2 树") - private String componentType; + @Comment("字典类型 1 枚举 2 树") + private String componentType; - @Formula( - "(select i.name\n" - + "from t_dictionary d,\n" - + " t_dictionary_item i\n" - + "where d.id = i.dictionary_id\n" - + " and d.code = 'dict.componentType'\n" - + " and i.code = component_type)") - private String componentTypeName; + @Formula( + "(select i.name\n" + + "from t_dictionary d,\n" + + " t_dictionary_item i\n" + + "where d.id = i.dictionary_id\n" + + " and d.code = 'dict.componentType'\n" + + " and i.code = component_type)") + private String componentTypeName; - @OneToOne - @Comment("动态字典关联的脚本") - private ScriptEntity script; + @OneToOne + @Comment("动态字典关联的脚本") + private ScriptEntity script; - public void setItem(List item) { - this.item = item; - if (item != null) { + public void setItem(List item) { + this.item = item; + if (item != null) { - this.item.forEach(x -> x.setDictionary(this)); - } - } - - public void addItem(DictionaryItemEntity ni) { - if (this.item == null) { - this.item = new ArrayList<>(); - } - ; - - boolean found = false; - - for (DictionaryItemEntity di : item) { - - if (StringUtils.equalsIgnoreCase(di.getCode(), ni.getCode())) { - found = true; - - return; - } + this.item.forEach(x -> x.setDictionary(this)); + } } - if (!found) { + public void addItem(DictionaryItemEntity ni) { + if (this.item == null) { + this.item = new ArrayList<>(); + } - ni.initParent(null); - ni.initDict(this); + boolean found = false; - this.item.add(ni); + for (DictionaryItemEntity di : item) { + + if (StringUtils.equalsIgnoreCase(di.getCode(), ni.getCode())) { + found = true; + + return; + } + } + + if (!found) { + + ni.initParent(null); + ni.initDict(this); + + this.item.add(ni); + } } - } } diff --git a/src/main/java/cn/lihongjie/coal/dictionary/entity/DictionaryItemEntity.java b/src/main/java/cn/lihongjie/coal/dictionary/entity/DictionaryItemEntity.java index ed8a3177..f3edafa8 100644 --- a/src/main/java/cn/lihongjie/coal/dictionary/entity/DictionaryItemEntity.java +++ b/src/main/java/cn/lihongjie/coal/dictionary/entity/DictionaryItemEntity.java @@ -1,40 +1,44 @@ package cn.lihongjie.coal.dictionary.entity; import cn.lihongjie.coal.base.entity.CommonEntity; + import jakarta.persistence.*; -import java.util.List; + import lombok.Getter; import lombok.Setter; + import org.hibernate.annotations.Comment; +import java.util.List; + @Entity @Getter @Setter @Comment("数据字典数据项") public class DictionaryItemEntity extends CommonEntity { - @ManyToOne() private DictionaryEntity dictionary; + @ManyToOne() private DictionaryEntity dictionary; - @OneToMany(mappedBy = "parent") - private List children; + @OneToMany(mappedBy = "parent") + private List children; - @ManyToOne - @JoinColumn(name = "parent_id", foreignKey = @ForeignKey(value = ConstraintMode.NO_CONSTRAINT)) - private DictionaryItemEntity parent; + @ManyToOne + @JoinColumn(name = "parent_id", foreignKey = @ForeignKey(value = ConstraintMode.NO_CONSTRAINT)) + private DictionaryItemEntity parent; - public void initParent(DictionaryItemEntity o) { + public void initParent(DictionaryItemEntity o) { - this.parent = o; + this.parent = o; - if (children != null) { - children.forEach(x -> x.initParent(this)); + if (children != null) { + children.forEach(x -> x.initParent(this)); + } } - } - public void initDict(DictionaryEntity dictionaryEntity) { - this.dictionary = dictionaryEntity; - if (children != null) { - children.forEach(x -> x.initDict(dictionaryEntity)); + public void initDict(DictionaryEntity dictionaryEntity) { + this.dictionary = dictionaryEntity; + if (children != null) { + children.forEach(x -> x.initDict(dictionaryEntity)); + } } - } } diff --git a/src/main/java/cn/lihongjie/coal/dictionary/mapper/DictionaryItemMapper.java b/src/main/java/cn/lihongjie/coal/dictionary/mapper/DictionaryItemMapper.java index a702ba59..cc302446 100644 --- a/src/main/java/cn/lihongjie/coal/dictionary/mapper/DictionaryItemMapper.java +++ b/src/main/java/cn/lihongjie/coal/dictionary/mapper/DictionaryItemMapper.java @@ -6,15 +6,16 @@ import cn.lihongjie.coal.dictionary.dto.CreateDictionaryItemDto; import cn.lihongjie.coal.dictionary.dto.DictionaryItemDto; import cn.lihongjie.coal.dictionary.dto.UpdateDictionaryItemDto; import cn.lihongjie.coal.dictionary.entity.DictionaryItemEntity; + import org.mapstruct.Mapper; import org.mapstruct.MappingConstants; @Mapper( - componentModel = MappingConstants.ComponentModel.SPRING, - uses = {CommonMapper.class}) + componentModel = MappingConstants.ComponentModel.SPRING, + uses = {CommonMapper.class}) public interface DictionaryItemMapper - extends BaseMapper< - DictionaryItemEntity, - DictionaryItemDto, - CreateDictionaryItemDto, - UpdateDictionaryItemDto> {} + extends BaseMapper< + DictionaryItemEntity, + DictionaryItemDto, + CreateDictionaryItemDto, + UpdateDictionaryItemDto> {} diff --git a/src/main/java/cn/lihongjie/coal/dictionary/mapper/DictionaryMapper.java b/src/main/java/cn/lihongjie/coal/dictionary/mapper/DictionaryMapper.java index dc248f18..969d2a61 100644 --- a/src/main/java/cn/lihongjie/coal/dictionary/mapper/DictionaryMapper.java +++ b/src/main/java/cn/lihongjie/coal/dictionary/mapper/DictionaryMapper.java @@ -4,17 +4,19 @@ import cn.lihongjie.coal.base.mapper.BaseMapper; import cn.lihongjie.coal.base.mapper.CommonMapper; import cn.lihongjie.coal.dictionary.dto.*; import cn.lihongjie.coal.dictionary.entity.DictionaryEntity; + import org.mapstruct.Mapper; import org.mapstruct.MappingConstants; import org.mapstruct.control.DeepClone; @Mapper( - componentModel = MappingConstants.ComponentModel.SPRING, - uses = {CommonMapper.class}, - mappingControl = DeepClone.class) + componentModel = MappingConstants.ComponentModel.SPRING, + uses = {CommonMapper.class}, + mappingControl = DeepClone.class) public interface DictionaryMapper - extends BaseMapper { - DictionaryDetailedDto toDetailedDto(DictionaryEntity entity); + extends BaseMapper< + DictionaryEntity, DictionaryDto, CreateDictionaryDto, UpdateDictionaryDto> { + DictionaryDetailedDto toDetailedDto(DictionaryEntity entity); - DictionaryTreeDto toDictTree(DictionaryEntity dict); + DictionaryTreeDto toDictTree(DictionaryEntity dict); } diff --git a/src/main/java/cn/lihongjie/coal/dictionary/repository/DictionaryItemRepository.java b/src/main/java/cn/lihongjie/coal/dictionary/repository/DictionaryItemRepository.java index 1e901cd8..31f10ac2 100644 --- a/src/main/java/cn/lihongjie/coal/dictionary/repository/DictionaryItemRepository.java +++ b/src/main/java/cn/lihongjie/coal/dictionary/repository/DictionaryItemRepository.java @@ -2,6 +2,7 @@ package cn.lihongjie.coal.dictionary.repository; import cn.lihongjie.coal.base.dao.BaseRepository; import cn.lihongjie.coal.dictionary.entity.DictionaryItemEntity; + import org.springframework.stereotype.Repository; @Repository diff --git a/src/main/java/cn/lihongjie/coal/dictionary/repository/DictionaryRepository.java b/src/main/java/cn/lihongjie/coal/dictionary/repository/DictionaryRepository.java index d4d87ed3..7aa1d10e 100644 --- a/src/main/java/cn/lihongjie/coal/dictionary/repository/DictionaryRepository.java +++ b/src/main/java/cn/lihongjie/coal/dictionary/repository/DictionaryRepository.java @@ -8,7 +8,7 @@ import org.springframework.stereotype.Repository; @Repository public interface DictionaryRepository extends BaseRepository { - DictionaryEntity findByCode(String code); + DictionaryEntity findByCode(String code); - Optional findByScript(ScriptEntity script); + Optional findByScript(ScriptEntity script); } diff --git a/src/main/java/cn/lihongjie/coal/dictionary/service/DictionaryItemService.java b/src/main/java/cn/lihongjie/coal/dictionary/service/DictionaryItemService.java index 7abdfa4c..0d8d8b69 100644 --- a/src/main/java/cn/lihongjie/coal/dictionary/service/DictionaryItemService.java +++ b/src/main/java/cn/lihongjie/coal/dictionary/service/DictionaryItemService.java @@ -9,8 +9,11 @@ import cn.lihongjie.coal.dictionary.dto.UpdateDictionaryItemDto; import cn.lihongjie.coal.dictionary.entity.DictionaryItemEntity; import cn.lihongjie.coal.dictionary.mapper.DictionaryItemMapper; import cn.lihongjie.coal.dictionary.repository.DictionaryItemRepository; + import jakarta.annotation.PostConstruct; + import lombok.extern.slf4j.Slf4j; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.convert.ConversionService; import org.springframework.data.domain.Page; @@ -21,52 +24,54 @@ import org.springframework.stereotype.Service; @Service @Slf4j public class DictionaryItemService - extends BaseService { + extends BaseService { - @Autowired DictionaryItemRepository repository; + @Autowired DictionaryItemRepository repository; - @Autowired DictionaryItemMapper mapper; + @Autowired DictionaryItemMapper mapper; + @Autowired ConversionService conversionService; - @PostConstruct - public void init() {} + @PostConstruct + public void init() {} - public DictionaryItemDto create(CreateDictionaryItemDto request) { + public DictionaryItemDto create(CreateDictionaryItemDto request) { - DictionaryItemEntity entity = mapper.toEntity(request); + DictionaryItemEntity entity = mapper.toEntity(request); - this.repository.save(entity); - return getById(entity.getId()); - } + this.repository.save(entity); + return getById(entity.getId()); + } - public DictionaryItemDto update(UpdateDictionaryItemDto request) { - DictionaryItemEntity entity = this.repository.get(request.getId()); - this.mapper.updateEntity(entity, request); + public DictionaryItemDto update(UpdateDictionaryItemDto request) { + DictionaryItemEntity entity = this.repository.get(request.getId()); + this.mapper.updateEntity(entity, request); - this.repository.save(entity); - return getById(entity.getId()); - } + this.repository.save(entity); + return getById(entity.getId()); + } - public void delete(IdRequest request) { + public void delete(IdRequest request) { - this.repository.deleteAllById(request.getIds()); - } + this.repository.deleteAllById(request.getIds()); + } - public DictionaryItemDto getById(String id) { + public DictionaryItemDto getById(String id) { - DictionaryItemEntity entity = repository.get(id); + DictionaryItemEntity entity = repository.get(id); - return mapper.toDto(entity); - } + return mapper.toDto(entity); + } - @Autowired ConversionService conversionService; + public Page list(CommonQuery query) { - public Page list(CommonQuery query) { + Page page = + repository.findAll( + query.specification(conversionService), + PageRequest.of( + query.getPageNo(), + query.getPageSize(), + Sort.by(query.getOrders()))); - Page page = - repository.findAll( - query.specification(conversionService), - PageRequest.of(query.getPageNo(), query.getPageSize(), Sort.by(query.getOrders()))); - - return page.map(this.mapper::toDto); - } + return page.map(this.mapper::toDto); + } } diff --git a/src/main/java/cn/lihongjie/coal/dictionary/service/DictionaryService.java b/src/main/java/cn/lihongjie/coal/dictionary/service/DictionaryService.java index 52ac5abe..23803943 100644 --- a/src/main/java/cn/lihongjie/coal/dictionary/service/DictionaryService.java +++ b/src/main/java/cn/lihongjie/coal/dictionary/service/DictionaryService.java @@ -14,15 +14,16 @@ import cn.lihongjie.coal.exception.BizException; import cn.lihongjie.coal.script.dto.ScriptExecResultDto; import cn.lihongjie.coal.script.entity.ScriptEntity; import cn.lihongjie.coal.script.service.ScriptService; + import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; + import jakarta.annotation.PostConstruct; -import java.io.InputStream; -import java.util.List; -import java.util.Optional; + import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; + import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.convert.ConversionService; @@ -32,173 +33,177 @@ import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Sort; import org.springframework.stereotype.Service; +import java.io.InputStream; +import java.util.List; +import java.util.Optional; + @Service @Slf4j public class DictionaryService extends BaseService { - @Autowired DictionaryRepository repository; + @Autowired DictionaryRepository repository; - @Autowired DictionaryMapper mapper; + @Autowired DictionaryMapper mapper; + @Autowired ScriptService scriptService; + @Autowired ConversionService conversionService; + @Autowired DictionaryItemMapper dictionaryItemMapper; - @PostConstruct - public void init() {} + @PostConstruct + public void init() {} - @Autowired ScriptService scriptService; + @SneakyThrows + public DictionaryTreeDto tree(DictTreeRequest request) { - @SneakyThrows - public DictionaryTreeDto tree(DictTreeRequest request) { - - DictionaryEntity dict = this.repository.findByCode(request.getCode()); - if (dict == null) { - throw new BizException("数据字典 %s 不存在".formatted(request.getCode())); - } - boolean flatten = StringUtils.equalsIgnoreCase(dict.getComponentType(), "1"); - DictionaryTreeDto ans = this.mapper.toDictTree(dict); - if (dict.getDictType().equalsIgnoreCase("1")) { - - ans.setTree(TreeDto.buildList(dict.getItem(), flatten)); - } else if (dict.getDictType().equalsIgnoreCase("2")) { - - ScriptExecResultDto resultDto = new ScriptExecResultDto(); - resultDto.setId(dict.getScript().getId()); - resultDto.setParams(request.getParams()); - ScriptExecResultDto result = scriptService.exec(resultDto); - if (StringUtils.isNotEmpty(result.getStackTrace())) { - log.warn( - "执行脚本出错 id:{}\nparams:{}\nstacktrace:{}\nlogs:{}", - result.getId(), - result.getParams() + "", - result.getStackTrace(), - result.getLogs()); - } - ans.setTree(TreeDto.buildList(result.getResponse(), flatten)); - } else { - - throw new BizException("不支持的字典类型 " + dict.getDictTypeName()); - } - - return ans; - } - - public DictionaryDto create(CreateDictionaryDto request) { - - DictionaryEntity entity = mapper.toEntity(request); - - this.repository.save(entity); - return getById(entity.getId()); - } - - public DictionaryDto update(UpdateDictionaryDto request) { - DictionaryEntity entity = this.repository.get(request.getId()); - this.mapper.updateEntity(entity, request); - - if (entity.getItem() != null) { - entity.getItem().forEach(x -> x.setDictionary(entity)); - } - this.repository.save(entity); - - return getById(entity.getId()); - } - - public void delete(IdRequest request) { - - this.repository.deleteAllById(request.getIds()); - } - - public DictionaryDto getById(String id) { - - DictionaryEntity entity = repository.get(id); - - return mapper.toDto(entity); - } - - @Autowired ConversionService conversionService; - - public Page list(CommonQuery query) { - - Page page = - repository.findAll( - query.specification(conversionService), - PageRequest.of(query.getPageNo(), query.getPageSize(), Sort.by(query.getOrders()))); - - return page.map(this.mapper::toDto); - } - - public DictionaryDetailedDto getByIdDetailed(String id) { - DictionaryEntity entity = repository.get(id); - - return mapper.toDetailedDto(entity); - } - - @Autowired DictionaryItemMapper dictionaryItemMapper; - - @SneakyThrows - public void initDefault() { - - ClassPathResource classPathResource = new ClassPathResource("/config/dictionary.json"); - - ObjectMapper mapper = new ObjectMapper(); - mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); - - List defaultDicts; - - List exists = findAll(); - - try (InputStream inputStream = classPathResource.getInputStream()) { - defaultDicts = mapper.readValue(inputStream, new TypeReference>() {}); - } - - for (DictionaryEntity dictionary : defaultDicts) { - - boolean found = false; - for (DictionaryEntity exist : exists) { - - if (StringUtils.equalsIgnoreCase(dictionary.getCode(), exist.getCode())) { - - for (DictionaryItemEntity item : dictionary.getItem()) { - found = true; - exist.addItem(dictionaryItemMapper.copy(item)); - } + DictionaryEntity dict = this.repository.findByCode(request.getCode()); + if (dict == null) { + throw new BizException("数据字典 %s 不存在".formatted(request.getCode())); } - } + boolean flatten = StringUtils.equalsIgnoreCase(dict.getComponentType(), "1"); + DictionaryTreeDto ans = this.mapper.toDictTree(dict); + if (dict.getDictType().equalsIgnoreCase("1")) { - if (!found) { - DictionaryEntity nd = new DictionaryEntity(); - nd.setCode(dictionary.getCode()); - nd.setName(dictionary.getName()); + ans.setTree(TreeDto.buildList(dict.getItem(), flatten)); + } else if (dict.getDictType().equalsIgnoreCase("2")) { - nd.setDictType("1"); - nd.setComponentType(StringUtils.defaultIfBlank(dictionary.getComponentType(), "1")); + ScriptExecResultDto resultDto = new ScriptExecResultDto(); + resultDto.setId(dict.getScript().getId()); + resultDto.setParams(request.getParams()); + ScriptExecResultDto result = scriptService.exec(resultDto); + if (StringUtils.isNotEmpty(result.getStackTrace())) { + log.warn( + "执行脚本出错 id:{}\nparams:{}\nstacktrace:{}\nlogs:{}", + result.getId(), + result.getParams() + "", + result.getStackTrace(), + result.getLogs()); + } + ans.setTree(TreeDto.buildList(result.getResponse(), flatten)); + } else { - for (DictionaryItemEntity item : dictionary.getItem()) { - nd.addItem(item); + throw new BizException("不支持的字典类型 " + dict.getDictTypeName()); } - this.repository.save(nd); - } + return ans; } - } - public void createScriptDict(ScriptEntity scriptEntity) { + public DictionaryDto create(CreateDictionaryDto request) { - Optional byScript = this.repository.findByScript(scriptEntity); + DictionaryEntity entity = mapper.toEntity(request); - if (byScript.isPresent()) { - return; - } else { - - DictionaryEntity dictionary = new DictionaryEntity(); - - dictionary.setName(scriptEntity.getName()); - dictionary.setCode(scriptEntity.getCode()); - - dictionary.setDictType("2"); - dictionary.setComponentType(scriptEntity.getScriptPath().contains("tree") ? "2" : "1"); - - dictionary.setScript(scriptEntity); - dictionary.setStatus(1); - - this.repository.save(dictionary); + this.repository.save(entity); + return getById(entity.getId()); + } + + public DictionaryDto update(UpdateDictionaryDto request) { + DictionaryEntity entity = this.repository.get(request.getId()); + this.mapper.updateEntity(entity, request); + + if (entity.getItem() != null) { + entity.getItem().forEach(x -> x.setDictionary(entity)); + } + this.repository.save(entity); + + return getById(entity.getId()); + } + + public void delete(IdRequest request) { + + this.repository.deleteAllById(request.getIds()); + } + + public DictionaryDto getById(String id) { + + DictionaryEntity entity = repository.get(id); + + return mapper.toDto(entity); + } + + public Page list(CommonQuery query) { + + Page page = + repository.findAll( + query.specification(conversionService), + PageRequest.of( + query.getPageNo(), + query.getPageSize(), + Sort.by(query.getOrders()))); + + return page.map(this.mapper::toDto); + } + + public DictionaryDetailedDto getByIdDetailed(String id) { + DictionaryEntity entity = repository.get(id); + + return mapper.toDetailedDto(entity); + } + + @SneakyThrows + public void initDefault() { + + ClassPathResource classPathResource = new ClassPathResource("/config/dictionary.json"); + + ObjectMapper mapper = new ObjectMapper(); + mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); + + List defaultDicts; + + List exists = findAll(); + + try (InputStream inputStream = classPathResource.getInputStream()) { + defaultDicts = + mapper.readValue(inputStream, new TypeReference>() {}); + } + + for (DictionaryEntity dictionary : defaultDicts) { + + boolean found = false; + for (DictionaryEntity exist : exists) { + + if (StringUtils.equalsIgnoreCase(dictionary.getCode(), exist.getCode())) { + + for (DictionaryItemEntity item : dictionary.getItem()) { + found = true; + exist.addItem(dictionaryItemMapper.copy(item)); + } + } + } + + if (!found) { + DictionaryEntity nd = new DictionaryEntity(); + nd.setCode(dictionary.getCode()); + nd.setName(dictionary.getName()); + + nd.setDictType("1"); + nd.setComponentType(StringUtils.defaultIfBlank(dictionary.getComponentType(), "1")); + + for (DictionaryItemEntity item : dictionary.getItem()) { + nd.addItem(item); + } + + this.repository.save(nd); + } + } + } + + public void createScriptDict(ScriptEntity scriptEntity) { + + Optional byScript = this.repository.findByScript(scriptEntity); + + if (byScript.isPresent()) { + } else { + + DictionaryEntity dictionary = new DictionaryEntity(); + + dictionary.setName(scriptEntity.getName()); + dictionary.setCode(scriptEntity.getCode()); + + dictionary.setDictType("2"); + dictionary.setComponentType(scriptEntity.getScriptPath().contains("tree") ? "2" : "1"); + + dictionary.setScript(scriptEntity); + dictionary.setStatus(1); + + this.repository.save(dictionary); + } } - } } diff --git a/src/main/java/cn/lihongjie/coal/enterprise/controller/EnterpriseController.java b/src/main/java/cn/lihongjie/coal/enterprise/controller/EnterpriseController.java index 17a30ef2..914d3914 100644 --- a/src/main/java/cn/lihongjie/coal/enterprise/controller/EnterpriseController.java +++ b/src/main/java/cn/lihongjie/coal/enterprise/controller/EnterpriseController.java @@ -7,7 +7,9 @@ import cn.lihongjie.coal.enterprise.dto.CreateEnterpriseDto; import cn.lihongjie.coal.enterprise.dto.EnterpriseDto; import cn.lihongjie.coal.enterprise.dto.UpdateEnterpriseDto; import cn.lihongjie.coal.enterprise.service.EnterpriseService; + import lombok.extern.slf4j.Slf4j; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.web.bind.annotation.PostMapping; @@ -20,31 +22,31 @@ import org.springframework.web.bind.annotation.RestController; @SysLog(module = "企业数据") @Slf4j public class EnterpriseController { - @Autowired private EnterpriseService service; + @Autowired private EnterpriseService service; - @PostMapping("/create") - public EnterpriseDto create(@RequestBody CreateEnterpriseDto request) { - return this.service.create(request); - } + @PostMapping("/create") + public EnterpriseDto create(@RequestBody CreateEnterpriseDto request) { + return this.service.create(request); + } - @PostMapping("/update") - public EnterpriseDto update(@RequestBody UpdateEnterpriseDto request) { - return this.service.update(request); - } + @PostMapping("/update") + public EnterpriseDto update(@RequestBody UpdateEnterpriseDto request) { + return this.service.update(request); + } - @PostMapping("/delete") - public Object delete(@RequestBody IdRequest request) { - this.service.delete(request); - return true; - } + @PostMapping("/delete") + public Object delete(@RequestBody IdRequest request) { + this.service.delete(request); + return true; + } - @PostMapping("/getById") - public EnterpriseDto getById(@RequestBody String request) { - return this.service.getById(request); - } + @PostMapping("/getById") + public EnterpriseDto getById(@RequestBody String request) { + return this.service.getById(request); + } - @PostMapping("/list") - public Page list(@RequestBody CommonQuery request) { - return this.service.list(request); - } + @PostMapping("/list") + public Page list(@RequestBody CommonQuery request) { + return this.service.list(request); + } } diff --git a/src/main/java/cn/lihongjie/coal/enterprise/dto/CreateEnterpriseDto.java b/src/main/java/cn/lihongjie/coal/enterprise/dto/CreateEnterpriseDto.java index 9e015f79..39e73fa9 100644 --- a/src/main/java/cn/lihongjie/coal/enterprise/dto/CreateEnterpriseDto.java +++ b/src/main/java/cn/lihongjie/coal/enterprise/dto/CreateEnterpriseDto.java @@ -1,83 +1,85 @@ package cn.lihongjie.coal.enterprise.dto; import cn.lihongjie.coal.base.dto.CommonDto; + import lombok.Data; + import org.hibernate.annotations.Comment; @Data public class CreateEnterpriseDto extends CommonDto { - @Comment("企业名称") - private String enterpriseName; + @Comment("企业名称") + private String enterpriseName; - @Comment("登记状态") - private String registrationStatus; + @Comment("登记状态") + private String registrationStatus; - @Comment("法定代表人") - private String legalRepresentative; + @Comment("法定代表人") + private String legalRepresentative; - @Comment("注册资本") - private String registeredCapital; + @Comment("注册资本") + private String registeredCapital; - @Comment("成立日期") - private String establishmentDate; + @Comment("成立日期") + private String establishmentDate; - @Comment("统一社会信用代码") - private String unifiedSocialCreditCode; + @Comment("统一社会信用代码") + private String unifiedSocialCreditCode; - @Comment("企业注册地址") - private String enterpriseRegisteredAddress; + @Comment("企业注册地址") + private String enterpriseRegisteredAddress; - @Comment("电话") - private String phone; + @Comment("电话") + private String phone; - @Comment("更多电话") - private String additionalPhone; + @Comment("更多电话") + private String additionalPhone; - @Comment("邮箱") - private String email; + @Comment("邮箱") + private String email; - @Comment("更多邮箱") - private String additionalEmail; + @Comment("更多邮箱") + private String additionalEmail; - @Comment("所属城市") - private String cityOfRegistration; + @Comment("所属城市") + private String cityOfRegistration; - @Comment("纳税人识别号") - private String taxpayerIdentificationNumber; + @Comment("纳税人识别号") + private String taxpayerIdentificationNumber; - @Comment("注册号") - private String registrationNumber; + @Comment("注册号") + private String registrationNumber; - @Comment("组织机构代码") - private String organizationCode; + @Comment("组织机构代码") + private String organizationCode; - @Comment("参保人数") - private String insuredCount; + @Comment("参保人数") + private String insuredCount; - @Comment("企业(机构)类型") - private String enterpriseType; + @Comment("企业(机构)类型") + private String enterpriseType; - @Comment("企业规模") - private String enterpriseSize; + @Comment("企业规模") + private String enterpriseSize; - @Comment("核准日期") - private String approvalDate; + @Comment("核准日期") + private String approvalDate; - @Comment("营业期限") - private String businessPeriod; + @Comment("营业期限") + private String businessPeriod; - @Comment("曾用名") - private String formerName; + @Comment("曾用名") + private String formerName; - @Comment("英文名") - private String englishName; + @Comment("英文名") + private String englishName; - @Comment("官网网址") - private String officialWebsiteUrl; + @Comment("官网网址") + private String officialWebsiteUrl; - @Comment("通信地址") - private String mailingAddress; + @Comment("通信地址") + private String mailingAddress; - @Comment("经营范围") - private String businessScope; + @Comment("经营范围") + private String businessScope; } diff --git a/src/main/java/cn/lihongjie/coal/enterprise/dto/EnterpriseDto.java b/src/main/java/cn/lihongjie/coal/enterprise/dto/EnterpriseDto.java index 652ffb9f..49855641 100644 --- a/src/main/java/cn/lihongjie/coal/enterprise/dto/EnterpriseDto.java +++ b/src/main/java/cn/lihongjie/coal/enterprise/dto/EnterpriseDto.java @@ -1,83 +1,85 @@ package cn.lihongjie.coal.enterprise.dto; import cn.lihongjie.coal.base.dto.CommonDto; + import lombok.Data; + import org.hibernate.annotations.Comment; @Data public class EnterpriseDto extends CommonDto { - @Comment("企业名称") - private String enterpriseName; + @Comment("企业名称") + private String enterpriseName; - @Comment("登记状态") - private String registrationStatus; + @Comment("登记状态") + private String registrationStatus; - @Comment("法定代表人") - private String legalRepresentative; + @Comment("法定代表人") + private String legalRepresentative; - @Comment("注册资本") - private String registeredCapital; + @Comment("注册资本") + private String registeredCapital; - @Comment("成立日期") - private String establishmentDate; + @Comment("成立日期") + private String establishmentDate; - @Comment("统一社会信用代码") - private String unifiedSocialCreditCode; + @Comment("统一社会信用代码") + private String unifiedSocialCreditCode; - @Comment("企业注册地址") - private String enterpriseRegisteredAddress; + @Comment("企业注册地址") + private String enterpriseRegisteredAddress; - @Comment("电话") - private String phone; + @Comment("电话") + private String phone; - @Comment("更多电话") - private String additionalPhone; + @Comment("更多电话") + private String additionalPhone; - @Comment("邮箱") - private String email; + @Comment("邮箱") + private String email; - @Comment("更多邮箱") - private String additionalEmail; + @Comment("更多邮箱") + private String additionalEmail; - @Comment("所属城市") - private String cityOfRegistration; + @Comment("所属城市") + private String cityOfRegistration; - @Comment("纳税人识别号") - private String taxpayerIdentificationNumber; + @Comment("纳税人识别号") + private String taxpayerIdentificationNumber; - @Comment("注册号") - private String registrationNumber; + @Comment("注册号") + private String registrationNumber; - @Comment("组织机构代码") - private String organizationCode; + @Comment("组织机构代码") + private String organizationCode; - @Comment("参保人数") - private String insuredCount; + @Comment("参保人数") + private String insuredCount; - @Comment("企业(机构)类型") - private String enterpriseType; + @Comment("企业(机构)类型") + private String enterpriseType; - @Comment("企业规模") - private String enterpriseSize; + @Comment("企业规模") + private String enterpriseSize; - @Comment("核准日期") - private String approvalDate; + @Comment("核准日期") + private String approvalDate; - @Comment("营业期限") - private String businessPeriod; + @Comment("营业期限") + private String businessPeriod; - @Comment("曾用名") - private String formerName; + @Comment("曾用名") + private String formerName; - @Comment("英文名") - private String englishName; + @Comment("英文名") + private String englishName; - @Comment("官网网址") - private String officialWebsiteUrl; + @Comment("官网网址") + private String officialWebsiteUrl; - @Comment("通信地址") - private String mailingAddress; + @Comment("通信地址") + private String mailingAddress; - @Comment("经营范围") - private String businessScope; + @Comment("经营范围") + private String businessScope; } diff --git a/src/main/java/cn/lihongjie/coal/enterprise/dto/UpdateEnterpriseDto.java b/src/main/java/cn/lihongjie/coal/enterprise/dto/UpdateEnterpriseDto.java index 2abf7b9e..6b293b63 100644 --- a/src/main/java/cn/lihongjie/coal/enterprise/dto/UpdateEnterpriseDto.java +++ b/src/main/java/cn/lihongjie/coal/enterprise/dto/UpdateEnterpriseDto.java @@ -1,83 +1,85 @@ package cn.lihongjie.coal.enterprise.dto; import cn.lihongjie.coal.base.dto.CommonDto; + import lombok.Data; + import org.hibernate.annotations.Comment; @Data public class UpdateEnterpriseDto extends CommonDto { - @Comment("企业名称") - private String enterpriseName; + @Comment("企业名称") + private String enterpriseName; - @Comment("登记状态") - private String registrationStatus; + @Comment("登记状态") + private String registrationStatus; - @Comment("法定代表人") - private String legalRepresentative; + @Comment("法定代表人") + private String legalRepresentative; - @Comment("注册资本") - private String registeredCapital; + @Comment("注册资本") + private String registeredCapital; - @Comment("成立日期") - private String establishmentDate; + @Comment("成立日期") + private String establishmentDate; - @Comment("统一社会信用代码") - private String unifiedSocialCreditCode; + @Comment("统一社会信用代码") + private String unifiedSocialCreditCode; - @Comment("企业注册地址") - private String enterpriseRegisteredAddress; + @Comment("企业注册地址") + private String enterpriseRegisteredAddress; - @Comment("电话") - private String phone; + @Comment("电话") + private String phone; - @Comment("更多电话") - private String additionalPhone; + @Comment("更多电话") + private String additionalPhone; - @Comment("邮箱") - private String email; + @Comment("邮箱") + private String email; - @Comment("更多邮箱") - private String additionalEmail; + @Comment("更多邮箱") + private String additionalEmail; - @Comment("所属城市") - private String cityOfRegistration; + @Comment("所属城市") + private String cityOfRegistration; - @Comment("纳税人识别号") - private String taxpayerIdentificationNumber; + @Comment("纳税人识别号") + private String taxpayerIdentificationNumber; - @Comment("注册号") - private String registrationNumber; + @Comment("注册号") + private String registrationNumber; - @Comment("组织机构代码") - private String organizationCode; + @Comment("组织机构代码") + private String organizationCode; - @Comment("参保人数") - private String insuredCount; + @Comment("参保人数") + private String insuredCount; - @Comment("企业(机构)类型") - private String enterpriseType; + @Comment("企业(机构)类型") + private String enterpriseType; - @Comment("企业规模") - private String enterpriseSize; + @Comment("企业规模") + private String enterpriseSize; - @Comment("核准日期") - private String approvalDate; + @Comment("核准日期") + private String approvalDate; - @Comment("营业期限") - private String businessPeriod; + @Comment("营业期限") + private String businessPeriod; - @Comment("曾用名") - private String formerName; + @Comment("曾用名") + private String formerName; - @Comment("英文名") - private String englishName; + @Comment("英文名") + private String englishName; - @Comment("官网网址") - private String officialWebsiteUrl; + @Comment("官网网址") + private String officialWebsiteUrl; - @Comment("通信地址") - private String mailingAddress; + @Comment("通信地址") + private String mailingAddress; - @Comment("经营范围") - private String businessScope; + @Comment("经营范围") + private String businessScope; } diff --git a/src/main/java/cn/lihongjie/coal/enterprise/entity/EnterpriseEntity.java b/src/main/java/cn/lihongjie/coal/enterprise/entity/EnterpriseEntity.java index 4770fe71..8e8f74d0 100644 --- a/src/main/java/cn/lihongjie/coal/enterprise/entity/EnterpriseEntity.java +++ b/src/main/java/cn/lihongjie/coal/enterprise/entity/EnterpriseEntity.java @@ -1,8 +1,11 @@ package cn.lihongjie.coal.enterprise.entity; import cn.lihongjie.coal.base.entity.CommonEntity; + import jakarta.persistence.Entity; + import lombok.Data; + import org.hibernate.annotations.Comment; @Data @@ -10,78 +13,78 @@ import org.hibernate.annotations.Comment; @Comment("企业信息") public class EnterpriseEntity extends CommonEntity { - @Comment("企业名称") - private String enterpriseName; + @Comment("企业名称") + private String enterpriseName; - @Comment("登记状态") - private String registrationStatus; + @Comment("登记状态") + private String registrationStatus; - @Comment("法定代表人") - private String legalRepresentative; + @Comment("法定代表人") + private String legalRepresentative; - @Comment("注册资本") - private String registeredCapital; + @Comment("注册资本") + private String registeredCapital; - @Comment("成立日期") - private String establishmentDate; + @Comment("成立日期") + private String establishmentDate; - @Comment("统一社会信用代码") - private String unifiedSocialCreditCode; + @Comment("统一社会信用代码") + private String unifiedSocialCreditCode; - @Comment("企业注册地址") - private String enterpriseRegisteredAddress; + @Comment("企业注册地址") + private String enterpriseRegisteredAddress; - @Comment("电话") - private String phone; + @Comment("电话") + private String phone; - @Comment("更多电话") - private String additionalPhone; + @Comment("更多电话") + private String additionalPhone; - @Comment("邮箱") - private String email; + @Comment("邮箱") + private String email; - @Comment("更多邮箱") - private String additionalEmail; + @Comment("更多邮箱") + private String additionalEmail; - @Comment("所属城市") - private String cityOfRegistration; + @Comment("所属城市") + private String cityOfRegistration; - @Comment("纳税人识别号") - private String taxpayerIdentificationNumber; + @Comment("纳税人识别号") + private String taxpayerIdentificationNumber; - @Comment("注册号") - private String registrationNumber; + @Comment("注册号") + private String registrationNumber; - @Comment("组织机构代码") - private String organizationCode; + @Comment("组织机构代码") + private String organizationCode; - @Comment("参保人数") - private String insuredCount; + @Comment("参保人数") + private String insuredCount; - @Comment("企业(机构)类型") - private String enterpriseType; + @Comment("企业(机构)类型") + private String enterpriseType; - @Comment("企业规模") - private String enterpriseSize; + @Comment("企业规模") + private String enterpriseSize; - @Comment("核准日期") - private String approvalDate; + @Comment("核准日期") + private String approvalDate; - @Comment("营业期限") - private String businessPeriod; + @Comment("营业期限") + private String businessPeriod; - @Comment("曾用名") - private String formerName; + @Comment("曾用名") + private String formerName; - @Comment("英文名") - private String englishName; + @Comment("英文名") + private String englishName; - @Comment("官网网址") - private String officialWebsiteUrl; + @Comment("官网网址") + private String officialWebsiteUrl; - @Comment("通信地址") - private String mailingAddress; + @Comment("通信地址") + private String mailingAddress; - @Comment("经营范围") - private String businessScope; + @Comment("经营范围") + private String businessScope; } diff --git a/src/main/java/cn/lihongjie/coal/enterprise/mapper/EnterpriseMapper.java b/src/main/java/cn/lihongjie/coal/enterprise/mapper/EnterpriseMapper.java index d95a5c33..c744dc7f 100644 --- a/src/main/java/cn/lihongjie/coal/enterprise/mapper/EnterpriseMapper.java +++ b/src/main/java/cn/lihongjie/coal/enterprise/mapper/EnterpriseMapper.java @@ -10,8 +10,9 @@ import org.mapstruct.Mapper; import org.mapstruct.control.DeepClone; @Mapper( - componentModel = org.mapstruct.MappingConstants.ComponentModel.SPRING, - uses = {CommonMapper.class}, - mappingControl = DeepClone.class) + componentModel = org.mapstruct.MappingConstants.ComponentModel.SPRING, + uses = {CommonMapper.class}, + mappingControl = DeepClone.class) public interface EnterpriseMapper - extends BaseMapper {} + extends BaseMapper< + EnterpriseEntity, EnterpriseDto, CreateEnterpriseDto, UpdateEnterpriseDto> {} diff --git a/src/main/java/cn/lihongjie/coal/enterprise/repository/EnterpriseRepository.java b/src/main/java/cn/lihongjie/coal/enterprise/repository/EnterpriseRepository.java index 7f8151be..21664e83 100644 --- a/src/main/java/cn/lihongjie/coal/enterprise/repository/EnterpriseRepository.java +++ b/src/main/java/cn/lihongjie/coal/enterprise/repository/EnterpriseRepository.java @@ -2,6 +2,7 @@ package cn.lihongjie.coal.enterprise.repository; import cn.lihongjie.coal.base.dao.BaseRepository; import cn.lihongjie.coal.enterprise.entity.EnterpriseEntity; + import org.springframework.stereotype.Repository; @Repository diff --git a/src/main/java/cn/lihongjie/coal/enterprise/service/EnterpriseService.java b/src/main/java/cn/lihongjie/coal/enterprise/service/EnterpriseService.java index 680a927a..e0c57a68 100644 --- a/src/main/java/cn/lihongjie/coal/enterprise/service/EnterpriseService.java +++ b/src/main/java/cn/lihongjie/coal/enterprise/service/EnterpriseService.java @@ -9,7 +9,9 @@ import cn.lihongjie.coal.enterprise.dto.UpdateEnterpriseDto; import cn.lihongjie.coal.enterprise.entity.EnterpriseEntity; import cn.lihongjie.coal.enterprise.mapper.EnterpriseMapper; import cn.lihongjie.coal.enterprise.repository.EnterpriseRepository; + import lombok.extern.slf4j.Slf4j; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.convert.ConversionService; import org.springframework.data.domain.Page; @@ -20,44 +22,47 @@ import org.springframework.stereotype.Service; @Service @Slf4j public class EnterpriseService extends BaseService { - @Autowired private EnterpriseRepository repository; + @Autowired private EnterpriseRepository repository; - @Autowired private EnterpriseMapper mapper; + @Autowired private EnterpriseMapper mapper; - @Autowired private ConversionService conversionService; + @Autowired private ConversionService conversionService; - public EnterpriseDto create(CreateEnterpriseDto request) { - EnterpriseEntity entity = mapper.toEntity(request); + public EnterpriseDto create(CreateEnterpriseDto request) { + EnterpriseEntity entity = mapper.toEntity(request); - this.repository.save(entity); - return getById(entity.getId()); - } + this.repository.save(entity); + return getById(entity.getId()); + } - public EnterpriseDto update(UpdateEnterpriseDto request) { - EnterpriseEntity entity = this.repository.get(request.getId()); - this.mapper.updateEntity(entity, request); + public EnterpriseDto update(UpdateEnterpriseDto request) { + EnterpriseEntity entity = this.repository.get(request.getId()); + this.mapper.updateEntity(entity, request); - this.repository.save(entity); + this.repository.save(entity); - return getById(entity.getId()); - } + return getById(entity.getId()); + } - public void delete(IdRequest request) { - this.repository.deleteAllById(request.getIds()); - } + public void delete(IdRequest request) { + this.repository.deleteAllById(request.getIds()); + } - public EnterpriseDto getById(String id) { - EnterpriseEntity entity = repository.get(id); + public EnterpriseDto getById(String id) { + EnterpriseEntity entity = repository.get(id); - return mapper.toDto(entity); - } + return mapper.toDto(entity); + } - public Page list(CommonQuery query) { - Page page = - repository.findAll( - query.specification(conversionService), - PageRequest.of(query.getPageNo(), query.getPageSize(), Sort.by(query.getOrders()))); + public Page list(CommonQuery query) { + Page page = + repository.findAll( + query.specification(conversionService), + PageRequest.of( + query.getPageNo(), + query.getPageSize(), + Sort.by(query.getOrders()))); - return page.map(this.mapper::toDto); - } + return page.map(this.mapper::toDto); + } } diff --git a/src/main/java/cn/lihongjie/coal/exception/BizException.java b/src/main/java/cn/lihongjie/coal/exception/BizException.java index 5d6a1ca7..e7297687 100644 --- a/src/main/java/cn/lihongjie/coal/exception/BizException.java +++ b/src/main/java/cn/lihongjie/coal/exception/BizException.java @@ -5,19 +5,19 @@ import lombok.Getter; @Getter public class BizException extends RuntimeException { - String code; + String code; - public BizException(String message) { - this("bizError", message); - } + public BizException(String message) { + this("bizError", message); + } - public BizException(String code, String message) { - super(message); - this.code = code; - } + public BizException(String code, String message) { + super(message); + this.code = code; + } - public BizException(String code, String message, Throwable cause) { - super(message, cause); - this.code = code; - } + public BizException(String code, String message, Throwable cause) { + super(message, cause); + this.code = code; + } } diff --git a/src/main/java/cn/lihongjie/coal/filter/AuthFilter.java b/src/main/java/cn/lihongjie/coal/filter/AuthFilter.java index 0faea08a..e685b158 100644 --- a/src/main/java/cn/lihongjie/coal/filter/AuthFilter.java +++ b/src/main/java/cn/lihongjie/coal/filter/AuthFilter.java @@ -8,14 +8,16 @@ import cn.lihongjie.coal.resource.service.ResourceService; import cn.lihongjie.coal.session.SessionService; import cn.lihongjie.coal.spring.config.SystemConfig; import cn.lihongjie.coal.user.entity.UserEntity; + import com.fasterxml.jackson.databind.ObjectMapper; + import jakarta.servlet.FilterChain; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; -import java.io.IOException; -import java.util.Optional; + import lombok.SneakyThrows; + import org.apache.commons.lang3.BooleanUtils; import org.apache.commons.lang3.StringUtils; import org.apache.http.entity.ContentType; @@ -32,149 +34,157 @@ import org.springframework.transaction.support.TransactionTemplate; import org.springframework.web.filter.OncePerRequestFilter; import org.springframework.web.util.pattern.PathPatternParser; +import java.io.IOException; +import java.util.Optional; + @Component @Order(0) public class AuthFilter extends OncePerRequestFilter { - @Autowired SessionService sessionService; + @Autowired SessionService sessionService; - @Autowired SystemConfig systemConfig; + @Autowired SystemConfig systemConfig; - @Autowired ResourceService resourceService; + @Autowired ResourceService resourceService; - @Autowired PlatformTransactionManager transactionManager; + @Autowired PlatformTransactionManager transactionManager; + @Autowired ObjectMapper objectMapper; + @Value("${server.servlet.context-path}") + private String contextPath; - @Value("${server.servlet.context-path}") - private String contextPath; + @Override + public void doFilterInternal( + HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) + throws ServletException, IOException { - @Override - public void doFilterInternal( - HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) - throws ServletException, IOException { + TransactionTemplate transactionTemplate = + new TransactionTemplate( + transactionManager, + new DefaultTransactionDefinition( + TransactionDefinition.PROPAGATION_REQUIRED)); - TransactionTemplate transactionTemplate = - new TransactionTemplate( - transactionManager, - new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_REQUIRED)); + transactionTemplate.executeWithoutResult( + tx -> { + MDC.remove("user"); + if (isMatches(request)) { - transactionTemplate.executeWithoutResult( - tx -> { - MDC.remove("user"); - if (isMatches(request)) { + try { + filterChain.doFilter(request, response); + } catch (IOException e) { + throw new RuntimeException(e); + } catch (ServletException e) { + throw new RuntimeException(e); + } + return; + } - try { - filterChain.doFilter(request, response); - } catch (IOException e) { - throw new RuntimeException(e); - } catch (ServletException e) { - throw new RuntimeException(e); - } - return; - } + String sessionId = request.getHeader("X-Token"); - String sessionId = request.getHeader("X-Token"); + Optional resource = + resourceService.findUrl(getRequestURI(request)); - Optional resource = resourceService.findUrl(getRequestURI(request)); + if (resource.isEmpty()) { + writeResponse(new BizException("invalidUrl", "资源未找到"), response); + return; + } - if (resource.isEmpty()) { - writeResponse(new BizException("invalidUrl", "资源未找到"), response); - return; - } + request.setAttribute("__resourceEntity", resource.get()); - request.setAttribute("__resourceEntity", resource.get()); + if (StringUtils.isEmpty(sessionId)) { - if (StringUtils.isEmpty(sessionId)) { + if (resource.get().getAnonymous()) { + sessionService.anonymousSession(); + UserEntity user = Ctx.currentUser(); + MDC.put("user", user.getUsername()); + try { + filterChain.doFilter(request, response); + } catch (IOException e) { + throw new RuntimeException(e); + } catch (ServletException e) { + throw new RuntimeException(e); + } + } else { - if (resource.get().getAnonymous()) { - sessionService.anonymousSession(); - UserEntity user = Ctx.currentUser(); - MDC.put("user", user.getUsername()); - try { - filterChain.doFilter(request, response); - } catch (IOException e) { - throw new RuntimeException(e); - } catch (ServletException e) { - throw new RuntimeException(e); - } - } else { + writeResponse(new BizException("loginRequired", "请先登录"), response); + } - writeResponse(new BizException("loginRequired", "请先登录"), response); - } + } else { - } else { + try { - try { + sessionService.rebuildSession(sessionId); - sessionService.rebuildSession(sessionId); + } catch (BizException ex) { - } catch (BizException ex) { + writeResponse(ex, response); - writeResponse(ex, response); + return; + } - return; - } + UserEntity user = Ctx.currentUser(); + MDC.put("user", user.getUsername()); - UserEntity user = Ctx.currentUser(); - MDC.put("user", user.getUsername()); + Optional userResource = + user.getRoles().stream() + .flatMap(x -> x.getPermissions().stream()) + .flatMap(x -> x.getResources().stream()) + .filter( + x -> + StringUtils.equals( + x.getId(), resource.get().getId())) + .findAny(); - Optional userResource = - user.getRoles().stream() - .flatMap(x -> x.getPermissions().stream()) - .flatMap(x -> x.getResources().stream()) - .filter(x -> StringUtils.equals(x.getId(), resource.get().getId())) - .findAny(); + if (userResource.isEmpty() && BooleanUtils.isFalse(user.getSysAdmin())) { - if (userResource.isEmpty() && BooleanUtils.isFalse(user.getSysAdmin())) { + writeResponse( + new BizException("invalidAccess", "当前资源未授权,请联系机构管理员处理。"), + response); + } else { - writeResponse(new BizException("invalidAccess", "当前资源未授权,请联系机构管理员处理。"), response); - } else { - - try { - filterChain.doFilter(request, response); - } catch (IOException e) { - throw new RuntimeException(e); - } catch (ServletException e) { - throw new RuntimeException(e); - } - } - } - }); - } - - private boolean isMatches(HttpServletRequest request) { - boolean matches = false; - for (String url : systemConfig.getAnonymous().getUrl()) { - - matches = - PathPatternParser.defaultInstance - .parse(url) - .matches(PathContainer.parsePath(getRequestURI(request))); - if (matches) { - break; - } + try { + filterChain.doFilter(request, response); + } catch (IOException e) { + throw new RuntimeException(e); + } catch (ServletException e) { + throw new RuntimeException(e); + } + } + } + }); } - return matches; - } - private String getRequestURI(HttpServletRequest request) { - if (StringUtils.equalsIgnoreCase(contextPath, "/")) { + private boolean isMatches(HttpServletRequest request) { + boolean matches = false; + for (String url : systemConfig.getAnonymous().getUrl()) { - return request.getRequestURI(); - } else { - - return request.getRequestURI().replace(contextPath, "/"); + matches = + PathPatternParser.defaultInstance + .parse(url) + .matches(PathContainer.parsePath(getRequestURI(request))); + if (matches) { + break; + } + } + return matches; } - } - @Autowired ObjectMapper objectMapper; + private String getRequestURI(HttpServletRequest request) { + if (StringUtils.equalsIgnoreCase(contextPath, "/")) { - @SneakyThrows - private void writeResponse(BizException ex, HttpServletResponse response) { + return request.getRequestURI(); + } else { - response.setStatus(200); - response.setContentType(ContentType.APPLICATION_JSON.getMimeType()); - R fail = R.fail(ex.getCode(), ex.getMessage()); - response.getOutputStream().write(objectMapper.writeValueAsBytes(fail)); - response.getOutputStream().flush(); - } + return request.getRequestURI().replace(contextPath, "/"); + } + } + + @SneakyThrows + private void writeResponse(BizException ex, HttpServletResponse response) { + + response.setStatus(200); + response.setContentType(ContentType.APPLICATION_JSON.getMimeType()); + R fail = R.fail(ex.getCode(), ex.getMessage()); + response.getOutputStream().write(objectMapper.writeValueAsBytes(fail)); + response.getOutputStream().flush(); + } } diff --git a/src/main/java/cn/lihongjie/coal/ip/IpQueryService.java b/src/main/java/cn/lihongjie/coal/ip/IpQueryService.java index dacde5e9..b2294ce6 100644 --- a/src/main/java/cn/lihongjie/coal/ip/IpQueryService.java +++ b/src/main/java/cn/lihongjie/coal/ip/IpQueryService.java @@ -2,14 +2,12 @@ package cn.lihongjie.coal.ip; import com.maxmind.geoip2.DatabaseReader; import com.maxmind.geoip2.model.CityResponse; + import jakarta.annotation.PostConstruct; -import java.io.*; -import java.net.InetAddress; -import java.net.URL; -import java.nio.file.Files; -import java.nio.file.Path; + import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; + import org.apache.commons.compress.archivers.tar.TarArchiveEntry; import org.apache.commons.compress.archivers.tar.TarArchiveInputStream; import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream; @@ -20,108 +18,116 @@ import org.springframework.beans.factory.annotation.Value; import org.springframework.core.env.Environment; import org.springframework.stereotype.Service; +import java.io.*; +import java.net.InetAddress; +import java.net.URL; +import java.nio.file.Files; +import java.nio.file.Path; + @Service @Slf4j public class IpQueryService { - @Autowired Environment environment; + @Autowired Environment environment; - @Value("${geolite2.url}") - private String geolite2DownloadUrl; + @Value("${geolite2.url}") + private String geolite2DownloadUrl; - private DatabaseReader reader; + private DatabaseReader reader; - @SneakyThrows - @PostConstruct - public void init() { + @SneakyThrows + @PostConstruct + public void init() { - log.info("开始初始化GeoLite2-City本地数据库"); + log.info("开始初始化GeoLite2-City本地数据库"); - Path dbPath = Path.of("./GeoLite2-City/GeoLite2-City.mmdb"); + Path dbPath = Path.of("./GeoLite2-City/GeoLite2-City.mmdb"); - Path dbDir = dbPath.getParent(); - if (Files.notExists(dbDir)) { + Path dbDir = dbPath.getParent(); + if (Files.notExists(dbDir)) { - Files.createDirectories(dbDir); - } - - if (Files.exists(dbPath)) { - - log.info("发现默认数据库文件: {}", dbPath); - - } else if (StringUtils.isNotEmpty(environment.getProperty("geolite2.city.path"))) { - - dbPath = Path.of(environment.getProperty("geolite2.city.path")); - - log.info("发现环境变量数据库文件: {}", dbPath); - - } else { - - log.info("没有找到数据库文件, 下载数据库文件"); - - File downloadPath = dbPath.getParent().resolve("GeoLite2-City.tar.gz").toFile(); - FileUtils.copyURLToFile(new URL(geolite2DownloadUrl), downloadPath, 10 * 1000, 30 * 1000); - - TarArchiveInputStream tarIn = - new TarArchiveInputStream( - new GzipCompressorInputStream( - new BufferedInputStream(new FileInputStream(downloadPath)))); - - TarArchiveEntry tarEntry = tarIn.getNextTarEntry(); - Path newDbFile = null; - // tarIn is a TarArchiveInputStream - while (tarEntry != null) { // create a file with the same name as the tarEntry - File destPath = dbDir.resolve(tarEntry.getName()).toFile(); - log.info(destPath.toString()); - - if (tarEntry.isDirectory()) { - destPath.mkdirs(); - } else { - destPath.createNewFile(); - if (destPath.getName().endsWith("mmdb")) { - newDbFile = destPath.toPath(); - } - // byte [] btoRead = new byte[(int)tarEntry.getSize()]; - byte[] btoRead = new byte[1024]; - // FileInputStream fin - // = new FileInputStream(destPath.getCanonicalPath()); - BufferedOutputStream bout = new BufferedOutputStream(new FileOutputStream(destPath)); - int len = 0; - - while ((len = tarIn.read(btoRead)) != -1) { - bout.write(btoRead, 0, len); - } - - bout.close(); - btoRead = null; + Files.createDirectories(dbDir); } - tarEntry = tarIn.getNextTarEntry(); - } - tarIn.close(); - if (newDbFile != null) { + if (Files.exists(dbPath)) { - Files.move(newDbFile, dbPath); - } + log.info("发现默认数据库文件: {}", dbPath); + + } else if (StringUtils.isNotEmpty(environment.getProperty("geolite2.city.path"))) { + + dbPath = Path.of(environment.getProperty("geolite2.city.path")); + + log.info("发现环境变量数据库文件: {}", dbPath); + + } else { + + log.info("没有找到数据库文件, 下载数据库文件"); + + File downloadPath = dbPath.getParent().resolve("GeoLite2-City.tar.gz").toFile(); + FileUtils.copyURLToFile( + new URL(geolite2DownloadUrl), downloadPath, 10 * 1000, 30 * 1000); + + TarArchiveInputStream tarIn = + new TarArchiveInputStream( + new GzipCompressorInputStream( + new BufferedInputStream(new FileInputStream(downloadPath)))); + + TarArchiveEntry tarEntry = tarIn.getNextTarEntry(); + Path newDbFile = null; + // tarIn is a TarArchiveInputStream + while (tarEntry != null) { // create a file with the same name as the tarEntry + File destPath = dbDir.resolve(tarEntry.getName()).toFile(); + log.info(destPath.toString()); + + if (tarEntry.isDirectory()) { + destPath.mkdirs(); + } else { + destPath.createNewFile(); + if (destPath.getName().endsWith("mmdb")) { + newDbFile = destPath.toPath(); + } + // byte [] btoRead = new byte[(int)tarEntry.getSize()]; + byte[] btoRead = new byte[1024]; + // FileInputStream fin + // = new FileInputStream(destPath.getCanonicalPath()); + BufferedOutputStream bout = + new BufferedOutputStream(new FileOutputStream(destPath)); + int len = 0; + + while ((len = tarIn.read(btoRead)) != -1) { + bout.write(btoRead, 0, len); + } + + bout.close(); + btoRead = null; + } + tarEntry = tarIn.getNextTarEntry(); + } + tarIn.close(); + + if (newDbFile != null) { + + Files.move(newDbFile, dbPath); + } + } + + reader = new DatabaseReader.Builder(dbPath.toFile()).build(); } - reader = new DatabaseReader.Builder(dbPath.toFile()).build(); - } + @SneakyThrows + public String query(String ipaddr) { - @SneakyThrows - public String query(String ipaddr) { + if (reader != null) { + InetAddress ipAddress = InetAddress.getByName(ipaddr); + boolean siteLocalAddress = ipAddress.isSiteLocalAddress(); + if (siteLocalAddress) { + return "内网地址"; + } - if (reader != null) { - InetAddress ipAddress = InetAddress.getByName(ipaddr); - boolean siteLocalAddress = ipAddress.isSiteLocalAddress(); - if (siteLocalAddress) { - return "内网地址"; - } + CityResponse city = reader.city(ipAddress); + return city.getCountry().getName() + city.getCity().getName(); + } - CityResponse city = reader.city(ipAddress); - return city.getCountry().getName() + city.getCity().getName(); + return null; } - - return null; - } } diff --git a/src/main/java/cn/lihongjie/coal/organization/controller/OrganizationController.java b/src/main/java/cn/lihongjie/coal/organization/controller/OrganizationController.java index a16e3b7a..605381c1 100644 --- a/src/main/java/cn/lihongjie/coal/organization/controller/OrganizationController.java +++ b/src/main/java/cn/lihongjie/coal/organization/controller/OrganizationController.java @@ -8,6 +8,7 @@ import cn.lihongjie.coal.organization.dto.CreateOrganizationDto; import cn.lihongjie.coal.organization.dto.OrganizationDto; import cn.lihongjie.coal.organization.dto.UpdateOrganizationDto; import cn.lihongjie.coal.organization.service.OrganizationService; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.web.bind.annotation.PostMapping; @@ -20,34 +21,34 @@ import org.springframework.web.bind.annotation.RestController; @SysLog(module = "机构管理") public class OrganizationController extends BaseController { - @Autowired OrganizationService service; + @Autowired OrganizationService service; - @PostMapping("/create") - @SysLog(action = "新增") - public OrganizationDto create(@RequestBody CreateOrganizationDto dto) { - return this.service.create(dto); - } + @PostMapping("/create") + @SysLog(action = "新增") + public OrganizationDto create(@RequestBody CreateOrganizationDto dto) { + return this.service.create(dto); + } - @PostMapping("/update") - @SysLog(action = "编辑") - public OrganizationDto update(@RequestBody UpdateOrganizationDto dto) { - return this.service.update(dto); - } + @PostMapping("/update") + @SysLog(action = "编辑") + public OrganizationDto update(@RequestBody UpdateOrganizationDto dto) { + return this.service.update(dto); + } - @PostMapping("/delete") - @SysLog(action = "删除") - public Object delete(@RequestBody IdRequest dto) { - this.service.delete(dto); - return true; - } + @PostMapping("/delete") + @SysLog(action = "删除") + public Object delete(@RequestBody IdRequest dto) { + this.service.delete(dto); + return true; + } - @PostMapping("/list") - public Page list(@RequestBody CommonQuery dto) { - return this.service.list(dto); - } + @PostMapping("/list") + public Page list(@RequestBody CommonQuery dto) { + return this.service.list(dto); + } - @PostMapping("/getById") - public OrganizationDto getById(@RequestBody IdRequest dto) { - return this.service.getById(dto.getId()); - } + @PostMapping("/getById") + public OrganizationDto getById(@RequestBody IdRequest dto) { + return this.service.getById(dto.getId()); + } } diff --git a/src/main/java/cn/lihongjie/coal/organization/dto/CreateOrganizationDto.java b/src/main/java/cn/lihongjie/coal/organization/dto/CreateOrganizationDto.java index 04b0a63a..fae66e08 100644 --- a/src/main/java/cn/lihongjie/coal/organization/dto/CreateOrganizationDto.java +++ b/src/main/java/cn/lihongjie/coal/organization/dto/CreateOrganizationDto.java @@ -1,6 +1,7 @@ package cn.lihongjie.coal.organization.dto; import cn.lihongjie.coal.base.dto.CommonDto; + import lombok.Data; @Data diff --git a/src/main/java/cn/lihongjie/coal/organization/dto/OrganizationDto.java b/src/main/java/cn/lihongjie/coal/organization/dto/OrganizationDto.java index eaa9a67d..8189564b 100644 --- a/src/main/java/cn/lihongjie/coal/organization/dto/OrganizationDto.java +++ b/src/main/java/cn/lihongjie/coal/organization/dto/OrganizationDto.java @@ -6,5 +6,5 @@ import lombok.Data; @Data public class OrganizationDto extends CommonDto { - private String parentId; + private String parentId; } diff --git a/src/main/java/cn/lihongjie/coal/organization/dto/UpdateOrganizationDto.java b/src/main/java/cn/lihongjie/coal/organization/dto/UpdateOrganizationDto.java index 8b1c8316..53cdb151 100644 --- a/src/main/java/cn/lihongjie/coal/organization/dto/UpdateOrganizationDto.java +++ b/src/main/java/cn/lihongjie/coal/organization/dto/UpdateOrganizationDto.java @@ -1,10 +1,11 @@ package cn.lihongjie.coal.organization.dto; import cn.lihongjie.coal.base.dto.CommonDto; + import lombok.Data; @Data public class UpdateOrganizationDto extends CommonDto { - private String parentId; + private String parentId; } diff --git a/src/main/java/cn/lihongjie/coal/organization/entity/OrganizationEntity.java b/src/main/java/cn/lihongjie/coal/organization/entity/OrganizationEntity.java index 68bf80fd..48df8588 100644 --- a/src/main/java/cn/lihongjie/coal/organization/entity/OrganizationEntity.java +++ b/src/main/java/cn/lihongjie/coal/organization/entity/OrganizationEntity.java @@ -1,26 +1,31 @@ package cn.lihongjie.coal.organization.entity; import cn.lihongjie.coal.base.entity.CommonEntity; + import com.fasterxml.jackson.annotation.JsonBackReference; import com.fasterxml.jackson.annotation.JsonManagedReference; + import jakarta.persistence.*; -import java.util.List; + import lombok.Getter; import lombok.Setter; + import org.hibernate.annotations.Comment; +import java.util.List; + @Entity @Comment("机构") @Getter @Setter public class OrganizationEntity extends CommonEntity { - @OneToMany(mappedBy = "parent") - @JsonManagedReference - private List children; + @OneToMany(mappedBy = "parent") + @JsonManagedReference + private List children; - @ManyToOne - @JsonBackReference - @JoinColumn(name = "parent_id", foreignKey = @ForeignKey(value = ConstraintMode.NO_CONSTRAINT)) - private OrganizationEntity parent; + @ManyToOne + @JsonBackReference + @JoinColumn(name = "parent_id", foreignKey = @ForeignKey(value = ConstraintMode.NO_CONSTRAINT)) + private OrganizationEntity parent; } diff --git a/src/main/java/cn/lihongjie/coal/organization/mapper/OrganizationMapper.java b/src/main/java/cn/lihongjie/coal/organization/mapper/OrganizationMapper.java index 835be702..c4a13430 100644 --- a/src/main/java/cn/lihongjie/coal/organization/mapper/OrganizationMapper.java +++ b/src/main/java/cn/lihongjie/coal/organization/mapper/OrganizationMapper.java @@ -6,14 +6,18 @@ import cn.lihongjie.coal.organization.dto.CreateOrganizationDto; import cn.lihongjie.coal.organization.dto.OrganizationDto; import cn.lihongjie.coal.organization.dto.UpdateOrganizationDto; import cn.lihongjie.coal.organization.entity.OrganizationEntity; + import org.mapstruct.Mapper; import org.mapstruct.MappingConstants; import org.mapstruct.control.DeepClone; @Mapper( - componentModel = MappingConstants.ComponentModel.SPRING, - uses = {CommonMapper.class}, - mappingControl = DeepClone.class) + componentModel = MappingConstants.ComponentModel.SPRING, + uses = {CommonMapper.class}, + mappingControl = DeepClone.class) public interface OrganizationMapper - extends BaseMapper< - OrganizationEntity, OrganizationDto, CreateOrganizationDto, UpdateOrganizationDto> {} + extends BaseMapper< + OrganizationEntity, + OrganizationDto, + CreateOrganizationDto, + UpdateOrganizationDto> {} diff --git a/src/main/java/cn/lihongjie/coal/organization/repository/OrganizationRepository.java b/src/main/java/cn/lihongjie/coal/organization/repository/OrganizationRepository.java index 54e8c1c5..4dced037 100644 --- a/src/main/java/cn/lihongjie/coal/organization/repository/OrganizationRepository.java +++ b/src/main/java/cn/lihongjie/coal/organization/repository/OrganizationRepository.java @@ -2,11 +2,12 @@ package cn.lihongjie.coal.organization.repository; import cn.lihongjie.coal.base.dao.BaseRepository; import cn.lihongjie.coal.organization.entity.OrganizationEntity; + import org.springframework.lang.Nullable; import org.springframework.stereotype.Repository; @Repository public interface OrganizationRepository extends BaseRepository { - @Nullable - OrganizationEntity findByCode(String code); + @Nullable + OrganizationEntity findByCode(String code); } diff --git a/src/main/java/cn/lihongjie/coal/organization/service/OrganizationService.java b/src/main/java/cn/lihongjie/coal/organization/service/OrganizationService.java index a085dbc8..66d9a762 100644 --- a/src/main/java/cn/lihongjie/coal/organization/service/OrganizationService.java +++ b/src/main/java/cn/lihongjie/coal/organization/service/OrganizationService.java @@ -9,8 +9,11 @@ import cn.lihongjie.coal.organization.dto.UpdateOrganizationDto; import cn.lihongjie.coal.organization.entity.OrganizationEntity; import cn.lihongjie.coal.organization.mapper.OrganizationMapper; import cn.lihongjie.coal.organization.repository.OrganizationRepository; + import jakarta.annotation.PostConstruct; + import lombok.extern.slf4j.Slf4j; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.convert.ConversionService; import org.springframework.data.domain.Page; @@ -22,70 +25,72 @@ import org.springframework.stereotype.Service; @Slf4j public class OrganizationService extends BaseService { - @Autowired OrganizationRepository repository; + @Autowired OrganizationRepository repository; - @Autowired OrganizationMapper mapper; + @Autowired OrganizationMapper mapper; + @Autowired ConversionService conversionService; - @PostConstruct - public void init() {} + @PostConstruct + public void init() {} - public OrganizationDto create(CreateOrganizationDto request) { + public OrganizationDto create(CreateOrganizationDto request) { - OrganizationEntity entity = mapper.toEntity(request); + OrganizationEntity entity = mapper.toEntity(request); - this.repository.save(entity); - return getById(entity.getId()); - } - - public OrganizationDto update(UpdateOrganizationDto request) { - OrganizationEntity entity = this.repository.get(request.getId()); - this.mapper.updateEntity(entity, request); - - this.repository.save(entity); - - return getById(entity.getId()); - } - - public void delete(IdRequest request) { - - this.repository.deleteAllById(request.getIds()); - } - - public OrganizationDto getById(String id) { - - OrganizationEntity entity = repository.get(id); - - return mapper.toDto(entity); - } - - @Autowired ConversionService conversionService; - - public Page list(CommonQuery query) { - - Page page = - repository.findAll( - query.specification(conversionService), - PageRequest.of(query.getPageNo(), query.getPageSize(), Sort.by(query.getOrders()))); - - return page.map(this.mapper::toDto); - } - - public OrganizationEntity initOrGetAdminOrg() { - - OrganizationEntity adminOrg = this.repository.findByCode("adminOrg"); - - if (adminOrg == null) { - - adminOrg = new OrganizationEntity(); - - adminOrg.setParent(null); - adminOrg.setName("管理员机构"); - adminOrg.setCode("adminOrg"); - adminOrg.setStatus(1); - - this.repository.save(adminOrg); + this.repository.save(entity); + return getById(entity.getId()); } - return adminOrg; - } + public OrganizationDto update(UpdateOrganizationDto request) { + OrganizationEntity entity = this.repository.get(request.getId()); + this.mapper.updateEntity(entity, request); + + this.repository.save(entity); + + return getById(entity.getId()); + } + + public void delete(IdRequest request) { + + this.repository.deleteAllById(request.getIds()); + } + + public OrganizationDto getById(String id) { + + OrganizationEntity entity = repository.get(id); + + return mapper.toDto(entity); + } + + public Page list(CommonQuery query) { + + Page page = + repository.findAll( + query.specification(conversionService), + PageRequest.of( + query.getPageNo(), + query.getPageSize(), + Sort.by(query.getOrders()))); + + return page.map(this.mapper::toDto); + } + + public OrganizationEntity initOrGetAdminOrg() { + + OrganizationEntity adminOrg = this.repository.findByCode("adminOrg"); + + if (adminOrg == null) { + + adminOrg = new OrganizationEntity(); + + adminOrg.setParent(null); + adminOrg.setName("管理员机构"); + adminOrg.setCode("adminOrg"); + adminOrg.setStatus(1); + + this.repository.save(adminOrg); + } + + return adminOrg; + } } diff --git a/src/main/java/cn/lihongjie/coal/permission/controller/PermissionController.java b/src/main/java/cn/lihongjie/coal/permission/controller/PermissionController.java index 89e170ba..cc68a82d 100644 --- a/src/main/java/cn/lihongjie/coal/permission/controller/PermissionController.java +++ b/src/main/java/cn/lihongjie/coal/permission/controller/PermissionController.java @@ -8,6 +8,7 @@ import cn.lihongjie.coal.permission.dto.CreatePermissionDto; import cn.lihongjie.coal.permission.dto.PermissionDto; import cn.lihongjie.coal.permission.dto.UpdatePermissionDto; import cn.lihongjie.coal.permission.service.PermissionService; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.web.bind.annotation.PostMapping; @@ -20,34 +21,34 @@ import org.springframework.web.bind.annotation.RestController; @SysLog(module = "权限管理") public class PermissionController extends BaseController { - @Autowired PermissionService service; + @Autowired PermissionService service; - @PostMapping("/create") - @SysLog(action = "新增") - public PermissionDto create(@RequestBody CreatePermissionDto dto) { - return this.service.create(dto); - } + @PostMapping("/create") + @SysLog(action = "新增") + public PermissionDto create(@RequestBody CreatePermissionDto dto) { + return this.service.create(dto); + } - @PostMapping("/update") - @SysLog(action = "编辑") - public PermissionDto update(@RequestBody UpdatePermissionDto dto) { - return this.service.update(dto); - } + @PostMapping("/update") + @SysLog(action = "编辑") + public PermissionDto update(@RequestBody UpdatePermissionDto dto) { + return this.service.update(dto); + } - @PostMapping("/delete") - @SysLog(action = "删除") - public Object delete(@RequestBody IdRequest dto) { - this.service.delete(dto); - return true; - } + @PostMapping("/delete") + @SysLog(action = "删除") + public Object delete(@RequestBody IdRequest dto) { + this.service.delete(dto); + return true; + } - @PostMapping("/list") - public Page list(@RequestBody CommonQuery dto) { - return this.service.list(dto); - } + @PostMapping("/list") + public Page list(@RequestBody CommonQuery dto) { + return this.service.list(dto); + } - @PostMapping("/getById") - public PermissionDto getById(@RequestBody IdRequest dto) { - return this.service.getById(dto.getId()); - } + @PostMapping("/getById") + public PermissionDto getById(@RequestBody IdRequest dto) { + return this.service.getById(dto.getId()); + } } diff --git a/src/main/java/cn/lihongjie/coal/permission/dto/CreatePermissionDto.java b/src/main/java/cn/lihongjie/coal/permission/dto/CreatePermissionDto.java index c5fc5927..dcfd16b9 100644 --- a/src/main/java/cn/lihongjie/coal/permission/dto/CreatePermissionDto.java +++ b/src/main/java/cn/lihongjie/coal/permission/dto/CreatePermissionDto.java @@ -1,11 +1,13 @@ package cn.lihongjie.coal.permission.dto; import cn.lihongjie.coal.base.dto.CommonDto; -import java.util.List; + import lombok.Data; +import java.util.List; + @Data public class CreatePermissionDto extends CommonDto { - private List resources; + private List resources; } diff --git a/src/main/java/cn/lihongjie/coal/permission/dto/PermissionDto.java b/src/main/java/cn/lihongjie/coal/permission/dto/PermissionDto.java index 45d80db1..df169268 100644 --- a/src/main/java/cn/lihongjie/coal/permission/dto/PermissionDto.java +++ b/src/main/java/cn/lihongjie/coal/permission/dto/PermissionDto.java @@ -1,25 +1,28 @@ package cn.lihongjie.coal.permission.dto; import cn.lihongjie.coal.base.dto.OrgCommonDto; -import java.util.List; + import lombok.Data; + import org.hibernate.annotations.Comment; +import java.util.List; + @Data public class PermissionDto extends OrgCommonDto { - private List resources; + private List resources; - @Data - public static class ResourceDto extends OrgCommonDto { + @Data + public static class ResourceDto extends OrgCommonDto { - // @OneToMany(mappedBy = "parent") - // private List children; + // @OneToMany(mappedBy = "parent") + // private List children; - @Comment("资源类型") - private String type; + @Comment("资源类型") + private String type; - @Comment("资源地址") - private String url; - } + @Comment("资源地址") + private String url; + } } diff --git a/src/main/java/cn/lihongjie/coal/permission/dto/UpdatePermissionDto.java b/src/main/java/cn/lihongjie/coal/permission/dto/UpdatePermissionDto.java index 8f196f08..d8ce7b30 100644 --- a/src/main/java/cn/lihongjie/coal/permission/dto/UpdatePermissionDto.java +++ b/src/main/java/cn/lihongjie/coal/permission/dto/UpdatePermissionDto.java @@ -7,5 +7,5 @@ import lombok.Data; @Data public class UpdatePermissionDto extends CommonDto { - private List resources; + private List resources; } diff --git a/src/main/java/cn/lihongjie/coal/permission/entity/PermissionEntity.java b/src/main/java/cn/lihongjie/coal/permission/entity/PermissionEntity.java index 4c4fc4a3..ff4b3744 100644 --- a/src/main/java/cn/lihongjie/coal/permission/entity/PermissionEntity.java +++ b/src/main/java/cn/lihongjie/coal/permission/entity/PermissionEntity.java @@ -2,31 +2,35 @@ package cn.lihongjie.coal.permission.entity; import cn.lihongjie.coal.base.entity.CommonEntity; import cn.lihongjie.coal.resource.entity.ResourceEntity; + import jakarta.persistence.Cacheable; import jakarta.persistence.Entity; import jakarta.persistence.JoinTable; import jakarta.persistence.ManyToMany; -import java.util.List; + import lombok.Data; + import org.hibernate.annotations.Cache; import org.hibernate.annotations.Comment; +import java.util.List; + @Data @Entity @Comment("权限") @Cacheable public class PermissionEntity extends CommonEntity { - @ManyToMany() - @JoinTable( - foreignKey = - @jakarta.persistence.ForeignKey( - name = "none", - value = jakarta.persistence.ConstraintMode.NO_CONSTRAINT), - inverseForeignKey = - @jakarta.persistence.ForeignKey( - name = "none", - value = jakarta.persistence.ConstraintMode.NO_CONSTRAINT)) - @Cache(usage = org.hibernate.annotations.CacheConcurrencyStrategy.READ_WRITE) - private List resources; + @ManyToMany() + @JoinTable( + foreignKey = + @jakarta.persistence.ForeignKey( + name = "none", + value = jakarta.persistence.ConstraintMode.NO_CONSTRAINT), + inverseForeignKey = + @jakarta.persistence.ForeignKey( + name = "none", + value = jakarta.persistence.ConstraintMode.NO_CONSTRAINT)) + @Cache(usage = org.hibernate.annotations.CacheConcurrencyStrategy.READ_WRITE) + private List resources; } diff --git a/src/main/java/cn/lihongjie/coal/permission/mapper/PermissionMapper.java b/src/main/java/cn/lihongjie/coal/permission/mapper/PermissionMapper.java index daf3d5f4..8d136019 100644 --- a/src/main/java/cn/lihongjie/coal/permission/mapper/PermissionMapper.java +++ b/src/main/java/cn/lihongjie/coal/permission/mapper/PermissionMapper.java @@ -6,20 +6,22 @@ import cn.lihongjie.coal.permission.dto.CreatePermissionDto; import cn.lihongjie.coal.permission.dto.PermissionDto; import cn.lihongjie.coal.permission.dto.UpdatePermissionDto; import cn.lihongjie.coal.permission.entity.PermissionEntity; + import org.mapstruct.Mapper; import org.mapstruct.MappingConstants; import org.mapstruct.MappingTarget; import org.mapstruct.control.DeepClone; @Mapper( - componentModel = MappingConstants.ComponentModel.SPRING, - uses = {CommonMapper.class}, - mappingControl = DeepClone.class) + componentModel = MappingConstants.ComponentModel.SPRING, + uses = {CommonMapper.class}, + mappingControl = DeepClone.class) public interface PermissionMapper - extends BaseMapper { - PermissionDto toDto(PermissionEntity user); + extends BaseMapper< + PermissionEntity, PermissionDto, CreatePermissionDto, UpdatePermissionDto> { + PermissionDto toDto(PermissionEntity user); - PermissionEntity toEntity(CreatePermissionDto request); + PermissionEntity toEntity(CreatePermissionDto request); - void updateEntity(@MappingTarget PermissionEntity entity, UpdatePermissionDto dto); + void updateEntity(@MappingTarget PermissionEntity entity, UpdatePermissionDto dto); } diff --git a/src/main/java/cn/lihongjie/coal/permission/repository/PermissionRepository.java b/src/main/java/cn/lihongjie/coal/permission/repository/PermissionRepository.java index 5319cf62..73c6a8b1 100644 --- a/src/main/java/cn/lihongjie/coal/permission/repository/PermissionRepository.java +++ b/src/main/java/cn/lihongjie/coal/permission/repository/PermissionRepository.java @@ -2,6 +2,7 @@ package cn.lihongjie.coal.permission.repository; import cn.lihongjie.coal.base.dao.BaseRepository; import cn.lihongjie.coal.permission.entity.PermissionEntity; + import org.springframework.stereotype.Repository; @Repository diff --git a/src/main/java/cn/lihongjie/coal/permission/service/PermissionService.java b/src/main/java/cn/lihongjie/coal/permission/service/PermissionService.java index 56db9480..b7f18dff 100644 --- a/src/main/java/cn/lihongjie/coal/permission/service/PermissionService.java +++ b/src/main/java/cn/lihongjie/coal/permission/service/PermissionService.java @@ -9,8 +9,11 @@ import cn.lihongjie.coal.permission.dto.UpdatePermissionDto; import cn.lihongjie.coal.permission.entity.PermissionEntity; import cn.lihongjie.coal.permission.mapper.PermissionMapper; import cn.lihongjie.coal.permission.repository.PermissionRepository; + import jakarta.annotation.PostConstruct; + import lombok.extern.slf4j.Slf4j; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.convert.ConversionService; import org.springframework.data.domain.Page; @@ -22,51 +25,53 @@ import org.springframework.stereotype.Service; @Slf4j public class PermissionService extends BaseService { - @Autowired PermissionRepository repository; + @Autowired PermissionRepository repository; - @Autowired PermissionMapper mapper; + @Autowired PermissionMapper mapper; + @Autowired ConversionService conversionService; - @PostConstruct - public void init() {} + @PostConstruct + public void init() {} - public PermissionDto create(CreatePermissionDto request) { + public PermissionDto create(CreatePermissionDto request) { - PermissionEntity entity = mapper.toEntity(request); + PermissionEntity entity = mapper.toEntity(request); - this.repository.save(entity); - return getById(entity.getId()); - } + this.repository.save(entity); + return getById(entity.getId()); + } - public PermissionDto update(UpdatePermissionDto request) { - PermissionEntity entity = this.repository.get(request.getId()); - this.mapper.updateEntity(entity, request); + public PermissionDto update(UpdatePermissionDto request) { + PermissionEntity entity = this.repository.get(request.getId()); + this.mapper.updateEntity(entity, request); - this.repository.save(entity); + this.repository.save(entity); - return getById(entity.getId()); - } + return getById(entity.getId()); + } - public void delete(IdRequest request) { + public void delete(IdRequest request) { - this.repository.deleteAllById(request.getIds()); - } + this.repository.deleteAllById(request.getIds()); + } - public PermissionDto getById(String id) { + public PermissionDto getById(String id) { - PermissionEntity entity = repository.get(id); + PermissionEntity entity = repository.get(id); - return mapper.toDto(entity); - } + return mapper.toDto(entity); + } - @Autowired ConversionService conversionService; + public Page list(CommonQuery query) { - public Page list(CommonQuery query) { + Page page = + repository.findAll( + query.specification(conversionService), + PageRequest.of( + query.getPageNo(), + query.getPageSize(), + Sort.by(query.getOrders()))); - Page page = - repository.findAll( - query.specification(conversionService), - PageRequest.of(query.getPageNo(), query.getPageSize(), Sort.by(query.getOrders()))); - - return page.map(this.mapper::toDto); - } + return page.map(this.mapper::toDto); + } } diff --git a/src/main/java/cn/lihongjie/coal/resource/controller/ResourceController.java b/src/main/java/cn/lihongjie/coal/resource/controller/ResourceController.java index 5378fd82..88889b65 100644 --- a/src/main/java/cn/lihongjie/coal/resource/controller/ResourceController.java +++ b/src/main/java/cn/lihongjie/coal/resource/controller/ResourceController.java @@ -9,7 +9,7 @@ import cn.lihongjie.coal.resource.dto.ResourceDto; import cn.lihongjie.coal.resource.dto.ResourceTreeDto; import cn.lihongjie.coal.resource.dto.UpdateResourceDto; import cn.lihongjie.coal.resource.service.ResourceService; -import java.util.List; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.web.bind.annotation.PostMapping; @@ -17,51 +17,53 @@ import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; +import java.util.List; + @RequestMapping("/resource") @RestController @SysLog(module = "资源管理") public class ResourceController extends BaseController { - @Autowired ResourceService service; + @Autowired ResourceService service; - @PostMapping("/apiTree") - @SysLog(action = "获取接口树") - public List apiTree() { - return this.service.apiTree(); - } + @PostMapping("/apiTree") + @SysLog(action = "获取接口树") + public List apiTree() { + return this.service.apiTree(); + } - @PostMapping("/menuTree") - @SysLog(action = "获取菜单树") - public List menuTree() { - return this.service.menuTree(); - } + @PostMapping("/menuTree") + @SysLog(action = "获取菜单树") + public List menuTree() { + return this.service.menuTree(); + } - @PostMapping("/create") - @SysLog(action = "新增") - public ResourceDto create(@RequestBody CreateResourceDto dto) { - return this.service.create(dto); - } + @PostMapping("/create") + @SysLog(action = "新增") + public ResourceDto create(@RequestBody CreateResourceDto dto) { + return this.service.create(dto); + } - @PostMapping("/update") - @SysLog(action = "编辑") - public ResourceDto update(@RequestBody UpdateResourceDto dto) { - return this.service.update(dto); - } + @PostMapping("/update") + @SysLog(action = "编辑") + public ResourceDto update(@RequestBody UpdateResourceDto dto) { + return this.service.update(dto); + } - @PostMapping("/delete") - @SysLog(action = "删除") - public Object delete(@RequestBody IdRequest dto) { - this.service.delete(dto); - return true; - } + @PostMapping("/delete") + @SysLog(action = "删除") + public Object delete(@RequestBody IdRequest dto) { + this.service.delete(dto); + return true; + } - @PostMapping("/list") - public Page list(@RequestBody CommonQuery dto) { - return this.service.list(dto); - } + @PostMapping("/list") + public Page list(@RequestBody CommonQuery dto) { + return this.service.list(dto); + } - @PostMapping("/getById") - public ResourceDto getById(@RequestBody IdRequest dto) { - return this.service.getById(dto.getId()); - } + @PostMapping("/getById") + public ResourceDto getById(@RequestBody IdRequest dto) { + return this.service.getById(dto.getId()); + } } diff --git a/src/main/java/cn/lihongjie/coal/resource/dto/CreateResourceDto.java b/src/main/java/cn/lihongjie/coal/resource/dto/CreateResourceDto.java index 279ec860..789a4f9c 100644 --- a/src/main/java/cn/lihongjie/coal/resource/dto/CreateResourceDto.java +++ b/src/main/java/cn/lihongjie/coal/resource/dto/CreateResourceDto.java @@ -1,35 +1,37 @@ package cn.lihongjie.coal.resource.dto; import cn.lihongjie.coal.base.dto.CommonDto; + import lombok.Data; + import org.hibernate.annotations.Comment; @Data public class CreateResourceDto extends CommonDto { - @Comment("资源类型") - private String type; + @Comment("资源类型") + private String type; - @Comment("资源地址") - private String url; + @Comment("资源地址") + private String url; - private String parent; + private String parent; - @Comment("需要机构管理员权限") - private Boolean orgAdmin; + @Comment("需要机构管理员权限") + private Boolean orgAdmin; - @Comment("需要系统管理员权限") - private Boolean sysAdmin; + @Comment("需要系统管理员权限") + private Boolean sysAdmin; - @Comment("匿名用户可以访问") - private Boolean anonymous; + @Comment("匿名用户可以访问") + private Boolean anonymous; - @Comment("图标") - private String icon; + @Comment("图标") + private String icon; - @Comment("是否可见") - private Boolean visible; + @Comment("是否可见") + private Boolean visible; - @Comment("其他数据") - private String metadata; + @Comment("其他数据") + private String metadata; } diff --git a/src/main/java/cn/lihongjie/coal/resource/dto/ResourceDto.java b/src/main/java/cn/lihongjie/coal/resource/dto/ResourceDto.java index acb94908..94070d4c 100644 --- a/src/main/java/cn/lihongjie/coal/resource/dto/ResourceDto.java +++ b/src/main/java/cn/lihongjie/coal/resource/dto/ResourceDto.java @@ -1,37 +1,39 @@ package cn.lihongjie.coal.resource.dto; import cn.lihongjie.coal.base.dto.CommonDto; + import lombok.Data; + import org.hibernate.annotations.Comment; @Data public class ResourceDto extends CommonDto { - @Comment("资源类型") - private String type; + @Comment("资源类型") + private String type; - private String typeName; + private String typeName; - @Comment("资源地址") - private String url; + @Comment("资源地址") + private String url; - @Comment("需要机构管理员权限") - private Boolean orgAdmin; + @Comment("需要机构管理员权限") + private Boolean orgAdmin; - @Comment("需要系统管理员权限") - private Boolean sysAdmin; + @Comment("需要系统管理员权限") + private Boolean sysAdmin; - @Comment("匿名用户可以访问") - private Boolean anonymous; + @Comment("匿名用户可以访问") + private Boolean anonymous; - @Comment("图标") - private String icon; + @Comment("图标") + private String icon; - @Comment("是否可见") - private Boolean visible; + @Comment("是否可见") + private Boolean visible; - @Comment("其他数据") - private String metadata; + @Comment("其他数据") + private String metadata; - private String parent; + private String parent; } diff --git a/src/main/java/cn/lihongjie/coal/resource/dto/ResourceTreeDto.java b/src/main/java/cn/lihongjie/coal/resource/dto/ResourceTreeDto.java index 332ea010..cbfa51b3 100644 --- a/src/main/java/cn/lihongjie/coal/resource/dto/ResourceTreeDto.java +++ b/src/main/java/cn/lihongjie/coal/resource/dto/ResourceTreeDto.java @@ -6,5 +6,5 @@ import lombok.Data; @Data public class ResourceTreeDto extends ResourceDto { - private List children; + private List children; } diff --git a/src/main/java/cn/lihongjie/coal/resource/dto/UpdateCreateResourceDto.java b/src/main/java/cn/lihongjie/coal/resource/dto/UpdateCreateResourceDto.java index 376c293e..2e0cfcfc 100644 --- a/src/main/java/cn/lihongjie/coal/resource/dto/UpdateCreateResourceDto.java +++ b/src/main/java/cn/lihongjie/coal/resource/dto/UpdateCreateResourceDto.java @@ -1,17 +1,19 @@ package cn.lihongjie.coal.resource.dto; import cn.lihongjie.coal.base.dto.CommonDto; + import lombok.Data; + import org.hibernate.annotations.Comment; @Data public class UpdateCreateResourceDto extends CommonDto { - @Comment("资源类型") - private String type; + @Comment("资源类型") + private String type; - @Comment("资源地址") - private String url; + @Comment("资源地址") + private String url; - private String parent; + private String parent; } diff --git a/src/main/java/cn/lihongjie/coal/resource/dto/UpdateResourceDto.java b/src/main/java/cn/lihongjie/coal/resource/dto/UpdateResourceDto.java index 8a23faac..c026e6ea 100644 --- a/src/main/java/cn/lihongjie/coal/resource/dto/UpdateResourceDto.java +++ b/src/main/java/cn/lihongjie/coal/resource/dto/UpdateResourceDto.java @@ -1,35 +1,37 @@ package cn.lihongjie.coal.resource.dto; import cn.lihongjie.coal.base.dto.CommonDto; + import lombok.Data; + import org.hibernate.annotations.Comment; @Data public class UpdateResourceDto extends CommonDto { - @Comment("资源类型") - private String type; + @Comment("资源类型") + private String type; - @Comment("资源地址") - private String url; + @Comment("资源地址") + private String url; - private String parent; + private String parent; - @Comment("需要机构管理员权限") - private Boolean orgAdmin; + @Comment("需要机构管理员权限") + private Boolean orgAdmin; - @Comment("需要系统管理员权限") - private Boolean sysAdmin; + @Comment("需要系统管理员权限") + private Boolean sysAdmin; - @Comment("匿名用户可以访问") - private Boolean anonymous; + @Comment("匿名用户可以访问") + private Boolean anonymous; - @Comment("图标") - private String icon; + @Comment("图标") + private String icon; - @Comment("是否可见") - private Boolean visible; + @Comment("是否可见") + private Boolean visible; - @Comment("其他数据") - private String metadata; + @Comment("其他数据") + private String metadata; } diff --git a/src/main/java/cn/lihongjie/coal/resource/entity/ResourceEntity.java b/src/main/java/cn/lihongjie/coal/resource/entity/ResourceEntity.java index f7aae338..e4226c4d 100644 --- a/src/main/java/cn/lihongjie/coal/resource/entity/ResourceEntity.java +++ b/src/main/java/cn/lihongjie/coal/resource/entity/ResourceEntity.java @@ -2,16 +2,21 @@ package cn.lihongjie.coal.resource.entity; import cn.lihongjie.coal.base.entity.CommonEntity; import cn.lihongjie.coal.permission.entity.PermissionEntity; + import io.vavr.collection.Stream; + import jakarta.persistence.*; -import java.util.ArrayList; -import java.util.List; + import lombok.Data; import lombok.extern.slf4j.Slf4j; + import org.apache.commons.lang3.StringUtils; import org.hibernate.annotations.Comment; import org.hibernate.annotations.Formula; +import java.util.ArrayList; +import java.util.List; + @Data @Entity @Comment("资源") @@ -20,133 +25,137 @@ import org.hibernate.annotations.Formula; @Cacheable public class ResourceEntity extends CommonEntity { - @ManyToMany(mappedBy = "resources") - @org.hibernate.annotations.Cache( - usage = org.hibernate.annotations.CacheConcurrencyStrategy.READ_WRITE) - private List permissions; + @ManyToMany(mappedBy = "resources") + @org.hibernate.annotations.Cache( + usage = org.hibernate.annotations.CacheConcurrencyStrategy.READ_WRITE) + private List permissions; - @OneToMany(mappedBy = "parent", cascade = CascadeType.ALL) - @org.hibernate.annotations.Cache( - usage = org.hibernate.annotations.CacheConcurrencyStrategy.READ_WRITE) - private List children; + @OneToMany(mappedBy = "parent", cascade = CascadeType.ALL) + @org.hibernate.annotations.Cache( + usage = org.hibernate.annotations.CacheConcurrencyStrategy.READ_WRITE) + private List children; - @ManyToOne - @JoinColumn(name = "parent_id", foreignKey = @ForeignKey(value = ConstraintMode.NO_CONSTRAINT)) - private ResourceEntity parent; + @ManyToOne + @JoinColumn(name = "parent_id", foreignKey = @ForeignKey(value = ConstraintMode.NO_CONSTRAINT)) + private ResourceEntity parent; - @Comment("资源类型 0 菜单 1 按钮 3 url") - private String type; + @Comment("资源类型 0 菜单 1 按钮 3 url") + private String type; - @Formula( - "(select i.name\n" - + "from t_dictionary d,\n" - + " t_dictionary_item i\n" - + "where d.id = i.dictionary_id\n" - + " and d.code = 'resource.type'\n" - + " and i.code = type)") - private String typeName; + @Formula( + "(select i.name\n" + + "from t_dictionary d,\n" + + " t_dictionary_item i\n" + + "where d.id = i.dictionary_id\n" + + " and d.code = 'resource.type'\n" + + " and i.code = type)") + private String typeName; - @Comment("资源地址") - private String url; + @Comment("资源地址") + private String url; - @Comment("需要机构管理员权限") - private Boolean orgAdmin = false; + @Comment("需要机构管理员权限") + private Boolean orgAdmin = false; - @Comment("需要系统管理员权限") - private Boolean sysAdmin = false; + @Comment("需要系统管理员权限") + private Boolean sysAdmin = false; - @Comment("匿名用户可以访问") - private Boolean anonymous = false; + @Comment("匿名用户可以访问") + private Boolean anonymous = false; - @Comment("图标") - private String icon; + @Comment("图标") + private String icon; - @Comment("是否可见") - private Boolean visible; + @Comment("是否可见") + private Boolean visible; - @Comment("其他数据") - private String metadata; + @Comment("其他数据") + private String metadata; - public void addChildren(ResourceEntity newRs) { + private static String getParent(String path) { + log.debug("getParent {}", path); - // log.debug();("addChildren1 {} {}", this.getUrl(), newRs.getUrl()); - if (this.children == null) { - this.children = new ArrayList<>(); + return "/" + StringUtils.join(Stream.of(StringUtils.split(path, "/")).dropRight(1), "/"); } - if (newRs.getUrl().equals(this.getUrl())) { - log.debug("添加子节点 当前url {} 子节点url {} 退出....", this.getUrl(), newRs.getUrl()); - return; - } + public void addChildren(ResourceEntity newRs) { - for (ResourceEntity child : this.children) { - - if (newRs.getUrl().equals(child.getUrl())) { - return; - } - - boolean isChildren = isChildren(newRs, child); - log.debug("isChildren {} c: {} p: {}", isChildren, newRs.getUrl(), child.getUrl()); - if (isChildren) { - - child.addChildren(newRs); - - return; - } - } - - ResourceEntity r = new ResourceEntity(); - - String tmp = newRs.getUrl(); - - while (!isSamePath(this.getUrl(), getParent(tmp))) { - tmp = getParent(tmp); - } - - r.setUrl(tmp); - - r.setName(r.getUrl()); - r.setType("3"); - r.setParent(this); - r.setChildren(new ArrayList<>()); - r.setCode(r.getUrl()); - - this.children.add(r); - // log.debug();("addChildren2 {} {}", r.getUrl(), this.getUrl()); - log.debug("添加子节点 当前url {} 子节点url {} 添加一个新节点 {} ", this.getUrl(), newRs.getUrl(), r.getUrl()); - - r.addChildren(newRs); - } - - private boolean isChildren(ResourceEntity c, ResourceEntity p) { - - if (!isSamePath(c.getUrl(), p.getUrl())) { - // 判断list是否有相同前缀 - - String[] pl = StringUtils.split(p.getUrl(), "/"); - String[] cl = StringUtils.split(c.getUrl(), "/"); - - for (int i = 0; i < pl.length; i++) { - if (i >= cl.length) { - return false; + // log.debug();("addChildren1 {} {}", this.getUrl(), newRs.getUrl()); + if (this.children == null) { + this.children = new ArrayList<>(); } - if (!pl[i].equalsIgnoreCase(cl[i])) { - return false; + + if (newRs.getUrl().equals(this.getUrl())) { + log.debug("添加子节点 当前url {} 子节点url {} 退出....", this.getUrl(), newRs.getUrl()); + return; } - } - return true; + for (ResourceEntity child : this.children) { + + if (newRs.getUrl().equals(child.getUrl())) { + return; + } + + boolean isChildren = isChildren(newRs, child); + log.debug("isChildren {} c: {} p: {}", isChildren, newRs.getUrl(), child.getUrl()); + if (isChildren) { + + child.addChildren(newRs); + + return; + } + } + + ResourceEntity r = new ResourceEntity(); + + String tmp = newRs.getUrl(); + + while (!isSamePath(this.getUrl(), getParent(tmp))) { + tmp = getParent(tmp); + } + + r.setUrl(tmp); + + r.setName(r.getUrl()); + r.setType("3"); + r.setParent(this); + r.setChildren(new ArrayList<>()); + r.setCode(r.getUrl()); + + this.children.add(r); + // log.debug();("addChildren2 {} {}", r.getUrl(), this.getUrl()); + log.debug( + "添加子节点 当前url {} 子节点url {} 添加一个新节点 {} ", + this.getUrl(), + newRs.getUrl(), + r.getUrl()); + + r.addChildren(newRs); } - return false; - } - private boolean isSamePath(String a, String b) { - return a.equalsIgnoreCase(b) || (a + "/").equalsIgnoreCase(b); - } + private boolean isChildren(ResourceEntity c, ResourceEntity p) { - private static String getParent(String path) { - log.debug("getParent {}", path); + if (!isSamePath(c.getUrl(), p.getUrl())) { + // 判断list是否有相同前缀 - return "/" + StringUtils.join(Stream.of(StringUtils.split(path, "/")).dropRight(1), "/"); - } + String[] pl = StringUtils.split(p.getUrl(), "/"); + String[] cl = StringUtils.split(c.getUrl(), "/"); + + for (int i = 0; i < pl.length; i++) { + if (i >= cl.length) { + return false; + } + if (!pl[i].equalsIgnoreCase(cl[i])) { + return false; + } + } + + return true; + } + return false; + } + + private boolean isSamePath(String a, String b) { + return a.equalsIgnoreCase(b) || (a + "/").equalsIgnoreCase(b); + } } diff --git a/src/main/java/cn/lihongjie/coal/resource/mapper/ResourceMapper.java b/src/main/java/cn/lihongjie/coal/resource/mapper/ResourceMapper.java index 73ec3e79..09d936c4 100644 --- a/src/main/java/cn/lihongjie/coal/resource/mapper/ResourceMapper.java +++ b/src/main/java/cn/lihongjie/coal/resource/mapper/ResourceMapper.java @@ -7,28 +7,30 @@ import cn.lihongjie.coal.resource.dto.ResourceDto; import cn.lihongjie.coal.resource.dto.ResourceTreeDto; import cn.lihongjie.coal.resource.dto.UpdateResourceDto; import cn.lihongjie.coal.resource.entity.ResourceEntity; -import java.util.List; + import org.mapstruct.Mapper; import org.mapstruct.MappingConstants; import org.mapstruct.MappingTarget; import org.mapstruct.Mappings; import org.mapstruct.control.DeepClone; +import java.util.List; + @Mapper( - componentModel = MappingConstants.ComponentModel.SPRING, - uses = {CommonMapper.class}, - mappingControl = DeepClone.class) + componentModel = MappingConstants.ComponentModel.SPRING, + uses = {CommonMapper.class}, + mappingControl = DeepClone.class) public interface ResourceMapper - extends BaseMapper { - @Mappings({@org.mapstruct.Mapping(target = "parent", source = "parent.id")}) - ResourceDto toDto(ResourceEntity user); + extends BaseMapper { + @Mappings({@org.mapstruct.Mapping(target = "parent", source = "parent.id")}) + ResourceDto toDto(ResourceEntity user); - ResourceEntity toEntity(CreateResourceDto request); + ResourceEntity toEntity(CreateResourceDto request); - void updateEntity(@MappingTarget ResourceEntity entity, UpdateResourceDto dto); + void updateEntity(@MappingTarget ResourceEntity entity, UpdateResourceDto dto); - List toTreeDto(List byTypeAndParentIsNull); + List toTreeDto(List byTypeAndParentIsNull); - @Mappings({@org.mapstruct.Mapping(target = "parent", source = "parent.id")}) - ResourceTreeDto toTreeDto(ResourceEntity byTypeAndParentIsNull); + @Mappings({@org.mapstruct.Mapping(target = "parent", source = "parent.id")}) + ResourceTreeDto toTreeDto(ResourceEntity byTypeAndParentIsNull); } diff --git a/src/main/java/cn/lihongjie/coal/resource/repository/ResourceRepository.java b/src/main/java/cn/lihongjie/coal/resource/repository/ResourceRepository.java index 3cb63c9e..688521e7 100644 --- a/src/main/java/cn/lihongjie/coal/resource/repository/ResourceRepository.java +++ b/src/main/java/cn/lihongjie/coal/resource/repository/ResourceRepository.java @@ -2,12 +2,14 @@ package cn.lihongjie.coal.resource.repository; import cn.lihongjie.coal.base.dao.BaseRepository; import cn.lihongjie.coal.resource.entity.ResourceEntity; -import java.util.List; + import org.springframework.stereotype.Repository; +import java.util.List; + @Repository public interface ResourceRepository extends BaseRepository { - // @EntityGraph(attributePaths = {"children"}) - List findAllByTypeAndParentIsNull(String type); + // @EntityGraph(attributePaths = {"children"}) + List findAllByTypeAndParentIsNull(String type); } diff --git a/src/main/java/cn/lihongjie/coal/resource/service/ResourceService.java b/src/main/java/cn/lihongjie/coal/resource/service/ResourceService.java index 9b85d982..c9a52103 100644 --- a/src/main/java/cn/lihongjie/coal/resource/service/ResourceService.java +++ b/src/main/java/cn/lihongjie/coal/resource/service/ResourceService.java @@ -10,6 +10,7 @@ import cn.lihongjie.coal.resource.dto.UpdateResourceDto; import cn.lihongjie.coal.resource.entity.ResourceEntity; import cn.lihongjie.coal.resource.mapper.ResourceMapper; import cn.lihongjie.coal.resource.repository.ResourceRepository; + import jakarta.annotation.PostConstruct; import jakarta.persistence.EntityManager; import jakarta.persistence.PersistenceContext; @@ -17,11 +18,9 @@ import jakarta.persistence.criteria.CriteriaBuilder; import jakarta.persistence.criteria.CriteriaQuery; import jakarta.persistence.criteria.Predicate; import jakarta.persistence.criteria.Root; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Optional; + import lombok.extern.slf4j.Slf4j; + import org.apache.commons.lang3.StringUtils; import org.hibernate.Cache; import org.hibernate.Session; @@ -38,170 +37,178 @@ import org.springframework.web.servlet.mvc.method.RequestMappingInfo; import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping; import org.springframework.web.util.pattern.PathPattern; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Optional; + @Service @Slf4j public class ResourceService extends BaseService { - @Autowired ResourceRepository repository; + @Autowired ResourceRepository repository; - @Autowired ResourceMapper mapper; + @Autowired ResourceMapper mapper; + @Autowired ConversionService conversionService; + @Autowired RequestMappingHandlerMapping requestMappingHandlerMapping; + @PersistenceContext EntityManager entityManager; - @PostConstruct - public void init() {} + @PostConstruct + public void init() {} - public ResourceDto create(CreateResourceDto request) { + public ResourceDto create(CreateResourceDto request) { - ResourceEntity entity = mapper.toEntity(request); + ResourceEntity entity = mapper.toEntity(request); - this.repository.save(entity); - entityManager - .unwrap(Session.class) - .getSessionFactory() - .getCache() - .evictCollectionData("cn.lihongjie.coal.resource.entity.ResourceEntity.children"); + this.repository.save(entity); + entityManager + .unwrap(Session.class) + .getSessionFactory() + .getCache() + .evictCollectionData("cn.lihongjie.coal.resource.entity.ResourceEntity.children"); - return getById(entity.getId()); - } - - public ResourceDto update(UpdateResourceDto request) { - ResourceEntity entity = this.repository.get(request.getId()); - this.mapper.updateEntity(entity, request); - - this.repository.save(entity); - entityManager - .unwrap(Session.class) - .getSessionFactory() - .getCache() - .evictCollectionData("cn.lihongjie.coal.resource.entity.ResourceEntity.children"); - - return getById(entity.getId()); - } - - public void delete(IdRequest request) { - - this.repository.deleteAllById(request.getIds()); - - Cache cache = entityManager.unwrap(Session.class).getSessionFactory().getCache(); - cache.evictCollectionData("cn.lihongjie.coal.resource.entity.ResourceEntity.children"); - } - - public ResourceDto getById(String id) { - - ResourceEntity entity = repository.get(id); - - return mapper.toDto(entity); - } - - @Autowired ConversionService conversionService; - - public Page list(CommonQuery query) { - - Page page = - repository.findAll( - query.specification(conversionService), - PageRequest.of(query.getPageNo(), query.getPageSize(), Sort.by(query.getOrders()))); - - return page.map(this.mapper::toDto); - } - - public Optional findUrl(String requestURL) { - - return findAll( - new Specification() { - @Override - public Predicate toPredicate( - Root root, - CriteriaQuery query, - CriteriaBuilder criteriaBuilder) { - return criteriaBuilder.and( - criteriaBuilder.equal(root.get("code"), requestURL), - criteriaBuilder.equal(root.get("type"), "3")); - } - }) - .stream() - .findFirst(); - } - - @Autowired RequestMappingHandlerMapping requestMappingHandlerMapping; - - @PersistenceContext EntityManager entityManager; - - @Transactional - public void initUrlResource() { - - List all = - findAll( - new Specification() { - @Override - public Predicate toPredicate( - Root root, - CriteriaQuery query, - CriteriaBuilder criteriaBuilder) { - return criteriaBuilder.and( - criteriaBuilder.equal(root.get("url"), "/"), - criteriaBuilder.equal(root.get("type"), "3")); - } - }); - - ResourceEntity root = null; - - if (all.isEmpty()) { - - ResourceEntity entity = new ResourceEntity(); - entity.setCode("/"); - entity.setType("3"); - entity.setName("接口资源"); - entity.setUrl("/"); - this.save(entity); - root = entity; - } else { - - root = all.get(0); + return getById(entity.getId()); } - List allUrls = getAllUrls(); + public ResourceDto update(UpdateResourceDto request) { + ResourceEntity entity = this.repository.get(request.getId()); + this.mapper.updateEntity(entity, request); - for (String allUrl : allUrls) { - ResourceEntity entity = new ResourceEntity(); - entity.setCode(allUrl); - entity.setType("3"); - entity.setName(""); - entity.setUrl(allUrl); - entity.setAnonymous(StringUtils.equalsAny(allUrl, "/login", "/logout", "/genCaptcha")); + this.repository.save(entity); + entityManager + .unwrap(Session.class) + .getSessionFactory() + .getCache() + .evictCollectionData("cn.lihongjie.coal.resource.entity.ResourceEntity.children"); - root.addChildren(entity); + return getById(entity.getId()); } - this.save(root); - } + public void delete(IdRequest request) { - private List getAllUrls() { - Map handlerMethods = - requestMappingHandlerMapping.getHandlerMethods(); - List urls = new ArrayList<>(); - for (Map.Entry entry : handlerMethods.entrySet()) { + this.repository.deleteAllById(request.getIds()); - RequestMappingInfo info = entry.getKey(); - HandlerMethod method = entry.getValue(); - if (!method.getMethod().getDeclaringClass().getCanonicalName().startsWith("cn.lihongjie")) { - continue; - } - for (PathPattern pattern : info.getPathPatternsCondition().getPatterns()) { - String ps = pattern.getPatternString(); - - urls.add(ps); - } + Cache cache = entityManager.unwrap(Session.class).getSessionFactory().getCache(); + cache.evictCollectionData("cn.lihongjie.coal.resource.entity.ResourceEntity.children"); } - return urls; - } + public ResourceDto getById(String id) { - public List menuTree() { + ResourceEntity entity = repository.get(id); - return this.mapper.toTreeDto(this.repository.findAllByTypeAndParentIsNull("0")); - } + return mapper.toDto(entity); + } - public List apiTree() { - return this.mapper.toTreeDto(this.repository.findAllByTypeAndParentIsNull("3")); - } + public Page list(CommonQuery query) { + + Page page = + repository.findAll( + query.specification(conversionService), + PageRequest.of( + query.getPageNo(), + query.getPageSize(), + Sort.by(query.getOrders()))); + + return page.map(this.mapper::toDto); + } + + public Optional findUrl(String requestURL) { + + return findAll( + new Specification() { + @Override + public Predicate toPredicate( + Root root, + CriteriaQuery query, + CriteriaBuilder criteriaBuilder) { + return criteriaBuilder.and( + criteriaBuilder.equal(root.get("code"), requestURL), + criteriaBuilder.equal(root.get("type"), "3")); + } + }) + .stream() + .findFirst(); + } + + @Transactional + public void initUrlResource() { + + List all = + findAll( + new Specification() { + @Override + public Predicate toPredicate( + Root root, + CriteriaQuery query, + CriteriaBuilder criteriaBuilder) { + return criteriaBuilder.and( + criteriaBuilder.equal(root.get("url"), "/"), + criteriaBuilder.equal(root.get("type"), "3")); + } + }); + + ResourceEntity root = null; + + if (all.isEmpty()) { + + ResourceEntity entity = new ResourceEntity(); + entity.setCode("/"); + entity.setType("3"); + entity.setName("接口资源"); + entity.setUrl("/"); + this.save(entity); + root = entity; + } else { + + root = all.get(0); + } + + List allUrls = getAllUrls(); + + for (String allUrl : allUrls) { + ResourceEntity entity = new ResourceEntity(); + entity.setCode(allUrl); + entity.setType("3"); + entity.setName(""); + entity.setUrl(allUrl); + entity.setAnonymous(StringUtils.equalsAny(allUrl, "/login", "/logout", "/genCaptcha")); + + root.addChildren(entity); + } + + this.save(root); + } + + private List getAllUrls() { + Map handlerMethods = + requestMappingHandlerMapping.getHandlerMethods(); + List urls = new ArrayList<>(); + for (Map.Entry entry : handlerMethods.entrySet()) { + + RequestMappingInfo info = entry.getKey(); + HandlerMethod method = entry.getValue(); + if (!method.getMethod() + .getDeclaringClass() + .getCanonicalName() + .startsWith("cn.lihongjie")) { + continue; + } + for (PathPattern pattern : info.getPathPatternsCondition().getPatterns()) { + String ps = pattern.getPatternString(); + + urls.add(ps); + } + } + + return urls; + } + + public List menuTree() { + + return this.mapper.toTreeDto(this.repository.findAllByTypeAndParentIsNull("0")); + } + + public List apiTree() { + return this.mapper.toTreeDto(this.repository.findAllByTypeAndParentIsNull("3")); + } } diff --git a/src/main/java/cn/lihongjie/coal/role/controller/RoleController.java b/src/main/java/cn/lihongjie/coal/role/controller/RoleController.java index 61a93b22..c24de1c2 100644 --- a/src/main/java/cn/lihongjie/coal/role/controller/RoleController.java +++ b/src/main/java/cn/lihongjie/coal/role/controller/RoleController.java @@ -9,6 +9,7 @@ import cn.lihongjie.coal.role.dto.CreateRoleDto; import cn.lihongjie.coal.role.dto.RoleDto; import cn.lihongjie.coal.role.dto.UpdateRoleDto; import cn.lihongjie.coal.role.service.RoleService; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.transaction.annotation.Transactional; @@ -24,34 +25,34 @@ import org.springframework.web.bind.annotation.RestController; @Transactional public class RoleController extends BaseController { - @Autowired RoleService service; + @Autowired RoleService service; - @PostMapping("/create") - @SysLog(action = "新增") - public RoleDto create(@RequestBody CreateRoleDto dto) { - return this.service.create(dto); - } + @PostMapping("/create") + @SysLog(action = "新增") + public RoleDto create(@RequestBody CreateRoleDto dto) { + return this.service.create(dto); + } - @PostMapping("/update") - @SysLog(action = "编辑") - public RoleDto update(@RequestBody UpdateRoleDto dto) { - return this.service.update(dto); - } + @PostMapping("/update") + @SysLog(action = "编辑") + public RoleDto update(@RequestBody UpdateRoleDto dto) { + return this.service.update(dto); + } - @PostMapping("/delete") - @SysLog(action = "删除") - public Object delete(@RequestBody IdRequest dto) { - this.service.delete(dto); - return true; - } + @PostMapping("/delete") + @SysLog(action = "删除") + public Object delete(@RequestBody IdRequest dto) { + this.service.delete(dto); + return true; + } - @PostMapping("/list") - public Page list(@RequestBody CommonQuery dto) { - return this.service.list(dto); - } + @PostMapping("/list") + public Page list(@RequestBody CommonQuery dto) { + return this.service.list(dto); + } - @PostMapping("/getById") - public RoleDto getById(@RequestBody IdRequest dto) { - return this.service.getById(dto.getId()); - } + @PostMapping("/getById") + public RoleDto getById(@RequestBody IdRequest dto) { + return this.service.getById(dto.getId()); + } } diff --git a/src/main/java/cn/lihongjie/coal/role/dto/CreateRoleDto.java b/src/main/java/cn/lihongjie/coal/role/dto/CreateRoleDto.java index 2a124698..1fdbfaa2 100644 --- a/src/main/java/cn/lihongjie/coal/role/dto/CreateRoleDto.java +++ b/src/main/java/cn/lihongjie/coal/role/dto/CreateRoleDto.java @@ -7,5 +7,5 @@ import lombok.Data; @Data public class CreateRoleDto extends OrgCommonDto { - private List permissions; + private List permissions; } diff --git a/src/main/java/cn/lihongjie/coal/role/dto/RoleDto.java b/src/main/java/cn/lihongjie/coal/role/dto/RoleDto.java index 6c90f715..def1e60a 100644 --- a/src/main/java/cn/lihongjie/coal/role/dto/RoleDto.java +++ b/src/main/java/cn/lihongjie/coal/role/dto/RoleDto.java @@ -7,8 +7,8 @@ import lombok.Data; @Data public class RoleDto extends OrgCommonDto { - private List permissions; + private List permissions; - @Data - public static class PermissionDto extends OrgCommonDto {} + @Data + public static class PermissionDto extends OrgCommonDto {} } diff --git a/src/main/java/cn/lihongjie/coal/role/dto/UpdateRoleDto.java b/src/main/java/cn/lihongjie/coal/role/dto/UpdateRoleDto.java index 0086fb07..19561f6a 100644 --- a/src/main/java/cn/lihongjie/coal/role/dto/UpdateRoleDto.java +++ b/src/main/java/cn/lihongjie/coal/role/dto/UpdateRoleDto.java @@ -7,5 +7,5 @@ import lombok.Data; @Data public class UpdateRoleDto extends OrgCommonDto { - private List permissions; + private List permissions; } diff --git a/src/main/java/cn/lihongjie/coal/role/entity/RoleEntity.java b/src/main/java/cn/lihongjie/coal/role/entity/RoleEntity.java index 0bc4c0b3..dccf9510 100644 --- a/src/main/java/cn/lihongjie/coal/role/entity/RoleEntity.java +++ b/src/main/java/cn/lihongjie/coal/role/entity/RoleEntity.java @@ -3,23 +3,27 @@ package cn.lihongjie.coal.role.entity; import cn.lihongjie.coal.base.entity.OrgCommonEntity; import cn.lihongjie.coal.permission.entity.PermissionEntity; import cn.lihongjie.coal.user.entity.UserEntity; + import jakarta.persistence.Cacheable; import jakarta.persistence.Entity; import jakarta.persistence.ManyToMany; -import java.util.List; + import lombok.Data; + import org.hibernate.annotations.Cache; +import java.util.List; + @Entity @Data @Cacheable public class RoleEntity extends OrgCommonEntity { - @ManyToMany(mappedBy = "roles") - @Cache(usage = org.hibernate.annotations.CacheConcurrencyStrategy.READ_WRITE) - private List users; + @ManyToMany(mappedBy = "roles") + @Cache(usage = org.hibernate.annotations.CacheConcurrencyStrategy.READ_WRITE) + private List users; - @ManyToMany - @Cache(usage = org.hibernate.annotations.CacheConcurrencyStrategy.READ_WRITE) - private List permissions; + @ManyToMany + @Cache(usage = org.hibernate.annotations.CacheConcurrencyStrategy.READ_WRITE) + private List permissions; } diff --git a/src/main/java/cn/lihongjie/coal/role/mapper/RoleMapper.java b/src/main/java/cn/lihongjie/coal/role/mapper/RoleMapper.java index 32d1e92c..86fa16f4 100644 --- a/src/main/java/cn/lihongjie/coal/role/mapper/RoleMapper.java +++ b/src/main/java/cn/lihongjie/coal/role/mapper/RoleMapper.java @@ -6,12 +6,13 @@ import cn.lihongjie.coal.role.dto.CreateRoleDto; import cn.lihongjie.coal.role.dto.RoleDto; import cn.lihongjie.coal.role.dto.UpdateRoleDto; import cn.lihongjie.coal.role.entity.RoleEntity; + import org.mapstruct.Mapper; import org.mapstruct.MappingConstants; import org.mapstruct.control.DeepClone; @Mapper( - componentModel = MappingConstants.ComponentModel.SPRING, - uses = {CommonMapper.class}, - mappingControl = DeepClone.class) + componentModel = MappingConstants.ComponentModel.SPRING, + uses = {CommonMapper.class}, + mappingControl = DeepClone.class) public interface RoleMapper extends BaseMapper {} diff --git a/src/main/java/cn/lihongjie/coal/role/repository/RoleRepository.java b/src/main/java/cn/lihongjie/coal/role/repository/RoleRepository.java index 3d3c4a67..631b0306 100644 --- a/src/main/java/cn/lihongjie/coal/role/repository/RoleRepository.java +++ b/src/main/java/cn/lihongjie/coal/role/repository/RoleRepository.java @@ -2,6 +2,7 @@ package cn.lihongjie.coal.role.repository; import cn.lihongjie.coal.base.dao.BaseRepository; import cn.lihongjie.coal.role.entity.RoleEntity; + import org.springframework.stereotype.Repository; @Repository diff --git a/src/main/java/cn/lihongjie/coal/role/service/RoleService.java b/src/main/java/cn/lihongjie/coal/role/service/RoleService.java index 6e5bfdfe..add40c93 100644 --- a/src/main/java/cn/lihongjie/coal/role/service/RoleService.java +++ b/src/main/java/cn/lihongjie/coal/role/service/RoleService.java @@ -9,8 +9,11 @@ import cn.lihongjie.coal.role.dto.UpdateRoleDto; import cn.lihongjie.coal.role.entity.RoleEntity; import cn.lihongjie.coal.role.mapper.RoleMapper; import cn.lihongjie.coal.role.repository.RoleRepository; + import jakarta.annotation.PostConstruct; + import lombok.extern.slf4j.Slf4j; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.convert.ConversionService; import org.springframework.data.domain.Page; @@ -22,51 +25,53 @@ import org.springframework.stereotype.Service; @Slf4j public class RoleService extends BaseService { - @Autowired RoleRepository repository; + @Autowired RoleRepository repository; - @Autowired RoleMapper mapper; + @Autowired RoleMapper mapper; + @Autowired ConversionService conversionService; - @PostConstruct - public void init() {} + @PostConstruct + public void init() {} - public RoleDto create(CreateRoleDto request) { + public RoleDto create(CreateRoleDto request) { - RoleEntity entity = mapper.toEntity(request); + RoleEntity entity = mapper.toEntity(request); - this.repository.save(entity); - return getById(entity.getId()); - } + this.repository.save(entity); + return getById(entity.getId()); + } - public RoleDto update(UpdateRoleDto request) { - RoleEntity entity = this.repository.get(request.getId()); - this.mapper.updateEntity(entity, request); + public RoleDto update(UpdateRoleDto request) { + RoleEntity entity = this.repository.get(request.getId()); + this.mapper.updateEntity(entity, request); - this.repository.save(entity); + this.repository.save(entity); - return getById(entity.getId()); - } + return getById(entity.getId()); + } - public void delete(IdRequest request) { + public void delete(IdRequest request) { - this.repository.deleteAllById(request.getIds()); - } + this.repository.deleteAllById(request.getIds()); + } - public RoleDto getById(String id) { + public RoleDto getById(String id) { - RoleEntity entity = repository.get(id); + RoleEntity entity = repository.get(id); - return mapper.toDto(entity); - } + return mapper.toDto(entity); + } - @Autowired ConversionService conversionService; + public Page list(CommonQuery query) { - public Page list(CommonQuery query) { + Page page = + repository.findAll( + query.specification(conversionService), + PageRequest.of( + query.getPageNo(), + query.getPageSize(), + Sort.by(query.getOrders()))); - Page page = - repository.findAll( - query.specification(conversionService), - PageRequest.of(query.getPageNo(), query.getPageSize(), Sort.by(query.getOrders()))); - - return page.map(this.mapper::toDto); - } + return page.map(this.mapper::toDto); + } } diff --git a/src/main/java/cn/lihongjie/coal/runner/InitDataRunner.java b/src/main/java/cn/lihongjie/coal/runner/InitDataRunner.java index 9f88c252..2dbf36e6 100644 --- a/src/main/java/cn/lihongjie/coal/runner/InitDataRunner.java +++ b/src/main/java/cn/lihongjie/coal/runner/InitDataRunner.java @@ -10,7 +10,9 @@ import cn.lihongjie.coal.session.SessionService; import cn.lihongjie.coal.sysconfig.service.SysConfigService; import cn.lihongjie.coal.user.entity.UserEntity; import cn.lihongjie.coal.user.service.UserService; + import lombok.extern.slf4j.Slf4j; + import org.flywaydb.core.Flyway; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; @@ -23,52 +25,52 @@ import org.springframework.transaction.annotation.Transactional; @Slf4j public class InitDataRunner implements CommandLineRunner { - @Autowired OrganizationService organizationService; + @Autowired OrganizationService organizationService; - @Autowired UserService userService; + @Autowired UserService userService; - @Autowired CoalParameterDefService coalParameterDefService; + @Autowired CoalParameterDefService coalParameterDefService; - @Autowired ResourceService resourceService; + @Autowired ResourceService resourceService; - @Autowired Flyway flyway; + @Autowired Flyway flyway; - @Autowired ScriptService scriptService; + @Autowired ScriptService scriptService; - @Autowired DictionaryService dictionaryService; + @Autowired DictionaryService dictionaryService; - @Autowired SysConfigService sysConfigService; + @Autowired SysConfigService sysConfigService; - @Override - @Transactional - public void run(String... args) throws Exception { + @Override + @Transactional + public void run(String... args) throws Exception { - flyway.migrate(); + flyway.migrate(); - OrganizationEntity e = organizationService.initOrGetAdminOrg(); + OrganizationEntity e = organizationService.initOrGetAdminOrg(); - UserEntity u = userService.initOrGetAdminUser(e); + UserEntity u = userService.initOrGetAdminUser(e); - SecurityContext context = SecurityContextHolder.createEmptyContext(); + SecurityContext context = SecurityContextHolder.createEmptyContext(); - context.setAuthentication(new SessionService.MyAuthentication(null, u, "")); + context.setAuthentication(new SessionService.MyAuthentication(null, u, "")); - SecurityContextHolder.setContext(context); + SecurityContextHolder.setContext(context); - try { + try { - sysConfigService.initDefault(); + sysConfigService.initDefault(); - coalParameterDefService.initDefault(); + coalParameterDefService.initDefault(); - resourceService.initUrlResource(); + resourceService.initUrlResource(); - dictionaryService.initDefault(); + dictionaryService.initDefault(); - scriptService.initFromResource(); + scriptService.initFromResource(); - } finally { - SecurityContextHolder.clearContext(); + } finally { + SecurityContextHolder.clearContext(); + } } - } } diff --git a/src/main/java/cn/lihongjie/coal/script/controller/ScriptController.java b/src/main/java/cn/lihongjie/coal/script/controller/ScriptController.java index 635c892e..af9c43b1 100644 --- a/src/main/java/cn/lihongjie/coal/script/controller/ScriptController.java +++ b/src/main/java/cn/lihongjie/coal/script/controller/ScriptController.java @@ -9,7 +9,9 @@ import cn.lihongjie.coal.script.dto.ScriptDto; import cn.lihongjie.coal.script.dto.ScriptExecResultDto; import cn.lihongjie.coal.script.dto.UpdateScriptDto; import cn.lihongjie.coal.script.service.ScriptService; + import lombok.SneakyThrows; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.web.bind.annotation.PostMapping; @@ -22,40 +24,40 @@ import org.springframework.web.bind.annotation.RestController; @SysLog(module = "") public class ScriptController extends BaseController { - @Autowired ScriptService service; + @Autowired ScriptService service; - @PostMapping("/create") - @SysLog(action = "新增") - public ScriptDto create(@RequestBody CreateScriptDto dto) { - return this.service.create(dto); - } + @PostMapping("/create") + @SysLog(action = "新增") + public ScriptDto create(@RequestBody CreateScriptDto dto) { + return this.service.create(dto); + } - @PostMapping("/update") - @SysLog(action = "编辑") - public ScriptDto update(@RequestBody UpdateScriptDto dto) { - return this.service.update(dto); - } + @PostMapping("/update") + @SysLog(action = "编辑") + public ScriptDto update(@RequestBody UpdateScriptDto dto) { + return this.service.update(dto); + } - @PostMapping("/delete") - @SysLog(action = "删除") - public Object delete(@RequestBody IdRequest dto) { - this.service.delete(dto); - return true; - } + @PostMapping("/delete") + @SysLog(action = "删除") + public Object delete(@RequestBody IdRequest dto) { + this.service.delete(dto); + return true; + } - @PostMapping("/list") - public Page list(@RequestBody CommonQuery dto) { - return this.service.list(dto); - } + @PostMapping("/list") + public Page list(@RequestBody CommonQuery dto) { + return this.service.list(dto); + } - @PostMapping("/getById") - public ScriptDto getById(@RequestBody IdRequest dto) { - return this.service.getById(dto.getId()); - } + @PostMapping("/getById") + public ScriptDto getById(@RequestBody IdRequest dto) { + return this.service.getById(dto.getId()); + } - @SneakyThrows - @PostMapping("/exec") - public ScriptExecResultDto exec(@RequestBody ScriptExecResultDto json) { - return this.service.exec(json); - } + @SneakyThrows + @PostMapping("/exec") + public ScriptExecResultDto exec(@RequestBody ScriptExecResultDto json) { + return this.service.exec(json); + } } diff --git a/src/main/java/cn/lihongjie/coal/script/dto/CreateScriptDto.java b/src/main/java/cn/lihongjie/coal/script/dto/CreateScriptDto.java index 24fef388..8b94b81e 100644 --- a/src/main/java/cn/lihongjie/coal/script/dto/CreateScriptDto.java +++ b/src/main/java/cn/lihongjie/coal/script/dto/CreateScriptDto.java @@ -1,16 +1,18 @@ package cn.lihongjie.coal.script.dto; import cn.lihongjie.coal.base.dto.CommonDto; + import lombok.Data; + import org.hibernate.annotations.Comment; @Data @Comment("脚本") public class CreateScriptDto extends CommonDto { - @Comment("脚本内容") - private String content; + @Comment("脚本内容") + private String content; - @Comment("脚本类型") - private String scriptType; + @Comment("脚本类型") + private String scriptType; } diff --git a/src/main/java/cn/lihongjie/coal/script/dto/ScriptDto.java b/src/main/java/cn/lihongjie/coal/script/dto/ScriptDto.java index ad8a66b2..44428a7c 100644 --- a/src/main/java/cn/lihongjie/coal/script/dto/ScriptDto.java +++ b/src/main/java/cn/lihongjie/coal/script/dto/ScriptDto.java @@ -1,16 +1,18 @@ package cn.lihongjie.coal.script.dto; import cn.lihongjie.coal.base.dto.CommonDto; + import lombok.Data; + import org.hibernate.annotations.Comment; @Data @Comment("脚本") public class ScriptDto extends CommonDto { - @Comment("脚本内容") - private String content; + @Comment("脚本内容") + private String content; - @Comment("脚本类型") - private String scriptType; + @Comment("脚本类型") + private String scriptType; } diff --git a/src/main/java/cn/lihongjie/coal/script/dto/ScriptExecResultDto.java b/src/main/java/cn/lihongjie/coal/script/dto/ScriptExecResultDto.java index 72b8ca08..159369c6 100644 --- a/src/main/java/cn/lihongjie/coal/script/dto/ScriptExecResultDto.java +++ b/src/main/java/cn/lihongjie/coal/script/dto/ScriptExecResultDto.java @@ -7,15 +7,15 @@ import lombok.Data; @Data public class ScriptExecResultDto { - private String id; + private String id; - private JsonNode params; + private JsonNode params; - private Object response; + private Object response; - private String stackTrace; + private String stackTrace; - private long time; + private long time; - private List logs; + private List logs; } diff --git a/src/main/java/cn/lihongjie/coal/script/dto/UpdateScriptDto.java b/src/main/java/cn/lihongjie/coal/script/dto/UpdateScriptDto.java index 5800776c..187d99a6 100644 --- a/src/main/java/cn/lihongjie/coal/script/dto/UpdateScriptDto.java +++ b/src/main/java/cn/lihongjie/coal/script/dto/UpdateScriptDto.java @@ -1,16 +1,18 @@ package cn.lihongjie.coal.script.dto; import cn.lihongjie.coal.base.dto.CommonDto; + import lombok.Data; + import org.hibernate.annotations.Comment; @Data @Comment("脚本") public class UpdateScriptDto extends CommonDto { - @Comment("脚本内容") - private String content; + @Comment("脚本内容") + private String content; - @Comment("脚本类型") - private String scriptType; + @Comment("脚本类型") + private String scriptType; } diff --git a/src/main/java/cn/lihongjie/coal/script/entity/ScriptEntity.java b/src/main/java/cn/lihongjie/coal/script/entity/ScriptEntity.java index 74b8c33c..50575555 100644 --- a/src/main/java/cn/lihongjie/coal/script/entity/ScriptEntity.java +++ b/src/main/java/cn/lihongjie/coal/script/entity/ScriptEntity.java @@ -1,8 +1,11 @@ package cn.lihongjie.coal.script.entity; import cn.lihongjie.coal.base.entity.CommonEntity; + import jakarta.persistence.Entity; + import lombok.Data; + import org.hibernate.annotations.Comment; @Data @@ -10,12 +13,12 @@ import org.hibernate.annotations.Comment; @Comment("脚本") public class ScriptEntity extends CommonEntity { - @Comment("脚本路径") - private String scriptPath; + @Comment("脚本路径") + private String scriptPath; - @Comment("脚本内容") - private String content; + @Comment("脚本内容") + private String content; - @Comment("脚本类型") - private String scriptType; + @Comment("脚本类型") + private String scriptType; } diff --git a/src/main/java/cn/lihongjie/coal/script/mapper/ScriptMapper.java b/src/main/java/cn/lihongjie/coal/script/mapper/ScriptMapper.java index 588e930d..bdcf0347 100644 --- a/src/main/java/cn/lihongjie/coal/script/mapper/ScriptMapper.java +++ b/src/main/java/cn/lihongjie/coal/script/mapper/ScriptMapper.java @@ -6,11 +6,12 @@ import cn.lihongjie.coal.script.dto.CreateScriptDto; import cn.lihongjie.coal.script.dto.ScriptDto; import cn.lihongjie.coal.script.dto.UpdateScriptDto; import cn.lihongjie.coal.script.entity.ScriptEntity; + import org.mapstruct.Mapper; import org.mapstruct.MappingConstants; @Mapper( - componentModel = MappingConstants.ComponentModel.SPRING, - uses = {CommonMapper.class}) + componentModel = MappingConstants.ComponentModel.SPRING, + uses = {CommonMapper.class}) public interface ScriptMapper - extends BaseMapper {} + extends BaseMapper {} diff --git a/src/main/java/cn/lihongjie/coal/script/repository/ScriptRepository.java b/src/main/java/cn/lihongjie/coal/script/repository/ScriptRepository.java index 0a6bce20..0a1959a1 100644 --- a/src/main/java/cn/lihongjie/coal/script/repository/ScriptRepository.java +++ b/src/main/java/cn/lihongjie/coal/script/repository/ScriptRepository.java @@ -2,6 +2,7 @@ package cn.lihongjie.coal.script.repository; import cn.lihongjie.coal.base.dao.BaseRepository; import cn.lihongjie.coal.script.entity.ScriptEntity; + import org.springframework.stereotype.Repository; @Repository diff --git a/src/main/java/cn/lihongjie/coal/script/service/ScriptService.java b/src/main/java/cn/lihongjie/coal/script/service/ScriptService.java index 598986c0..330e648f 100644 --- a/src/main/java/cn/lihongjie/coal/script/service/ScriptService.java +++ b/src/main/java/cn/lihongjie/coal/script/service/ScriptService.java @@ -2,6 +2,7 @@ package cn.lihongjie.coal.script.service; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.read.ListAppender; + import cn.lihongjie.coal.base.dto.CommonQuery; import cn.lihongjie.coal.base.dto.IdRequest; import cn.lihongjie.coal.base.service.BaseService; @@ -13,15 +14,16 @@ import cn.lihongjie.coal.script.dto.UpdateScriptDto; import cn.lihongjie.coal.script.entity.ScriptEntity; import cn.lihongjie.coal.script.mapper.ScriptMapper; import cn.lihongjie.coal.script.repository.ScriptRepository; + import groovy.lang.GroovyClassLoader; import groovy.lang.Script; + import jakarta.annotation.PostConstruct; -import java.nio.charset.StandardCharsets; -import java.util.List; -import javax.script.ScriptException; + import lombok.Cleanup; import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; + import org.apache.commons.io.FilenameUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.exception.ExceptionUtils; @@ -38,158 +40,162 @@ import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Sort; import org.springframework.stereotype.Service; +import java.nio.charset.StandardCharsets; +import java.util.List; + +import javax.script.ScriptException; + @Service @Slf4j public class ScriptService extends BaseService { - @Autowired ScriptRepository repository; + @Autowired ScriptRepository repository; - @Autowired ScriptMapper mapper; - private GroovyClassLoader groovyClassLoader; + @Autowired ScriptMapper mapper; + @Autowired ConversionService conversionService; + @Value("classpath:scripts/dict/**/*.groovy") + Resource[] dictScripts; + @Autowired DictionaryService dictionaryService; + @Autowired ApplicationContext applicationContext; + private GroovyClassLoader groovyClassLoader; - @PostConstruct - public void init() { + @PostConstruct + public void init() { - CompilerConfiguration config = new CompilerConfiguration(); - groovyClassLoader = new GroovyClassLoader(this.getClass().getClassLoader(), config); - } + CompilerConfiguration config = new CompilerConfiguration(); + groovyClassLoader = new GroovyClassLoader(this.getClass().getClassLoader(), config); + } - public ScriptDto create(CreateScriptDto request) { + public ScriptDto create(CreateScriptDto request) { - ScriptEntity entity = mapper.toEntity(request); + ScriptEntity entity = mapper.toEntity(request); - this.repository.save(entity); - return getById(entity.getId()); - } + this.repository.save(entity); + return getById(entity.getId()); + } - public ScriptDto update(UpdateScriptDto request) { - ScriptEntity entity = this.repository.get(request.getId()); - this.mapper.updateEntity(entity, request); + public ScriptDto update(UpdateScriptDto request) { + ScriptEntity entity = this.repository.get(request.getId()); + this.mapper.updateEntity(entity, request); - this.repository.save(entity); + this.repository.save(entity); - return getById(entity.getId()); - } + return getById(entity.getId()); + } - public void delete(IdRequest request) { + public void delete(IdRequest request) { - this.repository.deleteAllById(request.getIds()); - } + this.repository.deleteAllById(request.getIds()); + } - public ScriptDto getById(String id) { + public ScriptDto getById(String id) { - ScriptEntity entity = repository.get(id); + ScriptEntity entity = repository.get(id); - return mapper.toDto(entity); - } + return mapper.toDto(entity); + } - @Autowired ConversionService conversionService; + public Page list(CommonQuery query) { - public Page list(CommonQuery query) { + Page page = + repository.findAll( + query.specification(conversionService), + PageRequest.of( + query.getPageNo(), + query.getPageSize(), + Sort.by(query.getOrders()))); - Page page = - repository.findAll( - query.specification(conversionService), - PageRequest.of(query.getPageNo(), query.getPageSize(), Sort.by(query.getOrders()))); + return page.map(this.mapper::toDto); + } - return page.map(this.mapper::toDto); - } + @SneakyThrows + public void initFromResource() { - @Value("classpath:scripts/dict/**/*.groovy") - Resource[] dictScripts; + List all = findAll(); + for (Resource resource : dictScripts) { - @Autowired DictionaryService dictionaryService; + boolean find = false; + String baseName = FilenameUtils.getBaseName(resource.getFilename()); + String path = FilenameUtils.getPath(resource.getFilename()); + String ext = FilenameUtils.getExtension(resource.getFilename()); + for (ScriptEntity scriptEntity : all) { - @SneakyThrows - public void initFromResource() { + if (StringUtils.equals(scriptEntity.getName(), baseName)) { - List all = findAll(); - for (Resource resource : dictScripts) { + find = true; + scriptEntity.setContent(resource.getContentAsString(StandardCharsets.UTF_8)); + scriptEntity.setScriptPath(path); + scriptEntity.setScriptType(ext); + scriptEntity.setCode(baseName); + this.repository.save(scriptEntity); - boolean find = false; - String baseName = FilenameUtils.getBaseName(resource.getFilename()); - String path = FilenameUtils.getPath(resource.getFilename()); - String ext = FilenameUtils.getExtension(resource.getFilename()); - for (ScriptEntity scriptEntity : all) { + dictionaryService.createScriptDict(scriptEntity); + break; + } + } + if (!find) { - if (StringUtils.equals(scriptEntity.getName(), baseName)) { - - find = true; - scriptEntity.setContent(resource.getContentAsString(StandardCharsets.UTF_8)); - scriptEntity.setScriptPath(path); - scriptEntity.setScriptType(ext); - scriptEntity.setCode(baseName); - this.repository.save(scriptEntity); - - dictionaryService.createScriptDict(scriptEntity); - break; + ScriptEntity scriptEntity = new ScriptEntity(); + scriptEntity.setName(baseName); + scriptEntity.setCode(baseName); + scriptEntity.setContent(resource.getContentAsString(StandardCharsets.UTF_8)); + scriptEntity.setScriptPath(path); + scriptEntity.setScriptType(ext); + this.repository.save(scriptEntity); + dictionaryService.createScriptDict(scriptEntity); + } } - } - if (!find) { - - ScriptEntity scriptEntity = new ScriptEntity(); - scriptEntity.setName(baseName); - scriptEntity.setCode(baseName); - scriptEntity.setContent(resource.getContentAsString(StandardCharsets.UTF_8)); - scriptEntity.setScriptPath(path); - scriptEntity.setScriptType(ext); - this.repository.save(scriptEntity); - dictionaryService.createScriptDict(scriptEntity); - } } - } - @Autowired ApplicationContext applicationContext; + @SneakyThrows + public ScriptExecResultDto exec(ScriptExecResultDto json) throws ScriptException { - @SneakyThrows - public ScriptExecResultDto exec(ScriptExecResultDto json) throws ScriptException { + // 执行groovy脚本 + // 1. 从数据库中获取脚本 + ScriptEntity scriptEntity = this.get(json.getId()); - // 执行groovy脚本 - // 1. 从数据库中获取脚本 - ScriptEntity scriptEntity = this.get(json.getId()); + // 2. 执行脚本 - // 2. 执行脚本 + Class parsedClass = + groovyClassLoader.parseClass(scriptEntity.getContent(), scriptEntity.getId()); - Class parsedClass = - groovyClassLoader.parseClass(scriptEntity.getContent(), scriptEntity.getId()); + Script script = (Script) parsedClass.newInstance(); - Script script = (Script) parsedClass.newInstance(); + Logger scriptLogger = LoggerFactory.getLogger("scriptLogger"); + ch.qos.logback.classic.Logger logger = (ch.qos.logback.classic.Logger) scriptLogger; - Logger scriptLogger = LoggerFactory.getLogger("scriptLogger"); - ch.qos.logback.classic.Logger logger = (ch.qos.logback.classic.Logger) scriptLogger; + @Cleanup("stop") + ListAppender appender = new ListAppender<>(); + appender.start(); + logger.addAppender(appender); + script.setProperty( + "out", + new Object() { + public void println(Object o) { + logger.info("{}", o); + } - @Cleanup("stop") - ListAppender appender = new ListAppender<>(); - appender.start(); - logger.addAppender(appender); - script.setProperty( - "out", - new Object() { - public void println(Object o) { - logger.info("{}", o); - } + public void printf(String format, Object... args) { + logger.info(format, args); + } + }); - public void printf(String format, Object... args) { - logger.info(format, args); - } - }); + script.setProperty("params", json.getParams()); + script.setProperty("ioc", applicationContext); - script.setProperty("params", json.getParams()); - script.setProperty("ioc", applicationContext); + long start = System.currentTimeMillis(); + try { - long start = System.currentTimeMillis(); - try { + json.setResponse(script.run()); + } catch (Exception e) { + json.setStackTrace(ExceptionUtils.getStackTrace(e)); + } + long end = System.currentTimeMillis(); - json.setResponse(script.run()); - } catch (Exception e) { - json.setStackTrace(ExceptionUtils.getStackTrace(e)); + // 3. 返回结果 + json.setLogs(appender.list.stream().map(x -> x.getFormattedMessage()).toList()); + json.setTime(end - start); + + return json; } - long end = System.currentTimeMillis(); - - // 3. 返回结果 - json.setLogs(appender.list.stream().map(x -> x.getFormattedMessage()).toList()); - json.setTime(end - start); - - return json; - } } diff --git a/src/main/java/cn/lihongjie/coal/session/CaptchaDto.java b/src/main/java/cn/lihongjie/coal/session/CaptchaDto.java index be88c167..d5fb62af 100644 --- a/src/main/java/cn/lihongjie/coal/session/CaptchaDto.java +++ b/src/main/java/cn/lihongjie/coal/session/CaptchaDto.java @@ -9,7 +9,7 @@ import lombok.NoArgsConstructor; @NoArgsConstructor public class CaptchaDto { - private String id; + private String id; - private String base64; + private String base64; } diff --git a/src/main/java/cn/lihongjie/coal/session/LoginController.java b/src/main/java/cn/lihongjie/coal/session/LoginController.java index 293deaec..2a855aa5 100644 --- a/src/main/java/cn/lihongjie/coal/session/LoginController.java +++ b/src/main/java/cn/lihongjie/coal/session/LoginController.java @@ -6,6 +6,7 @@ import cn.lihongjie.coal.base.controller.BaseController; import cn.lihongjie.coal.common.Ctx; import cn.lihongjie.coal.user.dto.UserDto; import cn.lihongjie.coal.user.service.UserService; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.web.bind.annotation.PostMapping; @@ -17,41 +18,42 @@ import org.springframework.web.bind.annotation.RestController; @RequestMapping public class LoginController extends BaseController { - @Autowired SessionService service; + @Autowired SessionService service; - @Autowired UserService userService; + @Autowired UserService userService; - @PostMapping("/login") - @SysLog(action = "登录") - @Anonymous - public UserDto login(@RequestBody LoginDto dto) { - this.service.login(dto); + @PostMapping("/login") + @SysLog(action = "登录") + @Anonymous + public UserDto login(@RequestBody LoginDto dto) { + this.service.login(dto); - return userService.getById(Ctx.getUserId()); - } - - @PostMapping("/genCaptcha") - @Anonymous - public CaptchaDto genCaptcha() { - return this.service.genCaptcha(); - } - - @PostMapping("/logout") - @SysLog(action = "退出") - public Object logout() { - if (Ctx.isLoggedIn()) { - - this.service.logout( - ((SessionService.MyAuthentication) SecurityContextHolder.getContext().getAuthentication()) - .getSessionId()); + return userService.getById(Ctx.getUserId()); } - return true; - } - @PostMapping("/isValid") - @Anonymous - public Boolean isValid() { + @PostMapping("/genCaptcha") + @Anonymous + public CaptchaDto genCaptcha() { + return this.service.genCaptcha(); + } - return Ctx.isLoggedIn(); - } + @PostMapping("/logout") + @SysLog(action = "退出") + public Object logout() { + if (Ctx.isLoggedIn()) { + + this.service.logout( + ((SessionService.MyAuthentication) + SecurityContextHolder.getContext().getAuthentication()) + .getSessionId()); + } + return true; + } + + @PostMapping("/isValid") + @Anonymous + public Boolean isValid() { + + return Ctx.isLoggedIn(); + } } diff --git a/src/main/java/cn/lihongjie/coal/session/LoginDto.java b/src/main/java/cn/lihongjie/coal/session/LoginDto.java index aa061231..bc68597c 100644 --- a/src/main/java/cn/lihongjie/coal/session/LoginDto.java +++ b/src/main/java/cn/lihongjie/coal/session/LoginDto.java @@ -5,12 +5,12 @@ import lombok.Data; @Data public class LoginDto { - private String username; - private String password; - private String captchaId; - private String captcha; - private String ip; - private String ua; - private String userId; - private String sessionId; + private String username; + private String password; + private String captchaId; + private String captcha; + private String ip; + private String ua; + private String userId; + private String sessionId; } diff --git a/src/main/java/cn/lihongjie/coal/session/SessionService.java b/src/main/java/cn/lihongjie/coal/session/SessionService.java index 740b78f7..610d1110 100644 --- a/src/main/java/cn/lihongjie/coal/session/SessionService.java +++ b/src/main/java/cn/lihongjie/coal/session/SessionService.java @@ -8,17 +8,18 @@ import cn.lihongjie.coal.organization.service.OrganizationService; import cn.lihongjie.coal.sysconfig.service.SysConfigService; import cn.lihongjie.coal.user.entity.UserEntity; import cn.lihongjie.coal.user.service.UserService; + import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.wf.captcha.SpecCaptcha; import com.wf.captcha.base.Captcha; + import jakarta.servlet.http.HttpServletRequest; -import java.util.Collection; -import java.util.UUID; -import java.util.concurrent.TimeUnit; + import lombok.Data; import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; + import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.StringRedisTemplate; @@ -30,213 +31,217 @@ import org.springframework.stereotype.Service; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; +import java.util.Collection; +import java.util.UUID; +import java.util.concurrent.TimeUnit; + @Service @Slf4j public class SessionService { - @Autowired UserService userService; + @Autowired UserService userService; - @Autowired StringRedisTemplate stringRedisTemplate; + @Autowired StringRedisTemplate stringRedisTemplate; - @Autowired SysConfigService sysConfigService; + @Autowired SysConfigService sysConfigService; + @Autowired OrganizationService organizationService; + @Autowired ObjectMapper objectMapper; - /** - * 生成验证码 - * - * @return - */ - public CaptchaDto genCaptcha() { - boolean enable = sysConfigService.isEnable(Constants.SYSCONFIG_ENABLE_CAPTCHA); - if (!enable) { - return new CaptchaDto("", ""); + /** + * 生成验证码 + * + * @return + */ + public CaptchaDto genCaptcha() { + boolean enable = sysConfigService.isEnable(Constants.SYSCONFIG_ENABLE_CAPTCHA); + if (!enable) { + return new CaptchaDto("", ""); + } + + // 三个参数分别为宽、高、位数 + SpecCaptcha specCaptcha = new SpecCaptcha(130, 48, 4); + // 设置字体 + // 设置类型,纯数字、纯字母、字母数字混合 + specCaptcha.setCharType(Captcha.TYPE_ONLY_NUMBER); + + String text = specCaptcha.text(); + + String id = UUID.randomUUID().toString(); + + String base64 = specCaptcha.toBase64(); + + stringRedisTemplate.opsForValue().set(id, text, 5, TimeUnit.MINUTES); + + return new CaptchaDto(id, base64); } - // 三个参数分别为宽、高、位数 - SpecCaptcha specCaptcha = new SpecCaptcha(130, 48, 4); - // 设置字体 - // 设置类型,纯数字、纯字母、字母数字混合 - specCaptcha.setCharType(Captcha.TYPE_ONLY_NUMBER); + @SneakyThrows + public void login(LoginDto dto) { + HttpServletRequest request = + ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()) + .getRequest(); - String text = specCaptcha.text(); + if (sysConfigService.isEnable(Constants.SYSCONFIG_ENABLE_CAPTCHA)) { - String id = UUID.randomUUID().toString(); + String captchaId = dto.getCaptchaId(); - String base64 = specCaptcha.toBase64(); + String expectCaptcha = stringRedisTemplate.opsForValue().get(captchaId); - stringRedisTemplate.opsForValue().set(id, text, 5, TimeUnit.MINUTES); + if (expectCaptcha == null) { + throw new BizException("验证码已失效"); + } - return new CaptchaDto(id, base64); - } + if (!StringUtils.equals(expectCaptcha, dto.getCaptcha())) { + throw new BizException("验证码错误"); + } + } - @Autowired OrganizationService organizationService; + UserEntity user = + userService + .findByUsername(dto.getUsername()) + .orElseThrow(() -> new BizException("用户名或者密码错误")); - @Autowired ObjectMapper objectMapper; + if (user.isDisabled()) { + throw new BizException("用户被禁用"); + } - @SneakyThrows - public void login(LoginDto dto) { - HttpServletRequest request = - ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); + OrganizationEntity organization = organizationService.get(user.getOrganizationId()); + if (organization.isDisabled()) { + throw new BizException("用户所在机构被禁用"); + } - if (sysConfigService.isEnable(Constants.SYSCONFIG_ENABLE_CAPTCHA)) { + if (!userService.isValidPassword(dto.getPassword(), user.getPassword())) { + throw new BizException("用户名或者密码错误"); + } - String captchaId = dto.getCaptchaId(); + String sessionId = UUID.randomUUID().toString(); - String expectCaptcha = stringRedisTemplate.opsForValue().get(captchaId); + SecurityContext context = SecurityContextHolder.createEmptyContext(); - if (expectCaptcha == null) { - throw new BizException("验证码已失效"); - } + context.setAuthentication(new MyAuthentication(dto, user, sessionId)); - if (!StringUtils.equals(expectCaptcha, dto.getCaptcha())) { - throw new BizException("验证码错误"); - } + SecurityContextHolder.setContext(context); + dto.setUserId(user.getId()); + dto.setSessionId(sessionId); + dto.setUa(RequestUtils.getUa(request)); + dto.setIp(RequestUtils.getIp(request)); + + stringRedisTemplate + .opsForValue() + .set(sessionId, objectMapper.writeValueAsString(dto), 1, TimeUnit.HOURS); } - UserEntity user = - userService - .findByUsername(dto.getUsername()) - .orElseThrow(() -> new BizException("用户名或者密码错误")); + public void rebuildSession(String sessionId) { - if (user.isDisabled()) { - throw new BizException("用户被禁用"); + if (StringUtils.isEmpty(sessionId)) { + SecurityContextHolder.clearContext(); + return; + } + + String jsonstring = + stringRedisTemplate.opsForValue().getAndExpire(sessionId, 1, TimeUnit.HOURS); + + if (StringUtils.isEmpty(jsonstring)) { + throw new BizException("invalidToken", "会话已过期,请重新登录"); + } + LoginDto loginDto = null; + + try { + loginDto = objectMapper.readValue(jsonstring, LoginDto.class); + } catch (JsonProcessingException e) { + throw new BizException("invalidToken", "会话异常,请重新登录"); + } + + HttpServletRequest request = + ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()) + .getRequest(); + String currentIp = RequestUtils.getIp(request); + String currentUa = RequestUtils.getUa(request); + if (!StringUtils.equalsIgnoreCase(currentIp, loginDto.getIp())) { + + log.warn("检测到IP变化: {} {}", loginDto, currentIp); + logout(loginDto.getSessionId()); + throw new BizException("invalidToken", "检测到IP发生变化,请重新登录"); + } + if (!StringUtils.equalsIgnoreCase(currentUa, loginDto.getUa())) { + + log.warn("检测到浏览器变化: {} {}", loginDto, currentUa); + logout(loginDto.getSessionId()); + throw new BizException("invalidToken", "检测到浏览器发生变化,请重新登录"); + } + + UserEntity user = userService.get(loginDto.getUserId()); + + SecurityContext context = SecurityContextHolder.createEmptyContext(); + + context.setAuthentication(new MyAuthentication(loginDto, user, sessionId)); + + SecurityContextHolder.setContext(context); } - OrganizationEntity organization = organizationService.get(user.getOrganizationId()); - if (organization.isDisabled()) { - throw new BizException("用户所在机构被禁用"); + public void logout(String sessionId) { + + if (sessionId != null) { + + stringRedisTemplate.opsForValue().getAndDelete(sessionId); + } } - if (!userService.isValidPassword(dto.getPassword(), user.getPassword())) { - throw new BizException("用户名或者密码错误"); + public void anonymousSession() { + + SecurityContext context = SecurityContextHolder.createEmptyContext(); + + UserEntity user = new UserEntity(); + user.setName("匿名用户"); + user.setUsername("anonymous"); + context.setAuthentication(new MyAuthentication(null, user, "-1")); + + SecurityContextHolder.setContext(context); } - String sessionId = UUID.randomUUID().toString(); + @Data + public static class MyAuthentication implements Authentication { + private final LoginDto dto; + private final UserEntity user; + private final String sessionId; - SecurityContext context = SecurityContextHolder.createEmptyContext(); + public MyAuthentication(LoginDto dto, UserEntity user, String sessionId) { + this.dto = dto; + this.user = user; + this.sessionId = sessionId; + } - context.setAuthentication(new MyAuthentication(dto, user, sessionId)); + @Override + public Collection getAuthorities() { + return null; + } - SecurityContextHolder.setContext(context); - dto.setUserId(user.getId()); - dto.setSessionId(sessionId); - dto.setUa(RequestUtils.getUa(request)); - dto.setIp(RequestUtils.getIp(request)); + @Override + public Object getCredentials() { + return dto; + } - stringRedisTemplate - .opsForValue() - .set(sessionId, objectMapper.writeValueAsString(dto), 1, TimeUnit.HOURS); - } + @Override + public Object getDetails() { + return user; + } - public void rebuildSession(String sessionId) { + @Override + public Object getPrincipal() { + return user; + } - if (StringUtils.isEmpty(sessionId)) { - SecurityContextHolder.clearContext(); - return; + @Override + public boolean isAuthenticated() { + return true; + } + + @Override + public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException {} + + @Override + public String getName() { + return user.getUsername(); + } } - - String jsonstring = - stringRedisTemplate.opsForValue().getAndExpire(sessionId, 1, TimeUnit.HOURS); - - if (StringUtils.isEmpty(jsonstring)) { - throw new BizException("invalidToken", "会话已过期,请重新登录"); - } - LoginDto loginDto = null; - - try { - loginDto = objectMapper.readValue(jsonstring, LoginDto.class); - } catch (JsonProcessingException e) { - throw new BizException("invalidToken", "会话异常,请重新登录"); - } - - HttpServletRequest request = - ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); - String currentIp = RequestUtils.getIp(request); - String currentUa = RequestUtils.getUa(request); - if (!StringUtils.equalsIgnoreCase(currentIp, loginDto.getIp())) { - - log.warn("检测到IP变化: {} {}", loginDto, currentIp); - logout(loginDto.getSessionId()); - throw new BizException("invalidToken", "检测到IP发生变化,请重新登录"); - } - if (!StringUtils.equalsIgnoreCase(currentUa, loginDto.getUa())) { - - log.warn("检测到浏览器变化: {} {}", loginDto, currentUa); - logout(loginDto.getSessionId()); - throw new BizException("invalidToken", "检测到浏览器发生变化,请重新登录"); - } - - UserEntity user = userService.get(loginDto.getUserId()); - - SecurityContext context = SecurityContextHolder.createEmptyContext(); - - context.setAuthentication(new MyAuthentication(loginDto, user, sessionId)); - - SecurityContextHolder.setContext(context); - } - - public void logout(String sessionId) { - - if (sessionId != null) { - - stringRedisTemplate.opsForValue().getAndDelete(sessionId); - } - } - - public void anonymousSession() { - - SecurityContext context = SecurityContextHolder.createEmptyContext(); - - UserEntity user = new UserEntity(); - user.setName("匿名用户"); - user.setUsername("anonymous"); - context.setAuthentication(new MyAuthentication(null, user, "-1")); - - SecurityContextHolder.setContext(context); - } - - @Data - public static class MyAuthentication implements Authentication { - private final LoginDto dto; - private final UserEntity user; - private final String sessionId; - - public MyAuthentication(LoginDto dto, UserEntity user, String sessionId) { - this.dto = dto; - this.user = user; - this.sessionId = sessionId; - } - - @Override - public Collection getAuthorities() { - return null; - } - - @Override - public Object getCredentials() { - return dto; - } - - @Override - public Object getDetails() { - return user; - } - - @Override - public Object getPrincipal() { - return user; - } - - @Override - public boolean isAuthenticated() { - return true; - } - - @Override - public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException {} - - @Override - public String getName() { - return user.getUsername(); - } - } } diff --git a/src/main/java/cn/lihongjie/coal/spring/config/AsyncConfig.java b/src/main/java/cn/lihongjie/coal/spring/config/AsyncConfig.java index 5d487d5e..34ce18d1 100644 --- a/src/main/java/cn/lihongjie/coal/spring/config/AsyncConfig.java +++ b/src/main/java/cn/lihongjie/coal/spring/config/AsyncConfig.java @@ -1,6 +1,7 @@ package cn.lihongjie.coal.spring.config; import lombok.extern.slf4j.Slf4j; + import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.annotation.AsyncConfigurer; import org.springframework.scheduling.annotation.EnableAsync; diff --git a/src/main/java/cn/lihongjie/coal/spring/config/CacheConfig.java b/src/main/java/cn/lihongjie/coal/spring/config/CacheConfig.java index 16b912ba..1bfc2d36 100644 --- a/src/main/java/cn/lihongjie/coal/spring/config/CacheConfig.java +++ b/src/main/java/cn/lihongjie/coal/spring/config/CacheConfig.java @@ -8,13 +8,13 @@ import org.springframework.context.annotation.Configuration; @EnableCaching @Configuration public class CacheConfig { - @Bean - public RedisCacheManagerBuilderCustomizer myRedisCacheManagerBuilderCustomizer() { - return new RedisCacheManagerBuilderCustomizer() { - @Override - public void customize( - org.springframework.data.redis.cache.RedisCacheManager.RedisCacheManagerBuilder - builder) {} - }; - } + @Bean + public RedisCacheManagerBuilderCustomizer myRedisCacheManagerBuilderCustomizer() { + return new RedisCacheManagerBuilderCustomizer() { + @Override + public void customize( + org.springframework.data.redis.cache.RedisCacheManager.RedisCacheManagerBuilder + builder) {} + }; + } } diff --git a/src/main/java/cn/lihongjie/coal/spring/config/DruidConfig.java b/src/main/java/cn/lihongjie/coal/spring/config/DruidConfig.java index 5b8764ad..531cf0f3 100644 --- a/src/main/java/cn/lihongjie/coal/spring/config/DruidConfig.java +++ b/src/main/java/cn/lihongjie/coal/spring/config/DruidConfig.java @@ -2,7 +2,7 @@ package cn.lihongjie.coal.spring.config; import com.alibaba.druid.pool.DruidDataSource; import com.p6spy.engine.spy.P6DataSource; -import javax.sql.DataSource; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Bean; @@ -11,22 +11,24 @@ import org.springframework.context.annotation.Primary; import org.springframework.context.annotation.Profile; import org.springframework.core.env.Environment; +import javax.sql.DataSource; + @Configuration public class DruidConfig { - @Autowired Environment environment; + @Autowired Environment environment; - @ConfigurationProperties("spring.datasource.druid") - @Bean - public DataSource druidDataSource() { - return new DruidDataSource(); - } + @ConfigurationProperties("spring.datasource.druid") + @Bean + public DataSource druidDataSource() { + return new DruidDataSource(); + } - @Bean - @Primary - @Profile({"dev", "master"}) - public DataSource p6DataSource() { + @Bean + @Primary + @Profile({"dev", "master"}) + public DataSource p6DataSource() { - return new P6DataSource(druidDataSource()); - } + return new P6DataSource(druidDataSource()); + } } diff --git a/src/main/java/cn/lihongjie/coal/spring/config/FlywayConfig.java b/src/main/java/cn/lihongjie/coal/spring/config/FlywayConfig.java index f15759ce..00cef70f 100644 --- a/src/main/java/cn/lihongjie/coal/spring/config/FlywayConfig.java +++ b/src/main/java/cn/lihongjie/coal/spring/config/FlywayConfig.java @@ -8,9 +8,9 @@ import org.springframework.context.annotation.Configuration; @Configuration public class FlywayConfig { - /** Override default flyway initializer to do nothing */ - @Bean - FlywayMigrationInitializer flywayInitializer(Flyway flyway) { - return new FlywayMigrationInitializer(flyway, (f) -> {}); - } + /** Override default flyway initializer to do nothing */ + @Bean + FlywayMigrationInitializer flywayInitializer(Flyway flyway) { + return new FlywayMigrationInitializer(flyway, (f) -> {}); + } } diff --git a/src/main/java/cn/lihongjie/coal/spring/config/GlobalExceptionHandler.java b/src/main/java/cn/lihongjie/coal/spring/config/GlobalExceptionHandler.java index f67300e3..c050ee40 100644 --- a/src/main/java/cn/lihongjie/coal/spring/config/GlobalExceptionHandler.java +++ b/src/main/java/cn/lihongjie/coal/spring/config/GlobalExceptionHandler.java @@ -2,8 +2,11 @@ package cn.lihongjie.coal.spring.config; import cn.lihongjie.coal.base.dto.R; import cn.lihongjie.coal.exception.BizException; + import jakarta.servlet.http.HttpServletRequest; + import lombok.extern.slf4j.Slf4j; + import org.springframework.core.annotation.Order; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; @@ -14,36 +17,37 @@ import org.springframework.web.method.HandlerMethod; @Order(1) public class GlobalExceptionHandler { - @ExceptionHandler(BizException.class) - public R handleException( - BizException ex, HttpServletRequest request, HandlerMethod handlerMethod) { - logEx(ex, request, handlerMethod); - return R.fail(ex.getCode(), ex.getMessage()); - } - - private void logEx(Exception ex, HttpServletRequest request, HandlerMethod handlerMethod) { - if (request.getAttribute("__logged") != null) { - - log.info( - "接口调用异常: {}\nurl:{} {}\nmethod: {}", - ex.getMessage() == null ? "no message" : ex.getMessage(), - request.getMethod(), - request.getRequestURL(), - handlerMethod.getMethod(), - ex); + @ExceptionHandler(BizException.class) + public R handleException( + BizException ex, HttpServletRequest request, HandlerMethod handlerMethod) { + logEx(ex, request, handlerMethod); + return R.fail(ex.getCode(), ex.getMessage()); } - } - @ExceptionHandler(RuntimeException.class) - public R handleException( - RuntimeException ex, HttpServletRequest request, HandlerMethod handlerMethod) { - logEx(ex, request, handlerMethod); - return R.fail("sysError", "系统异常"); - } + private void logEx(Exception ex, HttpServletRequest request, HandlerMethod handlerMethod) { + if (request.getAttribute("__logged") != null) { - @ExceptionHandler(Exception.class) - public R handleException(Exception ex, HttpServletRequest request, HandlerMethod handlerMethod) { - logEx(ex, request, handlerMethod); - return R.fail("sysError", "系统异常"); - } + log.info( + "接口调用异常: {}\nurl:{} {}\nmethod: {}", + ex.getMessage() == null ? "no message" : ex.getMessage(), + request.getMethod(), + request.getRequestURL(), + handlerMethod.getMethod(), + ex); + } + } + + @ExceptionHandler(RuntimeException.class) + public R handleException( + RuntimeException ex, HttpServletRequest request, HandlerMethod handlerMethod) { + logEx(ex, request, handlerMethod); + return R.fail("sysError", "系统异常"); + } + + @ExceptionHandler(Exception.class) + public R handleException( + Exception ex, HttpServletRequest request, HandlerMethod handlerMethod) { + logEx(ex, request, handlerMethod); + return R.fail("sysError", "系统异常"); + } } diff --git a/src/main/java/cn/lihongjie/coal/spring/config/HibernateConfig.java b/src/main/java/cn/lihongjie/coal/spring/config/HibernateConfig.java index 0a889898..fe6f620f 100644 --- a/src/main/java/cn/lihongjie/coal/spring/config/HibernateConfig.java +++ b/src/main/java/cn/lihongjie/coal/spring/config/HibernateConfig.java @@ -1,6 +1,5 @@ package cn.lihongjie.coal.spring.config; -import java.util.Map; import org.hibernate.boot.model.naming.CamelCaseToUnderscoresNamingStrategy; import org.hibernate.boot.model.naming.Identifier; import org.hibernate.boot.model.naming.PhysicalNamingStrategy; @@ -11,62 +10,68 @@ import org.springframework.boot.autoconfigure.orm.jpa.HibernatePropertiesCustomi import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; +import java.util.Map; + @Configuration public class HibernateConfig { - @Autowired MyRedissonRegionFactory myRedissonRegionFactory; + @Autowired MyRedissonRegionFactory myRedissonRegionFactory; - @Bean - HibernatePropertiesCustomizer hibernatePropertiesCustomizer() { - return new HibernatePropertiesCustomizer() { - @Override - public void customize(Map hibernateProperties) { - hibernateProperties.put( - AvailableSettings.DIALECT, MyPostgreSQLDialect.class.getCanonicalName()); - // - hibernateProperties.put("hibernate.cache.region.factory_class", myRedissonRegionFactory); - hibernateProperties.put("hibernate.cache.use_structured_entries", true); - // hibernateProperties.put(AvailableSettings.SCHEMA_MANAGEMENT_TOOL, - // MultithreadHibernateSchemaManagementTool.class.getCanonicalName()); + @Bean + HibernatePropertiesCustomizer hibernatePropertiesCustomizer() { + return new HibernatePropertiesCustomizer() { + @Override + public void customize(Map hibernateProperties) { + hibernateProperties.put( + AvailableSettings.DIALECT, MyPostgreSQLDialect.class.getCanonicalName()); + // + hibernateProperties.put( + "hibernate.cache.region.factory_class", myRedissonRegionFactory); + hibernateProperties.put("hibernate.cache.use_structured_entries", true); + // hibernateProperties.put(AvailableSettings.SCHEMA_MANAGEMENT_TOOL, + // MultithreadHibernateSchemaManagementTool.class.getCanonicalName()); - /** - * - * - * - * - * - */ - hibernateProperties.put("hibernate.cache.use_second_level_cache", "true"); - hibernateProperties.put("hibernate.cache.use_query_cache", "false"); - hibernateProperties.put("hibernate.cache.redisson.fallback", "true"); - } - }; - } + /** + * + * + * + * + * + */ + hibernateProperties.put("hibernate.cache.use_second_level_cache", "true"); + hibernateProperties.put("hibernate.cache.use_query_cache", "false"); + hibernateProperties.put("hibernate.cache.redisson.fallback", "true"); + } + }; + } - @Bean - public PhysicalNamingStrategy physicalNamingStrategy() { + @Bean + public PhysicalNamingStrategy physicalNamingStrategy() { - return new CamelCaseToUnderscoresNamingStrategy() { + return new CamelCaseToUnderscoresNamingStrategy() { - @Override - public Identifier toPhysicalColumnName( - Identifier logicalName, JdbcEnvironment jdbcEnvironment) { - return super.toPhysicalColumnName( - new Identifier(logicalName.getText().replace("Entity", ""), logicalName.isQuoted()), - jdbcEnvironment); - } + @Override + public Identifier toPhysicalColumnName( + Identifier logicalName, JdbcEnvironment jdbcEnvironment) { + return super.toPhysicalColumnName( + new Identifier( + logicalName.getText().replace("Entity", ""), + logicalName.isQuoted()), + jdbcEnvironment); + } - @Override - public Identifier toPhysicalTableName( - Identifier logicalName, JdbcEnvironment jdbcEnvironment) { + @Override + public Identifier toPhysicalTableName( + Identifier logicalName, JdbcEnvironment jdbcEnvironment) { - return super.toPhysicalTableName( - new Identifier( - "t_" + logicalName.getText().replace("Entity", ""), logicalName.isQuoted()), - jdbcEnvironment); - } - }; - } + return super.toPhysicalTableName( + new Identifier( + "t_" + logicalName.getText().replace("Entity", ""), + logicalName.isQuoted()), + jdbcEnvironment); + } + }; + } } diff --git a/src/main/java/cn/lihongjie/coal/spring/config/HwCloudConfig.java b/src/main/java/cn/lihongjie/coal/spring/config/HwCloudConfig.java new file mode 100644 index 00000000..4c54df18 --- /dev/null +++ b/src/main/java/cn/lihongjie/coal/spring/config/HwCloudConfig.java @@ -0,0 +1,44 @@ +package cn.lihongjie.coal.spring.config; + +import com.obs.services.ObsClient; +import com.obs.services.model.AccessControlList; +import com.obs.services.model.BucketTypeEnum; +import com.obs.services.model.CreateBucketRequest; +import com.obs.services.model.ObsBucket; + +import lombok.extern.slf4j.Slf4j; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.stereotype.Component; + +@Component +@Slf4j +public class HwCloudConfig { + + @Autowired HwCloudProperty hwCloudProperty; + + @Bean + public ObsClient obsClient() { + ObsClient client = + new ObsClient( + hwCloudProperty.getObs().getAk(), + hwCloudProperty.getObs().getSk(), + hwCloudProperty.getObs().getZones().stream() + .filter(x -> x.getCode().equals(hwCloudProperty.getObs().getZone())) + .findFirst() + .orElseThrow(() -> new RuntimeException("zone not found")) + .getEndpoint()); + + if (!client.headBucket(hwCloudProperty.getObs().getBucketName())) { + CreateBucketRequest request = new CreateBucketRequest(); + request.setBucketName(hwCloudProperty.getObs().getBucketName()); + request.setBucketType(BucketTypeEnum.OBJECT); + request.setAcl(AccessControlList.REST_CANNED_PUBLIC_READ); + ObsBucket bucket = client.createBucket(request); + log.info("bucket created: {}", bucket.getBucketName()); + } + + return client; + } +} diff --git a/src/main/java/cn/lihongjie/coal/spring/config/HwCloudProperty.java b/src/main/java/cn/lihongjie/coal/spring/config/HwCloudProperty.java new file mode 100644 index 00000000..51eb96cf --- /dev/null +++ b/src/main/java/cn/lihongjie/coal/spring/config/HwCloudProperty.java @@ -0,0 +1,37 @@ +package cn.lihongjie.coal.spring.config; + +import lombok.Data; + +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.stereotype.Component; + +import java.util.*; + +@ConfigurationProperties("hwcloud") +@Component +@Data +public class HwCloudProperty { + + private OBS obs; + + @Data + public static class OBS { + + private List zones; + + private String ak; + + private String sk; + + private String zone; + + private String bucketName; + } + + @Data + public static class OBSZone { + private String code; + private String name; + private String endpoint; + } +} diff --git a/src/main/java/cn/lihongjie/coal/spring/config/JacksonConfig.java b/src/main/java/cn/lihongjie/coal/spring/config/JacksonConfig.java index 6e9ae1c4..f1ccbfcd 100644 --- a/src/main/java/cn/lihongjie/coal/spring/config/JacksonConfig.java +++ b/src/main/java/cn/lihongjie/coal/spring/config/JacksonConfig.java @@ -4,21 +4,25 @@ import com.fasterxml.jackson.databind.module.SimpleModule; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer; import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer; -import java.time.LocalDateTime; -import java.time.format.DateTimeFormatter; + import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; + @Configuration public class JacksonConfig { - private DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); + private final DateTimeFormatter dateTimeFormatter = + DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); - @Bean - public SimpleModule javaTimeModule() { - JavaTimeModule module = new JavaTimeModule(); - module.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(dateTimeFormatter)); - module.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(dateTimeFormatter)); - return module; - } + @Bean + public SimpleModule javaTimeModule() { + JavaTimeModule module = new JavaTimeModule(); + module.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(dateTimeFormatter)); + module.addDeserializer( + LocalDateTime.class, new LocalDateTimeDeserializer(dateTimeFormatter)); + return module; + } } diff --git a/src/main/java/cn/lihongjie/coal/spring/config/MultithreadHibernateSchemaManagementTool.java b/src/main/java/cn/lihongjie/coal/spring/config/MultithreadHibernateSchemaManagementTool.java index 38f17622..4a077313 100644 --- a/src/main/java/cn/lihongjie/coal/spring/config/MultithreadHibernateSchemaManagementTool.java +++ b/src/main/java/cn/lihongjie/coal/spring/config/MultithreadHibernateSchemaManagementTool.java @@ -1,9 +1,5 @@ package cn.lihongjie.coal.spring.config; -import java.util.List; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.ForkJoinPool; -import java.util.concurrent.ForkJoinTask; import org.hibernate.resource.transaction.spi.DdlTransactionIsolator; import org.hibernate.tool.schema.internal.HibernateSchemaManagementTool; import org.hibernate.tool.schema.internal.exec.GenerationTarget; @@ -11,81 +7,88 @@ import org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase; import org.hibernate.tool.schema.internal.exec.JdbcContext; import org.hibernate.tool.schema.spi.ScriptSourceInput; +import java.util.List; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ForkJoinPool; +import java.util.concurrent.ForkJoinTask; + public class MultithreadHibernateSchemaManagementTool extends HibernateSchemaManagementTool { - @Override - protected GenerationTarget buildDatabaseTarget(JdbcContext jdbcContext, boolean needsAutoCommit) { - return new MTGenerationTargetToDatabase( - getDdlTransactionIsolator(jdbcContext), true, needsAutoCommit); - } - - public static class MTGenerationTargetToDatabase extends GenerationTargetToDatabase { - - private DdlTransactionIsolator ddlTransactionIsolator; - private boolean releaseAfterUse; - private boolean autocommit; - - private List tasks; - - public MTGenerationTargetToDatabase(DdlTransactionIsolator ddlTransactionIsolator) { - super(ddlTransactionIsolator); - } - - public MTGenerationTargetToDatabase( - DdlTransactionIsolator ddlTransactionIsolator, boolean releaseAfterUse) { - super(ddlTransactionIsolator, releaseAfterUse); - } - - public MTGenerationTargetToDatabase( - DdlTransactionIsolator ddlTransactionIsolator, - boolean releaseAfterUse, - boolean autocommit) { - super(ddlTransactionIsolator, releaseAfterUse, autocommit); - this.ddlTransactionIsolator = ddlTransactionIsolator; - this.releaseAfterUse = releaseAfterUse; - this.autocommit = autocommit; - } - @Override - public void prepare() {} - - @Override - public void beforeScript(ScriptSourceInput scriptSource) { - super.beforeScript(scriptSource); + protected GenerationTarget buildDatabaseTarget( + JdbcContext jdbcContext, boolean needsAutoCommit) { + return new MTGenerationTargetToDatabase( + getDdlTransactionIsolator(jdbcContext), true, needsAutoCommit); } - @Override - public void accept(String command) { + public static class MTGenerationTargetToDatabase extends GenerationTargetToDatabase { - ForkJoinTask task = - ForkJoinPool.commonPool() - .submit( - () -> { - GenerationTargetToDatabase database = - new GenerationTargetToDatabase(ddlTransactionIsolator, true, autocommit); + private DdlTransactionIsolator ddlTransactionIsolator; + private boolean releaseAfterUse; + private boolean autocommit; - database.prepare(); - database.accept(command); + private List tasks; - database.release(); - }); + public MTGenerationTargetToDatabase(DdlTransactionIsolator ddlTransactionIsolator) { + super(ddlTransactionIsolator); + } - this.tasks.add(task); + public MTGenerationTargetToDatabase( + DdlTransactionIsolator ddlTransactionIsolator, boolean releaseAfterUse) { + super(ddlTransactionIsolator, releaseAfterUse); + } + + public MTGenerationTargetToDatabase( + DdlTransactionIsolator ddlTransactionIsolator, + boolean releaseAfterUse, + boolean autocommit) { + super(ddlTransactionIsolator, releaseAfterUse, autocommit); + this.ddlTransactionIsolator = ddlTransactionIsolator; + this.releaseAfterUse = releaseAfterUse; + this.autocommit = autocommit; + } + + @Override + public void prepare() {} + + @Override + public void beforeScript(ScriptSourceInput scriptSource) { + super.beforeScript(scriptSource); + } + + @Override + public void accept(String command) { + + ForkJoinTask task = + ForkJoinPool.commonPool() + .submit( + () -> { + GenerationTargetToDatabase database = + new GenerationTargetToDatabase( + ddlTransactionIsolator, true, autocommit); + + database.prepare(); + database.accept(command); + + database.release(); + }); + + this.tasks.add(task); + } + + @Override + public void release() { + + this.tasks.forEach( + x -> { + try { + x.get(); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } catch (ExecutionException e) { + throw new RuntimeException(e); + } + }); + } } - - @Override - public void release() { - - this.tasks.forEach( - x -> { - try { - x.get(); - } catch (InterruptedException e) { - throw new RuntimeException(e); - } catch (ExecutionException e) { - throw new RuntimeException(e); - } - }); - } - } } diff --git a/src/main/java/cn/lihongjie/coal/spring/config/MyPostgreSQLDialect.java b/src/main/java/cn/lihongjie/coal/spring/config/MyPostgreSQLDialect.java index ba5e3639..c704b836 100644 --- a/src/main/java/cn/lihongjie/coal/spring/config/MyPostgreSQLDialect.java +++ b/src/main/java/cn/lihongjie/coal/spring/config/MyPostgreSQLDialect.java @@ -5,27 +5,27 @@ import org.hibernate.type.SqlTypes; public class MyPostgreSQLDialect extends PostgreSQLDialect { - @Override - protected String columnType(int sqlTypeCode) { - if (sqlTypeCode == SqlTypes.VARCHAR) { - return "text"; + @Override + protected String columnType(int sqlTypeCode) { + if (sqlTypeCode == SqlTypes.VARCHAR) { + return "text"; + } + return super.columnType(sqlTypeCode); } - return super.columnType(sqlTypeCode); - } - @Override - public String getAddForeignKeyConstraintString( - String constraintName, - String[] foreignKey, - String referencedTable, - String[] primaryKey, - boolean referencesPrimaryKey) { - return " DROP CONSTRAINT IF EXISTS notexist "; - } + @Override + public String getAddForeignKeyConstraintString( + String constraintName, + String[] foreignKey, + String referencedTable, + String[] primaryKey, + boolean referencesPrimaryKey) { + return " DROP CONSTRAINT IF EXISTS notexist "; + } - @Override - public String getAddForeignKeyConstraintString( - String constraintName, String foreignKeyDefinition) { - return " DROP CONSTRAINT IF EXISTS notexist "; - } + @Override + public String getAddForeignKeyConstraintString( + String constraintName, String foreignKeyDefinition) { + return " DROP CONSTRAINT IF EXISTS notexist "; + } } diff --git a/src/main/java/cn/lihongjie/coal/spring/config/MyRedissonRegionFactory.java b/src/main/java/cn/lihongjie/coal/spring/config/MyRedissonRegionFactory.java index eddcbb8a..36adfee2 100644 --- a/src/main/java/cn/lihongjie/coal/spring/config/MyRedissonRegionFactory.java +++ b/src/main/java/cn/lihongjie/coal/spring/config/MyRedissonRegionFactory.java @@ -10,10 +10,11 @@ import org.springframework.stereotype.Component; @Component public class MyRedissonRegionFactory extends RedissonRegionFactory { - @Autowired RedissonClient redissonClient; + @Autowired RedissonClient redissonClient; - @Override - protected RedissonClient createRedissonClient(StandardServiceRegistry registry, Map properties) { - return redissonClient; - } + @Override + protected RedissonClient createRedissonClient( + StandardServiceRegistry registry, Map properties) { + return redissonClient; + } } diff --git a/src/main/java/cn/lihongjie/coal/spring/config/RResponseBodyAdvice.java b/src/main/java/cn/lihongjie/coal/spring/config/RResponseBodyAdvice.java index 08bc4fd7..5d601f15 100644 --- a/src/main/java/cn/lihongjie/coal/spring/config/RResponseBodyAdvice.java +++ b/src/main/java/cn/lihongjie/coal/spring/config/RResponseBodyAdvice.java @@ -1,7 +1,7 @@ package cn.lihongjie.coal.spring.config; import cn.lihongjie.coal.base.dto.R; -import java.util.List; + import org.springframework.core.MethodParameter; import org.springframework.data.domain.Page; import org.springframework.http.MediaType; @@ -11,50 +11,52 @@ import org.springframework.http.server.ServerHttpResponse; import org.springframework.web.bind.annotation.RestControllerAdvice; import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice; +import java.util.List; + @RestControllerAdvice public class RResponseBodyAdvice implements ResponseBodyAdvice { - @Override - public boolean supports( - MethodParameter returnType, Class> converterType) { + @Override + public boolean supports( + MethodParameter returnType, Class> converterType) { - return true; - } - - @Override - public Object beforeBodyWrite( - Object body, - MethodParameter returnType, - MediaType selectedContentType, - Class> selectedConverterType, - ServerHttpRequest request, - ServerHttpResponse response) { - - if (!selectedContentType.includes(MediaType.APPLICATION_JSON)) { - return body; + return true; } - if (body == null) { - return R.success(); - } + @Override + public Object beforeBodyWrite( + Object body, + MethodParameter returnType, + MediaType selectedContentType, + Class> selectedConverterType, + ServerHttpRequest request, + ServerHttpResponse response) { - if (body instanceof byte[]) { - return body; - } + if (!selectedContentType.includes(MediaType.APPLICATION_JSON)) { + return body; + } - if (body instanceof R) { - return body; - } + if (body == null) { + return R.success(); + } - if (body instanceof Page p) { - R> r = R.success(p.getContent()); - r.setPageNo(p.getNumber()); - r.setPageSize(p.getSize()); - r.setTotalPage(p.getTotalPages()); - r.setTotalCount((int) p.getTotalElements()); - return r; - } + if (body instanceof byte[]) { + return body; + } - return R.success(body); - } + if (body instanceof R) { + return body; + } + + if (body instanceof Page p) { + R> r = R.success(p.getContent()); + r.setPageNo(p.getNumber()); + r.setPageSize(p.getSize()); + r.setTotalPage(p.getTotalPages()); + r.setTotalCount((int) p.getTotalElements()); + return r; + } + + return R.success(body); + } } diff --git a/src/main/java/cn/lihongjie/coal/spring/config/RedisConfig.java b/src/main/java/cn/lihongjie/coal/spring/config/RedisConfig.java index 4ecd6458..82fc0075 100644 --- a/src/main/java/cn/lihongjie/coal/spring/config/RedisConfig.java +++ b/src/main/java/cn/lihongjie/coal/spring/config/RedisConfig.java @@ -9,5 +9,5 @@ import org.springframework.data.redis.connection.RedisConnectionFactory; @Slf4j public class RedisConfig { - @Autowired RedisConnectionFactory redisConnectionFactory; + @Autowired RedisConnectionFactory redisConnectionFactory; } diff --git a/src/main/java/cn/lihongjie/coal/spring/config/SecurityConfig.java b/src/main/java/cn/lihongjie/coal/spring/config/SecurityConfig.java index 34217fdb..18e64849 100644 --- a/src/main/java/cn/lihongjie/coal/spring/config/SecurityConfig.java +++ b/src/main/java/cn/lihongjie/coal/spring/config/SecurityConfig.java @@ -2,6 +2,7 @@ package cn.lihongjie.coal.spring.config; import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; + import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; @@ -15,18 +16,18 @@ import org.springframework.security.web.util.matcher.AntPathRequestMatcher; @EnableWebSecurity public class SecurityConfig { - @SneakyThrows - @Bean - SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) { + @SneakyThrows + @Bean + SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) { - return httpSecurity - .authorizeHttpRequests( - x -> { - x.requestMatchers(new AntPathRequestMatcher("/**/*")).permitAll(); - }) - .csrf(AbstractHttpConfigurer::disable) - .logout(AbstractHttpConfigurer::disable) - .formLogin(AbstractHttpConfigurer::disable) - .build(); - } + return httpSecurity + .authorizeHttpRequests( + x -> { + x.requestMatchers(new AntPathRequestMatcher("/**/*")).permitAll(); + }) + .csrf(AbstractHttpConfigurer::disable) + .logout(AbstractHttpConfigurer::disable) + .formLogin(AbstractHttpConfigurer::disable) + .build(); + } } diff --git a/src/main/java/cn/lihongjie/coal/spring/config/SystemConfig.java b/src/main/java/cn/lihongjie/coal/spring/config/SystemConfig.java index 1b72cb55..262a860c 100644 --- a/src/main/java/cn/lihongjie/coal/spring/config/SystemConfig.java +++ b/src/main/java/cn/lihongjie/coal/spring/config/SystemConfig.java @@ -1,25 +1,27 @@ package cn.lihongjie.coal.spring.config; -import java.util.List; import lombok.Data; import lombok.Getter; import lombok.Setter; + import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; +import java.util.List; + @Component @ConfigurationProperties("system") @Getter @Setter public class SystemConfig { - private AnonymousConfig anonymous; + private AnonymousConfig anonymous; - private String testAdminToken; + private String testAdminToken; - @Data - public static class AnonymousConfig { + @Data + public static class AnonymousConfig { - private List url; - } + private List url; + } } diff --git a/src/main/java/cn/lihongjie/coal/supplier/controller/SupplierController.java b/src/main/java/cn/lihongjie/coal/supplier/controller/SupplierController.java index b5830ab4..fd9abca8 100644 --- a/src/main/java/cn/lihongjie/coal/supplier/controller/SupplierController.java +++ b/src/main/java/cn/lihongjie/coal/supplier/controller/SupplierController.java @@ -8,6 +8,7 @@ import cn.lihongjie.coal.supplier.dto.CreateSupplierDto; import cn.lihongjie.coal.supplier.dto.SupplierDto; import cn.lihongjie.coal.supplier.dto.UpdateSupplierDto; import cn.lihongjie.coal.supplier.service.SupplierService; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.web.bind.annotation.PostMapping; @@ -21,34 +22,34 @@ import org.springframework.web.bind.annotation.RestController; @OrgScope public class SupplierController { - @Autowired SupplierService service; + @Autowired SupplierService service; - @PostMapping("/create") - @SysLog(action = "新增") - public SupplierDto create(@RequestBody CreateSupplierDto dto) { - return this.service.create(dto); - } + @PostMapping("/create") + @SysLog(action = "新增") + public SupplierDto create(@RequestBody CreateSupplierDto dto) { + return this.service.create(dto); + } - @PostMapping("/update") - @SysLog(action = "编辑") - public SupplierDto update(@RequestBody UpdateSupplierDto dto) { - return this.service.update(dto); - } + @PostMapping("/update") + @SysLog(action = "编辑") + public SupplierDto update(@RequestBody UpdateSupplierDto dto) { + return this.service.update(dto); + } - @PostMapping("/delete") - @SysLog(action = "删除") - public Object delete(@RequestBody IdRequest dto) { - this.service.delete(dto); - return true; - } + @PostMapping("/delete") + @SysLog(action = "删除") + public Object delete(@RequestBody IdRequest dto) { + this.service.delete(dto); + return true; + } - @PostMapping("/list") - public Page list(@RequestBody CommonQuery dto) { - return this.service.list(dto); - } + @PostMapping("/list") + public Page list(@RequestBody CommonQuery dto) { + return this.service.list(dto); + } - @PostMapping("/getById") - public SupplierDto getById(@RequestBody IdRequest dto) { - return this.service.getById(dto.getId()); - } + @PostMapping("/getById") + public SupplierDto getById(@RequestBody IdRequest dto) { + return this.service.getById(dto.getId()); + } } diff --git a/src/main/java/cn/lihongjie/coal/supplier/dto/CreateSupplierDto.java b/src/main/java/cn/lihongjie/coal/supplier/dto/CreateSupplierDto.java index 8c42c59a..2f50ac58 100644 --- a/src/main/java/cn/lihongjie/coal/supplier/dto/CreateSupplierDto.java +++ b/src/main/java/cn/lihongjie/coal/supplier/dto/CreateSupplierDto.java @@ -1,20 +1,22 @@ package cn.lihongjie.coal.supplier.dto; import cn.lihongjie.coal.base.dto.OrgCommonDto; + import lombok.Data; + import org.hibernate.annotations.Comment; @Data public class CreateSupplierDto extends OrgCommonDto { - @Comment("联系人") - private String contact; + @Comment("联系人") + private String contact; - @Comment("邮箱") - private String email; + @Comment("邮箱") + private String email; - @Comment("手机号") - private String phone; + @Comment("手机号") + private String phone; - @Comment("地址") - private String address; + @Comment("地址") + private String address; } diff --git a/src/main/java/cn/lihongjie/coal/supplier/dto/SupplierDto.java b/src/main/java/cn/lihongjie/coal/supplier/dto/SupplierDto.java index a96196fd..9ea06a8b 100644 --- a/src/main/java/cn/lihongjie/coal/supplier/dto/SupplierDto.java +++ b/src/main/java/cn/lihongjie/coal/supplier/dto/SupplierDto.java @@ -1,20 +1,22 @@ package cn.lihongjie.coal.supplier.dto; import cn.lihongjie.coal.base.dto.OrgCommonDto; + import lombok.Data; + import org.hibernate.annotations.Comment; @Data public class SupplierDto extends OrgCommonDto { - @Comment("联系人") - private String contact; + @Comment("联系人") + private String contact; - @Comment("邮箱") - private String email; + @Comment("邮箱") + private String email; - @Comment("手机号") - private String phone; + @Comment("手机号") + private String phone; - @Comment("地址") - private String address; + @Comment("地址") + private String address; } diff --git a/src/main/java/cn/lihongjie/coal/supplier/dto/UpdateSupplierDto.java b/src/main/java/cn/lihongjie/coal/supplier/dto/UpdateSupplierDto.java index 13c65f23..fbd72157 100644 --- a/src/main/java/cn/lihongjie/coal/supplier/dto/UpdateSupplierDto.java +++ b/src/main/java/cn/lihongjie/coal/supplier/dto/UpdateSupplierDto.java @@ -1,20 +1,22 @@ package cn.lihongjie.coal.supplier.dto; import cn.lihongjie.coal.base.dto.OrgCommonDto; + import lombok.Data; + import org.hibernate.annotations.Comment; @Data public class UpdateSupplierDto extends OrgCommonDto { - @Comment("联系人") - private String contact; + @Comment("联系人") + private String contact; - @Comment("邮箱") - private String email; + @Comment("邮箱") + private String email; - @Comment("手机号") - private String phone; + @Comment("手机号") + private String phone; - @Comment("地址") - private String address; + @Comment("地址") + private String address; } diff --git a/src/main/java/cn/lihongjie/coal/supplier/entity/SupplierEntity.java b/src/main/java/cn/lihongjie/coal/supplier/entity/SupplierEntity.java index 18ea7595..605acb1f 100644 --- a/src/main/java/cn/lihongjie/coal/supplier/entity/SupplierEntity.java +++ b/src/main/java/cn/lihongjie/coal/supplier/entity/SupplierEntity.java @@ -1,23 +1,26 @@ package cn.lihongjie.coal.supplier.entity; import cn.lihongjie.coal.base.entity.OrgCommonEntity; + import jakarta.persistence.Entity; + import lombok.Data; + import org.hibernate.annotations.Comment; @Data @Entity public class SupplierEntity extends OrgCommonEntity { - @Comment("联系人") - private String contact; + @Comment("联系人") + private String contact; - @Comment("邮箱") - private String email; + @Comment("邮箱") + private String email; - @Comment("手机号") - private String phone; + @Comment("手机号") + private String phone; - @Comment("地址") - private String address; + @Comment("地址") + private String address; } diff --git a/src/main/java/cn/lihongjie/coal/supplier/mapper/SupplierMapper.java b/src/main/java/cn/lihongjie/coal/supplier/mapper/SupplierMapper.java index 93982922..6774e797 100644 --- a/src/main/java/cn/lihongjie/coal/supplier/mapper/SupplierMapper.java +++ b/src/main/java/cn/lihongjie/coal/supplier/mapper/SupplierMapper.java @@ -8,12 +8,13 @@ import cn.lihongjie.coal.supplier.dto.CreateSupplierDto; import cn.lihongjie.coal.supplier.dto.SupplierDto; import cn.lihongjie.coal.supplier.dto.UpdateSupplierDto; import cn.lihongjie.coal.supplier.entity.SupplierEntity; + import org.mapstruct.Mapper; import org.mapstruct.control.DeepClone; @Mapper( - componentModel = SPRING, - uses = {CommonMapper.class}, - mappingControl = DeepClone.class) + componentModel = SPRING, + uses = {CommonMapper.class}, + mappingControl = DeepClone.class) public interface SupplierMapper - extends BaseMapper {} + extends BaseMapper {} diff --git a/src/main/java/cn/lihongjie/coal/supplier/repository/SupplierRepository.java b/src/main/java/cn/lihongjie/coal/supplier/repository/SupplierRepository.java index c850659a..99453cf3 100644 --- a/src/main/java/cn/lihongjie/coal/supplier/repository/SupplierRepository.java +++ b/src/main/java/cn/lihongjie/coal/supplier/repository/SupplierRepository.java @@ -2,6 +2,7 @@ package cn.lihongjie.coal.supplier.repository; import cn.lihongjie.coal.base.dao.BaseRepository; import cn.lihongjie.coal.supplier.entity.SupplierEntity; + import org.springframework.stereotype.Repository; @Repository diff --git a/src/main/java/cn/lihongjie/coal/supplier/service/SupplierService.java b/src/main/java/cn/lihongjie/coal/supplier/service/SupplierService.java index d4eeaa78..4792ea6d 100644 --- a/src/main/java/cn/lihongjie/coal/supplier/service/SupplierService.java +++ b/src/main/java/cn/lihongjie/coal/supplier/service/SupplierService.java @@ -9,8 +9,11 @@ import cn.lihongjie.coal.supplier.dto.UpdateSupplierDto; import cn.lihongjie.coal.supplier.entity.SupplierEntity; import cn.lihongjie.coal.supplier.mapper.SupplierMapper; import cn.lihongjie.coal.supplier.repository.SupplierRepository; + import jakarta.annotation.PostConstruct; + import lombok.extern.slf4j.Slf4j; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.convert.ConversionService; import org.springframework.data.domain.Page; @@ -22,51 +25,53 @@ import org.springframework.stereotype.Service; @Slf4j public class SupplierService extends BaseService { - @Autowired SupplierRepository repository; + @Autowired SupplierRepository repository; - @Autowired SupplierMapper mapper; + @Autowired SupplierMapper mapper; + @Autowired ConversionService conversionService; - @PostConstruct - public void init() {} + @PostConstruct + public void init() {} - public SupplierDto create(CreateSupplierDto request) { + public SupplierDto create(CreateSupplierDto request) { - SupplierEntity entity = mapper.toEntity(request); + SupplierEntity entity = mapper.toEntity(request); - this.repository.save(entity); - return getById(entity.getId()); - } + this.repository.save(entity); + return getById(entity.getId()); + } - public SupplierDto update(UpdateSupplierDto request) { - SupplierEntity entity = this.repository.get(request.getId()); - this.mapper.updateEntity(entity, request); + public SupplierDto update(UpdateSupplierDto request) { + SupplierEntity entity = this.repository.get(request.getId()); + this.mapper.updateEntity(entity, request); - this.repository.save(entity); + this.repository.save(entity); - return getById(entity.getId()); - } + return getById(entity.getId()); + } - public void delete(IdRequest request) { + public void delete(IdRequest request) { - this.repository.deleteAllById(request.getIds()); - } + this.repository.deleteAllById(request.getIds()); + } - public SupplierDto getById(String id) { + public SupplierDto getById(String id) { - SupplierEntity entity = repository.get(id); + SupplierEntity entity = repository.get(id); - return mapper.toDto(entity); - } + return mapper.toDto(entity); + } - @Autowired ConversionService conversionService; + public Page list(CommonQuery query) { - public Page list(CommonQuery query) { + Page page = + repository.findAll( + query.specification(conversionService), + PageRequest.of( + query.getPageNo(), + query.getPageSize(), + Sort.by(query.getOrders()))); - Page page = - repository.findAll( - query.specification(conversionService), - PageRequest.of(query.getPageNo(), query.getPageSize(), Sort.by(query.getOrders()))); - - return page.map(this.mapper::toDto); - } + return page.map(this.mapper::toDto); + } } diff --git a/src/main/java/cn/lihongjie/coal/sysconfig/controller/SysConfigController.java b/src/main/java/cn/lihongjie/coal/sysconfig/controller/SysConfigController.java index f3bff191..fe3233ae 100644 --- a/src/main/java/cn/lihongjie/coal/sysconfig/controller/SysConfigController.java +++ b/src/main/java/cn/lihongjie/coal/sysconfig/controller/SysConfigController.java @@ -9,6 +9,7 @@ import cn.lihongjie.coal.sysconfig.dto.SaveAllConfigDto; import cn.lihongjie.coal.sysconfig.dto.SysConfigDto; import cn.lihongjie.coal.sysconfig.dto.UpdateSysConfigDto; import cn.lihongjie.coal.sysconfig.service.SysConfigService; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.web.bind.annotation.PostMapping; @@ -21,41 +22,41 @@ import org.springframework.web.bind.annotation.RestController; @SysLog(module = "系统参数") public class SysConfigController extends BaseController { - @Autowired SysConfigService service; + @Autowired SysConfigService service; - @PostMapping("/create") - @SysLog(action = "新增") - public SysConfigDto create(@RequestBody CreateSysConfigDto dto) { - return this.service.create(dto); - } + @PostMapping("/create") + @SysLog(action = "新增") + public SysConfigDto create(@RequestBody CreateSysConfigDto dto) { + return this.service.create(dto); + } - @PostMapping("/update") - @SysLog(action = "编辑") - public SysConfigDto update(@RequestBody UpdateSysConfigDto dto) { - return this.service.update(dto); - } + @PostMapping("/update") + @SysLog(action = "编辑") + public SysConfigDto update(@RequestBody UpdateSysConfigDto dto) { + return this.service.update(dto); + } - @PostMapping("/delete") - @SysLog(action = "删除") - public Object delete(@RequestBody IdRequest dto) { - this.service.delete(dto); - return true; - } + @PostMapping("/delete") + @SysLog(action = "删除") + public Object delete(@RequestBody IdRequest dto) { + this.service.delete(dto); + return true; + } - @PostMapping("/saveAllConfig") - @SysLog(action = "更新系统配置") - public Object saveAllConfig(@RequestBody SaveAllConfigDto dto) { - this.service.saveAllConfig(dto); - return true; - } + @PostMapping("/saveAllConfig") + @SysLog(action = "更新系统配置") + public Object saveAllConfig(@RequestBody SaveAllConfigDto dto) { + this.service.saveAllConfig(dto); + return true; + } - @PostMapping("/list") - public Page list(@RequestBody CommonQuery dto) { - return this.service.list(dto); - } + @PostMapping("/list") + public Page list(@RequestBody CommonQuery dto) { + return this.service.list(dto); + } - @PostMapping("/getById") - public SysConfigDto getById(@RequestBody IdRequest dto) { - return this.service.getById(dto.getId()); - } + @PostMapping("/getById") + public SysConfigDto getById(@RequestBody IdRequest dto) { + return this.service.getById(dto.getId()); + } } diff --git a/src/main/java/cn/lihongjie/coal/sysconfig/dto/CreateSysConfigDto.java b/src/main/java/cn/lihongjie/coal/sysconfig/dto/CreateSysConfigDto.java index 43540a95..1b2c959f 100644 --- a/src/main/java/cn/lihongjie/coal/sysconfig/dto/CreateSysConfigDto.java +++ b/src/main/java/cn/lihongjie/coal/sysconfig/dto/CreateSysConfigDto.java @@ -1,27 +1,29 @@ package cn.lihongjie.coal.sysconfig.dto; import cn.lihongjie.coal.base.dto.CommonDto; + import lombok.Data; + import org.hibernate.annotations.Comment; @Data public class CreateSysConfigDto extends CommonDto { - @Comment("配置类型") - private String type; + @Comment("配置类型") + private String type; - @Comment("配置类型如果是数字, 最小值") - private Integer minValue; + @Comment("配置类型如果是数字, 最小值") + private Integer minValue; - @Comment("配置类型如果是数字, 最小值") - private Integer maxValue; + @Comment("配置类型如果是数字, 最小值") + private Integer maxValue; - @Comment("配置类型如果是字符串, 正则表达式校验") - private String regexValidator; + @Comment("配置类型如果是字符串, 正则表达式校验") + private String regexValidator; - @Comment("配置类型如果是数据字典, 字典编码") - private String dictCode; + @Comment("配置类型如果是数据字典, 字典编码") + private String dictCode; - @Comment("值") - private String configVal; + @Comment("值") + private String configVal; } diff --git a/src/main/java/cn/lihongjie/coal/sysconfig/dto/SaveAllConfigDto.java b/src/main/java/cn/lihongjie/coal/sysconfig/dto/SaveAllConfigDto.java index e28a74c5..c443e31f 100644 --- a/src/main/java/cn/lihongjie/coal/sysconfig/dto/SaveAllConfigDto.java +++ b/src/main/java/cn/lihongjie/coal/sysconfig/dto/SaveAllConfigDto.java @@ -5,5 +5,5 @@ import lombok.Data; @Data public class SaveAllConfigDto { - private List configs; + private List configs; } diff --git a/src/main/java/cn/lihongjie/coal/sysconfig/dto/SysConfigDto.java b/src/main/java/cn/lihongjie/coal/sysconfig/dto/SysConfigDto.java index 0eb82a18..6073fcb2 100644 --- a/src/main/java/cn/lihongjie/coal/sysconfig/dto/SysConfigDto.java +++ b/src/main/java/cn/lihongjie/coal/sysconfig/dto/SysConfigDto.java @@ -1,27 +1,29 @@ package cn.lihongjie.coal.sysconfig.dto; import cn.lihongjie.coal.base.dto.CommonDto; + import lombok.Data; + import org.hibernate.annotations.Comment; @Data public class SysConfigDto extends CommonDto { - @Comment("配置类型") - private String type; + @Comment("配置类型") + private String type; - @Comment("配置类型如果是数字, 最小值") - private Integer minValue; + @Comment("配置类型如果是数字, 最小值") + private Integer minValue; - @Comment("配置类型如果是数字, 最小值") - private Integer maxValue; + @Comment("配置类型如果是数字, 最小值") + private Integer maxValue; - @Comment("配置类型如果是字符串, 正则表达式校验") - private String regexValidator; + @Comment("配置类型如果是字符串, 正则表达式校验") + private String regexValidator; - @Comment("配置类型如果是数据字典, 字典编码") - private String dictCode; + @Comment("配置类型如果是数据字典, 字典编码") + private String dictCode; - @Comment("值") - private String configVal; + @Comment("值") + private String configVal; } diff --git a/src/main/java/cn/lihongjie/coal/sysconfig/dto/UpdateSysConfigDto.java b/src/main/java/cn/lihongjie/coal/sysconfig/dto/UpdateSysConfigDto.java index 8f0dfc20..a0f1f1bf 100644 --- a/src/main/java/cn/lihongjie/coal/sysconfig/dto/UpdateSysConfigDto.java +++ b/src/main/java/cn/lihongjie/coal/sysconfig/dto/UpdateSysConfigDto.java @@ -1,27 +1,29 @@ package cn.lihongjie.coal.sysconfig.dto; import cn.lihongjie.coal.base.dto.CommonDto; + import lombok.Data; + import org.hibernate.annotations.Comment; @Data public class UpdateSysConfigDto extends CommonDto { - @Comment("配置类型") - private String type; + @Comment("配置类型") + private String type; - @Comment("配置类型如果是数字, 最小值") - private Integer minValue; + @Comment("配置类型如果是数字, 最小值") + private Integer minValue; - @Comment("配置类型如果是数字, 最小值") - private Integer maxValue; + @Comment("配置类型如果是数字, 最小值") + private Integer maxValue; - @Comment("配置类型如果是字符串, 正则表达式校验") - private String regexValidator; + @Comment("配置类型如果是字符串, 正则表达式校验") + private String regexValidator; - @Comment("配置类型如果是数据字典, 字典编码") - private String dictCode; + @Comment("配置类型如果是数据字典, 字典编码") + private String dictCode; - @Comment("值") - private String configVal; + @Comment("值") + private String configVal; } diff --git a/src/main/java/cn/lihongjie/coal/sysconfig/entity/SysConfigEntity.java b/src/main/java/cn/lihongjie/coal/sysconfig/entity/SysConfigEntity.java index b8dfd2df..b31bd8fb 100644 --- a/src/main/java/cn/lihongjie/coal/sysconfig/entity/SysConfigEntity.java +++ b/src/main/java/cn/lihongjie/coal/sysconfig/entity/SysConfigEntity.java @@ -1,8 +1,11 @@ package cn.lihongjie.coal.sysconfig.entity; import cn.lihongjie.coal.base.entity.CommonEntity; + import jakarta.persistence.Entity; + import lombok.Data; + import org.hibernate.annotations.Comment; @Data @@ -10,38 +13,38 @@ import org.hibernate.annotations.Comment; @Comment("系统配置") public class SysConfigEntity extends CommonEntity { - @Comment("配置类型 1 字符串 2 数字 3 数据字典") - private String type; + @Comment("配置类型 1 字符串 2 数字 3 数据字典") + private String type; - @Comment("配置类型如果是数字, 最小值") - private Integer minValue; + @Comment("配置类型如果是数字, 最小值") + private Integer minValue; - @Comment("配置类型如果是数字, 最小值") - private Integer maxValue; + @Comment("配置类型如果是数字, 最小值") + private Integer maxValue; - @Comment("配置类型如果是字符串, 正则表达式校验") - private String regexValidator; + @Comment("配置类型如果是字符串, 正则表达式校验") + private String regexValidator; - @Comment("配置类型如果是数据字典, 字典编码") - private String dictCode; + @Comment("配置类型如果是数据字典, 字典编码") + private String dictCode; - @Comment("值") - private String configVal; + @Comment("值") + private String configVal; - public void validate(String configVal) { + public void validate(String configVal) { - switch (type) { - case "1": - if (!configVal.matches(regexValidator)) { - throw new RuntimeException("字符串不符合正则表达式"); + switch (type) { + case "1": + if (!configVal.matches(regexValidator)) { + throw new RuntimeException("字符串不符合正则表达式"); + } + break; + case "2": + Integer integer = Integer.valueOf(configVal); + if (integer < minValue || integer > maxValue) { + throw new RuntimeException("数字不符合要求"); + } + break; } - break; - case "2": - Integer integer = Integer.valueOf(configVal); - if (integer < minValue || integer > maxValue) { - throw new RuntimeException("数字不符合要求"); - } - break; } - } } diff --git a/src/main/java/cn/lihongjie/coal/sysconfig/mapper/SysConfigMapper.java b/src/main/java/cn/lihongjie/coal/sysconfig/mapper/SysConfigMapper.java index a2e7af6d..8720d78c 100644 --- a/src/main/java/cn/lihongjie/coal/sysconfig/mapper/SysConfigMapper.java +++ b/src/main/java/cn/lihongjie/coal/sysconfig/mapper/SysConfigMapper.java @@ -11,8 +11,8 @@ import org.mapstruct.MappingConstants; import org.mapstruct.control.DeepClone; @Mapper( - componentModel = MappingConstants.ComponentModel.SPRING, - uses = {CommonMapper.class}, - mappingControl = DeepClone.class) + componentModel = MappingConstants.ComponentModel.SPRING, + uses = {CommonMapper.class}, + mappingControl = DeepClone.class) public interface SysConfigMapper - extends BaseMapper {} + extends BaseMapper {} diff --git a/src/main/java/cn/lihongjie/coal/sysconfig/repository/SysConfigRepository.java b/src/main/java/cn/lihongjie/coal/sysconfig/repository/SysConfigRepository.java index 5842fffc..6ee47f10 100644 --- a/src/main/java/cn/lihongjie/coal/sysconfig/repository/SysConfigRepository.java +++ b/src/main/java/cn/lihongjie/coal/sysconfig/repository/SysConfigRepository.java @@ -2,9 +2,10 @@ package cn.lihongjie.coal.sysconfig.repository; import cn.lihongjie.coal.base.dao.BaseRepository; import cn.lihongjie.coal.sysconfig.entity.SysConfigEntity; + import org.springframework.stereotype.Repository; @Repository public interface SysConfigRepository extends BaseRepository { - SysConfigEntity findByCode(String configKey); + SysConfigEntity findByCode(String configKey); } diff --git a/src/main/java/cn/lihongjie/coal/sysconfig/service/SysConfigService.java b/src/main/java/cn/lihongjie/coal/sysconfig/service/SysConfigService.java index 7ae44197..287cd1ef 100644 --- a/src/main/java/cn/lihongjie/coal/sysconfig/service/SysConfigService.java +++ b/src/main/java/cn/lihongjie/coal/sysconfig/service/SysConfigService.java @@ -13,13 +13,13 @@ import cn.lihongjie.coal.sysconfig.dto.UpdateSysConfigDto; import cn.lihongjie.coal.sysconfig.entity.SysConfigEntity; import cn.lihongjie.coal.sysconfig.mapper.SysConfigMapper; import cn.lihongjie.coal.sysconfig.repository.SysConfigRepository; + import io.vavr.Tuple2; + import jakarta.annotation.PostConstruct; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; -import java.util.stream.StreamSupport; + import lombok.extern.slf4j.Slf4j; + import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.convert.ConversionService; @@ -28,108 +28,117 @@ import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Sort; import org.springframework.stereotype.Service; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; +import java.util.stream.StreamSupport; + @Service @Slf4j public class SysConfigService extends BaseService { - @Autowired SysConfigRepository repository; + @Autowired SysConfigRepository repository; - @Autowired SysConfigMapper mapper; + @Autowired SysConfigMapper mapper; + @Autowired ConversionService conversionService; - @PostConstruct - public void init() {} + @PostConstruct + public void init() {} - public void initDefault() { + public void initDefault() { - Map all = - StreamSupport.stream(findAll().spliterator(), false) - .collect(Collectors.toMap(e -> e.getCode(), e -> e)); + Map all = + StreamSupport.stream(findAll().spliterator(), false) + .collect(Collectors.toMap(e -> e.getCode(), e -> e)); - if (!all.containsKey(Constants.SYSCONFIG_ENABLE_CAPTCHA)) { - SysConfigEntity entity = new SysConfigEntity(); - entity.setName("验证码状态"); - entity.setCode(Constants.SYSCONFIG_ENABLE_CAPTCHA); - entity.setConfigVal("1"); - entity.setDictCode("status.type"); - entity.setMaxValue(null); - entity.setMinValue(null); - entity.setRegexValidator(null); - entity.setType("3"); - repository.save(entity); + if (!all.containsKey(Constants.SYSCONFIG_ENABLE_CAPTCHA)) { + SysConfigEntity entity = new SysConfigEntity(); + entity.setName("验证码状态"); + entity.setCode(Constants.SYSCONFIG_ENABLE_CAPTCHA); + entity.setConfigVal("1"); + entity.setDictCode("status.type"); + entity.setMaxValue(null); + entity.setMinValue(null); + entity.setRegexValidator(null); + entity.setType("3"); + repository.save(entity); + } } - } - public String getConfigVal(String configKey) { + public String getConfigVal(String configKey) { - SysConfigEntity config = this.repository.findByCode(configKey); + SysConfigEntity config = this.repository.findByCode(configKey); - return config.getConfigVal(); - } + return config.getConfigVal(); + } - public boolean isEnable(String configKey) { - return StringUtils.equalsIgnoreCase(getConfigVal(configKey), "1"); - } + public boolean isEnable(String configKey) { + return StringUtils.equalsIgnoreCase(getConfigVal(configKey), "1"); + } - public void saveAllConfig(SaveAllConfigDto dto) { + public void saveAllConfig(SaveAllConfigDto dto) { - List all = findAll(); + List all = findAll(); - List> joins = - CollectionUtils.leftHashJoin( - all, dto.getConfigs(), SysConfigEntity::getCode, CreateSysConfigDto::getCode); + List> joins = + CollectionUtils.leftHashJoin( + all, + dto.getConfigs(), + SysConfigEntity::getCode, + CreateSysConfigDto::getCode); - joins.forEach( - x -> { - if (x._2 == null) { - throw new BizException("缺少配置项 {}", x._1.getName()); - } - ; + joins.forEach( + x -> { + if (x._2 == null) { + throw new BizException("缺少配置项 {}", x._1.getName()); + } - x._1.validate(x._2.getConfigVal()); - x._1.setConfigVal(x._2.getConfigVal()); - }); + x._1.validate(x._2.getConfigVal()); + x._1.setConfigVal(x._2.getConfigVal()); + }); - this.repository.saveAll(joins.stream().map(x -> x._1).collect(Collectors.toList())); - } + this.repository.saveAll(joins.stream().map(x -> x._1).collect(Collectors.toList())); + } - public SysConfigDto create(CreateSysConfigDto request) { + public SysConfigDto create(CreateSysConfigDto request) { - SysConfigEntity entity = mapper.toEntity(request); + SysConfigEntity entity = mapper.toEntity(request); - this.repository.save(entity); - return getById(entity.getId()); - } + this.repository.save(entity); + return getById(entity.getId()); + } - public SysConfigDto update(UpdateSysConfigDto request) { - SysConfigEntity entity = this.repository.get(request.getId()); - this.mapper.updateEntity(entity, request); + public SysConfigDto update(UpdateSysConfigDto request) { + SysConfigEntity entity = this.repository.get(request.getId()); + this.mapper.updateEntity(entity, request); - this.repository.save(entity); + this.repository.save(entity); - return getById(entity.getId()); - } + return getById(entity.getId()); + } - public void delete(IdRequest request) { + public void delete(IdRequest request) { - this.repository.deleteAllById(request.getIds()); - } + this.repository.deleteAllById(request.getIds()); + } - public SysConfigDto getById(String id) { + public SysConfigDto getById(String id) { - SysConfigEntity entity = repository.get(id); + SysConfigEntity entity = repository.get(id); - return mapper.toDto(entity); - } + return mapper.toDto(entity); + } - @Autowired ConversionService conversionService; + public Page list(CommonQuery query) { - public Page list(CommonQuery query) { + Page page = + repository.findAll( + query.specification(conversionService), + PageRequest.of( + query.getPageNo(), + query.getPageSize(), + Sort.by(query.getOrders()))); - Page page = - repository.findAll( - query.specification(conversionService), - PageRequest.of(query.getPageNo(), query.getPageSize(), Sort.by(query.getOrders()))); - - return page.map(this.mapper::toDto); - } + return page.map(this.mapper::toDto); + } } diff --git a/src/main/java/cn/lihongjie/coal/syslog/controller/SysLogController.java b/src/main/java/cn/lihongjie/coal/syslog/controller/SysLogController.java index 0b4a5000..17d62004 100644 --- a/src/main/java/cn/lihongjie/coal/syslog/controller/SysLogController.java +++ b/src/main/java/cn/lihongjie/coal/syslog/controller/SysLogController.java @@ -7,6 +7,7 @@ import cn.lihongjie.coal.syslog.dto.CreateSysLogDto; import cn.lihongjie.coal.syslog.dto.SysLogDto; import cn.lihongjie.coal.syslog.dto.UpdateSysLogDto; import cn.lihongjie.coal.syslog.service.SysLogService; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.web.bind.annotation.PostMapping; @@ -19,34 +20,34 @@ import org.springframework.web.bind.annotation.RestController; @SysLog(module = "系统日志") public class SysLogController { - @Autowired SysLogService service; + @Autowired SysLogService service; - @PostMapping("/create") - @SysLog(action = "新增") - public SysLogDto create(@RequestBody CreateSysLogDto dto) { - return this.service.create(dto); - } + @PostMapping("/create") + @SysLog(action = "新增") + public SysLogDto create(@RequestBody CreateSysLogDto dto) { + return this.service.create(dto); + } - @PostMapping("/update") - @SysLog(action = "编辑") - public SysLogDto update(@RequestBody UpdateSysLogDto dto) { - return this.service.update(dto); - } + @PostMapping("/update") + @SysLog(action = "编辑") + public SysLogDto update(@RequestBody UpdateSysLogDto dto) { + return this.service.update(dto); + } - @PostMapping("/delete") - @SysLog(action = "删除") - public Object delete(@RequestBody IdRequest dto) { - this.service.delete(dto); - return true; - } + @PostMapping("/delete") + @SysLog(action = "删除") + public Object delete(@RequestBody IdRequest dto) { + this.service.delete(dto); + return true; + } - @PostMapping("/list") - public Page list(@RequestBody CommonQuery dto) { - return this.service.list(dto); - } + @PostMapping("/list") + public Page list(@RequestBody CommonQuery dto) { + return this.service.list(dto); + } - @PostMapping("/getById") - public SysLogDto getById(@RequestBody IdRequest dto) { - return this.service.getById(dto.getId()); - } + @PostMapping("/getById") + public SysLogDto getById(@RequestBody IdRequest dto) { + return this.service.getById(dto.getId()); + } } diff --git a/src/main/java/cn/lihongjie/coal/syslog/dto/CreateSysLogDto.java b/src/main/java/cn/lihongjie/coal/syslog/dto/CreateSysLogDto.java index 547e1d36..b12377fc 100644 --- a/src/main/java/cn/lihongjie/coal/syslog/dto/CreateSysLogDto.java +++ b/src/main/java/cn/lihongjie/coal/syslog/dto/CreateSysLogDto.java @@ -1,39 +1,41 @@ package cn.lihongjie.coal.syslog.dto; import cn.lihongjie.coal.base.dto.OrgCommonDto; + import lombok.Data; + import org.hibernate.annotations.Comment; @Data public class CreateSysLogDto extends OrgCommonDto { - @Comment("ip") - private String ip; + @Comment("ip") + private String ip; - @Comment("模块") - private String module; + @Comment("模块") + private String module; - @Comment("操作") - private String action; + @Comment("操作") + private String action; - @Comment("详细信息") - private String message; + @Comment("详细信息") + private String message; - @Comment("ip定位") - private String ipLocation; + @Comment("ip定位") + private String ipLocation; - @Comment("userAgent") - private String userAgent; + @Comment("userAgent") + private String userAgent; - @Comment("耗时") - private Integer timeCost; + @Comment("耗时") + private Integer timeCost; - @Comment("URL") - private String url; + @Comment("URL") + private String url; - @Comment("错误堆栈") - private String stacktrace; + @Comment("错误堆栈") + private String stacktrace; - private String optStatus; - private String optStatusName; + private String optStatus; + private String optStatusName; } diff --git a/src/main/java/cn/lihongjie/coal/syslog/dto/SysLogDto.java b/src/main/java/cn/lihongjie/coal/syslog/dto/SysLogDto.java index 7474e668..200c82a3 100644 --- a/src/main/java/cn/lihongjie/coal/syslog/dto/SysLogDto.java +++ b/src/main/java/cn/lihongjie/coal/syslog/dto/SysLogDto.java @@ -1,39 +1,41 @@ package cn.lihongjie.coal.syslog.dto; import cn.lihongjie.coal.base.dto.OrgCommonDto; + import lombok.Data; + import org.hibernate.annotations.Comment; @Data public class SysLogDto extends OrgCommonDto { - private String optStatus; - private String optStatusName; + private String optStatus; + private String optStatusName; - @Comment("ip") - private String ip; + @Comment("ip") + private String ip; - @Comment("模块") - private String module; + @Comment("模块") + private String module; - @Comment("操作") - private String action; + @Comment("操作") + private String action; - @Comment("详细信息") - private String message; + @Comment("详细信息") + private String message; - @Comment("ip定位") - private String ipLocation; + @Comment("ip定位") + private String ipLocation; - @Comment("userAgent") - private String userAgent; + @Comment("userAgent") + private String userAgent; - @Comment("耗时") - private Integer timeCost; + @Comment("耗时") + private Integer timeCost; - @Comment("URL") - private String url; + @Comment("URL") + private String url; - @Comment("错误堆栈") - private String stacktrace; + @Comment("错误堆栈") + private String stacktrace; } diff --git a/src/main/java/cn/lihongjie/coal/syslog/dto/UpdateSysLogDto.java b/src/main/java/cn/lihongjie/coal/syslog/dto/UpdateSysLogDto.java index 3f379304..ae7a6887 100644 --- a/src/main/java/cn/lihongjie/coal/syslog/dto/UpdateSysLogDto.java +++ b/src/main/java/cn/lihongjie/coal/syslog/dto/UpdateSysLogDto.java @@ -1,39 +1,41 @@ package cn.lihongjie.coal.syslog.dto; import cn.lihongjie.coal.base.dto.OrgCommonDto; + import lombok.Data; + import org.hibernate.annotations.Comment; @Data public class UpdateSysLogDto extends OrgCommonDto { - @Comment("ip") - private String ip; + @Comment("ip") + private String ip; - @Comment("模块") - private String module; + @Comment("模块") + private String module; - @Comment("操作") - private String action; + @Comment("操作") + private String action; - @Comment("详细信息") - private String message; + @Comment("详细信息") + private String message; - @Comment("ip定位") - private String ipLocation; + @Comment("ip定位") + private String ipLocation; - @Comment("userAgent") - private String userAgent; + @Comment("userAgent") + private String userAgent; - @Comment("耗时") - private Integer timeCost; + @Comment("耗时") + private Integer timeCost; - @Comment("URL") - private String url; + @Comment("URL") + private String url; - @Comment("错误堆栈") - private String stacktrace; + @Comment("错误堆栈") + private String stacktrace; - private String optStatus; - private String optStatusName; + private String optStatus; + private String optStatusName; } diff --git a/src/main/java/cn/lihongjie/coal/syslog/entity/SysLogEntity.java b/src/main/java/cn/lihongjie/coal/syslog/entity/SysLogEntity.java index 80af7ed7..5cc7f3cc 100644 --- a/src/main/java/cn/lihongjie/coal/syslog/entity/SysLogEntity.java +++ b/src/main/java/cn/lihongjie/coal/syslog/entity/SysLogEntity.java @@ -1,8 +1,11 @@ package cn.lihongjie.coal.syslog.entity; import cn.lihongjie.coal.base.entity.OrgBaseEntity; + import jakarta.persistence.Entity; + import lombok.Data; + import org.hibernate.annotations.Comment; import org.hibernate.annotations.Formula; @@ -11,42 +14,42 @@ import org.hibernate.annotations.Formula; @Comment("操作日志") public class SysLogEntity extends OrgBaseEntity { - @Comment("ip") - private String ip; + @Comment("ip") + private String ip; - @Comment("模块") - private String module; + @Comment("模块") + private String module; - @Comment("操作") - private String action; + @Comment("操作") + private String action; - @Comment("详细信息") - private String message; + @Comment("详细信息") + private String message; - @Comment("ip定位") - private String ipLocation; + @Comment("ip定位") + private String ipLocation; - @Comment("userAgent") - private String userAgent; + @Comment("userAgent") + private String userAgent; - @Comment("耗时") - private Integer timeCost; + @Comment("耗时") + private Integer timeCost; - @Comment("URL") - private String url; + @Comment("URL") + private String url; - @Comment("操作状态 0 成功 1 失败") - private String optStatus; + @Comment("操作状态 0 成功 1 失败") + private String optStatus; - @Formula( - "(select i.name\n" - + "from t_dictionary d,\n" - + " t_dictionary_item i\n" - + "where d.id = i.dictionary_id\n" - + " and d.code = 'syslog.status'\n" - + " and i.code = opt_status)") - private String optStatusName; + @Formula( + "(select i.name\n" + + "from t_dictionary d,\n" + + " t_dictionary_item i\n" + + "where d.id = i.dictionary_id\n" + + " and d.code = 'syslog.status'\n" + + " and i.code = opt_status)") + private String optStatusName; - @Comment("错误堆栈") - private String stacktrace; + @Comment("错误堆栈") + private String stacktrace; } diff --git a/src/main/java/cn/lihongjie/coal/syslog/mapper/SysLogMapper.java b/src/main/java/cn/lihongjie/coal/syslog/mapper/SysLogMapper.java index 5244aa2f..5bcd721b 100644 --- a/src/main/java/cn/lihongjie/coal/syslog/mapper/SysLogMapper.java +++ b/src/main/java/cn/lihongjie/coal/syslog/mapper/SysLogMapper.java @@ -11,8 +11,8 @@ import org.mapstruct.MappingConstants; import org.mapstruct.control.DeepClone; @Mapper( - componentModel = MappingConstants.ComponentModel.SPRING, - uses = {CommonMapper.class}, - mappingControl = DeepClone.class) + componentModel = MappingConstants.ComponentModel.SPRING, + uses = {CommonMapper.class}, + mappingControl = DeepClone.class) public interface SysLogMapper - extends BaseMapper {} + extends BaseMapper {} diff --git a/src/main/java/cn/lihongjie/coal/syslog/repository/SysLogRepository.java b/src/main/java/cn/lihongjie/coal/syslog/repository/SysLogRepository.java index b93e09b5..dcb7c172 100644 --- a/src/main/java/cn/lihongjie/coal/syslog/repository/SysLogRepository.java +++ b/src/main/java/cn/lihongjie/coal/syslog/repository/SysLogRepository.java @@ -2,6 +2,7 @@ package cn.lihongjie.coal.syslog.repository; import cn.lihongjie.coal.base.dao.BaseRepository; import cn.lihongjie.coal.syslog.entity.SysLogEntity; + import org.springframework.stereotype.Repository; @Repository diff --git a/src/main/java/cn/lihongjie/coal/syslog/service/SysLogService.java b/src/main/java/cn/lihongjie/coal/syslog/service/SysLogService.java index 80cf40b6..b5720568 100644 --- a/src/main/java/cn/lihongjie/coal/syslog/service/SysLogService.java +++ b/src/main/java/cn/lihongjie/coal/syslog/service/SysLogService.java @@ -9,8 +9,11 @@ import cn.lihongjie.coal.syslog.dto.UpdateSysLogDto; import cn.lihongjie.coal.syslog.entity.SysLogEntity; import cn.lihongjie.coal.syslog.mapper.SysLogMapper; import cn.lihongjie.coal.syslog.repository.SysLogRepository; + import jakarta.annotation.PostConstruct; + import lombok.extern.slf4j.Slf4j; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.convert.ConversionService; import org.springframework.data.domain.Page; @@ -23,58 +26,60 @@ import org.springframework.stereotype.Service; @Slf4j public class SysLogService extends BaseService { - @Autowired SysLogRepository repository; + @Autowired SysLogRepository repository; - @Autowired SysLogMapper mapper; + @Autowired SysLogMapper mapper; + @Autowired ConversionService conversionService; - @PostConstruct - public void init() {} + @PostConstruct + public void init() {} - public SysLogDto create(CreateSysLogDto request) { + public SysLogDto create(CreateSysLogDto request) { - SysLogEntity entity = mapper.toEntity(request); + SysLogEntity entity = mapper.toEntity(request); - this.repository.save(entity); - return getById(entity.getId()); - } + this.repository.save(entity); + return getById(entity.getId()); + } - public SysLogDto update(UpdateSysLogDto request) { - SysLogEntity entity = this.repository.get(request.getId()); - this.mapper.updateEntity(entity, request); + public SysLogDto update(UpdateSysLogDto request) { + SysLogEntity entity = this.repository.get(request.getId()); + this.mapper.updateEntity(entity, request); - this.repository.save(entity); + this.repository.save(entity); - return getById(entity.getId()); - } + return getById(entity.getId()); + } - public void delete(IdRequest request) { + public void delete(IdRequest request) { - this.repository.deleteAllById(request.getIds()); - } + this.repository.deleteAllById(request.getIds()); + } - public SysLogDto getById(String id) { + public SysLogDto getById(String id) { - SysLogEntity entity = repository.get(id); + SysLogEntity entity = repository.get(id); - return mapper.toDto(entity); - } + return mapper.toDto(entity); + } - @Autowired ConversionService conversionService; + @Override + @Async + public void save(SysLogEntity entity) { - @Override - @Async - public void save(SysLogEntity entity) { + super.save(entity); + } - super.save(entity); - } + public Page list(CommonQuery query) { - public Page list(CommonQuery query) { + Page page = + repository.findAll( + query.specification(conversionService), + PageRequest.of( + query.getPageNo(), + query.getPageSize(), + Sort.by(query.getOrders()))); - Page page = - repository.findAll( - query.specification(conversionService), - PageRequest.of(query.getPageNo(), query.getPageSize(), Sort.by(query.getOrders()))); - - return page.map(this.mapper::toDto); - } + return page.map(this.mapper::toDto); + } } diff --git a/src/main/java/cn/lihongjie/coal/user/controller/UserController.java b/src/main/java/cn/lihongjie/coal/user/controller/UserController.java index d37b3c59..3a3c213c 100644 --- a/src/main/java/cn/lihongjie/coal/user/controller/UserController.java +++ b/src/main/java/cn/lihongjie/coal/user/controller/UserController.java @@ -10,6 +10,7 @@ import cn.lihongjie.coal.user.dto.CreateUserDto; import cn.lihongjie.coal.user.dto.UpdateUserDto; import cn.lihongjie.coal.user.dto.UserDto; import cn.lihongjie.coal.user.service.UserService; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.web.bind.annotation.PostMapping; @@ -23,39 +24,39 @@ import org.springframework.web.bind.annotation.RestController; @OrgScope public class UserController extends BaseController { - @Autowired UserService service; + @Autowired UserService service; - @PostMapping("/create") - @SysLog(action = "新增") - public UserDto create(@RequestBody CreateUserDto dto) { - return this.service.create(dto); - } + @PostMapping("/create") + @SysLog(action = "新增") + public UserDto create(@RequestBody CreateUserDto dto) { + return this.service.create(dto); + } - @PostMapping("/update") - @SysLog(action = "编辑") - public UserDto update(@RequestBody UpdateUserDto dto) { - return this.service.update(dto); - } + @PostMapping("/update") + @SysLog(action = "编辑") + public UserDto update(@RequestBody UpdateUserDto dto) { + return this.service.update(dto); + } - @PostMapping("/delete") - @SysLog(action = "删除") - public Object delete(@RequestBody IdRequest dto) { - this.service.delete(dto); - return true; - } + @PostMapping("/delete") + @SysLog(action = "删除") + public Object delete(@RequestBody IdRequest dto) { + this.service.delete(dto); + return true; + } - @PostMapping("/changePwd") - public UserDto create(@RequestBody ChangeUserPwdDto dto) { - return this.service.changePwd(dto); - } + @PostMapping("/changePwd") + public UserDto create(@RequestBody ChangeUserPwdDto dto) { + return this.service.changePwd(dto); + } - @PostMapping("/list") - public Page list(@RequestBody CommonQuery dto) { - return this.service.list(dto); - } + @PostMapping("/list") + public Page list(@RequestBody CommonQuery dto) { + return this.service.list(dto); + } - @PostMapping("/getById") - public UserDto getById(@RequestBody IdRequest dto) { - return this.service.getById(dto.getId()); - } + @PostMapping("/getById") + public UserDto getById(@RequestBody IdRequest dto) { + return this.service.getById(dto.getId()); + } } diff --git a/src/main/java/cn/lihongjie/coal/user/dto/ChangeUserPwdDto.java b/src/main/java/cn/lihongjie/coal/user/dto/ChangeUserPwdDto.java index 06c32acb..06f959b3 100644 --- a/src/main/java/cn/lihongjie/coal/user/dto/ChangeUserPwdDto.java +++ b/src/main/java/cn/lihongjie/coal/user/dto/ChangeUserPwdDto.java @@ -1,11 +1,12 @@ package cn.lihongjie.coal.user.dto; import cn.lihongjie.coal.base.dto.CommonDto; + import lombok.Data; @Data public class ChangeUserPwdDto extends CommonDto { - private String newPassword; - private String newPassword2; + private String newPassword; + private String newPassword2; } diff --git a/src/main/java/cn/lihongjie/coal/user/dto/CreateUserDto.java b/src/main/java/cn/lihongjie/coal/user/dto/CreateUserDto.java index 583b17b0..8461c198 100644 --- a/src/main/java/cn/lihongjie/coal/user/dto/CreateUserDto.java +++ b/src/main/java/cn/lihongjie/coal/user/dto/CreateUserDto.java @@ -1,24 +1,27 @@ package cn.lihongjie.coal.user.dto; import cn.lihongjie.coal.base.dto.OrgCommonDto; -import java.util.List; + import lombok.Data; + import org.hibernate.annotations.Comment; +import java.util.List; + @Data public class CreateUserDto extends OrgCommonDto { - @Comment("用户名") - private String username; + @Comment("用户名") + private String username; - @Comment("密码") - private String password; + @Comment("密码") + private String password; - @Comment("邮箱") - private String email; + @Comment("邮箱") + private String email; - @Comment("手机号") - private String phone; + @Comment("手机号") + private String phone; - private List roles; + private List roles; } diff --git a/src/main/java/cn/lihongjie/coal/user/dto/UpdateUserDto.java b/src/main/java/cn/lihongjie/coal/user/dto/UpdateUserDto.java index a0ad7bab..6b4634e5 100644 --- a/src/main/java/cn/lihongjie/coal/user/dto/UpdateUserDto.java +++ b/src/main/java/cn/lihongjie/coal/user/dto/UpdateUserDto.java @@ -1,18 +1,21 @@ package cn.lihongjie.coal.user.dto; import cn.lihongjie.coal.base.dto.OrgCommonDto; -import java.util.List; + import lombok.Data; + import org.hibernate.annotations.Comment; +import java.util.List; + @Data public class UpdateUserDto extends OrgCommonDto { - @Comment("邮箱") - private String email; + @Comment("邮箱") + private String email; - @Comment("手机号") - private String phone; + @Comment("手机号") + private String phone; - private List roles; + private List roles; } diff --git a/src/main/java/cn/lihongjie/coal/user/dto/UserDto.java b/src/main/java/cn/lihongjie/coal/user/dto/UserDto.java index 9b8137b8..a6602316 100644 --- a/src/main/java/cn/lihongjie/coal/user/dto/UserDto.java +++ b/src/main/java/cn/lihongjie/coal/user/dto/UserDto.java @@ -1,26 +1,28 @@ package cn.lihongjie.coal.user.dto; import cn.lihongjie.coal.base.dto.OrgCommonDto; -import java.util.List; + import lombok.Data; + import org.hibernate.annotations.Comment; +import java.util.List; + @Data public class UserDto extends OrgCommonDto { - @Comment("用户名") - private String username; + @Comment("用户名") + private String username; - @Comment("邮箱") - private String email; + @Comment("邮箱") + private String email; - @Comment("手机号") - private String phone; + @Comment("手机号") + private String phone; - @Comment("会话ID") - private String sessionId; + @Comment("会话ID") + private String sessionId; + private List roles; - @Data - public static class RoleDto extends OrgCommonDto {} - - private List roles; + @Data + public static class RoleDto extends OrgCommonDto {} } diff --git a/src/main/java/cn/lihongjie/coal/user/entity/UserEntity.java b/src/main/java/cn/lihongjie/coal/user/entity/UserEntity.java index a74220d5..20524b6a 100644 --- a/src/main/java/cn/lihongjie/coal/user/entity/UserEntity.java +++ b/src/main/java/cn/lihongjie/coal/user/entity/UserEntity.java @@ -2,44 +2,52 @@ package cn.lihongjie.coal.user.entity; import cn.lihongjie.coal.base.entity.OrgCommonEntity; import cn.lihongjie.coal.role.entity.RoleEntity; + import jakarta.persistence.Cacheable; import jakarta.persistence.Entity; import jakarta.persistence.JoinTable; import jakarta.persistence.ManyToMany; -import java.util.List; + import lombok.Data; + import org.hibernate.annotations.Cache; import org.hibernate.annotations.Comment; +import java.util.List; + @Data @Entity @Cacheable public class UserEntity extends OrgCommonEntity { - @Comment("用户名") - private String username; + @Comment("用户名") + private String username; - @Comment("密码") - private String password; + @Comment("密码") + private String password; - @Comment("邮箱") - private String email; + @Comment("邮箱") + private String email; - @Comment("手机号") - private String phone; + @Comment("手机号") + private String phone; - @ManyToMany() - @JoinTable( - indexes = { - @jakarta.persistence.Index(name = "idx_user_roles_users_id", columnList = "users_id"), - @jakarta.persistence.Index(name = "idx_user_roles_roles_id", columnList = "roles_id") - }) - @Cache(usage = org.hibernate.annotations.CacheConcurrencyStrategy.READ_WRITE) - private List roles; + @ManyToMany() + @JoinTable( + indexes = { + @jakarta.persistence.Index( + name = "idx_user_roles_users_id", + columnList = "users_id"), + @jakarta.persistence.Index( + name = "idx_user_roles_roles_id", + columnList = "roles_id") + }) + @Cache(usage = org.hibernate.annotations.CacheConcurrencyStrategy.READ_WRITE) + private List roles; - @Comment("机构管理员标识") - private Boolean orgAdmin; + @Comment("机构管理员标识") + private Boolean orgAdmin; - @Comment("系统管理员标识") - private Boolean sysAdmin; + @Comment("系统管理员标识") + private Boolean sysAdmin; } diff --git a/src/main/java/cn/lihongjie/coal/user/mapper/UserMapper.java b/src/main/java/cn/lihongjie/coal/user/mapper/UserMapper.java index 1f91e19c..16e8a7b4 100644 --- a/src/main/java/cn/lihongjie/coal/user/mapper/UserMapper.java +++ b/src/main/java/cn/lihongjie/coal/user/mapper/UserMapper.java @@ -6,12 +6,13 @@ import cn.lihongjie.coal.user.dto.CreateUserDto; import cn.lihongjie.coal.user.dto.UpdateUserDto; import cn.lihongjie.coal.user.dto.UserDto; import cn.lihongjie.coal.user.entity.UserEntity; + import org.mapstruct.Mapper; import org.mapstruct.MappingConstants; import org.mapstruct.control.DeepClone; @Mapper( - componentModel = MappingConstants.ComponentModel.SPRING, - uses = {CommonMapper.class}, - mappingControl = DeepClone.class) + componentModel = MappingConstants.ComponentModel.SPRING, + uses = {CommonMapper.class}, + mappingControl = DeepClone.class) public interface UserMapper extends BaseMapper {} diff --git a/src/main/java/cn/lihongjie/coal/user/repository/UserRepository.java b/src/main/java/cn/lihongjie/coal/user/repository/UserRepository.java index a7c7e889..f760979c 100644 --- a/src/main/java/cn/lihongjie/coal/user/repository/UserRepository.java +++ b/src/main/java/cn/lihongjie/coal/user/repository/UserRepository.java @@ -2,10 +2,11 @@ package cn.lihongjie.coal.user.repository; import cn.lihongjie.coal.base.dao.BaseRepository; import cn.lihongjie.coal.user.entity.UserEntity; + import org.springframework.stereotype.Repository; @Repository public interface UserRepository extends BaseRepository { - public UserEntity findByUsername(String username); + UserEntity findByUsername(String username); } diff --git a/src/main/java/cn/lihongjie/coal/user/service/UserService.java b/src/main/java/cn/lihongjie/coal/user/service/UserService.java index 875c308b..bdeba3fc 100644 --- a/src/main/java/cn/lihongjie/coal/user/service/UserService.java +++ b/src/main/java/cn/lihongjie/coal/user/service/UserService.java @@ -13,13 +13,15 @@ import cn.lihongjie.coal.user.dto.UserDto; import cn.lihongjie.coal.user.entity.UserEntity; import cn.lihongjie.coal.user.mapper.UserMapper; import cn.lihongjie.coal.user.repository.UserRepository; + import jakarta.annotation.PostConstruct; import jakarta.persistence.criteria.CriteriaBuilder; import jakarta.persistence.criteria.CriteriaQuery; import jakarta.persistence.criteria.Predicate; import jakarta.persistence.criteria.Root; -import java.util.Optional; + import lombok.extern.slf4j.Slf4j; + import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.convert.ConversionService; @@ -31,139 +33,143 @@ import org.springframework.security.crypto.password.Pbkdf2PasswordEncoder; import org.springframework.stereotype.Service; import org.springframework.util.StopWatch; +import java.util.Optional; + @Service @Slf4j public class UserService extends BaseService { - @Autowired UserRepository repository; + @Autowired UserRepository repository; - @Autowired UserMapper mapper; + @Autowired UserMapper mapper; + @Autowired ConversionService conversionService; + private Pbkdf2PasswordEncoder passwordEncoder; - private Pbkdf2PasswordEncoder passwordEncoder; + @PostConstruct + public void init() { - @PostConstruct - public void init() { - - passwordEncoder = new Pbkdf2PasswordEncoder("", 8, 10000, 256); - ; - } - - public UserDto create(CreateUserDto request) { - - StopWatch stopWatch = new StopWatch(); - - try { - stopWatch.start("encode"); - request.setPassword(passwordEncoder.encode(request.getPassword())); - stopWatch.stop(); - UserEntity entity = mapper.toEntity(request); - - stopWatch.start("save"); - - this.repository.save(entity); - stopWatch.stop(); - - stopWatch.start("getById"); - return getById(entity.getId()); - } finally { - stopWatch.stop(); - log.info(stopWatch.prettyPrint()); - } - } - - public UserDto update(UpdateUserDto request) { - UserEntity user = this.repository.get(request.getId()); - this.mapper.updateEntity(user, request); - - this.repository.save(user); - return getById(user.getId()); - } - - public void delete(IdRequest request) { - - this.repository.deleteAllById(request.getIds()); - } - - public UserDto getById(String id) { - - UserEntity user = repository.get(id); - - UserDto dto = mapper.toDto(user); - if (Ctx.isLoggedIn()) { - dto.setSessionId(Ctx.getSessionId()); + passwordEncoder = new Pbkdf2PasswordEncoder("", 8, 10000, 256); } - return dto; - } + public UserDto create(CreateUserDto request) { - public UserDto changePwd(ChangeUserPwdDto request) { + StopWatch stopWatch = new StopWatch(); - UserEntity user = - repository.findById(request.getId()).orElseThrow(() -> new BizException("用户不存在")); + try { + stopWatch.start("encode"); + request.setPassword(passwordEncoder.encode(request.getPassword())); + stopWatch.stop(); + UserEntity entity = mapper.toEntity(request); - if (!StringUtils.equals(request.getNewPassword(), request.getNewPassword2())) { - throw new BizException("两次输入的密码不一致"); + stopWatch.start("save"); + + this.repository.save(entity); + stopWatch.stop(); + + stopWatch.start("getById"); + return getById(entity.getId()); + } finally { + stopWatch.stop(); + log.info(stopWatch.prettyPrint()); + } } - user.setPassword(passwordEncoder.encode(request.getNewPassword())); + public UserDto update(UpdateUserDto request) { + UserEntity user = this.repository.get(request.getId()); + this.mapper.updateEntity(user, request); - repository.save(user); - - return getById(request.getId()); - } - - @Autowired ConversionService conversionService; - - public Page list(CommonQuery query) { - - Page page = - repository.findAll( - query.specification(conversionService), - PageRequest.of(query.getPageNo(), query.getPageSize(), Sort.by(query.getOrders()))); - - return page.map(this.mapper::toDto); - } - - public Optional findByUsername(String username) { - - return this.findAll( - new Specification() { - @Override - public Predicate toPredicate( - Root root, CriteriaQuery query, CriteriaBuilder criteriaBuilder) { - return criteriaBuilder.equal(root.get("username"), username); - } - }) - .stream() - .findFirst(); - } - - public boolean isValidPassword(String rawPassword, String encodedPassword) { - return passwordEncoder.matches(rawPassword, encodedPassword); - } - - public UserEntity initOrGetAdminUser(OrganizationEntity e) { - - UserEntity adminuser = this.repository.findByUsername("adminuser"); - - if (adminuser == null) { - - adminuser = new UserEntity(); - - adminuser.setUsername("adminuser"); - - adminuser.setPassword(passwordEncoder.encode("abc@123")); - - adminuser.setOrgAdmin(true); - adminuser.setName("超级管理员"); - - adminuser.setSysAdmin(true); - - adminuser.setOrganizationId(e.getId()); - - this.repository.save(adminuser); + this.repository.save(user); + return getById(user.getId()); } - return adminuser; - } + public void delete(IdRequest request) { + + this.repository.deleteAllById(request.getIds()); + } + + public UserDto getById(String id) { + + UserEntity user = repository.get(id); + + UserDto dto = mapper.toDto(user); + if (Ctx.isLoggedIn()) { + dto.setSessionId(Ctx.getSessionId()); + } + + return dto; + } + + public UserDto changePwd(ChangeUserPwdDto request) { + + UserEntity user = + repository.findById(request.getId()).orElseThrow(() -> new BizException("用户不存在")); + + if (!StringUtils.equals(request.getNewPassword(), request.getNewPassword2())) { + throw new BizException("两次输入的密码不一致"); + } + + user.setPassword(passwordEncoder.encode(request.getNewPassword())); + + repository.save(user); + + return getById(request.getId()); + } + + public Page list(CommonQuery query) { + + Page page = + repository.findAll( + query.specification(conversionService), + PageRequest.of( + query.getPageNo(), + query.getPageSize(), + Sort.by(query.getOrders()))); + + return page.map(this.mapper::toDto); + } + + public Optional findByUsername(String username) { + + return this.findAll( + new Specification() { + @Override + public Predicate toPredicate( + Root root, + CriteriaQuery query, + CriteriaBuilder criteriaBuilder) { + return criteriaBuilder.equal(root.get("username"), username); + } + }) + .stream() + .findFirst(); + } + + public boolean isValidPassword(String rawPassword, String encodedPassword) { + return passwordEncoder.matches(rawPassword, encodedPassword); + } + + public UserEntity initOrGetAdminUser(OrganizationEntity e) { + + UserEntity adminuser = this.repository.findByUsername("adminuser"); + + if (adminuser == null) { + + adminuser = new UserEntity(); + + adminuser.setUsername("adminuser"); + + adminuser.setPassword(passwordEncoder.encode("abc@123")); + + adminuser.setOrgAdmin(true); + adminuser.setName("超级管理员"); + + adminuser.setSysAdmin(true); + + adminuser.setOrganizationId(e.getId()); + + this.repository.save(adminuser); + } + + return adminuser; + } } diff --git a/src/main/resources/application-prod.yaml b/src/main/resources/application-prod.yaml index 202bd65f..5767df0d 100644 --- a/src/main/resources/application-prod.yaml +++ b/src/main/resources/application-prod.yaml @@ -1,4 +1,3 @@ - logging: file: name: ${spring.application.name}.log diff --git a/src/main/resources/application-test.yaml b/src/main/resources/application-test.yaml index b437dd09..9e9200ce 100644 --- a/src/main/resources/application-test.yaml +++ b/src/main/resources/application-test.yaml @@ -1,4 +1,3 @@ - logging: file: name: ${spring.application.name}.log diff --git a/src/main/resources/application.yaml b/src/main/resources/application.yaml index ee44372c..f7ebefda 100644 --- a/src/main/resources/application.yaml +++ b/src/main/resources/application.yaml @@ -9,7 +9,6 @@ server: # forward-headers-strategy: framework - system: anonymous: url: @@ -21,9 +20,9 @@ system: management: endpoint: - health: - probes: - enabled: true + health: + probes: + enabled: true health: livenessstate: enabled: true @@ -84,6 +83,11 @@ spring: baseline-on-migrate: true main: allow-circular-references: true + servlet: + multipart: + max-file-size: 20MB + max-request-size: 21MB + logging: file: path: /data/logs @@ -100,3 +104,67 @@ springdoc: api-docs: enabled: false + + +hwcloud: + obs: + ak: "RNRUPXNO8DTOKHDADVRP" + sk: "3btYcyuVM0xR79RjjCKBQQKWZoonsppbiAhleRoa" + bucket-name: "coal" + zone: "cn-east-3" + zones: + - name: "非洲-约翰内斯堡" + "code": "af-south-1" + "endpoint": "obs.af-south-1.myhuaweicloud.com" + - name: "华北-北京四" + "code": "cn-north-4" + "endpoint": "obs.cn-north-4.myhuaweicloud.com" + - name: "华北-北京一" + "code": "cn-north-1" + "endpoint": "obs.cn-north-1.myhuaweicloud.com" + - name: "华北-乌兰察布一" + "code": "cn-north-9" + "endpoint": "obs.cn-north-9.myhuaweicloud.com" + - name: "华东-上海二" + "code": "cn-east-2" + "endpoint": "obs.cn-east-2.myhuaweicloud.com" + - name: "华东-上海一" + "code": "cn-east-3" + "endpoint": "obs.cn-east-3.myhuaweicloud.com" + - name: "华南-广州" + "code": "cn-south-1" + "endpoint": "obs.cn-south-1.myhuaweicloud.com" + - name: "华南-广州-友好用户环" + "code": "cn-south-4" + "endpoint": "obs.cn-south-4.myhuaweicloud.com" + - name: "拉美-墨西哥城二" + "code": "la-north-2" + "endpoint": "obs.la-north-2.myhuaweicloud.com" + - name: "拉美-墨西哥城一" + "code": "na-mexico-1" + "endpoint": "obs.na-mexico-1.myhuaweicloud.com" + - name: "拉美-圣保罗一" + "code": "sa-brazil-1" + "endpoint": "obs.sa-brazil-1.myhuaweicloud.com" + - name: "拉美-圣地亚哥" + "code": "la-south-2" + "endpoint": "obs.la-south-2.myhuaweicloud.com" + - name: "土耳其-伊斯坦布尔" + "code": "tr-west-1" + "endpoint": "obs.tr-west-1.myhuaweicloud.com" + - name: "西南-贵阳一" + "code": "cn-southwest-2" + "endpoint": "obs.cn-southwest-2.myhuaweicloud.com" + - name: "亚太-曼谷" + "code": "ap-southeast-2" + "endpoint": "obs.ap-southeast-2.myhuaweicloud.com" + - name: "亚太-新加坡" + "code": "ap-southeast-3" + "endpoint": "obs.ap-southeast-3.myhuaweicloud.com" + - name: "中东-利雅得" + "code": "me-east-1" + "endpoint": "obs.me-east-1.myhuaweicloud.com" + - name: "中国-香港" + "code": "ap-southeast-1" + "endpoint": "obs.ap-southeast-1.myhuaweicloud.com" + diff --git a/src/main/resources/spy.properties b/src/main/resources/spy.properties index 73f22d80..d04b3f7d 100644 --- a/src/main/resources/spy.properties +++ b/src/main/resources/spy.properties @@ -1,10 +1,8 @@ - ################################################################# # P6Spy Options File # # See documentation for detailed instructions # # http://p6spy.github.io/p6spy/2.0/configandusage.html # ################################################################# - ################################################################# # MODULES # # # @@ -18,11 +16,9 @@ # this one requires reload. # ################################################################# #modulelist=com.p6spy.engine.spy.P6SpyFactory,com.p6spy.engine.logging.P6LogFactory,com.p6spy.engine.outage.P6OutageFactory - ################################################################ # CORE (P6SPY) PROPERTIES # ################################################################ - # A comma separated list of JDBC drivers to load and register. # (default is empty) # @@ -31,31 +27,25 @@ # using a JDBC driver that does not implement the JDBC 4.0 API # (specifically automatic registration). #driverlist= - # for flushing per statement # (default is false) autoflush=false - # sets the date format using Java's SimpleDateFormat routine. # In case property is not set, milliseconds since 1.1.1970 (unix time) is used (default is empty) #dateformat= - # prints a stack trace for every statement logged #stacktrace=false # if stacktrace=true, specifies the stack trace to print #stacktraceclass= - # determines if property file should be reloaded # Please note: reload means forgetting all the previously set # settings (even those set during runtime - via JMX) # and starting with the clean table # (default is false) #reloadproperties=false - # determines how often should be reloaded in seconds # (default is 60) #reloadpropertiesinterval=60 - # specifies the appender to use for logging # Please note: reload means forgetting all the previously set # settings (even those set during runtime - via JMX) @@ -65,20 +55,16 @@ autoflush=false appender=com.p6spy.engine.spy.appender.Slf4JLogger #appender=com.p6spy.engine.spy.appender.StdoutLogger #appender=com.p6spy.engine.spy.appender.FileLogger - # name of logfile to use, note Windows users should make sure to use forward slashes in their pathname (e:/test/spy.log) # (used for com.p6spy.engine.spy.appender.FileLogger only) # (default is spy.log) #logfile=spy.log - # append to the p6spy log file. if this is set to false the # log file is truncated every time. (file logger only) # (default is true) #append=true - # class to use for formatting log messages (default is: com.p6spy.engine.spy.appender.SingleLineFormat) logMessageFormat=com.p6spy.engine.spy.appender.CustomLineFormat - # Custom log message format used ONLY IF logMessageFormat is set to com.p6spy.engine.spy.appender.CustomLineFormat # default is %(currentTime)|%(executionTime)|%(category)|connection%(connectionId)|%(sqlSingleLine) # Available placeholders are: @@ -91,39 +77,31 @@ logMessageFormat=com.p6spy.engine.spy.appender.CustomLineFormat # %(sql) the SQL statement with all bind variables replaced with actual values # %(sqlSingleLine) the SQL statement with all bind variables replaced with actual values, with all new lines removed customLogMessageFormat=times: %(executionTime)ms %(category) %(sqlSingleLine) - # format that is used for logging of the java.util.Date implementations (has to be compatible with java.text.SimpleDateFormat) # (default is yyyy-MM-dd'T'HH:mm:ss.SSSZ) #databaseDialectDateFormat=yyyy-MM-dd'T'HH:mm:ss.SSSZ - # format that is used for logging of the java.sql.Timestamp implementations (has to be compatible with java.text.SimpleDateFormat) # (default is yyyy-MM-dd'T'HH:mm:ss.SSSZ) #databaseDialectTimestampFormat=yyyy-MM-dd'T'HH:mm:ss.SSSZ - # format that is used for logging booleans, possible values: boolean, numeric # (default is boolean) #databaseDialectBooleanFormat=boolean - # Specifies the format for logging binary data. Not applicable if excludebinary is true. # (default is com.p6spy.engine.logging.format.HexEncodedBinaryFormat) databaseDialectBinaryFormat=com.p6spy.engine.logging.format.PostgreSQLBinaryFormat #databaseDialectBinaryFormat=com.p6spy.engine.logging.format.MySQLBinaryFormat #databaseDialectBinaryFormat=com.p6spy.engine.logging.format.HexEncodedBinaryFormat - # whether to expose options via JMX or not # (default is true) #jmx=true - # if exposing options via jmx (see option: jmx), what should be the prefix used? # jmx naming pattern constructed is: com.p6spy(.)?:name= # please note, if there is already such a name in use it would be unregistered first (the last registered wins) # (default is none) #jmxPrefix= - # if set to true, the execution time will be measured in nanoseconds as opposed to milliseconds # (default is false) #useNanoTime=false - ################################################################# # DataSource replacement # # # @@ -140,7 +118,6 @@ databaseDialectBinaryFormat=com.p6spy.engine.logging.format.PostgreSQLBinaryForm ################################################################# #realdatasource=/RealMySqlDS #realdatasourceclass=com.mysql.jdbc.jdbc2.optional.MysqlDataSource - ################################################################# # DataSource properties # # # @@ -154,7 +131,6 @@ databaseDialectBinaryFormat=com.p6spy.engine.logging.format.PostgreSQLBinaryForm # # ################################################################# #realdatasourceproperties=port;3306,serverName;myhost,databaseName;jbossdb,foo;bar - ################################################################# # JNDI DataSource lookup # # # @@ -182,19 +158,15 @@ databaseDialectBinaryFormat=com.p6spy.engine.logging.format.PostgreSQLBinaryForm #jndicontextfactory=org.jnp.interfaces.NamingContextFactory #jndicontextproviderurl=localhost:1099 #jndicontextcustom=java.naming.factory.url.pkgs;org.jboss.naming:org.jnp.interfaces - #jndicontextfactory=com.ibm.websphere.naming.WsnInitialContextFactory #jndicontextproviderurl=iiop://localhost:900 - ################################################################ # P6 LOGGING SPECIFIC PROPERTIES # ################################################################ - # filter what is logged # please note this is a precondition for usage of: include/exclude/sqlexpression # (default is false) #filter=false - # comma separated list of strings to include # please note that special characters escaping (used in java) has to be done for the provided regular expression # (default is empty) @@ -202,21 +174,17 @@ databaseDialectBinaryFormat=com.p6spy.engine.logging.format.PostgreSQLBinaryForm # comma separated list of strings to exclude # (default is empty) #exclude= - # sql expression to evaluate if using regex # please note that special characters escaping (used in java) has to be done for the provided regular expression # (default is empty) #sqlexpression= - #list of categories to exclude: error, info, batch, debug, statement, #commit, rollback, result and resultset are valid values # (default is info,debug,result,resultset,batch) #excludecategories=info,debug,result,resultset,batch - #whether the binary values (passed to DB or retrieved ones) should be logged with placeholder: [binary] or not. # (default is false) #excludebinary=false - # Execution threshold applies to the standard logging of P6Spy. # While the standard logging logs out every statement # regardless of its execution time, this feature puts a time @@ -229,7 +197,6 @@ databaseDialectBinaryFormat=com.p6spy.engine.logging.format.PostgreSQLBinaryForm # executionThreshold=integer time (milliseconds) # (default is 0) #executionThreshold= - ################################################################ # P6 OUTAGE SPECIFIC PROPERTIES # ################################################################ diff --git a/src/test/java/cn/lihongjie/coal/CoalApplicationTests.java b/src/test/java/cn/lihongjie/coal/CoalApplicationTests.java index c40212d5..ec6ecdd3 100644 --- a/src/test/java/cn/lihongjie/coal/CoalApplicationTests.java +++ b/src/test/java/cn/lihongjie/coal/CoalApplicationTests.java @@ -6,6 +6,6 @@ import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest class CoalApplicationTests { - @Test - void contextLoads() {} + @Test + void contextLoads() {} } diff --git a/src/test/java/cn/lihongjie/coal/entity/CoalWashingDailyAnalysisEntityTest.java b/src/test/java/cn/lihongjie/coal/entity/CoalWashingDailyAnalysisEntityTest.java index ed0f3541..01cf1c5e 100644 --- a/src/test/java/cn/lihongjie/coal/entity/CoalWashingDailyAnalysisEntityTest.java +++ b/src/test/java/cn/lihongjie/coal/entity/CoalWashingDailyAnalysisEntityTest.java @@ -2,35 +2,37 @@ package cn.lihongjie.coal.entity; import cn.lihongjie.coal.coalWashingDailyAnalysis.entity.CoalWashingDailyAnalysisEntity; import cn.lihongjie.coal.coalWashingDailyAnalysis.entity.CoalWashingDailyAnalysisItemVo; + +import org.junit.jupiter.api.Test; + import java.time.LocalTime; import java.util.Arrays; -import org.junit.jupiter.api.Test; class CoalWashingDailyAnalysisEntityTest { - @Test - void test1() { + @Test + void test1() { - CoalWashingDailyAnalysisEntity analysis = new CoalWashingDailyAnalysisEntity(); + CoalWashingDailyAnalysisEntity analysis = new CoalWashingDailyAnalysisEntity(); - CoalWashingDailyAnalysisItemVo vo1 = new CoalWashingDailyAnalysisItemVo(); - vo1.setC0p0(100.0); - vo1.setC0p1(10.0); - vo1.setC0p2(12.0); - vo1.setTime(LocalTime.of(1, 0)); - vo1.setTotalNumber(10.0); + CoalWashingDailyAnalysisItemVo vo1 = new CoalWashingDailyAnalysisItemVo(); + vo1.setC0p0(100.0); + vo1.setC0p1(10.0); + vo1.setC0p2(12.0); + vo1.setTime(LocalTime.of(1, 0)); + vo1.setTotalNumber(10.0); - CoalWashingDailyAnalysisItemVo vo2 = new CoalWashingDailyAnalysisItemVo(); - vo2.setC0p0(100.0); - vo2.setC0p1(10.0); - vo2.setC0p2(12.0); - vo2.setTime(LocalTime.of(2, 0)); - vo2.setTotalNumber(12.0); + CoalWashingDailyAnalysisItemVo vo2 = new CoalWashingDailyAnalysisItemVo(); + vo2.setC0p0(100.0); + vo2.setC0p1(10.0); + vo2.setC0p2(12.0); + vo2.setTime(LocalTime.of(2, 0)); + vo2.setTotalNumber(12.0); - analysis.setInputItems(Arrays.asList(vo1, vo2)); + analysis.setInputItems(Arrays.asList(vo1, vo2)); - analysis.rollingAvg(); + analysis.rollingAvg(); - System.out.println(analysis); - } + System.out.println(analysis); + } } diff --git a/src/test/java/cn/lihongjie/coal/service/CoalServiceTest.java b/src/test/java/cn/lihongjie/coal/service/CoalServiceTest.java index 444ab532..2829949e 100644 --- a/src/test/java/cn/lihongjie/coal/service/CoalServiceTest.java +++ b/src/test/java/cn/lihongjie/coal/service/CoalServiceTest.java @@ -3,28 +3,32 @@ package cn.lihongjie.coal.service; import cn.lihongjie.coal.coal.CoalService; import cn.lihongjie.coal.coalBlend.dto.CoalBlendRequest; import cn.lihongjie.coal.coalBlend.dto.CoalBlendResult; + import com.fasterxml.jackson.databind.ObjectMapper; -import java.io.InputStream; + import lombok.SneakyThrows; + import org.junit.jupiter.api.Test; +import java.io.InputStream; + class CoalServiceTest { - @SneakyThrows - @Test - void testBlend() { + @SneakyThrows + @Test + void testBlend() { - CoalService coalService = new CoalService(); + CoalService coalService = new CoalService(); - InputStream stream = this.getClass().getClassLoader().getResourceAsStream("request1.json"); + InputStream stream = this.getClass().getClassLoader().getResourceAsStream("request1.json"); - CoalBlendRequest coalBlendRequest = - new ObjectMapper().readValue(stream, CoalBlendRequest.class); + CoalBlendRequest coalBlendRequest = + new ObjectMapper().readValue(stream, CoalBlendRequest.class); - for (int i = 0; i < 1; i++) { + for (int i = 0; i < 1; i++) { - CoalBlendResult result = coalService.blend(coalBlendRequest); - System.out.println(result.tableString()); + CoalBlendResult result = coalService.blend(coalBlendRequest); + System.out.println(result.tableString()); + } } - } } diff --git a/src/test/java/cn/lihongjie/coal/service/SimpleSatProgram.java b/src/test/java/cn/lihongjie/coal/service/SimpleSatProgram.java index cff2f747..fba8a70f 100644 --- a/src/test/java/cn/lihongjie/coal/service/SimpleSatProgram.java +++ b/src/test/java/cn/lihongjie/coal/service/SimpleSatProgram.java @@ -8,33 +8,33 @@ import com.google.ortools.sat.IntVar; /** Minimal CP-SAT example to showcase calling the solver. */ public final class SimpleSatProgram { - public static void main(String[] args) throws Exception { - Loader.loadNativeLibraries(); - // Create the model. - CpModel model = new CpModel(); + private SimpleSatProgram() {} - // Create the variables. - int numVals = 3; + public static void main(String[] args) throws Exception { + Loader.loadNativeLibraries(); + // Create the model. + CpModel model = new CpModel(); - IntVar x = model.newIntVar(0, numVals - 1, "x"); - IntVar y = model.newIntVar(0, numVals - 1, "y"); - IntVar z = model.newIntVar(0, numVals - 1, "z"); + // Create the variables. + int numVals = 3; - // Create the constraints. - model.addDifferent(x, y); + IntVar x = model.newIntVar(0, numVals - 1, "x"); + IntVar y = model.newIntVar(0, numVals - 1, "y"); + IntVar z = model.newIntVar(0, numVals - 1, "z"); - // Create a solver and solve the model. - CpSolver solver = new CpSolver(); - CpSolverStatus status = solver.solve(model); + // Create the constraints. + model.addDifferent(x, y); - if (status == CpSolverStatus.OPTIMAL || status == CpSolverStatus.FEASIBLE) { - System.out.println("x = " + solver.value(x)); - System.out.println("y = " + solver.value(y)); - System.out.println("z = " + solver.value(z)); - } else { - System.out.println("No solution found."); + // Create a solver and solve the model. + CpSolver solver = new CpSolver(); + CpSolverStatus status = solver.solve(model); + + if (status == CpSolverStatus.OPTIMAL || status == CpSolverStatus.FEASIBLE) { + System.out.println("x = " + solver.value(x)); + System.out.println("y = " + solver.value(y)); + System.out.println("z = " + solver.value(z)); + } else { + System.out.println("No solution found."); + } } - } - - private SimpleSatProgram() {} } diff --git a/src/test/resources/request1.json b/src/test/resources/request1.json index e9343505..8aff6e81 100644 --- a/src/test/resources/request1.json +++ b/src/test/resources/request1.json @@ -79,5 +79,6 @@ "value": 8 } ] - }] + } + ] } \ No newline at end of file