Fix: Normalize paths for relative sub-path calculation (#1501)

Fixes a bug preventing import of books with duplicate filenames in
different sub-folders.

The path relativization in FileUtils.getRelativeSubPath would fail in
some cases, yielding an empty sub-path. This caused a database
unique index violation as only the filename was saved as the filePath.

This commit fixes the issue by normalizing both paths before
relativization. Adds FileUtilsTest.java to validate the fix.

Fixes #1499
This commit is contained in:
Subhashini Ganesh
2025-11-20 21:08:39 -07:00
committed by GitHub
parent db9bc40960
commit cb8f5e7a29
2 changed files with 76 additions and 5 deletions
@@ -27,11 +27,21 @@ public class FileUtils {
}
public static String getRelativeSubPath(String basePath, Path fullFilePath) {
return Optional.ofNullable(Path.of(basePath)
.relativize(fullFilePath)
.getParent())
.map(path -> path.toString().replace("\\", "/"))
.orElse("");
try {
// Add .normalize() to both paths for robust comparison
Path normalizedBasePath = Path.of(basePath).normalize();
Path normalizedFullPath = fullFilePath.normalize();
return Optional.ofNullable(normalizedBasePath
.relativize(normalizedFullPath)
.getParent())
.map(path -> path.toString().replace("\\", "/"))
.orElse("");
} catch (Exception e) {
log.error("Failed to get relative sub-path for basePath '{}' and fullFilePath '{}': {}",
basePath, fullFilePath, e.getMessage(), e);
return ""; // Fallback to empty string on any error
}
}
public static Long getFileSizeInKb(BookEntity bookEntity) {