1 25 26 package org.objectweb.easybeans.rpc.util; 27 28 import java.io.ByteArrayOutputStream ; 29 import java.io.DataOutputStream ; 30 import java.io.IOException ; 31 import java.lang.reflect.Method ; 32 import java.security.DigestOutputStream ; 33 import java.security.MessageDigest ; 34 import java.security.NoSuchAlgorithmException ; 35 import java.util.HashMap ; 36 import java.util.Map ; 37 38 import org.objectweb.asm.Type; 39 40 import org.objectweb.easybeans.log.JLog; 41 import org.objectweb.easybeans.log.JLogFactory; 42 43 48 public final class Hash { 49 50 53 private static JLog logger = JLogFactory.getLog(Hash.class); 54 55 58 private static final int BYTES_LENGTH = 8; 59 60 63 private static final int BYTE_MASK = 0xFF; 64 65 66 69 private Hash() { 70 71 } 72 73 94 public static long hashMethod(final Method method) { 95 96 MessageDigest md; 97 try { 98 md = MessageDigest.getInstance("SHA-1"); 99 } catch (NoSuchAlgorithmException e) { 100 throw new IllegalStateException ("Algorithm SHA-1 is not available", e); 101 } 102 ByteArrayOutputStream baos = new ByteArrayOutputStream (); 103 DigestOutputStream dos = new DigestOutputStream (baos, md); 104 DataOutputStream das = new DataOutputStream (dos); 105 106 StringBuilder sb = new StringBuilder (); 107 sb.append(method.getName()); 108 sb.append(Type.getMethodDescriptor(method)); 109 try { 110 das.writeUTF(sb.toString()); 111 } catch (IOException e) { 112 throw new IllegalStateException ("Cannot write data for method '" + method.getName() + "'.", e); 113 } 114 try { 115 das.flush(); 116 } catch (IOException e) { 117 logger.warn("Cannot flush the stream", e); 118 } 119 try { 120 das.close(); 121 } catch (IOException e) { 122 logger.warn("Cannot flush the stream", e); 123 } 124 125 byte[] digest = md.digest(); 126 long hash = 0; 127 int size = Math.min(digest.length, BYTES_LENGTH); 128 for (int i = 0; i < size; i++) { 129 hash += (long) (digest[i] & BYTE_MASK) << (BYTES_LENGTH * i); 130 } 131 return hash; 132 } 133 134 135 140 public static Map <Long , Method > hashClass(final Class clz) { 141 Map <Long , Method > map = new HashMap <Long , Method >(); 142 Method [] methods = clz.getMethods(); 143 for (Method m : methods) { 144 map.put(Long.valueOf(hashMethod(m)), m); 145 } 146 return map; 147 } 148 149 } 150 | Popular Tags |