Advertisement
Guest User

Untitled

a guest
May 24th, 2017
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5 5.27 KB | None | 0 0
  1. import org.apache.log4j.Logger;
  2. import org.hibernate.exception.ExceptionUtils;
  3.  
  4. import com.netjets.j2ee.log.ApplicationLogger;
  5.  
  6. import net.sf.ehcache.CacheException;
  7. import net.sf.ehcache.CacheManager;
  8. import net.sf.ehcache.Element;
  9. import net.sf.ehcache.constructs.blocking.SelfPopulatingCache;
  10. import net.sf.ehcache.Ehcache;
  11. import net.sf.ehcache.constructs.blocking.CacheEntryFactory;
  12. import net.sf.ehcache.event.CacheEventListener;
  13.  
  14. /**
  15.  * SelfPopulatingAgedCache is a SelfPopulatingCache
  16.  * which means it uses a CacheEntryFactory to create missing elements
  17.  * and return them from get.  It also inherits the ability to block
  18.  * other attempts to get the same key while a load is in progress with
  19.  * an upper bound timeout (which does not apply to the client that first
  20.  * tries to load the key).  If you want to keep the cache fresh with
  21.  * a background thread and have the same upper bound for all calls,
  22.  * look into also using an ehcache Loader with this.
  23.  *  
  24.  * This class adds a add way to set it's timeout in the constructor,
  25.  * and also tests for expired elements and reloads them transparently.
  26.  *
  27.  * ehcache.xml can only setup the basic cache properties (age till timeout
  28.  * and so forth), so to use this decorated cache, install it like this:
  29.  *
  30.  * MyImplConstructor or similar init() method {
  31.  *  Ehcache c = CacheManager.getInstance().getEhcache("com.netjets.ThingCache");
  32.  *  if (!(c instanceof SelfPopulatingAgedCache)) {
  33.  *      c = new SelfPopulatingAgedCache(c, categoryGetter, 5000);
  34.  *  }
  35.  *  
  36.  *  All this make final usage a one-liner:
  37.  *  
  38.  *  Thing getThing(Object key) {
  39.  *    return (Thing) CacheManager.getInstance().getEhcache("com.netjets.ThingCache")
  40.  *      .get(key).getValue();
  41.  *
  42.  * @author pinkham
  43.  */
  44.  
  45. public class SelfPopulatingAgedCache extends SelfPopulatingCache {
  46.    
  47.     static final Logger logger = ApplicationLogger.getLogger(SelfPopulatingAgedCache.class);
  48.    
  49.     public SelfPopulatingAgedCache(Ehcache c, CacheEntryFactory ef, int timeout) {
  50.         // super sets factory to this wrapper
  51.         super(c, new ExceptionEatingCacheEntryFactoryWrapper(ef, "Credential token expired"));
  52.         setTimeoutMillis(timeout);
  53.         CacheManager.getInstance().replaceCacheWithDecoratedCache(c, this);
  54.         // cache factory wrapper is also a listener but we need to register it
  55.         getCacheEventNotificationService().registerListener((CacheEventListener)factory);
  56.     }
  57.    
  58.     @Override
  59.     public Element get(Object key) {
  60.         try {
  61.             return super.get(key);  // decorated base cache handles expiration
  62.         } catch (CacheException e) {
  63.             // for some reason, CacheException doesn't call super(msg, cause) but has it's own cause field.
  64.             // Add the cache name too
  65.             // finally, subclass RuntimeException with empty {}
  66.             // to get the more descriptive exception name
  67.             // SelfPopulatingAgedCache$RuntimeException.
  68.             RuntimeException e2 = new RuntimeException(
  69.                     e.getMessage()+ " for cache: "+cache.getName(), e.getInitialCause()){};
  70.             //e2.setStackTrace(e.getStackTrace());   // as if they had done it right
  71.             throw e2;
  72.         }
  73.     }
  74.    
  75.     // TODO: Fix the real root cause, but meanwhile, this might buy us some time QC 44371
  76.     protected static final class ExceptionEatingCacheEntryFactoryWrapper implements CacheEventListener, CacheEntryFactory {
  77.         private CacheEntryFactory factory;
  78.         private String contains;
  79.         protected ExceptionEatingCacheEntryFactoryWrapper(CacheEntryFactory factory, String contains) {
  80.             this.factory = factory;
  81.             this.contains = contains;
  82.         }
  83.        
  84.         private Element lastExpiredElement;
  85.         public Object createEntry(Object key) throws Exception {
  86.             try {
  87.                 return factory.createEntry(key);
  88.             } catch (Exception e) {
  89.                 if (contains == null || ExceptionUtils.getStackTrace(e).contains(contains)) {
  90.                     if (lastExpiredElement != null && lastExpiredElement.getKey().equals(key)) {
  91.                         Object ret = lastExpiredElement.getObjectValue();   // keep re-using it's data
  92.                         lastExpiredElement = null;
  93.                         logger.warn(factory.getClass().getName()+
  94.                                 " Ignoring exception and using old cache value: ",e);
  95.                         return ret;
  96.                     }
  97.                     logger.warn(factory.getClass().getName()+
  98.                             " Unable to ignore first exception since cache has no old value: "+e);
  99.                 }
  100.                 throw e;
  101.             }
  102.         }
  103.  
  104.         public void dispose() {}
  105.         public void notifyElementEvicted(Ehcache ehcache, Element element) {}
  106.         public void notifyElementExpired(Ehcache ehcache, Element element)
  107.         {
  108.             lastExpiredElement = element;  // save it before it goes away
  109.         }
  110.         public void notifyElementPut(Ehcache ehcache, Element element) {}
  111.         public void notifyElementRemoved(Ehcache ehcache, Element element) {}
  112.         public void notifyElementUpdated(Ehcache ehcache, Element element) {}
  113.         public void notifyRemoveAll(Ehcache ehcache) {}
  114.         public Object clone() throws CloneNotSupportedException { return super.clone(); }
  115.     }  
  116. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement