method2testcases
stringlengths
118
6.63k
### Question: SelfPopulatingCache extends BlockingCache { protected void refreshElement(final Element element, Ehcache backingCache) throws Exception { refreshElement(element, backingCache, true); } SelfPopulatingCache(final Ehcache cache, final CacheEntryFactory factory); Element get(final Object key); void refresh(); void refresh(boolean quiet); Element refresh(Object key); Element refresh(Object key, boolean quiet); }### Answer: @Test public void testRefreshElement() throws Exception { final IncrementingCacheEntryFactory factory = new IncrementingCacheEntryFactory(); selfPopulatingCache = new SelfPopulatingCache(cache, factory); Element e1 = selfPopulatingCache.get("key1"); Element e2 = selfPopulatingCache.get("key2"); assertEquals(2, selfPopulatingCache.getSize()); assertEquals(2, factory.getCount()); assertEquals(Integer.valueOf(1), e1.getValue()); assertEquals(Integer.valueOf(2), e2.getValue()); selfPopulatingCache.refresh(); e1 = selfPopulatingCache.get("key1"); e2 = selfPopulatingCache.get("key2"); assertEquals(2, selfPopulatingCache.getSize()); assertEquals(4, factory.getCount()); int e1i = ((Integer) e1.getValue()).intValue(); int e2i = ((Integer) e2.getValue()).intValue(); assertTrue(((e1i == 3) && (e2i == 4)) || ((e1i == 4) && (e2i == 3))); selfPopulatingCache.get("key2"); Element e2r = selfPopulatingCache.refresh("key2"); assertEquals(2, selfPopulatingCache.getSize()); assertEquals(5, factory.getCount()); assertNotNull(e2r); assertEquals("key2", e2r.getKey()); assertEquals(Integer.valueOf(5), e2r.getValue()); Element e3 = selfPopulatingCache.get("key3"); assertEquals(3, selfPopulatingCache.getSize()); assertEquals(6, factory.getCount()); assertNotNull(e3); assertEquals("key3", e3.getKey()); assertEquals(Integer.valueOf(6), e3.getValue()); selfPopulatingCache.refresh(); assertEquals(3, selfPopulatingCache.getSize()); assertEquals(9, factory.getCount()); } @Test public void testRefreshElement() throws Exception { final IncrementingCacheEntryFactory factory = new IncrementingCacheEntryFactory(); selfPopulatingCache = new SelfPopulatingCache(cache, factory); Element e1 = selfPopulatingCache.get("key1"); Element e2 = selfPopulatingCache.get("key2"); assertEquals(2, selfPopulatingCache.getSize()); assertEquals(2, factory.getCount()); assertEquals(new Integer(1), e1.getValue()); assertEquals(new Integer(2), e2.getValue()); selfPopulatingCache.refresh(); e1 = selfPopulatingCache.get("key1"); e2 = selfPopulatingCache.get("key2"); assertEquals(2, selfPopulatingCache.getSize()); assertEquals(4, factory.getCount()); int e1i = ((Integer) e1.getValue()).intValue(); int e2i = ((Integer) e2.getValue()).intValue(); assertTrue(((e1i == 3) && (e2i == 4)) || ((e1i == 4) && (e2i == 3))); selfPopulatingCache.get("key2"); Element e2r = selfPopulatingCache.refresh("key2"); assertEquals(2, selfPopulatingCache.getSize()); assertEquals(5, factory.getCount()); assertNotNull(e2r); assertEquals("key2", e2r.getKey()); assertEquals(new Integer(5), e2r.getValue()); Element e3 = selfPopulatingCache.get("key3"); assertEquals(3, selfPopulatingCache.getSize()); assertEquals(6, factory.getCount()); assertNotNull(e3); assertEquals("key3", e3.getKey()); assertEquals(new Integer(6), e3.getValue()); selfPopulatingCache.refresh(); assertEquals(3, selfPopulatingCache.getSize()); assertEquals(9, factory.getCount()); }
### Question: BlockingCache implements Ehcache { protected Ehcache getCache() { return cache; } BlockingCache(final Ehcache cache, int numberOfStripes); BlockingCache(final Ehcache cache); String getName(); void setName(String name); boolean isExpired(Element element); @Override Object clone(); RegisteredEventListeners getCacheEventNotificationService(); boolean isElementInMemory(Serializable key); boolean isElementInMemory(Object key); boolean isElementOnDisk(Serializable key); boolean isElementOnDisk(Object key); String getGuid(); CacheManager getCacheManager(); void clearStatistics(); int getStatisticsAccuracy(); void setStatisticsAccuracy(int statisticsAccuracy); void evictExpiredElements(); boolean isKeyInCache(Object key); boolean isValueInCache(Object value); Statistics getStatistics(); LiveCacheStatistics getLiveCacheStatistics(); void setCacheManager(CacheManager cacheManager); BootstrapCacheLoader getBootstrapCacheLoader(); void setBootstrapCacheLoader(BootstrapCacheLoader bootstrapCacheLoader); void setDiskStorePath(String diskStorePath); void initialise(); void bootstrap(); void dispose(); CacheConfiguration getCacheConfiguration(); Element get(final Object key); CacheWriterManager getWriterManager(); void put(Element element); void put(Element element, boolean doNotNotifyCacheReplicators); void putQuiet(Element element); void putWithWriter(Element element); Element get(Serializable key); Element getQuiet(Serializable key); Element getQuiet(Object key); List getKeys(); List getKeysWithExpiryCheck(); List getKeysNoDuplicateCheck(); boolean remove(Serializable key); boolean remove(Object key); boolean remove(Serializable key, boolean doNotNotifyCacheReplicators); boolean remove(Object key, boolean doNotNotifyCacheReplicators); boolean removeQuiet(Serializable key); boolean removeQuiet(Object key); boolean removeWithWriter(Object key); void removeAll(); void removeAll(boolean doNotNotifyCacheReplicators); void flush(); int getSize(); int getSizeBasedOnAccuracy(int statisticsAccuracy); long calculateInMemorySize(); long getMemoryStoreSize(); int getDiskStoreSize(); Status getStatus(); synchronized String liveness(); void setTimeoutMillis(int timeoutMillis); int getTimeoutMillis(); void registerCacheExtension(CacheExtension cacheExtension); void unregisterCacheExtension(CacheExtension cacheExtension); List<CacheExtension> getRegisteredCacheExtensions(); float getAverageGetTime(); void setCacheExceptionHandler(CacheExceptionHandler cacheExceptionHandler); CacheExceptionHandler getCacheExceptionHandler(); void registerCacheLoader(CacheLoader cacheLoader); void unregisterCacheLoader(CacheLoader cacheLoader); List<CacheLoader> getRegisteredCacheLoaders(); void registerCacheWriter(CacheWriter cacheWriter); void unregisterCacheWriter(); CacheWriter getRegisteredCacheWriter(); Element getWithLoader(Object key, CacheLoader loader, Object loaderArgument); Map getAllWithLoader(Collection keys, Object loaderArgument); void load(Object key); void loadAll(Collection keys, Object argument); boolean isDisabled(); void setDisabled(boolean disabled); void registerCacheUsageListener(CacheUsageListener cacheUsageListener); void removeCacheUsageListener(CacheUsageListener cacheUsageListener); boolean isStatisticsEnabled(); void setStatisticsEnabled(boolean enabledStatistics); SampledCacheStatistics getSampledCacheStatistics(); void setSampledStatisticsEnabled(boolean enabledStatistics); boolean isSampledStatisticsEnabled(); Object getInternalContext(); void disableDynamicFeatures(); boolean isClusterCoherent(); boolean isNodeCoherent(); void setNodeCoherent(boolean coherent); void waitUntilClusterCoherent(); void setTransactionManagerLookup(TransactionManagerLookup transactionManagerLookup); }### Answer: @Test public void testThrashBlockingCache() throws Exception { Ehcache cache = manager.getCache("sampleCache1"); blockingCache = new BlockingCache(cache); long duration = thrashCache(blockingCache, 50, 500L, 1000L); LOG.debug("Thrash Duration:" + duration); }
### Question: BlockingCache implements Ehcache { public Element getWithLoader(Object key, CacheLoader loader, Object loaderArgument) throws CacheException { throw new CacheException("This method is not appropriate for a Blocking Cache"); } BlockingCache(final Ehcache cache, int numberOfStripes); BlockingCache(final Ehcache cache); String getName(); void setName(String name); boolean isExpired(Element element); @Override Object clone(); RegisteredEventListeners getCacheEventNotificationService(); boolean isElementInMemory(Serializable key); boolean isElementInMemory(Object key); boolean isElementOnDisk(Serializable key); boolean isElementOnDisk(Object key); String getGuid(); CacheManager getCacheManager(); void clearStatistics(); int getStatisticsAccuracy(); void setStatisticsAccuracy(int statisticsAccuracy); void evictExpiredElements(); boolean isKeyInCache(Object key); boolean isValueInCache(Object value); Statistics getStatistics(); LiveCacheStatistics getLiveCacheStatistics(); void setCacheManager(CacheManager cacheManager); BootstrapCacheLoader getBootstrapCacheLoader(); void setBootstrapCacheLoader(BootstrapCacheLoader bootstrapCacheLoader); void setDiskStorePath(String diskStorePath); void initialise(); void bootstrap(); void dispose(); CacheConfiguration getCacheConfiguration(); Element get(final Object key); CacheWriterManager getWriterManager(); void put(Element element); void put(Element element, boolean doNotNotifyCacheReplicators); void putQuiet(Element element); void putWithWriter(Element element); Element get(Serializable key); Element getQuiet(Serializable key); Element getQuiet(Object key); List getKeys(); List getKeysWithExpiryCheck(); List getKeysNoDuplicateCheck(); boolean remove(Serializable key); boolean remove(Object key); boolean remove(Serializable key, boolean doNotNotifyCacheReplicators); boolean remove(Object key, boolean doNotNotifyCacheReplicators); boolean removeQuiet(Serializable key); boolean removeQuiet(Object key); boolean removeWithWriter(Object key); void removeAll(); void removeAll(boolean doNotNotifyCacheReplicators); void flush(); int getSize(); int getSizeBasedOnAccuracy(int statisticsAccuracy); long calculateInMemorySize(); long getMemoryStoreSize(); int getDiskStoreSize(); Status getStatus(); synchronized String liveness(); void setTimeoutMillis(int timeoutMillis); int getTimeoutMillis(); void registerCacheExtension(CacheExtension cacheExtension); void unregisterCacheExtension(CacheExtension cacheExtension); List<CacheExtension> getRegisteredCacheExtensions(); float getAverageGetTime(); void setCacheExceptionHandler(CacheExceptionHandler cacheExceptionHandler); CacheExceptionHandler getCacheExceptionHandler(); void registerCacheLoader(CacheLoader cacheLoader); void unregisterCacheLoader(CacheLoader cacheLoader); List<CacheLoader> getRegisteredCacheLoaders(); void registerCacheWriter(CacheWriter cacheWriter); void unregisterCacheWriter(); CacheWriter getRegisteredCacheWriter(); Element getWithLoader(Object key, CacheLoader loader, Object loaderArgument); Map getAllWithLoader(Collection keys, Object loaderArgument); void load(Object key); void loadAll(Collection keys, Object argument); boolean isDisabled(); void setDisabled(boolean disabled); void registerCacheUsageListener(CacheUsageListener cacheUsageListener); void removeCacheUsageListener(CacheUsageListener cacheUsageListener); boolean isStatisticsEnabled(); void setStatisticsEnabled(boolean enabledStatistics); SampledCacheStatistics getSampledCacheStatistics(); void setSampledStatisticsEnabled(boolean enabledStatistics); boolean isSampledStatisticsEnabled(); Object getInternalContext(); void disableDynamicFeatures(); boolean isClusterCoherent(); boolean isNodeCoherent(); void setNodeCoherent(boolean coherent); void waitUntilClusterCoherent(); void setTransactionManagerLookup(TransactionManagerLookup transactionManagerLookup); }### Answer: @Test public void testGetWithLoader() { super.testGetWithLoader(); }
### Question: CacheWriterConfiguration implements Cloneable { public CacheWriterConfiguration writeMode(String writeMode) { setWriteMode(writeMode); return this; } @Override CacheWriterConfiguration clone(); void setWriteMode(String writeMode); CacheWriterConfiguration writeMode(String writeMode); CacheWriterConfiguration writeMode(WriteMode writeMode); WriteMode getWriteMode(); void setNotifyListenersOnException(boolean notifyListenersOnException); CacheWriterConfiguration notifyListenersOnException(boolean notifyListenersOnException); boolean getNotifyListenersOnException(); void setMinWriteDelay(int minWriteDelay); CacheWriterConfiguration minWriteDelay(int minWriteDelay); int getMinWriteDelay(); void setMaxWriteDelay(int maxWriteDelay); CacheWriterConfiguration maxWriteDelay(int maxWriteDelay); int getMaxWriteDelay(); void setRateLimitPerSecond(int rateLimitPerSecond); CacheWriterConfiguration rateLimitPerSecond(int rateLimitPerSecond); int getRateLimitPerSecond(); void setWriteCoalescing(boolean writeCoalescing); CacheWriterConfiguration writeCoalescing(boolean writeCoalescing); boolean getWriteCoalescing(); void setWriteBatching(boolean writeBatching); CacheWriterConfiguration writeBatching(boolean writeBatching); boolean getWriteBatching(); void setWriteBatchSize(int writeBatchSize); CacheWriterConfiguration writeBatchSize(int writeBatchSize); int getWriteBatchSize(); void setRetryAttempts(int retryAttempts); CacheWriterConfiguration retryAttempts(int retryAttempts); int getRetryAttempts(); void setRetryAttemptDelaySeconds(int retryAttemptDelaySeconds); CacheWriterConfiguration retryAttemptDelaySeconds(int retryAttemptDelaySeconds); int getRetryAttemptDelaySeconds(); final void addCacheWriterFactory(CacheWriterFactoryConfiguration cacheWriterFactoryConfiguration); CacheWriterConfiguration cacheWriterFactory(CacheWriterFactoryConfiguration cacheWriterFactory); CacheWriterFactoryConfiguration getCacheWriterFactoryConfiguration(); static final WriteMode DEFAULT_WRITE_MODE; static final boolean DEFAULT_NOTIFY_LISTENERS_ON_EXCEPTION; static final int DEFAULT_MIN_WRITE_DELAY; static final int DEFAULT_MAX_WRITE_DELAY; static final int DEFAULT_RATE_LIMIT_PER_SECOND; static final boolean DEFAULT_WRITE_COALESCING; static final boolean DEFAULT_WRITE_BATCHING; static final int DEFAULT_WRITE_BATCH_SIZE; static final int DEFAULT_RETRY_ATTEMPTS; static final int DEFAULT_RETRY_ATTEMPT_DELAY_SECONDS; }### Answer: @Test(expected = IllegalArgumentException.class) public void testNullWriteMode() { CacheWriterConfiguration config = new CacheWriterConfiguration() .writeMode((CacheWriterConfiguration.WriteMode) null); } @Test(expected = IllegalArgumentException.class) public void testInvalidWriteMode() { CacheWriterConfiguration config = new CacheWriterConfiguration() .writeMode("invalid"); }
### Question: UpdateChecker extends TimerTask { public void checkForUpdate() { try { if (!Boolean.getBoolean("net.sf.ehcache.skipUpdateCheck")) { doCheck(); } } catch (Throwable t) { LOG.debug("Update check failed: " + t.toString()); } } @Override void run(); void checkForUpdate(); }### Answer: @Test public void testErrorNotBubleUp() { System.setProperty("net.sf.ehcache.skipUpdateCheck", "false"); System.setProperty("ehcache.update-check.url", "this is a bad url"); UpdateChecker uc = new UpdateChecker(); uc.checkForUpdate(); }
### Question: SlewClock { static long timeMillis() { boolean interrupted = false; try { while (true) { long mono = CURRENT.get(); long wall = getCurrentTime(); if (wall == mono) { OFFSET.remove(); return wall; } else if (wall >= mono) { if (CURRENT.compareAndSet(mono, wall)) { OFFSET.remove(); return wall; } } else { long delta = mono - wall; if (delta < DRIFT_MAXIMAL) { OFFSET.remove(); return mono; } else { Long lastDelta = OFFSET.get(); if (lastDelta == null || delta < lastDelta) { long update = wall - delta; update = update < mono ? mono + 1 : update; if (CURRENT.compareAndSet(mono, update)) { OFFSET.set(Long.valueOf(delta)); return update; } } else { try { Thread.sleep(sleepTime(delta, lastDelta)); } catch (InterruptedException e) { interrupted = true; } } } } } } finally { if (interrupted) { Thread.currentThread().interrupt(); } } } private SlewClock(); }### Answer: @Test public void testTimeMillis() throws Throwable { final AtomicLong slewStart = new AtomicLong(); final AtomicLong offset = new AtomicLong(0); final List<Throwable> errors = Collections.synchronizedList(new ArrayList<Throwable>()); TimeProviderLoader.setTimeProvider(new SlewClock.TimeProvider() { public long currentTimeMillis() { return System.currentTimeMillis() - offset.get(); } }); final AtomicBoolean stopped = new AtomicBoolean(false); final AtomicInteger catchingUp = new AtomicInteger(); SlewClockVerifierThread[] threads = new SlewClockVerifierThread[THREADS]; for(int i =0; i < THREADS; i++) { threads[i] = new SlewClockVerifierThread(stopped, catchingUp, errors, slewStart, i == 0); } for (Thread thread : threads) { thread.start(); } Thread.sleep(TimeUnit.SECONDS.toMillis(DURATION)); System.out.println("Going back in time by " + BACK_IN_TIME); slewStart.set(System.currentTimeMillis()); offset.set(BACK_IN_TIME); Thread.sleep(SLOWRUN ? BACK_IN_TIME * 3 : BACK_IN_TIME * 2); stopped.set(true); for (SlewClockVerifierThread thread : threads) { thread.join(); } if(!errors.isEmpty()) { System.err.println("We have " + errors.size() + " error(s) here!"); throw errors.get(0); } assertThat(catchingUp.get(), is(THREADS)); }
### Question: CacheManager { public void shutdown() { synchronized (CacheManager.class) { if (status.equals(Status.STATUS_SHUTDOWN)) { LOG.debug("CacheManager already shutdown"); return; } for (CacheManagerPeerProvider cacheManagerPeerProvider : cacheManagerPeerProviders.values()) { if (cacheManagerPeerProvider != null) { cacheManagerPeerProvider.dispose(); } } if (cacheManagerTimer != null) { cacheManagerTimer.cancel(); cacheManagerTimer.purge(); } cacheManagerEventListenerRegistry.dispose(); synchronized (CacheManager.class) { ALL_CACHE_MANAGERS.remove(this); Collection cacheSet = ehcaches.values(); for (Iterator iterator = cacheSet.iterator(); iterator.hasNext();) { Ehcache cache = (Ehcache) iterator.next(); if (cache != null) { cache.dispose(); } } defaultCache.dispose(); status = Status.STATUS_SHUTDOWN; if (this == singleton) { singleton = null; } removeShutdownHook(); } } } CacheManager(Configuration configuration); CacheManager(String configurationFileName); CacheManager(URL configurationURL); CacheManager(InputStream configurationInputStream); CacheManager(); String getClusterUUID(); Store createTerracottaStore(Ehcache cache); WriteBehind createTerracottaWriteBehind(Ehcache cache); CacheEventListener createTerracottaEventReplicator(Ehcache cache); static CacheManager create(); static CacheManager getInstance(); static CacheManager create(String configurationFileName); static CacheManager create(URL configurationFileURL); static CacheManager create(InputStream inputStream); Cache getCache(String name); Ehcache getEhcache(String name); void addCache(String cacheName); void addCache(Cache cache); void addCache(Ehcache cache); boolean cacheExists(String cacheName); void removalAll(); void removeCache(String cacheName); void shutdown(); String[] getCacheNames(); Status getStatus(); void clearAll(); void clearAllStartingWith(String prefix); CacheManagerPeerProvider getCacheManagerPeerProvider(String scheme); CacheManagerPeerListener getCachePeerListener(String scheme); CacheManagerEventListener getCacheManagerEventListener(); void setCacheManagerEventListener(CacheManagerEventListener cacheManagerEventListener); CacheManagerEventListenerRegistry getCacheManagerEventListenerRegistry(); void replaceCacheWithDecoratedCache(Ehcache ehcache, Ehcache decoratedCache); String getName(); boolean isNamed(); void setName(String name); @Override String toString(); String getDiskStorePath(); FailSafeTimer getTimer(); CacheCluster getCluster(ClusterScheme scheme); String getOriginalConfigurationText(); String getActiveConfigurationText(); String getOriginalConfigurationText(String cacheName); String getActiveConfigurationText(String cacheName); @Override int hashCode(); static final List<CacheManager> ALL_CACHE_MANAGERS; static final String ENABLE_SHUTDOWN_HOOK_PROPERTY; }### Answer: @Test public void testForCacheManagerThreadLeak() throws CacheException, InterruptedException { int startingThreadCount = countThreads(); URL secondCacheConfiguration = this.getClass().getResource( "/ehcache-2.xml"); for (int i = 0; i < 100; i++) { instanceManager = new CacheManager(secondCacheConfiguration); instanceManager.shutdown(); } int endingThreadCount; int tries = 0; do { Thread.sleep(500); endingThreadCount = countThreads(); } while (tries++ < 5 || endingThreadCount >= startingThreadCount + 2); assertTrue(endingThreadCount < startingThreadCount + 2); } @Test public void testMultipleCacheManagers() { CacheManager[] managers = new CacheManager[2]; managers[0] = new CacheManager(makeCacheManagerConfig()); managers[1] = new CacheManager(makeCacheManagerConfig()); managers[0].shutdown(); managers[1].shutdown(); }
### Question: CacheManager { public static CacheManager create() throws CacheException { if (singleton != null) { return singleton; } synchronized (CacheManager.class) { if (singleton == null) { LOG.debug("Creating new CacheManager with default config"); singleton = new CacheManager(); } else { LOG.debug("Attempting to create an existing singleton. Existing singleton returned."); } return singleton; } } CacheManager(Configuration configuration); CacheManager(String configurationFileName); CacheManager(URL configurationURL); CacheManager(InputStream configurationInputStream); CacheManager(); String getClusterUUID(); Store createTerracottaStore(Ehcache cache); WriteBehind createTerracottaWriteBehind(Ehcache cache); CacheEventListener createTerracottaEventReplicator(Ehcache cache); static CacheManager create(); static CacheManager getInstance(); static CacheManager create(String configurationFileName); static CacheManager create(URL configurationFileURL); static CacheManager create(InputStream inputStream); Cache getCache(String name); Ehcache getEhcache(String name); void addCache(String cacheName); void addCache(Cache cache); void addCache(Ehcache cache); boolean cacheExists(String cacheName); void removalAll(); void removeCache(String cacheName); void shutdown(); String[] getCacheNames(); Status getStatus(); void clearAll(); void clearAllStartingWith(String prefix); CacheManagerPeerProvider getCacheManagerPeerProvider(String scheme); CacheManagerPeerListener getCachePeerListener(String scheme); CacheManagerEventListener getCacheManagerEventListener(); void setCacheManagerEventListener(CacheManagerEventListener cacheManagerEventListener); CacheManagerEventListenerRegistry getCacheManagerEventListenerRegistry(); void replaceCacheWithDecoratedCache(Ehcache ehcache, Ehcache decoratedCache); String getName(); boolean isNamed(); void setName(String name); @Override String toString(); String getDiskStorePath(); FailSafeTimer getTimer(); CacheCluster getCluster(ClusterScheme scheme); String getOriginalConfigurationText(); String getActiveConfigurationText(); String getOriginalConfigurationText(String cacheName); String getActiveConfigurationText(String cacheName); @Override int hashCode(); static final List<CacheManager> ALL_CACHE_MANAGERS; static final String ENABLE_SHUTDOWN_HOOK_PROPERTY; }### Answer: @Test public void testCacheManagerThreads() throws CacheException, InterruptedException { singletonManager = CacheManager .create(AbstractCacheTest.TEST_CONFIG_DIR + "ehcache-big.xml"); int threads = countThreads(); assertTrue("More than 145 threads: " + threads, countThreads() <= 145); }
### Question: CacheManager { public Cache getCache(String name) throws IllegalStateException, ClassCastException { checkStatus(); return (Cache) caches.get(name); } CacheManager(Configuration configuration); CacheManager(String configurationFileName); CacheManager(URL configurationURL); CacheManager(InputStream configurationInputStream); CacheManager(); String getClusterUUID(); Store createTerracottaStore(Ehcache cache); WriteBehind createTerracottaWriteBehind(Ehcache cache); CacheEventListener createTerracottaEventReplicator(Ehcache cache); static CacheManager create(); static CacheManager getInstance(); static CacheManager create(String configurationFileName); static CacheManager create(URL configurationFileURL); static CacheManager create(InputStream inputStream); Cache getCache(String name); Ehcache getEhcache(String name); void addCache(String cacheName); void addCache(Cache cache); void addCache(Ehcache cache); boolean cacheExists(String cacheName); void removalAll(); void removeCache(String cacheName); void shutdown(); String[] getCacheNames(); Status getStatus(); void clearAll(); void clearAllStartingWith(String prefix); CacheManagerPeerProvider getCacheManagerPeerProvider(String scheme); CacheManagerPeerListener getCachePeerListener(String scheme); CacheManagerEventListener getCacheManagerEventListener(); void setCacheManagerEventListener(CacheManagerEventListener cacheManagerEventListener); CacheManagerEventListenerRegistry getCacheManagerEventListenerRegistry(); void replaceCacheWithDecoratedCache(Ehcache ehcache, Ehcache decoratedCache); String getName(); boolean isNamed(); void setName(String name); @Override String toString(); String getDiskStorePath(); FailSafeTimer getTimer(); CacheCluster getCluster(ClusterScheme scheme); String getOriginalConfigurationText(); String getActiveConfigurationText(); String getOriginalConfigurationText(String cacheName); String getActiveConfigurationText(String cacheName); @Override int hashCode(); static final List<CacheManager> ALL_CACHE_MANAGERS; static final String ENABLE_SHUTDOWN_HOOK_PROPERTY; }### Answer: @Test public void testGetCache() throws CacheException { instanceManager = CacheManager.create(); Ehcache cache = instanceManager.getCache("sampleCache1"); assertNotNull(cache); }
### Question: CacheManager { public void removeCache(String cacheName) throws IllegalStateException { checkStatus(); if (cacheName == null || cacheName.length() == 0) { return; } Ehcache cache = (Ehcache) ehcaches.remove(cacheName); if (cache != null && cache.getStatus().equals(Status.STATUS_ALIVE)) { cache.dispose(); cacheManagerEventListenerRegistry.notifyCacheRemoved(cache.getName()); } caches.remove(cacheName); } CacheManager(Configuration configuration); CacheManager(String configurationFileName); CacheManager(URL configurationURL); CacheManager(InputStream configurationInputStream); CacheManager(); String getClusterUUID(); Store createTerracottaStore(Ehcache cache); WriteBehind createTerracottaWriteBehind(Ehcache cache); CacheEventListener createTerracottaEventReplicator(Ehcache cache); static CacheManager create(); static CacheManager getInstance(); static CacheManager create(String configurationFileName); static CacheManager create(URL configurationFileURL); static CacheManager create(InputStream inputStream); Cache getCache(String name); Ehcache getEhcache(String name); void addCache(String cacheName); void addCache(Cache cache); void addCache(Ehcache cache); boolean cacheExists(String cacheName); void removalAll(); void removeCache(String cacheName); void shutdown(); String[] getCacheNames(); Status getStatus(); void clearAll(); void clearAllStartingWith(String prefix); CacheManagerPeerProvider getCacheManagerPeerProvider(String scheme); CacheManagerPeerListener getCachePeerListener(String scheme); CacheManagerEventListener getCacheManagerEventListener(); void setCacheManagerEventListener(CacheManagerEventListener cacheManagerEventListener); CacheManagerEventListenerRegistry getCacheManagerEventListenerRegistry(); void replaceCacheWithDecoratedCache(Ehcache ehcache, Ehcache decoratedCache); String getName(); boolean isNamed(); void setName(String name); @Override String toString(); String getDiskStorePath(); FailSafeTimer getTimer(); CacheCluster getCluster(ClusterScheme scheme); String getOriginalConfigurationText(); String getActiveConfigurationText(); String getOriginalConfigurationText(String cacheName); String getActiveConfigurationText(String cacheName); @Override int hashCode(); static final List<CacheManager> ALL_CACHE_MANAGERS; static final String ENABLE_SHUTDOWN_HOOK_PROPERTY; }### Answer: @Test public void testRemoveCache() throws CacheException { singletonManager = CacheManager.create(); Ehcache cache = singletonManager.getCache("sampleCache1"); assertNotNull(cache); singletonManager.removeCache("sampleCache1"); cache = singletonManager.getCache("sampleCache1"); assertNull(cache); singletonManager.removeCache(null); singletonManager.removeCache(""); }
### Question: CacheManager { public void addCache(String cacheName) throws IllegalStateException, ObjectExistsException, CacheException { checkStatus(); if (cacheName == null || cacheName.length() == 0) { return; } if (ehcaches.get(cacheName) != null) { throw new ObjectExistsException("Cache " + cacheName + " already exists"); } Ehcache cache = null; try { cache = (Ehcache) defaultCache.clone(); } catch (CloneNotSupportedException e) { throw new CacheException("Failure adding cache. Initial cause was " + e.getMessage(), e); } if (cache != null) { cache.setName(cacheName); } addCache(cache); } CacheManager(Configuration configuration); CacheManager(String configurationFileName); CacheManager(URL configurationURL); CacheManager(InputStream configurationInputStream); CacheManager(); String getClusterUUID(); Store createTerracottaStore(Ehcache cache); WriteBehind createTerracottaWriteBehind(Ehcache cache); CacheEventListener createTerracottaEventReplicator(Ehcache cache); static CacheManager create(); static CacheManager getInstance(); static CacheManager create(String configurationFileName); static CacheManager create(URL configurationFileURL); static CacheManager create(InputStream inputStream); Cache getCache(String name); Ehcache getEhcache(String name); void addCache(String cacheName); void addCache(Cache cache); void addCache(Ehcache cache); boolean cacheExists(String cacheName); void removalAll(); void removeCache(String cacheName); void shutdown(); String[] getCacheNames(); Status getStatus(); void clearAll(); void clearAllStartingWith(String prefix); CacheManagerPeerProvider getCacheManagerPeerProvider(String scheme); CacheManagerPeerListener getCachePeerListener(String scheme); CacheManagerEventListener getCacheManagerEventListener(); void setCacheManagerEventListener(CacheManagerEventListener cacheManagerEventListener); CacheManagerEventListenerRegistry getCacheManagerEventListenerRegistry(); void replaceCacheWithDecoratedCache(Ehcache ehcache, Ehcache decoratedCache); String getName(); boolean isNamed(); void setName(String name); @Override String toString(); String getDiskStorePath(); FailSafeTimer getTimer(); CacheCluster getCluster(ClusterScheme scheme); String getOriginalConfigurationText(); String getActiveConfigurationText(); String getOriginalConfigurationText(String cacheName); String getActiveConfigurationText(String cacheName); @Override int hashCode(); static final List<CacheManager> ALL_CACHE_MANAGERS; static final String ENABLE_SHUTDOWN_HOOK_PROPERTY; }### Answer: @Test public void testAddCache() throws CacheException { singletonManager = CacheManager.create(); singletonManager.addCache("test"); singletonManager.addCache("test2"); 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); singletonManager.addCache(""); }
### Question: Statistics implements Serializable { public void clearStatistics() { if (cache == null) { throw new IllegalStateException("This statistics object no longer references a Cache."); } cache.clearStatistics(); } Statistics(Ehcache cache, int statisticsAccuracy, long cacheHits, long onDiskHits, long inMemoryHits, long misses, long size, float averageGetTime, long evictionCount, long memoryStoreSize, long diskStoreSize); void clearStatistics(); long getCacheHits(); long getInMemoryHits(); long getOnDiskHits(); long getCacheMisses(); long getObjectCount(); long getMemoryStoreObjectCount(); long getDiskStoreObjectCount(); int getStatisticsAccuracy(); String getStatisticsAccuracyDescription(); String getAssociatedCacheName(); Ehcache getAssociatedCache(); @Override final String toString(); float getAverageGetTime(); long getEvictionCount(); static boolean isValidStatisticsAccuracy(int statisticsAccuracy); static final int STATISTICS_ACCURACY_NONE; static final int STATISTICS_ACCURACY_BEST_EFFORT; static final int STATISTICS_ACCURACY_GUARANTEED; }### Answer: @Test public void testClearStatistics() throws InterruptedException { Cache cache = new Cache("test", 1, true, false, 5, 2); manager.addCache(cache); cache.put(new Element("key1", "value1")); cache.put(new Element("key2", "value1")); cache.get("key1"); Statistics statistics = cache.getStatistics(); assertEquals(1, statistics.getCacheHits()); assertEquals(1, statistics.getOnDiskHits()); assertEquals(0, statistics.getInMemoryHits()); assertEquals(0, statistics.getCacheMisses()); statistics.clearStatistics(); statistics = cache.getStatistics(); assertEquals(0, statistics.getCacheHits()); assertEquals(0, statistics.getOnDiskHits()); assertEquals(0, statistics.getInMemoryHits()); assertEquals(0, statistics.getCacheMisses()); } @Test public void testClearStatistics() throws InterruptedException { Cache cache = new Cache("test", 1, true, false, 5, 2); manager.addCache(cache); cache.setStatisticsEnabled(true); cache.put(new Element("key1", "value1")); cache.put(new Element("key2", "value1")); cache.get("key1"); Statistics statistics = cache.getStatistics(); assertEquals(1, statistics.getCacheHits()); assertEquals(1, statistics.getOnDiskHits()); assertEquals(0, statistics.getInMemoryHits()); assertEquals(0, statistics.getCacheMisses()); statistics.clearStatistics(); statistics = cache.getStatistics(); assertEquals(0, statistics.getCacheHits()); assertEquals(0, statistics.getOnDiskHits()); assertEquals(0, statistics.getInMemoryHits()); assertEquals(0, statistics.getCacheMisses()); }
### Question: BlockingCache implements Ehcache { protected Ehcache getCache() { return cache; } BlockingCache(final Ehcache cache, int numberOfStripes); BlockingCache(final Ehcache cache); String getName(); void setName(String name); boolean isExpired(Element element); @Override Object clone(); RegisteredEventListeners getCacheEventNotificationService(); boolean isElementInMemory(Serializable key); boolean isElementInMemory(Object key); boolean isElementOnDisk(Serializable key); boolean isElementOnDisk(Object key); String getGuid(); CacheManager getCacheManager(); void clearStatistics(); int getStatisticsAccuracy(); void setStatisticsAccuracy(int statisticsAccuracy); void evictExpiredElements(); boolean isKeyInCache(Object key); boolean isValueInCache(Object value); Statistics getStatistics(); LiveCacheStatistics getLiveCacheStatistics(); void setCacheManager(CacheManager cacheManager); BootstrapCacheLoader getBootstrapCacheLoader(); void setBootstrapCacheLoader(BootstrapCacheLoader bootstrapCacheLoader); void setDiskStorePath(String diskStorePath); void initialise(); void bootstrap(); void dispose(); CacheConfiguration getCacheConfiguration(); Element get(final Object key); CacheWriterManager getWriterManager(); void put(Element element); void put(Element element, boolean doNotNotifyCacheReplicators); void putQuiet(Element element); void putWithWriter(Element element); Element get(Serializable key); Element getQuiet(Serializable key); Element getQuiet(Object key); List getKeys(); List getKeysWithExpiryCheck(); List getKeysNoDuplicateCheck(); boolean remove(Serializable key); boolean remove(Object key); boolean remove(Serializable key, boolean doNotNotifyCacheReplicators); boolean remove(Object key, boolean doNotNotifyCacheReplicators); boolean removeQuiet(Serializable key); boolean removeQuiet(Object key); boolean removeWithWriter(Object key); void removeAll(); void removeAll(boolean doNotNotifyCacheReplicators); void flush(); int getSize(); int getSizeBasedOnAccuracy(int statisticsAccuracy); long calculateInMemorySize(); long getMemoryStoreSize(); int getDiskStoreSize(); Status getStatus(); synchronized String liveness(); void setTimeoutMillis(int timeoutMillis); int getTimeoutMillis(); void registerCacheExtension(CacheExtension cacheExtension); void unregisterCacheExtension(CacheExtension cacheExtension); List<CacheExtension> getRegisteredCacheExtensions(); float getAverageGetTime(); void setCacheExceptionHandler(CacheExceptionHandler cacheExceptionHandler); CacheExceptionHandler getCacheExceptionHandler(); void registerCacheLoader(CacheLoader cacheLoader); void unregisterCacheLoader(CacheLoader cacheLoader); List<CacheLoader> getRegisteredCacheLoaders(); void registerCacheWriter(CacheWriter cacheWriter); void unregisterCacheWriter(); CacheWriter getRegisteredCacheWriter(); Element getWithLoader(Object key, CacheLoader loader, Object loaderArgument); Map getAllWithLoader(Collection keys, Object loaderArgument); void load(Object key); void loadAll(Collection keys, Object argument); boolean isDisabled(); void setDisabled(boolean disabled); void registerCacheUsageListener(CacheUsageListener cacheUsageListener); void removeCacheUsageListener(CacheUsageListener cacheUsageListener); boolean isStatisticsEnabled(); void setStatisticsEnabled(boolean enabledStatistics); SampledCacheStatistics getSampledCacheStatistics(); void setSampledStatisticsEnabled(boolean enabledStatistics); boolean isSampledStatisticsEnabled(); Object getInternalContext(); void disableDynamicFeatures(); boolean isClusterCoherent(); boolean isNodeCoherent(); void setNodeCoherent(boolean coherent); void waitUntilClusterCoherent(); void setTransactionManagerLookup(TransactionManagerLookup transactionManagerLookup); Element putIfAbsent(Element element); boolean removeElement(Element element); boolean replace(Element old, Element element); Element replace(Element element); void addPropertyChangeListener(PropertyChangeListener listener); void removePropertyChangeListener(PropertyChangeListener listener); @Override String toString(); }### Answer: @Test public void testThrashBlockingCache() throws Exception { Ehcache cache = manager.getCache("sampleCache1"); blockingCache = new BlockingCache(cache); long duration = thrashCache(blockingCache, 50, 500L, 1000L); LOG.debug("Thrash Duration:" + duration); }
### Question: BlockingCache implements Ehcache { public Element getWithLoader(Object key, CacheLoader loader, Object loaderArgument) throws CacheException { throw new CacheException("This method is not appropriate for a Blocking Cache"); } BlockingCache(final Ehcache cache, int numberOfStripes); BlockingCache(final Ehcache cache); String getName(); void setName(String name); boolean isExpired(Element element); @Override Object clone(); RegisteredEventListeners getCacheEventNotificationService(); boolean isElementInMemory(Serializable key); boolean isElementInMemory(Object key); boolean isElementOnDisk(Serializable key); boolean isElementOnDisk(Object key); String getGuid(); CacheManager getCacheManager(); void clearStatistics(); int getStatisticsAccuracy(); void setStatisticsAccuracy(int statisticsAccuracy); void evictExpiredElements(); boolean isKeyInCache(Object key); boolean isValueInCache(Object value); Statistics getStatistics(); LiveCacheStatistics getLiveCacheStatistics(); void setCacheManager(CacheManager cacheManager); BootstrapCacheLoader getBootstrapCacheLoader(); void setBootstrapCacheLoader(BootstrapCacheLoader bootstrapCacheLoader); void setDiskStorePath(String diskStorePath); void initialise(); void bootstrap(); void dispose(); CacheConfiguration getCacheConfiguration(); Element get(final Object key); CacheWriterManager getWriterManager(); void put(Element element); void put(Element element, boolean doNotNotifyCacheReplicators); void putQuiet(Element element); void putWithWriter(Element element); Element get(Serializable key); Element getQuiet(Serializable key); Element getQuiet(Object key); List getKeys(); List getKeysWithExpiryCheck(); List getKeysNoDuplicateCheck(); boolean remove(Serializable key); boolean remove(Object key); boolean remove(Serializable key, boolean doNotNotifyCacheReplicators); boolean remove(Object key, boolean doNotNotifyCacheReplicators); boolean removeQuiet(Serializable key); boolean removeQuiet(Object key); boolean removeWithWriter(Object key); void removeAll(); void removeAll(boolean doNotNotifyCacheReplicators); void flush(); int getSize(); int getSizeBasedOnAccuracy(int statisticsAccuracy); long calculateInMemorySize(); long getMemoryStoreSize(); int getDiskStoreSize(); Status getStatus(); synchronized String liveness(); void setTimeoutMillis(int timeoutMillis); int getTimeoutMillis(); void registerCacheExtension(CacheExtension cacheExtension); void unregisterCacheExtension(CacheExtension cacheExtension); List<CacheExtension> getRegisteredCacheExtensions(); float getAverageGetTime(); void setCacheExceptionHandler(CacheExceptionHandler cacheExceptionHandler); CacheExceptionHandler getCacheExceptionHandler(); void registerCacheLoader(CacheLoader cacheLoader); void unregisterCacheLoader(CacheLoader cacheLoader); List<CacheLoader> getRegisteredCacheLoaders(); void registerCacheWriter(CacheWriter cacheWriter); void unregisterCacheWriter(); CacheWriter getRegisteredCacheWriter(); Element getWithLoader(Object key, CacheLoader loader, Object loaderArgument); Map getAllWithLoader(Collection keys, Object loaderArgument); void load(Object key); void loadAll(Collection keys, Object argument); boolean isDisabled(); void setDisabled(boolean disabled); void registerCacheUsageListener(CacheUsageListener cacheUsageListener); void removeCacheUsageListener(CacheUsageListener cacheUsageListener); boolean isStatisticsEnabled(); void setStatisticsEnabled(boolean enabledStatistics); SampledCacheStatistics getSampledCacheStatistics(); void setSampledStatisticsEnabled(boolean enabledStatistics); boolean isSampledStatisticsEnabled(); Object getInternalContext(); void disableDynamicFeatures(); boolean isClusterCoherent(); boolean isNodeCoherent(); void setNodeCoherent(boolean coherent); void waitUntilClusterCoherent(); void setTransactionManagerLookup(TransactionManagerLookup transactionManagerLookup); Element putIfAbsent(Element element); boolean removeElement(Element element); boolean replace(Element old, Element element); Element replace(Element element); void addPropertyChangeListener(PropertyChangeListener listener); void removePropertyChangeListener(PropertyChangeListener listener); @Override String toString(); }### Answer: @Override @Test public void testGetWithLoader() { super.testGetWithLoader(); } @Test public void testGetWithLoader() { super.testGetWithLoader(); }
### Question: XATransactionalStore extends AbstractStore { public Element removeElement(Element element) throws NullPointerException { TransactionContext context = getOrCreateTransactionContext(); Element previous = getCurrentElement(element.getKey(), context); if (previous != null && previous.getValue().equals(element.getValue())) { context.addCommand(new StoreRemoveElementCommand(element), element); return previous; } return null; } XATransactionalStore(Ehcache cache, EhcacheXAStore ehcacheXAStore, TransactionManagerLookup transactionManagerLookup, TransactionManager txnManager); boolean put(final Element element); boolean putWithWriter(final Element element, final CacheWriterManager writerManager); Element get(final Object key); Element getQuiet(final Object key); Object[] getKeyArray(); Element remove(final Object key); Element removeWithWriter(final Object key, final CacheWriterManager writerManager); void removeAll(); void dispose(); int getSize(); int getOnDiskSize(); int getInMemorySize(); int getTerracottaClusteredSize(); long getInMemorySizeInBytes(); long getOnDiskSizeInBytes(); Status getStatus(); boolean containsKey(final Object key); boolean containsKeyInMemory(final Object key); boolean containsKeyOnDisk(final Object key); void expireElements(); void flush(); boolean bufferFull(); Policy getInMemoryEvictionPolicy(); void setInMemoryEvictionPolicy(final Policy policy); Object getInternalContext(); @Override boolean isCacheCoherent(); @Override boolean isClusterCoherent(); @Override boolean isNodeCoherent(); @Override void setNodeCoherent(boolean coherent); @Override void waitUntilClusterCoherent(); Element putIfAbsent(Element element); Element removeElement(Element element); boolean replace(Element old, Element element); Element replace(Element element); EhcacheXAResource getOrCreateXAResource(); }### Answer: @Test public void testRemoveElement() throws Exception { transactionManager.begin(); assertEquals("Cache should be empty to start", 0, cache.getSize()); assertEquals("Cach1 should be empty to start", 0, cach1.getSize()); assertFalse(cache.removeElement(new Element("blah", "someValue"))); cache.put(new Element("blah", "value")); assertFalse(cache.removeElement(new Element("blah", "someValue"))); transactionManager.commit(); transactionManager.begin(); assertNotNull(cache.get("blah")); assertTrue(cache.removeElement(new Element("blah", "value"))); transactionManager.commit(); transactionManager.begin(); assertNull(cache.get("blah")); transactionManager.commit(); transactionManager.begin(); cache.put(new Element("key", "value")); transactionManager.commit(); transactionManager.begin(); cach1.put(new Element("random", "things")); cache.removeElement(new Element("key", "value")); Transaction tx1 = transactionManager.suspend(); transactionManager.begin(); assertTrue(cache.removeElement(new Element("key", "value"))); transactionManager.commit(); transactionManager.resume(tx1); try { transactionManager.commit(); fail("Transaction should have failed, element is deleted already"); } catch (RollbackException e) { } transactionManager.begin(); assertNull(cache.get("key")); transactionManager.commit(); transactionManager.begin(); cache.put(new Element("key", "value")); transactionManager.commit(); transactionManager.begin(); cach1.put(new Element("random", "things")); cache.removeElement(new Element("key", "value")); tx1 = transactionManager.suspend(); transactionManager.begin(); cache.put(new Element("key", "newValue")); transactionManager.commit(); transactionManager.resume(tx1); try { transactionManager.commit(); fail("Transaction should have failed, element has changed in the meantime!"); } catch (RollbackException e) { } transactionManager.begin(); assertNotNull(cache.get("key")); assertEquals("newValue", cache.get("key").getValue()); transactionManager.commit(); }
### Question: CacheManager { public void shutdown() { synchronized (CacheManager.class) { if (status.equals(Status.STATUS_SHUTDOWN)) { LOG.debug("CacheManager already shutdown"); return; } for (CacheManagerPeerProvider cacheManagerPeerProvider : cacheManagerPeerProviders.values()) { if (cacheManagerPeerProvider != null) { cacheManagerPeerProvider.dispose(); } } if (cacheManagerTimer != null) { cacheManagerTimer.cancel(); cacheManagerTimer.purge(); } cacheManagerEventListenerRegistry.dispose(); synchronized (CacheManager.class) { ALL_CACHE_MANAGERS.remove(this); for (Ehcache cache : ehcaches.values()) { if (cache != null) { cache.dispose(); } } defaultCache.dispose(); status = Status.STATUS_SHUTDOWN; if (this == singleton) { singleton = null; } if (terracottaClusteredInstanceFactory != null) { terracottaClusteredInstanceFactory.shutdown(); } removeShutdownHook(); } } } CacheManager(Configuration configuration); CacheManager(String configurationFileName); CacheManager(URL configurationURL); CacheManager(InputStream configurationInputStream); CacheManager(); String getClusterUUID(); Store createTerracottaStore(Ehcache cache); WriteBehind createTerracottaWriteBehind(Ehcache cache); CacheEventListener createTerracottaEventReplicator(Ehcache cache); static CacheManager create(); static CacheManager getInstance(); static CacheManager create(String configurationFileName); static CacheManager create(URL configurationFileURL); static CacheManager create(InputStream inputStream); static CacheManager create(Configuration config); Cache getCache(String name); Ehcache getEhcache(String name); void addCache(String cacheName); void addCache(Cache cache); void addCache(Ehcache cache); void addDecoratedCache(Ehcache decoratedCache); boolean cacheExists(String cacheName); void removalAll(); void removeCache(String cacheName); void shutdown(); String[] getCacheNames(); Status getStatus(); void clearAll(); void clearAllStartingWith(String prefix); CacheManagerPeerProvider getCacheManagerPeerProvider(String scheme); CacheManagerPeerListener getCachePeerListener(String scheme); CacheManagerEventListener getCacheManagerEventListener(); void setCacheManagerEventListener(CacheManagerEventListener cacheManagerEventListener); CacheManagerEventListenerRegistry getCacheManagerEventListenerRegistry(); void replaceCacheWithDecoratedCache(Ehcache ehcache, Ehcache decoratedCache); String getName(); boolean isNamed(); void setName(String name); @Override String toString(); String getDiskStorePath(); FailSafeTimer getTimer(); CacheCluster getCluster(ClusterScheme scheme); String getOriginalConfigurationText(); String getActiveConfigurationText(); String getOriginalConfigurationText(String cacheName); String getActiveConfigurationText(String cacheName); @Override int hashCode(); Ehcache addCacheIfAbsent(final Ehcache cache); Ehcache addCacheIfAbsent(final String cacheName); static final String DEFAULT_NAME; static final List<CacheManager> ALL_CACHE_MANAGERS; static final String ENABLE_SHUTDOWN_HOOK_PROPERTY; }### Answer: @Test public void testForCacheManagerThreadLeak() throws CacheException, InterruptedException { int startingThreadCount = countThreads(); URL secondCacheConfiguration = this.getClass().getResource( "/ehcache-2.xml"); for (int i = 0; i < 100; i++) { instanceManager = new CacheManager(secondCacheConfiguration); instanceManager.shutdown(); } int endingThreadCount; int tries = 0; do { Thread.sleep(500); endingThreadCount = countThreads(); } while (tries++ < 5 || endingThreadCount >= startingThreadCount + 2); assertTrue(endingThreadCount < startingThreadCount + 2); } @Test public void testMultipleCacheManagers() { CacheManager[] managers = new CacheManager[2]; managers[0] = new CacheManager(makeCacheManagerConfig()); managers[1] = new CacheManager(makeCacheManagerConfig()); managers[0].shutdown(); managers[1].shutdown(); }
### Question: CacheManager { public static CacheManager create() throws CacheException { if (singleton != null) { return singleton; } synchronized (CacheManager.class) { if (singleton == null) { LOG.debug("Creating new CacheManager with default config"); singleton = new CacheManager(); } else { LOG.debug("Attempting to create an existing singleton. Existing singleton returned."); } return singleton; } } CacheManager(Configuration configuration); CacheManager(String configurationFileName); CacheManager(URL configurationURL); CacheManager(InputStream configurationInputStream); CacheManager(); String getClusterUUID(); Store createTerracottaStore(Ehcache cache); WriteBehind createTerracottaWriteBehind(Ehcache cache); CacheEventListener createTerracottaEventReplicator(Ehcache cache); static CacheManager create(); static CacheManager getInstance(); static CacheManager create(String configurationFileName); static CacheManager create(URL configurationFileURL); static CacheManager create(InputStream inputStream); static CacheManager create(Configuration config); Cache getCache(String name); Ehcache getEhcache(String name); void addCache(String cacheName); void addCache(Cache cache); void addCache(Ehcache cache); void addDecoratedCache(Ehcache decoratedCache); boolean cacheExists(String cacheName); void removalAll(); void removeCache(String cacheName); void shutdown(); String[] getCacheNames(); Status getStatus(); void clearAll(); void clearAllStartingWith(String prefix); CacheManagerPeerProvider getCacheManagerPeerProvider(String scheme); CacheManagerPeerListener getCachePeerListener(String scheme); CacheManagerEventListener getCacheManagerEventListener(); void setCacheManagerEventListener(CacheManagerEventListener cacheManagerEventListener); CacheManagerEventListenerRegistry getCacheManagerEventListenerRegistry(); void replaceCacheWithDecoratedCache(Ehcache ehcache, Ehcache decoratedCache); String getName(); boolean isNamed(); void setName(String name); @Override String toString(); String getDiskStorePath(); FailSafeTimer getTimer(); CacheCluster getCluster(ClusterScheme scheme); String getOriginalConfigurationText(); String getActiveConfigurationText(); String getOriginalConfigurationText(String cacheName); String getActiveConfigurationText(String cacheName); @Override int hashCode(); Ehcache addCacheIfAbsent(final Ehcache cache); Ehcache addCacheIfAbsent(final String cacheName); static final String DEFAULT_NAME; static final List<CacheManager> ALL_CACHE_MANAGERS; static final String ENABLE_SHUTDOWN_HOOK_PROPERTY; }### Answer: @Test public void testCacheManagerThreads() throws CacheException, InterruptedException { singletonManager = CacheManager .create(AbstractCacheTest.TEST_CONFIG_DIR + "ehcache-big.xml"); int threads = countThreads(); assertTrue("More than 145 threads: " + threads, countThreads() <= 145); }
### Question: UpdatingSelfPopulatingCache extends SelfPopulatingCache { public void refresh() throws CacheException { throw new CacheException("UpdatingSelfPopulatingCache objects should not be refreshed."); } UpdatingSelfPopulatingCache(Ehcache cache, final UpdatingCacheEntryFactory factory); Element get(final Object key); void refresh(); }### Answer: @Test public void testRefresh() throws Exception { final String value = "value"; final CountingCacheEntryFactory factory = new CountingCacheEntryFactory(value); selfPopulatingCache = new UpdatingSelfPopulatingCache(cache, factory); try { selfPopulatingCache.refresh(); fail(); } catch (CacheException e) { assertEquals("UpdatingSelfPopulatingCache objects should not be refreshed.", e.getMessage()); } } @Test public void testRefresh() throws Exception { final String value = "value"; final CountingCacheEntryFactory factory = new CountingCacheEntryFactory(value); UpdatingSelfPopulatingCache selfPopulatingCache = new UpdatingSelfPopulatingCache(cache, factory); try { selfPopulatingCache.refresh(); fail(); } catch (CacheException e) { assertEquals("UpdatingSelfPopulatingCache objects should not be refreshed.", e.getMessage()); } }
### Question: CacheManager { public Cache getCache(String name) throws IllegalStateException, ClassCastException { checkStatus(); return ehcaches.get(name) instanceof Cache ? (Cache) ehcaches.get(name) : null; } CacheManager(Configuration configuration); CacheManager(String configurationFileName); CacheManager(URL configurationURL); CacheManager(InputStream configurationInputStream); CacheManager(); String getClusterUUID(); Store createTerracottaStore(Ehcache cache); WriteBehind createTerracottaWriteBehind(Ehcache cache); CacheEventListener createTerracottaEventReplicator(Ehcache cache); static CacheManager create(); static CacheManager getInstance(); static CacheManager create(String configurationFileName); static CacheManager create(URL configurationFileURL); static CacheManager create(InputStream inputStream); static CacheManager create(Configuration config); Cache getCache(String name); Ehcache getEhcache(String name); void addCache(String cacheName); void addCache(Cache cache); void addCache(Ehcache cache); void addDecoratedCache(Ehcache decoratedCache); boolean cacheExists(String cacheName); void removalAll(); void removeCache(String cacheName); void shutdown(); String[] getCacheNames(); Status getStatus(); void clearAll(); void clearAllStartingWith(String prefix); CacheManagerPeerProvider getCacheManagerPeerProvider(String scheme); CacheManagerPeerListener getCachePeerListener(String scheme); CacheManagerEventListener getCacheManagerEventListener(); void setCacheManagerEventListener(CacheManagerEventListener cacheManagerEventListener); CacheManagerEventListenerRegistry getCacheManagerEventListenerRegistry(); void replaceCacheWithDecoratedCache(Ehcache ehcache, Ehcache decoratedCache); String getName(); boolean isNamed(); void setName(String name); @Override String toString(); String getDiskStorePath(); FailSafeTimer getTimer(); CacheCluster getCluster(ClusterScheme scheme); String getOriginalConfigurationText(); String getActiveConfigurationText(); String getOriginalConfigurationText(String cacheName); String getActiveConfigurationText(String cacheName); @Override int hashCode(); Ehcache addCacheIfAbsent(final Ehcache cache); Ehcache addCacheIfAbsent(final String cacheName); static final String DEFAULT_NAME; static final List<CacheManager> ALL_CACHE_MANAGERS; static final String ENABLE_SHUTDOWN_HOOK_PROPERTY; }### Answer: @Test public void testGetCache() throws CacheException { instanceManager = CacheManager.create(); Ehcache cache = instanceManager.getCache("sampleCache1"); assertNotNull(cache); }
### Question: CacheManager { public void removeCache(String cacheName) throws IllegalStateException { checkStatus(); if (cacheName == null || cacheName.length() == 0) { return; } Ehcache cache = ehcaches.remove(cacheName); if (cache != null && cache.getStatus().equals(Status.STATUS_ALIVE)) { cache.dispose(); cacheManagerEventListenerRegistry.notifyCacheRemoved(cache.getName()); } } CacheManager(Configuration configuration); CacheManager(String configurationFileName); CacheManager(URL configurationURL); CacheManager(InputStream configurationInputStream); CacheManager(); String getClusterUUID(); Store createTerracottaStore(Ehcache cache); WriteBehind createTerracottaWriteBehind(Ehcache cache); CacheEventListener createTerracottaEventReplicator(Ehcache cache); static CacheManager create(); static CacheManager getInstance(); static CacheManager create(String configurationFileName); static CacheManager create(URL configurationFileURL); static CacheManager create(InputStream inputStream); static CacheManager create(Configuration config); Cache getCache(String name); Ehcache getEhcache(String name); void addCache(String cacheName); void addCache(Cache cache); void addCache(Ehcache cache); void addDecoratedCache(Ehcache decoratedCache); boolean cacheExists(String cacheName); void removalAll(); void removeCache(String cacheName); void shutdown(); String[] getCacheNames(); Status getStatus(); void clearAll(); void clearAllStartingWith(String prefix); CacheManagerPeerProvider getCacheManagerPeerProvider(String scheme); CacheManagerPeerListener getCachePeerListener(String scheme); CacheManagerEventListener getCacheManagerEventListener(); void setCacheManagerEventListener(CacheManagerEventListener cacheManagerEventListener); CacheManagerEventListenerRegistry getCacheManagerEventListenerRegistry(); void replaceCacheWithDecoratedCache(Ehcache ehcache, Ehcache decoratedCache); String getName(); boolean isNamed(); void setName(String name); @Override String toString(); String getDiskStorePath(); FailSafeTimer getTimer(); CacheCluster getCluster(ClusterScheme scheme); String getOriginalConfigurationText(); String getActiveConfigurationText(); String getOriginalConfigurationText(String cacheName); String getActiveConfigurationText(String cacheName); @Override int hashCode(); Ehcache addCacheIfAbsent(final Ehcache cache); Ehcache addCacheIfAbsent(final String cacheName); static final String DEFAULT_NAME; static final List<CacheManager> ALL_CACHE_MANAGERS; static final String ENABLE_SHUTDOWN_HOOK_PROPERTY; }### Answer: @Test public void testRemoveCache() throws CacheException { singletonManager = CacheManager.create(); Ehcache cache = singletonManager.getCache("sampleCache1"); assertNotNull(cache); singletonManager.removeCache("sampleCache1"); cache = singletonManager.getCache("sampleCache1"); assertNull(cache); singletonManager.removeCache(null); singletonManager.removeCache(""); }
### Question: CacheManager { public void addCache(String cacheName) throws IllegalStateException, ObjectExistsException, CacheException { checkStatus(); if (cacheName == null || cacheName.length() == 0) { return; } if (ehcaches.get(cacheName) != null) { throw new ObjectExistsException("Cache " + cacheName + " already exists"); } addCache(cloneDefaultCache(cacheName)); } CacheManager(Configuration configuration); CacheManager(String configurationFileName); CacheManager(URL configurationURL); CacheManager(InputStream configurationInputStream); CacheManager(); String getClusterUUID(); Store createTerracottaStore(Ehcache cache); WriteBehind createTerracottaWriteBehind(Ehcache cache); CacheEventListener createTerracottaEventReplicator(Ehcache cache); static CacheManager create(); static CacheManager getInstance(); static CacheManager create(String configurationFileName); static CacheManager create(URL configurationFileURL); static CacheManager create(InputStream inputStream); static CacheManager create(Configuration config); Cache getCache(String name); Ehcache getEhcache(String name); void addCache(String cacheName); void addCache(Cache cache); void addCache(Ehcache cache); void addDecoratedCache(Ehcache decoratedCache); boolean cacheExists(String cacheName); void removalAll(); void removeCache(String cacheName); void shutdown(); String[] getCacheNames(); Status getStatus(); void clearAll(); void clearAllStartingWith(String prefix); CacheManagerPeerProvider getCacheManagerPeerProvider(String scheme); CacheManagerPeerListener getCachePeerListener(String scheme); CacheManagerEventListener getCacheManagerEventListener(); void setCacheManagerEventListener(CacheManagerEventListener cacheManagerEventListener); CacheManagerEventListenerRegistry getCacheManagerEventListenerRegistry(); void replaceCacheWithDecoratedCache(Ehcache ehcache, Ehcache decoratedCache); String getName(); boolean isNamed(); void setName(String name); @Override String toString(); String getDiskStorePath(); FailSafeTimer getTimer(); CacheCluster getCluster(ClusterScheme scheme); String getOriginalConfigurationText(); String getActiveConfigurationText(); String getOriginalConfigurationText(String cacheName); String getActiveConfigurationText(String cacheName); @Override int hashCode(); Ehcache addCacheIfAbsent(final Ehcache cache); Ehcache addCacheIfAbsent(final String cacheName); static final String DEFAULT_NAME; static final List<CacheManager> ALL_CACHE_MANAGERS; static final String ENABLE_SHUTDOWN_HOOK_PROPERTY; }### Answer: @Test public void testAddCache() throws CacheException { singletonManager = CacheManager.create(); singletonManager.addCache("test"); singletonManager.addCache("test2"); 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); singletonManager.addCache(""); }
### Question: CacheManager { public Ehcache addCacheIfAbsent(final Ehcache cache) { checkStatus(); return cache == null ? null : addCacheNoCheck(cache, false); } CacheManager(Configuration configuration); CacheManager(String configurationFileName); CacheManager(URL configurationURL); CacheManager(InputStream configurationInputStream); CacheManager(); String getClusterUUID(); Store createTerracottaStore(Ehcache cache); WriteBehind createTerracottaWriteBehind(Ehcache cache); CacheEventListener createTerracottaEventReplicator(Ehcache cache); static CacheManager create(); static CacheManager getInstance(); static CacheManager create(String configurationFileName); static CacheManager create(URL configurationFileURL); static CacheManager create(InputStream inputStream); static CacheManager create(Configuration config); Cache getCache(String name); Ehcache getEhcache(String name); void addCache(String cacheName); void addCache(Cache cache); void addCache(Ehcache cache); void addDecoratedCache(Ehcache decoratedCache); boolean cacheExists(String cacheName); void removalAll(); void removeCache(String cacheName); void shutdown(); String[] getCacheNames(); Status getStatus(); void clearAll(); void clearAllStartingWith(String prefix); CacheManagerPeerProvider getCacheManagerPeerProvider(String scheme); CacheManagerPeerListener getCachePeerListener(String scheme); CacheManagerEventListener getCacheManagerEventListener(); void setCacheManagerEventListener(CacheManagerEventListener cacheManagerEventListener); CacheManagerEventListenerRegistry getCacheManagerEventListenerRegistry(); void replaceCacheWithDecoratedCache(Ehcache ehcache, Ehcache decoratedCache); String getName(); boolean isNamed(); void setName(String name); @Override String toString(); String getDiskStorePath(); FailSafeTimer getTimer(); CacheCluster getCluster(ClusterScheme scheme); String getOriginalConfigurationText(); String getActiveConfigurationText(); String getOriginalConfigurationText(String cacheName); String getActiveConfigurationText(String cacheName); @Override int hashCode(); Ehcache addCacheIfAbsent(final Ehcache cache); Ehcache addCacheIfAbsent(final String cacheName); static final String DEFAULT_NAME; static final List<CacheManager> ALL_CACHE_MANAGERS; static final String ENABLE_SHUTDOWN_HOOK_PROPERTY; }### Answer: @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)); }
### Question: EhcacheStatsImpl extends BaseEmitterBean implements EhcacheStats { public boolean isRegionCacheOrphanEvictionEnabled(String region) { Cache cache = this.cacheManager.getCache(region); if (cache != null && cache.isTerracottaClustered()) { return cache.getCacheConfiguration().getTerracottaConfiguration().getOrphanEviction(); } else { return false; } } EhcacheStatsImpl(CacheManager manager); boolean isStatisticsEnabled(); void clearStats(); void disableStats(); void enableStats(); void flushRegionCache(String region); void flushRegionCaches(); String generateActiveConfigDeclaration(); String generateActiveConfigDeclaration(String region); long getCacheHitCount(); double getCacheHitRate(); long getCacheHitSample(); long getCacheMissCount(); double getCacheMissRate(); long getCacheMissSample(); long getCachePutCount(); double getCachePutRate(); long getCachePutSample(); String getOriginalConfigDeclaration(); String getOriginalConfigDeclaration(String region); Map<String, Map<String, Object>> getRegionCacheAttributes(); Map<String, Object> getRegionCacheAttributes(String regionName); int getRegionCacheMaxTTISeconds(String region); int getRegionCacheMaxTTLSeconds(String region); int getRegionCacheOrphanEvictionPeriod(String region); Map<String, int[]> getRegionCacheSamples(); int getRegionCacheTargetMaxInMemoryCount(String region); int getRegionCacheTargetMaxTotalCount(String region); String[] getTerracottaHibernateCacheRegionNames(); boolean isRegionCacheEnabled(String region); void setRegionCacheEnabled(String region, boolean enabled); boolean isRegionCachesEnabled(); void setRegionCachesEnabled(final boolean flag); boolean isRegionCacheLoggingEnabled(String region); boolean isRegionCacheOrphanEvictionEnabled(String region); boolean isTerracottaHibernateCache(String region); void setRegionCacheLoggingEnabled(String region, boolean loggingEnabled); void setRegionCacheMaxTTISeconds(String region, int maxTTISeconds); void setRegionCacheMaxTTLSeconds(String region, int maxTTLSeconds); void setRegionCacheTargetMaxInMemoryCount(String region, int targetMaxInMemoryCount); void setRegionCacheTargetMaxTotalCount(String region, int targetMaxTotalCount); int getNumberOfElementsInMemory(String region); int getNumberOfElementsOnDisk(String region); void setStatisticsEnabled(boolean flag); long getMaxGetTimeMillis(); long getMinGetTimeMillis(); long getMaxGetTimeMillis(String cacheName); long getMinGetTimeMillis(String cacheName); float getAverageGetTimeMillis(String region); @Override MBeanNotificationInfo[] getNotificationInfo(); }### Answer: @Test public void testIsRegionCacheOrphanEvictionEnabled() { assertThat(stats.isRegionCacheOrphanEvictionEnabled("sampleCache1"), is(false)); }
### Question: EhcacheStatsImpl extends BaseEmitterBean implements EhcacheStats { public int getRegionCacheOrphanEvictionPeriod(String region) { Cache cache = this.cacheManager.getCache(region); if (cache != null && cache.isTerracottaClustered()) { return cache.getCacheConfiguration().getTerracottaConfiguration().getOrphanEvictionPeriod(); } else { return -1; } } EhcacheStatsImpl(CacheManager manager); boolean isStatisticsEnabled(); void clearStats(); void disableStats(); void enableStats(); void flushRegionCache(String region); void flushRegionCaches(); String generateActiveConfigDeclaration(); String generateActiveConfigDeclaration(String region); long getCacheHitCount(); double getCacheHitRate(); long getCacheHitSample(); long getCacheMissCount(); double getCacheMissRate(); long getCacheMissSample(); long getCachePutCount(); double getCachePutRate(); long getCachePutSample(); String getOriginalConfigDeclaration(); String getOriginalConfigDeclaration(String region); Map<String, Map<String, Object>> getRegionCacheAttributes(); Map<String, Object> getRegionCacheAttributes(String regionName); int getRegionCacheMaxTTISeconds(String region); int getRegionCacheMaxTTLSeconds(String region); int getRegionCacheOrphanEvictionPeriod(String region); Map<String, int[]> getRegionCacheSamples(); int getRegionCacheTargetMaxInMemoryCount(String region); int getRegionCacheTargetMaxTotalCount(String region); String[] getTerracottaHibernateCacheRegionNames(); boolean isRegionCacheEnabled(String region); void setRegionCacheEnabled(String region, boolean enabled); boolean isRegionCachesEnabled(); void setRegionCachesEnabled(final boolean flag); boolean isRegionCacheLoggingEnabled(String region); boolean isRegionCacheOrphanEvictionEnabled(String region); boolean isTerracottaHibernateCache(String region); void setRegionCacheLoggingEnabled(String region, boolean loggingEnabled); void setRegionCacheMaxTTISeconds(String region, int maxTTISeconds); void setRegionCacheMaxTTLSeconds(String region, int maxTTLSeconds); void setRegionCacheTargetMaxInMemoryCount(String region, int targetMaxInMemoryCount); void setRegionCacheTargetMaxTotalCount(String region, int targetMaxTotalCount); int getNumberOfElementsInMemory(String region); int getNumberOfElementsOnDisk(String region); void setStatisticsEnabled(boolean flag); long getMaxGetTimeMillis(); long getMinGetTimeMillis(); long getMaxGetTimeMillis(String cacheName); long getMinGetTimeMillis(String cacheName); float getAverageGetTimeMillis(String region); @Override MBeanNotificationInfo[] getNotificationInfo(); }### Answer: @Test public void testGetRegionCacheOrphanEvictionPeriod() { assertThat(stats.getRegionCacheOrphanEvictionPeriod("sampleCache1"), is(-1)); }
### Question: Statistics implements Serializable { public void clearStatistics() { if (cache == null) { throw new IllegalStateException("This statistics object no longer references a Cache."); } cache.clearStatistics(); } Statistics(Ehcache cache, int statisticsAccuracy, long cacheHits, long onDiskHits, long inMemoryHits, long misses, long size, float averageGetTime, long evictionCount, long memoryStoreSize, long diskStoreSize, long writerQueueLength); void clearStatistics(); long getCacheHits(); long getInMemoryHits(); long getOnDiskHits(); long getCacheMisses(); long getObjectCount(); long getMemoryStoreObjectCount(); long getDiskStoreObjectCount(); int getStatisticsAccuracy(); String getStatisticsAccuracyDescription(); String getAssociatedCacheName(); Ehcache getAssociatedCache(); @Override final String toString(); float getAverageGetTime(); long getEvictionCount(); static boolean isValidStatisticsAccuracy(int statisticsAccuracy); long getWriterQueueSize(); static final int STATISTICS_ACCURACY_NONE; static final int STATISTICS_ACCURACY_BEST_EFFORT; static final int STATISTICS_ACCURACY_GUARANTEED; }### Answer: @Test public void testClearStatistics() throws InterruptedException { Cache cache = new Cache("test", 1, true, false, 5, 2); manager.addCache(cache); cache.setStatisticsEnabled(true); cache.put(new Element("key1", "value1")); cache.put(new Element("key2", "value1")); cache.get("key1"); Statistics statistics = cache.getStatistics(); assertEquals(1, statistics.getCacheHits()); assertEquals(1, statistics.getOnDiskHits()); assertEquals(0, statistics.getInMemoryHits()); assertEquals(0, statistics.getCacheMisses()); statistics.clearStatistics(); statistics = cache.getStatistics(); assertEquals(0, statistics.getCacheHits()); assertEquals(0, statistics.getOnDiskHits()); assertEquals(0, statistics.getInMemoryHits()); assertEquals(0, statistics.getCacheMisses()); }
### Question: BlockingCache extends EhcacheDecoratorAdapter { @Override public Element getWithLoader(Object key, CacheLoader loader, Object loaderArgument) throws CacheException { throw new CacheException("This method is not appropriate for a Blocking Cache"); } BlockingCache(final Ehcache cache, int numberOfStripes); BlockingCache(final Ehcache cache); @Override Element get(final Object key); @Override void put(Element element); @Override Element get(Serializable key); synchronized String liveness(); void setTimeoutMillis(int timeoutMillis); int getTimeoutMillis(); @Override void registerCacheLoader(CacheLoader cacheLoader); @Override void unregisterCacheLoader(CacheLoader cacheLoader); @Override Element getWithLoader(Object key, CacheLoader loader, Object loaderArgument); @Override Map getAllWithLoader(Collection keys, Object loaderArgument); @Override void load(Object key); @Override void loadAll(Collection keys, Object argument); }### Answer: @Override @Test public void testGetWithLoader() { super.testGetWithLoader(); }
### Question: DeleteOperation implements SingleOperation { @Override public boolean equals(final Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; final DeleteOperation that = (DeleteOperation) o; return entry.getKey().equals(that.getKey()); } DeleteOperation(CacheEntry entry); DeleteOperation(CacheEntry entry, long creationTime); void performSingleOperation(CacheWriter cacheWriter); BatchOperation createBatchOperation(List<SingleOperation> operations); Object getKey(); long getCreationTime(); CacheEntry getEntry(); SingleOperationType getType(); @Override boolean equals(final Object o); @Override int hashCode(); }### Answer: @Test public void testEquals() throws Exception { DeleteOperation op1 = new DeleteOperation(new CacheEntry(OUR_KEY, new Element(OUR_KEY, "someValue"))); DeleteOperation op2 = new DeleteOperation(new CacheEntry(OUR_KEY, new Element(OUR_KEY, "someOtherValue"))); DeleteOperation op3 = new DeleteOperation(new CacheEntry(OTHER_KEY, new Element(OTHER_KEY, "someOtherValue"))); assertThat("Two delete operations for the same key are to be considered equal", op1.equals(op2), is(true)); assertThat("Two delete operations for the different keys are not to be equal", op1.equals(op3), is(false)); }
### Question: DeleteOperation implements SingleOperation { @Override public int hashCode() { return entry.getKey().hashCode(); } DeleteOperation(CacheEntry entry); DeleteOperation(CacheEntry entry, long creationTime); void performSingleOperation(CacheWriter cacheWriter); BatchOperation createBatchOperation(List<SingleOperation> operations); Object getKey(); long getCreationTime(); CacheEntry getEntry(); SingleOperationType getType(); @Override boolean equals(final Object o); @Override int hashCode(); }### Answer: @Test public void testHashCode() throws Exception { DeleteOperation op1 = new DeleteOperation(new CacheEntry(OUR_KEY, new Element(OUR_KEY, "someValue"))); DeleteOperation op2 = new DeleteOperation(new CacheEntry(OUR_KEY, new Element(OUR_KEY, "someOtherValue"))); assertThat("A Delete operation should have the same hashCode as its key", op1.hashCode(), is(OUR_KEY.hashCode())); assertThat("Delete operations for the same key, should have the same hashCode", op1.hashCode(), is(op2.hashCode())); }
### Question: WriteOperation implements SingleOperation { @Override public boolean equals(final Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; final WriteOperation that = (WriteOperation) o; return element.getKey().equals(that.element.getKey()) && element.getValue().equals(that.element.getValue()); } WriteOperation(Element element); WriteOperation(Element element, long creationTime); void performSingleOperation(CacheWriter cacheWriter); BatchOperation createBatchOperation(List<SingleOperation> operations); Object getKey(); long getCreationTime(); Element getElement(); SingleOperationType getType(); @Override boolean equals(final Object o); @Override int hashCode(); }### Answer: @Test public void testEquals() throws Exception { WriteOperation op1 = new WriteOperation(new Element(OUR_KEY, "someValue")); WriteOperation op2 = new WriteOperation(new Element(OUR_KEY, "someOtherValue")); WriteOperation op3 = new WriteOperation(new Element(OUR_KEY, "someValue")); WriteOperation op4 = new WriteOperation(new Element("otherKey", "someValue")); assertThat("Two write operations for the same key and same value should be equal", op1.equals(op3), is(true)); assertThat("Two write operations for the same key, but with different values should be different", op1.equals(op2), is(false)); assertThat("Two write operations for the different keys should be different", op1.equals(op4), is(false)); }
### Question: WriteOperation implements SingleOperation { @Override public int hashCode() { return element.hashCode(); } WriteOperation(Element element); WriteOperation(Element element, long creationTime); void performSingleOperation(CacheWriter cacheWriter); BatchOperation createBatchOperation(List<SingleOperation> operations); Object getKey(); long getCreationTime(); Element getElement(); SingleOperationType getType(); @Override boolean equals(final Object o); @Override int hashCode(); }### Answer: @Test public void testHashCode() throws Exception { WriteOperation op1 = new WriteOperation(new Element(OUR_KEY, "someValue")); WriteOperation op2 = new WriteOperation(new Element(OUR_KEY, "someOtherValue")); WriteOperation op3 = new WriteOperation(new Element(OUR_KEY, "someValue")); assertThat("A write operation should have the same hashCode as its key", op1.hashCode(), is(OUR_KEY.hashCode())); assertThat("Two write operations for the same key but different values should still have the same hashCode", op1.hashCode(), is(op2.hashCode())); assertThat("Two write operations for the same key and same value should have the same hashCode", op2.hashCode(), is(op3.hashCode())); }
### Question: CacheWriterConfiguration implements Cloneable { public CacheWriterConfiguration writeMode(String writeMode) { setWriteMode(writeMode); return this; } @Override CacheWriterConfiguration clone(); void setWriteMode(String writeMode); CacheWriterConfiguration writeMode(String writeMode); CacheWriterConfiguration writeMode(WriteMode writeMode); WriteMode getWriteMode(); void setNotifyListenersOnException(boolean notifyListenersOnException); CacheWriterConfiguration notifyListenersOnException(boolean notifyListenersOnException); boolean getNotifyListenersOnException(); void setMinWriteDelay(int minWriteDelay); CacheWriterConfiguration minWriteDelay(int minWriteDelay); int getMinWriteDelay(); void setMaxWriteDelay(int maxWriteDelay); CacheWriterConfiguration maxWriteDelay(int maxWriteDelay); int getMaxWriteDelay(); void setRateLimitPerSecond(int rateLimitPerSecond); CacheWriterConfiguration rateLimitPerSecond(int rateLimitPerSecond); int getRateLimitPerSecond(); void setWriteCoalescing(boolean writeCoalescing); CacheWriterConfiguration writeCoalescing(boolean writeCoalescing); boolean getWriteCoalescing(); void setWriteBatching(boolean writeBatching); CacheWriterConfiguration writeBatching(boolean writeBatching); boolean getWriteBatching(); void setWriteBatchSize(int writeBatchSize); CacheWriterConfiguration writeBatchSize(int writeBatchSize); int getWriteBatchSize(); void setRetryAttempts(int retryAttempts); CacheWriterConfiguration retryAttempts(int retryAttempts); int getRetryAttempts(); void setRetryAttemptDelaySeconds(int retryAttemptDelaySeconds); CacheWriterConfiguration retryAttemptDelaySeconds(int retryAttemptDelaySeconds); int getRetryAttemptDelaySeconds(); final void addCacheWriterFactory(CacheWriterFactoryConfiguration cacheWriterFactoryConfiguration); CacheWriterConfiguration cacheWriterFactory(CacheWriterFactoryConfiguration cacheWriterFactory); CacheWriterFactoryConfiguration getCacheWriterFactoryConfiguration(); void setWriteBehindConcurrency(int concurrency); CacheWriterConfiguration writeBehindConcurrency(int concurrency); int getWriteBehindConcurrency(); void setWriteBehindMaxQueueSize(final int writeBehindMaxQueueSize); int getWriteBehindMaxQueueSize(); CacheWriterConfiguration writeBehindMaxQueueSize(int writeBehindMaxQueueSize); @Override int hashCode(); @Override boolean equals(Object obj); static final WriteMode DEFAULT_WRITE_MODE; static final boolean DEFAULT_NOTIFY_LISTENERS_ON_EXCEPTION; static final int DEFAULT_MIN_WRITE_DELAY; static final int DEFAULT_MAX_WRITE_DELAY; static final int DEFAULT_RATE_LIMIT_PER_SECOND; static final boolean DEFAULT_WRITE_COALESCING; static final boolean DEFAULT_WRITE_BATCHING; static final int DEFAULT_WRITE_BATCH_SIZE; static final int DEFAULT_RETRY_ATTEMPTS; static final int DEFAULT_RETRY_ATTEMPT_DELAY_SECONDS; static final int DEFAULT_WRITE_BEHIND_CONCURRENCY; static final int DEFAULT_WRITE_BEHIND_MAX_QUEUE_SIZE; }### Answer: @Test(expected = IllegalArgumentException.class) public void testNullWriteMode() { CacheWriterConfiguration config = new CacheWriterConfiguration() .writeMode((CacheWriterConfiguration.WriteMode) null); } @Test(expected = IllegalArgumentException.class) public void testInvalidWriteMode() { CacheWriterConfiguration config = new CacheWriterConfiguration() .writeMode("invalid"); }
### Question: CachingFilter extends Filter { Integer parseBlockingCacheTimeoutMillis(FilterConfig filterConfig) { String timeout = filterConfig.getInitParameter(BLOCKING_TIMEOUT_MILLIS); try { return Integer.parseInt(timeout); } catch (NumberFormatException e) { return null; } } void doInit(FilterConfig filterConfig); }### Answer: @Test public void testParsing() { CachingFilter filter = new CachingFilter() { protected CacheManager getCacheManager() { return null; } protected String calculateKey(HttpServletRequest httpRequest) { return null; } }; assertNull(filter.parseBlockingCacheTimeoutMillis(new FilterConfig() { public String getFilterName() { return null; } public ServletContext getServletContext() { return null; } public String getInitParameter(String name) { return null; } public Enumeration getInitParameterNames() { return null; } })); assertNull(filter.parseBlockingCacheTimeoutMillis(new FilterConfig() { public String getFilterName() { return null; } public ServletContext getServletContext() { return null; } public String getInitParameter(String name) { return "sdfsd"; } public Enumeration getInitParameterNames() { return null; } })); assertNull(filter.parseBlockingCacheTimeoutMillis(new FilterConfig() { public String getFilterName() { return null; } public ServletContext getServletContext() { return null; } public String getInitParameter(String name) { return "10L"; } public Enumeration getInitParameterNames() { return null; } })); assertEquals(1000, filter.parseBlockingCacheTimeoutMillis(new FilterConfig() { public String getFilterName() { return null; } public ServletContext getServletContext() { return null; } public String getInitParameter(String name) { return "1000"; } public Enumeration getInitParameterNames() { return null; } })); assertEquals(120000, filter.parseBlockingCacheTimeoutMillis(new FilterConfig() { public String getFilterName() { return null; } public ServletContext getServletContext() { return null; } public String getInitParameter(String name) { return "120000"; } public Enumeration getInitParameterNames() { return null; } })); }
### Question: HttpDateFormatter { public synchronized Date parseDateFromHttpDate(String date) { try { return httpDateFormat.parse(date); } catch (ParseException e) { LOG.debug("ParseException on date {}. 1/1/1970 will be returned", date); return new Date(0); } } HttpDateFormatter(); synchronized String formatHttpDate(Date date); synchronized Date parseDateFromHttpDate(String date); }### Answer: @Test public void testParseBadDate() { HttpDateFormatter httpDateFormatter = new HttpDateFormatter(); String dateString1 = "dddddddddd^^^3s"; Date date = httpDateFormatter.parseDateFromHttpDate(dateString1); assertEquals(new Date(0), date); }
### Question: PageInfo implements Serializable { public byte[] getUngzippedBody() throws IOException { if (storeGzipped) { return ungzip(gzippedBody); } else { return ungzippedBody; } } PageInfo(final int statusCode, final String contentType, final Collection headers, final Collection cookies, final byte[] body, boolean storeGzipped, long timeToLiveSeconds); static boolean isGzipped(byte[] candidate); String getContentType(); byte[] getGzippedBody(); List getResponseHeaders(); List getSerializableCookies(); int getStatusCode(); byte[] getUngzippedBody(); boolean hasGzippedBody(); boolean hasUngzippedBody(); boolean isOk(); Date getCreated(); long getTimeToLiveSeconds(); }### Answer: @Test public void testUsedGunzipImplementationPerformance() throws IOException, AlreadyGzippedException, InterruptedException { byte[] gzip = getGzipFileAsBytes(); Collection headers = new ArrayList(); String[] header = new String[]{"Content-Encoding", "gzip"}; headers.add(header); PageInfo pageInfo = new PageInfo(200, "text/plain", headers, new ArrayList(), gzip, true, 0); long initialMemoryUsed = memoryUsed(); StopWatch stopWatch = new StopWatch(); int size = 0; long timeTaken = 0; long finalMemoryUsed = 0; long incrementalMemoryUsed = 0; byte[] ungzipped = null; for (int i = 0; i < 5; i++) { ungzipped = pageInfo.getUngzippedBody(); Thread.sleep(200); } stopWatch.getElapsedTime(); for (int i = 0; i < 50; i++) { ungzipped = pageInfo.getUngzippedBody(); } size = ungzipped.length; timeTaken = stopWatch.getElapsedTime() / 50; finalMemoryUsed = memoryUsed(); incrementalMemoryUsed = finalMemoryUsed - initialMemoryUsed; LOG.info("Average gunzip time: " + timeTaken + ". Memory used: " + incrementalMemoryUsed + ". Size: " + size); assertEquals(100000, size); assertTrue(timeTaken < 30); }
### Question: PageInfo implements Serializable { private byte[] gzip(byte[] ungzipped) throws IOException, AlreadyGzippedException { if (isGzipped(ungzipped)) { throw new AlreadyGzippedException("The byte[] is already gzipped. It should not be gzipped again."); } final ByteArrayOutputStream bytes = new ByteArrayOutputStream(); final GZIPOutputStream gzipOutputStream = new GZIPOutputStream(bytes); gzipOutputStream.write(ungzipped); gzipOutputStream.close(); return bytes.toByteArray(); } PageInfo(final int statusCode, final String contentType, final Collection headers, final Collection cookies, final byte[] body, boolean storeGzipped, long timeToLiveSeconds); static boolean isGzipped(byte[] candidate); String getContentType(); byte[] getGzippedBody(); List getResponseHeaders(); List getSerializableCookies(); int getStatusCode(); byte[] getUngzippedBody(); boolean hasGzippedBody(); boolean hasUngzippedBody(); boolean isOk(); Date getCreated(); long getTimeToLiveSeconds(); }### Answer: @Test public void testGzipPerformance() throws IOException, InterruptedException { long initialMemoryUsed = memoryUsed(); byte[] gzip = getGzipFileAsBytes(); byte[] ungzipped = null; int size = 0; long timeTaken = 0; long finalMemoryUsed = 0; long incrementalMemoryUsed = 0; StopWatch stopWatch = new StopWatch(); ungzipped = ungzip1(gzip); stopWatch.getElapsedTime(); for (int i = 0; i < 50; i++) { gzip = gzip(ungzipped); } timeTaken = stopWatch.getElapsedTime() / 50; ungzipped = ungzip1(gzip); size = ungzipped.length; assertEquals(100000, size); finalMemoryUsed = memoryUsed(); incrementalMemoryUsed = finalMemoryUsed - initialMemoryUsed; LOG.info("Average gzip time: " + timeTaken + ". Memory used: " + incrementalMemoryUsed + ". Size: " + size); }
### Question: EhcacheObjectMapperProvider implements ContextResolver<ObjectMapper> { public ObjectMapper getContext(Class<?> arg0) { return om; } EhcacheObjectMapperProvider(); ObjectMapper getContext(Class<?> arg0); }### Answer: @Test public void testObjectMapping() throws IOException { EhcacheObjectMapperProvider provider = new EhcacheObjectMapperProvider(); ObjectMapper om = provider.getContext(AgentEntity.class); String output = om.writer().writeValueAsString(new AgentEntity()); Assert.assertEquals("{\"agentId\":null,\"cacheManagers\":null}", output); }
### Question: ResourceClassLoader extends ClassLoader { @Override public synchronized Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException { Class c = findLoadedClass(name); if (c == null) { try { c = findClass(name); } catch (ClassNotFoundException e) { c = super.loadClass(name, resolve); } } if (resolve) { resolveClass(c); } return c; } ResourceClassLoader(String prefix, ClassLoader parent); @Override synchronized Class<?> loadClass(String name, boolean resolve); @Override URL getResource(String name); }### Answer: @Test(expected = ClassNotFoundException.class) public void contentOfTheJarNotVisibleWithNormalClassLoaderTest() throws ClassNotFoundException { Class<?> simpleClass = testCaseClassLoader.loadClass("pof.Simple"); } @Test public void workingWithClassFromPrivateClassPathTest() throws ClassNotFoundException, NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, IOException { ResourceClassLoader resourceClassLoader = new ResourceClassLoader("private-classpath", testCaseClassLoader); Class<?> simpleClass = resourceClassLoader.loadClass("pof.Simple"); Constructor<?> simpleClassConstructor = simpleClass.getConstructor(new Class[] {}); Object simpleObject = simpleClassConstructor.newInstance(new Object[] {}); Method sayHelloMethod = simpleClass.getMethod("sayHello", new Class[] {}); Object sayHello = sayHelloMethod.invoke(simpleObject, new Object[] {}); Assert.assertEquals("hello!", sayHello); Method printVersionMethod = simpleClass.getMethod("printVersion", new Class[] {}); Object printVersion = printVersionMethod.invoke(simpleObject, new Object[] {}); Assert.assertEquals("2.6.0-SNAPSHOT", printVersion); Method getMessageInTextFileMethod = simpleClass.getMethod("getMessageInTextFile", new Class[] {}); Object message = getMessageInTextFileMethod.invoke(simpleObject, new Object[] {}); Assert.assertEquals("Congratulations ! You could read a file from a hidden resource location !", message); }
### Question: SelectableConcurrentHashMap { public Element get(Object key) { int hash = hash(key.hashCode()); return segmentFor(hash).get(key, hash); } SelectableConcurrentHashMap(PoolAccessor poolAccessor, boolean elementPinningEnabled, int initialCapacity, float loadFactor, int concurrency, final long maximumSize, final RegisteredEventListeners cacheEventNotificationService); void setMaxSize(final long maxSize); Element[] getRandomValues(final int size, Object keyHint); Object storedObject(Element e); int quickSize(); boolean isEmpty(); int size(); int pinnedSize(); ReentrantReadWriteLock lockFor(Object key); ReentrantReadWriteLock[] locks(); Element get(Object key); boolean containsKey(Object key); boolean containsValue(Object value); Element put(Object key, Element element, long sizeOf); Element putIfAbsent(Object key, Element element, long sizeOf); Element remove(Object key); boolean remove(Object key, Object value); void clear(); void unpinAll(); void setPinned(Object key, boolean pinned); boolean isPinned(Object key); Set<Object> keySet(); Collection<Element> values(); Set<Entry<Object, Element>> entrySet(); boolean evict(); void recalculateSize(Object key); Set pinnedKeySet(); }### Answer: @Test public void testReturnsPinnedKeysThatArePresent() { assertThat(map.get(1), notNullValue()); assertThat(map.get(2), notNullValue()); assertThat(map.get(3), notNullValue()); assertThat(map.get(4), notNullValue()); } @Test public void testDoesNotReturnsPinnedKeysThatAreNotPresent() { assertThat(map.get(0), nullValue()); assertThat(map.get(5), nullValue()); }
### Question: CacheManager { public Cache getCache(String name) throws IllegalStateException, ClassCastException { checkStatus(); return ehcaches.get(name) instanceof Cache ? (Cache) ehcaches.get(name) : null; } CacheManager(Configuration configuration); CacheManager(String configurationFileName); CacheManager(URL configurationURL); CacheManager(InputStream configurationInputStream); CacheManager(); Pool getOnHeapPool(); Pool getOnDiskPool(); String getClusterUUID(); Store createTerracottaStore(Ehcache cache); WriteBehind createTerracottaWriteBehind(Ehcache cache); CacheEventListener createTerracottaEventReplicator(Ehcache cache); static CacheManager create(); static CacheManager newInstance(); static CacheManager getInstance(); static CacheManager create(String configurationFileName); static CacheManager newInstance(String configurationFileName); static CacheManager create(URL configurationFileURL); static CacheManager newInstance(URL configurationFileURL); static CacheManager create(InputStream inputStream); static CacheManager newInstance(InputStream inputStream); static CacheManager create(Configuration config); static CacheManager newInstance(Configuration config); static CacheManager getCacheManager(String name); Cache getCache(String name); Ehcache getEhcache(String name); void addCache(String cacheName); void addCache(Cache cache); void addCache(Ehcache cache); void addDecoratedCache(Ehcache decoratedCache); void addDecoratedCacheIfAbsent(Ehcache decoratedCache); boolean cacheExists(String cacheName); void removalAll(); void removeCache(String cacheName); void shutdown(); String[] getCacheNames(); Status getStatus(); void clearAll(); void clearAllStartingWith(String prefix); CacheManagerPeerProvider getCacheManagerPeerProvider(String scheme); Map<String, CacheManagerPeerProvider> getCacheManagerPeerProviders(); CacheManagerPeerListener getCachePeerListener(String scheme); CacheManagerEventListener getCacheManagerEventListener(); void setCacheManagerEventListener(CacheManagerEventListener cacheManagerEventListener); CacheManagerEventListenerRegistry getCacheManagerEventListenerRegistry(); void replaceCacheWithDecoratedCache(Ehcache ehcache, Ehcache decoratedCache); String getName(); boolean isNamed(); void setName(String name); @Override String toString(); DiskStorePathManager getDiskStorePathManager(); FailSafeTimer getTimer(); CacheCluster getCluster(ClusterScheme scheme); String getOriginalConfigurationText(); String getActiveConfigurationText(); String getOriginalConfigurationText(String cacheName); String getActiveConfigurationText(String cacheName); Configuration getConfiguration(); Ehcache addCacheIfAbsent(final Ehcache cache); Ehcache addCacheIfAbsent(final String cacheName); TransactionController getTransactionController(); TransactionIDFactory getOrCreateTransactionIDFactory(); FeaturesManager getFeaturesManager(); static final String DEFAULT_NAME; static final double ON_HEAP_THRESHOLD; static final List<CacheManager> ALL_CACHE_MANAGERS; static final String ENABLE_SHUTDOWN_HOOK_PROPERTY; }### Answer: @Test public void testGetCache() throws CacheException { CacheManager manager = CacheManager.create(); try { Ehcache cache = manager.getCache("sampleCache1"); assertNotNull(cache); } finally { manager.shutdown(); } } @Test public void testGetCache() throws CacheException { CacheManager manager = new CacheManager(new Configuration().cache(new CacheConfiguration("foo", 100))); try { assertNotNull(manager.getCache("foo")); } finally { manager.shutdown(); } }
### Question: CacheManager { public void removeCache(String cacheName) throws IllegalStateException { checkStatus(); if (cacheName == null || cacheName.length() == 0) { return; } Ehcache cache = ehcaches.remove(cacheName); if (cache != null && cache.getStatus().equals(Status.STATUS_ALIVE)) { cache.dispose(); runtimeCfg.removeCache(cache.getCacheConfiguration()); cacheManagerEventListenerRegistry.notifyCacheRemoved(cache.getName()); } } CacheManager(Configuration configuration); CacheManager(String configurationFileName); CacheManager(URL configurationURL); CacheManager(InputStream configurationInputStream); CacheManager(); Pool getOnHeapPool(); Pool getOnDiskPool(); String getClusterUUID(); Store createTerracottaStore(Ehcache cache); WriteBehind createTerracottaWriteBehind(Ehcache cache); CacheEventListener createTerracottaEventReplicator(Ehcache cache); static CacheManager create(); static CacheManager newInstance(); static CacheManager getInstance(); static CacheManager create(String configurationFileName); static CacheManager newInstance(String configurationFileName); static CacheManager create(URL configurationFileURL); static CacheManager newInstance(URL configurationFileURL); static CacheManager create(InputStream inputStream); static CacheManager newInstance(InputStream inputStream); static CacheManager create(Configuration config); static CacheManager newInstance(Configuration config); static CacheManager getCacheManager(String name); Cache getCache(String name); Ehcache getEhcache(String name); void addCache(String cacheName); void addCache(Cache cache); void addCache(Ehcache cache); void addDecoratedCache(Ehcache decoratedCache); void addDecoratedCacheIfAbsent(Ehcache decoratedCache); boolean cacheExists(String cacheName); void removalAll(); void removeCache(String cacheName); void shutdown(); String[] getCacheNames(); Status getStatus(); void clearAll(); void clearAllStartingWith(String prefix); CacheManagerPeerProvider getCacheManagerPeerProvider(String scheme); Map<String, CacheManagerPeerProvider> getCacheManagerPeerProviders(); CacheManagerPeerListener getCachePeerListener(String scheme); CacheManagerEventListener getCacheManagerEventListener(); void setCacheManagerEventListener(CacheManagerEventListener cacheManagerEventListener); CacheManagerEventListenerRegistry getCacheManagerEventListenerRegistry(); void replaceCacheWithDecoratedCache(Ehcache ehcache, Ehcache decoratedCache); String getName(); boolean isNamed(); void setName(String name); @Override String toString(); DiskStorePathManager getDiskStorePathManager(); FailSafeTimer getTimer(); CacheCluster getCluster(ClusterScheme scheme); String getOriginalConfigurationText(); String getActiveConfigurationText(); String getOriginalConfigurationText(String cacheName); String getActiveConfigurationText(String cacheName); Configuration getConfiguration(); Ehcache addCacheIfAbsent(final Ehcache cache); Ehcache addCacheIfAbsent(final String cacheName); TransactionController getTransactionController(); TransactionIDFactory getOrCreateTransactionIDFactory(); FeaturesManager getFeaturesManager(); static final String DEFAULT_NAME; static final double ON_HEAP_THRESHOLD; static final List<CacheManager> ALL_CACHE_MANAGERS; static final String ENABLE_SHUTDOWN_HOOK_PROPERTY; }### Answer: @Test public void testRemoveCache() throws CacheException { CacheManager manager = CacheManager.create(); try { assertEquals(15, manager.getConfiguration().getCacheConfigurations().size()); Ehcache cache = manager.getCache("sampleCache1"); assertNotNull(cache); manager.removeCache("sampleCache1"); cache = manager.getCache("sampleCache1"); assertNull(cache); assertEquals(14, manager.getConfiguration().getCacheConfigurations().size()); manager.removeCache(null); manager.removeCache(""); assertEquals(14, manager.getConfiguration().getCacheConfigurations().size()); } finally { manager.shutdown(); } } @Test public void testRemoveCache() throws CacheException { Configuration config = new Configuration().cache(new CacheConfiguration("foo", 100)); CacheManager manager = new CacheManager(config); try { assertEquals(1, manager.getConfiguration().getCacheConfigurations().size()); assertNotNull(manager.getCache("foo")); manager.removeCache("foo"); assertNull(manager.getCache("foo")); assertEquals(0, manager.getConfiguration().getCacheConfigurations().size()); manager.removeCache(null); manager.removeCache(""); assertEquals(0, manager.getConfiguration().getCacheConfigurations().size()); } finally { manager.shutdown(); } }
### Question: ManagementService implements CacheManagerEventListener { public void notifyCacheRemoved(String cacheName) { if (registerCaches) { unregisterMBean(Cache.createObjectName(backingCacheManager.toString(), cacheName)); } if (registerCacheConfigurations) { unregisterMBean(CacheConfiguration.createObjectName(backingCacheManager.toString(), cacheName)); } if (registerCacheStatistics) { unregisterMBean(CacheStatistics.createObjectName(backingCacheManager.toString(), cacheName)); } if (registerCacheStores) { unregisterMBean(Store.createObjectName(backingCacheManager.toString(), cacheName)); } } ManagementService(net.sf.ehcache.CacheManager cacheManager, MBeanServer mBeanServer, boolean registerCacheManager, boolean registerCaches, boolean registerCacheConfigurations, boolean registerCacheStatistics, boolean registerCacheStores); ManagementService(net.sf.ehcache.CacheManager cacheManager, MBeanServer mBeanServer, boolean registerCacheManager, boolean registerCaches, boolean registerCacheConfigurations, boolean registerCacheStatistics); static void registerMBeans( net.sf.ehcache.CacheManager cacheManager, MBeanServer mBeanServer, boolean registerCacheManager, boolean registerCaches, boolean registerCacheConfigurations, boolean registerCacheStatistics, boolean registerCacheStores); static void registerMBeans( net.sf.ehcache.CacheManager cacheManager, MBeanServer mBeanServer, boolean registerCacheManager, boolean registerCaches, boolean registerCacheConfigurations, boolean registerCacheStatistics); void init(); Status getStatus(); void dispose(); void notifyCacheAdded(String cacheName); void notifyCacheRemoved(String cacheName); }### Answer: @Test public void testNotifyCacheRemovedDoesNotCallWhenNotRegistered() { MBeanServer server = mock(MBeanServer.class); when(server.isRegistered(any(ObjectName.class))).thenReturn(true); net.sf.ehcache.CacheManager cm = mock(net.sf.ehcache.CacheManager.class); when(cm.toString()).thenReturn("cmName"); ManagementService managementService = new ManagementService(cm, server, false, false, false, false, false); managementService.notifyCacheRemoved("testName"); verifyZeroInteractions(server); }
### Question: CacheManager { public Cache getCache(String name) throws IllegalStateException, ClassCastException { checkStatus(); return ehcaches.get(name) instanceof Cache ? (Cache) ehcaches.get(name) : null; } CacheManager(Configuration configuration); CacheManager(String configurationFileName); CacheManager(URL configurationURL); CacheManager(InputStream configurationInputStream); CacheManager(); String getClusterUUID(); Store createTerracottaStore(Ehcache cache); WriteBehind createTerracottaWriteBehind(Ehcache cache); CacheEventListener createTerracottaEventReplicator(Ehcache cache); static CacheManager create(); static CacheManager getInstance(); static CacheManager create(String configurationFileName); static CacheManager create(URL configurationFileURL); static CacheManager create(InputStream inputStream); static CacheManager create(Configuration config); Cache getCache(String name); Ehcache getEhcache(String name); void addCache(String cacheName); void addCache(Cache cache); void addCache(Ehcache cache); void addDecoratedCache(Ehcache decoratedCache); void addDecoratedCacheIfAbsent(Ehcache decoratedCache); boolean cacheExists(String cacheName); void removalAll(); void removeCache(String cacheName); void shutdown(); String[] getCacheNames(); Status getStatus(); void clearAll(); void clearAllStartingWith(String prefix); CacheManagerPeerProvider getCacheManagerPeerProvider(String scheme); Map<String, CacheManagerPeerProvider> getCacheManagerPeerProviders(); CacheManagerPeerListener getCachePeerListener(String scheme); CacheManagerEventListener getCacheManagerEventListener(); void setCacheManagerEventListener(CacheManagerEventListener cacheManagerEventListener); CacheManagerEventListenerRegistry getCacheManagerEventListenerRegistry(); void replaceCacheWithDecoratedCache(Ehcache ehcache, Ehcache decoratedCache); String getName(); boolean isNamed(); void setName(String name); @Override String toString(); String getDiskStorePath(); FailSafeTimer getTimer(); CacheCluster getCluster(ClusterScheme scheme); String getOriginalConfigurationText(); String getActiveConfigurationText(); String getOriginalConfigurationText(String cacheName); String getActiveConfigurationText(String cacheName); @Override int hashCode(); Ehcache addCacheIfAbsent(final Ehcache cache); Ehcache addCacheIfAbsent(final String cacheName); TransactionController getTransactionController(); static final String DEFAULT_NAME; static final List<CacheManager> ALL_CACHE_MANAGERS; static final String ENABLE_SHUTDOWN_HOOK_PROPERTY; }### Answer: @Test public void testGetCache() throws CacheException { CacheManager manager = new CacheManager(new Configuration().cache(new CacheConfiguration("foo", 100))); try { assertNotNull(manager.getCache("foo")); } finally { manager.shutdown(); } } @Test public void testGetCache() throws CacheException { instanceManager = CacheManager.create(); Ehcache cache = instanceManager.getCache("sampleCache1"); assertNotNull(cache); }
### Question: CacheManager { public void removeCache(String cacheName) throws IllegalStateException { checkStatus(); if (cacheName == null || cacheName.length() == 0) { return; } Ehcache cache = ehcaches.remove(cacheName); if (cache != null && cache.getStatus().equals(Status.STATUS_ALIVE)) { cache.dispose(); configuration.getCacheConfigurations().remove(cacheName); cacheManagerEventListenerRegistry.notifyCacheRemoved(cache.getName()); } } CacheManager(Configuration configuration); CacheManager(String configurationFileName); CacheManager(URL configurationURL); CacheManager(InputStream configurationInputStream); CacheManager(); String getClusterUUID(); Store createTerracottaStore(Ehcache cache); WriteBehind createTerracottaWriteBehind(Ehcache cache); CacheEventListener createTerracottaEventReplicator(Ehcache cache); static CacheManager create(); static CacheManager getInstance(); static CacheManager create(String configurationFileName); static CacheManager create(URL configurationFileURL); static CacheManager create(InputStream inputStream); static CacheManager create(Configuration config); Cache getCache(String name); Ehcache getEhcache(String name); void addCache(String cacheName); void addCache(Cache cache); void addCache(Ehcache cache); void addDecoratedCache(Ehcache decoratedCache); void addDecoratedCacheIfAbsent(Ehcache decoratedCache); boolean cacheExists(String cacheName); void removalAll(); void removeCache(String cacheName); void shutdown(); String[] getCacheNames(); Status getStatus(); void clearAll(); void clearAllStartingWith(String prefix); CacheManagerPeerProvider getCacheManagerPeerProvider(String scheme); Map<String, CacheManagerPeerProvider> getCacheManagerPeerProviders(); CacheManagerPeerListener getCachePeerListener(String scheme); CacheManagerEventListener getCacheManagerEventListener(); void setCacheManagerEventListener(CacheManagerEventListener cacheManagerEventListener); CacheManagerEventListenerRegistry getCacheManagerEventListenerRegistry(); void replaceCacheWithDecoratedCache(Ehcache ehcache, Ehcache decoratedCache); String getName(); boolean isNamed(); void setName(String name); @Override String toString(); String getDiskStorePath(); FailSafeTimer getTimer(); CacheCluster getCluster(ClusterScheme scheme); String getOriginalConfigurationText(); String getActiveConfigurationText(); String getOriginalConfigurationText(String cacheName); String getActiveConfigurationText(String cacheName); @Override int hashCode(); Ehcache addCacheIfAbsent(final Ehcache cache); Ehcache addCacheIfAbsent(final String cacheName); TransactionController getTransactionController(); static final String DEFAULT_NAME; static final List<CacheManager> ALL_CACHE_MANAGERS; static final String ENABLE_SHUTDOWN_HOOK_PROPERTY; }### Answer: @Test public void testRemoveCache() throws CacheException { Configuration config = new Configuration().cache(new CacheConfiguration("foo", 100)); CacheManager manager = new CacheManager(config); try { assertEquals(1, manager.getConfiguration().getCacheConfigurations().size()); assertNotNull(manager.getCache("foo")); manager.removeCache("foo"); assertNull(manager.getCache("foo")); assertEquals(0, manager.getConfiguration().getCacheConfigurations().size()); manager.removeCache(null); manager.removeCache(""); assertEquals(0, manager.getConfiguration().getCacheConfigurations().size()); } finally { manager.shutdown(); } } @Test public void testRemoveCache() throws CacheException { singletonManager = CacheManager.create(); assertEquals(15, singletonManager.getConfiguration().getCacheConfigurations().size()); Ehcache cache = singletonManager.getCache("sampleCache1"); assertNotNull(cache); singletonManager.removeCache("sampleCache1"); cache = singletonManager.getCache("sampleCache1"); assertNull(cache); assertEquals(14, singletonManager.getConfiguration().getCacheConfigurations().size()); singletonManager.removeCache(null); singletonManager.removeCache(""); assertEquals(14, singletonManager.getConfiguration().getCacheConfigurations().size()); }
### Question: CacheManager { public void shutdown() { synchronized (CacheManager.class) { if (status.equals(Status.STATUS_SHUTDOWN)) { LOG.debug("CacheManager already shutdown"); return; } for (CacheManagerPeerProvider cacheManagerPeerProvider : cacheManagerPeerProviders.values()) { if (cacheManagerPeerProvider != null) { cacheManagerPeerProvider.dispose(); } } if (cacheManagerTimer != null) { cacheManagerTimer.cancel(); cacheManagerTimer.purge(); } cacheManagerEventListenerRegistry.dispose(); synchronized (CacheManager.class) { ALL_CACHE_MANAGERS.remove(this); for (Ehcache cache : ehcaches.values()) { if (cache != null) { cache.dispose(); } } if (defaultCache != null) { defaultCache.dispose(); } status = Status.STATUS_SHUTDOWN; XARequestProcessor.shutdown(); if (this == singleton) { singleton = null; } terracottaClient.shutdown(); transactionController = null; removeShutdownHook(); nonstopExecutorServiceFactory.shutdown(this); } } } CacheManager(Configuration configuration); CacheManager(String configurationFileName); CacheManager(URL configurationURL); CacheManager(InputStream configurationInputStream); CacheManager(); String getClusterUUID(); Store createTerracottaStore(Ehcache cache); WriteBehind createTerracottaWriteBehind(Ehcache cache); CacheEventListener createTerracottaEventReplicator(Ehcache cache); static CacheManager create(); static CacheManager getInstance(); static CacheManager create(String configurationFileName); static CacheManager create(URL configurationFileURL); static CacheManager create(InputStream inputStream); static CacheManager create(Configuration config); Cache getCache(String name); Ehcache getEhcache(String name); void addCache(String cacheName); void addCache(Cache cache); void addCache(Ehcache cache); void addDecoratedCache(Ehcache decoratedCache); void addDecoratedCacheIfAbsent(Ehcache decoratedCache); boolean cacheExists(String cacheName); void removalAll(); void removeCache(String cacheName); void shutdown(); String[] getCacheNames(); Status getStatus(); void clearAll(); void clearAllStartingWith(String prefix); CacheManagerPeerProvider getCacheManagerPeerProvider(String scheme); Map<String, CacheManagerPeerProvider> getCacheManagerPeerProviders(); CacheManagerPeerListener getCachePeerListener(String scheme); CacheManagerEventListener getCacheManagerEventListener(); void setCacheManagerEventListener(CacheManagerEventListener cacheManagerEventListener); CacheManagerEventListenerRegistry getCacheManagerEventListenerRegistry(); void replaceCacheWithDecoratedCache(Ehcache ehcache, Ehcache decoratedCache); String getName(); boolean isNamed(); void setName(String name); @Override String toString(); String getDiskStorePath(); FailSafeTimer getTimer(); CacheCluster getCluster(ClusterScheme scheme); String getOriginalConfigurationText(); String getActiveConfigurationText(); String getOriginalConfigurationText(String cacheName); String getActiveConfigurationText(String cacheName); @Override int hashCode(); Ehcache addCacheIfAbsent(final Ehcache cache); Ehcache addCacheIfAbsent(final String cacheName); TransactionController getTransactionController(); static final String DEFAULT_NAME; static final List<CacheManager> ALL_CACHE_MANAGERS; static final String ENABLE_SHUTDOWN_HOOK_PROPERTY; }### Answer: @Test public void testForCacheManagerThreadLeak() throws CacheException, InterruptedException { int startingThreadCount = countThreads(); URL secondCacheConfiguration = this.getClass().getResource( "/ehcache-2.xml"); for (int i = 0; i < 100; i++) { instanceManager = new CacheManager(secondCacheConfiguration); instanceManager.shutdown(); } int endingThreadCount; int tries = 0; do { Thread.sleep(500); endingThreadCount = countThreads(); } while (tries++ < 5 || endingThreadCount >= startingThreadCount + 2); assertTrue(endingThreadCount < startingThreadCount + 2); } @Test public void testMultipleCacheManagers() { CacheManager[] managers = new CacheManager[2]; managers[0] = new CacheManager(makeCacheManagerConfig()); managers[1] = new CacheManager(makeCacheManagerConfig()); managers[0].shutdown(); managers[1].shutdown(); }
### Question: CacheManager { public static CacheManager create() throws CacheException { if (singleton != null) { return singleton; } synchronized (CacheManager.class) { if (singleton == null) { LOG.debug("Creating new CacheManager with default config"); singleton = new CacheManager(); } else { LOG.debug("Attempting to create an existing singleton. Existing singleton returned."); } return singleton; } } CacheManager(Configuration configuration); CacheManager(String configurationFileName); CacheManager(URL configurationURL); CacheManager(InputStream configurationInputStream); CacheManager(); String getClusterUUID(); Store createTerracottaStore(Ehcache cache); WriteBehind createTerracottaWriteBehind(Ehcache cache); CacheEventListener createTerracottaEventReplicator(Ehcache cache); static CacheManager create(); static CacheManager getInstance(); static CacheManager create(String configurationFileName); static CacheManager create(URL configurationFileURL); static CacheManager create(InputStream inputStream); static CacheManager create(Configuration config); Cache getCache(String name); Ehcache getEhcache(String name); void addCache(String cacheName); void addCache(Cache cache); void addCache(Ehcache cache); void addDecoratedCache(Ehcache decoratedCache); void addDecoratedCacheIfAbsent(Ehcache decoratedCache); boolean cacheExists(String cacheName); void removalAll(); void removeCache(String cacheName); void shutdown(); String[] getCacheNames(); Status getStatus(); void clearAll(); void clearAllStartingWith(String prefix); CacheManagerPeerProvider getCacheManagerPeerProvider(String scheme); Map<String, CacheManagerPeerProvider> getCacheManagerPeerProviders(); CacheManagerPeerListener getCachePeerListener(String scheme); CacheManagerEventListener getCacheManagerEventListener(); void setCacheManagerEventListener(CacheManagerEventListener cacheManagerEventListener); CacheManagerEventListenerRegistry getCacheManagerEventListenerRegistry(); void replaceCacheWithDecoratedCache(Ehcache ehcache, Ehcache decoratedCache); String getName(); boolean isNamed(); void setName(String name); @Override String toString(); String getDiskStorePath(); FailSafeTimer getTimer(); CacheCluster getCluster(ClusterScheme scheme); String getOriginalConfigurationText(); String getActiveConfigurationText(); String getOriginalConfigurationText(String cacheName); String getActiveConfigurationText(String cacheName); @Override int hashCode(); Ehcache addCacheIfAbsent(final Ehcache cache); Ehcache addCacheIfAbsent(final String cacheName); TransactionController getTransactionController(); static final String DEFAULT_NAME; static final List<CacheManager> ALL_CACHE_MANAGERS; static final String ENABLE_SHUTDOWN_HOOK_PROPERTY; }### Answer: @Test public void testCacheManagerThreads() throws CacheException, InterruptedException { singletonManager = CacheManager .create(AbstractCacheTest.TEST_CONFIG_DIR + "ehcache-big.xml"); int threads = countThreads(); assertTrue("More than 145 threads: " + threads, countThreads() <= 145); }
### Question: DelegatingManagementEventSink implements ManagementEventSink { @Override public void sendManagementEvent(Serializable event, String type) { ManagementEventSink sink = get(); if (sink != null) { sink.sendManagementEvent(event, type); } } DelegatingManagementEventSink(TerracottaClient terracottaClient); @Override void sendManagementEvent(Serializable event, String type); }### Answer: @Test public void testNullClusteredInstanceFactoryForUnclusteredMode() throws Exception { TerracottaClient terracottaClient = mock(TerracottaClient.class); DelegatingManagementEventSink delegatingManagementEventSink = new DelegatingManagementEventSink(terracottaClient); delegatingManagementEventSink.sendManagementEvent("event1", "type1"); } @Test public void testClusteredInstanceFactoryChangeDetected() throws Exception { TerracottaClient terracottaClient = mock(TerracottaClient.class); ClusteredInstanceFactory clusteredInstanceFactory_1 = mock(ClusteredInstanceFactory.class); ClusteredInstanceFactory clusteredInstanceFactory_2 = mock(ClusteredInstanceFactory.class); ManagementEventSink managementEventSink_1 = mock(ManagementEventSink.class); ManagementEventSink managementEventSink_2 = mock(ManagementEventSink.class); when(clusteredInstanceFactory_1.createEventSink()).thenReturn(managementEventSink_1); when(clusteredInstanceFactory_2.createEventSink()).thenReturn(managementEventSink_2); when(terracottaClient.getClusteredInstanceFactory()).thenReturn(clusteredInstanceFactory_1); DelegatingManagementEventSink delegatingManagementEventSink = new DelegatingManagementEventSink(terracottaClient); delegatingManagementEventSink.sendManagementEvent("event1", "type1"); verify(managementEventSink_1, times(1)).sendManagementEvent("event1", "type1"); verify(managementEventSink_2, times(0)).sendManagementEvent(any(Serializable.class), anyString()); when(terracottaClient.getClusteredInstanceFactory()).thenReturn(clusteredInstanceFactory_2); delegatingManagementEventSink.sendManagementEvent("event2", "type2"); delegatingManagementEventSink.sendManagementEvent("event2", "type2"); verify(managementEventSink_1, times(1)).sendManagementEvent("event1", "type1"); verify(managementEventSink_2, times(2)).sendManagementEvent("event2", "type2"); }
### Question: EhcacheStatsImpl extends BaseEmitterBean implements EhcacheStats { public boolean isRegionCacheOrphanEvictionEnabled(String region) { Cache cache = this.cacheManager.getCache(region); if (cache != null && cache.isTerracottaClustered()) { return cache.getCacheConfiguration().getTerracottaConfiguration().getOrphanEviction(); } else { return false; } } EhcacheStatsImpl(CacheManager manager); boolean isStatisticsEnabled(); void clearStats(); void disableStats(); void enableStats(); void flushRegionCache(String region); void flushRegionCaches(); String generateActiveConfigDeclaration(); String generateActiveConfigDeclaration(String region); long getCacheHitCount(); double getCacheHitRate(); long getCacheHitSample(); long getCacheMissCount(); double getCacheMissRate(); long getCacheMissSample(); long getCachePutCount(); double getCachePutRate(); long getCachePutSample(); String getOriginalConfigDeclaration(); String getOriginalConfigDeclaration(String region); Map<String, Map<String, Object>> getRegionCacheAttributes(); Map<String, Object> getRegionCacheAttributes(String regionName); int getRegionCacheMaxTTISeconds(String region); int getRegionCacheMaxTTLSeconds(String region); int getRegionCacheOrphanEvictionPeriod(String region); Map<String, int[]> getRegionCacheSamples(); int getRegionCacheTargetMaxInMemoryCount(String region); int getRegionCacheTargetMaxTotalCount(String region); String[] getTerracottaHibernateCacheRegionNames(); boolean isRegionCacheEnabled(String region); void setRegionCacheEnabled(String region, boolean enabled); boolean isRegionCachesEnabled(); void setRegionCachesEnabled(final boolean flag); boolean isRegionCacheLoggingEnabled(String region); boolean isRegionCacheOrphanEvictionEnabled(String region); boolean isTerracottaHibernateCache(String region); void setRegionCacheLoggingEnabled(String region, boolean loggingEnabled); void setRegionCacheMaxTTISeconds(String region, int maxTTISeconds); void setRegionCacheMaxTTLSeconds(String region, int maxTTLSeconds); void setRegionCacheTargetMaxInMemoryCount(String region, int targetMaxInMemoryCount); void setRegionCacheTargetMaxTotalCount(String region, int targetMaxTotalCount); int getNumberOfElementsInMemory(String region); int getNumberOfElementsOffHeap(String region); int getNumberOfElementsOnDisk(String region); void setStatisticsEnabled(boolean flag); long getMaxGetTimeMillis(); long getMinGetTimeMillis(); long getMaxGetTimeMillis(String cacheName); long getMinGetTimeMillis(String cacheName); float getAverageGetTimeMillis(String region); @Override MBeanNotificationInfo[] getNotificationInfo(); }### Answer: @Test public void testIsRegionCacheOrphanEvictionEnabled() { assertThat(stats.isRegionCacheOrphanEvictionEnabled("sampleCache1"), is(false)); }
### Question: EhcacheStatsImpl extends BaseEmitterBean implements EhcacheStats { public int getRegionCacheOrphanEvictionPeriod(String region) { Cache cache = this.cacheManager.getCache(region); if (cache != null && cache.isTerracottaClustered()) { return cache.getCacheConfiguration().getTerracottaConfiguration().getOrphanEvictionPeriod(); } else { return -1; } } EhcacheStatsImpl(CacheManager manager); boolean isStatisticsEnabled(); void clearStats(); void disableStats(); void enableStats(); void flushRegionCache(String region); void flushRegionCaches(); String generateActiveConfigDeclaration(); String generateActiveConfigDeclaration(String region); long getCacheHitCount(); double getCacheHitRate(); long getCacheHitSample(); long getCacheMissCount(); double getCacheMissRate(); long getCacheMissSample(); long getCachePutCount(); double getCachePutRate(); long getCachePutSample(); String getOriginalConfigDeclaration(); String getOriginalConfigDeclaration(String region); Map<String, Map<String, Object>> getRegionCacheAttributes(); Map<String, Object> getRegionCacheAttributes(String regionName); int getRegionCacheMaxTTISeconds(String region); int getRegionCacheMaxTTLSeconds(String region); int getRegionCacheOrphanEvictionPeriod(String region); Map<String, int[]> getRegionCacheSamples(); int getRegionCacheTargetMaxInMemoryCount(String region); int getRegionCacheTargetMaxTotalCount(String region); String[] getTerracottaHibernateCacheRegionNames(); boolean isRegionCacheEnabled(String region); void setRegionCacheEnabled(String region, boolean enabled); boolean isRegionCachesEnabled(); void setRegionCachesEnabled(final boolean flag); boolean isRegionCacheLoggingEnabled(String region); boolean isRegionCacheOrphanEvictionEnabled(String region); boolean isTerracottaHibernateCache(String region); void setRegionCacheLoggingEnabled(String region, boolean loggingEnabled); void setRegionCacheMaxTTISeconds(String region, int maxTTISeconds); void setRegionCacheMaxTTLSeconds(String region, int maxTTLSeconds); void setRegionCacheTargetMaxInMemoryCount(String region, int targetMaxInMemoryCount); void setRegionCacheTargetMaxTotalCount(String region, int targetMaxTotalCount); int getNumberOfElementsInMemory(String region); int getNumberOfElementsOffHeap(String region); int getNumberOfElementsOnDisk(String region); void setStatisticsEnabled(boolean flag); long getMaxGetTimeMillis(); long getMinGetTimeMillis(); long getMaxGetTimeMillis(String cacheName); long getMinGetTimeMillis(String cacheName); float getAverageGetTimeMillis(String region); @Override MBeanNotificationInfo[] getNotificationInfo(); }### Answer: @Test public void testGetRegionCacheOrphanEvictionPeriod() { assertThat(stats.getRegionCacheOrphanEvictionPeriod("sampleCache1"), is(-1)); }
### Question: Element implements Serializable, Cloneable { public final boolean isSerializable() { return isKeySerializable() && (value instanceof Serializable || value == null) && elementEvictionData.canParticipateInSerialization(); } Element(final Serializable key, final Serializable value, final long version); Element(final Object key, final Object value, final long version); @Deprecated Element(final Object key, final Object value, final long version, final long creationTime, final long lastAccessTime, final long nextToLastAccessTime, final long lastUpdateTime, final long hitCount); Element(final Object key, final Object value, final long version, final long creationTime, final long lastAccessTime, final long lastUpdateTime, final long hitCount); Element(final Object key, final Object value, final long version, final long creationTime, final long lastAccessTime, final long hitCount, final boolean cacheDefaultLifespan, final int timeToLive, final int timeToIdle, final long lastUpdateTime); Element(final Object key, final Object value, final Boolean eternal, final Integer timeToIdleSeconds, final Integer timeToLiveSeconds); Element(final Serializable key, final Serializable value); Element(final Object key, final Object value); final Serializable getKey(); final Object getObjectKey(); final Serializable getValue(); final Object getObjectValue(); @Override final boolean equals(final Object object); void setTimeToLive(final int timeToLiveSeconds); void setTimeToIdle(final int timeToIdleSeconds); @Override final int hashCode(); final void setVersion(final long version); @Deprecated final void setCreateTime(); final long getCreationTime(); final long getLatestOfCreationAndUpdateTime(); final long getVersion(); final long getLastAccessTime(); @Deprecated final long getNextToLastAccessTime(); final long getHitCount(); ElementEvictionData getElementEvictionData(); void setElementEvictionData(ElementEvictionData elementEvictionData); final void resetAccessStatistics(); final void updateAccessStatistics(); final void updateUpdateStatistics(); @Override final String toString(); @Override final Object clone(); final long getSerializedSize(); final boolean isSerializable(); final boolean isKeySerializable(); long getLastUpdateTime(); boolean isExpired(); boolean isExpired(CacheConfiguration config); long getExpirationTime(); boolean isEternal(); void setEternal(final boolean eternal); boolean isLifespanSet(); int getTimeToLive(); int getTimeToIdle(); boolean usesCacheDefaultLifespan(); }### Answer: @Test public void testIsSerializable() { Element element = new Element(null, null); assertTrue(element.isSerializable()); Element elementWithNullValue = new Element("1", null); assertTrue(elementWithNullValue.isSerializable()); Element elementWithNullKey = new Element(null, "1"); assertTrue(elementWithNullValue.isSerializable()); Element elementWithObjectKey = new Element(new Object(), "1"); assertTrue(elementWithNullValue.isSerializable()); }
### Question: Element implements Serializable, Cloneable { @Override public final boolean equals(final Object object) { if (object == null || !(object instanceof Element)) { return false; } Element element = (Element) object; if (key == null || element.getObjectKey() == null) { return false; } return key.equals(element.getObjectKey()); } Element(final Serializable key, final Serializable value, final long version); Element(final Object key, final Object value, final long version); @Deprecated Element(final Object key, final Object value, final long version, final long creationTime, final long lastAccessTime, final long nextToLastAccessTime, final long lastUpdateTime, final long hitCount); Element(final Object key, final Object value, final long version, final long creationTime, final long lastAccessTime, final long lastUpdateTime, final long hitCount); Element(final Object key, final Object value, final long version, final long creationTime, final long lastAccessTime, final long hitCount, final boolean cacheDefaultLifespan, final int timeToLive, final int timeToIdle, final long lastUpdateTime); Element(final Object key, final Object value, final Boolean eternal, final Integer timeToIdleSeconds, final Integer timeToLiveSeconds); Element(final Serializable key, final Serializable value); Element(final Object key, final Object value); final Serializable getKey(); final Object getObjectKey(); final Serializable getValue(); final Object getObjectValue(); @Override final boolean equals(final Object object); void setTimeToLive(final int timeToLiveSeconds); void setTimeToIdle(final int timeToIdleSeconds); @Override final int hashCode(); final void setVersion(final long version); @Deprecated final void setCreateTime(); final long getCreationTime(); final long getLatestOfCreationAndUpdateTime(); final long getVersion(); final long getLastAccessTime(); @Deprecated final long getNextToLastAccessTime(); final long getHitCount(); ElementEvictionData getElementEvictionData(); void setElementEvictionData(ElementEvictionData elementEvictionData); final void resetAccessStatistics(); final void updateAccessStatistics(); final void updateUpdateStatistics(); @Override final String toString(); @Override final Object clone(); final long getSerializedSize(); final boolean isSerializable(); final boolean isKeySerializable(); long getLastUpdateTime(); boolean isExpired(); boolean isExpired(CacheConfiguration config); long getExpirationTime(); boolean isEternal(); void setEternal(final boolean eternal); boolean isLifespanSet(); int getTimeToLive(); int getTimeToIdle(); boolean usesCacheDefaultLifespan(); }### Answer: @Test public void testEquals() { Element element = new Element("key", "value"); assertFalse(element.equals("dog")); assertTrue(element.equals(element)); assertFalse(element.equals(null)); assertFalse(element.equals(new Element("cat", "hat"))); }
### Question: ApplicationEhCache extends javax.ws.rs.core.Application { public Set<Class<?>> getClasses() { Set<Class<?>> s = new HashSet<Class<?>>(); s.add(net.sf.ehcache.management.resource.services.ElementsResourceServiceImpl.class); s.add(net.sf.ehcache.management.resource.services.CacheStatisticSamplesResourceServiceImpl.class); s.add(net.sf.ehcache.management.resource.services.CachesResourceServiceImpl.class); s.add(net.sf.ehcache.management.resource.services.CacheManagersResourceServiceImpl.class); s.add(net.sf.ehcache.management.resource.services.CacheManagerConfigsResourceServiceImpl.class); s.add(net.sf.ehcache.management.resource.services.CacheConfigsResourceServiceImpl.class); s.add(net.sf.ehcache.management.resource.services.AgentsResourceServiceImpl.class); s.add(net.sf.ehcache.management.resource.exceptions.WebApplicationExceptionMapper.class); s.add(net.sf.ehcache.management.resource.exceptions.DefaultExceptionMapper.class); s.add(net.sf.ehcache.management.resource.exceptions.ResourceRuntimeExceptionMapper.class); return s; } Set<Class<?>> getClasses(); }### Answer: @Test public void testGetClasses() throws Exception { List<String> classpathElements = getClasspathElements(); ApplicationEhCache applicationEhCache = new ApplicationEhCache(); Set<Class<?>> applicationClasses = applicationEhCache.getClasses(); Set<Class<?>> allClassesFound = new HashSet<Class<?>>(); for (String cpElement : classpathElements) { if (cpElement.endsWith(".jar")) { if (pathOfJarNotFiltered(cpElement)) { System.out.println("last scanned path : " + cpElement); allClassesFound.addAll(getAllClassesFromJar(cpElement)); } } else { System.out.println("last scanned path : " + cpElement); allClassesFound.addAll(getAllClassesFromDirectory(cpElement)); } } Set<Class<?>> annotatedClasses = new HashSet<Class<?>>(); for (Class<?> aClass : allClassesFound) { if (aClass.isAnnotationPresent(javax.ws.rs.ext.Provider.class) || aClass.isAnnotationPresent(javax.ws.rs.Path.class)) { annotatedClasses.add(aClass); } } Assert.assertThat(annotatedClasses, equalTo(applicationClasses)); }
### Question: MemorySizeParser { public static long parse(String configuredMemorySize) throws IllegalArgumentException { MemorySize size = parseIncludingUnit(configuredMemorySize); return size.calculateMemorySizeInBytes(); } static long parse(String configuredMemorySize); }### Answer: @Test public void testParse() { assertEquals(0, MemorySizeParser.parse("0")); assertEquals(0, MemorySizeParser.parse("")); assertEquals(0, MemorySizeParser.parse(null)); assertEquals(10, MemorySizeParser.parse("10")); assertEquals(4096, MemorySizeParser.parse("4k")); assertEquals(4096, MemorySizeParser.parse("4K")); assertEquals(16777216, MemorySizeParser.parse("16m")); assertEquals(16777216, MemorySizeParser.parse("16M")); assertEquals(2147483648L, MemorySizeParser.parse("2g")); assertEquals(2147483648L, MemorySizeParser.parse("2G")); assertEquals(3298534883328L, MemorySizeParser.parse("3t")); assertEquals(3298534883328L, MemorySizeParser.parse("3T")); } @Test public void testParseErrors() { try { MemorySizeParser.parse("-1G"); Assert.fail("expected IllegalArgumentException"); } catch (IllegalArgumentException e) { } try { MemorySizeParser.parse("1000y"); Assert.fail("expected IllegalArgumentException"); } catch (IllegalArgumentException e) { } }
### Question: ClusteredStore implements TerracottaStore, StoreListener { @Override public Element putIfAbsent(Element element) throws NullPointerException { if (isEventual) { throw new UnsupportedOperationException( "CAS operations are not supported in eventual consistency mode, consider using a StronglyConsistentCacheAccessor"); } String pKey = generatePortableKeyFor(element.getObjectKey()); ElementData value = valueModeHandler.createElementData(element); Serializable data = backend.putIfAbsent(pKey, value); return data == null ? null : this.valueModeHandler.createElement(element.getKey(), data); } ClusteredStore(ToolkitInstanceFactory toolkitInstanceFactory, Ehcache cache, CacheCluster topology); String getFullyQualifiedCacheName(); @Override void recalculateSize(Object key); @Override synchronized void addStoreListener(StoreListener listener); @Override synchronized void removeStoreListener(StoreListener listener); @Override void clusterCoherent(final boolean clusterCoherent); @Override boolean put(Element element); @Override boolean putWithWriter(Element element, CacheWriterManager writerManager); @Override void putAll(Collection<Element> elements); @Override Element get(Object key); @Override Element getQuiet(Object key); @Override List getKeys(); @Override Element remove(Object key); @Override void removeAll(Collection<?> keys); @Override Element removeWithWriter(Object key, CacheWriterManager writerManager); @Override void removeAll(); @Override Element putIfAbsent(Element element); @Override Element removeElement(Element element, ElementValueComparator comparator); @Override boolean replace(Element old, Element element, ElementValueComparator comparator); @Override Element replace(Element element); @Override void dispose(); @Override int getSize(); @Override @Statistic(name = "size", tags = "local-heap") int getInMemorySize(); @Override @Statistic(name = "size", tags = "local-offheap") int getOffHeapSize(); @Override int getOnDiskSize(); @Override @Statistic(name = "size", tags = "remote") int getTerracottaClusteredSize(); @Override @Statistic(name = "size-in-bytes", tags = "local-heap") long getInMemorySizeInBytes(); @Override @Statistic(name = "size-in-bytes", tags = "local-offheap") long getOffHeapSizeInBytes(); @Override long getOnDiskSizeInBytes(); @Override boolean hasAbortedSizeOf(); @Override Status getStatus(); @Override boolean containsKey(Object key); @Override boolean containsKeyOnDisk(Object key); @Override boolean containsKeyOffHeap(Object key); @Override boolean containsKeyInMemory(Object key); @Override void expireElements(); @Override void flush(); @Override boolean bufferFull(); @Override Policy getInMemoryEvictionPolicy(); @Override void setInMemoryEvictionPolicy(Policy policy); @Override Object getInternalContext(); @Override boolean isCacheCoherent(); @Override boolean isClusterCoherent(); @Override boolean isNodeCoherent(); @Override void setNodeCoherent(boolean coherent); @Override void waitUntilClusterCoherent(); @Override Object getMBean(); @Override void setAttributeExtractors(Map<String, AttributeExtractor> extractors); @Override Results executeQuery(StoreQuery query); @Override Attribute<T> getSearchAttribute(String attributeName); @Override Map<Object, Element> getAllQuiet(Collection<?> keys); @Override Map<Object, Element> getAll(Collection<?> keys); String generatePortableKeyFor(final Object obj); @Override Element unsafeGet(Object key); @Override Set getLocalKeys(); @Override TransactionalMode getTransactionalMode(); boolean isSearchable(); String getLeader(); @Override WriteBehind createWriteBehind(); @Override synchronized void notifyCacheEventListenersChanged(); }### Answer: @Test(expected = UnsupportedOperationException.class) public void clusteredStore_putIfAbsent_throw_in_eventual_consistency() { clusteredStore.putIfAbsent(new Element("key", "value")); }
### Question: ClusteredStore implements TerracottaStore, StoreListener { @Override public boolean replace(Element old, Element element, ElementValueComparator comparator) throws NullPointerException, IllegalArgumentException { if (isEventual) { throw new UnsupportedOperationException( "CAS operations are not supported in eventual consistency mode, consider using a StronglyConsistentCacheAccessor"); } String pKey = generatePortableKeyFor(element.getKey()); ToolkitReadWriteLock lock = backend.createLockForKey(pKey); lock.writeLock().lock(); try { Element oldElement = getQuiet(element.getKey()); if (comparator.equals(oldElement, old)) { return putInternal(element); } } finally { lock.writeLock().unlock(); } return false; } ClusteredStore(ToolkitInstanceFactory toolkitInstanceFactory, Ehcache cache, CacheCluster topology); String getFullyQualifiedCacheName(); @Override void recalculateSize(Object key); @Override synchronized void addStoreListener(StoreListener listener); @Override synchronized void removeStoreListener(StoreListener listener); @Override void clusterCoherent(final boolean clusterCoherent); @Override boolean put(Element element); @Override boolean putWithWriter(Element element, CacheWriterManager writerManager); @Override void putAll(Collection<Element> elements); @Override Element get(Object key); @Override Element getQuiet(Object key); @Override List getKeys(); @Override Element remove(Object key); @Override void removeAll(Collection<?> keys); @Override Element removeWithWriter(Object key, CacheWriterManager writerManager); @Override void removeAll(); @Override Element putIfAbsent(Element element); @Override Element removeElement(Element element, ElementValueComparator comparator); @Override boolean replace(Element old, Element element, ElementValueComparator comparator); @Override Element replace(Element element); @Override void dispose(); @Override int getSize(); @Override @Statistic(name = "size", tags = "local-heap") int getInMemorySize(); @Override @Statistic(name = "size", tags = "local-offheap") int getOffHeapSize(); @Override int getOnDiskSize(); @Override @Statistic(name = "size", tags = "remote") int getTerracottaClusteredSize(); @Override @Statistic(name = "size-in-bytes", tags = "local-heap") long getInMemorySizeInBytes(); @Override @Statistic(name = "size-in-bytes", tags = "local-offheap") long getOffHeapSizeInBytes(); @Override long getOnDiskSizeInBytes(); @Override boolean hasAbortedSizeOf(); @Override Status getStatus(); @Override boolean containsKey(Object key); @Override boolean containsKeyOnDisk(Object key); @Override boolean containsKeyOffHeap(Object key); @Override boolean containsKeyInMemory(Object key); @Override void expireElements(); @Override void flush(); @Override boolean bufferFull(); @Override Policy getInMemoryEvictionPolicy(); @Override void setInMemoryEvictionPolicy(Policy policy); @Override Object getInternalContext(); @Override boolean isCacheCoherent(); @Override boolean isClusterCoherent(); @Override boolean isNodeCoherent(); @Override void setNodeCoherent(boolean coherent); @Override void waitUntilClusterCoherent(); @Override Object getMBean(); @Override void setAttributeExtractors(Map<String, AttributeExtractor> extractors); @Override Results executeQuery(StoreQuery query); @Override Attribute<T> getSearchAttribute(String attributeName); @Override Map<Object, Element> getAllQuiet(Collection<?> keys); @Override Map<Object, Element> getAll(Collection<?> keys); String generatePortableKeyFor(final Object obj); @Override Element unsafeGet(Object key); @Override Set getLocalKeys(); @Override TransactionalMode getTransactionalMode(); boolean isSearchable(); String getLeader(); @Override WriteBehind createWriteBehind(); @Override synchronized void notifyCacheEventListenersChanged(); }### Answer: @Test(expected = UnsupportedOperationException.class) public void clusteredStore_replace_1_arg_throw_in_eventual_consistency() { clusteredStore.replace(new Element("key", "value")); } @Test(expected = UnsupportedOperationException.class) public void clusteredStore_replace_2_args_throw_in_eventual_consistency() { clusteredStore.replace(new Element("key", "value"), new Element("key", "other"), new DefaultElementValueComparator(cacheConfiguration)); }
### Question: ClusteredStore implements TerracottaStore, StoreListener { @Override public Element removeElement(Element element, ElementValueComparator comparator) throws NullPointerException { if (isEventual) { throw new UnsupportedOperationException( "CAS operations are not supported in eventual consistency mode, consider using a StronglyConsistentCacheAccessor"); } String pKey = generatePortableKeyFor(element.getKey()); ToolkitReadWriteLock lock = backend.createLockForKey(pKey); lock.writeLock().lock(); try { Element oldElement = getQuiet(element.getKey()); if (comparator.equals(oldElement, element)) { return remove(element.getKey()); } } finally { lock.writeLock().unlock(); } return null; } ClusteredStore(ToolkitInstanceFactory toolkitInstanceFactory, Ehcache cache, CacheCluster topology); String getFullyQualifiedCacheName(); @Override void recalculateSize(Object key); @Override synchronized void addStoreListener(StoreListener listener); @Override synchronized void removeStoreListener(StoreListener listener); @Override void clusterCoherent(final boolean clusterCoherent); @Override boolean put(Element element); @Override boolean putWithWriter(Element element, CacheWriterManager writerManager); @Override void putAll(Collection<Element> elements); @Override Element get(Object key); @Override Element getQuiet(Object key); @Override List getKeys(); @Override Element remove(Object key); @Override void removeAll(Collection<?> keys); @Override Element removeWithWriter(Object key, CacheWriterManager writerManager); @Override void removeAll(); @Override Element putIfAbsent(Element element); @Override Element removeElement(Element element, ElementValueComparator comparator); @Override boolean replace(Element old, Element element, ElementValueComparator comparator); @Override Element replace(Element element); @Override void dispose(); @Override int getSize(); @Override @Statistic(name = "size", tags = "local-heap") int getInMemorySize(); @Override @Statistic(name = "size", tags = "local-offheap") int getOffHeapSize(); @Override int getOnDiskSize(); @Override @Statistic(name = "size", tags = "remote") int getTerracottaClusteredSize(); @Override @Statistic(name = "size-in-bytes", tags = "local-heap") long getInMemorySizeInBytes(); @Override @Statistic(name = "size-in-bytes", tags = "local-offheap") long getOffHeapSizeInBytes(); @Override long getOnDiskSizeInBytes(); @Override boolean hasAbortedSizeOf(); @Override Status getStatus(); @Override boolean containsKey(Object key); @Override boolean containsKeyOnDisk(Object key); @Override boolean containsKeyOffHeap(Object key); @Override boolean containsKeyInMemory(Object key); @Override void expireElements(); @Override void flush(); @Override boolean bufferFull(); @Override Policy getInMemoryEvictionPolicy(); @Override void setInMemoryEvictionPolicy(Policy policy); @Override Object getInternalContext(); @Override boolean isCacheCoherent(); @Override boolean isClusterCoherent(); @Override boolean isNodeCoherent(); @Override void setNodeCoherent(boolean coherent); @Override void waitUntilClusterCoherent(); @Override Object getMBean(); @Override void setAttributeExtractors(Map<String, AttributeExtractor> extractors); @Override Results executeQuery(StoreQuery query); @Override Attribute<T> getSearchAttribute(String attributeName); @Override Map<Object, Element> getAllQuiet(Collection<?> keys); @Override Map<Object, Element> getAll(Collection<?> keys); String generatePortableKeyFor(final Object obj); @Override Element unsafeGet(Object key); @Override Set getLocalKeys(); @Override TransactionalMode getTransactionalMode(); boolean isSearchable(); String getLeader(); @Override WriteBehind createWriteBehind(); @Override synchronized void notifyCacheEventListenersChanged(); }### Answer: @Test(expected = UnsupportedOperationException.class) public void clusteredStore_removeElement_throw_in_eventual_consistency() { clusteredStore.removeElement(new Element("key", "value"), new DefaultElementValueComparator(cacheConfiguration)); }
### Question: ClusteredStore implements TerracottaStore, StoreListener { @Override public void dispose() { dropLeaderStatus(); topology.removeTopologyListener(eventListenersRefresher); backend.removeListener(evictionListener); backend.disposeLocally(); cacheConfigChangeBridge.disconnectConfigs(); toolkitInstanceFactory.removeNonStopConfigforCache(cache); } ClusteredStore(ToolkitInstanceFactory toolkitInstanceFactory, Ehcache cache, CacheCluster topology); String getFullyQualifiedCacheName(); @Override void recalculateSize(Object key); @Override synchronized void addStoreListener(StoreListener listener); @Override synchronized void removeStoreListener(StoreListener listener); @Override void clusterCoherent(final boolean clusterCoherent); @Override boolean put(Element element); @Override boolean putWithWriter(Element element, CacheWriterManager writerManager); @Override void putAll(Collection<Element> elements); @Override Element get(Object key); @Override Element getQuiet(Object key); @Override List getKeys(); @Override Element remove(Object key); @Override void removeAll(Collection<?> keys); @Override Element removeWithWriter(Object key, CacheWriterManager writerManager); @Override void removeAll(); @Override Element putIfAbsent(Element element); @Override Element removeElement(Element element, ElementValueComparator comparator); @Override boolean replace(Element old, Element element, ElementValueComparator comparator); @Override Element replace(Element element); @Override void dispose(); @Override int getSize(); @Override @Statistic(name = "size", tags = "local-heap") int getInMemorySize(); @Override @Statistic(name = "size", tags = "local-offheap") int getOffHeapSize(); @Override int getOnDiskSize(); @Override @Statistic(name = "size", tags = "remote") int getTerracottaClusteredSize(); @Override @Statistic(name = "size-in-bytes", tags = "local-heap") long getInMemorySizeInBytes(); @Override @Statistic(name = "size-in-bytes", tags = "local-offheap") long getOffHeapSizeInBytes(); @Override long getOnDiskSizeInBytes(); @Override boolean hasAbortedSizeOf(); @Override Status getStatus(); @Override boolean containsKey(Object key); @Override boolean containsKeyOnDisk(Object key); @Override boolean containsKeyOffHeap(Object key); @Override boolean containsKeyInMemory(Object key); @Override void expireElements(); @Override void flush(); @Override boolean bufferFull(); @Override Policy getInMemoryEvictionPolicy(); @Override void setInMemoryEvictionPolicy(Policy policy); @Override Object getInternalContext(); @Override boolean isCacheCoherent(); @Override boolean isClusterCoherent(); @Override boolean isNodeCoherent(); @Override void setNodeCoherent(boolean coherent); @Override void waitUntilClusterCoherent(); @Override Object getMBean(); @Override void setAttributeExtractors(Map<String, AttributeExtractor> extractors); @Override Results executeQuery(StoreQuery query); @Override Attribute<T> getSearchAttribute(String attributeName); @Override Map<Object, Element> getAllQuiet(Collection<?> keys); @Override Map<Object, Element> getAll(Collection<?> keys); String generatePortableKeyFor(final Object obj); @Override Element unsafeGet(Object key); @Override Set getLocalKeys(); @Override TransactionalMode getTransactionalMode(); boolean isSearchable(); String getLeader(); @Override WriteBehind createWriteBehind(); @Override synchronized void notifyCacheEventListenersChanged(); }### Answer: @Test public void testDispose() throws Exception { clusteredStore.dispose(); verify(toolkitCacheInternal).disposeLocally(); verify(cacheCluster).removeTopologyListener(any(ClusterTopologyListener.class)); verify(toolkitCacheInternal).removeListener(any(ToolkitCacheListener.class)); }
### Question: AsyncWriteBehind implements WriteBehind { @Override public void delete(CacheEntry entry) { async.add(new DeleteAsyncOperation(entry.getKey(), entry.getElement())); } AsyncWriteBehind(AsyncCoordinator async, Ehcache cache); @Override void start(CacheWriter writer); @Override void write(Element element); @Override void delete(CacheEntry entry); @Override void setOperationsFilter(OperationsFilter filter); @Override void stop(); @Override long getQueueSize(); }### Answer: @Test(expected = IllegalStateException.class) public void testDeleteThrowsWhenNotStarted() { AsyncWriteBehind writeBehind = createAsyncWriteBehind(); writeBehind.delete(new CacheEntry("", new Element("", ""))); }
### Question: AsyncWriteBehind implements WriteBehind { @Override public void write(Element element) { async.add(new WriteAsyncOperation(element)); } AsyncWriteBehind(AsyncCoordinator async, Ehcache cache); @Override void start(CacheWriter writer); @Override void write(Element element); @Override void delete(CacheEntry entry); @Override void setOperationsFilter(OperationsFilter filter); @Override void stop(); @Override long getQueueSize(); }### Answer: @Test(expected = IllegalStateException.class) public void testWriteThrowsWhenNotStarted() { AsyncWriteBehind writeBehind = createAsyncWriteBehind(); writeBehind.write(new Element("", "")); }
### Question: UpdateChecker extends TimerTask { public void checkForUpdate() { try { if (!Boolean.getBoolean("net.sf.ehcache.skipUpdateCheck")) { doCheck(); } } catch (Throwable t) { LOG.debug("Update check failed: ", t); } } UpdateChecker(); @Override void run(); void checkForUpdate(); }### Answer: @Test public void testErrorNotBubleUp() { System.setProperty("net.sf.ehcache.skipUpdateCheck", "false"); System.setProperty("ehcache.update-check.url", "this is a bad url"); UpdateChecker uc = new UpdateChecker(); uc.checkForUpdate(); }
### Question: TerracottaBootstrapCacheLoader extends MemoryLimitedCacheLoader implements Disposable { public void load(final Ehcache cache) throws CacheException { if (!cache.getCacheConfiguration().isTerracottaClustered()) { LOG.error("You're trying to bootstrap a non Terracotta clustered cache with a TerracottaBootstrapCacheLoader! Cache " + "'{}' will not be bootstrapped and no keySet snapshot will be recorded...", cache.getName()); return; } if (cache.getStatus() != Status.STATUS_ALIVE) { throw new CacheException("Cache '" + cache.getName() + "' isn't alive yet: " + cache.getStatus()); } if (isAsynchronous()) { BootstrapThread thread = new BootstrapThread(cache); thread.start(); } else { doLoad(cache); } } private TerracottaBootstrapCacheLoader(final boolean doKeySnapshot, final boolean aSynchronous, final String directory, final long interval, final boolean doKeySnapshotOnDedicatedThread); TerracottaBootstrapCacheLoader(final boolean asynchronous, String directory, boolean doKeySnapshots); TerracottaBootstrapCacheLoader(final boolean asynchronous, String directory, long interval); TerracottaBootstrapCacheLoader(final boolean asynchronous, String directory, long interval, boolean onDedicatedThread); boolean isImmediateShutdown(); void setImmediateShutdown(final boolean immediateShutdown); void load(final Ehcache cache); boolean isAsynchronous(); void dispose(); void doLocalKeySnapshot(); @Override Object clone(); void setSnapshotOnDispose(final boolean doKeySnapshotOnDispose); static final long DEFAULT_INTERVAL; static final boolean DEFAULT_DEDICATED_THREAD; }### Answer: @Test public void testBootstrapsWhenSnapshotPresent() throws Exception { DiskStorePathManager pathManager = getDiskStorePathManager(cacheLoader); RotatingSnapshotFile file = new RotatingSnapshotFile(pathManager, MOCKED_CACHE_NAME); final List<Integer> localKeys = Arrays.asList(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 9); file.writeAll(localKeys); final Ehcache cache = mockCacheToBootStrap(); cacheLoader.load(cache); verify(cache, times(new HashSet<Integer>(localKeys).size())).get(Matchers.anyObject()); for (Integer localKey : localKeys) { verify(cache, times(1)).get((Object) localKey); } file.currentSnapshotFile().delete(); } @Test public void testComplainsOnNonTcClusteredCacheButDoesNotFail() { cacheLoader.load(new Cache(new CacheConfiguration("test", 0))); } @Test(expected = CacheException.class) public void testFailsWhenCacheIsNotAlive() { cacheLoader.load(new Cache(new CacheConfiguration("test", 0).terracotta(new TerracottaConfiguration()))); } @Test public void testBootstrapsWhenNoSnapshotPresent() { final Ehcache cache = mockCacheToBootStrap(); cacheLoader.load(cache); verify(cache, never()).get(Matchers.anyObject()); } @Test public void testBootstrapsWhenSnapshotPresent() throws Exception { DiskStorePathManager pathManager = getDiskStorePathManager(cacheLoader); RotatingSnapshotFile file = new RotatingSnapshotFile(pathManager, MOCKED_CACHE_NAME, getClass().getClassLoader()); final List<Integer> localKeys = Arrays.asList(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 9); file.writeAll(localKeys); final Ehcache cache = mockCacheToBootStrap(); cacheLoader.load(cache); verify(cache, times(new HashSet<Integer>(localKeys).size())).get(Matchers.anyObject()); for (Integer localKey : localKeys) { verify(cache, times(1)).get((Object) localKey); } file.currentSnapshotFile().delete(); }
### Question: MemoryEfficientByteArrayOutputStream extends ByteArrayOutputStream { public synchronized byte getBytes()[] { if (buf.length == size()) { return buf; } else { byte[] copy = new byte[size()]; System.arraycopy(buf, 0, copy, 0, size()); return copy; } } MemoryEfficientByteArrayOutputStream(int size); synchronized byte getBytes(); static MemoryEfficientByteArrayOutputStream serialize(Serializable serializable, int estimatedPayloadSize); static MemoryEfficientByteArrayOutputStream serialize(Serializable serializable); }### Answer: @Test public void testOutputIsCorrectlySized() throws IOException { Random rndm = new Random(); for (int i = 0; i < 100; i++) { int size = rndm.nextInt(1024); int initial = rndm.nextInt(1024); MemoryEfficientByteArrayOutputStream out = new MemoryEfficientByteArrayOutputStream(initial); out.write(new byte[size]); Assert.assertEquals(size, out.getBytes().length); } }
### Question: BlockingCache implements Ehcache { public Element getWithLoader(Object key, CacheLoader loader, Object loaderArgument) throws CacheException { throw new CacheException("This method is not appropriate for a Blocking Cache"); } BlockingCache(final Ehcache cache, int numberOfStripes); BlockingCache(final Ehcache cache); String getName(); void setName(String name); boolean isExpired(Element element); @Override Object clone(); RegisteredEventListeners getCacheEventNotificationService(); boolean isElementInMemory(Serializable key); boolean isElementInMemory(Object key); boolean isElementOnDisk(Serializable key); boolean isElementOnDisk(Object key); String getGuid(); CacheManager getCacheManager(); void clearStatistics(); int getStatisticsAccuracy(); void setStatisticsAccuracy(int statisticsAccuracy); void evictExpiredElements(); boolean isKeyInCache(Object key); boolean isValueInCache(Object value); Statistics getStatistics(); LiveCacheStatistics getLiveCacheStatistics(); void setCacheManager(CacheManager cacheManager); BootstrapCacheLoader getBootstrapCacheLoader(); void setBootstrapCacheLoader(BootstrapCacheLoader bootstrapCacheLoader); void setDiskStorePath(String diskStorePath); void initialise(); void bootstrap(); void dispose(); CacheConfiguration getCacheConfiguration(); Element get(final Object key); void put(Element element); void put(Element element, boolean doNotNotifyCacheReplicators); void putQuiet(Element element); Element get(Serializable key); Element getQuiet(Serializable key); Element getQuiet(Object key); List getKeys(); List getKeysWithExpiryCheck(); List getKeysNoDuplicateCheck(); boolean remove(Serializable key); boolean remove(Object key); boolean remove(Serializable key, boolean doNotNotifyCacheReplicators); boolean remove(Object key, boolean doNotNotifyCacheReplicators); boolean removeQuiet(Serializable key); boolean removeQuiet(Object key); void removeAll(); void removeAll(boolean doNotNotifyCacheReplicators); void flush(); int getSize(); int getSizeBasedOnAccuracy(int statisticsAccuracy); long calculateInMemorySize(); long getMemoryStoreSize(); int getDiskStoreSize(); Status getStatus(); synchronized String liveness(); void setTimeoutMillis(int timeoutMillis); int getTimeoutMillis(); void registerCacheExtension(CacheExtension cacheExtension); void unregisterCacheExtension(CacheExtension cacheExtension); List<CacheExtension> getRegisteredCacheExtensions(); float getAverageGetTime(); void setCacheExceptionHandler(CacheExceptionHandler cacheExceptionHandler); CacheExceptionHandler getCacheExceptionHandler(); void registerCacheLoader(CacheLoader cacheLoader); void unregisterCacheLoader(CacheLoader cacheLoader); List<CacheLoader> getRegisteredCacheLoaders(); Element getWithLoader(Object key, CacheLoader loader, Object loaderArgument); Map getAllWithLoader(Collection keys, Object loaderArgument); void load(Object key); void loadAll(Collection keys, Object argument); boolean isDisabled(); void setDisabled(boolean disabled); void registerCacheUsageListener(CacheUsageListener cacheUsageListener); void removeCacheUsageListener(CacheUsageListener cacheUsageListener); boolean isStatisticsEnabled(); void setStatisticsEnabled(boolean enabledStatistics); SampledCacheStatistics getSampledCacheStatistics(); void setSampledStatisticsEnabled(boolean enabledStatistics); boolean isSampledStatisticsEnabled(); Object getInternalContext(); }### Answer: @Test public void testGetWithLoader() { super.testGetWithLoader(); }
### Question: CacheManager { public void shutdown() { synchronized (CacheManager.class) { if (status.equals(Status.STATUS_SHUTDOWN)) { LOG.debug("CacheManager already shutdown"); return; } for (CacheManagerPeerProvider cacheManagerPeerProvider : cacheManagerPeerProviders.values()) { if (cacheManagerPeerProvider != null) { cacheManagerPeerProvider.dispose(); } } if (cacheManagerTimer != null) { cacheManagerTimer.cancel(); cacheManagerTimer.purge(); } cacheManagerEventListenerRegistry.dispose(); synchronized (CacheManager.class) { ALL_CACHE_MANAGERS.remove(this); Collection cacheSet = ehcaches.values(); for (Iterator iterator = cacheSet.iterator(); iterator.hasNext();) { Ehcache cache = (Ehcache) iterator.next(); if (cache != null) { cache.dispose(); } } defaultCache.dispose(); status = Status.STATUS_SHUTDOWN; if (this == singleton) { singleton = null; } removeShutdownHook(); } } } CacheManager(Configuration configuration); CacheManager(String configurationFileName); CacheManager(URL configurationURL); CacheManager(InputStream configurationInputStream); CacheManager(); static CacheManager create(); static CacheManager getInstance(); static CacheManager create(String configurationFileName); static CacheManager create(URL configurationFileURL); static CacheManager create(InputStream inputStream); Cache getCache(String name); Ehcache getEhcache(String name); void addCache(String cacheName); void addCache(Cache cache); void addCache(Ehcache cache); boolean cacheExists(String cacheName); void removalAll(); void removeCache(String cacheName); void shutdown(); String[] getCacheNames(); Status getStatus(); void clearAll(); CacheManagerPeerProvider getCacheManagerPeerProvider(String scheme); CacheManagerPeerListener getCachePeerListener(String scheme); CacheManagerEventListener getCacheManagerEventListener(); void setCacheManagerEventListener(CacheManagerEventListener cacheManagerEventListener); CacheManagerEventListenerRegistry getCacheManagerEventListenerRegistry(); void replaceCacheWithDecoratedCache(Ehcache ehcache, Ehcache decoratedCache); String getName(); boolean isNamed(); void setName(String name); @Override String toString(); String getDiskStorePath(); FailSafeTimer getTimer(); static final List<CacheManager> ALL_CACHE_MANAGERS; static final String ENABLE_SHUTDOWN_HOOK_PROPERTY; }### Answer: @Test public void testForCacheManagerThreadLeak() throws CacheException, InterruptedException { int startingThreadCount = countThreads(); URL secondCacheConfiguration = this.getClass().getResource( "/ehcache-2.xml"); for (int i = 0; i < 100; i++) { instanceManager = new CacheManager(secondCacheConfiguration); instanceManager.shutdown(); } int endingThreadCount; int tries = 0; do { Thread.sleep(500); endingThreadCount = countThreads(); } while (tries++ < 5 || endingThreadCount >= startingThreadCount + 2); assertTrue(endingThreadCount < startingThreadCount + 2); } @Test public void testMultipleCacheManagers() { CacheManager[] managers = new CacheManager[2]; managers[0] = new CacheManager(makeCacheManagerConfig()); managers[1] = new CacheManager(makeCacheManagerConfig()); managers[0].shutdown(); managers[1].shutdown(); }
### Question: ConcurrentHashMap implements ConcurrentMap<K, V> { @SuppressWarnings("unchecked") public V put(K key, V value) { if (key == null || value == null) throw new NullPointerException(); return (V)internalPut(key, value); } ConcurrentHashMap(); ConcurrentHashMap(int initialCapacity); ConcurrentHashMap(Map<? extends K, ? extends V> m); ConcurrentHashMap(int initialCapacity, float loadFactor); ConcurrentHashMap(int initialCapacity, float loadFactor, int concurrencyLevel); static KeySetView<K,Boolean> newKeySet(); static KeySetView<K,Boolean> newKeySet(int initialCapacity); boolean isEmpty(); int size(); long mappingCount(); @SuppressWarnings("unchecked") V get(Object key); @Deprecated void recalculateSize(final K k); List<V> getRandomValues(int amount); @SuppressWarnings("unchecked") V getValueOrDefault(Object key, V defaultValue); boolean containsKey(Object key); boolean containsValue(Object value); boolean contains(Object value); @SuppressWarnings("unchecked") V put(K key, V value); @SuppressWarnings("unchecked") V putIfAbsent(K key, V value); void putAll(Map<? extends K, ? extends V> m); @SuppressWarnings("unchecked") V remove(Object key); boolean remove(Object key, Object value); boolean replace(K key, V oldValue, V newValue); @SuppressWarnings("unchecked") V replace(K key, V value); void clear(); KeySetView<K,V> keySet(); KeySetView<K,V> keySet(V mappedValue); ValuesView<K,V> values(); Set<Map.Entry<K,V>> entrySet(); Enumeration<K> keys(); Enumeration<V> elements(); Spliterator<K> keySpliterator(); Spliterator<V> valueSpliterator(); Spliterator<Map.Entry<K,V>> entrySpliterator(); int hashCode(); String toString(); boolean equals(Object o); }### Answer: @Test public void testRandomValuesWithObjects() { ConcurrentHashMap<Object, KeyHolder<Object>> map = new ConcurrentHashMap<Object, KeyHolder<Object>>(); for(int i = 0; i < ENTRIES; i++) { final Object o = new Object(); map.put(o, new KeyHolder<Object>(o)); } assertThings(map); }
### Question: CacheManager { public static CacheManager create() throws CacheException { if (singleton != null) { return singleton; } synchronized (CacheManager.class) { if (singleton == null) { LOG.debug("Creating new CacheManager with default config"); singleton = new CacheManager(); } else { LOG.debug("Attempting to create an existing singleton. Existing singleton returned."); } return singleton; } } CacheManager(Configuration configuration); CacheManager(String configurationFileName); CacheManager(URL configurationURL); CacheManager(InputStream configurationInputStream); CacheManager(); static CacheManager create(); static CacheManager getInstance(); static CacheManager create(String configurationFileName); static CacheManager create(URL configurationFileURL); static CacheManager create(InputStream inputStream); Cache getCache(String name); Ehcache getEhcache(String name); void addCache(String cacheName); void addCache(Cache cache); void addCache(Ehcache cache); boolean cacheExists(String cacheName); void removalAll(); void removeCache(String cacheName); void shutdown(); String[] getCacheNames(); Status getStatus(); void clearAll(); CacheManagerPeerProvider getCacheManagerPeerProvider(String scheme); CacheManagerPeerListener getCachePeerListener(String scheme); CacheManagerEventListener getCacheManagerEventListener(); void setCacheManagerEventListener(CacheManagerEventListener cacheManagerEventListener); CacheManagerEventListenerRegistry getCacheManagerEventListenerRegistry(); void replaceCacheWithDecoratedCache(Ehcache ehcache, Ehcache decoratedCache); String getName(); boolean isNamed(); void setName(String name); @Override String toString(); String getDiskStorePath(); FailSafeTimer getTimer(); static final List<CacheManager> ALL_CACHE_MANAGERS; static final String ENABLE_SHUTDOWN_HOOK_PROPERTY; }### Answer: @Test public void testCacheManagerThreads() throws CacheException, InterruptedException { singletonManager = CacheManager .create(AbstractCacheTest.TEST_CONFIG_DIR + "ehcache-big.xml"); int threads = countThreads(); assertTrue("More than 145 threads: " + threads, countThreads() <= 145); }
### Question: CacheManager { public Cache getCache(String name) throws IllegalStateException, ClassCastException { checkStatus(); return (Cache) caches.get(name); } CacheManager(Configuration configuration); CacheManager(String configurationFileName); CacheManager(URL configurationURL); CacheManager(InputStream configurationInputStream); CacheManager(); static CacheManager create(); static CacheManager getInstance(); static CacheManager create(String configurationFileName); static CacheManager create(URL configurationFileURL); static CacheManager create(InputStream inputStream); Cache getCache(String name); Ehcache getEhcache(String name); void addCache(String cacheName); void addCache(Cache cache); void addCache(Ehcache cache); boolean cacheExists(String cacheName); void removalAll(); void removeCache(String cacheName); void shutdown(); String[] getCacheNames(); Status getStatus(); void clearAll(); CacheManagerPeerProvider getCacheManagerPeerProvider(String scheme); CacheManagerPeerListener getCachePeerListener(String scheme); CacheManagerEventListener getCacheManagerEventListener(); void setCacheManagerEventListener(CacheManagerEventListener cacheManagerEventListener); CacheManagerEventListenerRegistry getCacheManagerEventListenerRegistry(); void replaceCacheWithDecoratedCache(Ehcache ehcache, Ehcache decoratedCache); String getName(); boolean isNamed(); void setName(String name); @Override String toString(); String getDiskStorePath(); FailSafeTimer getTimer(); static final List<CacheManager> ALL_CACHE_MANAGERS; static final String ENABLE_SHUTDOWN_HOOK_PROPERTY; }### Answer: @Test public void testGetCache() throws CacheException { instanceManager = CacheManager.create(); Ehcache cache = instanceManager.getCache("sampleCache1"); assertNotNull(cache); }
### Question: CacheManager { public void removeCache(String cacheName) throws IllegalStateException { checkStatus(); if (cacheName == null || cacheName.length() == 0) { return; } Ehcache cache = (Ehcache) ehcaches.remove(cacheName); if (cache != null && cache.getStatus().equals(Status.STATUS_ALIVE)) { cache.dispose(); cacheManagerEventListenerRegistry.notifyCacheRemoved(cache.getName()); } caches.remove(cacheName); } CacheManager(Configuration configuration); CacheManager(String configurationFileName); CacheManager(URL configurationURL); CacheManager(InputStream configurationInputStream); CacheManager(); static CacheManager create(); static CacheManager getInstance(); static CacheManager create(String configurationFileName); static CacheManager create(URL configurationFileURL); static CacheManager create(InputStream inputStream); Cache getCache(String name); Ehcache getEhcache(String name); void addCache(String cacheName); void addCache(Cache cache); void addCache(Ehcache cache); boolean cacheExists(String cacheName); void removalAll(); void removeCache(String cacheName); void shutdown(); String[] getCacheNames(); Status getStatus(); void clearAll(); CacheManagerPeerProvider getCacheManagerPeerProvider(String scheme); CacheManagerPeerListener getCachePeerListener(String scheme); CacheManagerEventListener getCacheManagerEventListener(); void setCacheManagerEventListener(CacheManagerEventListener cacheManagerEventListener); CacheManagerEventListenerRegistry getCacheManagerEventListenerRegistry(); void replaceCacheWithDecoratedCache(Ehcache ehcache, Ehcache decoratedCache); String getName(); boolean isNamed(); void setName(String name); @Override String toString(); String getDiskStorePath(); FailSafeTimer getTimer(); static final List<CacheManager> ALL_CACHE_MANAGERS; static final String ENABLE_SHUTDOWN_HOOK_PROPERTY; }### Answer: @Test public void testRemoveCache() throws CacheException { singletonManager = CacheManager.create(); Ehcache cache = singletonManager.getCache("sampleCache1"); assertNotNull(cache); singletonManager.removeCache("sampleCache1"); cache = singletonManager.getCache("sampleCache1"); assertNull(cache); singletonManager.removeCache(null); singletonManager.removeCache(""); }
### Question: CacheManager { public void addCache(String cacheName) throws IllegalStateException, ObjectExistsException, CacheException { checkStatus(); if (cacheName == null || cacheName.length() == 0) { return; } if (ehcaches.get(cacheName) != null) { throw new ObjectExistsException("Cache " + cacheName + " already exists"); } Ehcache cache = null; try { cache = (Ehcache) defaultCache.clone(); } catch (CloneNotSupportedException e) { throw new CacheException("Failure adding cache. Initial cause was " + e.getMessage(), e); } if (cache != null) { cache.setName(cacheName); } addCache(cache); } CacheManager(Configuration configuration); CacheManager(String configurationFileName); CacheManager(URL configurationURL); CacheManager(InputStream configurationInputStream); CacheManager(); static CacheManager create(); static CacheManager getInstance(); static CacheManager create(String configurationFileName); static CacheManager create(URL configurationFileURL); static CacheManager create(InputStream inputStream); Cache getCache(String name); Ehcache getEhcache(String name); void addCache(String cacheName); void addCache(Cache cache); void addCache(Ehcache cache); boolean cacheExists(String cacheName); void removalAll(); void removeCache(String cacheName); void shutdown(); String[] getCacheNames(); Status getStatus(); void clearAll(); CacheManagerPeerProvider getCacheManagerPeerProvider(String scheme); CacheManagerPeerListener getCachePeerListener(String scheme); CacheManagerEventListener getCacheManagerEventListener(); void setCacheManagerEventListener(CacheManagerEventListener cacheManagerEventListener); CacheManagerEventListenerRegistry getCacheManagerEventListenerRegistry(); void replaceCacheWithDecoratedCache(Ehcache ehcache, Ehcache decoratedCache); String getName(); boolean isNamed(); void setName(String name); @Override String toString(); String getDiskStorePath(); FailSafeTimer getTimer(); static final List<CacheManager> ALL_CACHE_MANAGERS; static final String ENABLE_SHUTDOWN_HOOK_PROPERTY; }### Answer: @Test public void testAddCache() throws CacheException { singletonManager = CacheManager.create(); singletonManager.addCache("test"); singletonManager.addCache("test2"); 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); singletonManager.addCache(""); }
### Question: Element implements Serializable, Cloneable { public final boolean isSerializable() { return isKeySerializable() && (value instanceof Serializable || value == null) && elementEvictionData.canParticipateInSerialization(); } Element(final Serializable key, final Serializable value, final long version); Element(final Object key, final Object value, final long version); @Deprecated Element(final Object key, final Object value, final long version, final long creationTime, final long lastAccessTime, final long nextToLastAccessTime, final long lastUpdateTime, final long hitCount); Element(final Object key, final Object value, final long version, final long creationTime, final long lastAccessTime, final long lastUpdateTime, final long hitCount); Element(final Object key, final Object value, final long version, final long creationTime, final long lastAccessTime, final long hitCount, final int timeToLive, final int timeToIdle, final long lastUpdateTime); Element(final Object key, final Object value, final Boolean eternal, final Integer timeToIdleSeconds, final Integer timeToLiveSeconds); Element(final Serializable key, final Serializable value); Element(final Object key, final Object value); final Serializable getKey(); final Object getObjectKey(); final Serializable getValue(); final Object getObjectValue(); @Override final boolean equals(final Object object); void setTimeToLive(final int timeToLiveSeconds); void setTimeToIdle(final int timeToIdleSeconds); @Override final int hashCode(); final void setVersion(final long version); @Deprecated final void setCreateTime(); final long getCreationTime(); final long getLatestOfCreationAndUpdateTime(); final long getVersion(); final long getLastAccessTime(); @Deprecated final long getNextToLastAccessTime(); final long getHitCount(); ElementEvictionData getElementEvictionData(); void setElementEvictionData(ElementEvictionData elementEvictionData); final void resetAccessStatistics(); final void updateAccessStatistics(); final void updateUpdateStatistics(); @Override final String toString(); @Override final Object clone(); final long getSerializedSize(); final boolean isSerializable(); final boolean isKeySerializable(); long getLastUpdateTime(); boolean isExpired(); long getExpirationTime(); boolean isEternal(); void setEternal(final boolean eternal); boolean isLifespanSet(); int getTimeToLive(); int getTimeToIdle(); }### Answer: @Test public void testIsSerializable() { Element element = new Element(null, null); assertTrue(element.isSerializable()); Element elementWithNullValue = new Element("1", null); assertTrue(elementWithNullValue.isSerializable()); Element elementWithNullKey = new Element(null, "1"); assertTrue(elementWithNullValue.isSerializable()); Element elementWithObjectKey = new Element(new Object(), "1"); assertTrue(elementWithNullValue.isSerializable()); }
### Question: Element implements Serializable, Cloneable { @Override public final boolean equals(final Object object) { if (object == null || !(object instanceof Element)) { return false; } Element element = (Element) object; if (key == null || element.getObjectKey() == null) { return false; } return key.equals(element.getObjectKey()); } Element(final Serializable key, final Serializable value, final long version); Element(final Object key, final Object value, final long version); @Deprecated Element(final Object key, final Object value, final long version, final long creationTime, final long lastAccessTime, final long nextToLastAccessTime, final long lastUpdateTime, final long hitCount); Element(final Object key, final Object value, final long version, final long creationTime, final long lastAccessTime, final long lastUpdateTime, final long hitCount); Element(final Object key, final Object value, final long version, final long creationTime, final long lastAccessTime, final long hitCount, final int timeToLive, final int timeToIdle, final long lastUpdateTime); Element(final Object key, final Object value, final Boolean eternal, final Integer timeToIdleSeconds, final Integer timeToLiveSeconds); Element(final Serializable key, final Serializable value); Element(final Object key, final Object value); final Serializable getKey(); final Object getObjectKey(); final Serializable getValue(); final Object getObjectValue(); @Override final boolean equals(final Object object); void setTimeToLive(final int timeToLiveSeconds); void setTimeToIdle(final int timeToIdleSeconds); @Override final int hashCode(); final void setVersion(final long version); @Deprecated final void setCreateTime(); final long getCreationTime(); final long getLatestOfCreationAndUpdateTime(); final long getVersion(); final long getLastAccessTime(); @Deprecated final long getNextToLastAccessTime(); final long getHitCount(); ElementEvictionData getElementEvictionData(); void setElementEvictionData(ElementEvictionData elementEvictionData); final void resetAccessStatistics(); final void updateAccessStatistics(); final void updateUpdateStatistics(); @Override final String toString(); @Override final Object clone(); final long getSerializedSize(); final boolean isSerializable(); final boolean isKeySerializable(); long getLastUpdateTime(); boolean isExpired(); long getExpirationTime(); boolean isEternal(); void setEternal(final boolean eternal); boolean isLifespanSet(); int getTimeToLive(); int getTimeToIdle(); }### Answer: @Test public void testEquals() { Element element = new Element("key", "value"); assertFalse(element.equals("dog")); assertTrue(element.equals(element)); assertFalse(element.equals(null)); assertFalse(element.equals(new Element("cat", "hat"))); }
### Question: UpdatingSelfPopulatingCache extends SelfPopulatingCache { public Element get(final Object key) throws LockTimeoutException { try { Ehcache backingCache = getCache(); Element element = backingCache.get(key); if (element == null) { element = super.get(key); } else { Mutex lock = stripedMutex.getMutexForKey(key); try { lock.acquire(); update(key); } finally { lock.release(); } } return element; } catch (final Throwable throwable) { put(new Element(key, null)); throw new LockTimeoutException("Could not update object for cache entry with key \"" + key + "\".", throwable); } } UpdatingSelfPopulatingCache(Ehcache cache, final UpdatingCacheEntryFactory factory); Element get(final Object key); void refresh(); }### Answer: @Test public void testFetchAndUpdate() throws Exception { final String value = "value"; final CountingCacheEntryFactory factory = new CountingCacheEntryFactory(value); selfPopulatingCache = new UpdatingSelfPopulatingCache(cache, factory); Element element = selfPopulatingCache.get(null); element = selfPopulatingCache.get("key"); assertSame(value, element.getObjectValue()); assertEquals(2, factory.getCount()); Object actualValue = selfPopulatingCache.get("key").getObjectValue(); assertSame(value, actualValue); assertEquals(3, factory.getCount()); actualValue = selfPopulatingCache.get("key").getObjectValue(); assertSame(value, actualValue); assertEquals(4, factory.getCount()); } @Test public void testFetchFail() throws Exception { final Exception exception = new Exception("Failed."); final UpdatingCacheEntryFactory factory = new UpdatingCacheEntryFactory() { public Object createEntry(final Object key) throws Exception { throw exception; } public void updateEntryValue(Object key, Object value) throws Exception { throw exception; } }; selfPopulatingCache = new UpdatingSelfPopulatingCache(cache, factory); try { selfPopulatingCache.get("key"); fail(); } catch (final Exception e) { Thread.sleep(20); assertEquals("Could not update object for cache entry with key \"key\".", e.getMessage()); } }
### Question: BlockingCache implements Ehcache { protected Ehcache getCache() { return cache; } BlockingCache(final Ehcache cache, int numberOfStripes); BlockingCache(final Ehcache cache); String getName(); void setName(String name); boolean isExpired(Element element); Object clone(); RegisteredEventListeners getCacheEventNotificationService(); boolean isElementInMemory(Serializable key); boolean isElementInMemory(Object key); boolean isElementOnDisk(Serializable key); boolean isElementOnDisk(Object key); String getGuid(); CacheManager getCacheManager(); void clearStatistics(); int getStatisticsAccuracy(); void setStatisticsAccuracy(int statisticsAccuracy); void evictExpiredElements(); boolean isKeyInCache(Object key); boolean isValueInCache(Object value); Statistics getStatistics(); void setCacheManager(CacheManager cacheManager); BootstrapCacheLoader getBootstrapCacheLoader(); void setBootstrapCacheLoader(BootstrapCacheLoader bootstrapCacheLoader); void setDiskStorePath(String diskStorePath); void initialise(); void bootstrap(); void dispose(); CacheConfiguration getCacheConfiguration(); Element get(final Object key); void put(Element element); void put(Element element, boolean doNotNotifyCacheReplicators); void putQuiet(Element element); Element get(Serializable key); Element getQuiet(Serializable key); Element getQuiet(Object key); List getKeys(); List getKeysWithExpiryCheck(); List getKeysNoDuplicateCheck(); boolean remove(Serializable key); boolean remove(Object key); boolean remove(Serializable key, boolean doNotNotifyCacheReplicators); boolean remove(Object key, boolean doNotNotifyCacheReplicators); boolean removeQuiet(Serializable key); boolean removeQuiet(Object key); void removeAll(); void removeAll(boolean doNotNotifyCacheReplicators); void flush(); int getSize(); long calculateInMemorySize(); long getMemoryStoreSize(); int getDiskStoreSize(); Status getStatus(); synchronized String liveness(); void setTimeoutMillis(int timeoutMillis); int getTimeoutMillis(); void registerCacheExtension(CacheExtension cacheExtension); void unregisterCacheExtension(CacheExtension cacheExtension); List<CacheExtension> getRegisteredCacheExtensions(); float getAverageGetTime(); void setCacheExceptionHandler(CacheExceptionHandler cacheExceptionHandler); CacheExceptionHandler getCacheExceptionHandler(); void registerCacheLoader(CacheLoader cacheLoader); void unregisterCacheLoader(CacheLoader cacheLoader); List<CacheLoader> getRegisteredCacheLoaders(); Element getWithLoader(Object key, CacheLoader loader, Object loaderArgument); Map getAllWithLoader(Collection keys, Object loaderArgument); void load(Object key); void loadAll(Collection keys, Object argument); boolean isDisabled(); void setDisabled(boolean disabled); }### Answer: @Test public void testThrashBlockingCache() throws Exception { Ehcache cache = manager.getCache("sampleCache1"); blockingCache = new BlockingCache(cache); long duration = thrashCache(blockingCache, 50, 500L, 1000L); LOG.log(Level.FINE, "Thrash Duration:" + duration); }
### Question: BlockingCache implements Ehcache { public Element getWithLoader(Object key, CacheLoader loader, Object loaderArgument) throws CacheException { throw new CacheException("This method is not appropriate for a Blocking Cache"); } BlockingCache(final Ehcache cache, int numberOfStripes); BlockingCache(final Ehcache cache); String getName(); void setName(String name); boolean isExpired(Element element); Object clone(); RegisteredEventListeners getCacheEventNotificationService(); boolean isElementInMemory(Serializable key); boolean isElementInMemory(Object key); boolean isElementOnDisk(Serializable key); boolean isElementOnDisk(Object key); String getGuid(); CacheManager getCacheManager(); void clearStatistics(); int getStatisticsAccuracy(); void setStatisticsAccuracy(int statisticsAccuracy); void evictExpiredElements(); boolean isKeyInCache(Object key); boolean isValueInCache(Object value); Statistics getStatistics(); void setCacheManager(CacheManager cacheManager); BootstrapCacheLoader getBootstrapCacheLoader(); void setBootstrapCacheLoader(BootstrapCacheLoader bootstrapCacheLoader); void setDiskStorePath(String diskStorePath); void initialise(); void bootstrap(); void dispose(); CacheConfiguration getCacheConfiguration(); Element get(final Object key); void put(Element element); void put(Element element, boolean doNotNotifyCacheReplicators); void putQuiet(Element element); Element get(Serializable key); Element getQuiet(Serializable key); Element getQuiet(Object key); List getKeys(); List getKeysWithExpiryCheck(); List getKeysNoDuplicateCheck(); boolean remove(Serializable key); boolean remove(Object key); boolean remove(Serializable key, boolean doNotNotifyCacheReplicators); boolean remove(Object key, boolean doNotNotifyCacheReplicators); boolean removeQuiet(Serializable key); boolean removeQuiet(Object key); void removeAll(); void removeAll(boolean doNotNotifyCacheReplicators); void flush(); int getSize(); long calculateInMemorySize(); long getMemoryStoreSize(); int getDiskStoreSize(); Status getStatus(); synchronized String liveness(); void setTimeoutMillis(int timeoutMillis); int getTimeoutMillis(); void registerCacheExtension(CacheExtension cacheExtension); void unregisterCacheExtension(CacheExtension cacheExtension); List<CacheExtension> getRegisteredCacheExtensions(); float getAverageGetTime(); void setCacheExceptionHandler(CacheExceptionHandler cacheExceptionHandler); CacheExceptionHandler getCacheExceptionHandler(); void registerCacheLoader(CacheLoader cacheLoader); void unregisterCacheLoader(CacheLoader cacheLoader); List<CacheLoader> getRegisteredCacheLoaders(); Element getWithLoader(Object key, CacheLoader loader, Object loaderArgument); Map getAllWithLoader(Collection keys, Object loaderArgument); void load(Object key); void loadAll(Collection keys, Object argument); boolean isDisabled(); void setDisabled(boolean disabled); }### Answer: @Test public void testGetWithLoader() { super.testGetWithLoader(); }
### Question: LargeCollection extends AbstractCollection < E > { public final int size() { return Math.max(0, sourceSize() + addSet.size() - removeSet.size()); } LargeCollection(); @Override final boolean add(final E obj); @Override final boolean contains(final Object obj); @Override final boolean remove(final Object obj); final boolean removeAll(final Collection < ? > removeCandidates); final Iterator < E > iterator(); final int size(); abstract Iterator < E > sourceIterator(); abstract int sourceSize(); }### Answer: @Test public void testSize() throws Exception { final Set<String> authority = new HashSet<String>(); authority.add("1"); authority.add("2"); authority.add("3"); Set<String> set = new LargeSet<String>() { @Override public Iterator<String> sourceIterator() { return authority.iterator(); } @Override public int sourceSize() { return authority.size(); } }; Assert.assertEquals(3, set.size()); set.remove("1"); set.remove("2"); Assert.assertEquals(1, set.size()); authority.remove("2"); authority.remove("3"); Assert.assertEquals(0, set.size()); }
### Question: SelfPopulatingCache extends BlockingCache { @Override public Element get(final Object key) throws LockTimeoutException { try { Element element = super.get(key); if (element == null) { Object value = factory.createEntry(key); element = makeAndCheckElement(key, value); put(element); } return element; } catch (LockTimeoutException e) { String message = "Timeout after " + timeoutMillis + " waiting on another thread " + "to fetch object for cache entry \"" + key + "\"."; throw new LockTimeoutException(message, e); } catch (final Throwable throwable) { throwable.printStackTrace(); put(new Element(key, null)); throw new CacheException("Could not fetch object for cache entry with key \"" + key + "\".", throwable); } } SelfPopulatingCache(final Ehcache cache, final CacheEntryFactory factory); @Override Element get(final Object key); void refresh(); void refresh(boolean quiet); Element refresh(Object key); Element refresh(Object key, boolean quiet); }### Answer: @Test public void testFetch() throws Exception { LOG.error("."); final Element element = selfPopulatingCache.get("key"); assertEquals("value", element.getValue()); } @Test public void testFetchUnknown() throws Exception { final CacheEntryFactory factory = new CountingCacheEntryFactory(null); selfPopulatingCache = new SelfPopulatingCache(cache, factory); assertNull(cache.get("key")); } @Test public void testFetchFail() throws Exception { final Exception exception = new Exception("Failed."); final CacheEntryFactory factory = new CacheEntryFactory() { public Object createEntry(final Object key) throws Exception { throw exception; } }; selfPopulatingCache = new SelfPopulatingCache(cache, factory); try { selfPopulatingCache.get("key"); fail(); } catch (final Exception e) { Thread.sleep(20); assertEquals("Could not fetch object for cache entry with key \"key\".", e.getMessage()); } } @Test public void testCreateOnce() throws Exception { final String value = "value"; final CountingCacheEntryFactory factory = new CountingCacheEntryFactory(value); selfPopulatingCache = new SelfPopulatingCache(cache, factory); for (int i = 0; i < 5; i++) { assertSame(value, selfPopulatingCache.get("key").getObjectValue()); assertEquals(1, factory.getCount()); } } @Test public void testCacheEntryFactoryReturningElementMake() throws Exception { final long specialVersionNumber = 54321L; final CacheEntryFactory elementReturningFactory = new CacheEntryFactory() { public Object createEntry(final Object key) throws Exception { Element e = new Element(key, "V_" + key); e.setVersion(specialVersionNumber); return e; } }; selfPopulatingCache = new SelfPopulatingCache(cache, elementReturningFactory); Element e = null; e = selfPopulatingCache.get("key1"); assertEquals("V_key1", e.getValue()); assertEquals(specialVersionNumber, e.getVersion()); e = selfPopulatingCache.get("key2"); assertEquals("V_key2", e.getValue()); assertEquals(specialVersionNumber, e.getVersion()); assertEquals(2, selfPopulatingCache.getSize()); } @Test public void testCacheEntryFactoryReturningElementBadKey() throws Exception { final CacheEntryFactory elementReturningFactory = new CacheEntryFactory() { public Object createEntry(final Object key) throws Exception { Object modifiedKey = key.toString() + "XX"; Element e = new Element(modifiedKey, "V_" + modifiedKey); return e; } }; selfPopulatingCache = new SelfPopulatingCache(cache, elementReturningFactory); try { selfPopulatingCache.get("key"); fail("Should fail because key was changed"); } catch (final Exception e) { Thread.sleep(20); assertEquals("Could not fetch object for cache entry with key \"key\".", e.getMessage()); } }
### Question: CacheManager { public void shutdown() { synchronized (CacheManager.class) { if (status.equals(Status.STATUS_SHUTDOWN)) { LOG.debug("CacheManager already shutdown"); return; } for (CacheManagerPeerProvider cacheManagerPeerProvider : cacheManagerPeerProviders.values()) { if (cacheManagerPeerProvider != null) { cacheManagerPeerProvider.dispose(); } } if (cacheManagerTimer != null) { cacheManagerTimer.cancel(); cacheManagerTimer.purge(); } cacheManagerEventListenerRegistry.dispose(); synchronized (CacheManager.class) { ALL_CACHE_MANAGERS.remove(this); for (Ehcache cache : ehcaches.values()) { if (cache != null) { cache.dispose(); } } defaultCache.dispose(); status = Status.STATUS_SHUTDOWN; if (this == singleton) { singleton = null; } removeShutdownHook(); } } } CacheManager(Configuration configuration); CacheManager(String configurationFileName); CacheManager(URL configurationURL); CacheManager(InputStream configurationInputStream); CacheManager(); String getClusterUUID(); Store createTerracottaStore(Ehcache cache); WriteBehind createTerracottaWriteBehind(Ehcache cache); CacheEventListener createTerracottaEventReplicator(Ehcache cache); static CacheManager create(); static CacheManager getInstance(); static CacheManager create(String configurationFileName); static CacheManager create(URL configurationFileURL); static CacheManager create(InputStream inputStream); static CacheManager create(Configuration config); Cache getCache(String name); Ehcache getEhcache(String name); void addCache(String cacheName); void addCache(Cache cache); void addCache(Ehcache cache); void addDecoratedCache(Ehcache decoratedCache); boolean cacheExists(String cacheName); void removalAll(); void removeCache(String cacheName); void shutdown(); String[] getCacheNames(); Status getStatus(); void clearAll(); void clearAllStartingWith(String prefix); CacheManagerPeerProvider getCacheManagerPeerProvider(String scheme); CacheManagerPeerListener getCachePeerListener(String scheme); CacheManagerEventListener getCacheManagerEventListener(); void setCacheManagerEventListener(CacheManagerEventListener cacheManagerEventListener); CacheManagerEventListenerRegistry getCacheManagerEventListenerRegistry(); void replaceCacheWithDecoratedCache(Ehcache ehcache, Ehcache decoratedCache); String getName(); boolean isNamed(); void setName(String name); @Override String toString(); String getDiskStorePath(); FailSafeTimer getTimer(); CacheCluster getCluster(ClusterScheme scheme); String getOriginalConfigurationText(); String getActiveConfigurationText(); String getOriginalConfigurationText(String cacheName); String getActiveConfigurationText(String cacheName); @Override int hashCode(); Ehcache addCacheIfAbsent(final Ehcache cache); Ehcache addCacheIfAbsent(final String cacheName); static final String DEFAULT_NAME; static final List<CacheManager> ALL_CACHE_MANAGERS; static final String ENABLE_SHUTDOWN_HOOK_PROPERTY; }### Answer: @Test public void testForCacheManagerThreadLeak() throws CacheException, InterruptedException { int startingThreadCount = countThreads(); URL secondCacheConfiguration = this.getClass().getResource( "/ehcache-2.xml"); for (int i = 0; i < 100; i++) { instanceManager = new CacheManager(secondCacheConfiguration); instanceManager.shutdown(); } int endingThreadCount; int tries = 0; do { Thread.sleep(500); endingThreadCount = countThreads(); } while (tries++ < 5 || endingThreadCount >= startingThreadCount + 2); assertTrue(endingThreadCount < startingThreadCount + 2); } @Test public void testMultipleCacheManagers() { CacheManager[] managers = new CacheManager[2]; managers[0] = new CacheManager(makeCacheManagerConfig()); managers[1] = new CacheManager(makeCacheManagerConfig()); managers[0].shutdown(); managers[1].shutdown(); }
### Question: ReadThroughCache extends EhcacheDecoratorAdapter { @Override public Element get(Object key) throws IllegalStateException, CacheException { if (isModeGet) { return super.getWithLoader(key, null, null); } return super.get(key); } ReadThroughCache(Ehcache underlyingCache, ReadThroughCacheConfiguration config); @Override Element get(Object key); @Override Element get(Serializable key); @Override String getName(); }### Answer: @Test public void testReadThroughSimpleCase() { CacheManager manager = new CacheManager(); manager.removeAllCaches(); 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); Element got = cache.get(new Integer(1)); Assert.assertNull(got); got = decorator.get(new Integer(1)); Assert.assertNotNull(got); got = cache.get(new Integer(1)); Assert.assertNotNull(got); sleepySeconds(10); got = cache.get(new Integer(1)); Assert.assertNull(got); got = decorator.get(new Integer(1)); Assert.assertNotNull(got); got = cache.get(new Integer(1)); Assert.assertNotNull(got); manager.removeAllCaches(); manager.shutdown(); } @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); Element got = cache.get(new Integer(1)); Assert.assertNull(got); got = decorator.get(new Integer(1)); Assert.assertNotNull(got); got = cache.get(new Integer(1)); Assert.assertNotNull(got); sleepySeconds(10); got = cache.get(new Integer(1)); Assert.assertNull(got); got = decorator.get(new Integer(1)); Assert.assertNotNull(got); got = cache.get(new Integer(1)); Assert.assertNotNull(got); manager.removalAll(); manager.shutdown(); }
### Question: StronglyConsistentCacheAccessor extends EhcacheDecoratorAdapter { @Override public Element putIfAbsent(Element element, boolean doNotNotifyCacheReplicators) throws NullPointerException { Object objectKey = element.getObjectKey(); if (objectKey == null) { throw new NullPointerException(); } acquireWriteLockOnKey(objectKey); try { Element current = getQuiet(objectKey); if (current == null) { super.put(element, doNotNotifyCacheReplicators); } return current; } finally { releaseWriteLockOnKey(objectKey); } } StronglyConsistentCacheAccessor(Ehcache underlyingCache); @Override Element putIfAbsent(Element element, boolean doNotNotifyCacheReplicators); @Override Element putIfAbsent(Element element); @Override boolean replace(Element old, Element element); @Override Element replace(Element element); @Override boolean removeElement(Element element); @Override void put(Element element, boolean doNotNotifyCacheReplicators); @Override void put(Element element); @Override void putAll(Collection<Element> elements); @Override void putQuiet(Element element); @Override void putWithWriter(Element element); @Override boolean remove(Object key, boolean doNotNotifyCacheReplicators); @Override void removeAll(Collection<?> keys); @Override boolean remove(Object key); @Override void removeAll(Collection<?> keys, boolean doNotNotifyCacheReplicators); @Override boolean remove(Serializable key, boolean doNotNotifyCacheReplicators); @Override boolean remove(Serializable key); @Override boolean removeQuiet(Object key); @Override boolean removeQuiet(Serializable key); @Override boolean removeWithWriter(Object key); @Override Element removeAndReturnElement(Object key); @Override Element get(Object key); @Override Map<Object, Element> getAll(Collection<?> keys); @Override Element get(Serializable key); @Override Element getQuiet(Object key); @Override Element getQuiet(Serializable key); @Override Element getWithLoader(Object key, CacheLoader loader, Object loaderArgument); @Override Map getAllWithLoader(Collection keys, Object loaderArgument); }### Answer: @Test public void testPutIfAbsent() { Element element = new Element("key", "value"); Ehcache underlyingCache = buildMockCache(); when(underlyingCache.getQuiet((Object)"key")).thenReturn(null, element); StronglyConsistentCacheAccessor cacheAccessor = new StronglyConsistentCacheAccessor(underlyingCache); element = cacheAccessor.putIfAbsent(element); assertThat(element, nullValue()); element = cacheAccessor.putIfAbsent(new Element("key", "otherValue")); assertThat(element.getObjectValue(), equalTo((Object)"value")); try { cacheAccessor.putIfAbsent(new Element(null, null)); fail("Expected NPE with null key"); } catch (NullPointerException e) { } }
### Question: StronglyConsistentCacheAccessor extends EhcacheDecoratorAdapter { @Override public boolean removeElement(Element element) throws NullPointerException { Object objectKey = element.getObjectKey(); if (objectKey == null) { throw new NullPointerException(); } acquireWriteLockOnKey(objectKey); try { Element current = getQuiet(objectKey); if (elementComparator.equals(current, element)) { return super.remove(objectKey); } } finally { releaseWriteLockOnKey(objectKey); } return false; } StronglyConsistentCacheAccessor(Ehcache underlyingCache); @Override Element putIfAbsent(Element element, boolean doNotNotifyCacheReplicators); @Override Element putIfAbsent(Element element); @Override boolean replace(Element old, Element element); @Override Element replace(Element element); @Override boolean removeElement(Element element); @Override void put(Element element, boolean doNotNotifyCacheReplicators); @Override void put(Element element); @Override void putAll(Collection<Element> elements); @Override void putQuiet(Element element); @Override void putWithWriter(Element element); @Override boolean remove(Object key, boolean doNotNotifyCacheReplicators); @Override void removeAll(Collection<?> keys); @Override boolean remove(Object key); @Override void removeAll(Collection<?> keys, boolean doNotNotifyCacheReplicators); @Override boolean remove(Serializable key, boolean doNotNotifyCacheReplicators); @Override boolean remove(Serializable key); @Override boolean removeQuiet(Object key); @Override boolean removeQuiet(Serializable key); @Override boolean removeWithWriter(Object key); @Override Element removeAndReturnElement(Object key); @Override Element get(Object key); @Override Map<Object, Element> getAll(Collection<?> keys); @Override Element get(Serializable key); @Override Element getQuiet(Object key); @Override Element getQuiet(Serializable key); @Override Element getWithLoader(Object key, CacheLoader loader, Object loaderArgument); @Override Map getAllWithLoader(Collection keys, Object loaderArgument); }### Answer: @Test public void testRemoveElement() { Element element = new Element("key", "value"); Ehcache underlyingCache = buildMockCache(); when(underlyingCache.getQuiet((Object)"key")).thenReturn(new Element("key", "other"), element); when(underlyingCache.remove((Object)"key")).thenReturn(true); StronglyConsistentCacheAccessor cacheAccessor = new StronglyConsistentCacheAccessor(underlyingCache); assertThat(cacheAccessor.removeElement(element), is(false)); assertThat(cacheAccessor.removeElement(element), is(true)); try { cacheAccessor.removeElement(new Element(null, null)); fail("Expected NPE with null key"); } catch (NullPointerException e) { } }
### Question: ApplicationEhCacheV2 extends DefaultApplicationV2 implements ApplicationEhCacheService { @Override public Set<Class<?>> getRestResourceClasses() { Set<Class<?>> s = new HashSet<Class<?>>(super.getClasses()); s.add(net.sf.ehcache.management.resource.services.ElementsResourceServiceImplV2.class); s.add(net.sf.ehcache.management.resource.services.CacheStatisticSamplesResourceServiceImplV2.class); s.add(net.sf.ehcache.management.resource.services.CachesResourceServiceImplV2.class); s.add(net.sf.ehcache.management.resource.services.CacheManagersResourceServiceImplV2.class); s.add(net.sf.ehcache.management.resource.services.CacheManagerConfigsResourceServiceImplV2.class); s.add(net.sf.ehcache.management.resource.services.CacheConfigsResourceServiceImplV2.class); s.add(net.sf.ehcache.management.resource.services.QueryResourceServiceImplV2.class); return s; } @Override Set<Class<?>> getRestResourceClasses(); @Override Map<Class<?>, Object> getServiceClasses(ManagementRESTServiceConfiguration configuration, RemoteAgentEndpointImpl agentEndpointImpl); @Override Class<? extends ManagementServerLifecycle> getManagementServerLifecyle(); }### Answer: @Test public void testGetClasses() throws Exception { ApplicationEhCacheV2 applicationEhCache = new ApplicationEhCacheV2(); Set<Class<?>> filteredApplicationClasses = filterClassesFromJaxRSPackages(applicationEhCache.getRestResourceClasses()); Set<Class<?>> annotatedClasses = annotatedClassesFound(); Set<Class<?>> classesToIgnoreDuringComparison = new HashSet<Class<?>>(); if (filteredApplicationClasses.size() > annotatedClasses.size()) { for (Class<?> applicationClass : filteredApplicationClasses) { if(!annotatedClasses.contains(applicationClass)) { fail("While scanning the classpath, we could not find " + applicationClass); } } } else { for (Class<?> annotatedClass : annotatedClasses) { if (!filteredApplicationClasses.contains(annotatedClass)) { fail("Should " + annotatedClass + " be added to DefaultApplicationCommon ?"); } } } filteredApplicationClasses.removeAll(classesToIgnoreDuringComparison); Assert.assertThat(annotatedClasses, equalTo(filteredApplicationClasses)); }
### Question: SelfPopulatingCache extends BlockingCache { @Override public Element get(final Object key) throws LockTimeoutException { Element element = super.get(key); if (element == null) { try { Object value = factory.createEntry(key); element = makeAndCheckElement(key, value); } catch (final Throwable throwable) { element = new Element(key, null); throw new CacheException("Could not fetch object for cache entry with key \"" + key + "\".", throwable); } finally { put(element); } } return element; } SelfPopulatingCache(final Ehcache cache, final CacheEntryFactory factory); SelfPopulatingCache(Ehcache cache, int numberOfStripes, CacheEntryFactory factory); @Override Element get(final Object key); void refresh(); void refresh(boolean quiet); Element refresh(Object key); Element refresh(Object key, boolean quiet); }### Answer: @Test public void testFetch() throws Exception { LOG.error("."); final Element element = selfPopulatingCache.get("key"); assertEquals("value", element.getValue()); } @Test public void testFetchUnknown() throws Exception { final CacheEntryFactory factory = new CountingCacheEntryFactory(null); selfPopulatingCache = new SelfPopulatingCache(cache, factory); assertNull(cache.get("key")); } @Test public void testFetchFail() throws Exception { final Object value = new Object(); final Exception exception = new Exception("Failed."); final AtomicBoolean throwException = new AtomicBoolean(true); final CacheEntryFactory factory = new CacheEntryFactory() { public Object createEntry(final Object key) throws Exception { if (throwException.get()) { throw exception; } else { return value; } } }; selfPopulatingCache = new SelfPopulatingCache(cache, factory); try { selfPopulatingCache.get("key"); fail(); } catch (final Exception e) { Thread.sleep(20); assertEquals("Could not fetch object for cache entry with key \"key\".", e.getMessage()); } throwException.set(false); selfPopulatingCache.setTimeoutMillis(1); Element element = null; try { element = selfPopulatingCache.get("key"); } catch (LockTimeoutException e) { fail("Key should not be locked anymore!"); } assertThat(element, is(notNullValue())); assertThat(element.getObjectValue(), is(value)); } @Test public void testCreateOnce() throws Exception { final String value = "value"; final CountingCacheEntryFactory factory = new CountingCacheEntryFactory(value); final Cache cache = manager.getCache("sampleCacheNoIdle"); final Ehcache selfPopulatingCache = new SelfPopulatingCache(cache, factory); for (int i = 0; i < 5; i++) { assertSame(value, selfPopulatingCache.get("key").getObjectValue()); assertEquals(1, factory.getCount()); } } @Test public void testCacheEntryFactoryReturningElementMake() throws Exception { final long specialVersionNumber = 54321L; final CacheEntryFactory elementReturningFactory = new CacheEntryFactory() { public Object createEntry(final Object key) throws Exception { Element e = new Element(key, "V_" + key); e.setVersion(specialVersionNumber); return e; } }; selfPopulatingCache = new SelfPopulatingCache(cache, elementReturningFactory); Element e = null; e = selfPopulatingCache.get("key1"); assertEquals("V_key1", e.getValue()); assertEquals(specialVersionNumber, e.getVersion()); e = selfPopulatingCache.get("key2"); assertEquals("V_key2", e.getValue()); assertEquals(specialVersionNumber, e.getVersion()); assertEquals(2, selfPopulatingCache.getSize()); } @Test public void testCacheEntryFactoryReturningElementBadKey() throws Exception { final CacheEntryFactory elementReturningFactory = new CacheEntryFactory() { public Object createEntry(final Object key) throws Exception { Object modifiedKey = key.toString() + "XX"; Element e = new Element(modifiedKey, "V_" + modifiedKey); return e; } }; selfPopulatingCache = new SelfPopulatingCache(cache, elementReturningFactory); try { selfPopulatingCache.get("key"); fail("Should fail because key was changed"); } catch (final Exception e) { Thread.sleep(20); assertEquals("Could not fetch object for cache entry with key \"key\".", e.getMessage()); } }
### Question: SelfPopulatingCache extends BlockingCache { public void refresh() throws CacheException { Exception exception = null; Object keyWithException = null; final Collection keys = getKeys(); if (LOG.isTraceEnabled()) { LOG.trace(getName() + ": found " + keys.size() + " keys to refresh"); } for (Iterator iterator = keys.iterator(); iterator.hasNext();) { final Object key = iterator.next(); try { Ehcache backingCache = getCache(); final Element element = backingCache.getQuiet(key); if (element == null) { if (LOG.isTraceEnabled()) { LOG.trace(getName() + ": entry with key " + key + " has been removed - skipping it"); } continue; } refreshElement(element, backingCache); } catch (final Exception e) { LOG.warn(getName() + "Could not refresh element " + key, e); exception = e; } } if (exception != null) { throw new CacheException(exception.getMessage() + " on refresh with key " + keyWithException); } } SelfPopulatingCache(final Ehcache cache, final CacheEntryFactory factory); Element get(final Object key); void refresh(); }### Answer: @Test public void testRefresh() throws Exception { final String value = "value"; final CountingCacheEntryFactory factory = new CountingCacheEntryFactory(value); selfPopulatingCache = new SelfPopulatingCache(cache, factory); assertSame(value, selfPopulatingCache.get("key").getObjectValue()); assertEquals(1, factory.getCount()); selfPopulatingCache.refresh(); assertEquals(2, factory.getCount()); assertSame(value, selfPopulatingCache.get("key").getObjectValue()); assertEquals(2, factory.getCount()); }
### Question: CacheManager { public void shutdown() { synchronized (CacheManager.class) { if (status.equals(Status.STATUS_SHUTDOWN)) { if (LOG.isDebugEnabled()) { LOG.debug("CacheManager already shutdown"); } return; } for (CacheManagerPeerProvider cacheManagerPeerProvider : cacheManagerPeerProviders.values()) { if (cacheManagerPeerProvider != null) { cacheManagerPeerProvider.dispose(); } } cacheManagerEventListenerRegistry.dispose(); synchronized (CacheManager.class) { ALL_CACHE_MANAGERS.remove(this); Collection cacheSet = ehcaches.values(); for (Iterator iterator = cacheSet.iterator(); iterator.hasNext();) { Ehcache cache = (Ehcache) iterator.next(); if (cache != null) { cache.dispose(); } } defaultCache.dispose(); status = Status.STATUS_SHUTDOWN; if (this == singleton) { singleton = null; } removeShutdownHook(); } } } CacheManager(Configuration configuration); CacheManager(String configurationFileName); CacheManager(URL configurationURL); CacheManager(InputStream configurationInputStream); CacheManager(); static CacheManager create(); static CacheManager getInstance(); static CacheManager create(String configurationFileName); static CacheManager create(URL configurationFileURL); static CacheManager create(InputStream inputStream); Cache getCache(String name); Ehcache getEhcache(String name); void addCache(String cacheName); void addCache(Cache cache); void addCache(Ehcache cache); boolean cacheExists(String cacheName); void removalAll(); void removeCache(String cacheName); void shutdown(); String[] getCacheNames(); Status getStatus(); void clearAll(); CacheManagerPeerProvider getCacheManagerPeerProvider(String scheme); CacheManagerPeerListener getCachePeerListener(String scheme); CacheManagerEventListener getCacheManagerEventListener(); void setCacheManagerEventListener(CacheManagerEventListener cacheManagerEventListener); CacheManagerEventListenerRegistry getCacheManagerEventListenerRegistry(); void replaceCacheWithDecoratedCache(Ehcache ehcache, Ehcache decoratedCache); String getName(); void setName(String name); String toString(); String getDiskStorePath(); static final List ALL_CACHE_MANAGERS; static final String ENABLE_SHUTDOWN_HOOK_PROPERTY; }### Answer: @Test public void testForCacheManagerThreadLeak() throws CacheException, InterruptedException { int startingThreadCount = countThreads(); URL secondCacheConfiguration = this.getClass().getResource("/ehcache-2.xml"); for (int i = 0; i < 100; i++) { instanceManager = new CacheManager(secondCacheConfiguration); instanceManager.shutdown(); } Thread.sleep(300); int endingThreadCount = countThreads(); assertTrue(endingThreadCount < startingThreadCount + 2); } @Test public void testMultipleCacheManagers() { CacheManager[] managers = new CacheManager[2]; managers[0] = new CacheManager(makeCacheManagerConfig()); managers[1] = new CacheManager(makeCacheManagerConfig()); managers[0].shutdown(); managers[1].shutdown(); }
### Question: CacheManager { public static CacheManager create() throws CacheException { if (singleton != null) { return singleton; } synchronized (CacheManager.class) { if (singleton == null) { if (LOG.isDebugEnabled()) { LOG.debug("Creating new CacheManager with default config"); } singleton = new CacheManager(); } else { if (LOG.isDebugEnabled()) { LOG.debug("Attempting to create an existing singleton. Existing singleton returned."); } } return singleton; } } CacheManager(Configuration configuration); CacheManager(String configurationFileName); CacheManager(URL configurationURL); CacheManager(InputStream configurationInputStream); CacheManager(); static CacheManager create(); static CacheManager getInstance(); static CacheManager create(String configurationFileName); static CacheManager create(URL configurationFileURL); static CacheManager create(InputStream inputStream); Cache getCache(String name); Ehcache getEhcache(String name); void addCache(String cacheName); void addCache(Cache cache); void addCache(Ehcache cache); boolean cacheExists(String cacheName); void removalAll(); void removeCache(String cacheName); void shutdown(); String[] getCacheNames(); Status getStatus(); void clearAll(); CacheManagerPeerProvider getCacheManagerPeerProvider(String scheme); CacheManagerPeerListener getCachePeerListener(String scheme); CacheManagerEventListener getCacheManagerEventListener(); void setCacheManagerEventListener(CacheManagerEventListener cacheManagerEventListener); CacheManagerEventListenerRegistry getCacheManagerEventListenerRegistry(); void replaceCacheWithDecoratedCache(Ehcache ehcache, Ehcache decoratedCache); String getName(); void setName(String name); String toString(); String getDiskStorePath(); static final List ALL_CACHE_MANAGERS; static final String ENABLE_SHUTDOWN_HOOK_PROPERTY; }### Answer: @Test public void testCacheManagerThreads() throws CacheException, InterruptedException { singletonManager = CacheManager.create(AbstractCacheTest.TEST_CONFIG_DIR + "ehcache-big.xml"); int threads = countThreads(); assertTrue("More than 75 threads: " + threads, countThreads() <= 75); }
### Question: Element implements Serializable, Cloneable { public final long getSerializedSize() { if (!isSerializable()) { return 0; } long size = 0; ByteArrayOutputStream bout = new ByteArrayOutputStream(); ObjectOutputStream oos = null; try { oos = new ObjectOutputStream(bout); oos.writeObject(this); size = bout.size(); return size; } catch (IOException e) { LOG.debug("Error measuring element size for element with key " + key + ". Cause was: " + e.getMessage()); } finally { try { if (oos != null) { oos.close(); } } catch (Exception e) { LOG.error("Error closing ObjectOutputStream"); } } return size; } Element(Serializable key, Serializable value, long version); Element(Object key, Object value, long version); Element(Object key, Object value, long version, long creationTime, long lastAccessTime, long nextToLastAccessTime, long lastUpdateTime, long hitCount); Element(Object key, Object value, Boolean eternal, Integer timeToIdleSeconds, Integer timeToLiveSeconds); Element(Serializable key, Serializable value); Element(Object key, Object value); final Serializable getKey(); final Object getObjectKey(); final Serializable getValue(); final Object getObjectValue(); final boolean equals(Object object); void setTimeToLive(int timeToLiveSeconds); void setTimeToIdle(int timeToIdleSeconds); final int hashCode(); final void setVersion(long version); final long getCreationTime(); final long getLatestOfCreationAndUpdateTime(); final void setCreateTime(); final long getVersion(); final long getLastAccessTime(); final long getNextToLastAccessTime(); final long getHitCount(); final void resetAccessStatistics(); final void updateAccessStatistics(); final void updateUpdateStatistics(); final String toString(); final Object clone(); final long getSerializedSize(); final boolean isSerializable(); final boolean isKeySerializable(); long getLastUpdateTime(); boolean isExpired(); long getExpirationTime(); boolean isEternal(); void setEternal(boolean eternal); boolean isLifespanSet(); int getTimeToLive(); int getTimeToIdle(); }### Answer: @Test public void testSerializationPerformanceByteArray() throws CacheException { Serializable key = "key"; ByteArrayOutputStream bout = new ByteArrayOutputStream(); for (int j = 0; j < 10000; j++) { try { bout.write("abcdefghijklmnopqrstv1234567890".getBytes()); } catch (IOException e) { LOG.error("This should not happen"); } } byte[] value = bout.toByteArray(); Element element = new Element(key, value); StopWatch stopWatch = new StopWatch(); for (int i = 0; i < 100; i++) { element.getSerializedSize(); } long elapsed = stopWatch.getElapsedTime() / 100; LOG.info("In-memory size in bytes: " + element.getSerializedSize() + " time to serialize in ms: " + elapsed); assertTrue("Large object clone takes more than than 100ms", elapsed < 100); } @Test public void testSerializationPerformanceJavaObjects() throws Exception { HashMap map = new HashMap(10000); for (int j = 0; j < 10000; j++) { map.put("key" + j, new String[]{"adfdafs", "asdfdsafa", "sdfasdf"}); } Element element = new Element("key1", map); StopWatch stopWatch = new StopWatch(); for (int i = 0; i < 100; i++) { element.getSerializedSize(); } long elapsed = stopWatch.getElapsedTime() / 100; LOG.info("In-memory size in bytes: " + element.getSerializedSize() + " time to serialize in ms: " + elapsed); assertTrue("Large object clone took more than 500ms", elapsed < 500); }
### Question: PayloadUtil { public static byte[] gzip(byte[] ungzipped) { final ByteArrayOutputStream bytes = new ByteArrayOutputStream(); try { final GZIPOutputStream gzipOutputStream = new GZIPOutputStream(bytes); gzipOutputStream.write(ungzipped); gzipOutputStream.close(); } catch (IOException e) { LOG.error("Could not gzip " + ungzipped); } return bytes.toByteArray(); } private PayloadUtil(); static byte[] assembleUrlList(List localCachePeers); static byte[] gzip(byte[] ungzipped); static byte[] ungzip(final byte[] gzipped); static final int MTU; static final String URL_DELIMITER; }### Answer: @Test public void testMaximumDatagram() throws IOException { String payload = createReferenceString(); final byte[] compressed = PayloadUtil.gzip(payload.getBytes()); int length = compressed.length; LOG.info("gzipped size: " + length); assertTrue("Heartbeat too big for one Datagram " + length, length <= 1500); } @Test public void testGzipSanityAndPerformance() throws IOException, InterruptedException { String payload = createReferenceString(); for (int i = 0; i < 10; i++) { byte[] compressed = PayloadUtil.gzip(payload.getBytes()); assertTrue(compressed.length > 300); Thread.sleep(20); } int hashCode = payload.hashCode(); StopWatch stopWatch = new StopWatch(); for (int i = 0; i < 10000; i++) { if (hashCode != payload.hashCode()) { PayloadUtil.gzip(payload.getBytes()); } } long elapsed = stopWatch.getElapsedTime(); LOG.info("Gzip took " + elapsed / 10F + " µs"); }
### Question: SelfPopulatingCache extends BlockingCache { public void refresh() throws CacheException { refresh(true); } SelfPopulatingCache(final Ehcache cache, final CacheEntryFactory factory); SelfPopulatingCache(Ehcache cache, int numberOfStripes, CacheEntryFactory factory); @Override Element get(final Object key); void refresh(); void refresh(boolean quiet); Element refresh(Object key); Element refresh(Object key, boolean quiet); }### Answer: @Test public void testRefresh() throws Exception { final String value = "value"; final CountingCacheEntryFactory factory = new CountingCacheEntryFactory(value); selfPopulatingCache = new SelfPopulatingCache(cache, factory); assertSame(value, selfPopulatingCache.get("key").getObjectValue()); assertEquals(1, factory.getCount()); selfPopulatingCache.refresh(); assertEquals(2, factory.getCount()); assertSame(value, selfPopulatingCache.get("key").getObjectValue()); assertEquals(2, factory.getCount()); }
### Question: SelfPopulatingCache extends BlockingCache { protected void refreshElement(final Element element, Ehcache backingCache) throws Exception { refreshElement(element, backingCache, true); } SelfPopulatingCache(final Ehcache cache, final CacheEntryFactory factory); SelfPopulatingCache(Ehcache cache, int numberOfStripes, CacheEntryFactory factory); @Override Element get(final Object key); void refresh(); void refresh(boolean quiet); Element refresh(Object key); Element refresh(Object key, boolean quiet); }### Answer: @Test public void testRefreshElement() throws Exception { final IncrementingCacheEntryFactory factory = new IncrementingCacheEntryFactory(); selfPopulatingCache = new SelfPopulatingCache(cache, factory); Element e1 = selfPopulatingCache.get("key1"); Element e2 = selfPopulatingCache.get("key2"); assertEquals(2, selfPopulatingCache.getSize()); assertEquals(2, factory.getCount()); assertEquals(Integer.valueOf(1), e1.getValue()); assertEquals(Integer.valueOf(2), e2.getValue()); selfPopulatingCache.refresh(); e1 = selfPopulatingCache.get("key1"); e2 = selfPopulatingCache.get("key2"); assertEquals(2, selfPopulatingCache.getSize()); assertEquals(4, factory.getCount()); int e1i = ((Integer) e1.getValue()).intValue(); int e2i = ((Integer) e2.getValue()).intValue(); assertTrue(((e1i == 3) && (e2i == 4)) || ((e1i == 4) && (e2i == 3))); selfPopulatingCache.get("key2"); Element e2r = selfPopulatingCache.refresh("key2"); assertEquals(2, selfPopulatingCache.getSize()); assertEquals(5, factory.getCount()); assertNotNull(e2r); assertEquals("key2", e2r.getKey()); assertEquals(Integer.valueOf(5), e2r.getValue()); Element e3 = selfPopulatingCache.get("key3"); assertEquals(3, selfPopulatingCache.getSize()); assertEquals(6, factory.getCount()); assertNotNull(e3); assertEquals("key3", e3.getKey()); assertEquals(Integer.valueOf(6), e3.getValue()); selfPopulatingCache.refresh(); assertEquals(3, selfPopulatingCache.getSize()); assertEquals(9, factory.getCount()); }
### Question: EhcacheWebServiceEndpoint { @WebMethod public String ping() { return "pong"; } @WebMethod String ping(); @WebMethod Cache getCache(String cacheName); @WebMethod void addCache(String cacheName); @WebMethod void removeCache(String cacheName); @WebMethod String[] cacheNames(); @WebMethod Status getStatus(String cacheName); @WebMethod void put(String cacheName, Element element); @WebMethod Element get(String cacheName, String key); @WebMethod List getKeys(String cacheName); @WebMethod boolean remove(String cacheName, String key); @WebMethod List getKeysWithExpiryCheck(String cacheName); @WebMethod List getKeysNoDuplicateCheck(String cacheName); @WebMethod Element getQuiet(String cacheName, Object key); @WebMethod void putQuiet(String cacheName, Element element); @WebMethod boolean removeQuiet(String cacheName, String key); @WebMethod void removeAll(String cacheName); @WebMethod int getSize(String cacheName); @WebMethod Statistics getStatistics(String cacheName); @WebMethod StatisticsAccuracy getStatisticsAccuracy(String cacheName); @WebMethod void clearStatistics(String cacheName); @WebMethod void load(String cacheName, String key); @WebMethod void loadAll(String cacheName, Collection<String> keys); @WebMethod HashMap getAllWithLoader(String cacheName, Collection keys); @WebMethod Element getWithLoader(String cacheName, String key); }### Answer: @Test public void testPing() { String result = cacheService.ping(); assertEquals("pong", result); }
### Question: EhcacheWebServiceEndpoint { @WebMethod public Cache getCache(String cacheName) throws CacheException { Ehcache ehcache = manager.getCache(cacheName); if (ehcache != null) { return new Cache(ehcache); } else { return null; } } @WebMethod String ping(); @WebMethod Cache getCache(String cacheName); @WebMethod void addCache(String cacheName); @WebMethod void removeCache(String cacheName); @WebMethod String[] cacheNames(); @WebMethod Status getStatus(String cacheName); @WebMethod void put(String cacheName, Element element); @WebMethod Element get(String cacheName, String key); @WebMethod List getKeys(String cacheName); @WebMethod boolean remove(String cacheName, String key); @WebMethod List getKeysWithExpiryCheck(String cacheName); @WebMethod List getKeysNoDuplicateCheck(String cacheName); @WebMethod Element getQuiet(String cacheName, Object key); @WebMethod void putQuiet(String cacheName, Element element); @WebMethod boolean removeQuiet(String cacheName, String key); @WebMethod void removeAll(String cacheName); @WebMethod int getSize(String cacheName); @WebMethod Statistics getStatistics(String cacheName); @WebMethod StatisticsAccuracy getStatisticsAccuracy(String cacheName); @WebMethod void clearStatistics(String cacheName); @WebMethod void load(String cacheName, String key); @WebMethod void loadAll(String cacheName, Collection<String> keys); @WebMethod HashMap getAllWithLoader(String cacheName, Collection keys); @WebMethod Element getWithLoader(String cacheName, String key); }### Answer: @Test public void testGetCache() throws CacheException_Exception, NoSuchCacheException_Exception { Cache cache = cacheService.getCache("doesnotexist"); assertNull(cache); cache = cacheService.getCache("sampleCache1"); assertEquals("sampleCache1", cache.getName()); assertEquals("rest/sampleCache1", cache.getUri()); assertTrue(cache.getDescription().indexOf("sampleCache1") != -1); }
### Question: EhcacheWebServiceEndpoint { @WebMethod public String[] cacheNames() throws IllegalStateException { return manager.getCacheNames(); } @WebMethod String ping(); @WebMethod Cache getCache(String cacheName); @WebMethod void addCache(String cacheName); @WebMethod void removeCache(String cacheName); @WebMethod String[] cacheNames(); @WebMethod Status getStatus(String cacheName); @WebMethod void put(String cacheName, Element element); @WebMethod Element get(String cacheName, String key); @WebMethod List getKeys(String cacheName); @WebMethod boolean remove(String cacheName, String key); @WebMethod List getKeysWithExpiryCheck(String cacheName); @WebMethod List getKeysNoDuplicateCheck(String cacheName); @WebMethod Element getQuiet(String cacheName, Object key); @WebMethod void putQuiet(String cacheName, Element element); @WebMethod boolean removeQuiet(String cacheName, String key); @WebMethod void removeAll(String cacheName); @WebMethod int getSize(String cacheName); @WebMethod Statistics getStatistics(String cacheName); @WebMethod StatisticsAccuracy getStatisticsAccuracy(String cacheName); @WebMethod void clearStatistics(String cacheName); @WebMethod void load(String cacheName, String key); @WebMethod void loadAll(String cacheName, Collection<String> keys); @WebMethod HashMap getAllWithLoader(String cacheName, Collection keys); @WebMethod Element getWithLoader(String cacheName, String key); }### Answer: @Test public void testCacheNames() throws IllegalStateException_Exception { List cacheNames = cacheService.cacheNames(); assertTrue(cacheNames.size() >= 6); }
### Question: EhcacheWebServiceEndpoint { @WebMethod public Status getStatus(String cacheName) { net.sf.ehcache.Cache cache = lookupCache(cacheName); return Status.fromCode(cache.getStatus().intValue()); } @WebMethod String ping(); @WebMethod Cache getCache(String cacheName); @WebMethod void addCache(String cacheName); @WebMethod void removeCache(String cacheName); @WebMethod String[] cacheNames(); @WebMethod Status getStatus(String cacheName); @WebMethod void put(String cacheName, Element element); @WebMethod Element get(String cacheName, String key); @WebMethod List getKeys(String cacheName); @WebMethod boolean remove(String cacheName, String key); @WebMethod List getKeysWithExpiryCheck(String cacheName); @WebMethod List getKeysNoDuplicateCheck(String cacheName); @WebMethod Element getQuiet(String cacheName, Object key); @WebMethod void putQuiet(String cacheName, Element element); @WebMethod boolean removeQuiet(String cacheName, String key); @WebMethod void removeAll(String cacheName); @WebMethod int getSize(String cacheName); @WebMethod Statistics getStatistics(String cacheName); @WebMethod StatisticsAccuracy getStatisticsAccuracy(String cacheName); @WebMethod void clearStatistics(String cacheName); @WebMethod void load(String cacheName, String key); @WebMethod void loadAll(String cacheName, Collection<String> keys); @WebMethod HashMap getAllWithLoader(String cacheName, Collection keys); @WebMethod Element getWithLoader(String cacheName, String key); }### Answer: @Test public void testCacheStatus() throws CacheException_Exception, NoSuchCacheException_Exception { Status status = cacheService.getStatus("sampleCache1"); assertTrue(status == Status.STATUS_ALIVE); }
### Question: EhcacheWebServiceEndpoint { @WebMethod public List getKeys(String cacheName) throws IllegalStateException, CacheException { net.sf.ehcache.Cache cache = lookupCache(cacheName); return cache.getKeys(); } @WebMethod String ping(); @WebMethod Cache getCache(String cacheName); @WebMethod void addCache(String cacheName); @WebMethod void removeCache(String cacheName); @WebMethod String[] cacheNames(); @WebMethod Status getStatus(String cacheName); @WebMethod void put(String cacheName, Element element); @WebMethod Element get(String cacheName, String key); @WebMethod List getKeys(String cacheName); @WebMethod boolean remove(String cacheName, String key); @WebMethod List getKeysWithExpiryCheck(String cacheName); @WebMethod List getKeysNoDuplicateCheck(String cacheName); @WebMethod Element getQuiet(String cacheName, Object key); @WebMethod void putQuiet(String cacheName, Element element); @WebMethod boolean removeQuiet(String cacheName, String key); @WebMethod void removeAll(String cacheName); @WebMethod int getSize(String cacheName); @WebMethod Statistics getStatistics(String cacheName); @WebMethod StatisticsAccuracy getStatisticsAccuracy(String cacheName); @WebMethod void clearStatistics(String cacheName); @WebMethod void load(String cacheName, String key); @WebMethod void loadAll(String cacheName, Collection<String> keys); @WebMethod HashMap getAllWithLoader(String cacheName, Collection keys); @WebMethod Element getWithLoader(String cacheName, String key); }### Answer: @Test public void testGetKeys() throws NoSuchCacheException_Exception, CacheException_Exception, IllegalStateException_Exception { for (int i = 0; i < 1000; i++) { Element element = new Element(); element.setKey(i); element.setValue(("value" + i).getBytes()); cacheService.put("sampleCache1", element); } List keys = cacheService.getKeys("sampleCache1"); assertEquals(1000, keys.size()); keys = cacheService.getKeysWithExpiryCheck("sampleCache1"); assertEquals(1000, keys.size()); keys = cacheService.getKeysNoDuplicateCheck("sampleCache1"); assertEquals(1000, keys.size()); }
### Question: EhcacheWebServiceEndpoint { @WebMethod public boolean remove(String cacheName, String key) throws CacheException { net.sf.ehcache.Cache cache = lookupCache(cacheName); return cache.remove(key); } @WebMethod String ping(); @WebMethod Cache getCache(String cacheName); @WebMethod void addCache(String cacheName); @WebMethod void removeCache(String cacheName); @WebMethod String[] cacheNames(); @WebMethod Status getStatus(String cacheName); @WebMethod void put(String cacheName, Element element); @WebMethod Element get(String cacheName, String key); @WebMethod List getKeys(String cacheName); @WebMethod boolean remove(String cacheName, String key); @WebMethod List getKeysWithExpiryCheck(String cacheName); @WebMethod List getKeysNoDuplicateCheck(String cacheName); @WebMethod Element getQuiet(String cacheName, Object key); @WebMethod void putQuiet(String cacheName, Element element); @WebMethod boolean removeQuiet(String cacheName, String key); @WebMethod void removeAll(String cacheName); @WebMethod int getSize(String cacheName); @WebMethod Statistics getStatistics(String cacheName); @WebMethod StatisticsAccuracy getStatisticsAccuracy(String cacheName); @WebMethod void clearStatistics(String cacheName); @WebMethod void load(String cacheName, String key); @WebMethod void loadAll(String cacheName, Collection<String> keys); @WebMethod HashMap getAllWithLoader(String cacheName, Collection keys); @WebMethod Element getWithLoader(String cacheName, String key); }### Answer: @Test public void testRemove() throws NoSuchCacheException_Exception, CacheException_Exception, IllegalStateException_Exception { putElementIntoCache(); assertEquals(1, cacheService.getSize("sampleCache1")); }
### Question: EhcacheWebServiceEndpoint { @WebMethod public StatisticsAccuracy getStatisticsAccuracy(String cacheName) { net.sf.ehcache.Cache cache = lookupCache(cacheName); return StatisticsAccuracy.fromCode(cache.getStatisticsAccuracy()); } @WebMethod String ping(); @WebMethod Cache getCache(String cacheName); @WebMethod void addCache(String cacheName); @WebMethod void removeCache(String cacheName); @WebMethod String[] cacheNames(); @WebMethod Status getStatus(String cacheName); @WebMethod void put(String cacheName, Element element); @WebMethod Element get(String cacheName, String key); @WebMethod List getKeys(String cacheName); @WebMethod boolean remove(String cacheName, String key); @WebMethod List getKeysWithExpiryCheck(String cacheName); @WebMethod List getKeysNoDuplicateCheck(String cacheName); @WebMethod Element getQuiet(String cacheName, Object key); @WebMethod void putQuiet(String cacheName, Element element); @WebMethod boolean removeQuiet(String cacheName, String key); @WebMethod void removeAll(String cacheName); @WebMethod int getSize(String cacheName); @WebMethod Statistics getStatistics(String cacheName); @WebMethod StatisticsAccuracy getStatisticsAccuracy(String cacheName); @WebMethod void clearStatistics(String cacheName); @WebMethod void load(String cacheName, String key); @WebMethod void loadAll(String cacheName, Collection<String> keys); @WebMethod HashMap getAllWithLoader(String cacheName, Collection keys); @WebMethod Element getWithLoader(String cacheName, String key); }### Answer: @Test public void testGetStatisticsAccuracy() throws NoSuchCacheException_Exception, CacheException_Exception, IllegalStateException_Exception { assertEquals(StatisticsAccuracy.STATISTICS_ACCURACY_BEST_EFFORT, cacheService.getStatisticsAccuracy("sampleCache1")); }
### Question: EhcacheWebServiceEndpoint { @WebMethod public void load(String cacheName, String key) throws CacheException { net.sf.ehcache.Cache cache = lookupCache(cacheName); cache.load(key); } @WebMethod String ping(); @WebMethod Cache getCache(String cacheName); @WebMethod void addCache(String cacheName); @WebMethod void removeCache(String cacheName); @WebMethod String[] cacheNames(); @WebMethod Status getStatus(String cacheName); @WebMethod void put(String cacheName, Element element); @WebMethod Element get(String cacheName, String key); @WebMethod List getKeys(String cacheName); @WebMethod boolean remove(String cacheName, String key); @WebMethod List getKeysWithExpiryCheck(String cacheName); @WebMethod List getKeysNoDuplicateCheck(String cacheName); @WebMethod Element getQuiet(String cacheName, Object key); @WebMethod void putQuiet(String cacheName, Element element); @WebMethod boolean removeQuiet(String cacheName, String key); @WebMethod void removeAll(String cacheName); @WebMethod int getSize(String cacheName); @WebMethod Statistics getStatistics(String cacheName); @WebMethod StatisticsAccuracy getStatisticsAccuracy(String cacheName); @WebMethod void clearStatistics(String cacheName); @WebMethod void load(String cacheName, String key); @WebMethod void loadAll(String cacheName, Collection<String> keys); @WebMethod HashMap getAllWithLoader(String cacheName, Collection keys); @WebMethod Element getWithLoader(String cacheName, String key); }### Answer: @Test public void testLoad() throws NoSuchCacheException_Exception, CacheException_Exception, IllegalStateException_Exception { cacheService.load("sampleCache1", "2"); }
### Question: EhcacheWebServiceEndpoint { @WebMethod public void loadAll(String cacheName, Collection<String> keys) throws CacheException { net.sf.ehcache.Cache cache = lookupCache(cacheName); cache.loadAll(keys, null); } @WebMethod String ping(); @WebMethod Cache getCache(String cacheName); @WebMethod void addCache(String cacheName); @WebMethod void removeCache(String cacheName); @WebMethod String[] cacheNames(); @WebMethod Status getStatus(String cacheName); @WebMethod void put(String cacheName, Element element); @WebMethod Element get(String cacheName, String key); @WebMethod List getKeys(String cacheName); @WebMethod boolean remove(String cacheName, String key); @WebMethod List getKeysWithExpiryCheck(String cacheName); @WebMethod List getKeysNoDuplicateCheck(String cacheName); @WebMethod Element getQuiet(String cacheName, Object key); @WebMethod void putQuiet(String cacheName, Element element); @WebMethod boolean removeQuiet(String cacheName, String key); @WebMethod void removeAll(String cacheName); @WebMethod int getSize(String cacheName); @WebMethod Statistics getStatistics(String cacheName); @WebMethod StatisticsAccuracy getStatisticsAccuracy(String cacheName); @WebMethod void clearStatistics(String cacheName); @WebMethod void load(String cacheName, String key); @WebMethod void loadAll(String cacheName, Collection<String> keys); @WebMethod HashMap getAllWithLoader(String cacheName, Collection keys); @WebMethod Element getWithLoader(String cacheName, String key); }### Answer: @Test public void testLoadAll() throws NoSuchCacheException_Exception, CacheException_Exception, IllegalStateException_Exception { List keys = new ArrayList(); for (int i = 0; i < 5; i++) { keys.add("" + i); } cacheService.loadAll("sampleCache1", keys); }
### Question: EhcacheWebServiceEndpoint { @WebMethod public Element getWithLoader(String cacheName, String key) { net.sf.ehcache.Cache cache = lookupCache(cacheName); net.sf.ehcache.Element element = cache.getWithLoader(key, null, null); if (element != null) { return new Element(element); } else { return null; } } @WebMethod String ping(); @WebMethod Cache getCache(String cacheName); @WebMethod void addCache(String cacheName); @WebMethod void removeCache(String cacheName); @WebMethod String[] cacheNames(); @WebMethod Status getStatus(String cacheName); @WebMethod void put(String cacheName, Element element); @WebMethod Element get(String cacheName, String key); @WebMethod List getKeys(String cacheName); @WebMethod boolean remove(String cacheName, String key); @WebMethod List getKeysWithExpiryCheck(String cacheName); @WebMethod List getKeysNoDuplicateCheck(String cacheName); @WebMethod Element getQuiet(String cacheName, Object key); @WebMethod void putQuiet(String cacheName, Element element); @WebMethod boolean removeQuiet(String cacheName, String key); @WebMethod void removeAll(String cacheName); @WebMethod int getSize(String cacheName); @WebMethod Statistics getStatistics(String cacheName); @WebMethod StatisticsAccuracy getStatisticsAccuracy(String cacheName); @WebMethod void clearStatistics(String cacheName); @WebMethod void load(String cacheName, String key); @WebMethod void loadAll(String cacheName, Collection<String> keys); @WebMethod HashMap getAllWithLoader(String cacheName, Collection keys); @WebMethod Element getWithLoader(String cacheName, String key); }### Answer: @Test public void testGetWithLoad() throws NoSuchCacheException_Exception, CacheException_Exception, IllegalStateException_Exception { cacheService.getWithLoader("sampleCache1", "2"); }
### Question: EhcacheWebServiceEndpoint { @WebMethod public HashMap getAllWithLoader(String cacheName, Collection keys) throws CacheException { net.sf.ehcache.Cache cache = lookupCache(cacheName); return (HashMap) cache.getAllWithLoader(keys, null); } @WebMethod String ping(); @WebMethod Cache getCache(String cacheName); @WebMethod void addCache(String cacheName); @WebMethod void removeCache(String cacheName); @WebMethod String[] cacheNames(); @WebMethod Status getStatus(String cacheName); @WebMethod void put(String cacheName, Element element); @WebMethod Element get(String cacheName, String key); @WebMethod List getKeys(String cacheName); @WebMethod boolean remove(String cacheName, String key); @WebMethod List getKeysWithExpiryCheck(String cacheName); @WebMethod List getKeysNoDuplicateCheck(String cacheName); @WebMethod Element getQuiet(String cacheName, Object key); @WebMethod void putQuiet(String cacheName, Element element); @WebMethod boolean removeQuiet(String cacheName, String key); @WebMethod void removeAll(String cacheName); @WebMethod int getSize(String cacheName); @WebMethod Statistics getStatistics(String cacheName); @WebMethod StatisticsAccuracy getStatisticsAccuracy(String cacheName); @WebMethod void clearStatistics(String cacheName); @WebMethod void load(String cacheName, String key); @WebMethod void loadAll(String cacheName, Collection<String> keys); @WebMethod HashMap getAllWithLoader(String cacheName, Collection keys); @WebMethod Element getWithLoader(String cacheName, String key); }### Answer: @Test public void testGetAllWithLoader() throws NoSuchCacheException_Exception, CacheException_Exception, IllegalStateException_Exception { List keys = new ArrayList(); for (int i = 0; i < 5; i++) { keys.add("" + i); } cacheService.getAllWithLoader("sampleCache1", keys); }
### Question: ExplicitLockingCache implements Ehcache { public boolean putIfAbsent(Element element) { try { acquireWriteLockOnKey(element.getKey()); if (!isKeyInCache(element.getKey())) { this.put(element); return true; } return false; } finally { releaseWriteLockOnKey(element.getKey()); } } ExplicitLockingCache(Ehcache cache); String getName(); void setName(String name); boolean isExpired(Element element); @Override Object clone(); RegisteredEventListeners getCacheEventNotificationService(); boolean isElementInMemory(Serializable key); boolean isElementInMemory(Object key); boolean isElementOnDisk(Serializable key); boolean isElementOnDisk(Object key); String getGuid(); CacheManager getCacheManager(); void clearStatistics(); int getStatisticsAccuracy(); void setStatisticsAccuracy(int statisticsAccuracy); void evictExpiredElements(); boolean isKeyInCache(Object key); boolean isValueInCache(Object value); Statistics getStatistics(); LiveCacheStatistics getLiveCacheStatistics(); void setCacheManager(CacheManager cacheManager); BootstrapCacheLoader getBootstrapCacheLoader(); void setBootstrapCacheLoader(BootstrapCacheLoader bootstrapCacheLoader); void setDiskStorePath(String diskStorePath); void initialise(); void bootstrap(); void dispose(); CacheConfiguration getCacheConfiguration(); Element get(final Object key); void put(Element element); void put(Element element, boolean doNotNotifyCacheReplicators); void putQuiet(Element element); Element get(Serializable key); Element getQuiet(Serializable key); Element getQuiet(Object key); List getKeys(); List getKeysWithExpiryCheck(); List getKeysNoDuplicateCheck(); boolean remove(Serializable key); boolean remove(Object key); boolean remove(Serializable key, boolean doNotNotifyCacheReplicators); boolean remove(Object key, boolean doNotNotifyCacheReplicators); boolean removeQuiet(Serializable key); boolean removeQuiet(Object key); void removeAll(); void removeAll(boolean doNotNotifyCacheReplicators); void flush(); int getSize(); int getSizeBasedOnAccuracy(int statisticsAccuracy); long calculateInMemorySize(); long getMemoryStoreSize(); int getDiskStoreSize(); Status getStatus(); synchronized String liveness(); void registerCacheExtension(CacheExtension cacheExtension); void unregisterCacheExtension(CacheExtension cacheExtension); List<CacheExtension> getRegisteredCacheExtensions(); float getAverageGetTime(); void setCacheExceptionHandler(CacheExceptionHandler cacheExceptionHandler); CacheExceptionHandler getCacheExceptionHandler(); void registerCacheLoader(CacheLoader cacheLoader); void unregisterCacheLoader(CacheLoader cacheLoader); List<CacheLoader> getRegisteredCacheLoaders(); Element getWithLoader(Object key, CacheLoader loader, Object loaderArgument); Map getAllWithLoader(Collection keys, Object loaderArgument); void load(Object key); void loadAll(Collection keys, Object argument); boolean isDisabled(); void setDisabled(boolean disabled); void registerCacheUsageListener(CacheUsageListener cacheUsageListener); void removeCacheUsageListener(CacheUsageListener cacheUsageListener); boolean isStatisticsEnabled(); void setStatisticsEnabled(boolean enabledStatistics); SampledCacheStatistics getSampledCacheStatistics(); void setSampledStatisticsEnabled(boolean enabledStatistics); boolean isSampledStatisticsEnabled(); Object getInternalContext(); void acquireReadLockOnKey(Object key); void acquireWriteLockOnKey(Object key); void releaseReadLockOnKey(Object key); void releaseWriteLockOnKey(Object key); boolean tryReadLockOnKey(Object key, long timeout); boolean tryWriteLockOnKey(Object key, long timeout); boolean putIfAbsent(Element element); void disableDynamicFeatures(); void putWithWriter(Element element); boolean removeWithWriter(Object key); void registerCacheWriter(CacheWriter cacheWriter); void unregisterCacheWriter(); CacheWriter getRegisteredCacheWriter(); CacheWriterManager getWriterManager(); boolean isNodeCoherent(); boolean isClusterCoherent(); void setNodeCoherent(boolean coherent); void waitUntilClusterCoherent(); void setTransactionManagerLookup( TransactionManagerLookup transactionManagerLookup); }### Answer: @Test public void testPutIfAbsent() { assertEquals(testCache.get("putIfAbsent"), null); testCache.putIfAbsent(new Element("putIfAbsent", "1")); assertEquals(testCache.get("putIfAbsent").getValue(), "1"); testCache.putIfAbsent(new Element("putIfAbsent", "2")); assertEquals(testCache.get("putIfAbsent").getValue(), "1"); }