@Override public Object get(Object key) { return store.get(key); }
@Override public void put(Object key, Object value) { store.put(key, value); }
@Override public void evict(Object key) { this.cache.remove(key); }
@Override public boolean contains(Class<?> type, Object key) { Cache cache = getCache(type); return cache != null && !cache.isClosed() && cache.containsKey(key); }
/** Returns the object name of the management bean. */ private static ObjectName getObjectName(Cache<?, ?> cache, MBeanType type) { String cacheManagerName = sanitize(cache.getCacheManager().getURI().toString()); String cacheName = sanitize(cache.getName()); try { String name = String.format("javax.cache:type=Cache%s,CacheManager=%s,Cache=%s", type, cacheManagerName, cacheName); return new ObjectName(name); } catch (MalformedObjectNameException e) { String msg = String.format("Illegal ObjectName for cacheManager=[%s], cache=[%s]", cacheManagerName, cacheName); throw new CacheException(msg, e); } }
/** * Ensure that {@link Cache#loadAll(java.util.Set, boolean, javax.cache.integration.CompletionListener)} * won't load <code>null</code> entries. */ @Test public void shouldNotLoadMultipleNullEntriesUsingLoadAll() throws Exception { NullValueCacheLoader<String, String> cacheLoader = new NullValueCacheLoader<>(); cacheLoaderServer.setCacheLoader(cacheLoader); HashSet<String> keys = new HashSet<>(); keys.add("gudday"); keys.add("hello"); keys.add("howdy"); keys.add("bonjour"); CompletionListenerFuture future = new CompletionListenerFuture(); cache.loadAll(keys, false, future); //wait for the load to complete future.get(); assertThat(future.isDone(), is(true)); for (String key : keys) { assertThat(cache.containsKey(key), is(false)); } }
protected static <K, V extends ServerAccessToken> List<V> getTokens(Cache<K, V> cache, Client client, UserSubject sub) { final Set<K> toRemove = new HashSet<>(); final List<V> tokens = new ArrayList<>(); for (Iterator<Cache.Entry<K, V>> it = cache.iterator(); it.hasNext();) { Cache.Entry<K, V> entry = it.next(); V token = entry.getValue(); if (isExpired(token)) { toRemove.add(entry.getKey()); } else if (isTokenMatched(token, client, sub)) { tokens.add(token); } } cache.removeAll(toRemove); return tokens; }
/** * Ensure that {@link Cache#loadAll(java.util.Set, boolean, javax.cache.integration.CompletionListener)} * for a non-existent single value will cause it to be loaded. */ @Test public void shouldLoadSingleMissingEntryUsingLoadAll() throws Exception { RecordingCacheLoader<String> cacheLoader = new RecordingCacheLoader<String>(); cacheLoaderServer.setCacheLoader(cacheLoader); String key = "message"; HashSet<String> keys = new HashSet<>(); keys.add(key); assertThat(cache.containsKey(key), is(false)); CompletionListenerFuture future = new CompletionListenerFuture(); cache.loadAll(keys, false, future); //wait for the load to complete future.get(); assertThat(future.isDone(), is(true)); assertThat(cache.get(key), is(equalTo(key))); assertThat(cacheLoader.getLoadCount(), is(1)); assertThat(cacheLoader.hasLoaded(key), is(true)); }
@Test public void test_getCacheHitsAndMisses() { heapCache.put("key1", "value1"); heapCache.put("key3", "value3"); heapCache.put("key5", "value5"); HashSet<String> keys = new HashSet<>(5); for (int i = 1; i <= 5; i++) { keys.add("key" + i); } heapCache.getAll(keys); assertThat(heapStatistics.getCacheHits(), is(3L)); assertThat(heapStatistics.getCacheMisses(), is(2L)); }
@Test public void getAllShouldCallGetExpiryForAccessedEntry() { 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); Set<Integer> keys = new HashSet<>(); keys.add(1); keys.add(2); // when getting a non-existent entry, getExpiryForAccessedEntry is not called. cache.getAll(keys); assertThat(expiryPolicy.getCreationCount(), is(0)); assertThat(expiryPolicy.getAccessCount(), is(0)); assertThat(expiryPolicy.getUpdatedCount(), is(0)); cache.put(1, 1); cache.put(2, 2); assertThat(expiryPolicy.getCreationCount(), greaterThanOrEqualTo(2)); assertThat(expiryPolicy.getAccessCount(), is(0)); assertThat(expiryPolicy.getUpdatedCount(), is(0)); expiryPolicy.resetCount(); // when getting an existing entry, getExpiryForAccessedEntry is called. cache.get(1); cache.get(2); assertThat(expiryPolicy.getCreationCount(), is(0)); assertThat(expiryPolicy.getAccessCount(), greaterThanOrEqualTo(2)); assertThat(expiryPolicy.getUpdatedCount(), is(0)); expiryPolicy.resetCount(); }
@Test public void iteratorNextShouldCallGetExpiryForAccessedEntry() { 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); Set<Integer> keys = new HashSet<>(); keys.add(1); keys.add(2); cache.put(1, 1); cache.put(2, 2); assertThat(expiryPolicy.getCreationCount(), greaterThanOrEqualTo(2)); assertThat(expiryPolicy.getAccessCount(), is(0)); assertThat(expiryPolicy.getUpdatedCount(), is(0)); expiryPolicy.resetCount(); // when getting an existing entry, getExpiryForAccessedEntry is called. Iterator<Entry<Integer, Integer>> iter = cache.iterator(); int count = 0; while (iter.hasNext()) { Entry<Integer, Integer> entry = iter.next(); count++; assertThat(expiryPolicy.getCreationCount(), is(0)); assertThat(expiryPolicy.getAccessCount(), greaterThanOrEqualTo(1)); assertThat(expiryPolicy.getUpdatedCount(), is(0)); expiryPolicy.resetCount(); } }
@SuppressWarnings("unchecked") @Test public void testXmlExampleIn107() throws Exception { javax.cache.Cache<Long, Product> productCache = cacheManager.getCache("productCache", Long.class, Product.class); assertThat(productCache, is(notNullValue())); Configuration<Long, Product> configuration = productCache.getConfiguration(Configuration.class); assertThat(configuration.getKeyType(), is(equalTo(Long.class))); assertThat(configuration.getValueType(), is(equalTo(Product.class))); Eh107ReverseConfiguration<Long, Product> eh107ReverseConfiguration = productCache.getConfiguration(Eh107ReverseConfiguration.class); assertThat(eh107ReverseConfiguration.isReadThrough(), is(true)); assertThat(eh107ReverseConfiguration.isWriteThrough(), is(true)); assertThat(eh107ReverseConfiguration.isStoreByValue(), is(true)); Product product = new Product(1L); productCache.put(1L, product); assertThat(productCache.get(1L).getId(), equalTo(product.getId())); product.setMutable("foo"); assertThat(productCache.get(1L).getMutable(), nullValue()); assertThat(productCache.get(1L), not(sameInstance(product))); javax.cache.Cache<Long, Customer> customerCache = cacheManager.getCache("customerCache", Long.class, Customer.class); assertThat(customerCache, is(notNullValue())); Configuration<Long, Customer> customerConfiguration = customerCache.getConfiguration(Configuration.class); assertThat(customerConfiguration.getKeyType(), is(equalTo(Long.class))); assertThat(customerConfiguration.getValueType(), is(equalTo(Customer.class))); Customer customer = new Customer(1L); customerCache.put(1L, customer); assertThat(customerCache.get(1L).getId(), equalTo(customer.getId())); }
@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 testSimplePutIfAbsentWithLoaderAndWriter_existsInSor() throws Exception { assertThat(testCache.containsKey(1), is(false)); assertThat(testCache.putIfAbsent(1, "one"), is(true)); assertThat(testCache.get(1), Matchers.<CharSequence>equalTo("one")); verifyZeroInteractions(cacheLoader); verify(cacheWriter, times(1)).write(eq(new Eh107CacheLoaderWriter.Entry<Number, CharSequence>(1, "one"))); }
@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 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())); }
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();