Merge branch 'fix/cache-md5' into 'master'

Fix: if a file has been modified them its md5 is not the same anymore

See merge request sheepitrenderfarm/client!229
This commit is contained in:
Sheepit Renderfarm
2023-08-29 10:34:50 +00:00

View File

@@ -19,6 +19,7 @@
package com.sheepit.client; package com.sheepit.client;
import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.nio.file.Files; import java.nio.file.Files;
@@ -32,17 +33,18 @@ import java.util.Map;
public class Md5 { public class Md5 {
private static Map<String, String> cache = new HashMap<>(); private static Map<String, String> 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 // TODO: to avoid memory increase, check if files are deleted
public String get(String path) { public String get(String path) {
if (cache.containsKey(path) == false) { String key = getUniqueKey(path);
if (cache.containsKey(key) == false) {
generate(path); 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 { try {
MessageDigest md = MessageDigest.getInstance("MD5"); MessageDigest md = MessageDigest.getInstance("MD5");
InputStream is = Files.newInputStream(Paths.get(path)); InputStream is = Files.newInputStream(Paths.get(path));
@@ -53,10 +55,15 @@ public class Md5 {
String data = Utils.convertBinaryToHex(md.digest()); String data = Utils.convertBinaryToHex(md.digest());
dis.close(); dis.close();
is.close(); is.close();
cache.put(path, data); cache.put(key, data);
} }
catch (NoSuchAlgorithmException | IOException e) { 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;
}
} }