1 package com.tirsen.nanning.samples.prevayler; 2 3 import java.util.*; 4 5 import org.prevayler.util.clock.AbstractClockedSystem; 6 import org.apache.commons.logging.Log; 7 import org.apache.commons.logging.LogFactory; 8 9 public class BasicIdentifyingSystem extends AbstractClockedSystem implements IdentifyingSystem { 10 private static final Log logger = LogFactory.getLog(BasicIdentifyingSystem.class); 11 static final long serialVersionUID = 4503034161857395426L; 12 13 private Map idToObject = SoftMap.createSoftValuesMap(); 14 18 private Map objectToId = SoftMap.createSoftKeysMap(); 19 20 private long nextObjectId = 0; 21 22 public void rebuildKeysMap() { 23 objectToId = SoftMap.createSoftKeysMap(); 24 for (Iterator iterator = idToObject.entrySet().iterator(); iterator.hasNext();) { 25 Map.Entry entry = (Map.Entry) iterator.next(); 26 Long id = (Long ) entry.getKey(); 27 Object o = entry.getValue(); 28 objectToId.put(o, id); 29 } 30 } 31 32 public synchronized Object getObjectWithID(long oid) { 33 Object object = idToObject.get(new Long (oid)); 34 assert object != null : "could not find object with id " + oid; 35 assert hasObjectID(object) : "object is not registered " + object; 36 return object; 37 } 38 39 public synchronized long getObjectID(Object object) { 40 assert hasObjectID(object) : "object " + object + " had no object id, use registerObjectID(Object)"; 41 return ((Long ) objectToId.get(object)).longValue(); 42 } 43 44 public synchronized boolean hasNoRegisteredObjects() { 45 return objectToId.isEmpty(); 46 } 47 48 public synchronized Collection getAllRegisteredObjects() { 49 50 Collection result = new ArrayList(); 51 for (Iterator i = objectToId.entrySet().iterator(); i.hasNext();) { 52 try { 53 Map.Entry entry = (Map.Entry) i.next(); 54 result.add(entry.getKey()); 55 } catch (NoSuchElementException ignore) { 56 57 } 58 } 59 60 return result; 61 } 62 63 public synchronized boolean hasObjectID(Object object) { 64 return objectToId.containsKey(object); 65 } 66 67 public synchronized boolean isIDRegistered(long objectId) { 68 return idToObject.containsKey(new Long (objectId)); 69 } 70 71 public synchronized long registerObjectID(final Object object) { 72 if (!CurrentPrevayler.isInTransaction()) { 73 throw new IllegalStateException ("You have to be inside a transaction to register objects"); 74 } 75 76 assert object != null : "can't register null"; 77 assert !hasObjectID(object) : "already has ID: " + object; 78 79 Long id = getNextId(); 80 assert !isIDRegistered(id.longValue()); 81 82 idToObject.put(id, object); 83 objectToId.put(object, id); 84 85 logger.debug("registering object " + object + " with id " + id); 86 87 return id.longValue(); 88 } 89 90 private synchronized Long getNextId() { 91 return new Long (nextObjectId++); 92 } 93 } 94 | Popular Tags |