1 package org.apache.maven.repository.applet;
4 * Copyright 2005-2006 The Apache Software Foundation.
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
10 * http://www.apache.org/licenses/LICENSE-2.0
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.
21 import java.applet.Applet;
24 import java.io.FileInputStream;
25 import java.io.IOException;
26 import java.io.InputStream;
27 import java.security.AccessController;
28 import java.security.MessageDigest;
29 import java.security.NoSuchAlgorithmException;
30 import java.security.PrivilegedAction;
35 * @author <a href="mailto:brett@apache.org">Brett Porter</a>
37 public class ChecksumApplet
40 private static final int CHECKSUM_BUFFER_SIZE = 8192;
42 private static final int BYTE_MASK = 0xFF;
44 private JProgressBar progressBar;
48 setLayout( new BorderLayout() );
49 progressBar = new JProgressBar();
50 progressBar.setStringPainted( true );
51 add( progressBar, BorderLayout.CENTER );
52 JLabel label = new JLabel( "Checksum progress: " );
53 add( label, BorderLayout.WEST );
56 public String generateMd5( final String file )
57 throws IOException, NoSuchAlgorithmException
59 return (String) AccessController.doPrivileged( new PrivilegedAction()
65 MessageDigest digest = MessageDigest.getInstance( "MD5" );
67 long total = new File( file ).length();
68 InputStream fis = new FileInputStream( file );
72 byte[] buffer = new byte[CHECKSUM_BUFFER_SIZE];
76 numRead = fis.read( buffer );
79 digest.update( buffer, 0, numRead );
81 progressBar.setValue( (int) ( totalRead * progressBar.getMaximum() / total ) );
84 while ( numRead != -1 );
91 return byteArrayToHexStr( digest.digest() );
93 catch ( NoSuchAlgorithmException e )
95 throw new RuntimeException( e );
97 catch ( IOException e )
99 throw new RuntimeException( e );
105 private static String byteArrayToHexStr( byte[] data )
109 for ( int cnt = 0; cnt < data.length; cnt++ )
111 //Deposit a byte into the 8 lsb of an int.
112 int tempInt = data[cnt] & BYTE_MASK;
114 //Get hex representation of the int as a string.
115 String tempStr = Integer.toHexString( tempInt );
117 //Append a leading 0 if necessary so that each hex string will contain 2 characters.
118 if ( tempStr.length() == 1 )
120 tempStr = "0" + tempStr;
123 //Concatenate the two characters to the output string.
124 output = output + tempStr;
127 return output.toUpperCase();