1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.eclipse.aether.spi.connector.checksum;
20
21 import java.io.BufferedInputStream;
22 import java.io.ByteArrayInputStream;
23 import java.io.File;
24 import java.io.IOException;
25 import java.io.InputStream;
26 import java.nio.ByteBuffer;
27 import java.nio.file.Files;
28 import java.util.LinkedHashMap;
29 import java.util.List;
30 import java.util.Map;
31
32
33
34
35
36
37 public final class ChecksumAlgorithmHelper {
38 private ChecksumAlgorithmHelper() {
39
40 }
41
42
43
44
45
46
47
48
49
50
51 public static Map<String, String> calculate(byte[] data, List<ChecksumAlgorithmFactory> factories)
52 throws IOException {
53 try (InputStream inputStream = new ByteArrayInputStream(data)) {
54 return calculate(inputStream, factories);
55 }
56 }
57
58
59
60
61
62
63
64
65
66
67 public static Map<String, String> calculate(File file, List<ChecksumAlgorithmFactory> factories)
68 throws IOException {
69 try (InputStream inputStream = new BufferedInputStream(Files.newInputStream(file.toPath()))) {
70 return calculate(inputStream, factories);
71 }
72 }
73
74 private static Map<String, String> calculate(InputStream inputStream, List<ChecksumAlgorithmFactory> factories)
75 throws IOException {
76 LinkedHashMap<String, ChecksumAlgorithm> algorithms = new LinkedHashMap<>();
77 factories.forEach(f -> algorithms.put(f.getName(), f.getAlgorithm()));
78 final byte[] buffer = new byte[1024 * 32];
79 for (; ; ) {
80 int read = inputStream.read(buffer);
81 if (read < 0) {
82 break;
83 }
84 for (ChecksumAlgorithm checksumAlgorithm : algorithms.values()) {
85 checksumAlgorithm.update(ByteBuffer.wrap(buffer, 0, read));
86 }
87 }
88 LinkedHashMap<String, String> result = new LinkedHashMap<>();
89 algorithms.forEach((k, v) -> result.put(k, v.checksum()));
90 return result;
91 }
92 }