|
| 1 | +package ee.cyber.cdoc2.util; |
| 2 | + |
| 3 | +import java.io.File; |
| 4 | +import java.nio.file.Path; |
| 5 | +import java.util.ArrayList; |
| 6 | +import java.util.List; |
| 7 | + |
| 8 | + |
| 9 | +/** |
| 10 | + * Utility class containing methods used for logging |
| 11 | + */ |
| 12 | +public final class LoggingUtil { |
| 13 | + private LoggingUtil() { |
| 14 | + // utility class |
| 15 | + } |
| 16 | + |
| 17 | + /** |
| 18 | + * Censors the file name for logs. E.g. "hello.txt" would be "xxxxx.txt". |
| 19 | + * |
| 20 | + * @param fileName filename |
| 21 | + * @return The censored filename |
| 22 | + */ |
| 23 | + public static String censorFileName(String fileName) { |
| 24 | + if (fileName == null || fileName.isEmpty()) { |
| 25 | + return fileName; |
| 26 | + } |
| 27 | + |
| 28 | + int lastDotIndex = fileName.lastIndexOf('.'); |
| 29 | + |
| 30 | + // No extension or dot is the first character (e.g. ".gitignore") |
| 31 | + if (lastDotIndex <= 0) { |
| 32 | + return "X".repeat(fileName.length()); |
| 33 | + } |
| 34 | + |
| 35 | + String namePart = fileName.substring(0, lastDotIndex); |
| 36 | + String extensionPart = fileName.substring(lastDotIndex); |
| 37 | + |
| 38 | + return "X".repeat(namePart.length()) + extensionPart; |
| 39 | + } |
| 40 | + |
| 41 | + /** |
| 42 | + * Censors the file path for logs. E.g. "abc/aaa/hello.txt" would be "abc/aaa/xxxxx.txt". |
| 43 | + * |
| 44 | + * @param path file path |
| 45 | + * @return censored file path as string |
| 46 | + */ |
| 47 | + public static String censorPathFileName(Path path) { |
| 48 | + if (path == null) { |
| 49 | + return null; |
| 50 | + } |
| 51 | + |
| 52 | + Path fileName = path.getFileName(); |
| 53 | + if (fileName == null) { |
| 54 | + return path.toString(); |
| 55 | + } |
| 56 | + |
| 57 | + String censoredFileName = censorFileName(fileName.toString()); |
| 58 | + |
| 59 | + Path parent = path.getParent(); |
| 60 | + if (parent == null) { |
| 61 | + return censoredFileName; |
| 62 | + } |
| 63 | + |
| 64 | + return parent.resolve(censoredFileName).toString(); |
| 65 | + } |
| 66 | + |
| 67 | + public static List<String> censorFileNames(File[] files) { |
| 68 | + if (files == null) { |
| 69 | + return null; |
| 70 | + } |
| 71 | + |
| 72 | + List<String> result = new ArrayList<>(files.length); |
| 73 | + |
| 74 | + for (File file : files) { |
| 75 | + if (file == null) { |
| 76 | + result.add(null); |
| 77 | + continue; |
| 78 | + } |
| 79 | + |
| 80 | + String censoredName = censorFileName(file.getName()); |
| 81 | + result.add(censoredName); |
| 82 | + } |
| 83 | + |
| 84 | + return result; |
| 85 | + } |
| 86 | +} |
0 commit comments