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