]> gerrit.simantics Code Review - simantics/platform.git/blobdiff - bundles/org.simantics.lz4/src/net/jpountz/util/ChecksumUtil.java
Fixed org.simantics.lz4 to use bundle data area when running in OSGi
[simantics/platform.git] / bundles / org.simantics.lz4 / src / net / jpountz / util / ChecksumUtil.java
diff --git a/bundles/org.simantics.lz4/src/net/jpountz/util/ChecksumUtil.java b/bundles/org.simantics.lz4/src/net/jpountz/util/ChecksumUtil.java
new file mode 100644 (file)
index 0000000..c047f21
--- /dev/null
@@ -0,0 +1,49 @@
+package net.jpountz.util;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.URL;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+
+/**
+ * @author Tuukka Lehtonen
+ */
+public final class ChecksumUtil {
+
+    private static byte[] computeSum(InputStream in) throws IOException {
+        if (in == null)
+            throw new IllegalArgumentException("Input cannot be null!");
+
+        MessageDigest md;
+        try {
+            md = MessageDigest.getInstance("MD5");
+        } catch (NoSuchAlgorithmException e) {
+            throw new Error("MD5 digest must be supported by JVM");
+        }
+        byte[] data = new byte[64 * 1024];
+
+        while (true) {
+            int read = in.read(data);
+            if (read == -1) {
+                return md.digest();
+            }
+            md.update(data, 0, read);
+        }
+    }
+
+    public static byte[] computeSum(Path p) throws IOException {
+        try (InputStream in = Files.newInputStream(p)) {
+            return computeSum(in);
+        }
+    }
+
+    public static byte[] computeSum(URL url) throws IOException {
+        try (InputStream in = url.openStream()) {
+            return computeSum(in);
+        }
+    }
+
+}