]> gerrit.simantics Code Review - simantics/platform.git/blob - 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
1 package net.jpountz.util;
2
3 import java.io.IOException;
4 import java.io.InputStream;
5 import java.net.URL;
6 import java.nio.file.Files;
7 import java.nio.file.Path;
8 import java.security.MessageDigest;
9 import java.security.NoSuchAlgorithmException;
10
11 /**
12  * @author Tuukka Lehtonen
13  */
14 public final class ChecksumUtil {
15
16     private static byte[] computeSum(InputStream in) throws IOException {
17         if (in == null)
18             throw new IllegalArgumentException("Input cannot be null!");
19
20         MessageDigest md;
21         try {
22             md = MessageDigest.getInstance("MD5");
23         } catch (NoSuchAlgorithmException e) {
24             throw new Error("MD5 digest must be supported by JVM");
25         }
26         byte[] data = new byte[64 * 1024];
27
28         while (true) {
29             int read = in.read(data);
30             if (read == -1) {
31                 return md.digest();
32             }
33             md.update(data, 0, read);
34         }
35     }
36
37     public static byte[] computeSum(Path p) throws IOException {
38         try (InputStream in = Files.newInputStream(p)) {
39             return computeSum(in);
40         }
41     }
42
43     public static byte[] computeSum(URL url) throws IOException {
44         try (InputStream in = url.openStream()) {
45             return computeSum(in);
46         }
47     }
48
49 }