Files
sheepit-shadow-nabber/src/main/java/com/sheepit/client/Md5.java

71 lines
2.1 KiB
Java
Raw Normal View History

2023-01-04 17:08:35 +01:00
/*
* Copyright (C) 2023 Laurent CLOUET
* Author Laurent CLOUET <laurent.clouet@nopnop.net>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; version 2
* of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package com.sheepit.client;
import java.io.File;
2023-01-04 17:08:35 +01:00
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
public class Md5 {
private static Map<String, String> cache = new HashMap<>();
2023-01-04 17:08:35 +01:00
// TODO: to avoid memory increase, check if files are deleted
2023-01-04 17:08:35 +01:00
public String get(String path) {
String key = getUniqueKey(path);
if (cache.containsKey(key) == false) {
2023-01-04 17:08:35 +01:00
generate(path);
}
return cache.get(key);
2023-01-04 17:08:35 +01:00
}
private void generate(String path) {
String key = getUniqueKey(path);
2023-01-04 17:08:35 +01:00
try {
MessageDigest md = MessageDigest.getInstance("MD5");
InputStream is = Files.newInputStream(Paths.get(path));
DigestInputStream dis = new DigestInputStream(is, md);
byte[] buffer = new byte[8192];
2024-06-03 14:02:30 +00:00
while (dis.read(buffer) > 0) {
// process the entire file
}
String data = Utils.convertBinaryToHex(md.digest());
2023-01-04 17:08:35 +01:00
dis.close();
is.close();
cache.put(key, data);
2023-01-04 17:08:35 +01:00
}
catch (NoSuchAlgorithmException | IOException e) {
cache.put(key, "");
2023-01-04 17:08:35 +01:00
}
}
private String getUniqueKey(String path) {
File file = new File(path);
return Long.toString(file.lastModified()) + '_' + path;
}
2023-01-04 17:08:35 +01:00
}