View Javadoc
1   package org.codehaus.plexus.digest;
2   
3   /*
4    * Copyright 2001-2006 The Codehaus.
5    *
6    * Licensed under the Apache License, Version 2.0 (the "License");
7    * you may not use this file except in compliance with the License.
8    * You may obtain a copy of the License at
9    *
10   *      http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing, software
13   * distributed under the License is distributed on an "AS IS" BASIS,
14   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15   * See the License for the specific language governing permissions and
16   * limitations under the License.
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   * Create a digest for a file.
28   *
29   * @author <a href="mailto:brett@apache.org">Brett Porter</a>
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          //Create checksum for file
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  }