Remove commons-codec as dep for MD hashing

This commit is contained in:
Frank van der Heijden 2021-02-22 15:56:39 +01:00
parent b51ff445dd
commit 5226866a74
No known key found for this signature in database
GPG key ID: 26DA56488D314D11
4 changed files with 29 additions and 10 deletions

View file

@ -70,7 +70,7 @@ public class PluginWatcherTask extends AbstractTask {
for (WatchEvent<?> event : key.pollEvents()) {
if (file.getName().equals(event.context().toString())) {
String previousHash = hash;
hash = FileUtils.getHash(file);
hash = FileUtils.getHash(file.toPath());
if (task != null) {
//noinspection unchecked
taskManager.cancelTask(task);

View file

@ -2,15 +2,16 @@ package net.frankheijden.serverutils.common.utils;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import org.apache.commons.codec.digest.DigestUtils;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class FileUtils {
@ -36,17 +37,18 @@ public class FileUtils {
}
/**
* Get the Hash of a file.
* Get the Hash of a file at given path.
*
* @param file The file
* @param path The path
* @return The file's hash
*/
public static String getHash(File file) {
public static String getHash(Path path) {
byte[] digest;
try {
return DigestUtils.md5Hex(new FileInputStream(file));
} catch (IOException e) {
// Shouldn't happen
digest = MessageDigest.getInstance("MD5").digest(Files.readAllBytes(path));
} catch (IOException | NoSuchAlgorithmException ex) {
return null;
}
return StringUtils.bytesToHex(digest);
}
}

View file

@ -1,5 +1,7 @@
package net.frankheijden.serverutils.common.utils;
import java.nio.charset.StandardCharsets;
public class StringUtils {
/**
@ -44,4 +46,20 @@ public class StringUtils {
}
return sb.substring(1);
}
private static final byte[] HEX_ARRAY = "0123456789abcdef".getBytes(StandardCharsets.US_ASCII);
/**
* Converts a bytes array to hex.
* via https://stackoverflow.com/a/9855338/11239174
*/
public static String bytesToHex(byte[] bytes) {
byte[] hexChars = new byte[bytes.length * 2];
for (int j = 0; j < bytes.length; j++) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = HEX_ARRAY[v >>> 4];
hexChars[j * 2 + 1] = HEX_ARRAY[v & 0x0F];
}
return new String(hexChars, StandardCharsets.UTF_8);
}
}