1 22 package org.jboss.net.sockets; 23 import java.util.WeakHashMap ; 24 import java.util.Map ; 25 import java.lang.reflect.Method ; 26 import java.util.HashMap ; 27 import java.io.DataOutputStream ; 28 import java.io.ByteArrayOutputStream ; 29 import java.security.DigestOutputStream ; 30 import java.security.MessageDigest ; 31 32 public class MethodHash 33 { 34 35 static Map hashMap = new WeakHashMap (); 37 38 44 public static Map getInterfaceHashes(Class intf) 45 { 46 Method [] methods = intf.getMethods(); 48 HashMap map = new HashMap (); 49 for (int i = 0; i < methods.length; i++) 50 { 51 Method method = methods[i]; 52 Class [] parameterTypes = method.getParameterTypes(); 53 String methodDesc = method.getName()+"("; 54 for(int j = 0; j < parameterTypes.length; j++) 55 { 56 methodDesc += getTypeString(parameterTypes[j]); 57 } 58 methodDesc += ")"+getTypeString(method.getReturnType()); 59 60 try 61 { 62 long hash = 0; 63 ByteArrayOutputStream bytearrayoutputstream = new ByteArrayOutputStream (512); 64 MessageDigest messagedigest = MessageDigest.getInstance("SHA"); 65 DataOutputStream dataoutputstream = new DataOutputStream (new DigestOutputStream (bytearrayoutputstream, messagedigest)); 66 dataoutputstream.writeUTF(methodDesc); 67 dataoutputstream.flush(); 68 byte abyte0[] = messagedigest.digest(); 69 for(int j = 0; j < Math.min(8, abyte0.length); j++) 70 hash += (long)(abyte0[j] & 0xff) << j * 8; 71 map.put(method.toString(), new Long (hash)); 72 } 73 catch (Exception e) 74 { 75 e.printStackTrace(); 76 } 77 } 78 79 return map; 80 } 81 82 static String getTypeString(Class cl) 83 { 84 if (cl == Byte.TYPE) 85 { 86 return "B"; 87 } else if (cl == Character.TYPE) 88 { 89 return "C"; 90 } else if (cl == Double.TYPE) 91 { 92 return "D"; 93 } else if (cl == Float.TYPE) 94 { 95 return "F"; 96 } else if (cl == Integer.TYPE) 97 { 98 return "I"; 99 } else if (cl == Long.TYPE) 100 { 101 return "J"; 102 } else if (cl == Short.TYPE) 103 { 104 return "S"; 105 } else if (cl == Boolean.TYPE) 106 { 107 return "Z"; 108 } else if (cl == Void.TYPE) 109 { 110 return "V"; 111 } else if (cl.isArray()) 112 { 113 return "["+getTypeString(cl.getComponentType()); 114 } else 115 { 116 return "L"+cl.getName().replace('.','/')+";"; 117 } 118 } 119 120 127 public static long calculateHash(Method method) 128 { 129 Map methodHashes = (Map )hashMap.get(method.getDeclaringClass()); 130 131 if (methodHashes == null) 132 { 133 methodHashes = getInterfaceHashes(method.getDeclaringClass()); 134 135 WeakHashMap newHashMap = new WeakHashMap (); 137 newHashMap.putAll(hashMap); 138 newHashMap.put(method.getDeclaringClass(), methodHashes); 139 hashMap = newHashMap; 140 } 141 142 return ((Long )methodHashes.get(method.toString())).longValue(); 143 } 144 145 } 146 | Popular Tags |