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 {
38 this.streamingDigester = streamingDigester;
39 }
40
41 public String getAlgorithm()
42 {
43 return streamingDigester.getAlgorithm();
44 }
45
46 public String calc( File file )
47 throws DigesterException
48 {
49 FileInputStream fis = null;
50 try
51 {
52 fis = new FileInputStream( file );
53 streamingDigester.reset();
54 streamingDigester.update( fis );
55 return streamingDigester.calc();
56 }
57 catch ( IOException e )
58 {
59 throw new DigesterException( "Unable to calculate the " + streamingDigester.getAlgorithm() +
60 " hashcode for " + file.getAbsolutePath() + ": " + e.getMessage(), e );
61 }
62 finally
63 {
64 IOUtil.close( fis );
65 }
66 }
67
68 public void verify( File file, String checksum )
69 throws DigesterException
70 {
71 String trimmedChecksum =
72 DigestUtils.cleanChecksum( checksum, streamingDigester.getAlgorithm(), file.getName() );
73
74
75 String sum = calc( file );
76 if ( !StringUtils.equalsIgnoreCase( trimmedChecksum, sum ) )
77 {
78 throw new DigesterException( "Checksum failed (expected=" + trimmedChecksum + ", actual=" + sum + ")" );
79 }
80 }
81
82 public String toString()
83 {
84 return "[Digester:" + streamingDigester.getAlgorithm() + "]";
85 }
86 }