diff --git a/src/main/java/com/kri/contact/server/common/external/contactsurvey/ContactSurveyApiClient.java b/src/main/java/com/kri/contact/server/common/external/contactsurvey/ContactSurveyApiClient.java index 91a07da..0776db5 100644 --- a/src/main/java/com/kri/contact/server/common/external/contactsurvey/ContactSurveyApiClient.java +++ b/src/main/java/com/kri/contact/server/common/external/contactsurvey/ContactSurveyApiClient.java @@ -117,7 +117,7 @@ public class ContactSurveyApiClient { } } - throw new IllegalStateException("Unsupported contact survey target profile"); + throw BusinessException.internalError("UNSUPPORTED_CONTACT_SURVEY_PROFILE", "Unsupported contact survey target profile"); } private Map headers() { diff --git a/src/main/java/com/kri/contact/server/persistence/jdbc/ListAssignJdbcSupport.java b/src/main/java/com/kri/contact/server/persistence/jdbc/ListAssignJdbcSupport.java index 8a1689e..d51c0d0 100644 --- a/src/main/java/com/kri/contact/server/persistence/jdbc/ListAssignJdbcSupport.java +++ b/src/main/java/com/kri/contact/server/persistence/jdbc/ListAssignJdbcSupport.java @@ -1,5 +1,6 @@ package com.kri.contact.server.persistence.jdbc; +import com.kri.common.feature.web.BusinessException; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.Timestamp; @@ -150,7 +151,7 @@ public class ListAssignJdbcSupport { return List.of(); } if (chunkSize <= 0) { - throw new IllegalArgumentException("chunkSize must be greater than 0"); + throw BusinessException.internalError("INVALID_LIST_CHUNK_SIZE", "chunkSize must be greater than 0"); } List sidList = sids instanceof List list ? list : new ArrayList<>(sids); diff --git a/src/main/java/com/kri/contact/server/persistence/jdbc/ListResetJdbcSupport.java b/src/main/java/com/kri/contact/server/persistence/jdbc/ListResetJdbcSupport.java index 14c9ec2..14c3a5a 100644 --- a/src/main/java/com/kri/contact/server/persistence/jdbc/ListResetJdbcSupport.java +++ b/src/main/java/com/kri/contact/server/persistence/jdbc/ListResetJdbcSupport.java @@ -1,5 +1,6 @@ package com.kri.contact.server.persistence.jdbc; +import com.kri.common.feature.web.BusinessException; import jakarta.persistence.EntityManager; import jakarta.persistence.Query; import java.util.ArrayList; @@ -123,7 +124,7 @@ public class ListResetJdbcSupport { return List.of(); } if (chunkSize <= 0) { - throw new IllegalArgumentException("chunkSize must be greater than 0"); + throw BusinessException.internalError("INVALID_LIST_CHUNK_SIZE", "chunkSize must be greater than 0"); } List sidList = new ArrayList<>(sids); diff --git a/src/main/java/com/kri/contact/server/persistence/support/ListResetPersistenceSupport.java b/src/main/java/com/kri/contact/server/persistence/support/ListResetPersistenceSupport.java index 64f99d3..d365d4d 100644 --- a/src/main/java/com/kri/contact/server/persistence/support/ListResetPersistenceSupport.java +++ b/src/main/java/com/kri/contact/server/persistence/support/ListResetPersistenceSupport.java @@ -62,7 +62,7 @@ public class ListResetPersistenceSupport { TListResetLogEntity log = listResetLogRepository.findById(listResetLogId) .orElseThrow(() -> BusinessException.internalError("List reset log not found.")); if (!java.util.Objects.equals(log.getPrjctIdx(), prjctIdx) || !java.util.Objects.equals(log.getMode(), mode.getCode())) { - throw new IllegalArgumentException("Reset log does not match project and mode"); + throw BusinessException.internalError("RESET_LOG_PROJECT_OR_MODE_MISMATCH", "Reset log does not match project and mode"); } log.setListCnt(accumulate ? Math.addExact(log.getListCnt(), resetCount) : resetCount); listResetLogRepository.saveAndFlush(log); diff --git a/src/main/java/com/kri/contact/server/service/ListUpdateService.java b/src/main/java/com/kri/contact/server/service/ListUpdateService.java index 2b6179f..186ce60 100644 --- a/src/main/java/com/kri/contact/server/service/ListUpdateService.java +++ b/src/main/java/com/kri/contact/server/service/ListUpdateService.java @@ -238,7 +238,7 @@ public class ListUpdateService { private void lockSurveyHistoryUntilTransactionCompletion(ListEventHistFromSurveyDto request) { if (!TransactionSynchronizationManager.isSynchronizationActive()) { - throw new IllegalStateException("설문 이력 처리는 활성 트랜잭션 동기화가 필요합니다."); + throw BusinessException.internalError("SURVEY_HISTORY_TRANSACTION_REQUIRED", "설문 이력 처리는 활성 트랜잭션 동기화가 필요합니다."); } SurveyHistoryKey key = new SurveyHistoryKey(request.getPrjctSurveyIdx(), request.getSid()); @@ -254,13 +254,15 @@ public class ListUpdateService { long timeoutSeconds = listEventHistoryProperties.getSurveyLockWaitTimeoutSeconds(); if (!lock.semaphore.tryAcquire(timeoutSeconds, TimeUnit.SECONDS)) { releaseSurveyHistoryLockReference(key, lock); - throw new IllegalStateException("설문 이력 잠금 대기 시간이 " + timeoutSeconds + "초를 초과했습니다."); + throw BusinessException.conflict("SURVEY_HISTORY_LOCK_TIMEOUT", "설문 이력 잠금 대기 시간이 " + timeoutSeconds + "초를 초과했습니다."); } } catch (InterruptedException e) { // 허가를 얻지 못했으므로 semaphore.release() 없이 참조만 정리한다. releaseSurveyHistoryLockReference(key, lock); Thread.currentThread().interrupt(); - throw new IllegalStateException("설문 이력 잠금 대기 중 요청이 중단되었습니다.", e); + var failure = BusinessException.internalError("SURVEY_HISTORY_LOCK_INTERRUPTED", "설문 이력 잠금 대기 중 요청이 중단되었습니다."); + failure.addSuppressed(e); + throw failure; } try { @@ -284,7 +286,7 @@ public class ListUpdateService { // 대기자와 보유자가 모두 사라진 키만 제거해 잠금 맵이 계속 커지지 않게 한다. surveyHistoryLocks.compute(key, (ignored, current) -> { if (current != lock) { - throw new IllegalStateException("설문 이력 잠금 참조가 예상과 다르게 변경되었습니다."); + throw BusinessException.internalError("SURVEY_HISTORY_LOCK_REFERENCE_CHANGED", "설문 이력 잠금 참조가 예상과 다르게 변경되었습니다."); } return --current.users == 0 ? null : current; }); diff --git a/src/main/java/com/kri/contact/server/service/ListUploadService.java b/src/main/java/com/kri/contact/server/service/ListUploadService.java index 2711cc0..dc6ac76 100644 --- a/src/main/java/com/kri/contact/server/service/ListUploadService.java +++ b/src/main/java/com/kri/contact/server/service/ListUploadService.java @@ -580,7 +580,7 @@ public class ListUploadService { public PreparedUpload prepareAsync(Long projectId, Path source, ListUploadRequestDto request, String logId, Runnable checkCancelled) { if (request.getUploadMode() == null) { - throw new IllegalArgumentException("Upload mode is required"); + throw BusinessException.badRequest("ASYNC_UPLOAD_MODE_REQUIRED", "Upload mode is required"); } try { checkCancelled.run(); @@ -604,9 +604,10 @@ public class ListUploadService { assignService.findAllowedUserRolesByAssignRole(new LinkedHashSet<>(roles.values())), companies, logId, checkCancelled, request.getUploadMode() != ListUploadMode.RESET_AND_INSERT); checkCancelled.run(); - var log = listUploadLogRepository.findById(logId).orElseThrow(); + var log = listUploadLogRepository.findById(logId).orElseThrow(() -> + BusinessException.internalError("LIST_UPLOAD_LOG_NOT_FOUND", "업로드 로그를 찾을 수 없습니다.")); if (!Objects.equals(log.getPrjctIdx(), projectId)) { - throw new IllegalArgumentException("Upload log project mismatch"); + throw BusinessException.internalError("UPLOAD_LOG_PROJECT_MISMATCH", "Upload log project mismatch"); } markValidated(log, validation.totalCount()); return new PreparedUpload(validation.totalCount(), Set.copyOf(validation.uploadedSids()), @@ -652,9 +653,10 @@ public class ListUploadService { createAsyncHeaders(projectId, prepared, user, time); } listContentItemService.refreshListContentItem(projectId, prepared.headers()); - var log = listUploadLogRepository.findById(logId).orElseThrow(); + var log = listUploadLogRepository.findById(logId).orElseThrow(() -> + BusinessException.internalError("LIST_UPLOAD_LOG_NOT_FOUND", "업로드 로그를 찾을 수 없습니다.")); if (!Objects.equals(log.getPrjctIdx(), projectId)) { - throw new IllegalArgumentException("Upload log project mismatch"); + throw BusinessException.internalError("UPLOAD_LOG_PROJECT_MISMATCH", "Upload log project mismatch"); } markSuccess(log, prepared.totalCount()); } diff --git a/src/main/java/com/kri/contact/server/service/async/ListAsyncDownloadService.java b/src/main/java/com/kri/contact/server/service/async/ListAsyncDownloadService.java index 3816dd3..7510777 100644 --- a/src/main/java/com/kri/contact/server/service/async/ListAsyncDownloadService.java +++ b/src/main/java/com/kri/contact/server/service/async/ListAsyncDownloadService.java @@ -83,7 +83,7 @@ public class ListAsyncDownloadService { case CONTACT_HISTORY_DOWNLOAD -> " 컨택 이력.xlsx"; case UPDATE_HISTORY_DOWNLOAD -> " 수정 이력.xlsx"; case ITEM_ZIP_DOWNLOAD -> " item_files.zip"; - default -> throw new IllegalArgumentException("Unsupported download type"); + default -> throw BusinessException.internalError("UNSUPPORTED_LIST_DOWNLOAD_TYPE", "Unsupported download type"); }; String key = executor.submit(projectId, user.getUserId(), type, snapshot, null, context -> generate(projectId, type, savedFilter, includeResult, savedEvent, name, user, context)); @@ -118,7 +118,7 @@ public class ListAsyncDownloadService { event.getHistoryOrder(), includeResult, checked, observer); case UPDATE_HISTORY_DOWNLOAD -> downloads.writeSidWithUpdateHist(projectId, filter, checked, observer); case ITEM_ZIP_DOWNLOAD -> downloads.writeItemFile(projectId, filter, checked, observer); - default -> throw new IllegalArgumentException("Unsupported download type"); + default -> throw BusinessException.internalError("UNSUPPORTED_LIST_DOWNLOAD_TYPE", "Unsupported download type"); } context.checkCancelled(); }); diff --git a/src/main/java/com/kri/contact/server/service/async/ListAsyncJobExecutor.java b/src/main/java/com/kri/contact/server/service/async/ListAsyncJobExecutor.java index 4e77641..17753cd 100644 --- a/src/main/java/com/kri/contact/server/service/async/ListAsyncJobExecutor.java +++ b/src/main/java/com/kri/contact/server/service/async/ListAsyncJobExecutor.java @@ -88,11 +88,11 @@ public class ListAsyncJobExecutor implements ApplicationRunner { throw BusinessException.conflict("LIST_JOBS_UNAVAILABLE", "작업 접수를 준비 중입니다."); } if (TransactionSynchronizationManager.isActualTransactionActive()) { - throw new IllegalStateException("Submit outside a business transaction"); + throw BusinessException.internalError("LIST_JOB_SUBMIT_TRANSACTION_ACTIVE", "Submit outside a business transaction"); } if (projectId == null || user == null || user.isBlank() || user.length() > 32 || type == null || request == null || work == null) { - throw new IllegalArgumentException("Invalid job submission"); + throw BusinessException.internalError("INVALID_LIST_JOB_SUBMISSION", "Invalid job submission"); } Map snapshot = mapper.convertValue(request, new TypeReference<>() {}); String key = UUID.randomUUID().toString().replace("-", ""); diff --git a/src/main/java/com/kri/contact/server/service/async/ListAsyncJobStore.java b/src/main/java/com/kri/contact/server/service/async/ListAsyncJobStore.java index cf55ef0..8617a1f 100644 --- a/src/main/java/com/kri/contact/server/service/async/ListAsyncJobStore.java +++ b/src/main/java/com/kri/contact/server/service/async/ListAsyncJobStore.java @@ -230,7 +230,7 @@ public class ListAsyncJobStore { TListAsyncJobEntity job = lock(key); requireRunning(job); if (stage == null || stage.isBlank() || stage.length() > 32 || (totalSids != null && totalSids < 0)) { - throw new IllegalArgumentException("Invalid job progress"); + throw BusinessException.internalError("INVALID_LIST_JOB_PROGRESS", "Invalid job progress"); } job.setJobStage(stage); job.setTotalSidCnt(totalSids); @@ -261,7 +261,7 @@ public class ListAsyncJobStore { if (chunkNo < 1 || operation == null || operation.isBlank() || operation.length() > 32 || sids.isEmpty() || sids.stream().anyMatch(java.util.Objects::isNull) || new HashSet<>(sids).size() != sids.size()) { - throw new IllegalArgumentException("Invalid job chunk"); + throw BusinessException.internalError("INVALID_LIST_JOB_CHUNK", "Invalid job chunk"); } checkCancelled.run(); changes.run(); @@ -269,7 +269,7 @@ public class ListAsyncJobStore { TListAsyncJobEntity job = lock(key); requireRunning(job); if (chunkNo != job.getCompletedChunkCnt() + 1) { - throw new IllegalArgumentException("Chunk number must follow the last committed chunk"); + throw BusinessException.internalError("INVALID_LIST_JOB_CHUNK_SEQUENCE", "Chunk number must follow the last committed chunk"); } TListAsyncJobChunkEntity chunk = new TListAsyncJobChunkEntity(); chunk.setId(new TListAsyncJobChunkId(key, chunkNo)); @@ -328,19 +328,19 @@ public class ListAsyncJobStore { public void messageBatch(String key, int number, Map batch) { var job = lock(key); if (job.getJobStatus() != ListAsyncJobStatus.RUNNING && job.getJobStatus() != ListAsyncJobStatus.CANCEL_REQUESTED) { - throw new IllegalStateException("Message job is not active"); + throw BusinessException.conflict("MESSAGE_JOB_NOT_ACTIVE", "Message job is not active"); } var detail = new java.util.LinkedHashMap(job.getErrorDetailJson() == null ? Map.of() : job.getErrorDetailJson()); var batches = new java.util.ArrayList>(); if (detail.get("messageBatches") instanceof List old) { for (Object entry : old) batches.add(new java.util.LinkedHashMap<>((Map) entry)); } - if (number < 1 || number > batches.size() + 1) throw new IllegalArgumentException("Invalid dispatch sequence"); + if (number < 1 || number > batches.size() + 1) throw BusinessException.internalError("INVALID_MESSAGE_DISPATCH_SEQUENCE", "Invalid dispatch sequence"); var entryValue = new java.util.LinkedHashMap(batch); entryValue.put("batchNo", number); if (number == batches.size() + 1) batches.add(Map.copyOf(entryValue)); else { - if (Boolean.TRUE.equals(batches.get(number - 1).get("completed"))) throw new IllegalStateException("Dispatch already recorded"); + if (Boolean.TRUE.equals(batches.get(number - 1).get("completed"))) throw BusinessException.conflict("MESSAGE_DISPATCH_ALREADY_RECORDED", "Dispatch already recorded"); batches.set(number - 1, Map.copyOf(entryValue)); } detail.put("messageBatches", batches); @@ -372,14 +372,14 @@ public class ListAsyncJobStore { if (chunkNo < 1 || operation == null || operation.isBlank() || operation.length() > 32 || requested.isEmpty() || requested.stream().anyMatch(java.util.Objects::isNull) || new HashSet<>(requested).size() != requested.size()) { - throw new IllegalArgumentException("Invalid fixed SID chunk"); + throw BusinessException.internalError("INVALID_LIST_JOB_FIXED_SID_CHUNK", "Invalid fixed SID chunk"); } checkCancelled.run(); TListAsyncJobEntity job = lock(key); requireRunning(job); if (!java.util.Objects.equals(projectId, job.getPrjctIdx()) || chunkNo != job.getCompletedChunkCnt() + 1) { - throw new IllegalArgumentException("Invalid project or chunk sequence"); + throw BusinessException.internalError("INVALID_LIST_JOB_PROJECT_OR_CHUNK", "Invalid project or chunk sequence"); } var existing = lists.findForUpdate(projectId, requested).stream() .map(row -> row.getId().getSid()).collect(java.util.stream.Collectors.toSet()); @@ -422,7 +422,7 @@ public class ListAsyncJobStore { throw new CancellationException(); } if (job.getJobStatus() != ListAsyncJobStatus.RUNNING) { - throw new IllegalStateException("Job is not running"); + throw BusinessException.conflict("LIST_JOB_NOT_RUNNING", "Job is not running"); } } } diff --git a/src/main/java/com/kri/contact/server/service/async/ListAsyncMaintenanceService.java b/src/main/java/com/kri/contact/server/service/async/ListAsyncMaintenanceService.java index 0491e52..3d4d343 100644 --- a/src/main/java/com/kri/contact/server/service/async/ListAsyncMaintenanceService.java +++ b/src/main/java/com/kri/contact/server/service/async/ListAsyncMaintenanceService.java @@ -153,7 +153,7 @@ public class ListAsyncMaintenanceService { access.requireProject(projectId, user); var sids = chunk.sids(); if (!prepared.sids().containsAll(sids) || sids.stream().anyMatch(sid -> !seen.add(sid))) { - throw new IllegalStateException("Validated upload SIDs changed"); + throw BusinessException.conflict("VALIDATED_UPLOAD_SIDS_CHANGED", "Validated upload SIDs changed"); } int attempt = attempted.incrementAndGet(); int chunkNo = number.get() + 1; @@ -184,7 +184,7 @@ public class ListAsyncMaintenanceService { throw failure; } if (!seen.equals(prepared.sids())) { - throw new IllegalStateException("Validated upload SID count changed"); + throw BusinessException.conflict("VALIDATED_UPLOAD_SID_COUNT_CHANGED", "Validated upload SID count changed"); } var finalProgress = new java.util.LinkedHashMap(context.job().getProgressJson() == null ? Map.of() : context.job().getProgressJson()); finalProgress.put("dataApplied", true); diff --git a/src/main/java/com/kri/contact/server/service/async/ListAsyncMessageService.java b/src/main/java/com/kri/contact/server/service/async/ListAsyncMessageService.java index 6e2d019..f7a4814 100644 --- a/src/main/java/com/kri/contact/server/service/async/ListAsyncMessageService.java +++ b/src/main/java/com/kri/contact/server/service/async/ListAsyncMessageService.java @@ -80,7 +80,7 @@ public class ListAsyncMessageService { var found = new HashSet(); for (var row : rows) { context.checkCancelled(); - if (!filter.getSidSet().contains(row.sid()) || !found.add(row.sid())) throw new IllegalStateException("Unexpected message target"); + if (!filter.getSidSet().contains(row.sid()) || !found.add(row.sid())) throw BusinessException.internalError("UNEXPECTED_MESSAGE_TARGET", "Unexpected message target"); List candidates; try { candidates = messages.prepareAsyncRow(row, request, messageContext, channel); } catch (RuntimeException failure) { @@ -141,7 +141,7 @@ public class ListAsyncMessageService { context.reject("MESSAGE_SETUP_FAILED", "발송 작업 생성에 실패하여 수신처 요청을 전달하지 못했습니다.", context.job().getErrorDetailJson()); return; } - if (bulkKey == null || bulkKey.isBlank()) throw new IllegalStateException("Missing bulk key"); + if (bulkKey == null || bulkKey.isBlank()) throw BusinessException.internalError("MISSING_MESSAGE_BULK_KEY", "Missing bulk key"); progress.put("bulkSendKey", bulkKey); context.progress("DISPATCHING", null, progress); long failed = failedSids.size(); @@ -175,7 +175,9 @@ public class ListAsyncMessageService { if (failed > 0) context.reject("MESSAGE_PARTIAL_FAILURE", "전체 대상 처리를 마쳤으며 실패 또는 접수 불명 대상이 있습니다.", context.job().getErrorDetailJson()); else context.complete(() -> {}); } catch (IOException failure) { - throw BusinessException.internalError("MESSAGE_PREPARATION_FAILED", "발송 준비 파일 처리에 실패했습니다."); + var wrapped = BusinessException.internalError("MESSAGE_PREPARATION_FAILED", "발송 준비 파일 처리에 실패했습니다."); + wrapped.addSuppressed(failure); + throw wrapped; } } diff --git a/src/main/java/com/kri/contact/server/service/file/AbstractFileService.java b/src/main/java/com/kri/contact/server/service/file/AbstractFileService.java index 58e695e..1ecb9b6 100644 --- a/src/main/java/com/kri/contact/server/service/file/AbstractFileService.java +++ b/src/main/java/com/kri/contact/server/service/file/AbstractFileService.java @@ -72,7 +72,7 @@ public abstract class AbstractFileService { Path target = normalizedDir.resolve(fileName).normalize(); if (!target.startsWith(normalizedDir)) { - throw new IllegalStateException("잘못된 파일 경로입니다."); + throw BusinessException.badRequest("WRONG_FILE_PATH", "잘못된 파일 경로입니다."); } file.transferTo(target.toFile()); @@ -106,7 +106,7 @@ public abstract class AbstractFileService { Path target = normalizedTargetDir.resolve(fileName).normalize(); if (!source.startsWith(normalizedSourceDir) || !target.startsWith(normalizedTargetDir)) { - throw new IllegalStateException("잘못된 파일 경로입니다."); + throw BusinessException.badRequest("WRONG_FILE_PATH", "잘못된 파일 경로입니다."); } if (!Files.exists(source)) { return; @@ -124,7 +124,7 @@ public abstract class AbstractFileService { Path target = normalizedDir.resolve(fileName).normalize(); if (!target.startsWith(normalizedDir)) { - throw new IllegalStateException("잘못된 파일 경로입니다."); + throw BusinessException.badRequest("WRONG_FILE_PATH", "잘못된 파일 경로입니다."); } Files.deleteIfExists(target); diff --git a/src/main/java/com/kri/contact/server/service/file/ContactScenarioFileService.java b/src/main/java/com/kri/contact/server/service/file/ContactScenarioFileService.java index dadae46..051bfb5 100644 --- a/src/main/java/com/kri/contact/server/service/file/ContactScenarioFileService.java +++ b/src/main/java/com/kri/contact/server/service/file/ContactScenarioFileService.java @@ -1,5 +1,6 @@ package com.kri.contact.server.service.file; +import com.kri.common.feature.web.BusinessException; import com.kri.common.feature.file.FileUtil; import com.kri.contact.server.config.FileStorageProperties; import java.io.IOException; @@ -62,7 +63,9 @@ public class ContactScenarioFileService extends AbstractFileService { String fileName = saveFile(getTempDir(prjctCd), file); return publicBaseUrlPrefix + "/" + prjctCd + "/Temp/" + fileName; } catch (IOException e) { - throw new RuntimeException("파일 저장 실패", e); + var failure = BusinessException.internalError("SCENARIO_FILE_SAVE_FAILED", "파일 저장 실패"); + failure.addSuppressed(e); + throw failure; } } diff --git a/src/main/java/com/kri/contact/server/service/file/ListAsyncMessageSpool.java b/src/main/java/com/kri/contact/server/service/file/ListAsyncMessageSpool.java index f8aa053..6e66445 100644 --- a/src/main/java/com/kri/contact/server/service/file/ListAsyncMessageSpool.java +++ b/src/main/java/com/kri/contact/server/service/file/ListAsyncMessageSpool.java @@ -1,5 +1,6 @@ package com.kri.contact.server.service.file; +import com.kri.common.feature.web.BusinessException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.kri.contact.server.common.external.notihub.dto.NotiHubDestInfoDto; @@ -29,12 +30,12 @@ public class ListAsyncMessageSpool { private Path root() throws IOException { Path path = Path.of(properties.getResultBaseDir()).toAbsolutePath().normalize().resolve("message-preparation"); Files.createDirectories(path); - if (!path.toRealPath().equals(path)) throw new IOException("Message preparation storage must not contain symbolic links"); + if (!path.toRealPath().equals(path)) throw BusinessException.internalError("UNSAFE_MESSAGE_PREPARATION_STORAGE", "Message preparation storage must not contain symbolic links"); return path; } public Prepared open(String jobKey) throws IOException { - if (jobKey == null || !jobKey.matches("[0-9a-f]{32}")) throw new IllegalArgumentException("Invalid job key"); + if (jobKey == null || !jobKey.matches("[0-9a-f]{32}")) throw BusinessException.internalError("INVALID_MESSAGE_PREPARATION_JOB_KEY", "Invalid job key"); Path directory = root().resolve(jobKey); Files.createDirectory(directory); return new Prepared(directory); @@ -51,7 +52,7 @@ public class ListAsyncMessageSpool { } private void cleanup(Path directory) throws IOException { - if (!directory.toRealPath().getParent().equals(root())) throw new IOException("Invalid preparation directory"); + if (!directory.toRealPath().getParent().equals(root())) throw BusinessException.internalError("INVALID_MESSAGE_PREPARATION_DIRECTORY", "Invalid preparation directory"); try (var entries = Files.newDirectoryStream(directory)) { for (Path entry : entries) { if (entry.getFileName().toString().matches("[1-9][0-9]*\\.json(?:\\.part)?") && !Files.isSymbolicLink(entry)) { @@ -71,8 +72,8 @@ public class ListAsyncMessageSpool { public int batches() { return batches; } public int targets() { return targets; } public void append(List destinations) throws IOException { - if (closed) throw new IllegalStateException("Preparation is closed"); - if (destinations.isEmpty() || destinations.size() > 1000) throw new IllegalArgumentException("Invalid message batch"); + if (closed) throw BusinessException.internalError("MESSAGE_PREPARATION_CLOSED", "Preparation is closed"); + if (destinations.isEmpty() || destinations.size() > 1000) throw BusinessException.internalError("INVALID_MESSAGE_PREPARATION_BATCH", "Invalid message batch"); int number = batches + 1; Path temporary = directory.resolve(number + ".json.part"); mapper.writeValue(temporary.toFile(), destinations.stream().map(Destination::from).toList()); @@ -81,8 +82,8 @@ public class ListAsyncMessageSpool { targets = Math.addExact(targets, destinations.size()); } public List read(int number) throws IOException { - if (closed) throw new IllegalStateException("Preparation is closed"); - if (number < 1 || number > batches) throw new IllegalArgumentException("Invalid batch number"); + if (closed) throw BusinessException.internalError("MESSAGE_PREPARATION_CLOSED", "Preparation is closed"); + if (number < 1 || number > batches) throw BusinessException.internalError("INVALID_MESSAGE_PREPARATION_BATCH_NUMBER", "Invalid batch number"); List values = mapper.readValue(directory.resolve(number + ".json").toFile(), new TypeReference<>() {}); return values.stream().map(Destination::toRequest).toList(); } diff --git a/src/main/java/com/kri/contact/server/service/file/ListAsyncResultFileService.java b/src/main/java/com/kri/contact/server/service/file/ListAsyncResultFileService.java index 1741be3..e803e3e 100644 --- a/src/main/java/com/kri/contact/server/service/file/ListAsyncResultFileService.java +++ b/src/main/java/com/kri/contact/server/service/file/ListAsyncResultFileService.java @@ -9,7 +9,6 @@ import java.nio.file.Files; import java.nio.file.LinkOption; import java.nio.file.Path; import java.nio.file.StandardCopyOption; -import java.nio.file.attribute.BasicFileAttributeView; import java.nio.file.attribute.FileTime; import java.time.Clock; import java.time.Duration; @@ -55,11 +54,11 @@ public class ListAsyncResultFileService { public ListAsyncResultFileDto create(String type, String name, FileWriter writer) throws IOException { if (type == null || type.isBlank() || name == null || name.isBlank() || name.length() > 255 || name.indexOf('\r') >= 0 || name.indexOf('\n') >= 0) { - throw new IllegalArgumentException("Invalid result file metadata"); + throw BusinessException.badRequest("INVALID_RESULT_FILE_METADATA", "결과 파일 정보가 올바르지 않습니다."); } Files.createDirectories(root); if (Files.isSymbolicLink(root) || !root.toRealPath().equals(root)) { - throw new IOException("Result storage must not contain symbolic links"); + throw BusinessException.internalError("UNSAFE_RESULT_STORAGE", "결과 파일 저장소 설정이 올바르지 않습니다."); } String ref = UUID.randomUUID().toString().replace("-", "") + ".result"; Path target = resolve(ref); @@ -71,14 +70,7 @@ public class ListAsyncResultFileService { writer.write(output); } Files.move(temporary, target, StandardCopyOption.ATOMIC_MOVE); - Instant completed = clock.instant(); - BasicFileAttributeView attributes = Files.getFileAttributeView( - target, BasicFileAttributeView.class, LinkOption.NOFOLLOW_LINKS); - attributes.setTimes(null, null, FileTime.from(completed)); - Instant recorded = attributes.readAttributes().creationTime().toInstant(); - if (Duration.between(recorded, completed).abs().compareTo(Duration.ofSeconds(2)) > 0) { - throw new IOException("Filesystem cannot record result file completion as creation time"); - } + Files.setLastModifiedTime(target, FileTime.from(clock.instant())); return new ListAsyncResultFileDto(type, ref, name, Files.size(target), true); } catch (IOException | RuntimeException failure) { try { @@ -138,7 +130,7 @@ public class ListAsyncResultFileService { return 0; } if (Files.isSymbolicLink(root) || !root.toRealPath().equals(root)) { - throw new IOException("Unsafe result storage"); + throw BusinessException.internalError("UNSAFE_RESULT_STORAGE", "결과 파일 저장소 설정이 올바르지 않습니다."); } int removed = 0; Instant cutoff = clock.instant().minus(RETENTION); @@ -154,7 +146,7 @@ public class ListAsyncResultFileService { try { if (safeRegularFile(file) && !Files.readAttributes(file, java.nio.file.attribute.BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS) - .creationTime().toInstant().isAfter(cutoff)) { + .lastModifiedTime().toInstant().isAfter(cutoff)) { Files.deleteIfExists(file); removed++; } @@ -174,7 +166,7 @@ public class ListAsyncResultFileService { return; } if (Files.isSymbolicLink(root) || !root.toRealPath().equals(root)) { - throw new IOException("Unsafe result storage"); + throw BusinessException.internalError("UNSAFE_RESULT_STORAGE", "결과 파일 저장소 설정이 올바르지 않습니다."); } try (var paths = Files.list(root)) { var iterator = paths.filter(path -> path.getFileName().toString() diff --git a/src/main/java/com/kri/contact/server/service/file/ListFileService.java b/src/main/java/com/kri/contact/server/service/file/ListFileService.java index dd87d0f..4673c10 100644 --- a/src/main/java/com/kri/contact/server/service/file/ListFileService.java +++ b/src/main/java/com/kri/contact/server/service/file/ListFileService.java @@ -79,7 +79,7 @@ public class ListFileService extends AbstractFileService { public void deleteOnRegistrationRollback(Long projectId, String fileName) { if (!TransactionSynchronizationManager.isActualTransactionActive()) { - throw new IllegalStateException("Source registration requires an active transaction"); + throw BusinessException.internalError("SOURCE_REGISTER_TRANSACTION_REQUIRED", "Source registration requires an active transaction"); } TransactionSynchronizationManager.registerSynchronization( new TransactionSynchronization() { diff --git a/src/main/java/com/kri/contact/server/service/file/ListItemFileService.java b/src/main/java/com/kri/contact/server/service/file/ListItemFileService.java index 8c31958..742e92a 100644 --- a/src/main/java/com/kri/contact/server/service/file/ListItemFileService.java +++ b/src/main/java/com/kri/contact/server/service/file/ListItemFileService.java @@ -92,7 +92,7 @@ public class ListItemFileService extends AbstractFileService { public void deleteItemFileAfterCommit(String filePath, String fileName) { if (!TransactionSynchronizationManager.isActualTransactionActive() || !TransactionSynchronizationManager.isSynchronizationActive()) { - throw new IllegalStateException("File deletion requires an active transaction"); + throw BusinessException.internalError("FILE_DELETE_TRANSACTION_REQUIRED", "File deletion requires an active transaction"); } TransactionSynchronizationManager.registerSynchronization( new TransactionSynchronization() {