From 0e92313764531403294320cb74dc284266542087 Mon Sep 17 00:00:00 2001 From: BOUHOURS Antoine Date: Fri, 26 Jun 2026 16:57:19 +0200 Subject: [PATCH] Use exceptions instead of optional --- .../server/controllers/MonitorController.java | 33 +++--- .../controllers/ProcessConfigController.java | 21 ++-- .../error/MonitorServerBusinessErrorCode.java | 5 +- .../error/MonitorServerExceptionHandler.java | 1 + .../processconfig/ProcessConfigService.java | 68 +++++------ .../ProcessExecutionService.java | 64 ++++------- .../ProcessExecutionTxService.java | 108 +++++++++--------- .../server/MonitorIntegrationTest.java | 50 ++++---- .../controllers/MonitorControllerTest.java | 46 ++++---- .../ProcessConfigControllerTest.java | 31 +++-- .../MonitorServerExceptionHandlerTest.java | 12 ++ .../ProcessConfigServiceTest.java | 68 +++++------ .../ProcessExecutionServiceTest.java | 75 ++++++------ .../ProcessExecutionTxServiceTest.java | 74 ++++++------ 14 files changed, 311 insertions(+), 345 deletions(-) diff --git a/monitor-server/src/main/java/org/gridsuite/monitor/server/controllers/MonitorController.java b/monitor-server/src/main/java/org/gridsuite/monitor/server/controllers/MonitorController.java index fe98c56c..ec691565 100644 --- a/monitor-server/src/main/java/org/gridsuite/monitor/server/controllers/MonitorController.java +++ b/monitor-server/src/main/java/org/gridsuite/monitor/server/controllers/MonitorController.java @@ -22,7 +22,6 @@ import org.springframework.web.bind.annotation.*; import java.util.List; -import java.util.Optional; import java.util.UUID; /** @@ -50,8 +49,7 @@ public ResponseEntity executeProcess( @Parameter(description = "Process config uuid") @RequestParam(name = "processConfigUuid") UUID processConfigUuid, @RequestParam(required = false, defaultValue = "false") boolean isDebug, @RequestHeader(HEADER_USER_ID) String userId) { - Optional executionId = processExecutionService.executeProcess(caseUuid, userId, processConfigUuid, isDebug); - return executionId.map(ResponseEntity::ok).orElseGet(() -> ResponseEntity.notFound().build()); + return ResponseEntity.ok(processExecutionService.executeProcess(caseUuid, userId, processConfigUuid, isDebug)); } @GetMapping("/executions/{executionId}/reports") @@ -59,8 +57,7 @@ public ResponseEntity executeProcess( @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "The execution reports"), @ApiResponse(responseCode = "404", description = "execution id was not found")}) public ResponseEntity getExecutionReports(@Parameter(description = "Execution UUID") @PathVariable UUID executionId) { - Optional reports = processExecutionService.getReports(executionId); - return reports.map(ResponseEntity::ok).orElseGet(() -> ResponseEntity.notFound().build()); + return ResponseEntity.ok(processExecutionService.getReports(executionId)); } @GetMapping("/executions/{executionId}/results") @@ -68,8 +65,7 @@ public ResponseEntity getExecutionReports(@Parameter(description = " @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "The execution results"), @ApiResponse(responseCode = "404", description = "execution id was not found")}) public ResponseEntity> getExecutionResults(@Parameter(description = "Execution UUID") @PathVariable UUID executionId) { - Optional> results = processExecutionService.getResults(executionId); - return results.map(ResponseEntity::ok).orElseGet(() -> ResponseEntity.notFound().build()); + return ResponseEntity.ok(processExecutionService.getResults(executionId)); } @GetMapping("/executions") @@ -85,8 +81,7 @@ public ResponseEntity> getLaunchedProcesses(@Parameter(de @ApiResponse(responseCode = "200", description = "The execution steps statuses"), @ApiResponse(responseCode = "404", description = "execution id was not found")}) public ResponseEntity> getStepsInfos(@Parameter(description = "Execution UUID") @PathVariable UUID executionId) { - return processExecutionService.getStepsInfos(executionId).map(list -> ResponseEntity.ok().body(list)) - .orElseGet(() -> ResponseEntity.notFound().build()); + return ResponseEntity.ok().body(processExecutionService.getStepsInfos(executionId)); } @GetMapping("/executions/{executionId}/debug-infos") @@ -95,14 +90,13 @@ public ResponseEntity> getStepsInfos(@Parameter(descr @ApiResponse(responseCode = "200", description = "Debug file downloaded"), @ApiResponse(responseCode = "404", description = "execution id was not found")}) public ResponseEntity getDebugInfos(@Parameter(description = "Execution UUID") @PathVariable UUID executionId) { - return processExecutionService.getDebugInfos(executionId) - .map(bytes -> ResponseEntity.ok() - .header(HttpHeaders.CONTENT_DISPOSITION, - "attachment; filename=\"archive.zip\"") - .contentType(MediaType.APPLICATION_OCTET_STREAM) - .contentLength(bytes.length) - .body(bytes)) - .orElseGet(() -> ResponseEntity.notFound().build()); + byte[] bytes = processExecutionService.getDebugInfos(executionId); + return ResponseEntity.ok() + .header(HttpHeaders.CONTENT_DISPOSITION, + "attachment; filename=\"archive.zip\"") + .contentType(MediaType.APPLICATION_OCTET_STREAM) + .contentLength(bytes.length) + .body(bytes); } @DeleteMapping("/executions/{executionId}") @@ -110,8 +104,7 @@ public ResponseEntity getDebugInfos(@Parameter(description = "Execution @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Execution was deleted"), @ApiResponse(responseCode = "404", description = "execution id was not found")}) public ResponseEntity deleteExecution(@PathVariable UUID executionId) { - Optional deletedExecutionId = processExecutionService.deleteExecution(executionId); - return deletedExecutionId.isPresent() ? ResponseEntity.ok().build() : ResponseEntity.notFound().build(); + processExecutionService.deleteExecution(executionId); + return ResponseEntity.ok().build(); } } - diff --git a/monitor-server/src/main/java/org/gridsuite/monitor/server/controllers/ProcessConfigController.java b/monitor-server/src/main/java/org/gridsuite/monitor/server/controllers/ProcessConfigController.java index 784a74c8..ea6276d0 100644 --- a/monitor-server/src/main/java/org/gridsuite/monitor/server/controllers/ProcessConfigController.java +++ b/monitor-server/src/main/java/org/gridsuite/monitor/server/controllers/ProcessConfigController.java @@ -18,7 +18,6 @@ import org.gridsuite.monitor.server.dto.processconfig.PersistedProcessConfig; import org.gridsuite.monitor.server.dto.processconfig.ProcessConfigComparison; import org.gridsuite.monitor.server.services.processconfig.ProcessConfigService; -import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; @@ -31,7 +30,6 @@ import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import java.util.List; -import java.util.Optional; import java.util.UUID; /** @@ -64,8 +62,7 @@ public ResponseEntity createProcessConfig(@Valid @RequestBody ProcessConfi @ApiResponse(responseCode = "404", description = "process config was not found")}) public ResponseEntity getProcessConfig( @Parameter(description = "process config UUID") @PathVariable("uuid") UUID processConfigUuid) { - Optional processConfig = processConfigService.getProcessConfig(processConfigUuid); - return processConfig.map(config -> ResponseEntity.ok().body(config)).orElseGet(() -> ResponseEntity.notFound().build()); + return ResponseEntity.ok().body(processConfigService.getProcessConfig(processConfigUuid)); } @GetMapping(value = "/metadata", produces = MediaType.APPLICATION_JSON_VALUE) @@ -85,8 +82,8 @@ public ResponseEntity> getProcessConfigsMetadata(@RequestPar public ResponseEntity updateProcessConfig( @Parameter(description = "process config UUID") @PathVariable("uuid") UUID processConfigUuid, @Valid @RequestBody ProcessConfig processConfig) { - Optional processConfigUpdated = processConfigService.updateProcessConfig(processConfigUuid, processConfig); - return processConfigUpdated.isPresent() ? ResponseEntity.ok().build() : ResponseEntity.notFound().build(); + processConfigService.updateProcessConfig(processConfigUuid, processConfig); + return ResponseEntity.ok().build(); } @PostMapping(value = "", params = "duplicateFrom", produces = MediaType.APPLICATION_JSON_VALUE) @@ -96,10 +93,7 @@ public ResponseEntity updateProcessConfig( @ApiResponse(responseCode = "404", description = "process config to duplicate was not found")}) public ResponseEntity duplicateProcessConfig( @Parameter(description = "UUID of the process config to duplicate") @RequestParam("duplicateFrom") UUID sourceProcessConfigUuid) { - Optional newProcessConfigUuid = processConfigService.duplicateProcessConfig(sourceProcessConfigUuid); - return newProcessConfigUuid - .map(configUuid -> ResponseEntity.ok().body(configUuid)) - .orElseGet(() -> ResponseEntity.notFound().build()); + return ResponseEntity.ok().body(processConfigService.duplicateProcessConfig(sourceProcessConfigUuid)); } @DeleteMapping(value = "/{uuid}", produces = MediaType.APPLICATION_JSON_VALUE) @@ -109,8 +103,8 @@ public ResponseEntity duplicateProcessConfig( @ApiResponse(responseCode = "404", description = "process config was not found")}) public ResponseEntity deleteProcessConfig( @Parameter(description = "process config UUID") @PathVariable("uuid") UUID processConfigUuid) { - Optional deletedProcessConfigId = processConfigService.deleteProcessConfig(processConfigUuid); - return deletedProcessConfigId.isPresent() ? ResponseEntity.ok().build() : ResponseEntity.notFound().build(); + processConfigService.deleteProcessConfig(processConfigUuid); + return ResponseEntity.ok().build(); } @GetMapping(value = "", produces = MediaType.APPLICATION_JSON_VALUE) @@ -132,7 +126,6 @@ public ResponseEntity> getProcessConfigs( public ResponseEntity compareProcessConfigs( @Parameter(description = "First process config UUID") @RequestParam("uuid1") UUID uuid1, @Parameter(description = "Second process config UUID") @RequestParam("uuid2") UUID uuid2) { - Optional comparison = processConfigService.compareProcessConfigs(uuid1, uuid2); - return comparison.map(c -> ResponseEntity.status(HttpStatus.OK).body(c)).orElseGet(() -> ResponseEntity.status(HttpStatus.NOT_FOUND).build()); + return ResponseEntity.ok(processConfigService.compareProcessConfigs(uuid1, uuid2)); } } diff --git a/monitor-server/src/main/java/org/gridsuite/monitor/server/error/MonitorServerBusinessErrorCode.java b/monitor-server/src/main/java/org/gridsuite/monitor/server/error/MonitorServerBusinessErrorCode.java index db96aa3a..14661ad8 100644 --- a/monitor-server/src/main/java/org/gridsuite/monitor/server/error/MonitorServerBusinessErrorCode.java +++ b/monitor-server/src/main/java/org/gridsuite/monitor/server/error/MonitorServerBusinessErrorCode.java @@ -12,7 +12,10 @@ * @author Franck Lecuyer */ public enum MonitorServerBusinessErrorCode implements BusinessErrorCode { - DIFFERENT_PROCESS_CONFIG_TYPE("monitor.server.differentProcessConfigType"); + DIFFERENT_PROCESS_CONFIG_TYPE("monitor.server.differentProcessConfigType"), + PROCESS_CONFIG_NOT_FOUND("monitor.server.processConfigNotFound"), + PROCESS_EXECUTION_NOT_FOUND("monitor.server.processExecutionNotFound"), + DEBUG_INFOS_NOT_FOUND("monitor.server.debugInfosNotFound"); private final String code; diff --git a/monitor-server/src/main/java/org/gridsuite/monitor/server/error/MonitorServerExceptionHandler.java b/monitor-server/src/main/java/org/gridsuite/monitor/server/error/MonitorServerExceptionHandler.java index 05aa2258..77fa820b 100644 --- a/monitor-server/src/main/java/org/gridsuite/monitor/server/error/MonitorServerExceptionHandler.java +++ b/monitor-server/src/main/java/org/gridsuite/monitor/server/error/MonitorServerExceptionHandler.java @@ -36,6 +36,7 @@ protected MonitorServerBusinessErrorCode getBusinessCode(MonitorServerException protected HttpStatus mapStatus(MonitorServerBusinessErrorCode errorCode) { return switch (errorCode) { case DIFFERENT_PROCESS_CONFIG_TYPE -> HttpStatus.BAD_REQUEST; + case PROCESS_CONFIG_NOT_FOUND, PROCESS_EXECUTION_NOT_FOUND, DEBUG_INFOS_NOT_FOUND -> HttpStatus.NOT_FOUND; }; } diff --git a/monitor-server/src/main/java/org/gridsuite/monitor/server/services/processconfig/ProcessConfigService.java b/monitor-server/src/main/java/org/gridsuite/monitor/server/services/processconfig/ProcessConfigService.java index b45ff683..d01345fb 100644 --- a/monitor-server/src/main/java/org/gridsuite/monitor/server/services/processconfig/ProcessConfigService.java +++ b/monitor-server/src/main/java/org/gridsuite/monitor/server/services/processconfig/ProcessConfigService.java @@ -23,6 +23,7 @@ import java.util.stream.Collectors; import static org.gridsuite.monitor.server.error.MonitorServerBusinessErrorCode.DIFFERENT_PROCESS_CONFIG_TYPE; +import static org.gridsuite.monitor.server.error.MonitorServerBusinessErrorCode.PROCESS_CONFIG_NOT_FOUND; /** * @author Franck Lecuyer @@ -58,9 +59,8 @@ public UUID createProcessConfig(ProcessConfig processConfig) { } @Transactional(readOnly = true) - public Optional getProcessConfig(UUID processConfigUuid) { - return processConfigRepository.findById(processConfigUuid) - .map(this::toPersistedProcessConfig); + public PersistedProcessConfig getProcessConfig(UUID processConfigUuid) { + return toPersistedProcessConfig(getProcessConfigEntity(processConfigUuid)); } @Transactional(readOnly = true) @@ -78,34 +78,28 @@ public List getProcessConfigsMetadata(List processConfigUui } @Transactional - public Optional updateProcessConfig(UUID processConfigUuid, ProcessConfig processConfig) { - return processConfigRepository.findById(processConfigUuid) - .map(entity -> { - if (entity.getProcessType() != processConfig.processType()) { - throw new IllegalArgumentException("Process config type mismatch : " + entity.getProcessType()); - } - getHandler(processConfig.processType()).update(processConfig, entity); - return processConfigUuid; - }); + public void updateProcessConfig(UUID processConfigUuid, ProcessConfig processConfig) { + ProcessConfigEntity entity = getProcessConfigEntity(processConfigUuid); + if (entity.getProcessType() != processConfig.processType()) { + throw new IllegalArgumentException("Process config type mismatch : " + entity.getProcessType()); + } + getHandler(processConfig.processType()).update(processConfig, entity); } @Transactional - public Optional duplicateProcessConfig(UUID sourceProcessConfigUuid) { - return processConfigRepository.findById(sourceProcessConfigUuid) - .map(sourceEntity -> { - ProcessConfigEntity entity = getHandler(sourceEntity.getProcessType()).copyEntity(sourceEntity); - return processConfigRepository.save(entity).getId(); - }); + public UUID duplicateProcessConfig(UUID sourceProcessConfigUuid) { + ProcessConfigEntity sourceEntity = getProcessConfigEntity(sourceProcessConfigUuid); + ProcessConfigEntity entity = getHandler(sourceEntity.getProcessType()).copyEntity(sourceEntity); + return processConfigRepository.save(entity).getId(); } @Transactional - public Optional deleteProcessConfig(UUID processConfigUuid) { + public void deleteProcessConfig(UUID processConfigUuid) { if (processConfigRepository.existsById(processConfigUuid)) { processConfigRepository.deleteById(processConfigUuid); - return Optional.of(processConfigUuid); - } else { - return Optional.empty(); + return; } + throw processConfigNotFound(processConfigUuid); } private PersistedProcessConfig toPersistedProcessConfig(ProcessConfigEntity entity) { @@ -117,25 +111,31 @@ private ProcessConfig toProcessConfig(ProcessConfigEntity entity) { } @Transactional(readOnly = true) - public Optional compareProcessConfigs(UUID uuid1, UUID uuid2) { - Optional processConfigEntity1 = processConfigRepository.findById(uuid1); - Optional processConfigEntity2 = processConfigRepository.findById(uuid2); - - if (processConfigEntity1.isEmpty() || processConfigEntity2.isEmpty()) { - return Optional.empty(); - } + public ProcessConfigComparison compareProcessConfigs(UUID uuid1, UUID uuid2) { + ProcessConfigEntity processConfigEntity1 = getProcessConfigEntity(uuid1); + ProcessConfigEntity processConfigEntity2 = getProcessConfigEntity(uuid2); - if (processConfigEntity1.get().getProcessType() != processConfigEntity2.get().getProcessType()) { + if (processConfigEntity1.getProcessType() != processConfigEntity2.getProcessType()) { throw new MonitorServerException(DIFFERENT_PROCESS_CONFIG_TYPE, "Cannot compare different process config types", - Map.of("processConfigEntity1Type", processConfigEntity1.get().getProcessType(), "processConfigEntity2Type", processConfigEntity2.get().getProcessType())); + Map.of("processConfigEntity1Type", processConfigEntity1.getProcessType(), "processConfigEntity2Type", processConfigEntity2.getProcessType())); } - ProcessConfig processConfig1 = toProcessConfig(processConfigEntity1.get()); - ProcessConfig processConfig2 = toProcessConfig(processConfigEntity2.get()); + ProcessConfig processConfig1 = toProcessConfig(processConfigEntity1); + ProcessConfig processConfig2 = toProcessConfig(processConfigEntity2); List differences = processConfig1.compareWith(processConfig2); boolean identical = differences.stream().allMatch(ProcessConfigFieldComparison::identical); - return Optional.of(new ProcessConfigComparison(uuid1, uuid2, identical, differences)); + return new ProcessConfigComparison(uuid1, uuid2, identical, differences); + } + + private ProcessConfigEntity getProcessConfigEntity(UUID processConfigUuid) { + return processConfigRepository.findById(processConfigUuid) + .orElseThrow(() -> processConfigNotFound(processConfigUuid)); + } + + private MonitorServerException processConfigNotFound(UUID processConfigUuid) { + return new MonitorServerException(PROCESS_CONFIG_NOT_FOUND, "Process config not found", + Map.of("processConfigUuid", processConfigUuid)); } } diff --git a/monitor-server/src/main/java/org/gridsuite/monitor/server/services/processexecution/ProcessExecutionService.java b/monitor-server/src/main/java/org/gridsuite/monitor/server/services/processexecution/ProcessExecutionService.java index 303fbdf6..08e0582a 100644 --- a/monitor-server/src/main/java/org/gridsuite/monitor/server/services/processexecution/ProcessExecutionService.java +++ b/monitor-server/src/main/java/org/gridsuite/monitor/server/services/processexecution/ProcessExecutionService.java @@ -10,7 +10,6 @@ import org.gridsuite.monitor.commons.types.messaging.ProcessExecutionStep; import org.gridsuite.monitor.commons.types.processexecution.ProcessStatus; import org.gridsuite.monitor.commons.types.processexecution.ProcessType; -import org.gridsuite.monitor.commons.types.result.ResultInfos; import org.gridsuite.monitor.server.clients.ReportRestClient; import org.gridsuite.monitor.server.clients.S3RestClient; import org.gridsuite.monitor.server.dto.processexecution.ProcessExecution; @@ -22,8 +21,6 @@ import java.io.IOException; import java.time.Instant; import java.util.List; -import java.util.Objects; -import java.util.Optional; import java.util.UUID; /** @@ -50,32 +47,28 @@ public ProcessExecutionService(ProcessExecutionTxService processExecutionTxServi this.s3RestClient = s3RestClient; } - public Optional executeProcess(UUID caseUuid, String userId, UUID processConfigId, boolean isDebug) { + public UUID executeProcess(UUID caseUuid, String userId, UUID processConfigId, boolean isDebug) { UUID executionId = UUID.randomUUID(); UUID reportId = UUID.randomUUID(); - Optional result = processExecutionTxService.createExecution( + ProcessCreationResult result = processExecutionTxService.createExecution( caseUuid, userId, processConfigId, executionId, reportId, isDebug ); - if (result.isEmpty()) { - return Optional.empty(); - } - notificationService.sendProcessRunMessage( caseUuid, - result.get().processConfig(), + result.processConfig(), executionId, reportId, - result.get().debugLocationFile() + result.debugLocationFile() ); notificationService.sendProcessUpdatedMessage( - result.get().processConfig().processType(), + result.processConfig().processType(), executionId ); - return Optional.of(executionId); + return executionId; } public void updateExecutionStatus(UUID executionId, ProcessStatus status, String executionEnvName, Instant startedAt, Instant completedAt) { @@ -90,47 +83,38 @@ public void updateStepsStatuses(UUID executionId, List pro processExecutionTxService.updateStepsStatuses(executionId, processExecutionSteps); } - public Optional getReports(UUID executionId) { - return processExecutionTxService.getReportId(executionId) - .map(reportRestClient::getReport); + public ReportPage getReports(UUID executionId) { + return reportRestClient.getReport(processExecutionTxService.getReportId(executionId)); } - public Optional> getResults(UUID executionId) { - Optional> resultInfos = processExecutionTxService.getResultInfos(executionId); - return resultInfos.map(results -> results.stream() + public List getResults(UUID executionId) { + return processExecutionTxService.getResultInfos(executionId).stream() .map(resultService::getResult) - .toList()); + .toList(); } - public Optional getDebugInfos(UUID executionId) { - return processExecutionTxService.getDebugFileLocation(executionId) - .filter(Objects::nonNull) - .map(debugFileLocation -> { - try { - return s3RestClient.downloadDirectoryAsZip(debugFileLocation); - } catch (IOException e) { - throw new PowsyblException("An error occurred while downloading debug files", e); - } - }); + public byte[] getDebugInfos(UUID executionId) { + String debugFileLocation = processExecutionTxService.getDebugFileLocation(executionId); + try { + return s3RestClient.downloadDirectoryAsZip(debugFileLocation); + } catch (IOException e) { + throw new PowsyblException("An error occurred while downloading debug files", e); + } } public List getLaunchedProcesses(ProcessType processType) { return processExecutionTxService.getLaunchedProcesses(processType); } - public Optional> getStepsInfos(UUID executionId) { + public List getStepsInfos(UUID executionId) { return processExecutionTxService.getStepsInfos(executionId); } - public Optional deleteExecution(UUID executionId) { - Optional executionDeletionData = processExecutionTxService.deleteExecution(executionId); - if (executionDeletionData.isPresent()) { - executionDeletionData.get().resultInfos().forEach(resultService::deleteResult); - if (executionDeletionData.get().reportId() != null) { - reportRestClient.deleteReport(executionDeletionData.get().reportId()); - } - return Optional.of(executionId); + public void deleteExecution(UUID executionId) { + ProcessDeletionInfos executionDeletionData = processExecutionTxService.deleteExecution(executionId); + executionDeletionData.resultInfos().forEach(resultService::deleteResult); + if (executionDeletionData.reportId() != null) { + reportRestClient.deleteReport(executionDeletionData.reportId()); } - return Optional.empty(); } } diff --git a/monitor-server/src/main/java/org/gridsuite/monitor/server/services/processexecution/ProcessExecutionTxService.java b/monitor-server/src/main/java/org/gridsuite/monitor/server/services/processexecution/ProcessExecutionTxService.java index 283d1f03..5d289b74 100644 --- a/monitor-server/src/main/java/org/gridsuite/monitor/server/services/processexecution/ProcessExecutionTxService.java +++ b/monitor-server/src/main/java/org/gridsuite/monitor/server/services/processexecution/ProcessExecutionTxService.java @@ -14,6 +14,7 @@ import org.gridsuite.monitor.server.dto.processexecution.ProcessExecution; import org.gridsuite.monitor.server.entities.processexecution.ProcessExecutionEntity; import org.gridsuite.monitor.server.entities.processexecution.ProcessExecutionStepEntity; +import org.gridsuite.monitor.server.error.MonitorServerException; import org.gridsuite.monitor.server.mappers.processexecution.ProcessExecutionMapper; import org.gridsuite.monitor.server.mappers.processexecution.ProcessExecutionStepMapper; import org.gridsuite.monitor.server.repositories.ProcessExecutionRepository; @@ -27,9 +28,13 @@ import java.time.Instant; import java.util.ArrayList; import java.util.List; +import java.util.Map; import java.util.Optional; import java.util.UUID; +import static org.gridsuite.monitor.server.error.MonitorServerBusinessErrorCode.DEBUG_INFOS_NOT_FOUND; +import static org.gridsuite.monitor.server.error.MonitorServerBusinessErrorCode.PROCESS_EXECUTION_NOT_FOUND; + @Service @Transactional(readOnly = true) public class ProcessExecutionTxService { @@ -55,33 +60,29 @@ public ProcessExecutionTxService(ProcessExecutionRepository processExecutionRepo } @Transactional - public Optional createExecution(UUID caseUuid, String userId, UUID processConfigId, UUID executionId, UUID reportId, boolean isDebug) { - Optional persistedProcessConfigOpt = processConfigService.getProcessConfig(processConfigId); - if (persistedProcessConfigOpt.isPresent()) { - PersistedProcessConfig persistedProcessConfig = persistedProcessConfigOpt.get(); - - String debugFileLocation = isDebug - ? s3PathResolver.toDebugLocation(persistedProcessConfig.processConfig().processType().name(), executionId) - : null; - - processExecutionRepository.save(ProcessExecutionEntity.builder() - .id(executionId) - .type(persistedProcessConfig.processConfig().processType().name()) - .caseUuid(caseUuid) - .processConfigId(persistedProcessConfig.id()) - .status(ProcessStatus.SCHEDULED) - .scheduledAt(Instant.now()) - .reportId(reportId) - .userId(userId) - .debugFileLocation(debugFileLocation) - .build()); - - return Optional.of(new ProcessCreationResult( - debugFileLocation, - persistedProcessConfig.processConfig() - )); - } - return Optional.empty(); + public ProcessCreationResult createExecution(UUID caseUuid, String userId, UUID processConfigId, UUID executionId, UUID reportId, boolean isDebug) { + PersistedProcessConfig persistedProcessConfig = processConfigService.getProcessConfig(processConfigId); + + String debugFileLocation = isDebug + ? s3PathResolver.toDebugLocation(persistedProcessConfig.processConfig().processType().name(), executionId) + : null; + + processExecutionRepository.save(ProcessExecutionEntity.builder() + .id(executionId) + .type(persistedProcessConfig.processConfig().processType().name()) + .caseUuid(caseUuid) + .processConfigId(persistedProcessConfig.id()) + .status(ProcessStatus.SCHEDULED) + .scheduledAt(Instant.now()) + .reportId(reportId) + .userId(userId) + .debugFileLocation(debugFileLocation) + .build()); + + return new ProcessCreationResult( + debugFileLocation, + persistedProcessConfig.processConfig() + ); } @Transactional @@ -121,22 +122,24 @@ public void updateStepsStatuses(UUID executionId, List pro }, () -> LOGGER.warn("Execution {} not found in DB, ignoring steps update", executionId)); } - public Optional getReportId(UUID executionId) { - return processExecutionRepository.findById(executionId) - .map(ProcessExecutionEntity::getReportId); + public UUID getReportId(UUID executionId) { + return getExecutionEntity(executionId).getReportId(); } - public Optional> getResultInfos(UUID executionId) { - return processExecutionRepository.findById(executionId) - .map(execution -> Optional.ofNullable(execution.getSteps()).orElse(List.of()).stream() - .filter(step -> step.getResultId() != null) - .map(step -> new ResultInfos(step.getResultId(), step.getResultType())) - .toList()); + public List getResultInfos(UUID executionId) { + return Optional.ofNullable(getExecutionEntity(executionId).getSteps()).orElse(List.of()).stream() + .filter(step -> step.getResultId() != null) + .map(step -> new ResultInfos(step.getResultId(), step.getResultType())) + .toList(); } - public Optional getDebugFileLocation(UUID executionId) { - return processExecutionRepository.findById(executionId) - .map(ProcessExecutionEntity::getDebugFileLocation); + public String getDebugFileLocation(UUID executionId) { + String debugFileLocation = getExecutionEntity(executionId).getDebugFileLocation(); + if (debugFileLocation == null) { + throw new MonitorServerException(DEBUG_INFOS_NOT_FOUND, "Debug infos not found", + Map.of("executionId", executionId)); + } + return debugFileLocation; } public List getLaunchedProcesses(ProcessType processType) { @@ -145,27 +148,20 @@ public List getLaunchedProcesses(ProcessType processType) { .toList(); } - public Optional> getStepsInfos(UUID executionId) { - return processExecutionRepository.findById(executionId) - .map(execution -> Optional.ofNullable(execution.getSteps()).orElse(List.of()).stream() - .map(processExecutionStepMapper::toDto) - .toList()); + public List getStepsInfos(UUID executionId) { + return Optional.ofNullable(getExecutionEntity(executionId).getSteps()).orElse(List.of()).stream() + .map(processExecutionStepMapper::toDto) + .toList(); } @Transactional - public Optional deleteExecution(UUID executionId) { - Optional opt = - processExecutionRepository.findById(executionId); - if (opt.isEmpty()) { - return Optional.empty(); - } - - ProcessExecutionEntity entity = opt.get(); + public ProcessDeletionInfos deleteExecution(UUID executionId) { + ProcessExecutionEntity entity = getExecutionEntity(executionId); ProcessDeletionInfos infos = ProcessDeletionInfos.fromProcessExecutionEntity(entity); processExecutionRepository.delete(entity); - return Optional.of(infos); + return infos; } private void updateStep(ProcessExecutionEntity execution, ProcessExecutionStepEntity stepEntity) { @@ -181,4 +177,10 @@ private void updateStep(ProcessExecutionEntity execution, ProcessExecutionStepEn existingStep -> processExecutionStepMapper.updateEntityFromEntity(stepEntity, existingStep), () -> steps.add(stepEntity)); } + + private ProcessExecutionEntity getExecutionEntity(UUID executionId) { + return processExecutionRepository.findById(executionId) + .orElseThrow(() -> new MonitorServerException(PROCESS_EXECUTION_NOT_FOUND, "Process execution not found", + Map.of("executionId", executionId))); + } } diff --git a/monitor-server/src/test/java/org/gridsuite/monitor/server/MonitorIntegrationTest.java b/monitor-server/src/test/java/org/gridsuite/monitor/server/MonitorIntegrationTest.java index c4abdad2..2fcb2641 100644 --- a/monitor-server/src/test/java/org/gridsuite/monitor/server/MonitorIntegrationTest.java +++ b/monitor-server/src/test/java/org/gridsuite/monitor/server/MonitorIntegrationTest.java @@ -21,6 +21,7 @@ import org.gridsuite.monitor.server.dto.report.ReportPage; import org.gridsuite.monitor.server.dto.report.Severity; import org.gridsuite.monitor.server.entities.processexecution.ProcessExecutionEntity; +import org.gridsuite.monitor.server.error.MonitorServerException; import org.gridsuite.monitor.server.messaging.ConsumerService; import org.gridsuite.monitor.server.repositories.ProcessConfigRepository; import org.gridsuite.monitor.server.repositories.ProcessExecutionRepository; @@ -43,9 +44,9 @@ import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.List; -import java.util.Optional; import java.util.UUID; -import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.*; +import static org.gridsuite.monitor.server.error.MonitorServerBusinessErrorCode.PROCESS_CONFIG_NOT_FOUND; import static org.hamcrest.Matchers.hasSize; import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; @@ -113,14 +114,14 @@ void securityAnalysisProcessIT() throws Exception { UUID.randomUUID()); UUID processConfigId = configService.createProcessConfig(securityAnalysisConfig); - Optional executionId = processExecutionService.executeProcess(caseUuid, userId, processConfigId, false); + UUID executionId = processExecutionService.executeProcess(caseUuid, userId, processConfigId, false); // Verify message was published Message sentMessage = outputDestination.receive(1000, PROCESS_SA_RUN_DESTINATION); assertThat(sentMessage).isNotNull(); // Verify execution persisted with correct initial state - ProcessExecutionEntity execution = executionRepository.findById(executionId.get()).orElse(null); + ProcessExecutionEntity execution = executionRepository.findById(executionId).orElse(null); assertThat(execution).isNotNull(); assertThat(execution.getReportId()).isNotNull(); assertThat(execution.getStatus()).isEqualTo(ProcessStatus.SCHEDULED); @@ -139,7 +140,7 @@ void securityAnalysisProcessIT() throws Exception { .startedAt(Instant.now()) .completedAt(Instant.now()) .build(); - sendMessage(executionId.get(), step0, MessageType.STEP_STATUS_UPDATE); + sendMessage(executionId, step0, MessageType.STEP_STATUS_UPDATE); // Simulate second step creation via message with both report and result UUID stepId1 = UUID.randomUUID(); @@ -154,10 +155,10 @@ void securityAnalysisProcessIT() throws Exception { .startedAt(Instant.now()) .completedAt(Instant.now()) .build(); - sendMessage(executionId.get(), step1, MessageType.STEP_STATUS_UPDATE); + sendMessage(executionId, step1, MessageType.STEP_STATUS_UPDATE); // Verify both steps were added to database with correct data - execution = executionRepository.findById(executionId.get()).orElse(null); + execution = executionRepository.findById(executionId).orElse(null); assertThat(execution.getSteps()).hasSize(2); assertThat(execution.getSteps().get(0).getId()).isEqualTo(stepId0); assertThat(execution.getSteps().get(0).getStatus()).isEqualTo(StepStatus.COMPLETED); @@ -174,10 +175,10 @@ void securityAnalysisProcessIT() throws Exception { .startedAt(startedAt) .completedAt(completedAt) .build(); - sendMessage(executionId.get(), finalStatus, MessageType.EXECUTION_STATUS_UPDATE); + sendMessage(executionId, finalStatus, MessageType.EXECUTION_STATUS_UPDATE); // Verify final state persisted - execution = executionRepository.findById(executionId.get()).orElse(null); + execution = executionRepository.findById(executionId).orElse(null); assertThat(execution.getStatus()).isEqualTo(ProcessStatus.COMPLETED); assertThat(execution.getExecutionEnvName()).isEqualTo("test-env"); assertThat(execution.getStartedAt().truncatedTo(ChronoUnit.MILLIS)).isEqualTo(startedAt.truncatedTo(ChronoUnit.MILLIS)); @@ -192,7 +193,7 @@ void securityAnalysisProcessIT() throws Exception { when(reportRestClient.getReport(execution.getReportId())).thenReturn(reportPage); // Test the reports endpoint fetches correctly from database - mockMvc.perform(get("/v1/executions/{executionId}/reports", executionId.get())) + mockMvc.perform(get("/v1/executions/{executionId}/reports", executionId)) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andExpect(jsonPath("number").value(1)) @@ -216,7 +217,7 @@ void securityAnalysisProcessIT() throws Exception { when(resultService.getResult(new ResultInfos(resultId1, ResultType.SECURITY_ANALYSIS))).thenReturn(result1); // Test the results endpoint fetches correctly from database - mockMvc.perform(get("/v1/executions/{executionId}/results", executionId.get())) + mockMvc.perform(get("/v1/executions/{executionId}/results", executionId)) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andExpect(jsonPath("$", hasSize(2))) @@ -247,9 +248,8 @@ void processConfigIT() { UUID configId = configService.createProcessConfig(securityAnalysisConfig); assertThat(processConfigRepository.findById(configId)).isNotEmpty(); - Optional config = configService.getProcessConfig(configId); - assertThat(config).isNotEmpty(); - assertThat(config.get().processConfig()).usingRecursiveComparison().isEqualTo(securityAnalysisConfig); + PersistedProcessConfig config = configService.getProcessConfig(configId); + assertThat(config.processConfig()).usingRecursiveComparison().isEqualTo(securityAnalysisConfig); UUID updatedParametersUuid = UUID.randomUUID(); UUID updatedModificationUuid = UUID.randomUUID(); @@ -259,17 +259,15 @@ void processConfigIT() { List.of(updatedModificationUuid), updatedLoadflowParametersUuid ); - Optional updatedProcessConfigId = configService.updateProcessConfig(configId, updatedSecurityAnalysisConfig); - assertThat(updatedProcessConfigId).contains(configId); - Optional updatedConfig = configService.getProcessConfig(configId); - assertThat(updatedConfig).isNotEmpty(); - assertThat(updatedConfig.get().processConfig()).usingRecursiveComparison().isEqualTo(updatedSecurityAnalysisConfig); + configService.updateProcessConfig(configId, updatedSecurityAnalysisConfig); + PersistedProcessConfig updatedConfig = configService.getProcessConfig(configId); + assertThat(updatedConfig.processConfig()).usingRecursiveComparison().isEqualTo(updatedSecurityAnalysisConfig); - Optional deletedProcessConfigId = configService.deleteProcessConfig(configId); - assertThat(deletedProcessConfigId).contains(configId); + configService.deleteProcessConfig(configId); - Optional deletedConfig = configService.getProcessConfig(configId); - assertThat(deletedConfig).isEmpty(); + assertThatThrownBy(() -> configService.getProcessConfig(configId)) + .isInstanceOf(MonitorServerException.class) + .satisfies(ex -> assertThat(((MonitorServerException) ex).getErrorCode()).isEqualTo(PROCESS_CONFIG_NOT_FOUND)); } @Test @@ -319,15 +317,13 @@ void processConfigsIT() { assertThat(retrievedSecurityAnalysisConfig2.loadflowParametersUuid()).isEqualTo(loadFlowParametersUuid2); assertThat(retrievedSecurityAnalysisConfig2.modificationUuids()).isEqualTo(List.of(modificationUuid2)); - Optional deletedProcessConfigId = configService.deleteProcessConfig(configId1); - assertThat(deletedProcessConfigId).contains(configId1); + configService.deleteProcessConfig(configId1); List remainingConfigs = configService.getProcessConfigs(ProcessType.SECURITY_ANALYSIS); assertThat(remainingConfigs).hasSize(1); assertThat(remainingConfigs.get(0).processConfig().processType()).isEqualTo(ProcessType.SECURITY_ANALYSIS); - deletedProcessConfigId = configService.deleteProcessConfig(configId2); - assertThat(deletedProcessConfigId).contains(configId2); + configService.deleteProcessConfig(configId2); List noConfigs = configService.getProcessConfigs(ProcessType.SECURITY_ANALYSIS); assertThat(noConfigs).isEmpty(); diff --git a/monitor-server/src/test/java/org/gridsuite/monitor/server/controllers/MonitorControllerTest.java b/monitor-server/src/test/java/org/gridsuite/monitor/server/controllers/MonitorControllerTest.java index 2543fc1c..bc84631a 100644 --- a/monitor-server/src/test/java/org/gridsuite/monitor/server/controllers/MonitorControllerTest.java +++ b/monitor-server/src/test/java/org/gridsuite/monitor/server/controllers/MonitorControllerTest.java @@ -8,16 +8,15 @@ import com.fasterxml.jackson.databind.ObjectMapper; import org.gridsuite.monitor.commons.types.messaging.ProcessExecutionStep; -import org.gridsuite.monitor.commons.types.processconfig.SecurityAnalysisConfig; import org.gridsuite.monitor.commons.types.processexecution.ProcessStatus; import org.gridsuite.monitor.commons.types.processexecution.ProcessType; import org.gridsuite.monitor.commons.types.processexecution.StepStatus; import org.gridsuite.monitor.server.PropertyServerNameProvider; -import org.gridsuite.monitor.server.dto.processconfig.PersistedProcessConfig; import org.gridsuite.monitor.server.dto.processexecution.ProcessExecution; import org.gridsuite.monitor.server.dto.report.ReportLog; import org.gridsuite.monitor.server.dto.report.ReportPage; import org.gridsuite.monitor.server.dto.report.Severity; +import org.gridsuite.monitor.server.error.MonitorServerException; import org.gridsuite.monitor.server.services.processconfig.ProcessConfigService; import org.gridsuite.monitor.server.services.processexecution.ProcessExecutionService; import org.junit.jupiter.api.Test; @@ -33,11 +32,14 @@ import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; import java.time.Instant; import java.util.List; -import java.util.Optional; import java.util.UUID; +import static org.gridsuite.monitor.server.error.MonitorServerBusinessErrorCode.DEBUG_INFOS_NOT_FOUND; +import static org.gridsuite.monitor.server.error.MonitorServerBusinessErrorCode.PROCESS_CONFIG_NOT_FOUND; +import static org.gridsuite.monitor.server.error.MonitorServerBusinessErrorCode.PROCESS_EXECUTION_NOT_FOUND; import static org.hamcrest.Matchers.hasSize; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; @@ -72,18 +74,10 @@ void executeProcessShouldReturnExecutionId(Boolean isDebug) throws Exception { UUID loadflowParametersUuid = UUID.randomUUID(); UUID processConfigUuid = UUID.randomUUID(); - SecurityAnalysisConfig config = new SecurityAnalysisConfig( - parametersUuid, - List.of(modificationUuid), - loadflowParametersUuid - ); - PersistedProcessConfig persistedProcessConfig = new PersistedProcessConfig(processConfigUuid, config); - boolean expectedDebugValue = Boolean.TRUE.equals(isDebug); - when(processConfigService.getProcessConfig(processConfigUuid)).thenReturn(Optional.of(persistedProcessConfig)); when(processExecutionService.executeProcess(any(UUID.class), any(String.class), any(UUID.class), eq(expectedDebugValue))) - .thenReturn(Optional.of(executionId)); + .thenReturn(executionId); MockHttpServletRequestBuilder request = post("/v1/execute") .param("caseUuid", caseUuid.toString()) @@ -107,7 +101,8 @@ void executeProcessWithConfigNotFoundShouldReturnError() throws Exception { UUID caseUuid = UUID.randomUUID(); UUID processConfigUuid = UUID.randomUUID(); - when(processExecutionService.executeProcess(caseUuid, "user1", processConfigUuid, false)).thenReturn(Optional.empty()); + when(processExecutionService.executeProcess(caseUuid, "user1", processConfigUuid, false)) + .thenThrow(new MonitorServerException(PROCESS_CONFIG_NOT_FOUND, "Process config not found")); MockHttpServletRequestBuilder request = post("/v1/execute") .param("caseUuid", caseUuid.toString()) @@ -128,7 +123,7 @@ void getExecutionReportsShouldReturnReports() throws Exception { ReportLog reportLog3 = new ReportLog("message3", Severity.ERROR, 1, UUID.randomUUID()); ReportPage reportPage = new ReportPage(1, List.of(reportLog1, reportLog2, reportLog3), 100, 10); when(processExecutionService.getReports(executionId)) - .thenReturn(Optional.of(reportPage)); + .thenReturn(reportPage); mockMvc.perform(get("/v1/executions/{executionId}/reports", executionId)) .andExpect(status().isOk()) @@ -154,7 +149,7 @@ void getExecutionReportsShouldReturnReports() throws Exception { void getExecutionReportsReturnsNotFound() throws Exception { UUID executionId = UUID.randomUUID(); when(processExecutionService.getReports(executionId)) - .thenReturn(Optional.empty()); + .thenThrow(new MonitorServerException(PROCESS_EXECUTION_NOT_FOUND, "Process execution not found")); mockMvc.perform(get("/v1/executions/{executionId}/reports", executionId)) .andExpect(status().isNotFound()); @@ -168,7 +163,7 @@ void getExecutionResultsShouldReturnListOfResults() throws Exception { String result1 = "{\"result\": \"data1\"}"; String result2 = "{\"result\": \"data2\"}"; when(processExecutionService.getResults(executionId)) - .thenReturn(Optional.of(List.of(result1, result2))); + .thenReturn(List.of(result1, result2)); mockMvc.perform(get("/v1/executions/{executionId}/results", executionId)) .andExpect(status().isOk()) @@ -184,7 +179,7 @@ void getExecutionResultsShouldReturnListOfResults() throws Exception { void getExecutionResultsReturnsNotFound() throws Exception { UUID executionId = UUID.randomUUID(); when(processExecutionService.getResults(executionId)) - .thenReturn(Optional.empty()); + .thenThrow(new MonitorServerException(PROCESS_EXECUTION_NOT_FOUND, "Process execution not found")); mockMvc.perform(get("/v1/executions/{executionId}/results", executionId)) .andExpect(status().isNotFound()); @@ -222,7 +217,7 @@ void getStepsInfos() throws Exception { ProcessExecutionStep processExecutionStep3 = new ProcessExecutionStep(UUID.randomUUID(), "runSA", 2, StepStatus.SCHEDULED, null, null, null, null); List processExecutionStepList = List.of(processExecutionStep1, processExecutionStep2, processExecutionStep3); - when(processExecutionService.getStepsInfos(executionId)).thenReturn(Optional.of(processExecutionStepList)); + when(processExecutionService.getStepsInfos(executionId)).thenReturn(processExecutionStepList); mockMvc.perform(get("/v1/executions/{executionId}/step-infos", executionId)) .andExpect(status().isOk()) @@ -236,7 +231,8 @@ void getStepsInfos() throws Exception { @Test void getStepsInfosShouldReturn404WhenExecutionNotFound() throws Exception { UUID executionId = UUID.randomUUID(); - when(processExecutionService.getStepsInfos(executionId)).thenReturn(Optional.empty()); + when(processExecutionService.getStepsInfos(executionId)) + .thenThrow(new MonitorServerException(PROCESS_EXECUTION_NOT_FOUND, "Process execution not found")); mockMvc.perform(get("/v1/executions/{executionId}/step-infos", executionId)) .andExpect(status().isNotFound()); @@ -247,9 +243,6 @@ void getStepsInfosShouldReturn404WhenExecutionNotFound() throws Exception { @Test void deleteExecutionReturnsOK() throws Exception { UUID executionId = UUID.randomUUID(); - when(processExecutionService.deleteExecution(executionId)) - .thenReturn(Optional.of(executionId)); - mockMvc.perform(delete("/v1/executions/{executionId}", executionId)) .andExpect(status().isOk()); @@ -259,8 +252,8 @@ void deleteExecutionReturnsOK() throws Exception { @Test void deleteExecutionReturnsNotFound() throws Exception { UUID executionId = UUID.randomUUID(); - when(processExecutionService.deleteExecution(executionId)) - .thenReturn(Optional.empty()); + doThrow(new MonitorServerException(PROCESS_EXECUTION_NOT_FOUND, "Process execution not found")) + .when(processExecutionService).deleteExecution(executionId); mockMvc.perform(delete("/v1/executions/{executionId}", executionId)) .andExpect(status().isNotFound()); @@ -274,7 +267,7 @@ void getDebugFilesReturnsOK() throws Exception { byte[] zipContent = "dummy-zip-content".getBytes(); when(processExecutionService.getDebugInfos(executionId)) - .thenReturn(Optional.of(zipContent)); + .thenReturn(zipContent); mockMvc.perform(get("/v1/executions/{executionId}/debug-infos", executionId)) .andExpect(status().isOk()) @@ -292,7 +285,8 @@ void getDebugFilesReturnsOK() throws Exception { @Test void getDebugFilesReturnsNotFound() throws Exception { - when(processExecutionService.getDebugInfos(any())).thenReturn(Optional.empty()); + when(processExecutionService.getDebugInfos(any())) + .thenThrow(new MonitorServerException(DEBUG_INFOS_NOT_FOUND, "Debug infos not found")); mockMvc.perform(get("/v1/executions/{executionId}/debug-infos", UUID.randomUUID())) .andExpect(status().isNotFound()); diff --git a/monitor-server/src/test/java/org/gridsuite/monitor/server/controllers/ProcessConfigControllerTest.java b/monitor-server/src/test/java/org/gridsuite/monitor/server/controllers/ProcessConfigControllerTest.java index 92acb1de..1201eb19 100644 --- a/monitor-server/src/test/java/org/gridsuite/monitor/server/controllers/ProcessConfigControllerTest.java +++ b/monitor-server/src/test/java/org/gridsuite/monitor/server/controllers/ProcessConfigControllerTest.java @@ -25,11 +25,12 @@ import org.springframework.test.web.servlet.MockMvc; import java.util.List; -import java.util.Optional; import java.util.UUID; import static org.gridsuite.monitor.server.error.MonitorServerBusinessErrorCode.DIFFERENT_PROCESS_CONFIG_TYPE; +import static org.gridsuite.monitor.server.error.MonitorServerBusinessErrorCode.PROCESS_CONFIG_NOT_FOUND; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; @@ -82,7 +83,7 @@ void getProcessConfig() throws Exception { String expectedJson = objectMapper.writeValueAsString(config); when(processConfigService.getProcessConfig(any(UUID.class))) - .thenReturn(Optional.of(config)); + .thenReturn(config); mockMvc.perform(get("/v1/process-configs/{uuid}", processConfigId) .contentType(MediaType.APPLICATION_JSON)) @@ -98,7 +99,7 @@ void getProcessConfigNotFound() throws Exception { UUID processConfigId = UUID.randomUUID(); when(processConfigService.getProcessConfig(any(UUID.class))) - .thenReturn(Optional.empty()); + .thenThrow(new MonitorServerException(PROCESS_CONFIG_NOT_FOUND, "Process config not found")); mockMvc.perform(get("/v1/process-configs/{uuid}", processConfigId) .contentType(MediaType.APPLICATION_JSON)) @@ -134,9 +135,6 @@ void updateProcessConfig() throws Exception { UUID processConfigId = UUID.randomUUID(); SecurityAnalysisConfig config = new SecurityAnalysisConfig(UUID.randomUUID(), List.of(UUID.randomUUID(), UUID.randomUUID()), UUID.randomUUID()); - when(processConfigService.updateProcessConfig(any(UUID.class), any(ProcessConfig.class))) - .thenReturn(Optional.of(processConfigId)); - mockMvc.perform(put("/v1/process-configs/{uuid}", processConfigId) .contentType(MediaType.APPLICATION_JSON) .content(objectMapper.writeValueAsString(config))) @@ -150,8 +148,8 @@ void updateProcessConfigNotFound() throws Exception { UUID processConfigId = UUID.randomUUID(); SecurityAnalysisConfig config = new SecurityAnalysisConfig(UUID.randomUUID(), List.of(UUID.randomUUID()), UUID.randomUUID()); - when(processConfigService.updateProcessConfig(any(UUID.class), any(ProcessConfig.class))) - .thenReturn(Optional.empty()); + doThrow(new MonitorServerException(PROCESS_CONFIG_NOT_FOUND, "Process config not found")) + .when(processConfigService).updateProcessConfig(any(UUID.class), any(ProcessConfig.class)); mockMvc.perform(put("/v1/process-configs/{uuid}", processConfigId) .contentType(MediaType.APPLICATION_JSON) @@ -167,7 +165,7 @@ void duplicateProcessConfig() throws Exception { UUID newProcessConfigId = UUID.randomUUID(); when(processConfigService.duplicateProcessConfig(processConfigId)) - .thenReturn(Optional.of(newProcessConfigId)); + .thenReturn(newProcessConfigId); mockMvc.perform(post("/v1/process-configs?duplicateFrom={uuid}", processConfigId)) .andExpect(status().isOk()) @@ -182,7 +180,7 @@ void duplicateProcessConfigNotFound() throws Exception { UUID processConfigId = UUID.randomUUID(); when(processConfigService.duplicateProcessConfig(processConfigId)) - .thenReturn(Optional.empty()); + .thenThrow(new MonitorServerException(PROCESS_CONFIG_NOT_FOUND, "Process config not found")); mockMvc.perform(post("/v1/process-configs?duplicateFrom={uuid}", processConfigId)) .andExpect(status().isNotFound()); @@ -194,9 +192,6 @@ void duplicateProcessConfigNotFound() throws Exception { void deleteProcessConfig() throws Exception { UUID processConfigId = UUID.randomUUID(); - when(processConfigService.deleteProcessConfig(any(UUID.class))) - .thenReturn(Optional.of(processConfigId)); - mockMvc.perform(delete("/v1/process-configs/{uuid}", processConfigId)) .andExpect(status().isOk()); @@ -207,8 +202,8 @@ void deleteProcessConfig() throws Exception { void deleteProcessConfigNotFound() throws Exception { UUID processConfigId = UUID.randomUUID(); - when(processConfigService.deleteProcessConfig(any(UUID.class))) - .thenReturn(Optional.empty()); + doThrow(new MonitorServerException(PROCESS_CONFIG_NOT_FOUND, "Process config not found")) + .when(processConfigService).deleteProcessConfig(any(UUID.class)); mockMvc.perform(delete("/v1/process-configs/{uuid}", processConfigId)) .andExpect(status().isNotFound()); @@ -272,7 +267,7 @@ void compareProcessConfigsShouldReturnComparisonResult() throws Exception { ); when(processConfigService.compareProcessConfigs(uuid1, uuid2)) - .thenReturn(Optional.of(comparison)); + .thenReturn(comparison); mockMvc.perform(get("/v1/process-configs/compare") .param("uuid1", uuid1.toString()) @@ -306,7 +301,7 @@ void compareProcessConfigsShouldReturnDifferences() throws Exception { ); when(processConfigService.compareProcessConfigs(uuid1, uuid2)) - .thenReturn(Optional.of(comparison)); + .thenReturn(comparison); mockMvc.perform(get("/v1/process-configs/compare") .param("uuid1", uuid1.toString()) @@ -326,7 +321,7 @@ void compareProcessConfigsShouldReturn404WhenConfigNotFound() throws Exception { UUID uuid2 = UUID.randomUUID(); when(processConfigService.compareProcessConfigs(uuid1, uuid2)) - .thenReturn(Optional.empty()); + .thenThrow(new MonitorServerException(PROCESS_CONFIG_NOT_FOUND, "Process config not found")); mockMvc.perform(get("/v1/process-configs/compare") .param("uuid1", uuid1.toString()) diff --git a/monitor-server/src/test/java/org/gridsuite/monitor/server/error/MonitorServerExceptionHandlerTest.java b/monitor-server/src/test/java/org/gridsuite/monitor/server/error/MonitorServerExceptionHandlerTest.java index d507307c..63c522a3 100644 --- a/monitor-server/src/test/java/org/gridsuite/monitor/server/error/MonitorServerExceptionHandlerTest.java +++ b/monitor-server/src/test/java/org/gridsuite/monitor/server/error/MonitorServerExceptionHandlerTest.java @@ -15,6 +15,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.gridsuite.monitor.server.error.MonitorServerBusinessErrorCode.DIFFERENT_PROCESS_CONFIG_TYPE; +import static org.gridsuite.monitor.server.error.MonitorServerBusinessErrorCode.PROCESS_CONFIG_NOT_FOUND; import static org.junit.jupiter.api.Assertions.assertEquals; /** @@ -38,4 +39,15 @@ void mapsBadRequestBusinessErrorToStatus() { assertThat(response.getBody()).isNotNull(); assertEquals("monitor.server.differentProcessConfigType", response.getBody().getBusinessErrorCode()); } + + @Test + void mapsNotFoundBusinessErrorToStatus() { + MockHttpServletRequest request = new MockHttpServletRequest("GET", "/process-configs/uuid"); + MonitorServerException exception = new MonitorServerException(PROCESS_CONFIG_NOT_FOUND, "Process config not found"); + ResponseEntity response = handler.handleMonitorServerException(exception, request); + + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); + assertThat(response.getBody()).isNotNull(); + assertEquals("monitor.server.processConfigNotFound", response.getBody().getBusinessErrorCode()); + } } diff --git a/monitor-server/src/test/java/org/gridsuite/monitor/server/services/processconfig/ProcessConfigServiceTest.java b/monitor-server/src/test/java/org/gridsuite/monitor/server/services/processconfig/ProcessConfigServiceTest.java index 832ca637..fb9ebd20 100644 --- a/monitor-server/src/test/java/org/gridsuite/monitor/server/services/processconfig/ProcessConfigServiceTest.java +++ b/monitor-server/src/test/java/org/gridsuite/monitor/server/services/processconfig/ProcessConfigServiceTest.java @@ -28,6 +28,7 @@ import static org.assertj.core.api.Assertions.*; import static org.gridsuite.monitor.server.error.MonitorServerBusinessErrorCode.DIFFERENT_PROCESS_CONFIG_TYPE; +import static org.gridsuite.monitor.server.error.MonitorServerBusinessErrorCode.PROCESS_CONFIG_NOT_FOUND; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; @@ -87,10 +88,9 @@ void getProcessConfig() { when(handler.toDto(processConfigEntity)).thenReturn(processConfig); when(processConfigEntity.getId()).thenReturn(processConfigUuid); - Optional result = processConfigService.getProcessConfig(processConfigUuid); + PersistedProcessConfig result = processConfigService.getProcessConfig(processConfigUuid); - assertThat(result).isPresent(); - assertThat(result.get().processConfig()).isEqualTo(processConfig); + assertThat(result.processConfig()).isEqualTo(processConfig); verify(processConfigRepository).findById(processConfigUuid); verify(handler).toDto(processConfigEntity); } @@ -101,9 +101,9 @@ void getProcessConfigNotFound() { when(processConfigRepository.findById(processConfigUuid)).thenReturn(Optional.empty()); - Optional result = processConfigService.getProcessConfig(processConfigUuid); - - assertThat(result).isEmpty(); + assertThatThrownBy(() -> processConfigService.getProcessConfig(processConfigUuid)) + .isInstanceOf(MonitorServerException.class) + .satisfies(ex -> assertThat(((MonitorServerException) ex).getErrorCode()).isEqualTo(PROCESS_CONFIG_NOT_FOUND)); verify(processConfigRepository).findById(processConfigUuid); verify(handler, never()).toDto(any()); } @@ -158,11 +158,8 @@ void updateProcessConfig() { when(processConfig.processType()).thenReturn(PROCESS_TYPE); doNothing().when(handler).update(processConfig, processConfigEntity); - Optional result = processConfigService.updateProcessConfig(processConfigUuid, processConfig); + processConfigService.updateProcessConfig(processConfigUuid, processConfig); - assertThat(result) - .isPresent() - .contains(processConfigUuid); verify(processConfigRepository).findById(processConfigUuid); verify(handler).update(processConfig, processConfigEntity); } @@ -173,9 +170,9 @@ void updateProcessConfigNotFound() { when(processConfigRepository.findById(processConfigUuid)).thenReturn(Optional.empty()); - Optional result = processConfigService.updateProcessConfig(processConfigUuid, processConfig); - - assertThat(result).isEmpty(); + assertThatThrownBy(() -> processConfigService.updateProcessConfig(processConfigUuid, processConfig)) + .isInstanceOf(MonitorServerException.class) + .satisfies(ex -> assertThat(((MonitorServerException) ex).getErrorCode()).isEqualTo(PROCESS_CONFIG_NOT_FOUND)); verify(processConfigRepository).findById(processConfigUuid); verify(handler, never()).update(processConfig, processConfigEntity); } @@ -206,11 +203,9 @@ void duplicateSecurityAnalysisConfig() { when(processConfigRepository.save(copiedProcessConfigEntity)).thenReturn(copiedProcessConfigEntity); when(copiedProcessConfigEntity.getId()).thenReturn(copiedProcessConfigUuid); - Optional result = processConfigService.duplicateProcessConfig(processConfigUuid); + UUID result = processConfigService.duplicateProcessConfig(processConfigUuid); - assertThat(result) - .isPresent() - .contains(copiedProcessConfigUuid); + assertThat(result).isEqualTo(copiedProcessConfigUuid); verify(processConfigRepository).findById(processConfigUuid); verify(handler).copyEntity(processConfigEntity); verify(processConfigRepository).save(copiedProcessConfigEntity); @@ -222,9 +217,9 @@ void duplicateProcessConfigNotFound() { when(processConfigRepository.findById(processConfigUuid)).thenReturn(Optional.empty()); - Optional result = processConfigService.duplicateProcessConfig(processConfigUuid); - - assertThat(result).isEmpty(); + assertThatThrownBy(() -> processConfigService.duplicateProcessConfig(processConfigUuid)) + .isInstanceOf(MonitorServerException.class) + .satisfies(ex -> assertThat(((MonitorServerException) ex).getErrorCode()).isEqualTo(PROCESS_CONFIG_NOT_FOUND)); verify(processConfigRepository).findById(processConfigUuid); verify(handler, never()).copyEntity(any()); } @@ -235,9 +230,8 @@ void deleteProcessConfig() { when(processConfigRepository.existsById(processConfigUuid)).thenReturn(Boolean.TRUE); doNothing().when(processConfigRepository).deleteById(processConfigUuid); - Optional result = processConfigService.deleteProcessConfig(processConfigUuid); + processConfigService.deleteProcessConfig(processConfigUuid); - assertThat(result).contains(processConfigUuid); verify(processConfigRepository).existsById(processConfigUuid); verify(processConfigRepository).deleteById(processConfigUuid); } @@ -248,9 +242,9 @@ void deleteProcessConfigNotFound() { when(processConfigRepository.existsById(processConfigUuid)).thenReturn(Boolean.FALSE); - Optional result = processConfigService.deleteProcessConfig(processConfigUuid); - - assertThat(result).isEmpty(); + assertThatThrownBy(() -> processConfigService.deleteProcessConfig(processConfigUuid)) + .isInstanceOf(MonitorServerException.class) + .satisfies(ex -> assertThat(((MonitorServerException) ex).getErrorCode()).isEqualTo(PROCESS_CONFIG_NOT_FOUND)); verify(processConfigRepository).existsById(processConfigUuid); verify(processConfigRepository, never()).deleteById(any()); } @@ -267,11 +261,9 @@ void compareProcessConfigsWithEqualProcessConfigs() { when(handler.toDto(processConfigEntity)).thenReturn(processConfig); when(processConfig.compareWith(processConfig)).thenReturn(List.of(fieldComparison)); - Optional result = processConfigService.compareProcessConfigs(processConfigUuid1, processConfigUuid2); + ProcessConfigComparison result = processConfigService.compareProcessConfigs(processConfigUuid1, processConfigUuid2); - assertThat(result) - .isPresent() - .contains(new ProcessConfigComparison(processConfigUuid1, processConfigUuid2, true, List.of(fieldComparison))); + assertThat(result).isEqualTo(new ProcessConfigComparison(processConfigUuid1, processConfigUuid2, true, List.of(fieldComparison))); verify(processConfigRepository).findById(processConfigUuid1); verify(processConfigRepository).findById(processConfigUuid2); verify(handler, times(2)).toDto(processConfigEntity); @@ -296,11 +288,9 @@ void compareProcessConfigsWithDifferentProcessConfigs() { when(handler.toDto(processConfigEntity2)).thenReturn(processConfig2); when(processConfig1.compareWith(processConfig2)).thenReturn(List.of(fieldComparison)); - Optional result = processConfigService.compareProcessConfigs(processConfigUuid1, processConfigUuid2); + ProcessConfigComparison result = processConfigService.compareProcessConfigs(processConfigUuid1, processConfigUuid2); - assertThat(result) - .isPresent() - .contains(new ProcessConfigComparison(processConfigUuid1, processConfigUuid2, false, List.of(fieldComparison))); + assertThat(result).isEqualTo(new ProcessConfigComparison(processConfigUuid1, processConfigUuid2, false, List.of(fieldComparison))); verify(processConfigRepository).findById(processConfigUuid1); verify(processConfigRepository).findById(processConfigUuid2); verify(handler).toDto(processConfigEntity1); @@ -316,9 +306,9 @@ void compareProcessConfigWithFirstProcessConfigNotFound() { // test when the first process config is not found when(processConfigRepository.findById(processConfigUuid1)).thenReturn(Optional.empty()); - Optional result = processConfigService.compareProcessConfigs(processConfigUuid1, processConfigUuid2); - - assertThat(result).isEmpty(); + assertThatThrownBy(() -> processConfigService.compareProcessConfigs(processConfigUuid1, processConfigUuid2)) + .isInstanceOf(MonitorServerException.class) + .satisfies(ex -> assertThat(((MonitorServerException) ex).getErrorCode()).isEqualTo(PROCESS_CONFIG_NOT_FOUND)); verify(processConfigRepository).findById(processConfigUuid1); verify(handler, never()).toDto(any()); } @@ -334,9 +324,9 @@ void compareProcessConfigWithSecondProcessConfigNotFound() { when(processConfigRepository.findById(processConfigUuid1)).thenReturn(Optional.of(processConfigEntity1)); when(processConfigRepository.findById(processConfigUuid2)).thenReturn(Optional.empty()); - Optional result = processConfigService.compareProcessConfigs(processConfigUuid1, processConfigUuid2); - - assertThat(result).isEmpty(); + assertThatThrownBy(() -> processConfigService.compareProcessConfigs(processConfigUuid1, processConfigUuid2)) + .isInstanceOf(MonitorServerException.class) + .satisfies(ex -> assertThat(((MonitorServerException) ex).getErrorCode()).isEqualTo(PROCESS_CONFIG_NOT_FOUND)); verify(processConfigRepository).findById(processConfigUuid1); verify(processConfigRepository).findById(processConfigUuid2); verify(handler, never()).toDto(any()); diff --git a/monitor-server/src/test/java/org/gridsuite/monitor/server/services/processexecution/ProcessExecutionServiceTest.java b/monitor-server/src/test/java/org/gridsuite/monitor/server/services/processexecution/ProcessExecutionServiceTest.java index 4e19ba31..4fae4ad7 100644 --- a/monitor-server/src/test/java/org/gridsuite/monitor/server/services/processexecution/ProcessExecutionServiceTest.java +++ b/monitor-server/src/test/java/org/gridsuite/monitor/server/services/processexecution/ProcessExecutionServiceTest.java @@ -20,6 +20,7 @@ import org.gridsuite.monitor.server.dto.report.ReportLog; import org.gridsuite.monitor.server.dto.report.ReportPage; import org.gridsuite.monitor.server.dto.report.Severity; +import org.gridsuite.monitor.server.error.MonitorServerException; import org.gridsuite.monitor.server.messaging.NotificationService; import org.gridsuite.monitor.server.services.result.ResultService; import org.junit.jupiter.api.BeforeEach; @@ -32,10 +33,11 @@ import java.io.IOException; import java.time.Instant; import java.util.List; -import java.util.Optional; import java.util.UUID; -import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.*; +import static org.gridsuite.monitor.server.error.MonitorServerBusinessErrorCode.DEBUG_INFOS_NOT_FOUND; +import static org.gridsuite.monitor.server.error.MonitorServerBusinessErrorCode.PROCESS_EXECUTION_NOT_FOUND; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.*; @@ -87,22 +89,22 @@ void setUp() { void executeProcessCreateExecutionAndSendNotifications() { String debugFileLocation = "debug/file/location"; - doReturn(Optional.of(new ProcessCreationResult(debugFileLocation, securityAnalysisConfig))) + doReturn(new ProcessCreationResult(debugFileLocation, securityAnalysisConfig)) .when(processExecutionTxService).createExecution(eq(caseUuid), eq(userId), any(UUID.class), any(UUID.class), any(UUID.class), anyBoolean()); - Optional result = processExecutionService.executeProcess(caseUuid, userId, UUID.randomUUID(), true); + UUID result = processExecutionService.executeProcess(caseUuid, userId, UUID.randomUUID(), true); - assertThat(result).isNotEmpty(); + assertThat(result).isNotNull(); verify(notificationService).sendProcessRunMessage( eq(caseUuid), eq(securityAnalysisConfig), - eq(result.get()), + eq(result), any(UUID.class), eq(debugFileLocation) ); verify(notificationService).sendProcessUpdatedMessage( ProcessType.SECURITY_ANALYSIS, - result.get() + result ); } @@ -158,7 +160,7 @@ void updateStepsStatusesShouldDelegateToTxService() { @Test void getReportsShouldReturnReports() { - when(processExecutionTxService.getReportId(executionId)).thenReturn(Optional.of(reportId)); + when(processExecutionTxService.getReportId(executionId)).thenReturn(reportId); ReportLog reportLog1 = new ReportLog("message1", Severity.INFO, 1, UUID.randomUUID()); ReportLog reportLog2 = new ReportLog("message2", Severity.WARN, 2, UUID.randomUUID()); @@ -167,8 +169,8 @@ void getReportsShouldReturnReports() { when(reportRestClient.getReport(reportId)).thenReturn(reportPage); - Optional result = processExecutionService.getReports(executionId); - assertThat(result).contains(reportPage); + ReportPage result = processExecutionService.getReports(executionId); + assertThat(result).isEqualTo(reportPage); verify(processExecutionTxService).getReportId(executionId); verify(reportRestClient).getReport(reportId); @@ -185,12 +187,11 @@ void getResultsShouldReturnResults() { .thenReturn(result1); when(resultService.getResult(resultInfos.get(1))) .thenReturn(result2); - when(processExecutionTxService.getResultInfos(executionId)).thenReturn(Optional.of(resultInfos)); + when(processExecutionTxService.getResultInfos(executionId)).thenReturn(resultInfos); - Optional> results = processExecutionService.getResults(executionId); + List results = processExecutionService.getResults(executionId); - assertThat(results).isPresent(); - assertThat(results.get()).hasSize(2).containsExactly(result1, result2); + assertThat(results).hasSize(2).containsExactly(result1, result2); verify(processExecutionTxService).getResultInfos(executionId); verify(resultService, times(2)).getResult(any(ResultInfos.class)); } @@ -200,13 +201,12 @@ void deleteExecutionShouldDeleteResultsAndReports() { UUID resultId1 = UUID.randomUUID(); UUID resultId2 = UUID.randomUUID(); when(processExecutionTxService.deleteExecution(executionId)) - .thenReturn(Optional.of(new ProcessDeletionInfos(reportId, List.of(new ResultInfos(resultId1, ResultType.SECURITY_ANALYSIS), new ResultInfos(resultId2, ResultType.SECURITY_ANALYSIS))))); + .thenReturn(new ProcessDeletionInfos(reportId, List.of(new ResultInfos(resultId1, ResultType.SECURITY_ANALYSIS), new ResultInfos(resultId2, ResultType.SECURITY_ANALYSIS)))); doNothing().when(reportRestClient).deleteReport(reportId); doNothing().when(resultService).deleteResult(any(ResultInfos.class)); - Optional deletedExecutionId = processExecutionService.deleteExecution(executionId); - assertThat(deletedExecutionId).contains(executionId); + processExecutionService.deleteExecution(executionId); verify(reportRestClient).deleteReport(reportId); verify(resultService, times(2)).deleteResult(any(ResultInfos.class)); @@ -214,10 +214,12 @@ void deleteExecutionShouldDeleteResultsAndReports() { @Test void deleteExecutionShouldReturnFalseWhenExecutionNotFound() { - when(processExecutionTxService.deleteExecution(executionId)).thenReturn(Optional.empty()); + when(processExecutionTxService.deleteExecution(executionId)) + .thenThrow(new MonitorServerException(PROCESS_EXECUTION_NOT_FOUND, "Process execution not found")); - Optional deletedExecution = processExecutionService.deleteExecution(executionId); - assertThat(deletedExecution).isNotPresent(); + assertThatThrownBy(() -> processExecutionService.deleteExecution(executionId)) + .isInstanceOf(MonitorServerException.class) + .satisfies(ex -> assertThat(((MonitorServerException) ex).getErrorCode()).isEqualTo(PROCESS_EXECUTION_NOT_FOUND)); verify(processExecutionTxService).deleteExecution(executionId); verifyNoInteractions(reportRestClient); @@ -229,13 +231,12 @@ void getExistingDebugInfo() throws Exception { String debugFileLocation = "debug/file/location"; byte[] expectedBytes = "zip-content".getBytes(); - when(processExecutionTxService.getDebugFileLocation(executionId)).thenReturn(Optional.of(debugFileLocation)); + when(processExecutionTxService.getDebugFileLocation(executionId)).thenReturn(debugFileLocation); when(s3RestClient.downloadDirectoryAsZip(debugFileLocation)).thenReturn(expectedBytes); - Optional result = processExecutionService.getDebugInfos(executionId); + byte[] result = processExecutionService.getDebugInfos(executionId); - assertThat(result).isPresent(); - assertThat(expectedBytes).isEqualTo(result.get()); + assertThat(result).isEqualTo(expectedBytes); verify(processExecutionTxService).getDebugFileLocation(executionId); verify(s3RestClient).downloadDirectoryAsZip("debug/file/location"); @@ -243,11 +244,12 @@ void getExistingDebugInfo() throws Exception { @Test void getNotExistingExecutionDebugInfo() { - when(processExecutionTxService.getDebugFileLocation(executionId)).thenReturn(Optional.empty()); - - Optional result = processExecutionService.getDebugInfos(executionId); + when(processExecutionTxService.getDebugFileLocation(executionId)) + .thenThrow(new MonitorServerException(PROCESS_EXECUTION_NOT_FOUND, "Process execution not found")); - assertThat(result).isEmpty(); + assertThatThrownBy(() -> processExecutionService.getDebugInfos(executionId)) + .isInstanceOf(MonitorServerException.class) + .satisfies(ex -> assertThat(((MonitorServerException) ex).getErrorCode()).isEqualTo(PROCESS_EXECUTION_NOT_FOUND)); verify(processExecutionTxService).getDebugFileLocation(executionId); verifyNoInteractions(s3RestClient); @@ -257,7 +259,7 @@ void getNotExistingExecutionDebugInfo() { void getExistingDebugInfoError() throws Exception { String debugFileLocation = "debug/file/location"; - when(processExecutionTxService.getDebugFileLocation(executionId)).thenReturn(Optional.of(debugFileLocation)); + when(processExecutionTxService.getDebugFileLocation(executionId)).thenReturn(debugFileLocation); when(s3RestClient.downloadDirectoryAsZip(debugFileLocation)).thenThrow(new IOException("S3 error")); @@ -307,21 +309,22 @@ void getStepsInfosShouldDelegateToTxService() { .build() ); - when(processExecutionTxService.getStepsInfos(executionId)).thenReturn(Optional.of(steps)); + when(processExecutionTxService.getStepsInfos(executionId)).thenReturn(steps); - Optional> result = processExecutionService.getStepsInfos(executionId); + List result = processExecutionService.getStepsInfos(executionId); - assertThat(result).contains(steps); + assertThat(result).isEqualTo(steps); verify(processExecutionTxService).getStepsInfos(executionId); } @Test void getExecutionWithoutDebugInfo() { - when(processExecutionTxService.getDebugFileLocation(executionId)).thenReturn(Optional.empty()); - - Optional result = processExecutionService.getDebugInfos(executionId); + when(processExecutionTxService.getDebugFileLocation(executionId)) + .thenThrow(new MonitorServerException(DEBUG_INFOS_NOT_FOUND, "Debug infos not found")); - assertThat(result).isEmpty(); + assertThatThrownBy(() -> processExecutionService.getDebugInfos(executionId)) + .isInstanceOf(MonitorServerException.class) + .satisfies(ex -> assertThat(((MonitorServerException) ex).getErrorCode()).isEqualTo(DEBUG_INFOS_NOT_FOUND)); verifyNoInteractions(s3RestClient); } diff --git a/monitor-server/src/test/java/org/gridsuite/monitor/server/services/processexecution/ProcessExecutionTxServiceTest.java b/monitor-server/src/test/java/org/gridsuite/monitor/server/services/processexecution/ProcessExecutionTxServiceTest.java index 1b78844e..c102ed13 100644 --- a/monitor-server/src/test/java/org/gridsuite/monitor/server/services/processexecution/ProcessExecutionTxServiceTest.java +++ b/monitor-server/src/test/java/org/gridsuite/monitor/server/services/processexecution/ProcessExecutionTxServiceTest.java @@ -17,6 +17,7 @@ import org.gridsuite.monitor.server.dto.processexecution.ProcessExecution; import org.gridsuite.monitor.server.entities.processexecution.ProcessExecutionEntity; import org.gridsuite.monitor.server.entities.processexecution.ProcessExecutionStepEntity; +import org.gridsuite.monitor.server.error.MonitorServerException; import org.gridsuite.monitor.server.mappers.processexecution.ProcessExecutionMapper; import org.gridsuite.monitor.server.mappers.processexecution.ProcessExecutionStepMapper; import org.gridsuite.monitor.server.repositories.ProcessExecutionRepository; @@ -35,7 +36,9 @@ import java.util.List; import java.util.Optional; import java.util.UUID; -import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.*; +import static org.gridsuite.monitor.server.error.MonitorServerBusinessErrorCode.DEBUG_INFOS_NOT_FOUND; +import static org.gridsuite.monitor.server.error.MonitorServerBusinessErrorCode.PROCESS_EXECUTION_NOT_FOUND; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; @@ -85,11 +88,11 @@ void setUp() { void executeProcessCreateExecution() { String debugFileLocation = "debug/file/location"; when(s3PathResolver.toDebugLocation(eq(ProcessType.SECURITY_ANALYSIS.name()), any(UUID.class))).thenReturn(debugFileLocation); - when(processConfigService.getProcessConfig(any(UUID.class))).thenReturn(Optional.of(new PersistedProcessConfig(UUID.randomUUID(), securityAnalysisConfig))); + when(processConfigService.getProcessConfig(any(UUID.class))).thenReturn(new PersistedProcessConfig(UUID.randomUUID(), securityAnalysisConfig)); - Optional result = processExecutionTxService.createExecution(caseUuid, userId, UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID(), true); + ProcessCreationResult result = processExecutionTxService.createExecution(caseUuid, userId, UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID(), true); - assertThat(result).isNotEmpty(); + assertThat(result).isNotNull(); verify(processConfigService).getProcessConfig(any(UUID.class)); verify(executionRepository).save(argThat(execution -> execution.getId() != null && @@ -343,8 +346,8 @@ void getReportIdShouldReturnExecutionReportId() { .build(); when(executionRepository.findById(executionId)).thenReturn(Optional.of(execution)); - Optional result = processExecutionTxService.getReportId(executionId); - assertThat(result).contains(reportId); + UUID result = processExecutionTxService.getReportId(executionId); + assertThat(result).isEqualTo(reportId); verify(executionRepository).findById(executionId); } @@ -354,9 +357,9 @@ void getReportIdShouldReturnEmptyWhenExecutionNotFound() { UUID executionUuid = UUID.randomUUID(); when(executionRepository.findById(executionUuid)).thenReturn(Optional.empty()); - Optional reports = processExecutionTxService.getReportId(executionUuid); - - assertThat(reports).isNotPresent(); + assertThatThrownBy(() -> processExecutionTxService.getReportId(executionUuid)) + .isInstanceOf(MonitorServerException.class) + .satisfies(ex -> assertThat(((MonitorServerException) ex).getErrorCode()).isEqualTo(PROCESS_EXECUTION_NOT_FOUND)); verify(executionRepository).findById(executionUuid); } @@ -383,10 +386,9 @@ void getResultInfosShouldReturnResultInfos() { .build(); when(executionRepository.findById(executionId)).thenReturn(Optional.of(execution)); - Optional> results = processExecutionTxService.getResultInfos(executionId); + List results = processExecutionTxService.getResultInfos(executionId); - assertThat(results).isPresent(); - assertThat(results.get()).usingRecursiveComparison().isEqualTo(List.of( + assertThat(results).usingRecursiveComparison().isEqualTo(List.of( new ResultInfos(resultId1, ResultType.SECURITY_ANALYSIS), new ResultInfos(resultId2, ResultType.SECURITY_ANALYSIS) )); @@ -398,9 +400,9 @@ void getResultsShouldReturnEmptyWhenExecutionNotFound() { UUID executionUuid = UUID.randomUUID(); when(executionRepository.findById(executionUuid)).thenReturn(Optional.empty()); - Optional> results = processExecutionTxService.getResultInfos(executionUuid); - - assertThat(results).isEmpty(); + assertThatThrownBy(() -> processExecutionTxService.getResultInfos(executionUuid)) + .isInstanceOf(MonitorServerException.class) + .satisfies(ex -> assertThat(((MonitorServerException) ex).getErrorCode()).isEqualTo(PROCESS_EXECUTION_NOT_FOUND)); verify(executionRepository).findById(executionUuid); } @@ -474,13 +476,12 @@ void getStepsInfos() { when(executionRepository.findById(executionUuid)).thenReturn(Optional.of(execution)); - Optional> result = processExecutionTxService.getStepsInfos(executionUuid); + List result = processExecutionTxService.getStepsInfos(executionUuid); ProcessExecutionStep processExecutionStep1 = new ProcessExecutionStep(stepId1, "loadNetwork", 0, StepStatus.RUNNING, null, null, startedAt1, null); ProcessExecutionStep processExecutionStep2 = new ProcessExecutionStep(stepId2, "applyModifs", 1, StepStatus.SCHEDULED, null, null, null, null); - assertThat(result).isPresent(); - assertThat(result.get()).hasSize(2).containsExactly(processExecutionStep1, processExecutionStep2); + assertThat(result).hasSize(2).containsExactly(processExecutionStep1, processExecutionStep2); verify(executionRepository).findById(executionUuid); } @@ -489,9 +490,9 @@ void getStepsInfosShouldReturnEmptyWhenExecutionNotFound() { UUID executionUuid = UUID.randomUUID(); when(executionRepository.findById(executionUuid)).thenReturn(Optional.empty()); - Optional> result = processExecutionTxService.getStepsInfos(executionUuid); - - assertThat(result).isEmpty(); + assertThatThrownBy(() -> processExecutionTxService.getStepsInfos(executionUuid)) + .isInstanceOf(MonitorServerException.class) + .satisfies(ex -> assertThat(((MonitorServerException) ex).getErrorCode()).isEqualTo(PROCESS_EXECUTION_NOT_FOUND)); verify(executionRepository).findById(executionUuid); } @@ -505,10 +506,9 @@ void getStepsInfosShouldReturnEmptyListWhenNoSteps() { .build(); when(executionRepository.findById(executionUuid)).thenReturn(Optional.of(execution)); - Optional> result = processExecutionTxService.getStepsInfos(executionUuid); + List result = processExecutionTxService.getStepsInfos(executionUuid); - assertThat(result).isPresent(); - assertThat(result.get()).isEmpty(); + assertThat(result).isEmpty(); } @Test @@ -535,8 +535,8 @@ void deleteExecutionShouldDeleteExecutionAndReturnResultsAndReports() { when(executionRepository.findById(executionId)).thenReturn(Optional.of(execution)); doNothing().when(executionRepository).delete(execution); - Optional processDeletionInfos = processExecutionTxService.deleteExecution(executionId); - assertThat(processDeletionInfos.get()).usingRecursiveComparison() + ProcessDeletionInfos processDeletionInfos = processExecutionTxService.deleteExecution(executionId); + assertThat(processDeletionInfos).usingRecursiveComparison() .isEqualTo(new ProcessDeletionInfos(reportId, List.of(new ResultInfos(resultId2, ResultType.SECURITY_ANALYSIS)))); verify(executionRepository).findById(executionId); @@ -547,8 +547,9 @@ void deleteExecutionShouldDeleteExecutionAndReturnResultsAndReports() { void deleteExecutionShouldReturnFalseWhenExecutionNotFound() { when(executionRepository.findById(executionId)).thenReturn(Optional.empty()); - Optional deletedExecution = processExecutionTxService.deleteExecution(executionId); - assertThat(deletedExecution).isNotPresent(); + assertThatThrownBy(() -> processExecutionTxService.deleteExecution(executionId)) + .isInstanceOf(MonitorServerException.class) + .satisfies(ex -> assertThat(((MonitorServerException) ex).getErrorCode()).isEqualTo(PROCESS_EXECUTION_NOT_FOUND)); verify(executionRepository).findById(executionId); verifyNoMoreInteractions(executionRepository); @@ -562,10 +563,9 @@ void getExistingDebugInfo() { when(executionRepository.findById(executionId)).thenReturn(Optional.of(execution)); - Optional result = processExecutionTxService.getDebugFileLocation(executionId); + String result = processExecutionTxService.getDebugFileLocation(executionId); - assertThat(result).isPresent(); - assertThat(result.get()).contains(debugFileLocation); + assertThat(result).isEqualTo(debugFileLocation); verify(executionRepository).findById(executionId); } @@ -574,9 +574,9 @@ void getExistingDebugInfo() { void getNotExistingExecutionDebugInfo() { when(executionRepository.findById(executionId)).thenReturn(Optional.empty()); - Optional result = processExecutionTxService.getDebugFileLocation(executionId); - - assertThat(result).isEmpty(); + assertThatThrownBy(() -> processExecutionTxService.getDebugFileLocation(executionId)) + .isInstanceOf(MonitorServerException.class) + .satisfies(ex -> assertThat(((MonitorServerException) ex).getErrorCode()).isEqualTo(PROCESS_EXECUTION_NOT_FOUND)); verify(executionRepository).findById(executionId); } @@ -587,9 +587,9 @@ void getExecutionWithoutDebugInfo() { when(executionRepository.findById(executionId)).thenReturn(Optional.of(execution)); - Optional result = processExecutionTxService.getDebugFileLocation(executionId); - - assertThat(result).isEmpty(); + assertThatThrownBy(() -> processExecutionTxService.getDebugFileLocation(executionId)) + .isInstanceOf(MonitorServerException.class) + .satisfies(ex -> assertThat(((MonitorServerException) ex).getErrorCode()).isEqualTo(DEBUG_INFOS_NOT_FOUND)); verify(executionRepository).findById(executionId); }