1 package org.apache.maven.shared.project.install.internal;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 import java.io.File;
23 import java.io.FileInputStream;
24 import java.io.IOException;
25 import java.io.InputStream;
26 import java.security.MessageDigest;
27 import java.security.NoSuchAlgorithmException;
28
29 import org.apache.commons.codec.binary.Hex;
30 import org.codehaus.plexus.util.IOUtil;
31
32
33
34
35
36
37
38
39
40
41
42
43 class DualDigester
44 {
45 private final MessageDigest md5 = getDigester( "MD5" );
46
47 private final MessageDigest sh1 = getDigester( "SHA-1" );
48
49 private static final int BUFSIZE = 65536 * 2;
50
51 private final byte[] buffer = new byte[BUFSIZE];
52
53 static MessageDigest getDigester( String algorithm )
54 {
55 try
56 {
57 return MessageDigest.getInstance( algorithm );
58 }
59 catch ( NoSuchAlgorithmException e )
60 {
61 throw new RuntimeException( "Unable to initialize digest " + algorithm + " : " + e.getMessage() );
62 }
63 }
64
65 public void calculate( File file ) throws IOException
66 {
67 FileInputStream fis = null;
68
69 try
70 {
71 fis = new FileInputStream( file );
72 calculate( fis );
73 fis.close();
74 fis = null;
75 }
76 catch ( IOException e )
77 {
78 throw new IOException( "Failed to calculate digest checksum for " + file, e );
79 }
80 finally
81 {
82 IOUtil.close( fis );
83 }
84 }
85
86 void calculate( InputStream stream )
87 throws IOException
88 {
89 md5.reset();
90 sh1.reset();
91 update( stream );
92 }
93
94 public String getMd5()
95 {
96 return Hex.encodeHexString( md5.digest() );
97 }
98
99 public String getSha1()
100 {
101 return Hex.encodeHexString( sh1.digest() );
102 }
103
104 private void update( InputStream is )
105 throws IOException
106 {
107 int size = is.read( buffer, 0, BUFSIZE );
108 while ( size >= 0 )
109 {
110 md5.update( buffer, 0, size );
111 sh1.update( buffer, 0, size );
112 size = is.read( buffer, 0, BUFSIZE );
113 }
114 }
115 }