1 package org.apache.maven.plugin.install;
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.File;
24 import java.io.FileInputStream;
25 import java.io.IOException;
26 import java.io.InputStream;
27 import java.security.MessageDigest;
28 import java.security.NoSuchAlgorithmException;
29
30 import org.apache.commons.codec.binary.Hex;
31 import org.apache.maven.plugin.MojoExecutionException;
32 import org.codehaus.plexus.util.IOUtil;
33
34
35
36
37
38
39
40
41
42 public class DualDigester
43 {
44 private final MessageDigest md5 = getDigester( "MD5" );
45
46 private final MessageDigest sh1 = getDigester( "SHA-1" );
47
48 private static final int bufsize = 65536 * 2;
49
50 private final byte[] buffer = new byte[bufsize];
51
52 static MessageDigest getDigester( String algorithm )
53 {
54 try
55 {
56 return MessageDigest.getInstance( algorithm );
57 }
58 catch ( NoSuchAlgorithmException e )
59 {
60 throw new RuntimeException( "Unable to initialize digest " + algorithm + " : " + e.getMessage() );
61 }
62 }
63
64 public void calculate( File file )
65 throws MojoExecutionException
66 {
67 FileInputStream fis = null;
68 BufferedInputStream bis = null;
69
70 try
71 {
72 fis = new FileInputStream( file );
73 calculate( fis );
74 }
75 catch ( IOException e )
76 {
77 throw new MojoExecutionException( "Failed to calculate digest checksum for " + file, e );
78 }
79 finally
80 {
81 IOUtil.close( bis );
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 }