@Test
 public void testPut() throws Exception {
   buildStore(Collections.<String, String>emptyMap());
   final Ehcache<String, String> ehcache = getEhcache();
   ehcache.put("key", "value");
   verify(cacheEventListener, times(1)).onEvent(argThat(isCreated));
 }
  @Test
  public void testPutStoreThrowsNoWriter() throws Exception {
    buildStore(Collections.singletonMap("key", "oldValue"));
    doThrow(new CacheAccessException("")).when(store).compute(eq("key"), getAnyBiFunction());

    final Ehcache<String, String> ehcache = getEhcache();

    ehcache.put("key", "value");
    verify(cacheEventListener, never()).onEvent(Matchers.<CacheEvent<String, String>>any());
  }
 /** Does a cache with a reference to a singleton hang on to it? */
 @Test
 public void testCacheManagerReferenceSingleton() {
   singletonManager = CacheManager.create();
   singletonManager.addCache("test");
   Ehcache cache = singletonManager.getCache("test");
   assertEquals("test", cache.getName());
   assertEquals(Status.STATUS_ALIVE, cache.getStatus());
   CacheManager reference = cache.getCacheManager();
   assertTrue(reference == singletonManager);
 }
 /** Does the cache hang on to its instance? */
 @Test
 public void testCacheManagerReferenceInstance() {
   instanceManager = new CacheManager();
   instanceManager.addCache("test");
   Ehcache cache = instanceManager.getCache("test");
   assertEquals("test", cache.getName());
   assertEquals(Status.STATUS_ALIVE, cache.getStatus());
   CacheManager reference = cache.getCacheManager();
   assertTrue(reference == instanceManager);
 }
 @Test
 public void testPutKeyNotNullValueNull() {
   final Ehcache<String, String> ehcache = getEhcache();
   try {
     ehcache.put("key", null);
     fail();
   } catch (NullPointerException e) {
     // expected
   }
   verify(cacheEventListener, never()).onEvent(Matchers.<CacheEvent<String, String>>any());
 }
  /** Shows that a decorated cache can be substituted */
  @Test
  public void testDecoratorRequiresDecoratedCache() {

    singletonManager = CacheManager.create();
    Ehcache cache = singletonManager.getEhcache("sampleCache1");
    // decorate and substitute
    BlockingCache newBlockingCache = new BlockingCache(cache);
    singletonManager.replaceCacheWithDecoratedCache(cache, newBlockingCache);
    Ehcache blockingCache = singletonManager.getEhcache("sampleCache1");
    assertNull(singletonManager.getCache("sampleCache1"));
    blockingCache.get("unknownkey");
    assertTrue(singletonManager.getEhcache("sampleCache1") == newBlockingCache);
  }
 @Test
 public void testPutWriterThrows() throws Exception {
   buildStore(Collections.singletonMap("key", "oldValue"));
   doThrow(new Exception()).when(cacheLoaderWriter).write("key", "value");
   final Ehcache<String, String> ehcache =
       getEhcache(cacheLoaderWriter, "EhcacheBasicPutEventsTest");
   try {
     ehcache.put("key", "value");
     fail();
   } catch (CacheWritingException e) {
     // Expected
   }
   verify(cacheEventListener, never()).onEvent(Matchers.<CacheEvent<String, String>>any());
 }
 @Test
 public void testPutStoreAndWriterThrow() throws Exception {
   buildStore(Collections.<String, String>emptyMap());
   doThrow(new CacheAccessException("")).when(store).compute(eq("key"), getAnyBiFunction());
   doThrow(new Exception()).when(cacheLoaderWriter).write("key", "value");
   final Ehcache<String, String> ehcache =
       getEhcache(cacheLoaderWriter, "EhcacheBasicPutEventsTest");
   try {
     ehcache.put("key", "value");
     fail();
   } catch (CacheWritingException e) {
     // Expected
   }
   verify(cacheEventListener, never()).onEvent(Matchers.<CacheEvent<String, String>>any());
 }
Beispiel #9
0
 /**
  * @return the name of the Ehcache, or null if a reference is no longer held to the cache, as, it
  *     would be after deserialization.
  */
 public String getAssociatedCacheName() {
   if (cache != null) {
     return cache.getName();
   } else {
     return null;
   }
 }
Beispiel #10
0
  /** Checks we can disable ehcache using a system property */
  @Test
  public void testDisableEhcache() throws CacheException, InterruptedException {
    System.setProperty(Cache.NET_SF_EHCACHE_DISABLED, "true");
    Thread.sleep(1000);
    instanceManager = CacheManager.create();
    Ehcache cache = instanceManager.getCache("sampleCache1");
    assertNotNull(cache);
    cache.put(new Element("key123", "value"));
    Element element = cache.get("key123");
    assertNull("When the disabled property is set all puts should be discarded", element);

    cache.putQuiet(new Element("key1234", "value"));
    assertNull(
        "When the disabled property is set all puts should be discarded", cache.get("key1234"));

    System.setProperty(Cache.NET_SF_EHCACHE_DISABLED, "false");
  }
Beispiel #11
0
  @Test
  public void testAddNamedCacheIfAbsent() {
    singletonManager = CacheManager.create();
    String presentCacheName = "present";
    singletonManager.addCache(presentCacheName);
    Cache alreadyPresent = singletonManager.getCache(presentCacheName);
    Ehcache cache = singletonManager.addCacheIfAbsent(presentCacheName);
    assertNotNull(cache);
    assertTrue(alreadyPresent == cache);
    assertEquals(presentCacheName, cache.getName());

    Ehcache actualCacheRegisteredWithManager = singletonManager.addCacheIfAbsent("absent");
    assertNotNull(actualCacheRegisteredWithManager);
    assertTrue(
        singletonManager.getCache(actualCacheRegisteredWithManager.getName())
            == actualCacheRegisteredWithManager);
    assertEquals("absent", actualCacheRegisteredWithManager.getName());
    assertTrue(
        singletonManager.addCacheIfAbsent(actualCacheRegisteredWithManager.getName())
            == actualCacheRegisteredWithManager);

    assertTrue(
        singletonManager.addCacheIfAbsent(
                new Cache(new CacheConfiguration(actualCacheRegisteredWithManager.getName(), 1000)))
            == actualCacheRegisteredWithManager);
    assertNull(singletonManager.addCacheIfAbsent((String) null));
    assertNull(singletonManager.addCacheIfAbsent(""));
  }
Beispiel #12
0
  @Test
  public void testAddCacheIfAbsent() {
    singletonManager = CacheManager.create();
    singletonManager.addCache("present");
    assertTrue(
        singletonManager.getCache("present")
            == singletonManager.addCacheIfAbsent(
                new Cache(new CacheConfiguration("present", 1000))));

    Cache theCache = new Cache(new CacheConfiguration("absent", 1000));
    Ehcache cache = singletonManager.addCacheIfAbsent(theCache);
    assertNotNull(cache);
    assertTrue(theCache == cache);
    assertEquals("absent", cache.getName());

    Cache other = new Cache(new CacheConfiguration(cache.getName(), 1000));
    Ehcache actualCacheRegisteredWithManager = singletonManager.addCacheIfAbsent(other);
    assertNotNull(actualCacheRegisteredWithManager);
    assertFalse(other == actualCacheRegisteredWithManager);
    assertTrue(cache == actualCacheRegisteredWithManager);

    Cache newCache = new Cache(new CacheConfiguration(cache.getName(), 1000));
    singletonManager.removeCache(actualCacheRegisteredWithManager.getName());
    actualCacheRegisteredWithManager = singletonManager.addCacheIfAbsent(newCache);
    assertNotNull(actualCacheRegisteredWithManager);
    assertFalse(cache == actualCacheRegisteredWithManager);
    assertTrue(newCache == actualCacheRegisteredWithManager);

    assertTrue(
        singletonManager.addCacheIfAbsent(
                new Cache(new CacheConfiguration(actualCacheRegisteredWithManager.getName(), 1000)))
            == actualCacheRegisteredWithManager);

    assertNull(singletonManager.addCacheIfAbsent((Ehcache) null));
  }
Beispiel #13
0
  /** Test using a cache which has been removed and replaced. */
  @Test
  public void testStaleCacheReference() throws CacheException {
    singletonManager = CacheManager.create();
    singletonManager.addCache("test");
    Ehcache cache = singletonManager.getCache("test");
    assertNotNull(cache);
    cache.put(new Element("key1", "value1"));

    assertEquals("value1", cache.get("key1").getObjectValue());
    singletonManager.removeCache("test");
    singletonManager.addCache("test");

    try {
      cache.get("key1");
      fail();
    } catch (IllegalStateException e) {
      assertEquals("The test Cache is not alive.", e.getMessage());
    }
  }
Beispiel #14
0
  /**
   * Shows that a decorated cache has decorated behaviour for methods that override Cache methods,
   * without requiring a cast.
   */
  @Test
  public void testDecoratorOverridesDefaultBehaviour() {

    singletonManager = CacheManager.create();
    Ehcache cache = singletonManager.getEhcache("sampleCache1");
    Element element = cache.get("key");
    // default behaviour for a missing key
    assertNull(element);

    // decorate and substitute
    SelfPopulatingCache selfPopulatingCache =
        new SelfPopulatingCache(cache, new CountingCacheEntryFactory("value"));
    selfPopulatingCache.get("key");
    singletonManager.replaceCacheWithDecoratedCache(cache, selfPopulatingCache);

    Ehcache decoratedCache = singletonManager.getEhcache("sampleCache1");
    assertNull(singletonManager.getCache("sampleCache1"));
    Element element2 = cache.get("key");
    assertEquals("value", element2.getObjectValue());
  }
Beispiel #15
0
  /**
   * Tests we can add caches from the default where the default has listeners. Since 1.7, a
   * CacheUsageStatisticsData is also registered.
   */
  @Test
  public void testAddCacheFromDefaultWithListeners() throws CacheException {
    singletonManager =
        CacheManager.create(
            AbstractCacheTest.TEST_CONFIG_DIR
                + File.separator
                + "distribution"
                + File.separator
                + "ehcache-distributed1.xml");
    singletonManager.addCache("test");
    Ehcache cache = singletonManager.getCache("test");
    assertNotNull(cache);
    assertEquals("test", cache.getName());

    Set listeners = cache.getCacheEventNotificationService().getCacheEventListeners();
    assertEquals(2, listeners.size());
    for (Iterator iterator = listeners.iterator(); iterator.hasNext(); ) {
      CacheEventListener cacheEventListener = (CacheEventListener) iterator.next();
      assertTrue(
          cacheEventListener instanceof RMIAsynchronousCacheReplicator
              || cacheEventListener instanceof LiveCacheStatisticsData);
    }
  }
Beispiel #16
0
  /** An integration test, at the CacheManager level, to make sure persistence works */
  @Test
  public void testPersistentStoreFromCacheManager()
      throws IOException, InterruptedException, CacheException {
    // initialise with an instance CacheManager so that the following line actually does something
    CacheManager manager = new CacheManager(AbstractCacheTest.TEST_CONFIG_DIR + "ehcache-disk.xml");
    Ehcache cache = manager.getCache("persistentLongExpiryIntervalCache");

    LOG.info("DiskStore path: {}", manager.getDiskStorePath());

    for (int i = 0; i < 100; i++) {
      byte[] data = new byte[1024];
      cache.put(new Element("key" + (i + 100), data));
    }
    assertEquals(100, cache.getSize());

    manager.shutdown();

    manager = new CacheManager(AbstractCacheTest.TEST_CONFIG_DIR + "ehcache-disk.xml");
    cache = manager.getCache("persistentLongExpiryIntervalCache");
    assertEquals(100, cache.getSize());

    manager.shutdown();
  }
Beispiel #17
0
  /** Tests adding a new cache with default config */
  @Test
  public void testAddCache() throws CacheException {
    singletonManager = CacheManager.create();
    assertEquals(15, singletonManager.getConfiguration().getCacheConfigurations().size());
    singletonManager.addCache("test");
    singletonManager.addCache("test2");
    assertEquals(17, singletonManager.getConfiguration().getCacheConfigurations().size());
    Ehcache cache = singletonManager.getCache("test");
    assertNotNull(cache);
    assertEquals("test", cache.getName());
    String[] cacheNames = singletonManager.getCacheNames();
    boolean match = false;
    for (String cacheName : cacheNames) {
      if (cacheName.equals("test")) {
        match = true;
      }
    }
    assertTrue(match);

    // NPE tests
    singletonManager.addCache("");
    assertEquals(17, singletonManager.getConfiguration().getCacheConfigurations().size());
  }
 /**
  * Replaces the {@link org.ehcache.resilience.ResilienceStrategy ResilienceStrategy} instance in
  * the {@link org.ehcache.Ehcache Ehcache} instance provided with a {@link
  * org.mockito.Mockito#spy(Object) Mockito <code>spy</code>} wrapping the original {@code
  * ResilienceStrategy} instance.
  *
  * @param ehcache the {@code Ehcache} instance to alter
  * @return the <code>spy</code>-wrapped {@code ResilienceStrategy} instance
  */
 protected final <K, V> ResilienceStrategy<K, V> setResilienceStrategySpy(
     final Ehcache<K, V> ehcache) {
   assert ehcache != null;
   try {
     final Field resilienceStrategyField =
         ehcache.getClass().getDeclaredField("resilienceStrategy");
     resilienceStrategyField.setAccessible(true);
     @SuppressWarnings("unchecked")
     ResilienceStrategy<K, V> resilienceStrategy =
         (ResilienceStrategy<K, V>) resilienceStrategyField.get(ehcache);
     if (resilienceStrategy != null) {
       resilienceStrategy = spy(resilienceStrategy);
       resilienceStrategyField.set(ehcache, resilienceStrategy);
     }
     return resilienceStrategy;
   } catch (Exception e) {
     throw new AssertionError(
         String.format("Unable to wrap ResilienceStrategy in Ehcache instance: %s", e));
   }
 }
Beispiel #19
0
  /**
   * An integration test, at the CacheManager level, to make sure persistence works This test checks
   * the config where a cache is not configured overflow to disk, but is disk persistent. It should
   * work by putting elements in the DiskStore initially and then loading them into memory as they
   * are called.
   */
  @Test
  public void testPersistentNonOverflowToDiskStoreFromCacheManager()
      throws IOException, InterruptedException, CacheException {
    // initialise with an instance CacheManager so that the following line actually does something
    CacheManager manager = new CacheManager(AbstractCacheTest.TEST_CONFIG_DIR + "ehcache-disk.xml");
    Ehcache cache = manager.getCache("persistentLongExpiryIntervalNonOverflowCache");

    for (int i = 0; i < 100; i++) {
      byte[] data = new byte[1024];
      cache.put(new Element("key" + (i + 100), data));
    }
    assertEquals(100, cache.getSize());

    manager.shutdown();

    manager = new CacheManager(AbstractCacheTest.TEST_CONFIG_DIR + "ehcache-disk.xml");
    cache = manager.getCache("persistentLongExpiryIntervalNonOverflowCache");

    // Now check that the DiskStore is involved in Cache methods it needs to be involved in.
    assertEquals(100, cache.getSize());
    assertEquals(100, cache.getDiskStoreSize());
    assertEquals(100, cache.getKeysNoDuplicateCheck().size());
    assertEquals(100, cache.getKeys().size());
    assertEquals(100, cache.getKeysWithExpiryCheck().size());

    // now check some of the Cache methods work
    assertNotNull(cache.get("key100"));
    assertNotNull(cache.getQuiet("key100"));
    cache.remove("key100");
    assertNull(cache.get("key100"));
    assertNull(cache.getQuiet("key100"));
    cache.removeAll();
    assertEquals(0, cache.getSize());
    assertEquals(0, cache.getDiskStoreSize());

    manager.shutdown();
  }
Beispiel #20
0
 /** Clears the statistic counters to 0 for the associated Cache. */
 public void clearStatistics() {
   if (cache == null) {
     throw new IllegalStateException("This statistics object no longer references a Cache.");
   }
   cache.clearStatistics();
 }