1 19 package org.netbeans.modules.javacore; 20 21 import java.lang.reflect.InvocationHandler ; 22 import java.lang.reflect.Proxy ; 23 import java.util.*; 24 import javax.jmi.reflect.RefObject; 25 26 30 public class Snapshot implements InvocationHandler { 31 private final HashMap results = new HashMap(); 32 private RefObject wrappedObject; 33 private HashSet snapshots; 34 35 private Snapshot(RefObject wrappedObject) { 36 this.wrappedObject = wrappedObject; 37 } 38 39 public Object invoke(Object proxy, java.lang.reflect.Method method, Object [] args) throws Throwable { 40 Object result; 41 if (wrappedObject == null) { 42 result = results.get(method); 43 if (result == null && !results.containsKey(method)) { 44 throw new IllegalStateException ("Value for " + method + " not cached."); 45 } 46 } else { 47 result = method.invoke(wrappedObject, args); 48 result = wrap(result); 49 results.put(method, result); 50 } 51 return result; 52 } 53 54 private void addSnapshot(Object snapshot) { 55 if (snapshots == null) { 56 snapshots = new HashSet(); 57 } 58 snapshots.add(snapshot); 59 } 60 61 private Object wrap(Object obj) { 62 if (obj instanceof Collection) { 63 return wrapCollection((Collection) obj); 64 } else if (obj instanceof RefObject) { 65 Object result = createSnapshot((RefObject) obj); 66 addSnapshot(result); 67 return result; 68 } else { 69 return obj; 70 } 71 } 72 73 private Object wrapCollection(Collection col) { 74 Collection result = new ArrayList(); 75 for (Iterator it = col.iterator(); it.hasNext();) { 76 result.add(wrap(it.next())); 77 } 78 return result; 79 } 80 81 private void freeze() { 82 if (snapshots != null) { 83 for (Iterator it = snapshots.iterator(); it.hasNext();) { 84 ((Snapshot) it.next()).freeze(); 85 } 86 snapshots = null; 87 } 88 wrappedObject = null; 89 } 90 91 public static RefObject createSnapshot(RefObject wrappedObject) { 92 Snapshot ss = new Snapshot(wrappedObject); 93 Class clz = wrappedObject.getClass(); 94 return (RefObject) Proxy.newProxyInstance(clz.getClassLoader(), clz.getInterfaces(), ss); 95 } 96 97 public static void freeze(RefObject snapshot) { 98 ((Snapshot) Proxy.getInvocationHandler(snapshot)).freeze(); 99 } 100 } 101 | Popular Tags |