Ejemplo n.º 1
0
  @Test
  public void testCacheDecoratorFactoryProperties() {
    CacheManager cacheManager =
        new CacheManager(getClass().getResourceAsStream(EHCACHE_DEFAULT_DECORATOR_TEST_XML));
    List<String> cacheNames = Arrays.asList(cacheManager.getCacheNames());
    assertEquals(7, cacheNames.size());

    MockDecoratorFactoryCache cache =
        (MockDecoratorFactoryCache) cacheManager.getEhcache("noDecoratorCache-defaultDecoratorOne");
    assertEquals("defaultDecoratorOne", cache.getProperties().getProperty("someKey"));

    cache =
        (MockDecoratorFactoryCache) cacheManager.getEhcache("noDecoratorCache-defaultDecoratorTwo");
    assertEquals("defaultDecoratorTwo", cache.getProperties().getProperty("someKey"));

    cache =
        (MockDecoratorFactoryCache)
            cacheManager.getEhcache("oneDecoratorCache-defaultDecoratorOne");
    assertEquals("defaultDecoratorOne", cache.getProperties().getProperty("someKey"));

    cache =
        (MockDecoratorFactoryCache)
            cacheManager.getEhcache("oneDecoratorCache-defaultDecoratorTwo");
    assertEquals("defaultDecoratorTwo", cache.getProperties().getProperty("someKey"));

    cache = (MockDecoratorFactoryCache) cacheManager.getEhcache("oneDecoratorCacheFirst");
    assertEquals("oneFirst", cache.getProperties().getProperty("someKey"));
  }
  @Test
  public void testAddManager() throws Exception {
    LOG.info("START TEST");

    cacheName = "sampleCacheSyncBootstrap";
    if (manager1.getStatus() != Status.STATUS_SHUTDOWN) {
      manager1.shutdown();
    }

    manager1 = new CacheManager(CacheTestUtilities.ASYNC_CONFIG_URL1);
    CacheTestUtilities.waitForBootstrap(manager1, MAX_WAIT_TIME);

    final Ehcache cache1 = manager1.getEhcache(cacheName);
    final Ehcache cache2 = manager2.getEhcache(cacheName);
    final Ehcache cache3 = manager3.getEhcache(cacheName);
    final Ehcache cache4 = manager4.getEhcache(cacheName);

    // Wait up to 2 seconds for the caches to become coherent
    CacheTestUtilities.waitForReplication(0, MAX_WAIT_TIME, cache1, cache2, cache3, cache4);

    cache1.put(new Element(1, new Date()));
    cache2.put(new Element(2, new Date()));

    // Wait up to 2 seconds for the caches to become coherent
    CacheTestUtilities.waitForReplication(2, MAX_WAIT_TIME, cache1, cache2, cache3, cache4);

    assertEquals(2, cache1.getKeys().size());
    assertEquals(2, cache2.getKeys().size());
    assertEquals(2, cache3.getKeys().size());
    assertEquals(2, cache4.getKeys().size());

    LOG.info("END TEST");
  }
  @Test
  public void testBasicReplication() throws Exception {
    LOG.info("START TEST");

    final Ehcache cache1 = manager1.getEhcache(cacheName);
    final Ehcache cache2 = manager2.getEhcache(cacheName);
    final Ehcache cache3 = manager3.getEhcache(cacheName);
    final Ehcache cache4 = manager4.getEhcache(cacheName);

    for (int i = 0; i < NBR_ELEMENTS; i++) {
      cache1.put(new Element(i, "testdat"));
    }

    // Wait up to 3 seconds for the caches to become coherent
    CacheTestUtilities.waitForReplication(NBR_ELEMENTS, MAX_WAIT_TIME, cache2, cache3, cache4);

    assertEquals(NBR_ELEMENTS, cache1.getKeys().size());
    assertEquals(NBR_ELEMENTS, cache2.getKeys().size());
    assertEquals(NBR_ELEMENTS, cache3.getKeys().size());
    assertEquals(NBR_ELEMENTS, cache4.getKeys().size());

    cache1.removeAll();

    // Wait up to 3 seconds for the caches to become coherent
    CacheTestUtilities.waitForReplication(0, MAX_WAIT_TIME, cache2, cache3, cache4);

    assertEquals(0, cache1.getKeys().size());
    assertEquals(0, cache2.getKeys().size());
    assertEquals(0, cache3.getKeys().size());
    assertEquals(0, cache4.getKeys().size());

    LOG.info("END TEST");
  }
Ejemplo n.º 4
0
  public void testSimultaneousPutRemove() throws InterruptedException {
    cacheName = SAMPLE_CACHE2; // Synced one
    Ehcache cache1 = manager1.getEhcache(cacheName);
    Ehcache cache2 = manager2.getEhcache(cacheName);

    Serializable key = "1";
    Serializable value = new Date();
    Element element = new Element(key, value);

    // Put
    cache1.put(element);
    Thread.currentThread().sleep(1000);
    cache2.remove(element.getKey());
    Thread.currentThread().sleep(1000);

    assertNull(cache1.get(element.getKey()));
    manager1.clearAll();
    Thread.currentThread().sleep(1000);

    cache2.put(element);
    cache2.remove(element.getKey());
    Thread.currentThread().sleep(1000);
    cache1.put(element);
    Thread.currentThread().sleep(1000);
    assertNotNull(cache2.get(element.getKey()));

    manager1.clearAll();
    Thread.currentThread().sleep(1000);
  }
Ejemplo n.º 5
0
 public void testConfig() throws InterruptedException {
   cacheName = SAMPLE_CACHE_NOREP;
   Ehcache cache1 = manager1.getEhcache(cacheName);
   Ehcache cache2 = manager2.getEhcache(cacheName);
   Element element = new Element(new Integer(1), new Date());
   cache2.put(element);
   Thread.currentThread().sleep(1000);
   assertTrue(cache1.getKeys().size() == 0 && cache2.getKeys().size() == 1);
 }
Ejemplo n.º 6
0
  public void testAddManager() throws Exception {
    cacheName = SAMPLE_CACHE1;
    if (manager1.getStatus() != Status.STATUS_SHUTDOWN) manager1.shutdown();

    Thread.currentThread().sleep(1000);
    manager1 =
        new CacheManager(
            AbstractCacheTest.TEST_CONFIG_DIR
                + "distribution/jgroups/ehcache-distributed-jgroups.xml");
    Thread.currentThread().sleep(3000);
    manager2.clearAll();

    Thread.currentThread().sleep(1000);

    manager2.getEhcache(cacheName).put(new Element(new Integer(2), new Date()));
    manager1.getEhcache(cacheName).put(new Element(new Integer(3), new Date()));
    Thread.currentThread().sleep(2000);

    assertTrue(
        manager1.getEhcache(cacheName).getKeys().size()
                == manager2.getEhcache(cacheName).getKeys().size()
            && manager1.getEhcache(cacheName).getKeys().size()
                == manager3.getEhcache(cacheName).getKeys().size()
            && manager1.getEhcache(cacheName).getKeys().size()
                == manager4.getEhcache(cacheName).getKeys().size()
            && manager1.getEhcache(cacheName).getKeys().size() == 2);
  }
  @Before
  public void setUp() throws Exception {
    this.cache = MANAGER.getEhcache("test-config");
    assumeThat(cache, is(CoreMatchers.notNullValue()));

    this.registry = SharedMetricRegistries.getOrCreate("cache-metrics");
  }
Ejemplo n.º 8
0
 /**
  * 获取系统设置
  *
  * @return 系统设置
  */
 public static Setting get() {
   Ehcache cache = cacheManager.getEhcache(Setting.CACHE_NAME);
   net.sf.ehcache.Element cacheElement = cache.get(Setting.CACHE_KEY);
   Setting setting;
   if (cacheElement != null) {
     setting = (Setting) cacheElement.getObjectValue();
   } else {
     setting = new Setting();
     try {
       File shopxxXmlFile = new ClassPathResource(CommonAttributes.SHOPXX_XML_PATH).getFile();
       Document document = new SAXReader().read(shopxxXmlFile);
       List<Element> elements = document.selectNodes("/shopxx/setting");
       for (Element element : elements) {
         String name = element.attributeValue("name");
         String value = element.attributeValue("value");
         try {
           beanUtils.setProperty(setting, name, value);
         } catch (IllegalAccessException e) {
           e.printStackTrace();
         } catch (InvocationTargetException e) {
           e.printStackTrace();
         }
       }
     } catch (Exception e) {
       e.printStackTrace();
     }
     cache.put(new net.sf.ehcache.Element(Setting.CACHE_KEY, setting));
   }
   return setting;
 }
  @Test
  public void testSimultaneousPutRemove() throws InterruptedException {
    LOG.info("START TEST");

    // Synced one
    cacheName = SAMPLE_CACHE2;
    Ehcache cache1 = manager1.getEhcache(cacheName);
    Ehcache cache2 = manager2.getEhcache(cacheName);

    Serializable key = "1";
    Serializable value = new Date();
    Element element = new Element(key, value);

    // Put
    cache1.put(element);

    // Wait up to 2 seconds for the caches to become coherent
    CacheTestUtilities.waitForReplication(1, MAX_WAIT_TIME, cache2);

    cache2.remove(element.getKey());

    // Wait up to 2 seconds for the caches to become coherent
    CacheTestUtilities.waitForReplication(0, MAX_WAIT_TIME, cache1);

    assertNull(cache1.get(element.getKey()));
    manager1.clearAll();

    // Wait up to 2 seconds for the caches to become coherent
    CacheTestUtilities.waitForReplication(0, MAX_WAIT_TIME, cache2);

    cache2.put(element);
    cache2.remove(element.getKey());

    // Wait up to 2 seconds for the caches to become coherent
    CacheTestUtilities.waitForReplication(0, MAX_WAIT_TIME, cache2);

    cache1.put(element);

    // Wait up to 2 seconds for the caches to become coherent
    CacheTestUtilities.waitForReplication(1, MAX_WAIT_TIME, cache2);

    assertNotNull(cache2.get(element.getKey()));

    manager1.clearAll();

    LOG.info("END TEST");
  }
  /**
   * What happens when two cache instances replicate to each other and a change is initiated
   *
   * @throws InterruptedException -
   */
  @Test
  public void testVariousPuts() throws InterruptedException {
    LOG.info("START TEST");

    cacheName = SAMPLE_CACHE1;
    Ehcache cache1 = manager1.getEhcache(cacheName);
    Ehcache cache2 = manager2.getEhcache(cacheName);

    Serializable key = "1";
    Serializable value = new Date();
    Element element = new Element(key, value);

    // Put
    cache1.put(element);

    // Wait up to 2 seconds for the caches to become coherent
    CacheTestUtilities.waitForReplication(1, MAX_WAIT_TIME, cache2);

    // Should have been replicated to cache2.
    Element element2 = cache2.get(key);
    assertEquals(element, element2);

    // Remove
    cache1.remove(key);
    assertNull(cache1.get(key));

    // Wait up to 2 seconds for the caches to become coherent
    CacheTestUtilities.waitForReplication(0, MAX_WAIT_TIME, cache2);

    element2 = cache2.get(key);
    assertNull(element2);

    // Put into 2
    Element element3 = new Element("3", "ddsfds");
    cache2.put(element3);

    // Wait up to 2 seconds for the caches to become coherent
    CacheTestUtilities.waitForReplication(1, MAX_WAIT_TIME, cache2);

    Element element4 = cache2.get("3");
    assertEquals(element3, element4);

    manager1.clearAll();

    LOG.info("END TEST");
  }
  @Test
  public void testConfig() throws InterruptedException {
    LOG.info("START TEST");

    cacheName = SAMPLE_CACHE_NOREP;
    Ehcache cache1 = manager1.getEhcache(cacheName);
    Ehcache cache2 = manager2.getEhcache(cacheName);
    Element element = new Element(1, new Date());
    cache2.put(element);

    // Wait up 2 seconds to see if replication happens (it shouldn't)
    Thread.sleep(2000);

    assertEquals(0, cache1.getKeys().size());
    assertEquals(1, cache2.getKeys().size());

    LOG.info("END TEST");
  }
  @Test
  public void testShutdownManager() throws Exception {
    LOG.info("START TEST");

    cacheName = SAMPLE_CACHE1;
    final Ehcache cache1 = manager1.getEhcache(cacheName);
    final Ehcache cache2 = manager2.getEhcache(cacheName);

    cache1.removeAll();

    // Wait up to 2 seconds for the caches to become coherent
    CacheTestUtilities.waitForReplication(0, MAX_WAIT_TIME, cache2);

    CacheManagerPeerProvider provider =
        manager1.getCacheManagerPeerProvider(JGroupsCacheManagerPeerProvider.SCHEME_NAME);
    JGroupsCacheManagerPeerProvider jg = (JGroupsCacheManagerPeerProvider) provider;
    assertEquals(Status.STATUS_ALIVE, jg.getStatus());

    manager1.shutdown();
    assertEquals(Status.STATUS_UNINITIALISED, jg.getStatus());

    // Lets see if the other still replicate

    cache2.put(new Element(1, new Date()));

    final Ehcache cache3 = manager3.getEhcache(cacheName);
    final Ehcache cache4 = manager4.getEhcache(cacheName);

    // Wait up to 2 seconds for the caches to become coherent
    CacheTestUtilities.waitForReplication(1, MAX_WAIT_TIME, cache3, cache4);

    try {
      cache1.getKeys();
      fail("");
    } catch (IllegalStateException e) {
      // expected
    }
    assertEquals(1, cache2.getKeys().size());
    assertEquals(1, cache3.getKeys().size());
    assertEquals(1, cache4.getKeys().size());

    LOG.info("END TEST");
  }
  /**
   * Return all caches from the CacheManager
   *
   * @param sorted Should the caches be sorted by name?
   * @return
   */
  private List<Ehcache> getAllCaches(boolean sorted) {
    M_log.debug("getAllCaches()");

    final String[] cacheNames = cacheManager.getCacheNames();
    if (sorted) Arrays.sort(cacheNames);
    final List<Ehcache> caches = new ArrayList<Ehcache>(cacheNames.length);
    for (String cacheName : cacheNames) {
      caches.add(cacheManager.getEhcache(cacheName));
    }
    return caches;
  }
Ejemplo n.º 14
0
  @Test
  public void testReadThroughSimpleCase() {

    CacheManager manager = new CacheManager();
    manager.removalAll();

    CacheConfiguration config =
        new CacheConfiguration()
            .name("sampleCacheReadThru")
            .maxElementsInMemory(100)
            .timeToIdleSeconds(8)
            .timeToLiveSeconds(8)
            .overflowToDisk(false);
    manager.addCache(new Cache(config));

    Ehcache cache = manager.getEhcache("sampleCacheReadThru");
    ReadThroughCacheConfiguration readThroughConfig =
        new ReadThroughCacheConfiguration().modeGet(true).build();

    ReadThroughCache decorator = new ReadThroughCache(cache, readThroughConfig);

    cache.registerCacheLoader(stringifyCacheLoader);

    // should not be in the cache
    Element got = cache.get(new Integer(1));
    Assert.assertNull(got);

    // now load with decorator via get
    got = decorator.get(new Integer(1));
    Assert.assertNotNull(got);

    // now should be in the base cache
    got = cache.get(new Integer(1));
    Assert.assertNotNull(got);

    // now let it expire.
    sleepySeconds(10);

    // missing
    got = cache.get(new Integer(1));
    Assert.assertNull(got);

    // now load with get with loader
    got = decorator.get(new Integer(1));
    Assert.assertNotNull(got);

    // now should be in the base cache too.
    got = cache.get(new Integer(1));
    Assert.assertNotNull(got);

    manager.removalAll();
    manager.shutdown();
  }
Ejemplo n.º 15
0
public class App {
  public static void main(String[] args) {
    new App().testIt();
  }

  static CacheManager cacheManager =
      new CacheManager(App.class.getResourceAsStream("/ehcache.xml"));
  Ehcache cache = cacheManager.getEhcache("date-cache");

  private void testIt() {
    Date now = Calendar.getInstance().getTime();
    final Calendar instance = Calendar.getInstance();
    instance.add(Calendar.DAY_OF_MONTH, -1);
    Date before = instance.getTime();
    // cache.bootstrap();
    cache.put(new Element(1, now));
    cache.put(new Element(2, before));

    out.println("value found with key 1: " + cache.get(1).getObjectValue());
    out.println("value found with key 2: " + cache.get(2).getObjectValue());
    sleepForOneSeconds();
    out.println("value found with key 3: " + cache.get(3));
    dumpCacheInfo(cache);
    cache.remove(1);
    cache.get(1);
    sleepForOneSeconds();
    dumpCacheInfo(cache);
  }

  private void sleepForOneSeconds() {
    try {
      Thread.sleep(1000);
    } catch (InterruptedException e) {
      e
          .printStackTrace(); // To change body of catch statement use File | Settings | File
                              // Templates.
    }
  }

  private void dumpCacheInfo(final Ehcache cache) {
    out.println("cache-size: " + cache.getSize());
    out.println("cache-status: " + cache.getStatus());
    out.println("cache-guild: " + cache.getGuid());
    out.println("cache-name: " + cache.getName());
    out.println("mem-size: " + cache.calculateInMemorySize());
    out.println("heap-size: " + cache.calculateOffHeapSize());
    out.println("avg get-time: " + cache.getAverageGetTime());
    out.println("mem store-size: " + cache.getMemoryStoreSize());
    out.println("off-heap size: " + cache.getOffHeapStoreSize());
    out.println("cache-statistics: " + cache.getStatistics());
  }
}
  @Test
  public void testCASOperationsNotSupported() throws Exception {
    LOG.info("START TEST");

    final Ehcache cache1 = manager1.getEhcache(cacheName);
    final Ehcache cache2 = manager2.getEhcache(cacheName);
    final Ehcache cache3 = manager3.getEhcache(cacheName);
    final Ehcache cache4 = manager4.getEhcache(cacheName);

    try {
      cache1.putIfAbsent(new Element("foo", "poo"));
      throw new AssertionError("CAS operation should have failed.");
    } catch (CacheException ce) {
      assertEquals(true, ce.getMessage().contains("CAS"));
    }

    try {
      cache2.removeElement(new Element("foo", "poo"));
      throw new AssertionError("CAS operation should have failed.");
    } catch (CacheException ce) {
      assertEquals(true, ce.getMessage().contains("CAS"));
    }

    try {
      cache3.replace(new Element("foo", "poo"));
      throw new AssertionError("CAS operation should have failed.");
    } catch (CacheException ce) {
      assertEquals(true, ce.getMessage().contains("CAS"));
    }

    try {
      cache4.replace(new Element("foo", "poo"), new Element("foo", "poo2"));
      throw new AssertionError("CAS operation should have failed.");
    } catch (CacheException ce) {
      assertEquals(true, ce.getMessage().contains("CAS"));
    }

    LOG.info("END TEST");
  }
Ejemplo n.º 17
0
    public SamplerRepoEntry(CacheManager cacheManager) {
      if (cacheManager == null) throw new IllegalArgumentException("cacheManager == null");

      this.cacheManagerSampler = new CacheManagerSamplerImpl(cacheManager);
      this.cacheManager = cacheManager;

      String[] cNames = cacheManager.getCacheNames();
      this.cacheSamplersByName = new HashMap<String, CacheSampler>(cNames.length);

      for (String cName : cNames) {
        cacheSamplersByName.put(cName, new CacheSamplerImpl(cacheManager.getEhcache(cName)));
      }
    }
Ejemplo n.º 18
0
  /**
   * @param cacheManagerUrl
   * @param cacheName
   * @return
   */
  public static Ehcache getCache(String cacheManagerUrl, String cacheName) {
    CacheManager mgr = (CacheManager) managers.get(cacheManagerUrl);

    if (mgr == null) {
      mgr = CacheManager.create(AbstractCacheTest.TEST_CONFIG_DIR + cacheManagerUrl);
      // Requires the config file to be in the classpath, which is not how we test specific configs
      // in these tests
      // mgr = new
      // CacheManager(Thread.currentThread().getContextClassLoader().getResourceAsStream(cacheManagerUrl));
      managers.put(cacheManagerUrl, mgr);
    }

    return mgr.getEhcache(cacheName);
  }
Ejemplo n.º 19
0
  /**
   * 设置系统设置
   *
   * @param setting 系统设置
   */
  public static void set(Setting setting) {
    try {
      File shopxxXmlFile = new ClassPathResource(CommonAttributes.SHOPXX_XML_PATH).getFile();
      Document document = new SAXReader().read(shopxxXmlFile);
      List<Element> elements = document.selectNodes("/shopxx/setting");
      for (Element element : elements) {
        try {
          String name = element.attributeValue("name");
          String value = beanUtils.getProperty(setting, name);
          Attribute attribute = element.attribute("value");
          attribute.setValue(value);
        } catch (IllegalAccessException e) {
          e.printStackTrace();
        } catch (InvocationTargetException e) {
          e.printStackTrace();
        } catch (NoSuchMethodException e) {
          e.printStackTrace();
        }
      }

      FileOutputStream fileOutputStream = null;
      XMLWriter xmlWriter = null;
      try {
        OutputFormat outputFormat = OutputFormat.createPrettyPrint();
        outputFormat.setEncoding("UTF-8");
        outputFormat.setIndent(true);
        outputFormat.setIndent("	");
        outputFormat.setNewlines(true);
        fileOutputStream = new FileOutputStream(shopxxXmlFile);
        xmlWriter = new XMLWriter(fileOutputStream, outputFormat);
        xmlWriter.write(document);
      } catch (Exception e) {
        e.printStackTrace();
      } finally {
        if (xmlWriter != null) {
          try {
            xmlWriter.close();
          } catch (IOException e) {
          }
        }
        IOUtils.closeQuietly(fileOutputStream);
      }

      Ehcache cache = cacheManager.getEhcache(Setting.CACHE_NAME);
      cache.put(new net.sf.ehcache.Element(Setting.CACHE_KEY, setting));
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Ejemplo n.º 20
0
  /** What happens when two cache instances replicate to each other and a change is initiated */
  public void testVariousPuts() throws InterruptedException {
    cacheName = SAMPLE_CACHE1;
    Ehcache cache1 = manager1.getEhcache(cacheName);
    Ehcache cache2 = manager2.getEhcache(cacheName);

    Serializable key = "1";
    Serializable value = new Date();
    Element element = new Element(key, value);

    // Put
    cache1.put(element);
    Thread.currentThread().sleep(1000);

    // Should have been replicated to cache2.
    Element element2 = cache2.get(key);
    assertEquals(element, element2);

    // Remove
    cache1.remove(key);
    assertNull(cache1.get(key));

    // Should have been replicated to cache2.
    Thread.currentThread().sleep(1000);
    element2 = cache2.get(key);
    assertNull(element2);

    // Put into 2
    Element element3 = new Element("3", "ddsfds");
    cache2.put(element3);
    Thread.currentThread().sleep(1000);
    Element element4 = cache2.get("3");
    assertEquals(element3, element4);

    manager1.clearAll();
    Thread.currentThread().sleep(1000);
  }
Ejemplo n.º 21
0
  protected Ehcache createCache(String key, boolean inMemory, int maxInMemory) {
    Ehcache cache = null;
    try {
      cache = ehmanager.getEhcache(key);
    } catch (Exception e) {
      // ok
    }

    if (cache == null) {
      CacheFactory factory = new CacheFactory();
      factory.setBeanName(key);
      factory.setCacheManager(ehmanager);
      factory.setOverflowToDisk(!inMemory);
      factory.setMaxElementsInMemory(maxInMemory);
      factory.setMaxElementsOnDisk(0);
      factory.setDiskPersistent(false);
      factory.setTimeToIdle(0);
      factory.setTimeToLive(0);
      cache = factory.createCache();
    }
    return cache;
  }
Ejemplo n.º 22
0
  public void testShutdownManager() throws Exception {
    cacheName = SAMPLE_CACHE1;
    manager1.getEhcache(cacheName).removeAll();
    Thread.currentThread().sleep(1000);

    CacheManagerPeerProvider provider = manager1.getCachePeerProvider();
    JGroupManager jg = (JGroupManager) provider;
    assertEquals(Status.STATUS_ALIVE, jg.getStatus());
    manager1.shutdown();
    assertEquals(Status.STATUS_SHUTDOWN, jg.getStatus());
    // Lets see if the other still replicate
    manager2.getEhcache(cacheName).put(new Element(new Integer(1), new Date()));
    Thread.currentThread().sleep(2000);

    assertTrue(
        manager2.getEhcache(cacheName).getKeys().size()
                == manager3.getEhcache(cacheName).getKeys().size()
            && manager2.getEhcache(cacheName).getKeys().size()
                == manager4.getEhcache(cacheName).getKeys().size()
            && manager2.getEhcache(cacheName).getKeys().size() == 1);
  }
Ejemplo n.º 23
0
  /**
   * @param cacheName the name of the cache
   * @param configuration [OPTIONAL] a config to use when building the cache, if null then use
   *     default methods to create cache
   * @return an Ehcache
   */
  private Ehcache makeEhcache(
      String cacheName, org.sakaiproject.memory.api.Configuration configuration) {
    /** Indicates a cache is a new one and should be configured */
    boolean newCache = false;
    String name = cacheName;
    if (name == null || "".equals(name)) {
      name = "DefaultCache" + UUID.randomUUID().toString();
      log.warn("Creating cache without a name, generating dynamic name: (" + name + ")");
      newCache = true;
    }

    Ehcache cache;
    // fetch an existing cache first if possible
    if (!newCache && cacheManager.cacheExists(name)) {
      cache = cacheManager.getEhcache(name);
      if (log.isDebugEnabled()) log.debug("Retrieved existing ehcache (" + name + ")");
    } else {
      // create a new defaulted cache
      cacheManager.addCache(name);
      cache = cacheManager.getEhcache(name);
      newCache = true;
      log.info("Created ehcache (" + name + ") using defaults");
    }

    if (newCache) {
      if (log.isDebugEnabled())
        log.debug("Prepared to configure new ehcache (" + name + "): " + cache);
      // warn people if they are using an old config style
      if (serverConfigurationService.getString(name) == null) {
        log.warn(
            "Old cache configuration for cache ("
                + name
                + "), must be changed to memory."
                + name
                + " or it will be ignored");
      }

      // load the ehcache config from the Sakai config service
      String config = serverConfigurationService.getString("memory." + name);
      if (StringUtils.isNotBlank(config)) {
        log.info("Configuring ehcache (" + name + ") from Sakai config: " + config);
        try {
          // ehcache specific code here - no exceptions thrown
          //noinspection deprecation
          new CacheInitializer().configure(config).initialize(cache.getCacheConfiguration());
        } catch (Exception e) {
          // nothing to do here but proceed
          log.error("Failure configuring cache (" + name + "): " + config + " :: " + e, e);
        }
      }

      /* KNL-532 - Upgraded Ehcache 2.5.1 (2.1.0+) defaults to no stats collection.
       * We may choose to allow configuration per-cache for performance tuning.
       * For now, we default everything to on, while this property allows a system-wide override.
       */
      boolean enabled = true;
      if (serverConfigurationService != null) {
        enabled =
            !serverConfigurationService.getBoolean("memory.cache.statistics.force.disabled", false);
      }
      if (cache.isStatisticsEnabled() != enabled) {
        cache.setStatisticsEnabled(enabled);
      }
    }

    // apply config to the cache (every time)
    if (configuration != null) {
      if (configuration.getMaxEntries() >= 0) {
        cache.getCacheConfiguration().setMaxEntriesLocalHeap(configuration.getMaxEntries());
      }
      if (configuration.isEternal()) {
        cache.getCacheConfiguration().setTimeToLiveSeconds(0l);
        cache.getCacheConfiguration().setTimeToIdleSeconds(0l);
      } else {
        if (configuration.getTimeToLiveSeconds() >= 0) {
          cache.getCacheConfiguration().setTimeToLiveSeconds(configuration.getTimeToLiveSeconds());
        }
        if (configuration.getTimeToIdleSeconds() >= 0) {
          cache.getCacheConfiguration().setTimeToIdleSeconds(configuration.getTimeToIdleSeconds());
        }
      }
      cache.getCacheConfiguration().setEternal(configuration.isEternal());
      cache.setStatisticsEnabled(configuration.isStatisticsEnabled());
      log.info("Configured ehcache (" + name + ") from inputs: " + configuration);
    }

    if (log.isDebugEnabled()) log.debug("Returning initialized ehcache (" + name + "): " + cache);
    return cache;
  }
Ejemplo n.º 24
0
  /**
   * @param cacheName
   * @param legacyMode If true always create a new Cache. If false, cache must be defined in bean
   *     factory.
   * @return
   */
  private Ehcache instantiateCache(String cacheName) {
    if (M_log.isDebugEnabled()) M_log.debug("createNewCache(String " + cacheName + ")");

    String name = cacheName;
    if (name == null || "".equals(name)) {
      name = "DefaultCache" + UUID.randomUUID().toString();
    }

    // Cache creation should all go to the cache manager and be
    // configured via the cache manager setup.

    if (cacheManager.cacheExists(name)) {
      return cacheManager.getEhcache(name);
    }
    cacheManager.addCache(name);
    return cacheManager.getEhcache(name);

    /*


    if(legacyMode)
    {
    	if (cacheManager.cacheExists(name)) {
    		M_log.warn("Cache already exists and is bound to CacheManager; creating new cache from defaults: "
    				+ name);
    		// favor creation of new caches for backwards compatibility
    		// in the future, it seems like you would want to return the same
    		// cache if it already exists
    		name = name + UUID.randomUUID().toString();
    	}
    }

    Ehcache cache = null;

    // try to locate a named cache in the bean factory
    try {
    	cache = (Ehcache) ComponentManager.get(name);
    } catch (Throwable e) {
    	cache = null;
    	M_log.error("Error occurred when trying to load cache from bean factory!", e);
    }


    if(cache != null) // found the cache
    {
    	M_log.info("Loaded Named Cache " + cache);

    	return cache;
    }
    else // did not find the cache
    {
    	if(legacyMode)
    	{
    		cacheManager.addCache(name); // create a new cache
    		cache = cacheManager.getEhcache(name);
    		M_log.info("Loaded Default Cache " + cache);
    	}
    	else
    	{
    		M_log.error("Could not find named cache in the bean factory!:"
    						+ name);
    	}

    	return cache;
    }
    */
  }
Ejemplo n.º 25
0
  public void testBasicReplication() throws Exception {

    for (int i = 0; i < NBR_ELEMENTS; i++) {
      manager1.getEhcache(cacheName).put(new Element(new Integer(i), "testdat"));
      // Thread.currentThread().sleep(2);
    }
    Thread.currentThread().sleep(3000);

    LOG.debug(
        manager1.getEhcache(cacheName).getKeys().size()
            + "  "
            + manager2.getEhcache(cacheName).getKeys().size()
            + " "
            + manager3.getEhcache(cacheName).getKeys().size());
    assertTrue(
        manager1.getEhcache(cacheName).getKeys().size()
                == manager2.getEhcache(cacheName).getKeys().size()
            && manager1.getEhcache(cacheName).getKeys().size()
                == manager3.getEhcache(cacheName).getKeys().size()
            && manager1.getEhcache(cacheName).getKeys().size()
                == manager4.getEhcache(cacheName).getKeys().size()
            && manager1.getEhcache(cacheName).getKeys().size() == NBR_ELEMENTS);

    manager1.getEhcache(cacheName).removeAll();
    Thread.currentThread().sleep(1000);
    assertTrue(
        manager1.getEhcache(cacheName).getKeys().size()
                == manager2.getEhcache(cacheName).getKeys().size()
            && manager1.getEhcache(cacheName).getKeys().size()
                == manager3.getEhcache(cacheName).getKeys().size()
            && manager1.getEhcache(cacheName).getKeys().size()
                == manager4.getEhcache(cacheName).getKeys().size()
            && manager1.getEhcache(cacheName).getKeys().size() == 0);
  }
Ejemplo n.º 26
0
 private void tracePeers() {
   CacheManagerPeerProvider peerProvider = manager.getCacheManagerPeerProvider("RMI");
   int peers = peerProvider.listRemoteCachePeers(manager.getEhcache(cacheName)).size();
   log.trace("Found {} remote cache peer(s)", peers);
 }
  /**
   * @param cacheName
   * @param legacyMode If true always create a new Cache. If false, cache must be defined in bean
   *     factory.
   * @return
   */
  private Ehcache instantiateCache(String cacheName) {
    if (M_log.isDebugEnabled()) M_log.debug("createNewCache(String " + cacheName + ")");

    String name = cacheName;
    if (name == null || "".equals(name)) {
      name = "DefaultCache" + UUID.randomUUID().toString();
    }

    // Cache creation should all go to the cache manager and be
    // configured via the cache manager setup.

    if (cacheManager.cacheExists(name)) {
      return cacheManager.getEhcache(name);
    }

    Ehcache cache = null;

    try {
      Ehcache defaultCache = getDefaultCache();
      if (defaultCache != null) {
        cache = (Ehcache) defaultCache.clone();
        cache.setName(cacheName);

        // Not look for any custom configuration.
        // Check for old configuration properties.
        if (serverConfigurationService().getString(name) == null) {
          M_log.warn("Old cache configuration " + name + " must be changed to memory." + name);
        }
        String config = serverConfigurationService().getString("memory." + name);
        if (config != null && config.length() > 0) {
          M_log.debug("Found configuration for cache: " + name + " of: " + config);
          new CacheInitializer().configure(config).initialize(cache.getCacheConfiguration());
        }

        cacheManager.addCache(cache);
      }
    } catch (Exception ex) {
      M_log.warn("Unable to access or close default cache", ex);
    }

    if (cache == null) {
      cacheManager.addCache(name);
      cache = cacheManager.getEhcache(name);
    }

    // KNL-1292: do not set if the cache is not yet init'ed
    if (cache != null && cache.getStatus().equals(Status.STATUS_ALIVE)) {
      // KNL-532 - Upgraded Ehcache 2.5.1 (2.1.0+) defaults to no stats collection.
      // We may choose to allow configuration per-cache for performance tuning.
      // For now, we default everything to on, while this property allows a system-wide override.
      cache.setStatisticsEnabled(
          !(serverConfigurationService()
              .getBoolean("memory.cache.statistics.force.disabled", false)));
    }

    return cache;

    /*


    if(legacyMode)
    {
    	if (cacheManager.cacheExists(name)) {
    		M_log.warn("Cache already exists and is bound to CacheManager; creating new cache from defaults: "
    				+ name);
    		// favor creation of new caches for backwards compatibility
    		// in the future, it seems like you would want to return the same
    		// cache if it already exists
    		name = name + UUID.randomUUID().toString();
    	}
    }

    Ehcache cache = null;

    // try to locate a named cache in the bean factory
    try {
    	cache = (Ehcache) ComponentManager.get(name);
    } catch (Exception e) {
    	cache = null;
    	M_log.error("Error occurred when trying to load cache from bean factory!", e);
    }


    if(cache != null) // found the cache
    {
    	M_log.info("Loaded Named Cache " + cache);

    	return cache;
    }
    else // did not find the cache
    {
    	if(legacyMode)
    	{
    		cacheManager.addCache(name); // create a new cache
    		cache = cacheManager.getEhcache(name);
    		M_log.info("Loaded Default Cache " + cache);
    	}
    	else
    	{
    		M_log.error("Could not find named cache in the bean factory!:"
    						+ name);
    	}

    	return cache;
    }
    */
  }