]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics.fastlz/testcases/org/simantics/fastlz/ChecksumUtil.java
Fixed all line endings of the repository
[simantics/platform.git] / bundles / org.simantics.fastlz / testcases / org / simantics / fastlz / ChecksumUtil.java
1 package org.simantics.fastlz;
2
3 import java.io.File;
4 import java.io.FileInputStream;
5 import java.io.IOException;
6 import java.io.InputStream;
7 import java.net.URL;
8 import java.security.MessageDigest;
9 import java.security.NoSuchAlgorithmException;
10
11 /**
12  * @author Tuukka Lehtonen
13  */
14 public final class ChecksumUtil {
15
16     public static byte[] computeSum(byte[] in) {
17         if (in == null)
18             throw new IllegalArgumentException("Input cannot be null!");
19         try {
20             MessageDigest md = MessageDigest.getInstance("MD5");
21             md.update(in, 0, in.length);
22             return md.digest();
23         } catch (NoSuchAlgorithmException e) {
24             throw new Error("MD5 digest must be supported by JVM");
25         }
26     }
27
28     public static byte[] computeSum(InputStream in) throws IOException {
29         if (in == null)
30             throw new IllegalArgumentException("Input cannot be null!");
31
32         MessageDigest md;
33         try {
34             md = MessageDigest.getInstance("MD5");
35         } catch (NoSuchAlgorithmException e) {
36             throw new Error("MD5 digest must be supported by JVM");
37         }
38         byte[] data = new byte[64 * 1024];
39
40         while (true) {
41             int read = in.read(data);
42             if (read == -1) {
43                 return md.digest();
44             }
45             md.update(data, 0, read);
46         }
47     }
48
49     public static byte[] computeSum(File f) throws IOException {
50         InputStream in = null;
51         try {
52             in = new FileInputStream(f);
53             return computeSum(in);
54         } finally {
55             if (in != null)
56                 in.close();
57         }
58     }
59
60     public static byte[] computeSum(URL url) throws IOException {
61         InputStream in = null;
62         try {
63             in = url.openStream();
64             return computeSum(in);
65         } finally {
66             if (in != null)
67                 in.close();
68         }
69     }
70
71 }