From 70c747a8635a672eaca34ce5642eb15895a207d4 Mon Sep 17 00:00:00 2001 From: Laurent Clouet Date: Tue, 29 Aug 2023 01:40:44 +0200 Subject: [PATCH] Fix: if a file has been modified them its md5 is not the same anymore --- src/main/java/com/sheepit/client/Md5.java | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/src/main/java/com/sheepit/client/Md5.java b/src/main/java/com/sheepit/client/Md5.java index 94d919c..ee731da 100644 --- a/src/main/java/com/sheepit/client/Md5.java +++ b/src/main/java/com/sheepit/client/Md5.java @@ -19,6 +19,7 @@ package com.sheepit.client; +import java.io.File; import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; @@ -32,17 +33,18 @@ import java.util.Map; public class Md5 { private static Map cache = new HashMap<>(); - // TODO: check if the file has changed (cache the time of modification) // TODO: to avoid memory increase, check if files are deleted public String get(String path) { - if (cache.containsKey(path) == false) { + String key = getUniqueKey(path); + if (cache.containsKey(key) == false) { generate(path); } - return cache.get(path); + return cache.get(key); } - public void generate(String path) { + private void generate(String path) { + String key = getUniqueKey(path); try { MessageDigest md = MessageDigest.getInstance("MD5"); InputStream is = Files.newInputStream(Paths.get(path)); @@ -53,10 +55,15 @@ public class Md5 { String data = Utils.convertBinaryToHex(md.digest()); dis.close(); is.close(); - cache.put(path, data); + cache.put(key, data); } catch (NoSuchAlgorithmException | IOException e) { - cache.put(path, ""); + cache.put(key, ""); } } + + private String getUniqueKey(String path) { + File file = new File(path); + return Long.toString(file.lastModified()) + '_' + path; + } }