]> gerrit.simantics Code Review - simantics/platform.git/blobdiff - bundles/org.simantics.fastlz/testcases/org/simantics/fastlz/ChecksumUtil.java
Migrated source code from Simantics SVN
[simantics/platform.git] / bundles / org.simantics.fastlz / testcases / org / simantics / fastlz / ChecksumUtil.java
diff --git a/bundles/org.simantics.fastlz/testcases/org/simantics/fastlz/ChecksumUtil.java b/bundles/org.simantics.fastlz/testcases/org/simantics/fastlz/ChecksumUtil.java
new file mode 100644 (file)
index 0000000..04cdde2
--- /dev/null
@@ -0,0 +1,71 @@
+package org.simantics.fastlz;\r
+\r
+import java.io.File;\r
+import java.io.FileInputStream;\r
+import java.io.IOException;\r
+import java.io.InputStream;\r
+import java.net.URL;\r
+import java.security.MessageDigest;\r
+import java.security.NoSuchAlgorithmException;\r
+\r
+/**\r
+ * @author Tuukka Lehtonen\r
+ */\r
+public final class ChecksumUtil {\r
+\r
+    public static byte[] computeSum(byte[] in) {\r
+        if (in == null)\r
+            throw new IllegalArgumentException("Input cannot be null!");\r
+        try {\r
+            MessageDigest md = MessageDigest.getInstance("MD5");\r
+            md.update(in, 0, in.length);\r
+            return md.digest();\r
+        } catch (NoSuchAlgorithmException e) {\r
+            throw new Error("MD5 digest must be supported by JVM");\r
+        }\r
+    }\r
+\r
+    public static byte[] computeSum(InputStream in) throws IOException {\r
+        if (in == null)\r
+            throw new IllegalArgumentException("Input cannot be null!");\r
+\r
+        MessageDigest md;\r
+        try {\r
+            md = MessageDigest.getInstance("MD5");\r
+        } catch (NoSuchAlgorithmException e) {\r
+            throw new Error("MD5 digest must be supported by JVM");\r
+        }\r
+        byte[] data = new byte[64 * 1024];\r
+\r
+        while (true) {\r
+            int read = in.read(data);\r
+            if (read == -1) {\r
+                return md.digest();\r
+            }\r
+            md.update(data, 0, read);\r
+        }\r
+    }\r
+\r
+    public static byte[] computeSum(File f) throws IOException {\r
+        InputStream in = null;\r
+        try {\r
+            in = new FileInputStream(f);\r
+            return computeSum(in);\r
+        } finally {\r
+            if (in != null)\r
+                in.close();\r
+        }\r
+    }\r
+\r
+    public static byte[] computeSum(URL url) throws IOException {\r
+        InputStream in = null;\r
+        try {\r
+            in = url.openStream();\r
+            return computeSum(in);\r
+        } finally {\r
+            if (in != null)\r
+                in.close();\r
+        }\r
+    }\r
+\r
+}\r