1 | |
package org.codehaus.plexus.digest; |
2 | |
|
3 | |
|
4 | |
|
5 | |
|
6 | |
|
7 | |
|
8 | |
|
9 | |
|
10 | |
|
11 | |
|
12 | |
|
13 | |
|
14 | |
|
15 | |
|
16 | |
|
17 | |
|
18 | |
|
19 | |
import org.codehaus.plexus.util.IOUtil; |
20 | |
import org.codehaus.plexus.util.StringUtils; |
21 | |
|
22 | |
import java.io.File; |
23 | |
import java.io.FileInputStream; |
24 | |
import java.io.IOException; |
25 | |
|
26 | |
|
27 | |
|
28 | |
|
29 | |
|
30 | |
|
31 | |
public abstract class AbstractDigester |
32 | |
implements Digester |
33 | |
{ |
34 | |
private final StreamingDigester streamingDigester; |
35 | |
|
36 | |
protected AbstractDigester( StreamingDigester streamingDigester ) |
37 | 16 | { |
38 | 16 | this.streamingDigester = streamingDigester; |
39 | 16 | } |
40 | |
|
41 | |
public String getAlgorithm() |
42 | |
{ |
43 | 14 | return streamingDigester.getAlgorithm(); |
44 | |
} |
45 | |
|
46 | |
public String calc( File file ) |
47 | |
throws DigesterException |
48 | |
{ |
49 | 28 | FileInputStream fis = null; |
50 | |
try |
51 | |
{ |
52 | 28 | fis = new FileInputStream( file ); |
53 | 28 | streamingDigester.reset(); |
54 | 28 | streamingDigester.update( fis ); |
55 | 28 | return streamingDigester.calc(); |
56 | |
} |
57 | 0 | catch ( IOException e ) |
58 | |
{ |
59 | 0 | throw new DigesterException( "Unable to calculate the " + streamingDigester.getAlgorithm() + |
60 | |
" hashcode for " + file.getAbsolutePath() + ": " + e.getMessage(), e ); |
61 | |
} |
62 | |
finally |
63 | |
{ |
64 | 28 | IOUtil.close( fis ); |
65 | |
} |
66 | |
} |
67 | |
|
68 | |
public void verify( File file, String checksum ) |
69 | |
throws DigesterException |
70 | |
{ |
71 | 16 | String trimmedChecksum = |
72 | |
DigestUtils.cleanChecksum( checksum, streamingDigester.getAlgorithm(), file.getName() ); |
73 | |
|
74 | |
|
75 | 14 | String sum = calc( file ); |
76 | 14 | if ( !StringUtils.equalsIgnoreCase( trimmedChecksum, sum ) ) |
77 | |
{ |
78 | 3 | throw new DigesterException( "Checksum failed (expected=" + trimmedChecksum + ", actual=" + sum + ")" ); |
79 | |
} |
80 | 11 | } |
81 | |
|
82 | |
public String toString() |
83 | |
{ |
84 | 0 | return "[Digester:" + streamingDigester.getAlgorithm() + "]"; |
85 | |
} |
86 | |
} |