1 package org.apache.maven.wagon.observers;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 import org.apache.maven.wagon.events.TransferEvent;
23 import org.apache.maven.wagon.events.TransferListener;
24
25 import java.security.MessageDigest;
26 import java.security.NoSuchAlgorithmException;
27
28
29
30
31
32
33
34 public class ChecksumObserver
35 implements TransferListener
36 {
37 private MessageDigest digester = null;
38
39 private String actualChecksum;
40
41 public ChecksumObserver()
42 throws NoSuchAlgorithmException
43 {
44 this( "MD5" );
45 }
46
47
48
49
50 public ChecksumObserver( String algorithm )
51 throws NoSuchAlgorithmException
52 {
53 digester = MessageDigest.getInstance( algorithm );
54 }
55
56 public void transferInitiated( TransferEvent transferEvent )
57 {
58
59 }
60
61
62
63
64 public void transferStarted( TransferEvent transferEvent )
65 {
66 actualChecksum = null;
67
68 digester.reset();
69 }
70
71
72
73
74 public void transferProgress( TransferEvent transferEvent, byte[] buffer, int length )
75 {
76 digester.update( buffer, 0, length );
77 }
78
79 public void transferCompleted( TransferEvent transferEvent )
80 {
81 actualChecksum = encode( digester.digest() );
82 }
83
84 public void transferError( TransferEvent transferEvent )
85 {
86 digester.reset();
87
88 actualChecksum = null;
89 }
90
91 public void debug( String message )
92 {
93
94 }
95
96
97
98
99
100
101 public String getActualChecksum()
102 {
103 return actualChecksum;
104 }
105
106
107
108
109
110
111
112 @SuppressWarnings( "checkstyle:magicnumber" )
113 protected String encode( byte[] binaryData )
114 {
115
116 if ( binaryData.length != 16 && binaryData.length != 20 )
117 {
118 int bitLength = binaryData.length * 8;
119 throw new IllegalArgumentException( "Unrecognised length for binary data: " + bitLength + " bits" );
120 }
121
122 StringBuilder retValue = new StringBuilder();
123
124 for ( byte b : binaryData )
125 {
126 String t = Integer.toHexString( b & 0xff );
127
128 if ( t.length() == 1 )
129 {
130 retValue.append( '0' ).append( t );
131 }
132 else
133 {
134 retValue.append( t );
135 }
136 }
137
138 return retValue.toString().trim();
139 }
140
141
142 }