diff --git a/build.gradle b/build.gradle index 14c0d8a..4659349 100644 --- a/build.gradle +++ b/build.gradle @@ -22,6 +22,7 @@ repositories { } dependencies { + // SpringBoot原生依赖 implementation 'org.springframework.boot:spring-boot-starter-data-redis' implementation 'org.springframework.boot:spring-boot-starter-web' implementation 'org.springframework.boot:spring-boot-starter-validation' @@ -33,11 +34,11 @@ dependencies { testImplementation 'org.springframework.boot:spring-boot-starter-test' testImplementation 'org.mybatis.spring.boot:mybatis-spring-boot-starter-test:3.0.3' + // 外部引入依赖 // Sa-Token 权限认证,在线文档:https://sa-token.cc implementation 'cn.dev33:sa-token-spring-boot3-starter:1.37.0' - implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.3.0' - + implementation 'com.alibaba:easyexcel:3.3.3' } tasks.named('test') { diff --git a/gradlew b/gradlew old mode 100755 new mode 100644 diff --git a/src/main/java/com/realtime/protection/configuration/entity/defense/object/ProtectObject.java b/src/main/java/com/realtime/protection/configuration/entity/defense/object/ProtectObject.java index 11d1cda..b8d90a5 100644 --- a/src/main/java/com/realtime/protection/configuration/entity/defense/object/ProtectObject.java +++ b/src/main/java/com/realtime/protection/configuration/entity/defense/object/ProtectObject.java @@ -1,7 +1,10 @@ package com.realtime.protection.configuration.entity.defense.object; import com.fasterxml.jackson.annotation.JsonProperty; +import jakarta.validation.constraints.Max; +import jakarta.validation.constraints.Min; import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Pattern; import lombok.Data; @Data @@ -17,10 +20,13 @@ public class ProtectObject { private String protectObjectSystemName; @JsonProperty("proobj_ip_address") + @Pattern(regexp = "^(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})$", message = "Invalid IPv4 Address") private String protectObjectIPAddress; @JsonProperty("proobj_port") @NotNull(message = "proobj_port should not be empty.") + @Max(value = 65535, message = "port should not be more than 65535") + @Min(value = 1, message = "port should not be less than 1") private Integer protectObjectPort; @JsonProperty("proobj_url") diff --git a/src/main/java/com/realtime/protection/configuration/entity/task/Task.java b/src/main/java/com/realtime/protection/configuration/entity/task/Task.java index 4731f4c..4f921d3 100644 --- a/src/main/java/com/realtime/protection/configuration/entity/task/Task.java +++ b/src/main/java/com/realtime/protection/configuration/entity/task/Task.java @@ -1,6 +1,7 @@ package com.realtime.protection.configuration.entity.task; import com.fasterxml.jackson.annotation.JsonProperty; +import jakarta.validation.constraints.Future; import jakarta.validation.constraints.NotNull; import lombok.Data; @@ -13,15 +14,16 @@ public class Task { private Integer taskId; @JsonProperty("task_name") - @NotNull(message = "task_name should not be empty.") + @NotNull(message = "task_name should not be empty. ") private String taskName; @JsonProperty("task_start_time") - @NotNull(message = "task_start_time should not be empty.") + @NotNull(message = "task_start_time should not be empty. ") private LocalDateTime taskStartTime; @JsonProperty("task_end_time") - @NotNull(message = "task_end_time should not be empty.") + @NotNull(message = "task_end_time should not be empty. ") + @Future(message = "task_end_time should be a future time. ") private LocalDateTime taskEndTime; @JsonProperty("task_create_time") @@ -31,11 +33,11 @@ public class Task { private LocalDateTime taskModifyTime; @JsonProperty("task_type") - @NotNull(message = "task_type should not be empty.") + @NotNull(message = "task_type should not be empty. ") private String taskType; @JsonProperty("task_act") - @NotNull(message = "task_act should not be empty.") + @NotNull(message = "task_act should not be empty. ") private String taskAct; @JsonProperty("task_create_username") diff --git a/src/main/java/com/realtime/protection/configuration/exception/GlobalExceptionHandler.java b/src/main/java/com/realtime/protection/configuration/exception/GlobalExceptionHandler.java index c3b85ba..00309a2 100644 --- a/src/main/java/com/realtime/protection/configuration/exception/GlobalExceptionHandler.java +++ b/src/main/java/com/realtime/protection/configuration/exception/GlobalExceptionHandler.java @@ -48,7 +48,7 @@ public class GlobalExceptionHandler { } @Order(2) - @ExceptionHandler(value = HandlerMethodValidationException.class) + @ExceptionHandler(value = {HandlerMethodValidationException.class, IllegalArgumentException.class}) public ResponseResult handleHandlerMethodValidationException(HandlerMethodValidationException e) { return ResponseResult.invalid().setMessage(e.getMessage()); } diff --git a/src/main/java/com/realtime/protection/configuration/response/ResponseResult.java b/src/main/java/com/realtime/protection/configuration/response/ResponseResult.java index e327b99..af93b56 100644 --- a/src/main/java/com/realtime/protection/configuration/response/ResponseResult.java +++ b/src/main/java/com/realtime/protection/configuration/response/ResponseResult.java @@ -4,13 +4,14 @@ import lombok.Data; import java.io.Serializable; import java.util.LinkedHashMap; +import java.util.Map; @Data public class ResponseResult implements Serializable { private int code; private String message; - private LinkedHashMap data; + private Map data; public ResponseResult(int code, String message, LinkedHashMap data) { this.code = code; @@ -45,6 +46,10 @@ public class ResponseResult implements Serializable { return new ResponseResult(400, "invalid request"); } + public static ResponseResult invalid(String message) { + return new ResponseResult(400, message); + } + public static ResponseResult unAuthorized() { return new ResponseResult(401, "UnAuthorized User"); } @@ -68,7 +73,7 @@ public class ResponseResult implements Serializable { return this; } - public ResponseResult setDataMap(LinkedHashMap data) { + public ResponseResult setDataMap(Map data) { this.data = data; return this; } diff --git a/src/main/java/com/realtime/protection/configuration/utils/AuditStatusValidator.java b/src/main/java/com/realtime/protection/configuration/utils/AuditStatusValidator.java new file mode 100644 index 0000000..ae67873 --- /dev/null +++ b/src/main/java/com/realtime/protection/configuration/utils/AuditStatusValidator.java @@ -0,0 +1,22 @@ +package com.realtime.protection.configuration.utils; + +public class AuditStatusValidator { + + private final Integer auditStatusOriginal; + + public AuditStatusValidator(Integer auditStatusOriginal) { + this.auditStatusOriginal = auditStatusOriginal; + } + + public static AuditStatusValidator setOriginal(Integer auditStatusOriginal) { + return new AuditStatusValidator(auditStatusOriginal); + } + + public Boolean checkValidate(Integer auditStatusNow) { + switch (auditStatusNow) { + case 0, 1 -> {return auditStatusOriginal != 2;} + case 2 -> {return auditStatusOriginal != 1;} + default -> {return false;} + } + } +} diff --git a/src/main/java/com/realtime/protection/configuration/utils/SqlSessionWrapper.java b/src/main/java/com/realtime/protection/configuration/utils/SqlSessionWrapper.java new file mode 100644 index 0000000..8795f5c --- /dev/null +++ b/src/main/java/com/realtime/protection/configuration/utils/SqlSessionWrapper.java @@ -0,0 +1,37 @@ +package com.realtime.protection.configuration.utils; + +import org.apache.ibatis.session.ExecutorType; +import org.apache.ibatis.session.SqlSession; +import org.apache.ibatis.session.SqlSessionFactory; +import org.springframework.stereotype.Component; + +import java.util.function.Function; + +@Component +public class SqlSessionWrapper { + + private final SqlSessionFactory sqlSessionFactory; + + public SqlSessionWrapper(SqlSessionFactory sqlSessionFactory) { + this.sqlSessionFactory = sqlSessionFactory; + } + + public O startBatchSession(Class mapperClass, + Function> wrappedFunction, + I arguments) { + SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH, false); + M mapper = sqlSession.getMapper(mapperClass); + try { + O result = wrappedFunction.apply(mapper).apply(arguments); + sqlSession.commit(); + sqlSession.clearCache(); + + return result; + } catch (Exception e) { + sqlSession.rollback(); + throw e; + } finally { + sqlSession.close(); + } + } +} diff --git a/src/main/java/com/realtime/protection/server/defense/object/ProjectObjectDataListener.java b/src/main/java/com/realtime/protection/server/defense/object/ProjectObjectDataListener.java new file mode 100644 index 0000000..55e5e75 --- /dev/null +++ b/src/main/java/com/realtime/protection/server/defense/object/ProjectObjectDataListener.java @@ -0,0 +1,42 @@ +package com.realtime.protection.server.defense.object; + + +import com.alibaba.excel.context.AnalysisContext; +import com.alibaba.excel.read.listener.ReadListener; +import com.alibaba.excel.util.ListUtils; +import com.realtime.protection.configuration.entity.defense.object.ProtectObject; +import org.springframework.beans.factory.annotation.Autowired; + +import java.util.List; + +public class ProjectObjectDataListener implements ReadListener { + + private final ProtectObjectService protectObjectService; + private final List cachedDataList = ListUtils.newArrayListWithExpectedSize(batchCount); + private static final int batchCount = 100; + + public ProjectObjectDataListener(ProtectObjectService protectObjectService) { + this.protectObjectService = protectObjectService; + } + + @Override + public void invoke(ProtectObject protectObject, AnalysisContext analysisContext) { + cachedDataList.add(protectObject); + if (cachedDataList.size() > 1000) { + saveData(); + cachedDataList.clear(); + } + } + + @Override + public void doAfterAllAnalysed(AnalysisContext analysisContext) { + saveData(); + } + + private void saveData() { + Boolean success = protectObjectService.newProtectObjects(cachedDataList); + if (!success) { + throw new RuntimeException("Error reading data in newProtectObjects"); + } + } +} diff --git a/src/main/java/com/realtime/protection/server/defense/object/ProtectObjectController.java b/src/main/java/com/realtime/protection/server/defense/object/ProtectObjectController.java index c92b40c..34ade31 100644 --- a/src/main/java/com/realtime/protection/server/defense/object/ProtectObjectController.java +++ b/src/main/java/com/realtime/protection/server/defense/object/ProtectObjectController.java @@ -1,4 +1,104 @@ package com.realtime.protection.server.defense.object; +import com.alibaba.excel.EasyExcel; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.realtime.protection.configuration.entity.defense.object.ProtectObject; +import com.realtime.protection.configuration.response.ResponseResult; +import jakarta.validation.Valid; +import jakarta.validation.constraints.Min; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.multipart.MultipartFile; + +import java.io.IOException; +import java.util.List; + +@RestController +@RequestMapping("/proobj") public class ProtectObjectController { + + private final ProtectObjectService protectObjectService; + + public ProtectObjectController(ProtectObjectService protectObjectService) { + this.protectObjectService = protectObjectService; + } + + @PostMapping("/new") + public ResponseResult newProtectObject(@RequestBody @Valid ProtectObject protectObject) { + Integer protectObjectId = protectObjectService.newProtectObject(protectObject); + if (protectObjectId == 0) { + return ResponseResult.error().setMessage("failed to create a protect object") + .setData("proobj_name", protectObject.getProtectObjectName()) + .setData("proobj_id", protectObjectId) + .setData("success", false); + } + + return ResponseResult.ok() + .setData("proobj_name", protectObject.getProtectObjectName()) + .setData("proobj_id", protectObject.getProtectObjectId()) + .setData("success", true); + } + + @PutMapping("/new") + public ResponseResult newProtectObjectFromFile(MultipartFile updateFile) throws IOException { + EasyExcel.read(updateFile.getInputStream(), ProtectObject.class, + new ProjectObjectDataListener(protectObjectService)).sheet().doRead(); + return ResponseResult.ok(); + } + + @GetMapping("/query") + public ResponseResult queryProtectObjects(@RequestParam(value = "proobj_name", required = false) + String protectObjectName, + @RequestParam(value = "proobj_id", required = false) @Min(1) + Integer protectObjectId, + @RequestParam("page") @Min(1) Integer page, + @RequestParam("page_size") @Min(1) Integer pageSize) { + return ResponseResult.ok() + .setData("proobj_list", protectObjectService.queryProtectObjects(protectObjectName, + protectObjectId, page, pageSize)); + + } + + @GetMapping("/{id}/query") + public ResponseResult queryProtectObject(@PathVariable("id") Integer protectObjectId) { + ProtectObject protectObject = protectObjectService.queryProtectObject(protectObjectId); + return ResponseResult.ok() + .setData("proobj_id", protectObject.getProtectObjectId()) + .setData("proobj_name", protectObject.getProtectObjectName()) + .setData("proobj_system_name", protectObject.getProtectObjectSystemName()) + .setData("proobj_ip_address", protectObject.getProtectObjectIPAddress()) + .setData("proobj_port", protectObject.getProtectObjectPort()) + .setData("proobj_url", protectObject.getProtectObjectURL()) + .setData("proobj_protocol", protectObject.getProtectObjectProtocol()); + } + + @PostMapping("/{id}/update") + public ResponseResult updateProtectObject(@PathVariable("id") Integer protectObjectId, + @RequestBody @Valid ProtectObject protectObject) { + protectObject.setProtectObjectId(protectObjectId); + return ResponseResult.ok() + .setData("proobj_id", protectObject.getProtectObjectId()) + .setData("success", protectObjectService.updateProtectObject(protectObject)); + } + + @DeleteMapping("/{id}/delete") + public ResponseResult deleteProtectObject(@PathVariable("id") Integer protectObjectId) { + return ResponseResult.ok() + .setData("proobj_id", protectObjectId) + .setData("success", protectObjectService.deleteProtectObject(protectObjectId)); + } + + @PostMapping("/delete") + public ResponseResult deleteProtectObject(@RequestBody @JsonProperty("proobj_ids") List protectObjectIds) { + return ResponseResult.ok() + .setData("proobj_ids", protectObjectIds) + .setData("success", protectObjectService.deleteProtectObjects(protectObjectIds)); + } + + @PostMapping("/{id}/audit/{status}") + public ResponseResult changeProtectObjectAuditStatus(@PathVariable("id") Integer protectObjectId, + @PathVariable("status") Integer auditStatus) { + return ResponseResult.ok() + .setDataMap(protectObjectService.changeProtectObjectAuditStatus(protectObjectId, auditStatus)) + .setData("proobj_id", protectObjectId); + } } diff --git a/src/main/java/com/realtime/protection/server/defense/object/ProtectObjectMapper.java b/src/main/java/com/realtime/protection/server/defense/object/ProtectObjectMapper.java index 54bbb4b..b735f98 100644 --- a/src/main/java/com/realtime/protection/server/defense/object/ProtectObjectMapper.java +++ b/src/main/java/com/realtime/protection/server/defense/object/ProtectObjectMapper.java @@ -10,6 +10,8 @@ import java.util.List; public interface ProtectObjectMapper { void newProtectObject(@Param("proobj") ProtectObject protectObject); + void newProtectObjects(@Param("proobjs") List protectObject); + List queryProtectObjects(@Param("proobj_name") String protectObjectName, @Param("proobj_id") Integer protectObjectId, @Param("page") Integer page, @@ -21,5 +23,8 @@ public interface ProtectObjectMapper { Boolean deleteProtectObject(@Param("proobj_id") Integer protectObjectId); - Boolean changeProtectObjectAuditStatus(@Param("proobj_audit_status") Integer protectObjectAuditStatus); + Boolean deleteProtectObjects(@Param("proobj_ids") List protectObjectIds); + + Boolean changeProtectObjectAuditStatus(@Param("proobj_id") Integer protectObjectId, + @Param("proobj_audit_status") Integer protectObjectAuditStatus); } diff --git a/src/main/java/com/realtime/protection/server/defense/object/ProtectObjectService.java b/src/main/java/com/realtime/protection/server/defense/object/ProtectObjectService.java index 0d5a4bf..1c82eeb 100644 --- a/src/main/java/com/realtime/protection/server/defense/object/ProtectObjectService.java +++ b/src/main/java/com/realtime/protection/server/defense/object/ProtectObjectService.java @@ -1,18 +1,26 @@ package com.realtime.protection.server.defense.object; +import com.alibaba.excel.util.ListUtils; import com.realtime.protection.configuration.entity.defense.object.ProtectObject; +import com.realtime.protection.configuration.utils.AuditStatusValidator; +import com.realtime.protection.configuration.utils.SqlSessionWrapper; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; +import java.util.HashMap; import java.util.List; +import java.util.Map; +import java.util.function.Function; import java.util.stream.Collectors; @Service public class ProtectObjectService { private final ProtectObjectMapper protectObjectMapper; + private final SqlSessionWrapper sqlSessionWrapper; - public ProtectObjectService(ProtectObjectMapper protectObjectMapper) { + public ProtectObjectService(ProtectObjectMapper protectObjectMapper, SqlSessionWrapper sqlSessionWrapper) { this.protectObjectMapper = protectObjectMapper; + this.sqlSessionWrapper = sqlSessionWrapper; } public Integer newProtectObject(ProtectObject protectObject) { @@ -24,10 +32,22 @@ public class ProtectObjectService { return protectObject.getProtectObjectId(); } - @Transactional - public List newProtectObjects(List protectObjectList) { - protectObjectList.forEach(protectObjectMapper::newProtectObject); - return protectObjectList.stream().map(ProtectObject::getProtectObjectId).collect(Collectors.toList()); + public Boolean newProtectObjects(List protectObjectList) { + Function, Boolean>> newProtectObjectFunction = mapper -> list -> { + List protectObjectBatch = ListUtils.newArrayListWithExpectedSize(100); + for (ProtectObject protectObject : protectObjectList) { + protectObjectBatch.add(protectObject); + if (protectObjectBatch.size() < 1000) { + continue; + } + mapper.newProtectObjects(protectObjectBatch); + protectObjectBatch.clear(); + } + mapper.newProtectObjects(protectObjectBatch); + return true; + }; + + return sqlSessionWrapper.startBatchSession(ProtectObjectMapper.class, newProtectObjectFunction, protectObjectList); } public List queryProtectObjects(String protectObjectName, Integer protectObjectId, Integer page, Integer pageSize) { @@ -46,8 +66,42 @@ public class ProtectObjectService { return protectObjectMapper.deleteProtectObject(protectObjectId); } - @Transactional public Boolean deleteProtectObjects(List protectObjectIds) { - return protectObjectIds.stream().allMatch(protectObjectMapper::deleteProtectObject); + Function, Void>> deleteProtectObjectFunction = mapper -> list -> { + if (list == null || list.isEmpty()) { + return null; + } + + List protectObjectBatch = ListUtils.newArrayListWithExpectedSize(100); + for (Integer protectObjectId : list) { + protectObjectBatch.add(protectObjectId); + if (protectObjectBatch.size() < 100) { + continue; + } + mapper.deleteProtectObjects(protectObjectIds); + protectObjectBatch.clear(); + } + mapper.deleteProtectObjects(protectObjectBatch); + return null; + }; + + sqlSessionWrapper.startBatchSession(ProtectObjectMapper.class, deleteProtectObjectFunction, protectObjectIds); + return true; + } + + @Transactional + public Map changeProtectObjectAuditStatus(Integer protectObjectId, Integer auditStatus) { + Integer originalAuditStatus = protectObjectMapper.queryProtectObject(protectObjectId).getProtectObjectAuditStatus(); + if (!AuditStatusValidator.setOriginal(originalAuditStatus).checkValidate(auditStatus)) { + throw new IllegalArgumentException("invalid audit status"); + } + Boolean success = protectObjectMapper.changeProtectObjectAuditStatus(protectObjectId, auditStatus); + + Integer auditStatusNow = protectObjectMapper.queryProtectObject(protectObjectId).getProtectObjectAuditStatus(); + Map resultMap = new HashMap<>(); + resultMap.put("success", success); + resultMap.put("audit_status", auditStatusNow); + + return resultMap; } } diff --git a/src/main/java/com/realtime/protection/server/task/TaskService.java b/src/main/java/com/realtime/protection/server/task/TaskService.java index 34d66bb..5102f97 100644 --- a/src/main/java/com/realtime/protection/server/task/TaskService.java +++ b/src/main/java/com/realtime/protection/server/task/TaskService.java @@ -82,11 +82,11 @@ public class TaskService { taskMapper.clearTaskProtectObjectConcat(task.getTaskId()); taskMapper.clearTaskConnectedStaticRule(task.getTaskId()); - taskMapper.clearTaskConnectedDynamicRule(task.getTaskId()); +// taskMapper.clearTaskConnectedDynamicRule(task.getTaskId()); task.getProtectObjectIds().forEach( proobjId -> taskMapper.newTaskProtectObjectConcat(task.getTaskId(), proobjId)); taskMapper.newTaskStaticRuleConcat(task.getTaskId(), task.getStaticRuleIds()); - taskMapper.newTaskDynamicRuleConcat(task.getTaskId(), task.getDynamicRuleIds()); +// taskMapper.newTaskDynamicRuleConcat(task.getTaskId(), task.getDynamicRuleIds()); } } diff --git a/src/main/resources/mappers/ProtectObjectMapper.xml b/src/main/resources/mappers/ProtectObjectMapper.xml index 3dfe27c..20d6541 100644 --- a/src/main/resources/mappers/ProtectObjectMapper.xml +++ b/src/main/resources/mappers/ProtectObjectMapper.xml @@ -3,8 +3,96 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> + + INSERT INTO t_protect_object(protect_object_id, protect_object_name, protect_object_system_name, + protect_object_ip, protect_object_port, protect_object_url, + protect_object_protocol, + protect_object_create_username, protect_object_create_depart, + protect_object_create_user_id) + VALUE (#{proobj.protectObjectId}, #{proobj.protectObjectName}, #{proobj.protectObjectSystemName}, + INET_ATON(#{proobj.protectObjectIPAddress}), #{proobj.protectObjectPort}, #{proobj.protectObjectURL}, + #{proobj.protectObjectProtocol}, + #{proobj.protectObjectCreateUsername}, #{proobj.protectObjectCreateDepart}, + #{proobj.protectObjectCreateUserId}) + + + + INSERT INTO t_protect_object(protect_object_id, protect_object_name, protect_object_system_name, + protect_object_ip, protect_object_port, protect_object_url, + protect_object_protocol, + protect_object_create_username, protect_object_create_depart, + protect_object_create_user_id) + VALUES + + (#{proobj.protectObjectId}, #{proobj.protectObjectName}, #{proobj.protectObjectSystemName}, + INET_ATON(#{proobj.protectObjectIPAddress}), #{proobj.protectObjectPort}, #{proobj.protectObjectURL}, + #{proobj.protectObjectProtocol}, + #{proobj.protectObjectCreateUsername}, #{proobj.protectObjectCreateDepart}, + #{proobj.protectObjectCreateUserId}) + + + + + + + + + + + + + + + + + + + + UPDATE t_protect_object + + protect_object_name = #{proobj.protectObjectName}, + + protect_object_system_name = #{proobj.protectObjectSystemName}, + + protect_object_ip = INET_ATON(#{proobj.protectObjectIPAddress}), + + protect_object_port = #{proobj.protectObjectPort}, + protect_object_url = #{proobj.protectObjectURL}, + protect_object_protocol = #{proobj.protectObjectProtocol}, + + + protect_object_id = #{proobj.protectObjectId} + + + DELETE FROM t_protect_object WHERE protect_object_id = #{proobj_id} + + + DELETE FROM t_protect_object + WHERE protect_object_id IN + + #{proobj_id} + + + + + UPDATE t_protect_object + SET protect_object_audit_status = #{proobj_audit_status} + WHERE protect_object_id = #{proobj_id} + \ No newline at end of file diff --git a/src/test/java/com/realtime/protection/server/defense/object/ProtectObjectServiceTest.java b/src/test/java/com/realtime/protection/server/defense/object/ProtectObjectServiceTest.java index 5a17ae3..ee2b37e 100644 --- a/src/test/java/com/realtime/protection/server/defense/object/ProtectObjectServiceTest.java +++ b/src/test/java/com/realtime/protection/server/defense/object/ProtectObjectServiceTest.java @@ -1,17 +1,23 @@ package com.realtime.protection.server.defense.object; +import com.realtime.protection.configuration.entity.defense.object.ProtectObject; +import org.apache.ibatis.exceptions.PersistenceException; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.dao.DataIntegrityViolationException; +import java.util.ArrayList; import java.util.List; -import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.*; @SpringBootTest class ProtectObjectServiceTest { private final ProtectObjectService protectObjectService; + private ProtectObject protectObject; @Autowired ProtectObjectServiceTest(ProtectObjectService protectObjectService) { @@ -23,4 +29,83 @@ class ProtectObjectServiceTest { Boolean success = protectObjectService.deleteProtectObjects(List.of(1, 2, 3, 4)); assertFalse(success); } + + @BeforeEach + void setUp() { + protectObject = new ProtectObject(); + protectObject.setProtectObjectName("x-2-2"); + protectObject.setProtectObjectSystemName("xxxx system"); + protectObject.setProtectObjectIPAddress("192.168.1.4"); + protectObject.setProtectObjectPort(11); + protectObject.setProtectObjectURL("alice.bob.com"); + protectObject.setProtectObjectProtocol("UDP"); + } + + @Test + void newProtectObject() { + assertTrue(protectObjectService.newProtectObject(protectObject) > 0); + + protectObject.setProtectObjectId(null); + protectObject.setProtectObjectProtocol(null); + + assertThrows(DataIntegrityViolationException.class, () -> { + assertTrue(protectObjectService.newProtectObject(protectObject) > 0); + }); + } + + @Test + void newProtectObjects() { + List protectObjects = new ArrayList<>(); + for (int i = 0; i < 100; i++) { + protectObjects.add(protectObject); + } + + Boolean success = protectObjectService.newProtectObjects(protectObjects); + assertTrue(success); + } + + @Test + void updateProtectObject() { + protectObject.setProtectObjectName("x-1-1"); + protectObject.setProtectObjectId(10); + assertTrue(protectObjectService.updateProtectObject(protectObject)); + assertEquals("x-1-1", protectObjectService.queryProtectObject(10).getProtectObjectName()); + } + + @Test + void deleteProtectObject() { + int testNum = 0; + for (int i = 0; i < 100000; i++ ) { + if (protectObjectService.queryProtectObject(i) != null) { + testNum = i; + break; + } + } + + assertTrue(protectObjectService.deleteProtectObject(testNum)); + assertNull(protectObjectService.queryProtectObject(testNum)); + } + + @Test + void deleteProtectObjects() { + assertTrue(protectObjectService.deleteProtectObjects(List.of(270, 271))); + assertNull(protectObjectService.queryProtectObject(270)); + assertNull(protectObjectService.queryProtectObject(271)); + } + + @Test + void changeProtectObjectAuditStatus() { + int testNum = 0; + for (int i = 300; i < 100000; i++ ) { + if (protectObjectService.queryProtectObject(i) != null) { + testNum = i; + break; + } + } + assertTrue((Boolean) protectObjectService.changeProtectObjectAuditStatus(testNum, 1).get("success")); + int finalTestNum = testNum; + assertThrows(IllegalArgumentException.class, () -> { + protectObjectService.changeProtectObjectAuditStatus(finalTestNum, 2); + }); + } } \ No newline at end of file