Refactor Bookdrop file processing to prevent orphan target files on error
This commit is contained in:
committed by
Aditya Chandel
parent
7cea853756
commit
3ab52de171
+15
-2
@@ -274,6 +274,7 @@ public class BookDropService {
|
|||||||
return failureResult(targetFile.getName(), "File already exists in the library '" + library.getName() + "'");
|
return failureResult(targetFile.getName(), "File already exists in the library '" + library.getName() + "'");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
Files.createDirectories(target.getParent());
|
Files.createDirectories(target.getParent());
|
||||||
Files.move(source, target);
|
Files.move(source, target);
|
||||||
|
|
||||||
@@ -282,8 +283,7 @@ public class BookDropService {
|
|||||||
Book processedBook = processFile(targetFile.getName(), library, path, targetFile,
|
Book processedBook = processFile(targetFile.getName(), library, path, targetFile,
|
||||||
BookFileExtension.fromFileName(bookdropFile.getFileName())
|
BookFileExtension.fromFileName(bookdropFile.getFileName())
|
||||||
.orElseThrow(() -> ApiError.INVALID_FILE_FORMAT.createException("Unsupported file extension"))
|
.orElseThrow(() -> ApiError.INVALID_FILE_FORMAT.createException("Unsupported file extension"))
|
||||||
.getType()
|
.getType());
|
||||||
);
|
|
||||||
|
|
||||||
BookEntity bookEntity = bookRepository.findById(processedBook.getId())
|
BookEntity bookEntity = bookRepository.findById(processedBook.getId())
|
||||||
.orElseThrow(() -> ApiError.FILE_NOT_FOUND.createException("Book ID missing after import"));
|
.orElseThrow(() -> ApiError.FILE_NOT_FOUND.createException("Book ID missing after import"));
|
||||||
@@ -306,6 +306,19 @@ public class BookDropService {
|
|||||||
.message("File successfully imported into the '" + library.getName() + "' library from the Bookdrop folder")
|
.message("File successfully imported into the '" + library.getName() + "' library from the Bookdrop folder")
|
||||||
.success(true)
|
.success(true)
|
||||||
.build();
|
.build();
|
||||||
|
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("Failed to move file id={}, name={} from '{}' to '{}': {}", bookdropFile.getId(), bookdropFile.getFileName(), source, target, e.getMessage(), e);
|
||||||
|
try {
|
||||||
|
if (Files.exists(target)) {
|
||||||
|
Files.deleteIfExists(target);
|
||||||
|
log.info("Cleaned up partially created target file: {}", target);
|
||||||
|
}
|
||||||
|
} catch (Exception cleanupException) {
|
||||||
|
log.warn("Failed to cleanup target file after move error: {}", target, cleanupException);
|
||||||
|
}
|
||||||
|
return failureResult(bookdropFile.getFileName(), "Failed to move file: " + e.getMessage());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private BookdropFileResult failureResult(String fileName, String message) {
|
private BookdropFileResult failureResult(String fileName, String message) {
|
||||||
|
|||||||
Reference in New Issue
Block a user