/* * Copyright (C) 2023 Laurent CLOUET * Author Laurent CLOUET * * 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; 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 cache = new HashMap<>(); // TODO: to avoid memory increase, check if files are deleted public String get(String path) { String key = getUniqueKey(path); if (cache.containsKey(key) == false) { generate(path); } return cache.get(key); } private void generate(String path) { String key = getUniqueKey(path); try { MessageDigest md = MessageDigest.getInstance("MD5"); InputStream is = Files.newInputStream(Paths.get(path)); DigestInputStream dis = new DigestInputStream(is, md); byte[] buffer = new byte[8192]; while (dis.read(buffer) > 0) { // process the entire file } String data = Utils.convertBinaryToHex(md.digest()); dis.close(); is.close(); cache.put(key, data); } catch (NoSuchAlgorithmException | IOException e) { cache.put(key, ""); } } private String getUniqueKey(String path) { File file = new File(path); return Long.toString(file.lastModified()) + '_' + path; } }