[jboss-cvs] JBossCache/src-50/org/jboss/cache/pojo/impl ...

Ben Wang bwang at jboss.com
Thu Jul 13 11:56:12 EDT 2006


  User: bwang   
  Date: 06/07/13 11:56:12

  Modified:    src-50/org/jboss/cache/pojo/impl        PojoCacheImpl.java
  Added:       src-50/org/jboss/cache/pojo/impl       
                        CollectionClassHandler.java InternalConstant.java
                        InternalHelper.java ObjectGraphHandler.java
                        PojoCacheDelegate.java
                        SerializableObjectHandler.java
  Log:
  Refctoring and moved some classes to impl dir.
  
  Revision  Changes    Path
  1.8       +112 -8    JBossCache/src-50/org/jboss/cache/pojo/impl/PojoCacheImpl.java
  
  (In the diff below, changes in quantity of whitespace are not shown.)
  
  Index: PojoCacheImpl.java
  ===================================================================
  RCS file: /cvsroot/jboss/JBossCache/src-50/org/jboss/cache/pojo/impl/PojoCacheImpl.java,v
  retrieving revision 1.7
  retrieving revision 1.8
  diff -u -b -r1.7 -r1.8
  --- PojoCacheImpl.java	13 Jul 2006 04:26:07 -0000	1.7
  +++ PojoCacheImpl.java	13 Jul 2006 15:56:12 -0000	1.8
  @@ -10,22 +10,26 @@
   import org.jboss.cache.CacheException;
   import org.jboss.cache.PropertyConfigurator;
   import org.jboss.cache.TreeCache;
  +import org.jboss.cache.Fqn;
   import org.jboss.cache.pojo.PojoCache;
   import org.jboss.cache.pojo.PojoCacheException;
   import org.jboss.cache.pojo.PojoCacheListener;
   import org.jboss.cache.pojo.PojoTreeCache;
  +import org.jboss.cache.pojo.CachedType;
   import org.jboss.cache.pojo.observable.Observer;
   import org.jboss.cache.pojo.observable.Subject;
  -import org.jboss.cache.pojo.annotation.CheckIdValidity;
   import org.jboss.cache.pojo.annotation.Attach;
   import org.jboss.cache.pojo.annotation.Detach;
   import org.jboss.cache.pojo.annotation.Find;
  +import org.apache.commons.logging.Log;
  +import org.apache.commons.logging.LogFactory;
   
   import java.util.Collection;
   import java.util.Map;
   import java.util.Set;
   import java.util.Collections;
   import java.util.Iterator;
  +import java.util.WeakHashMap;
   import java.lang.reflect.Field;
   
   import EDU.oswego.cs.dl.util.concurrent.CopyOnWriteArraySet;
  @@ -34,11 +38,17 @@
    * Implementation class for PojoCache interface
    *
    * @author Ben Wang
  - * @version $Id: PojoCacheImpl.java,v 1.7 2006/07/13 04:26:07 bwang Exp $
  + * @version $Id: PojoCacheImpl.java,v 1.8 2006/07/13 15:56:12 bwang Exp $
    */
   public class PojoCacheImpl implements PojoCache, Observer
   {
      private PojoTreeCache cache_ = null;
  +   protected final Log log = LogFactory.getLog(PojoCacheImpl.this.getClass());
  +   private PojoCacheDelegate delegate_;
  +   // Class -> CachedType
  +   // use WeakHashMap to allow class reloading
  +   private Map cachedTypes = new WeakHashMap();
  +
      /**
       * Set of TreeCacheListener.
       *
  @@ -54,7 +64,7 @@
      {
         try
         {
  -         cache_ = new PojoTreeCache(this);
  +         cache_ = new PojoTreeCache();
            PropertyConfigurator config = new PropertyConfigurator();
            config.configure(cache_, configStr);
         } catch (Exception e)
  @@ -62,6 +72,12 @@
            e.printStackTrace();
            throw new PojoCacheException("PojoTreeCache: " + e);
         }
  +      init();
  +   }
  +
  +   private void init()
  +   {
  +      delegate_ = new PojoCacheDelegate(this, this);
      }
   
      public PojoTreeCache getUnderlyingCache() { return cache_; }
  @@ -72,7 +88,7 @@
         try
         {
            notifyAttach(pojo, true);
  -         Object obj = cache_.putObject(id, pojo);
  +         Object obj = putObject(Fqn.fromString(id), pojo);
            notifyAttach(pojo, false);
            return obj;
         } catch (CacheException e)
  @@ -89,7 +105,7 @@
         {
            Object pojo = find(id); // TODO need optimization here since it will be redundant here
            notifyDetach(pojo, true);
  -         Object obj = cache_.removeObject(id);
  +         Object obj = removeObject(Fqn.fromString(id));
            notifyDetach(pojo, false);
            return obj;
         } catch (CacheException e)
  @@ -109,7 +125,7 @@
      {
         try
         {
  -         return cache_.getObject(id);
  +         return getObject(Fqn.fromString(id));
         } catch (CacheException e)
         {
            e.printStackTrace();  // TODO
  @@ -122,7 +138,7 @@
      {
         try
         {
  -         return cache_.findObjects(id);
  +         return findObjects(Fqn.fromString(id));
         } catch (CacheException e)
         {
            e.printStackTrace();  // TODO
  @@ -184,8 +200,96 @@
         return cache_;
      }
   
  +
  +   /********************************************************************************
  +    * Internal API for event notification
  +    ********************************************************************************/
  +
  +   public Object getObject(Fqn fqn) throws CacheException
  +   {
  +      return delegate_._getObject(fqn);
  +   }
  +
  +   public Object putObject(Fqn fqn, Object obj) throws CacheException
  +   {
  +      return delegate_._putObject(fqn, obj);
  +   }
  +
  +   public Object removeObject(Fqn fqn) throws CacheException
  +   {
  +      return _removeObject(fqn, true);
  +   }
  +
  +   public Map findObjects(Fqn fqn) throws CacheException
  +   {
  +      return delegate_._findObjects(fqn);
  +   }
  +
  +   /**
  +    * Used by internal implementation. Not for general public.
  +    */
  +   public Object _removeObject(Fqn fqn) throws CacheException
  +   {
  +      boolean removeCacheInterceptor = true;
  +      return _removeObject(fqn, removeCacheInterceptor);
  +   }
  +
  +   /**
  +    * Used by internal implementation. Not for general public.
  +    */
  +   public Object _removeObject(Fqn fqn, boolean removeCacheInterceptor) throws CacheException
  +   {
  +      boolean evict = false;
  +      return _removeObject(fqn, removeCacheInterceptor, evict);
  +   }
  +
  +   public Object _removeObject(Fqn fqn, boolean removeCacheInterceptor, boolean evict) throws CacheException
  +   {
  +      // Don't trigger bulk remove now since there is still some problem with Collection class
  +      // when it is detached.
  +      delegate_.setBulkRemove(true);
  +      return delegate_._removeObject(fqn, removeCacheInterceptor, evict);
  +   }
  +
  +   /**
  +    * Used by internal implementation. Not for general public.
  +    */
  +   public Object _evictObject(Fqn fqn) throws CacheException
  +   {
  +      boolean evict = true;
  +      boolean removeCacheInterceptor = false;
  +
  +      // Configurable option to see if we want to remove the cache interceptor when the pojo is
  +      // evicted.
  +//      if(detachPojoWhenEvicted_) removeCacheInterceptor = true;
  +      delegate_.setBulkRemove(false);
  +      return delegate_._removeObject(fqn, removeCacheInterceptor, evict);
  +   }
  +
  +   /**
  +    * Obtain a cache aop type for user to traverse the defined "primitive" types in aop.
  +    * Note that this is not a synchronized call now for speed optimization.
  +    *
  +    * @param clazz The original pojo class
  +    * @return CachedType
  +    */
  +   public synchronized CachedType getCachedType(Class clazz)
  +   {
  +      CachedType type = (CachedType) cachedTypes.get(clazz);
  +      if (type == null)
  +      {
  +         type = new CachedType(clazz);
  +         cachedTypes.put(clazz, type);
  +         return type;
  +      } else
  +      {
  +         return type;
  +      }
  +   }
  +
  +
      /********************************************************************************
  -    * Internal API
  +    * Internal API for event notification
       ********************************************************************************/
   
      /**
  
  
  
  1.1      date: 2006/07/13 15:56:12;  author: bwang;  state: Exp;JBossCache/src-50/org/jboss/cache/pojo/impl/CollectionClassHandler.java
  
  Index: CollectionClassHandler.java
  ===================================================================
  /*
   * JBoss, Home of Professional Open Source
   *
   * Distributable under LGPL license.
   * See terms of license at gnu.org.
   */
  
  package org.jboss.cache.pojo.impl;
  
  import org.apache.commons.logging.Log;
  import org.apache.commons.logging.LogFactory;
  import org.jboss.aop.advice.Interceptor;
  import org.jboss.aop.proxy.ClassProxy;
  import org.jboss.cache.CacheException;
  import org.jboss.cache.Fqn;
  import org.jboss.cache.pojo.interceptors.dynamic.AbstractCollectionInterceptor;
  import org.jboss.cache.pojo.collection.CollectionInterceptorUtil;
  import org.jboss.cache.pojo.interceptors.dynamic.BaseInterceptor;
  import org.jboss.cache.pojo.PojoTreeCache;
  import org.jboss.cache.pojo.CachedType;
  import org.jboss.cache.pojo.PojoReference;
  
  import java.util.Collection;
  import java.util.Iterator;
  import java.util.List;
  import java.util.Map;
  import java.util.Set;
  
  /**
   * Handling the Collection class management.
   *
   * @author Ben Wang
   *         Date: Aug 4, 2005
   * @version $Id: CollectionClassHandler.java,v 1.1 2006/07/13 15:56:12 bwang Exp $
   */
  class CollectionClassHandler
  {
     private final static Log log = LogFactory.getLog(CollectionClassHandler.class);
     private PojoTreeCache cache_;
     private PojoCacheImpl pCache_;
     private InternalHelper internal_;
     private ObjectGraphHandler graphHandler_;
  
     public CollectionClassHandler(PojoCacheImpl pCache, InternalHelper internal,
                                   ObjectGraphHandler graphHandler)
     {
        pCache_ = pCache;
        cache_ = (PojoTreeCache)pCache_.getCache();
        internal_ = internal;
        graphHandler_ = graphHandler;
     }
  
     Object collectionObjectGet(Fqn fqn, Class clazz)
             throws CacheException
     {
        Object obj = null;
        try
        {
           if (Map.class.isAssignableFrom(clazz))
           {
              Object map = clazz.newInstance();
              obj = CollectionInterceptorUtil.createMapProxy(pCache_, fqn, clazz, (Map) map);
           } else if (List.class.isAssignableFrom(clazz))
           {
              Object list = clazz.newInstance();
              obj = CollectionInterceptorUtil.createListProxy(pCache_, fqn, clazz, (List) list);
           } else if (Set.class.isAssignableFrom(clazz))
           {
              Object set = clazz.newInstance();
              obj = CollectionInterceptorUtil.createSetProxy(pCache_, fqn, clazz, (Set) set);
           }
        } catch (Exception e)
        {
           throw new CacheException("failure creating proxy", e);
        }
  
        return obj;
     }
  
  
     boolean collectionObjectPut(Fqn fqn, Object obj) throws CacheException
     {
        boolean isCollection = false;
  
        CachedType type = null;
        AbstractCollectionInterceptor interceptor = null;
        if (obj instanceof ClassProxy)
        {
           Class originalClaz = obj.getClass().getSuperclass();
           interceptor = CollectionInterceptorUtil.getInterceptor((ClassProxy) obj);
           type = pCache_.getCachedType(originalClaz);
        } else
        {
           type = pCache_.getCachedType(obj.getClass());
        }
  
        if (obj instanceof ClassProxy)
        {
           // A proxy here. We may have multiple references.
           if (interceptor == null)
           {
              if (log.isDebugEnabled())
              {
                 log.debug("collectionObjectPut(): null interceptor. Could be removed previously. " + fqn);
              }
           } else
           {
              if (interceptor.isAttached()) // If it is not attached, it is not active.
              {
                 // Let's check for object graph, e.g., multiple and circular references first
                 if (graphHandler_.objectGraphPut(fqn, interceptor, type))
                 { // found cross references
                    return true;
                 }
              } else
              {
                 // Re-attach the interceptor to this fqn.
                 boolean copyToCache = true;
                 interceptor.attach(fqn, copyToCache);
                 internal_.putAopClazz(fqn, type.getType());
                 internal_.setPojo(fqn, obj);
                 return true; // we are done
              }
           }
        }
  
        if (obj instanceof Map)
        {
           if (log.isDebugEnabled())
           {
              log.debug("collectionPutObject(): aspectized obj is a Map type of size: " + ((Map) obj).size());
           }
  
           internal_.putAopClazz(fqn, type.getType());
  
           // Let's replace it with a proxy if necessary
           Map map = (Map) obj;
           if (!(obj instanceof ClassProxy))
           {
              Class clazz = obj.getClass();
              try
              {
                 obj = CollectionInterceptorUtil.createMapProxy(pCache_, fqn, clazz, (Map) obj);
              } catch (Exception e)
              {
                 throw new CacheException("failure creating proxy", e);
              }
           }
  
           isCollection = true;
           // populate via the proxied collection
           for (Iterator i = map.entrySet().iterator(); i.hasNext();)
           {
              Map.Entry entry = (Map.Entry) i.next();
              ((Map) obj).put(entry.getKey(), entry.getValue());
           }
  
        } else if (obj instanceof List)
        {
           if (log.isDebugEnabled())
           {
              log.debug("collectionPutObject(): aspectized obj is a List type of size: "
                      + ((List) obj).size());
           }
  
           List list = (List) obj;
           internal_.putAopClazz(fqn, type.getType());
  
           // Let's replace it with a proxy if necessary
           if (!(obj instanceof ClassProxy))
           {
              Class clazz = obj.getClass();
              try
              {
                 obj = CollectionInterceptorUtil.createListProxy(pCache_, fqn, clazz, (List) obj);
              } catch (Exception e)
              {
                 throw new CacheException("failure creating proxy", e);
              }
           }
  
           isCollection = true;
           // populate via the proxied collection
           for (Iterator i = list.iterator(); i.hasNext();)
           {
              ((List) obj).add(i.next());
           }
  
        } else if (obj instanceof Set)
        {
           if (log.isDebugEnabled())
           {
              log.debug("collectionPutObject(): aspectized obj is a Set type of size: "
                      + ((Set) obj).size());
           }
  
           Set set = (Set) obj;
           internal_.putAopClazz(fqn, type.getType());
  
           // Let's replace it with a proxy if necessary
           if (!(obj instanceof ClassProxy))
           {
              Class clazz = obj.getClass();
              try
              {
                 obj = CollectionInterceptorUtil.createSetProxy(pCache_, fqn, clazz, (Set) obj);
              } catch (Exception e)
              {
                 throw new CacheException("failure creating proxy", e);
              }
           }
  
           isCollection = true;
           // populate via the proxied collection
           for (Iterator i = set.iterator(); i.hasNext();)
           {
              ((Set) obj).add(i.next());
           }
  
        }
  
        if (isCollection)
        {
           // Always initialize the ref count so that we can mark this as an AopNode.
           PojoReference pojoReference = InternalHelper.initializeAopInstance();
           cache_.put(fqn, PojoReference.KEY, pojoReference);
  
           // Attach pojoReference to that interceptor
           BaseInterceptor baseInterceptor = (BaseInterceptor) CollectionInterceptorUtil.getInterceptor(
                   (ClassProxy) obj);
           baseInterceptor.setAopInstance(pojoReference);
  
           InternalHelper.setPojo(pojoReference, obj);
        }
        return isCollection;
     }
  
     boolean collectionObjectRemove(Fqn fqn
     ) throws CacheException
     {
        Class clazz = internal_.peekAopClazz(fqn);
  
        if (!Map.class.isAssignableFrom(clazz) && !Collection.class.isAssignableFrom(clazz))
        {
           return false;
        }
  
        Object obj = pCache_.getObject(fqn);
        if (!(obj instanceof ClassProxy))
        {
           throw new RuntimeException("CollectionClassHandler.collectionRemoveObject(): object is not a proxy :" + obj);
        }
  
        Interceptor interceptor = CollectionInterceptorUtil.getInterceptor((ClassProxy) obj);
        boolean removeFromCache = true;
        ((AbstractCollectionInterceptor) interceptor).detach(removeFromCache); // detach the interceptor. This will trigger a copy and remove.
  
        return true;
     }
  }
  
  
  
  1.1      date: 2006/07/13 15:56:12;  author: bwang;  state: Exp;JBossCache/src-50/org/jboss/cache/pojo/impl/InternalConstant.java
  
  Index: InternalConstant.java
  ===================================================================
  /*
   * JBoss, Home of Professional Open Source
   *
   * Distributable under LGPL license.
   * See terms of license at gnu.org.
   */
  
  package org.jboss.cache.pojo.impl;
  
  import org.jboss.cache.Fqn;
  
  /**
   * Internal helper class to handle internal cache sotre, that is, the portion that is not part of
   * user's data.
   *
   * @author Ben Wang
   */
  public class InternalConstant
  {
     public static final String CLASS_INTERNAL = "__jboss:internal:class__";
     public static final String SERIALIZED = "__SERIALIZED__";
     public static final Fqn JBOSS_INTERNAL = new Fqn("__JBossInternal__");
     public static final Fqn JBOSS_INTERNAL_MAP = new Fqn(InternalConstant.JBOSS_INTERNAL, "__RefMap__");
  }
  
  
  
  1.1      date: 2006/07/13 15:56:12;  author: bwang;  state: Exp;JBossCache/src-50/org/jboss/cache/pojo/impl/InternalHelper.java
  
  Index: InternalHelper.java
  ===================================================================
  /*
   * JBoss, the OpenSource J2EE webOS
   *
   * Distributable under LGPL license.
   * See terms of license at gnu.org.
   */
  package org.jboss.cache.pojo.impl;
  
  import org.apache.commons.logging.Log;
  import org.apache.commons.logging.LogFactory;
  import org.jboss.cache.CacheException;
  import org.jboss.cache.DataNode;
  import org.jboss.cache.Fqn;
  import org.jboss.cache.config.Option;
  import org.jboss.cache.pojo.util.ObjectUtil;
  import org.jboss.cache.pojo.PojoTreeCache;
  import org.jboss.cache.pojo.PojoReference;
  
  import java.util.Map;
  
  /**
   * Internal helper class to handle internal cache sotre, that is, the portion that is not part of
   * user's data.
   *
   * @author Ben Wang
   */
  public class InternalHelper
  {
     private static Log log = LogFactory.getLog(InternalHelper.class.getName());
     // This is an optimization flag to skip put lock when we are sure that it has been locked from
     // putObject. However, if later on there are transactional field updates, then we we will need
     // this off to protected the write lock.
     private boolean cacheOperationSkipLocking = true;
     private Option skipLockOption_;
     private Option gravitateOption_;
     private Option localModeOption_;
  
     private PojoTreeCache cache_;
  
     InternalHelper(PojoTreeCache cache)
     {
        cache_ = cache;
  
        skipLockOption_ = new Option();
        if (cacheOperationSkipLocking)
        {
           skipLockOption_.setSuppressLocking(true);
        } else
        {
           skipLockOption_.setSuppressLocking(false);
        }
  
        localModeOption_ = new Option();
        localModeOption_.setCacheModeLocal(true);
  
        gravitateOption_ = new Option();
        gravitateOption_.setForceDataGravitation(true);
     }
  
     Option getLockOption()
     {
        return skipLockOption_;
     }
  
     PojoReference getAopInstance(Fqn fqn) throws CacheException
     {
        // Not very efficient now since we are peeking every single time.
        // Should have cache it without going to local cache.
        return (PojoReference) get(fqn, PojoReference.KEY, false);
     }
  
     private PojoReference getAopInstanceWithGravitation(Fqn fqn) throws CacheException
     {
        // Not very efficient now since we are peeking every single time.
        // Should have cache it without going to local cache.
        return (PojoReference) get(fqn, PojoReference.KEY, true);
     }
  
     static PojoReference initializeAopInstance()
     {
        PojoReference pojoReference = new PojoReference();
  
        pojoReference.incrementRefCount(null);
        return pojoReference;
     }
  
     /**
      * Increment reference count for the pojo. Note that this is not thread safe or atomic.
      */
     int incrementRefCount(Fqn originalFqn, Fqn referencingFqn) throws CacheException
     {
        PojoReference pojoReference = getAopInstance(originalFqn);
        if (pojoReference == null)
           throw new RuntimeException("InternalDelegate.incrementRefCount(): null pojoReference for fqn: " + originalFqn);
  
        int count = pojoReference.incrementRefCount(referencingFqn);
        // need to update it.
        put(originalFqn, PojoReference.KEY, pojoReference);
        return count;
     }
  
     /**
      * Has a delegate method so we can use the switch.
      */
  
     Object get(Fqn fqn, Object key) throws CacheException
     {
        return get(fqn, key, false);
     }
  
     private Object get(Fqn fqn, Object key, boolean gravitate) throws CacheException
     {
        // TODO let's find a better way to decouple this.
        if (gravitate && cache_.getBuddyManager() != null)
        {
           return cache_.get(fqn, key, gravitateOption_);
        } else if (cache_.getCacheLoader() != null)
        {
           // We have cache loader, we can't get it directly from the local get.
           return cache_.get(fqn, key, skipLockOption_);
        } else
        {
           return cache_._get(fqn, key, false);
        }
     }
  
     private void put(Fqn fqn, Object key, Object value) throws CacheException
     {
        // Use option to ski locking since we have parent lock already.
        cache_.put(fqn, key, value, skipLockOption_);
  //      cache_.put(fqn, key, value);
     }
  
     void put(Fqn fqn, Map map) throws CacheException
     {
        // Use option to ski locking since we have parent lock already.
        cache_.put(fqn, map, skipLockOption_);
  //      cache_.put(fqn, key, value);
     }
  
     protected void localPut(Fqn fqn, Object key, Object value) throws CacheException
     {
        // Use option to ski locking since we have parent lock already.
        // TODO Need to make sure there is no tx here otherwise it won't work.
        cache_.put(fqn, key, value, localModeOption_);
     }
  
  
     /**
      * decrement reference count for the pojo. Note that this is not thread safe or atomic.
      */
     int decrementRefCount(Fqn originalFqn, Fqn referencingFqn) throws CacheException
     {
        PojoReference pojoReference = getAopInstance(originalFqn);
        if (pojoReference == null)
           throw new RuntimeException("InternalDelegate.decrementRefCount(): null pojoReference.");
  
        int count = pojoReference.decrementRefCount(referencingFqn);
  
        if (count < -1)  // can't dip below -1
           throw new RuntimeException("InternalDelegate.decrementRefCount(): null pojoReference.");
  
        // need to update it.
        put(originalFqn, PojoReference.KEY, pojoReference);
        return count;
     }
  
     static boolean isReferenced(PojoReference pojoReference)
     {
        // If ref counter is greater than 0, we fqn is being referenced.
        return (pojoReference.getRefCount() > 0);
     }
  
     int getRefCount(Fqn fqn) throws CacheException
     {
        return getAopInstance(fqn).getRefCount();
     }
  
     String getRefFqn(Fqn fqn) throws CacheException
     {
        PojoReference pojoReference = getAopInstance(fqn);
        return getRefFqn(pojoReference);
     }
  
     String getRefFqn(PojoReference pojoReference) throws CacheException
     {
        if (pojoReference == null)
           return null;
  
        String aliasFqn = pojoReference.getInternalFqn();
  
        if (aliasFqn == null || aliasFqn.length() == 0) return null;
  
        return getRefFqnFromAlias(aliasFqn);
     }
  
     void setRefFqn(Fqn fqn, String internalFqn) throws CacheException
     {
        PojoReference pojoReference = getAopInstance(fqn);
        if (pojoReference == null)
           pojoReference = new PojoReference();
  
        pojoReference.setInternalFqn(internalFqn);
        put(fqn, PojoReference.KEY, pojoReference);
     }
  
     void removeRefFqn(Fqn fqn) throws CacheException
     {
        PojoReference pojoReference = getAopInstance(fqn);
        if (pojoReference == null)
           throw new RuntimeException("InternalDelegate.getInternalFqn(): null pojoReference.");
  
        pojoReference.removeInternalFqn();
        put(fqn, PojoReference.KEY, pojoReference);
     }
  
     Object getPojo(Fqn fqn) throws CacheException
     {
        PojoReference pojoReference = getAopInstance(fqn);
        if (pojoReference == null)
           return null;
  
        return pojoReference.get();
     }
  
     Object getPojoWithGravitation(Fqn fqn) throws CacheException
     {
        // This is for buddy replication
        PojoReference pojoReference = getAopInstanceWithGravitation(fqn);
        if (pojoReference == null)
           return null;
  
        return pojoReference.get();
     }
  
     void setPojo(Fqn fqn, Object pojo) throws CacheException
     {
        PojoReference pojoReference = getAopInstance(fqn);
        if (pojoReference == null)
        {
           pojoReference = new PojoReference();
           put(fqn, PojoReference.KEY, pojoReference);
        }
  
        pojoReference.set(pojo);
        // No need to do a cache put since pojo is transient anyway.
     }
  
     static void setPojo(PojoReference pojoReference, Object pojo)
     {
        // No need to do a cache put since pojo is transient anyway.
        pojoReference.set(pojo);
     }
  
     void setPojo(Fqn fqn, Object pojo, PojoReference pojoReference) throws CacheException
     {
        if (pojoReference == null)
        {
           pojoReference = new PojoReference();
           put(fqn, PojoReference.KEY, pojoReference);
        }
  
        pojoReference.set(pojo);
        // No need to do a cache put since pojo is transient anyway.
     }
  
     /**
      * We store the class name in string.
      */
     void putAopClazz(Fqn fqn, Class clazz) throws CacheException
     {
        put(fqn, InternalConstant.CLASS_INTERNAL, clazz);
     }
  
     /**
      * We store the class name in string and put it in map instead of directly putting
      * it into cache for optimization.
      */
     static void putAopClazz(Class clazz, Map map)
     {
        map.put(InternalConstant.CLASS_INTERNAL, clazz);
     }
  
     Class peekAopClazz(Fqn fqn) throws CacheException
     {
        return (Class) get(fqn, InternalConstant.CLASS_INTERNAL);
     }
  
     void removeInternalAttributes(Fqn fqn) throws CacheException
     {
        cache_.remove(fqn, PojoReference.KEY);
        cache_.remove(fqn, InternalConstant.CLASS_INTERNAL);
     }
  
     void cleanUp(Fqn fqn, boolean evict) throws CacheException
     {
        // We can't do a brute force remove anymore?
        if (!evict)
        {
           if (!cache_._get(fqn).hasChildren())
           {
              // remove everything
              cache_.remove(fqn);
           } else
           {
              // Assume everything here is all PojoCache data for optimization
              cache_.removeData(fqn);
              if (log.isTraceEnabled())
              {
                 log.trace("cleanup(): fqn: " + fqn + " is not empty. That means it has sub-pojos. Will not remove node");
              }
           }
        } else
        {
           // This has to use plainEvict method otherwise it is recursively calling aop version of evict.
  //         cache_.plainEvict(fqn);
        }
     }
  
     String createIndirectFqn(String fqn) throws CacheException
     {
        String indirectFqn = getIndirectFqn(fqn);
        Fqn internalFqn = getInternalFqn(fqn);
        put(internalFqn, indirectFqn, fqn);
        return indirectFqn;
     }
  
     private Fqn getInternalFqn(String fqn)
     {
        if (fqn == null || fqn.length() == 0)
           throw new IllegalStateException("InternalDelegate.getInternalFqn(). fqn is either null or empty!");
  
        String indirectFqn = getIndirectFqn(fqn);
        return new Fqn(InternalConstant.JBOSS_INTERNAL_MAP, indirectFqn);
  //      return JBOSS_INTERNAL_MAP;
     }
  
     static String getIndirectFqn(String fqn)
     {
        // TODO This is not unique. Will need to come up with a better one in the future.
        return ObjectUtil.getIndirectFqn(fqn);
     }
  
     void removeIndirectFqn(String oldFqn) throws CacheException
     {
        String indirectFqn = getIndirectFqn(oldFqn);
        cache_.remove(getInternalFqn(oldFqn), indirectFqn);
     }
  
     void setIndirectFqn(String oldFqn, String newFqn) throws CacheException
     {
        String indirectFqn = getIndirectFqn(oldFqn);
        Fqn tmpFqn = getInternalFqn(oldFqn);
        if (cache_.exists(tmpFqn, indirectFqn)) // No need to update if it doesn't exist.
        {
           put(tmpFqn, indirectFqn, newFqn);
        }
     }
  
     void updateIndirectFqn(Fqn originalFqn, Fqn newFqn) throws CacheException
     {
        put(getInternalFqn(originalFqn.toString()), getIndirectFqn(originalFqn.toString()), newFqn.toString());
     }
  
     private String getRefFqnFromAlias(String aliasFqn) throws CacheException
     {
        return (String) get(getInternalFqn(aliasFqn), aliasFqn, true);
     }
  
     Fqn getNextFqnInLine(Fqn currentFqn) throws CacheException
     {
        PojoReference ai = getAopInstance(currentFqn);
        return ai.getAndRemoveFirstFqnInList();
     }
  
     void relocate(Fqn thisFqn, Fqn newFqn) throws CacheException
     {
        /**
         DataNode node = cache_.get(thisFqn);
         DataNode newParent = (DataNode)cache_.get(newFqn).getParent();
         node.relocate(newParent, newFqn); // relocation
         updateIndirectFqn(thisFqn, newFqn);
         */
  
        // Let's do cache-wide copy then. It won't be fast and atomic but
        // at least it preserves the pojo structure and also do replication
        // TODO Can TreeCache provide a method to do this??
  
        // First do a recursive copy using the new base fqn
        DataNode node = cache_.get(thisFqn);
        Map value = node.getData();
        cache_.put(newFqn, value);
  
        Map children = node.getChildren();
        if (children == null || children.size() == 0)
        {
           cache_.remove(thisFqn);
           return; // we are done
        }
  
        for (Object key : children.keySet())
        {
           Fqn thisChildFqn = new Fqn(thisFqn, key);
           Fqn newChildFqn = new Fqn(newFqn, key);
           relocate(thisChildFqn, newChildFqn);
        }
  
        // Finally do a remove
        cache_.remove(thisFqn);
     }
  
     /**
      * Test if this internal node.
      *
      * @param fqn
      */
     public static boolean isInternalNode(Fqn fqn)
     {
        // we ignore all the node events corresponding to JBOSS_INTERNAL
        if (fqn.isChildOrEquals(InternalConstant.JBOSS_INTERNAL)) return true;
  
        return false;
     }
  }
  
  
  
  1.1      date: 2006/07/13 15:56:12;  author: bwang;  state: Exp;JBossCache/src-50/org/jboss/cache/pojo/impl/ObjectGraphHandler.java
  
  Index: ObjectGraphHandler.java
  ===================================================================
  /*
   * JBoss, Home of Professional Open Source
   *
   * Distributable under LGPL license.
   * See terms of license at gnu.org.
   */
  
  package org.jboss.cache.pojo.impl;
  
  import org.apache.commons.logging.Log;
  import org.apache.commons.logging.LogFactory;
  import org.jboss.aop.Advised;
  import org.jboss.aop.InstanceAdvisor;
  import org.jboss.aop.advice.Interceptor;
  import org.jboss.cache.CacheException;
  import org.jboss.cache.Fqn;
  import org.jboss.cache.pojo.interceptors.dynamic.AbstractCollectionInterceptor;
  import org.jboss.cache.pojo.util.AopUtil;
  import org.jboss.cache.pojo.interceptors.dynamic.BaseInterceptor;
  import org.jboss.cache.pojo.interceptors.dynamic.CacheFieldInterceptor;
  import org.jboss.cache.pojo.PojoTreeCache;
  import org.jboss.cache.pojo.CachedType;
  import org.jboss.cache.pojo.PojoReference;
  
  /**
   * Handle the object graph management.
   *
   * @author Ben Wang
   *         Date: Aug 4, 2005
   * @version $Id: ObjectGraphHandler.java,v 1.1 2006/07/13 15:56:12 bwang Exp $
   */
  class ObjectGraphHandler
  {
     private PojoTreeCache cache_;
     private PojoCacheImpl pCache_;
     private InternalHelper internal_;
     private final static Log log = LogFactory.getLog(ObjectGraphHandler.class);
  
     public ObjectGraphHandler(PojoCacheImpl cache, InternalHelper internal)
     {
        pCache_ = cache;
        cache_ = (PojoTreeCache)pCache_.getCache();
        internal_ = internal;
     }
  
     Object objectGraphGet(Fqn fqn) throws CacheException
     {
        // Note this is actually the aliasFqn, not the real fqn!
        String refFqn = internal_.getRefFqn(fqn);
        Object obj;
        if (refFqn != null)
        {
           // this is recursive. Need to obtain the object from parent fqn
           // No need to add CacheFieldInterceptor as a result. Everything is re-directed.
           // In addition, this op will not be recursive.
           if (log.isDebugEnabled())
           {
              log.debug("getObject(): obtain value from reference fqn: " + refFqn);
           }
           obj = pCache_.getObject(Fqn.fromString(refFqn));
           if (obj == null)
              throw new RuntimeException("ObjectGraphHandler.objectGraphGet(): null object from internal ref node." +
                      " Original fqn: " + fqn + " Internal ref node: " + refFqn);
  
           return obj; // No need to set the instance under fqn. It is located in refFqn anyway.
        }
  
        return null;
     }
  
     boolean objectGraphPut(Fqn fqn, Interceptor interceptor, CachedType type) throws CacheException
     {
        Fqn originalFqn = null;
  
        if (interceptor instanceof AbstractCollectionInterceptor)
        {
           // Special case for Collection class. If it is detached, we don't care.
           if (!((AbstractCollectionInterceptor) interceptor).isAttached())
           {
              return false;
           }
        }
        // ah, found something. So this will be multiple referenced.
        originalFqn = ((BaseInterceptor) interceptor).getFqn();
  
        if (originalFqn == null) return false;
  
        if (log.isDebugEnabled())
        {
           log.debug("handleObjectGraph(): fqn: " + fqn + " and " + originalFqn + " share the object.");
        }
  
        // This will increment the ref count, reset, and add ref fqn in the current fqn node.
        setupRefCounting(fqn, originalFqn);
        internal_.putAopClazz(fqn, type.getType());
        return true;
     }
  
     boolean objectGraphRemove(Fqn fqn, boolean removeCacheInterceptor, Object pojo, boolean evict)
             throws CacheException
     {
        boolean isTrue = false;
  
        // Note this is actually the aliasFqn, not the real fqn!
        PojoReference pojoReference = internal_.getAopInstance(fqn);
        String refFqn = internal_.getRefFqn(pojoReference);
        // check if this is a refernce
        if (refFqn != null)
        {
           if (log.isDebugEnabled())
           {
              log.debug("objectGraphRemove(): removing object fqn: " + fqn + " but is actually from ref fqn: " + refFqn
                      + " Will just de-reference it.");
           }
           removeFromReference(fqn, refFqn, removeCacheInterceptor, evict);
           internal_.cleanUp(fqn, evict);
           isTrue = true;
        } else
        {
           if (InternalHelper.isReferenced(pojoReference))
           {
              // This node is currently referenced by others. We will relocate it to the next in line,
              // and update the indirectFqnMap
  
              // First decrement counter.
              decrementRefCount(fqn, null);
              // Determine where to move first.
              Fqn newFqn = internal_.getNextFqnInLine(fqn);
              // Is newFqn is child of fqn?
              if (newFqn.isChildOf(fqn))
              {
                 // Take out the child fqn reference to me.
                 internal_.removeRefFqn(newFqn);
  
                 if (log.isDebugEnabled())
                 {
                    log.debug("objectGraphRemove(): this node " + fqn + " is currently referenced by a cyclic reference: "
                            + newFqn + "Will only decrement reference count.");
                 }
              } else
              {
                 // Relocate all the contents from old to the new fqn
                 internal_.relocate(fqn, newFqn);
                 // Reset the fqn in the cache interceptor
                 InstanceAdvisor advisor = ((Advised) pojo)._getInstanceAdvisor();
                 CacheFieldInterceptor interceptor = (CacheFieldInterceptor) AopUtil.findCacheInterceptor(advisor);
                 if (interceptor == null)
                    throw new IllegalStateException("ObjectGraphHandler.objectGraphRemove(): null interceptor");
                 interceptor.setFqn(newFqn);
                 // reset the fqn in the indirect fqn map
                 internal_.setIndirectFqn(fqn.toString(), newFqn.toString());
  
                 isTrue = true;
  
                 if (log.isDebugEnabled())
                 {
                    log.debug("objectGraphRemove(): this node " + fqn + " is currently referenced by " +
                            +internal_.getRefCount(newFqn) +
                            " other pojos after relocating to " + newFqn.toString());
                 }
              }
           }
        }
  
        return isTrue;
     }
  
     /**
      * Remove the object from the the reference fqn, meaning just decrement the ref counter.
      *
      * @param fqn
      * @param refFqn
      * @param removeCacheInterceptor
      * @param evict
      * @throws CacheException
      */
     private void removeFromReference(Fqn fqn, String refFqn, boolean removeCacheInterceptor,
                                      boolean evict) throws CacheException
     {
        synchronized (refFqn)
        {  // we lock the internal fqn here so no one else has access.
           // Decrement ref counting on the internal node
           if (decrementRefCount(Fqn.fromString(refFqn), fqn) == PojoReference.INITIAL_COUNTER_VALUE)
           {
              // No one is referring it so it is safe to remove
              // TODO we should make sure the parent nodes are also removed they are empty as well.
              pCache_._removeObject(Fqn.fromString(refFqn), removeCacheInterceptor, evict);
           }
        }
  
        // Remove ref fqn from this fqn
        internal_.removeRefFqn(fqn);
     }
  
     /**
      * 1. increment reference counter
      * 2. put in refFqn so we can get it.
      *
      * @param fqn    The original fqn node
      * @param refFqn The new internal fqn node
      */
     private void setupRefCounting(Fqn fqn, Fqn refFqn) throws CacheException
     {
        synchronized (refFqn)
        { // we lock the ref fqn here so no one else has access.
           // increment the reference counting
           String aliasFqn = null;
           if (incrementRefCount(refFqn, fqn) == 1)
           {
              // We have the first multiple reference
              aliasFqn = internal_.createIndirectFqn(refFqn.toString());
           } else
           {
              aliasFqn = InternalHelper.getIndirectFqn(refFqn.toString());
           }
           // set the internal fqn in fqn so we can reference it.
           if (log.isTraceEnabled())
           {
              log.trace("setupRefCounting(): current fqn: " + fqn + " set to point to: " + refFqn);
           }
  
           internal_.setRefFqn(fqn, aliasFqn);
        }
     }
  
     private int incrementRefCount(Fqn originalFqn, Fqn referencingFqn) throws CacheException
     {
        return internal_.incrementRefCount(originalFqn, referencingFqn);
     }
  
     private int decrementRefCount(Fqn originalFqn, Fqn referencingFqn) throws CacheException
     {
        int count = 0;
        if ((count = internal_.decrementRefCount(originalFqn, referencingFqn)) == (PojoReference.INITIAL_COUNTER_VALUE + 1))
        {
           internal_.removeIndirectFqn(originalFqn.toString());
        }
  
        return count;
     }
  }
  
  
  
  1.1      date: 2006/07/13 15:56:12;  author: bwang;  state: Exp;JBossCache/src-50/org/jboss/cache/pojo/impl/PojoCacheDelegate.java
  
  Index: PojoCacheDelegate.java
  ===================================================================
  /*
   * JBoss, the OpenSource J2EE webOS
   *
   * Distributable under LGPL license.
   * See terms of license at gnu.org.
   */
  package org.jboss.cache.pojo.impl;
  
  import org.apache.commons.logging.Log;
  import org.apache.commons.logging.LogFactory;
  import org.jboss.aop.Advised;
  import org.jboss.aop.Advisor;
  import org.jboss.aop.ClassInstanceAdvisor;
  import org.jboss.aop.InstanceAdvisor;
  import org.jboss.aop.advice.Interceptor;
  import org.jboss.aop.proxy.ClassProxy;
  import org.jboss.cache.CacheException;
  import org.jboss.cache.Fqn;
  import org.jboss.cache.pojo.interceptors.dynamic.AbstractCollectionInterceptor;
  import org.jboss.cache.pojo.memory.FieldPersistentReference;
  import org.jboss.cache.pojo.util.AopUtil;
  import org.jboss.cache.pojo.interceptors.dynamic.BaseInterceptor;
  import org.jboss.cache.pojo.interceptors.dynamic.CacheFieldInterceptor;
  import org.jboss.cache.pojo.observable.Observer;
  import org.jboss.cache.pojo.PojoTreeCache;
  import org.jboss.cache.pojo.PojoUtil;
  import org.jboss.cache.pojo.CachedType;
  import org.jboss.cache.pojo.PojoReference;
  
  import java.lang.reflect.Field;
  import java.util.Collection;
  import java.util.HashMap;
  import java.util.Iterator;
  import java.util.List;
  import java.util.Map;
  import java.util.Set;
  
  /**
   * Delegate class for PojoCache, the real implementation code happens here.
   *
   * @author Ben Wang
   */
  public class PojoCacheDelegate
  {
     private PojoCacheImpl pCache_;
     private PojoTreeCache cache_;
     private final static Log log = LogFactory.getLog(PojoCacheDelegate.class);
     private InternalHelper internal_;
     private ObjectGraphHandler graphHandler_;
     private CollectionClassHandler collectionHandler_;
     private SerializableObjectHandler serializableHandler_;
     // Use ThreadLocal to hold a boolean isBulkRemove
     private ThreadLocal<Boolean> bulkRemove_ = new ThreadLocal<Boolean>();
     private final String DETACH = "DETACH";
     private PojoUtil util_ = new PojoUtil();
     // Observer for field event notification
     private Observer observer_;
  
     public PojoCacheDelegate(PojoCacheImpl cache, Observer observer)
     {
        pCache_ = cache;
        cache_ = (PojoTreeCache)pCache_.getCache();
        internal_ = new InternalHelper(cache_);
        graphHandler_ = new ObjectGraphHandler(pCache_, internal_);
        collectionHandler_ = new CollectionClassHandler(pCache_, internal_, graphHandler_);
        serializableHandler_ = new SerializableObjectHandler(pCache_, internal_);
        observer_ = observer;
     }
  
     public void setBulkRemove(boolean bulk)
     {
        bulkRemove_.set(Boolean.valueOf(bulk));
     }
  
     private boolean getBulkRemove()
     {
        return ((Boolean) bulkRemove_.get()).booleanValue();
     }
  
     Object _getObject(Fqn fqn) throws CacheException
     {
        // TODO Must we really to couple with BR? JBCACHE-669
        Object pojo = internal_.getPojoWithGravitation(fqn);
        if (pojo != null)
        {
           // we already have an advised instance
           return pojo;
        }
  
        // OK. So we are here meaning that this is a failover or passivation since the transient
        // pojo instance is not around. Let's also make sure the right classloader is used
        // as well.
        ClassLoader prevCL = Thread.currentThread().getContextClassLoader();
        try
        {
           if (cache_.getRegionManager() != null)
           {
              cache_.getRegionManager().setUnmarshallingClassLoader(fqn);
           }
           return _getObjectInternal(fqn);
        }
        finally
        {
           Thread.currentThread().setContextClassLoader(prevCL);
        }
     }
  
     private Object _getObjectInternal(Fqn fqn) throws CacheException
     {
        // the class attribute is implicitly stored as an immutable read-only attribute
        Class clazz = internal_.peekAopClazz(fqn);
        //  clazz and pojoReference can be not null if this node is the replicated brother node.
        if (clazz == null)
           return null;
  
        /**
         * Reconstruct the managed POJO
         */
        CachedType type = pCache_.getCachedType(clazz);
        Object obj;
  
        // Check for both Advised and Collection classes for object graph.
        if ((obj = graphHandler_.objectGraphGet(fqn)) != null)
           return obj; // retrieved from internal ref node. We are done.
  
        PojoReference pojoReference = internal_.getAopInstance(fqn);
        if (pojoReference == null)
        {
           throw new RuntimeException("PojoCacheDelegate._getObject(): null PojoReference.");
        }
  
        if (Advised.class.isAssignableFrom(clazz))
        {
           try
           {
              obj = clazz.newInstance();
              // TODO Need to populate the object from the cache as well.
           }
           catch (Exception e)
           {
              throw new CacheException("failed creating instance of " + clazz.getName(), e);
           }
           // Insert interceptor at runtime
           InstanceAdvisor advisor = ((Advised) obj)._getInstanceAdvisor();
           CacheFieldInterceptor interceptor = new CacheFieldInterceptor(pCache_, fqn, type);
           interceptor.setAopInstance(pojoReference);
           util_.attachInterceptor(obj, advisor, interceptor, observer_);
        } else
        { // Must be Collection classes. We will use aop.ClassProxy instance instead.
           try
           {
              if ((obj = collectionHandler_.collectionObjectGet(fqn, clazz)) != null)
              {
              } else
              {
                 // Maybe it is just a serialized object.
                 obj = serializableHandler_.serializableObjectGet(fqn);
              }
           }
           catch (Exception e)
           {
              throw new CacheException("failure creating proxy", e);
           }
        }
  
        InternalHelper.setPojo(pojoReference, obj);
        return obj;
     }
  
     /**
      * Note that caller of this method will take care of synchronization within the <code>fqn</code> sub-tree.
      *
      * @param fqn
      * @param obj
      * @return
      * @throws CacheException
      */
     Object _putObject(Fqn fqn, Object obj) throws CacheException
     {
        if (obj == null)
        {
           return pCache_._removeObject(fqn, true);
        }
        // Skip some un-necessary update if obj is the same class as the old one
        Object oldValue = internal_.getPojo(fqn);
        if (oldValue == obj) return obj;  // value already in cache. return right away.
  
        if (oldValue != null)
        {
           // Trigger bulk remove here for performance
           setBulkRemove(true);
           pCache_._removeObject(fqn, true); // remove old value before overwriting it.
        }
  
        // Remember not to print obj here since it will trigger the CacheFieldInterceptor.
        if (log.isDebugEnabled())
        {
           log.debug("putObject(): fqn: " + fqn);
        }
  
        // store object in cache
        if (obj instanceof Advised)
        {
           CachedType type = pCache_.getCachedType(obj.getClass());
           // add interceptor
           InstanceAdvisor advisor = ((Advised) obj)._getInstanceAdvisor();
           if (advisor == null)
              throw new RuntimeException("_putObject(): InstanceAdvisor is null for: " + obj);
  
           // Step Check for cross references
           Interceptor interceptor = AopUtil.findCacheInterceptor(advisor);
           if (interceptor != null && graphHandler_.objectGraphPut(fqn, interceptor, type))
           { // found cross references
              return oldValue;
           }
  
           // We have a clean slate then.
           _regularPutObject(fqn, obj, advisor, type);
  
           /**
            * Handling collection classes here.
            * First check if obj has been aspectized? That is, if it is a ClassProxy or not.
            * If not, we will need to create a proxy first for the Collection classes
            */
        } else if (collectionHandler_.collectionObjectPut(fqn, obj))
        {
           //
        } else if (serializableHandler_.serializableObjectPut(fqn, obj))
        {
           // must be Serializable, including primitive types
        } else
        {
           // I really don't know what this is.
           throw new RuntimeException("putObject(): obj: " + obj + " type is not recognizable.");
        }
  
        return oldValue;
     }
  
     /**
      * Based on the pojo to perform a bulk remove recursively if there is no object graph
      * relationship for performance optimization.
      */
     private boolean bulkRemove(Fqn fqn, Object obj) throws CacheException
     {
        // Check for cross-reference. If there is, we can't do bulk remove
        // map contains (pojo, cacheinterceptor) pair that needs to undo the the removal.
  //      return false;
        Map undoMap = new HashMap();
        if (pojoGraphMultipleReferenced(obj, undoMap))
        {
           undoInterceptorDetach(undoMap);
           return false;
        } else
        {
           cache_.remove(fqn); // interceptor has been removed so it is safe to do bulk remove now.
        }
        return true;
     }
  
     private void detachInterceptor(InstanceAdvisor advisor, Interceptor interceptor,
                                    boolean detachOnly, Map undoMap)
     {
        if (!detachOnly)
        {
           util_.detachInterceptor(advisor, interceptor, observer_);
           undoMap.put(advisor, interceptor);
        } else
        {
           undoMap.put(DETACH, interceptor);
        }
     }
  
     private static void undoInterceptorDetach(Map undoMap)
     {
        for (Iterator it = undoMap.keySet().iterator(); it.hasNext();)
        {
           Object obj = it.next();
  
           if (obj instanceof InstanceAdvisor)
           {
              InstanceAdvisor advisor = (InstanceAdvisor) obj;
              BaseInterceptor interceptor = (BaseInterceptor) undoMap.get(advisor);
  
              if (interceptor == null)
              {
                 throw new IllegalStateException("PojoCacheDelegate.undoInterceptorDetach(): null interceptor");
              }
  
              advisor.appendInterceptor(interceptor);
           } else
           {
              BaseInterceptor interceptor = (BaseInterceptor) undoMap.get(obj);
              boolean copyToCache = false;
              ((AbstractCollectionInterceptor) interceptor).attach(null, copyToCache);
           }
        }
     }
  
     /**
      * Check recursively if the pojo and its graph is multiple referenced. If it is, we can't
      * do a bulk remove.
      */
     private boolean pojoGraphMultipleReferenced(Object obj, Map undoMap) throws CacheException
     {
        // store object in cache
        if (obj instanceof Advised)
        {
           CachedType type = pCache_.getCachedType(obj.getClass());
           // add interceptor
           InstanceAdvisor advisor = ((Advised) obj)._getInstanceAdvisor();
           if (advisor == null)
              throw new RuntimeException("pojoGraphMultipleReferenced(): InstanceAdvisor is null for: " + obj);
  
           BaseInterceptor interceptor = (BaseInterceptor) AopUtil.findCacheInterceptor(advisor);
           // just in case
           if (interceptor == null)
           {
              return false;
           }
           PojoReference pojoReference = interceptor.getAopInstance();
           // Check if there is cross referenced.
           if (pojoReference.getRefCount() != 0) return true; // I have been referenced
           if (pojoReference.getInternalFqn() != null) return true; // I am referencing others
  
           boolean hasFieldAnnotation = hasAnnotation(obj.getClass(), ((Advised) obj)._getAdvisor(), type);
           // Check the fields
           for (Iterator i = type.getFields().iterator(); i.hasNext();)
           {
              Field field = (Field) (((FieldPersistentReference) i.next())).get();
              Object value = null;
              try
              {
                 value = field.get(obj);
              }
              catch (IllegalAccessException e)
              {
                 throw new CacheException("field access failed", e);
              }
  
              CachedType fieldType = pCache_.getCachedType(field.getType());
  
              // we simply treat field that has @Serializable as a primitive type.
              if (fieldType.isImmediate() ||
                      (hasFieldAnnotation &&
                              CachedType.hasSerializableAnnotation(field, ((Advised) obj)._getAdvisor())))
              {
                 continue;
              }
  
              // check for non-replicatable types
              if (CachedType.isPrimitiveNonReplicatable(field))
              {
                 continue;
              }
  
              if (!hasFieldAnnotation)
              {
                 if (CachedType.hasTransientAnnotation(field, ((Advised) obj)._getAdvisor()))
                 {
                    continue;
                 }
              }
  
              // Need to do a getObject just in case this is a failover removeObject.
              if (value == null)
                 value = _getObject(new Fqn(interceptor.getFqn(), field.getName()));
  
              if (value == null) continue; // this is no brainer.
  
              if (pojoGraphMultipleReferenced(value, undoMap)) return true;
           }
           boolean detachOnly = false;
           detachInterceptor(advisor, interceptor, detachOnly, undoMap);
        } else if (obj instanceof Map || obj instanceof List || obj instanceof Set)
        {
           // TODO Is this really necessary?
           if (!(obj instanceof ClassProxy)) return false;
  
           InstanceAdvisor advisor = ((ClassProxy) obj)._getInstanceAdvisor();
           BaseInterceptor interceptor = (BaseInterceptor) AopUtil.findCollectionInterceptor(advisor);
           PojoReference pojoReference = interceptor.getAopInstance();
           if (pojoReference == null) return false; // safeguard
           // Check if there is cross referenced.
           if (pojoReference.getRefCount() != 0) return true; // I have been referenced
           if (pojoReference.getInternalFqn() != null) return true; // I am referencing others
           // iterate thru the keys
           if (obj instanceof Map)
           {
              for (Iterator it = ((Map) obj).keySet().iterator(); it.hasNext();)
              {
                 Object subObj = ((Map) obj).get(it.next());
                 if (pojoGraphMultipleReferenced(subObj, undoMap)) return true;
              }
           } else if (obj instanceof List || obj instanceof Set)
           {
              for (Iterator it = ((Collection) obj).iterator(); it.hasNext();)
              {
                 Object subObj = it.next();
                 if (pojoGraphMultipleReferenced(subObj, undoMap)) return true;
              }
           }
           // Don't remove now.
           boolean removeFromCache = false;
           ((AbstractCollectionInterceptor) interceptor).detach(removeFromCache); // detach the interceptor. This will trigger a copy and remove.
           boolean detachOnly = true;
           detachInterceptor(advisor, interceptor, detachOnly, undoMap);
        }
  
        return false;
     }
  
     private void _regularPutObject(Fqn fqn, Object obj, InstanceAdvisor advisor, CachedType type) throws CacheException
     {
        // TODO workaround for deserialiased objects
        if (advisor == null)
        {
           advisor = new ClassInstanceAdvisor(obj);
           ((Advised) obj)._setInstanceAdvisor(advisor);
        }
  
        // Let's do batch update via Map instead
        Map map = new HashMap();
        // Always initialize the ref count so we can mark this as an AopNode.
        PojoReference pojoReference = InternalHelper.initializeAopInstance();
        // Insert interceptor at runtime
        CacheFieldInterceptor interceptor = new CacheFieldInterceptor(pCache_, fqn, type);
        interceptor.setAopInstance(pojoReference);
        util_.attachInterceptor(obj, advisor, interceptor, observer_);
  
        map.put(PojoReference.KEY, pojoReference);
        // This is put into map first.
        InternalHelper.putAopClazz(type.getType(), map);
        // we will do it recursively.
        // Map of sub-objects that are non-primitive
        Map subPojoMap = new HashMap();
        boolean hasFieldAnnotation = hasAnnotation(obj.getClass(), ((Advised) obj)._getAdvisor(), type);
  
        for (Iterator i = type.getFields().iterator(); i.hasNext();)
        {
           Field field = (Field) (((FieldPersistentReference) i.next())).get();
           Object value = null;
           try
           {
              value = field.get(obj);
           }
           catch (IllegalAccessException e)
           {
              throw new CacheException("field access failed", e);
           }
           CachedType fieldType = pCache_.getCachedType(field.getType());
           // check for non-replicatable types
           if (CachedType.isPrimitiveNonReplicatable(field))
           {
              continue;
           }
  
           if (hasFieldAnnotation)
           {
              if (CachedType.hasTransientAnnotation(field, ((Advised) obj)._getAdvisor()))
              {
                 continue;
              }
           }
  
           // we simply treat field that has @Serializable as a primitive type.
           if (fieldType.isImmediate() ||
                   (hasFieldAnnotation &&
                           CachedType.hasSerializableAnnotation(field, ((Advised) obj)._getAdvisor())))
           {
              // switched using batch update
              map.put(field.getName(), value);
           } else
           {
              subPojoMap.put(field, value);
           }
        }
  
        // Use option to skip locking since we have parent lock already.
        cache_.put(fqn, map, internal_.getLockOption());
        // This is in-memory operation only
        InternalHelper.setPojo(pojoReference, obj);
  
        for (Object o : subPojoMap.keySet())
        {
           Field field = (Field) o;
           Object value = subPojoMap.get(field);
           Fqn tmpFqn = new Fqn(fqn, field.getName());
           _putObject(tmpFqn, value);
           // If it is Collection classes, we replace it with dynamic proxy.
           // But we will have to ignore it if value is null
           if (value instanceof Map || value instanceof List || value instanceof Set)
           {
              Object newValue = pCache_.getObject(tmpFqn);
              util_.collectionReplaceWithProxy(obj, value, field, newValue);
           }
        }
  
        // Need to make sure this is behind put such that obj.toString is done correctly.
        if (log.isDebugEnabled())
        {
           log.debug("_regularPutObject(): inserting with fqn: " + fqn);
        }
     }
  
     private static boolean hasAnnotation(Class clazz, Advisor advisor, CachedType type)
     {
        return CachedType.hasAnnotation(clazz, advisor, type);
     }
  
     /**
      * Note that caller of this method will take care of synchronization within the <code>fqn</code> sub-tree.
      *
      * @param fqn
      * @param removeCacheInterceptor
      * @param evict
      * @return
      * @throws CacheException
      */
     public Object _removeObject(Fqn fqn, boolean removeCacheInterceptor, boolean evict)
             throws CacheException
     {
        Class clazz = internal_.peekAopClazz(fqn);
        if (clazz == null)
        {
           if (log.isTraceEnabled())
           {
              log.trace("_removeObject(): clasz is null. fqn: " + fqn + " No need to remove.");
           }
           return null;
        }
  
        if (log.isDebugEnabled())
        {
           log.debug("_removeObject(): removing object from fqn: " + fqn);
        }
  
        Object result = pCache_.getObject(fqn);
        if (result == null)
        {
           // This is not a *Pojo*. Must be regular cache stuffs
           if (cache_.exists(fqn))
           {
              // TODO What do we do here. It can still have children pojo though.
              if (!evict)
              {
                 cache_.remove(fqn);
              } else
              {
                 cache_._evict(fqn);
              }
           }
           return null;
        }
  
        // can check if we need to do any bulk remove. E.g., if there is no object graph.
        if (getBulkRemove())
        {
           if (bulkRemove(fqn, result))
           {
              // Remember not to print obj here since it will trigger the CacheFieldInterceptor.
              if (log.isDebugEnabled())
              {
                 log.debug("_removeObject(): fqn: " + fqn + "removing exisiting object in bulk.");
              }
  
              return result;
           }
           setBulkRemove(false);
        }
  
        if (graphHandler_.objectGraphRemove(fqn, removeCacheInterceptor, result, evict))
        {
           return result;
        }
  
        // Not multi-referenced
        if (Advised.class.isAssignableFrom(clazz))
        {
           _regularRemoveObject(fqn, removeCacheInterceptor, result, clazz, evict);
        } else if (collectionHandler_.collectionObjectRemove(fqn))
        {
        } else
        { // Just Serializable objects. Do a brute force remove is ok.
           serializableHandler_.serializableObjectRemove();
        }
  
        internal_.cleanUp(fqn, evict);
  
        // remove the interceptor as well.
        return result;
     }
  
     private void _regularRemoveObject(Fqn fqn, boolean removeCacheInterceptor, Object result, Class clazz,
                                       boolean evict) throws CacheException
     {
        InstanceAdvisor advisor = ((Advised) result)._getInstanceAdvisor();
        CachedType type = pCache_.getCachedType(clazz);
        for (Iterator i = type.getFields().iterator(); i.hasNext();)
        {
           Field field = (Field) (((FieldPersistentReference) i.next())).get();
           CachedType fieldType = pCache_.getCachedType(field.getType());
           if (!fieldType.isImmediate())
           {
              _removeObject(new Fqn(fqn, field.getName()), removeCacheInterceptor, evict);
           }
        }
  
        // batch remove
        cache_.removeData(fqn);
  
        // Determine if we want to keep the interceptor for later use.
        if (removeCacheInterceptor)
        {
           CacheFieldInterceptor interceptor = (CacheFieldInterceptor) AopUtil.findCacheInterceptor(advisor);
           // Remember to remove the interceptor from in-memory object but make sure it belongs to me first.
           if (interceptor != null)
           {
              if (log.isDebugEnabled())
              {
                 log.debug("regularRemoveObject(): removed cache interceptor fqn: " + fqn + " interceptor: " + interceptor);
              }
              util_.detachInterceptor(advisor, interceptor, observer_);
           }
        }
  
     }
  
     Map _findObjects(Fqn fqn) throws CacheException
     {
  
        // Traverse from fqn to do getObject, if it return a pojo we then stop.
        Map map = new HashMap();
        Object pojo = _getObject(fqn);
        if (pojo != null)
        {
           map.put(fqn, pojo); // we are done!
           return map;
        }
  
        findChildObjects(fqn, map);
        if (log.isDebugEnabled())
        {
           log.debug("_findObjects(): Fqn: " + fqn + " size of pojos found: " + map.size());
        }
        return map;
     }
  
     private void findChildObjects(Fqn fqn, Map map) throws CacheException
     {
        // We need to traverse then
        Set set = cache_.getChildrenNames(fqn);
        if (set == null) return; // We stop here.
        for (Object aSet : set)
        {
           String obj = (String) aSet;
           Fqn newFqn = new Fqn(fqn, obj);
  
           Object pojo = _getObject(newFqn);
           if (pojo != null)
           {
              map.put(newFqn, pojo);
           } else
           {
              findChildObjects(newFqn, map);
           }
        }
     }
  }
  
  
  
  1.1      date: 2006/07/13 15:56:12;  author: bwang;  state: Exp;JBossCache/src-50/org/jboss/cache/pojo/impl/SerializableObjectHandler.java
  
  Index: SerializableObjectHandler.java
  ===================================================================
  /*
   * JBoss, Home of Professional Open Source
   *
   * Distributable under LGPL license.
   * See terms of license at gnu.org.
   */
  
  package org.jboss.cache.pojo.impl;
  
  import org.apache.commons.logging.Log;
  import org.apache.commons.logging.LogFactory;
  import org.jboss.cache.CacheException;
  import org.jboss.cache.Fqn;
  import org.jboss.cache.pojo.PojoTreeCache;
  import org.jboss.cache.pojo.PojoReference;
  
  import java.util.HashMap;
  import java.util.Map;
  
  /**
   * Handle Serializable object cache management.
   *
   * @author Ben Wang
   * @version $Id: SerializableObjectHandler.java,v 1.1 2006/07/13 15:56:12 bwang Exp $
   */
  class SerializableObjectHandler
  {
     private PojoTreeCache cache_;
     private PojoCacheImpl pCache_;
     private InternalHelper internal_;
     private final Log log = LogFactory.getLog(SerializableObjectHandler.class);
  
     public SerializableObjectHandler(PojoCacheImpl cache, InternalHelper internal)
     {
        pCache_ = cache;
        cache_ = (PojoTreeCache)pCache_.getCache();
        internal_ = internal;
     }
  
     Object serializableObjectGet(Fqn fqn)
             throws CacheException
     {
        Object obj = internal_.get(fqn, InternalConstant.SERIALIZED);
        return obj;
     }
  
  
     boolean serializableObjectPut(Fqn fqn, Object obj)
             throws CacheException
     {
          // Note that JBoss Serialization can serialize any type now.
           if (log.isDebugEnabled())
           {
              log.debug("putObject(): obj (" + obj.getClass() + ") is non-advisable but serialize it anyway. "
              + "Note that if it is non-serializable we require to use JBoss Serialization.");
           }
  
           putIntoCache(fqn, obj);
           return true;
     }
  
     private void putIntoCache(Fqn fqn, Object obj)
             throws CacheException
     {
        Map map = new HashMap();
        InternalHelper.putAopClazz(obj.getClass(), map);
  
        // Special optimization here.
        PojoReference pojoReference = new PojoReference();
        pojoReference.set(obj);
        map.put(PojoReference.KEY, pojoReference);
        // Note that we will only have one key in this fqn.
        map.put(InternalConstant.SERIALIZED, obj);
        internal_.put(fqn, map);
     }
  
     @SuppressWarnings({"CanBeStatic"})
     void serializableObjectRemove()
     {
        // No need to do anything here since we will do clean up afterwards.
     }
  
  }
  
  
  



More information about the jboss-cvs-commits mailing list