@Test public void getCache() { Cache<Integer, Integer> cache = Caching.getCachingProvider() .getCacheManager().getCache("test-cache"); assertThat(cache, is(not(nullValue()))); @SuppressWarnings("unchecked") CaffeineConfiguration<Integer, Integer> config = cache.getConfiguration(CaffeineConfiguration.class); checkTestCache(config); }
public JCache(URL url) { String method = url.getParameter(Constants.METHOD_KEY, ""); String key = url.getAddress() + "." + url.getServiceKey() + "." + method; // jcache parameter is the full-qualified class name of SPI implementation String type = url.getParameter("jcache"); CachingProvider provider = StringUtils.isEmpty(type) ? Caching.getCachingProvider() : Caching.getCachingProvider(type); CacheManager cacheManager = provider.getCacheManager(); Cache<Object, Object> cache = cacheManager.getCache(key); if (cache == null) { try { //configure the cache MutableConfiguration config = new MutableConfiguration<Object, Object>() .setTypes(Object.class, Object.class) .setExpiryPolicyFactory(CreatedExpiryPolicy.factoryOf(new Duration(TimeUnit.MILLISECONDS, url.getMethodParameter(method, "cache.write.expire", 60 * 1000)))) .setStoreByValue(false) .setManagementEnabled(true) .setStatisticsEnabled(true); cache = cacheManager.createCache(key, config); } catch (CacheException e) { // concurrent cache initialization cache = cacheManager.getCache(key); } } this.store = cache; }
@Test public void testCacheManagerCloseLenientToEhcacheClosed() throws Exception { CachingProvider provider = Caching.getCachingProvider(); javax.cache.CacheManager cacheManager = provider.getCacheManager(this.getClass() .getResource("/ehcache-107-types.xml") .toURI(), getClass().getClassLoader()); MutableConfiguration<Long, String> cache1Conf = new MutableConfiguration<>(); javax.cache.Cache<Long, String> cache = cacheManager.createCache("cache1", cache1Conf); cacheManager.unwrap(org.ehcache.CacheManager.class).removeCache(cache.getName()); cacheManager.close(); } }
@Override protected Collection<Cache> loadCaches() { CacheManager cacheManager = getCacheManager(); Assert.state(cacheManager != null, "No CacheManager set"); Collection<Cache> caches = new LinkedHashSet<>(); for (String cacheName : cacheManager.getCacheNames()) { javax.cache.Cache<Object, Object> jcache = cacheManager.getCache(cacheName); caches.add(new JCacheCache(jcache, isAllowNullValues())); } return caches; }
<C extends Configuration> void createCache(final CacheManager cacheManager, final String cacheName, final C configuration) { // Make sure we start from a clean state - this is mainly useful for tests cacheManager.destroyCache(cacheName); final Cache cache = cacheManager.createCache(cacheName, configuration); Preconditions.checkState(!cache.isClosed(), "Cache '%s' should not be closed", cacheName); // Re-create the metrics to support dynamically created caches (e.g. for Shiro) metricRegistry.removeMatching(new MetricFilter() { @Override public boolean matches(final String name, final Metric metric) { return name != null && name.startsWith(PROP_METRIC_REG_JCACHE_STATISTICS); } }); metricRegistry.register(PROP_METRIC_REG_JCACHE_STATISTICS, new JCacheGaugeSet()); } }
@Test public void testManagementDisabledOverriddenFromTemplate() throws Exception { CacheManager cacheManager = provider.getCacheManager(getClass().getResource("/ehcache-107-mbeans-template-config.xml") .toURI(), provider.getDefaultClassLoader()); MutableConfiguration<Long, String> configuration = new MutableConfiguration<>(); configuration.setTypes(Long.class, String.class); configuration.setManagementEnabled(false); configuration.setStatisticsEnabled(false); Cache<Long, String> cache = cacheManager.createCache("enables-mbeans", configuration); @SuppressWarnings("unchecked") Eh107Configuration<Long, String> eh107Configuration = cache.getConfiguration(Eh107Configuration.class); assertThat(eh107Configuration.isManagementEnabled(), is(true)); assertThat(eh107Configuration.isStatisticsEnabled(), is(true)); assertThat(isMbeanRegistered("enables-mbeans", MBEAN_MANAGEMENT_TYPE), is(true)); assertThat(isMbeanRegistered("enables-mbeans", MBEAN_STATISTICS_TYPE), is(true)); }
@Test public void testEnabledAtCacheLevel() throws Exception { CacheManager cacheManager = provider.getCacheManager(getClass().getResource("/ehcache-107-mbeans-cache-config.xml") .toURI(), provider.getDefaultClassLoader()); Cache<String, String> cache = cacheManager.getCache("stringCache", String.class, String.class); @SuppressWarnings("unchecked") Eh107Configuration<String, String> configuration = cache.getConfiguration(Eh107Configuration.class); assertThat(configuration.isManagementEnabled(), is(true)); assertThat(configuration.isStatisticsEnabled(), is(true)); assertThat(isMbeanRegistered("stringCache", MBEAN_MANAGEMENT_TYPE), is(true)); assertThat(isMbeanRegistered("stringCache", MBEAN_STATISTICS_TYPE), is(true)); }
@Test public void testIterateExpiredReturnsNull() throws Exception { EhcacheCachingProvider provider = (EhcacheCachingProvider) Caching.getCachingProvider(); TestTimeSource testTimeSource = new TestTimeSource(); TimeSourceConfiguration timeSourceConfiguration = new TimeSourceConfiguration(testTimeSource); CacheManager cacheManager = provider.getCacheManager(new URI("test://testIterateExpiredReturnsNull"), new DefaultConfiguration(getClass().getClassLoader(), timeSourceConfiguration)); Cache<Number, CharSequence> testCache = cacheManager.createCache("testCache", new MutableConfiguration<Number, CharSequence>() .setExpiryPolicyFactory(() -> new ExpiryPolicy() { @Override public Duration getExpiryForCreation() { .setTypes(Number.class, CharSequence.class)); testCache.put(1, "one"); testCache.get(1); Iterator<Cache.Entry<Number, CharSequence>> iterator = testCache.iterator(); assertThat(iterator.hasNext(), is(true)); assertThat(next, is(nullValue())); assertThat(loopCount, is(1)); cacheManager.close();
@Test public void basicConfiguration() throws Exception { // tag::basicConfigurationExample[] CachingProvider provider = Caching.getCachingProvider(); // <1> CacheManager cacheManager = provider.getCacheManager(); // <2> MutableConfiguration<Long, String> configuration = new MutableConfiguration<Long, String>() // <3> .setTypes(Long.class, String.class) // <4> .setStoreByValue(false) // <5> .setExpiryPolicyFactory(CreatedExpiryPolicy.factoryOf(Duration.ONE_MINUTE)); // <6> Cache<Long, String> cache = cacheManager.createCache("jCache", configuration); // <7> cache.put(1L, "one"); // <8> String value = cache.get(1L); // <9> // end::basicConfigurationExample[] assertThat(value, is("one")); }
@Test public void testLoaderConfiguration() throws Exception { final AtomicBoolean loaderCreated = new AtomicBoolean(false); MutableConfiguration<String, String> configuration = new MutableConfiguration<>(); configuration.setTypes(String.class, String.class).setReadThrough(true); configuration.setCacheLoaderFactory(() -> { loaderCreated.set(true); return new TestCacheLoader(); }); CachingProvider provider = Caching.getCachingProvider(); CacheManager cacheManager = provider.getCacheManager(); Cache<String, String> cache = cacheManager.createCache("cache", configuration); assertThat(loaderCreated.get(), is(true)); cache.putIfAbsent("42", "The Answer"); TestCacheLoader.seen.clear(); CompletionListenerFuture future = new CompletionListenerFuture(); cache.loadAll(Collections.singleton("42"), true, future); future.get(); assertThat(TestCacheLoader.seen, contains("42")); }
@Test @SuppressWarnings("unchecked") public void testGettingToEhcacheConfiguration() { // tag::mutableConfigurationExample[] MutableConfiguration<Long, String> configuration = new MutableConfiguration<>(); configuration.setTypes(Long.class, String.class); Cache<Long, String> cache = cacheManager.createCache("someCache", configuration); // <1> CompleteConfiguration<Long, String> completeConfiguration = cache.getConfiguration(CompleteConfiguration.class); // <2> Eh107Configuration<Long, String> eh107Configuration = cache.getConfiguration(Eh107Configuration.class); // <3> CacheRuntimeConfiguration<Long, String> runtimeConfiguration = eh107Configuration.unwrap(CacheRuntimeConfiguration.class); // <4> // end::mutableConfigurationExample[] assertThat(completeConfiguration, notNullValue()); assertThat(runtimeConfiguration, notNullValue()); // Check uses default JSR-107 expiry long nanoTime = System.nanoTime(); LOGGER.info("Seeding random with {}", nanoTime); Random random = new Random(nanoTime); assertThat(runtimeConfiguration.getExpiryPolicy().getExpiryForCreation(random.nextLong(), Long.toOctalString(random.nextLong())), equalTo(org.ehcache.expiry.ExpiryPolicy.INFINITE)); assertThat(runtimeConfiguration.getExpiryPolicy().getExpiryForAccess(random.nextLong(), () -> Long.toOctalString(random.nextLong())), nullValue()); assertThat(runtimeConfiguration.getExpiryPolicy().getExpiryForUpdate(random.nextLong(), () -> Long.toOctalString(random.nextLong()), Long.toOctalString(random.nextLong())), nullValue()); }
@Test public void testTemplateAddsListeners() throws Exception { CacheManager cacheManager = cachingProvider.getCacheManager(getClass().getResource("/ehcache-107-listeners.xml") .toURI(), getClass().getClassLoader()); MutableConfiguration<String, String> configuration = new MutableConfiguration<>(); configuration.setTypes(String.class, String.class); MutableCacheEntryListenerConfiguration<String, String> listenerConfiguration = new MutableCacheEntryListenerConfiguration<>(Test107CacheEntryListener::new, null, false, true); configuration.addCacheEntryListenerConfiguration(listenerConfiguration); Cache<String, String> cache = cacheManager.createCache("foos", configuration); cache.put("Hello", "Bonjour"); assertThat(Test107CacheEntryListener.seen.size(), Matchers.is(1)); assertThat(TestCacheEventListener.seen.size(), Matchers.is(1)); }
MutableConfiguration<Long, Client> mutableConfiguration = new MutableConfiguration<>(); mutableConfiguration.setTypes(Long.class, Client.class); // <1> Cache<Long, Client> anyCache = manager.createCache("anyCache", mutableConfiguration); // <2> CacheRuntimeConfiguration<Long, Client> ehcacheConfig = (CacheRuntimeConfiguration<Long, Client>)anyCache.getConfiguration( Eh107Configuration.class).unwrap(CacheRuntimeConfiguration.class); // <3> Cache<Long, Client> anotherCache = manager.createCache("byRefCache", mutableConfiguration); assertFalse(anotherCache.getConfiguration(Configuration.class).isStoreByValue()); // <5> MutableConfiguration<String, Client> otherConfiguration = new MutableConfiguration<>(); otherConfiguration.setTypes(String.class, Client.class); otherConfiguration.setExpiryPolicyFactory(CreatedExpiryPolicy.factoryOf(Duration.ONE_MINUTE)); // <6> Cache<String, Client> foosCache = manager.createCache("foos", otherConfiguration);// <7> CacheRuntimeConfiguration<Long, Client> foosEhcacheConfig = (CacheRuntimeConfiguration<Long, Client>)foosCache.getConfiguration( Eh107Configuration.class).unwrap(CacheRuntimeConfiguration.class); Client client1 = new Client("client1", 1); assertThat(ehcacheConfig.getResourcePools().getPoolForResource(ResourceType.Core.HEAP).getSize(), is(20L)); assertThat(foosEhcacheConfig.getExpiryPolicy().getExpiryForCreation(42L, client1), is(java.time.Duration.ofMinutes(2)));
@Test public void testExpiryConfiguration() { final AtomicBoolean expiryCreated = new AtomicBoolean(false); MutableConfiguration<String, String> configuration = new MutableConfiguration<>(); configuration.setTypes(String.class, String.class); configuration.setExpiryPolicyFactory(() -> { expiryCreated.set(true); return new CreatedExpiryPolicy(Duration.FIVE_MINUTES); }); Cache<String, String> cache = cacheManager.createCache("cache", configuration); cache.putIfAbsent("42", "The Answer"); cache.putIfAbsent("42", "Or not!?"); assertThat(expiryCreated.get(), is(true)); }
@Test public void testEnableCacheLevelProgrammatic() throws Exception { CacheManager cacheManager = provider.getCacheManager(); CacheConfigurationBuilder<Long, String> configurationBuilder = newCacheConfigurationBuilder(Long.class, String.class, heap(10)) .add(new Jsr107CacheConfiguration(ConfigurationElementState.ENABLED, ConfigurationElementState.ENABLED)); Cache<Long, String> cache = cacheManager.createCache("test", Eh107Configuration.fromEhcacheCacheConfiguration(configurationBuilder)); @SuppressWarnings("unchecked") Eh107Configuration<Long, String> configuration = cache.getConfiguration(Eh107Configuration.class); assertThat(configuration.isManagementEnabled(), is(true)); assertThat(configuration.isStatisticsEnabled(), is(true)); assertThat(isMbeanRegistered("test", MBEAN_MANAGEMENT_TYPE), is(true)); assertThat(isMbeanRegistered("test", MBEAN_STATISTICS_TYPE), is(true)); }
@Test @SuppressWarnings("unchecked") public void testCompileTimeTypeSafety() throws Exception { CachingProvider provider = Caching.getCachingProvider(); javax.cache.CacheManager cacheManager = provider.getCacheManager(this.getClass().getResource("/ehcache-107-types.xml").toURI(), getClass().getClassLoader()); MutableConfiguration<Long, String> cache1Conf = new MutableConfiguration<>(); javax.cache.Cache<Long, String> cache = cacheManager.createCache("cache1", cache1Conf); cache.put(1l, "one"); cache.put(2l, "two"); Configuration<Object, Object> cache1CompleteConf = cache.getConfiguration(Configuration.class); //This ensures that we have compile time type safety, i.e when configuration does not have types defined but // what you get cache as should work. assertThat(cache1CompleteConf.getKeyType(), is(equalTo(Object.class))); assertThat(cache1CompleteConf.getValueType(), is(equalTo(Object.class))); assertThat(cache.get(1l), is(equalTo("one"))); assertThat(cache.get(2l), is(equalTo("two"))); javax.cache.Cache<String, String> second = cacheManager.getCache("cache1"); second.put("3","three"); assertThat(second.get("3"), is(equalTo("three"))); cacheManager.destroyCache("cache1"); cacheManager.close(); }
@Test public void test107LoaderOverriddenByEhcacheTemplateLoaderWriter() throws Exception { final AtomicBoolean loaderFactoryInvoked = new AtomicBoolean(false); final DumbCacheLoader product2CacheLoader = new DumbCacheLoader(); MutableConfiguration<Long, Product> product2Configuration = new MutableConfiguration<>(); product2Configuration.setTypes(Long.class, Product.class).setReadThrough(true); product2Configuration.setCacheLoaderFactory(() -> { loaderFactoryInvoked.set(true); return product2CacheLoader; }); Cache<Long, Product> productCache2 = cacheManager.createCache("productCache2", product2Configuration); assertThat(loaderFactoryInvoked.get(), is(false)); Product product = productCache2.get(124L); assertThat(product.getId(), is(124L)); assertThat(ProductCacheLoaderWriter.seen, hasItem(124L)); assertThat(product2CacheLoader.seen, is(empty())); CompletionListenerFuture future = new CompletionListenerFuture(); productCache2.loadAll(Collections.singleton(42L), false, future); future.get(); assertThat(ProductCacheLoaderWriter.seen, hasItem(42L)); assertThat(product2CacheLoader.seen, is(empty())); }
@Test public void containsKeyShouldNotCallExpiryPolicyMethods() { CountingExpiryPolicy expiryPolicy = new CountingExpiryPolicy(); expiryPolicyServer.setExpiryPolicy(expiryPolicy); MutableConfiguration<Integer, Integer> config = new MutableConfiguration<>(); config.setExpiryPolicyFactory(FactoryBuilder.factoryOf(expiryPolicyClient)); Cache<Integer, Integer> cache = getCacheManager().createCache(getTestCacheName(), config); cache.containsKey(1); assertThat(expiryPolicy.getCreationCount(), is(0)); assertThat(expiryPolicy.getAccessCount(), is(0)); assertThat(expiryPolicy.getUpdatedCount(), is(0)); cache.put(1, 1); assertThat(expiryPolicy.getCreationCount(), greaterThanOrEqualTo(1)); assertThat(expiryPolicy.getAccessCount(), is(0)); assertThat(expiryPolicy.getUpdatedCount(), is(0)); expiryPolicy.resetCount(); cache.containsKey(1); assertThat(expiryPolicy.getCreationCount(), is(0)); assertThat(expiryPolicy.getAccessCount(), is(0)); assertThat(expiryPolicy.getUpdatedCount(), is(0)); }
@Test public void testCacheUsesCacheManagerClassLoaderForDefaultURI() { CachingProvider cachingProvider = Caching.getCachingProvider(); LimitedClassLoader limitedClassLoader = new LimitedClassLoader(cachingProvider.getDefaultClassLoader()); CacheManager cacheManager = cachingProvider.getCacheManager(cachingProvider.getDefaultURI(), limitedClassLoader); MutableConfiguration<Object, Object> configuration = new MutableConfiguration<>(); Cache<Object, Object> cache = cacheManager.createCache("test", configuration); cache.put(1L, new Customer(1L)); try { cache.get(1L); fail("Expected AssertionError"); } catch (AssertionError e) { assertThat(e.getMessage(), is("No com.pany here")); } }