View Javadoc

1   /**
2    * Copyright 2005-2015 The Kuali Foundation
3    *
4    * Licensed under the Educational Community License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    * http://www.opensource.org/licenses/ecl2.php
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  package org.kuali.rice.core.api.util;
17  
18  import org.apache.commons.codec.binary.Base64;
19  import org.kuali.rice.core.api.exception.RiceRuntimeException;
20  
21  import java.io.ByteArrayOutputStream;
22  import java.io.IOException;
23  import java.io.ObjectOutput;
24  import java.io.ObjectOutputStream;
25  import java.io.UnsupportedEncodingException;
26  import java.security.GeneralSecurityException;
27  import java.security.MessageDigest;
28  
29  /**
30   * A utility class for generating checksum values from Serializable objects.
31   *
32   * @author Kuali Rice Team (rice.collab@kuali.org)
33   */
34  public final class ChecksumUtils {
35  
36      /**
37  	 * Creates a checksum for the given object which must be serializable.
38  	 *
39  	 * @param object the serializable object for which to calculate the checksum
40       * 
41  	 * @return A checksum value for the object.
42  	 */
43  	public static String calculateChecksum(Object object) {
44  		ByteArrayOutputStream bos = new ByteArrayOutputStream();
45          ObjectOutput out = null;
46          try {
47              out = new ObjectOutputStream(bos);
48              out.writeObject(object);
49          } catch (IOException e) {
50              throw new RiceRuntimeException(e);
51          } finally {
52              try {
53                  out.close();
54              } catch (IOException e) {}
55          }
56          try {
57              MessageDigest md = MessageDigest.getInstance("SHA-1");
58              return new String( Base64.encodeBase64(md.digest(bos.toByteArray())), "UTF-8");
59          } catch( GeneralSecurityException ex ) {
60          	throw new RiceRuntimeException(ex);
61          } catch( UnsupportedEncodingException ex ) {
62          	throw new RiceRuntimeException(ex);
63          }
64  	}
65  
66      @SuppressWarnings("unused")
67      private ChecksumUtils() {
68          throw new UnsupportedOperationException("Should never be executed.");
69      }
70  
71  }