method2testcases
stringlengths
118
3.08k
### Question: EhcacheWebServiceEndpoint { @WebMethod public void clearStatistics(String cacheName) { net.sf.ehcache.Cache cache = lookupCache(cacheName); cache.clearStatistics(); } @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 testClearStatistics() throws NoSuchCacheException_Exception, CacheException_Exception, IllegalStateException_Exception { putElementIntoCache(); getElementFromCache(); cacheService.clearStatistics("sampleCache1"); Statistics statistics = cacheService.getStatistics("sampleCache1"); assertEquals(0L, statistics.getCacheHits()); } @Test public void testClearStatistics() throws Exception { putElementIntoCache(); getElementFromCache(); cacheService.clearStatistics("sampleCache1"); Statistics statistics = cacheService.getStatistics("sampleCache1"); assertEquals(0L, statistics.getCacheHits()); }
### Question: EhcacheWebServiceEndpoint { @WebMethod public Element getWithLoader(String cacheName, String key) throws NoSuchCacheException { 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: CacheManager { public static CacheManager create() throws CacheException { if (singleton != null) { return singleton; } synchronized (CacheManager.class) { if (singleton == null) { if (LOG.isLoggable(Level.FINE)) { LOG.log(Level.FINE, "Creating new CacheManager with default config"); } singleton = new CacheManager(); } else { if (LOG.isLoggable(Level.FINE)) { LOG.log(Level.FINE, "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: 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(); 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 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(); 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 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: 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(); final String toString(); float getAverageGetTime(); long getEvictionCount(); 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()); }
### Question: Element implements Serializable, Cloneable { public final boolean isSerializable() { return isKeySerializable() && (value instanceof Serializable || value == null); } 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 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 { public final boolean equals(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(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 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: 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.log(Level.SEVERE, "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.log(Level.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.log(Level.INFO, "Gzip took " + elapsed / 10F + " µs"); }
### Question: JCacheEntry implements CacheEntry { public boolean isValid() { if (element != null) { return !element.isExpired(); } else { return false; } } JCacheEntry(Element element); Object getKey(); Object getValue(); Object setValue(Object value); long getCost(); long getCreationTime(); long getExpirationTime(); int getHits(); long getLastAccessTime(); long getLastUpdateTime(); long getVersion(); boolean isValid(); }### Answer: @Test public void testIsValid() throws Exception { Cache cache = getTestCache(); CacheEntry entry = new JCacheEntry(new Element("key1", "value1")); assertEquals(true, entry.isValid()); cache.put(entry.getKey(), entry.getValue()); CacheEntry retrievedEntry = cache.getCacheEntry(entry.getKey()); assertEquals(true, retrievedEntry.isValid()); Thread.sleep(1020); assertEquals(false, retrievedEntry.isValid()); } @Test public void testIsValid() throws Exception { Cache cache = getTestCache(); CacheEntry entry = new JCacheEntry(new Element("key1", "value1")); assertEquals(true, entry.isValid()); cache.put(entry.getKey(), entry.getValue()); CacheEntry retrievedEntry = cache.getCacheEntry(entry.getKey()); assertEquals(true, retrievedEntry.isValid()); Thread.sleep(1999); assertEquals(false, retrievedEntry.isValid()); }
### 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(); 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(String scheme); String getOriginalConfigurationText(); String getActiveConfigurationText(); String getOriginalConfigurationText(String cacheName); String getActiveConfigurationText(String cacheName); 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: JCacheStatistics implements CacheStatistics, Serializable { public void clearStatistics() { statistics.clearStatistics(); } JCacheStatistics(Statistics statistics); int getStatisticsAccuracy(); void clearStatistics(); int getCacheHits(); int getCacheMisses(); int getObjectCount(); float getAverageGetTime(); long getEvictionCount(); }### Answer: @Test public void testClearStatistics() throws InterruptedException { Ehcache ehcache = new net.sf.ehcache.Cache("test", 1, true, false, 5, 2); manager.addCache(ehcache); ehcache.setStatisticsEnabled(true); Cache cache = new JCache(ehcache, null); cache.put("key1", "value1"); cache.put("key2", "value1"); cache.get("key1"); CacheStatistics statistics = cache.getCacheStatistics(); assertEquals(1, statistics.getCacheHits()); assertEquals(0, statistics.getCacheMisses()); statistics.clearStatistics(); statistics = cache.getCacheStatistics(); assertEquals(0, statistics.getCacheHits()); assertEquals(0, statistics.getCacheMisses()); } @Test public void testClearStatistics() throws InterruptedException { Ehcache ehcache = new net.sf.ehcache.Cache("test", 1, true, false, 5, 2); manager.addCache(ehcache); Cache cache = new JCache(ehcache, null); cache.put("key1", "value1"); cache.put("key2", "value1"); cache.get("key1"); CacheStatistics statistics = cache.getCacheStatistics(); assertEquals(1, statistics.getCacheHits()); assertEquals(0, statistics.getCacheMisses()); statistics.clearStatistics(); statistics = cache.getCacheStatistics(); assertEquals(0, statistics.getCacheHits()); assertEquals(0, statistics.getCacheMisses()); }
### Question: SelfPopulatingCache extends BlockingCache { public void refresh() throws CacheException { Exception exception = null; Object keyWithException = null; final Collection keys = getKeys(); if (LOG.isLoggable(Level.FINEST)) { LOG.finest(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.isLoggable(Level.FINEST)) { LOG.finest(getName() + ": entry with key " + key + " has been removed - skipping it"); } continue; } refreshElement(element, backingCache); } catch (final Exception e) { LOG.log(Level.WARNING, 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: GroupElement extends Element { public Set getMemberKeys() { return (Set) getObjectValue(); } GroupElement(Object key); GroupElement(Object key, Object value, long version, long creationTime, long lastAccessTime, long nextToLastAccessTime, long lastUpdateTime, long hitCount); Set getMemberKeys(); static final String MASTER_GROUP_KEY; }### Answer: @Test public void testConstructor() { GroupElement element = new GroupElement("key"); assertEquals("key", element.getKey()); assertNotNull(element.getObjectValue()); assertTrue(element.getObjectValue() instanceof Set); assertEquals(0, ((Set) element.getValue()).size()); assertNotNull(element.getMemberKeys()); assertEquals(0, element.getMemberKeys().size()); assertEquals(0L, element.getVersion()); long now = System.currentTimeMillis(); long MARGIN = 2000L; assertTrue(element.getCreationTime()-now<MARGIN); assertEquals(0L, element.getLastAccessTime()); assertEquals(0L, element.getNextToLastAccessTime()); assertEquals(0L, element.getLastUpdateTime()); assertEquals(0L, element.getHitCount()); }
### Question: CacheManager { public static CacheManager create() throws CacheException { if (singleton != null) { return singleton; } synchronized (CacheManager.class) { if (singleton == null) { if (LOG.isLoggable(Level.FINE)) { LOG.fine("Creating new CacheManager with default config"); } singleton = new CacheManager(); } else { if (LOG.isLoggable(Level.FINE)) { LOG.fine("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: 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.severe("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: ElementResource { @DELETE public void deleteElement() throws NotFoundException { LOG.log(Level.FINE, "DELETE element {0}", element); net.sf.ehcache.Cache ehcache = lookupCache(); if (element.equals("*")) { ehcache.removeAll(); } else { boolean removed = ehcache.remove(element); if (!removed) { throw new NotFoundException("Element " + element + " not found"); } } } ElementResource(UriInfo uriInfo, Request request, String cache, String element); @HEAD Response getElementHeader(); @GET Response getElement(); @PUT Response putElement(@Context HttpHeaders headers, byte[] data); @DELETE void deleteElement(); }### Answer: @Test public void testDeleteElement() throws Exception { long beforeCreated = System.currentTimeMillis(); Thread.sleep(10); String originalString = "The rain in Spain falls mainly on the plain"; ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(originalString.getBytes()); int status = HttpUtil.put("http: assertEquals(201, status); HttpURLConnection urlConnection = HttpUtil.get("http: assertEquals(200, urlConnection.getResponseCode()); urlConnection = HttpUtil.delete("http: assertEquals(404, HttpUtil.get("http: }
### Question: ElementResource { @GET public Response getElement() throws NotFoundException { LOG.log(Level.FINE, "GET element {}", element); net.sf.ehcache.Cache ehcache = lookupCache(); net.sf.ehcache.Element ehcacheElement = lookupElement(ehcache); Element localElement = new Element(ehcacheElement, uriInfo.getAbsolutePath().toString()); Date lastModifiedDate = createLastModified(ehcacheElement); EntityTag entityTag = createETag(ehcacheElement); Response.ResponseBuilder responseBuilder = request.evaluatePreconditions(lastModifiedDate, entityTag); if (responseBuilder != null) { return responseBuilder.build(); } else { return Response.ok(localElement.getValue(), localElement.getMimeType()) .lastModified(lastModifiedDate) .tag(entityTag) .header("Expires", (new Date(localElement.getExpirationDate())).toString()) .build(); } } ElementResource(UriInfo uriInfo, Request request, String cache, String element); @HEAD Response getElementHeader(); @GET Response getElement(); @PUT Response putElement(@Context HttpHeaders headers, byte[] data); @DELETE void deleteElement(); }### Answer: @Test public void testGetElement() throws Exception { HttpURLConnection result = HttpUtil.get("http: assertEquals(200, result.getResponseCode()); assertEquals("application/xml", result.getContentType()); JAXBContext jaxbContext = new JAXBContextResolver().getContext(Caches.class); Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); Cache cache = (Cache) unmarshaller.unmarshal(result.getInputStream()); assertEquals("sampleCache1", cache.getName()); assertEquals("http: assertNotNull("http: }
### Question: CacheResource { @GET public Cache getCache() { LOG.log(Level.FINE, "GET Cache {}" + cache); net.sf.ehcache.Cache ehcache = MANAGER.getCache(cache); if (ehcache == null) { throw new NotFoundException("Cache not found"); } String cacheAsString = ehcache.toString(); cacheAsString = cacheAsString.substring(0, cacheAsString.length() - 1); cacheAsString = cacheAsString + "size = " + ehcache.getSize() + " ]"; return new Cache(ehcache.getName(), uriInfo.getAbsolutePath().toString(), cacheAsString, new Statistics(ehcache.getStatistics()), ehcache.getCacheConfiguration()); } CacheResource(UriInfo uriInfo, Request request, String cache); @HEAD Response getCacheHeader(); @GET Cache getCache(); @PUT Response putCache(); @DELETE Response deleteCache(); @Path(value = "{element}") ElementResource getElementResource(@PathParam("element")String element); }### Answer: @Test public void testGetCache() throws Exception { HttpURLConnection result = HttpUtil.get("http: assertEquals(200, result.getResponseCode()); assertEquals("application/xml", result.getContentType()); JAXBContext jaxbContext = new JAXBContextResolver().getContext(Caches.class); Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); Cache cache = (Cache) unmarshaller.unmarshal(result.getInputStream()); assertEquals("sampleCache1", cache.getName()); assertEquals("http: assertNotNull("http: }
### Question: CacheResource { @DELETE public Response deleteCache() { LOG.log(Level.FINE, "DELETE Cache {}" + cache); net.sf.ehcache.Cache ehcache = MANAGER.getCache(cache); Response response; if (ehcache == null) { throw new NotFoundException("Cache not found " + cache); } else { CacheManager.getInstance().removeCache(cache); response = Response.ok().build(); } return response; } CacheResource(UriInfo uriInfo, Request request, String cache); @HEAD Response getCacheHeader(); @GET Cache getCache(); @PUT Response putCache(); @DELETE Response deleteCache(); @Path(value = "{element}") ElementResource getElementResource(@PathParam("element")String element); }### Answer: @Test public void testDeleteCache() throws Exception { HttpURLConnection urlConnection = HttpUtil.put("http: urlConnection = HttpUtil.delete("http: assertEquals(200, urlConnection.getResponseCode()); if (urlConnection.getHeaderField("Server").matches("(.*)Glassfish(.*)")) { assertTrue(urlConnection.getContentType().matches("text/plain(.*)")); } String responseBody = HttpUtil.inputStreamToText(urlConnection.getInputStream()); assertEquals("", responseBody); urlConnection = HttpUtil.delete("http: assertEquals(404, urlConnection.getResponseCode()); assertTrue(urlConnection.getContentType().matches("text/plain(.*)")); try { responseBody = HttpUtil.inputStreamToText(urlConnection.getInputStream()); } catch (IOException e) { } }
### Question: HttpDateFormatter { public synchronized Date parseDateFromHttpDate(String date) { try { return httpDateFormat.parse(date); } catch (ParseException e) { LOG.log(Level.FINE, "ParseException on date {0}. 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: AsyncWriteBehind implements WriteBehind { public void delete(CacheEntry entry) { readLock.lock(); try { status.checkRunning(); async.add(new DeleteAsyncOperation(createKeySnapshot(entry.getKey()), createElementSnapshot(entry.getElement()))); } finally { readLock.unlock(); } } AsyncWriteBehind(AsyncCoordinator async, Ehcache cache, DsoSerializationStrategy serializationStrategy); void start(CacheWriter writer); void write(Element element); void delete(CacheEntry entry); void setOperationsFilter(final OperationsFilter filter); void stop(); long getQueueSize(); }### Answer: @Test(expected = IllegalStateException.class) public void testDeleteThrowsWhenNotStarted() { AsyncWriteBehind writeBehind = createAsyncWriteBehind(); writeBehind.delete(new CacheEntry("", new Element("", ""))); }
### Question: AsyncWriteBehind implements WriteBehind { public void write(Element element) { readLock.lock(); try { status.checkRunning(); ElementSnapshot snapshot = createElementSnapshot(element); async.add(new WriteAsyncOperation(snapshot)); } finally { readLock.unlock(); } } AsyncWriteBehind(AsyncCoordinator async, Ehcache cache, DsoSerializationStrategy serializationStrategy); void start(CacheWriter writer); void write(Element element); void delete(CacheEntry entry); void setOperationsFilter(final OperationsFilter filter); void stop(); long getQueueSize(); }### Answer: @Test(expected = IllegalStateException.class) public void testWriteThrowsWhenNotStarted() { AsyncWriteBehind writeBehind = createAsyncWriteBehind(); writeBehind.write(new Element("", "")); }
### Question: CopyStrategyHandler { boolean isCopyActive() { return copyOnRead || copyOnWrite; } CopyStrategyHandler(boolean copyOnRead, boolean copyOnWrite, ReadWriteCopyStrategy<Element> copyStrategy); Element copyElementForReadIfNeeded(Element element); }### Answer: @Test public void given_no_copy_when_isCopyActive_then_false() { CopyStrategyHandler copyStrategyHandler = new CopyStrategyHandler(false, false, null); assertThat(copyStrategyHandler.isCopyActive(), is(false)); } @Test public void given_copy_on_read_when_isCopyActive_then_false() { CopyStrategyHandler copyStrategyHandler = new CopyStrategyHandler(true, false, copyStrategy); assertThat(copyStrategyHandler.isCopyActive(), is(true)); } @Test public void given_copy_on_write_when_isCopyActive_then_false() { CopyStrategyHandler copyStrategyHandler = new CopyStrategyHandler(true, false, copyStrategy); assertThat(copyStrategyHandler.isCopyActive(), is(true)); } @Test public void given_copy_on_read_and_write_when_isCopyActive_then_false() { CopyStrategyHandler copyStrategyHandler = new CopyStrategyHandler(true, false, copyStrategy); assertThat(copyStrategyHandler.isCopyActive(), is(true)); }
### Question: MValue implements ModelElement<T> { public T asJavaObject() { return javaObject; } MValue(Token tok, String typeName, Message errMessage, String value); T asJavaObject(); T asEhcacheObject(); @Override String toString(); String getTypeName(); String getValue(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer: @Test public void testEnumValue() throws CustomParseException { MEnum<Foo> enumVal = new MValue.MEnum<Foo>(null, Foo.class.getName(), "Bar"); Enum<Foo> obj = enumVal.asJavaObject(); Assert.assertEquals(Foo.Bar, obj); try { new MValue.MEnum<Foo>(null, Foo.class.getName(), "Barr"); Assert.fail(); } catch (Exception e) { } }
### Question: QueryManagerBuilder { public static QueryManagerBuilder newQueryManagerBuilder() { return new QueryManagerBuilder(); } private QueryManagerBuilder(); QueryManagerBuilder(Class<? extends QueryManager> implementationClass); static QueryManagerBuilder newQueryManagerBuilder(); QueryManagerBuilder addCache(Ehcache cache); QueryManagerBuilder addAllCachesCurrentlyIn(CacheManager cacheManager); QueryManager build(); }### Answer: @Test public void testDefaultsToProperDefaultClass() { try { newQueryManagerBuilder(); } catch (CacheException e) { Assert.assertTrue(e.getCause().getClass() == ClassNotFoundException.class); } }
### 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 " + Arrays.toString(ungzipped)); } return bytes.toByteArray(); } private PayloadUtil(); static List<byte[]> createCompressedPayloadList(final List<CachePeer> localCachePeers, final int maximumPeersPerSend); 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); }
### Question: EventMessage implements Serializable { public final Serializable getSerializableKey() { return key; } EventMessage(Ehcache cache, Serializable key); final Ehcache getEhcache(); final Serializable getSerializableKey(); }### Answer: @Test public void testSerialization() throws IOException, ClassNotFoundException { RmiEventMessage eventMessage = new RmiEventMessage(null, RmiEventType.PUT, "key", new Element("key", "element")); ByteArrayOutputStream bout = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(bout); oos.writeObject(eventMessage); byte[] serializedValue = bout.toByteArray(); oos.close(); RmiEventMessage eventMessage2 = null; ByteArrayInputStream bin = new ByteArrayInputStream(serializedValue); ObjectInputStream ois = new ObjectInputStream(bin); eventMessage2 = (RmiEventMessage) ois.readObject(); ois.close(); assertEquals("key", eventMessage2.getSerializableKey()); assertEquals("element", eventMessage2.getElement().getObjectValue()); assertEquals(RmiEventType.PUT, eventMessage2.getType()); }
### Question: RegisteredEventListeners { public final boolean registerListener(CacheEventListener cacheEventListener) { return registerListener(cacheEventListener, NotificationScope.ALL); } RegisteredEventListeners(Cache cache); RegisteredEventListeners(Ehcache cache, CacheStoreHelper helper); final void notifyElementUpdatedOrdered(Element oldElement, Element newElement); final void notifyElementRemovedOrdered(Element element); final void notifyElementPutOrdered(Element element); final void notifyElementRemoved(Element element, boolean remoteEvent); final void notifyElementRemoved(ElementCreationCallback callback, boolean remoteEvent); final void notifyElementPut(Element element, boolean remoteEvent); final void notifyElementPut(ElementCreationCallback callback, boolean remoteEvent); final void notifyElementUpdated(Element element, boolean remoteEvent); final void notifyElementUpdated(ElementCreationCallback callback, boolean remoteEvent); final void notifyElementExpiry(Element element, boolean remoteEvent); final void notifyElementExpiry(ElementCreationCallback callback, boolean remoteEvent); final boolean hasCacheEventListeners(); final void notifyElementEvicted(Element element, boolean remoteEvent); final void notifyElementEvicted(ElementCreationCallback callback, boolean remoteEvent); final void notifyRemoveAll(boolean remoteEvent); final boolean registerListener(CacheEventListener cacheEventListener); final boolean registerListener(CacheEventListener cacheEventListener, NotificationScope scope); final boolean unregisterListener(CacheEventListener cacheEventListener); final boolean hasCacheReplicators(); final Set<CacheEventListener> getCacheEventListeners(); final void dispose(); @Override final String toString(); }### Answer: @Test public void testNotifyTerracottaStoreOfListenerChangeOnRegister() throws Exception { TerracottaStore store = mock(TerracottaStore.class); RegisteredEventListeners registeredEventListeners = createRegisteredEventListeners(store); CacheEventListener listener = mock(CacheEventListener.class); registeredEventListeners.registerListener(listener); verify(store).notifyCacheEventListenersChanged(); }
### Question: MValue implements ModelElement<T> { public T asEhcacheObject(ClassLoader loader) { return javaObject; } MValue(Token tok, String typeName, Message errMessage, String value); T asEhcacheObject(ClassLoader loader); @Override String toString(); String getTypeName(); String getValue(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer: @Test public void testEnumValue() throws CustomParseException { MEnum<Foo> enumVal = new MValue.MEnum<Foo>(null, Foo.class.getName(), "Bar"); Enum<Foo> obj = enumVal.asEhcacheObject(getClass().getClassLoader()); Assert.assertEquals(Foo.Bar, obj); try { MEnum<Foo> mEnum = new MValue.MEnum<Foo>(null, Foo.class.getName(), "Barr"); mEnum.asEhcacheObject(getClass().getClassLoader()); Assert.fail(); } catch (Exception e) { } } @Test public void testNonEnumValue() throws CustomParseException { try { MEnum<Foo> mEnum = new MValue.MEnum<Foo>(null, Boolean.class.getName(), "TRUE"); mEnum.asEhcacheObject(getClass().getClassLoader()); Assert.fail(); } catch (Exception e) { } }
### Question: ClusteredInstanceFactoryAccessor { public static ClusteredInstanceFactory getClusteredInstanceFactory(CacheManager cacheManager) { try { Field field = CacheManager.class.getDeclaredField("terracottaClient"); field.setAccessible(true); TerracottaClient terracottaClient = (TerracottaClient)field.get(cacheManager); return terracottaClient.getClusteredInstanceFactory(); } catch (NoSuchFieldException nsfe) { throw new CacheException(nsfe); } catch (IllegalAccessException iae) { throw new CacheException(iae); } } static ClusteredInstanceFactory getClusteredInstanceFactory(CacheManager cacheManager); static void setTerracottaClient(CacheManager cacheManager, TerracottaClient terracottaClient); }### Answer: @Test public void testAccessorDoesNotThrowException() throws Exception { CacheManager cm = new CacheManager(); try { ClusteredInstanceFactoryAccessor.getClusteredInstanceFactory(cm); } finally { cm.shutdown(); } }
### Question: AsyncWriteBehind implements WriteBehind { @Override public void start(CacheWriter writer) throws CacheException { async.start(new CacheWriterProcessor(writer), concurrency, POLICY); } AsyncWriteBehind(final AsyncCoordinator async, final int writeBehindConcurrency); @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(); static final ItemScatterPolicy<SingleAsyncOperation> POLICY; }### Answer: @SuppressWarnings("unchecked") @Test public void testPassesConcurrencyToAsyncCoordinatorOnStart() { asyncWriteBehind.start(null); verify(asyncCoordinator).start(any(CacheWriterProcessor.class), eq(CONCURRENCY), any(ItemScatterPolicy.class)); } @Test public void testPassesItemScatterPolicyToAsyncCoordinatorOnStart() { asyncWriteBehind.start(null); verify(asyncCoordinator).start(any(CacheWriterProcessor.class), eq(CONCURRENCY), same(AsyncWriteBehind.POLICY)); } @Test public void testPassesWrappedWriterToAsyncCoordinatorOnStart() { final CacheWriter writer = mock(CacheWriter.class); asyncWriteBehind.start(writer); ArgumentCaptor<CacheWriterProcessor> captor = ArgumentCaptor.forClass(CacheWriterProcessor.class); verify(asyncCoordinator).start(captor.capture(), eq(CONCURRENCY), same(AsyncWriteBehind.POLICY)); assertThat(captor.getAllValues().size(), is(1)); assertThat(captor.getValue().getCacheWriter(), sameInstance(writer)); }
### 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(final Element element); @Override void put(final Element element, final boolean doNotNotifyCacheReplicators); @Override void putQuiet(final Element element); @Override void putWithWriter(final Element element); @Override Element putIfAbsent(final Element element); @Override Element putIfAbsent(final Element element, final boolean doNotNotifyCacheReplicators); @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: LruMemoryStore extends AbstractStore { public final boolean containsKey(Object key) { return map.containsKey(key); } LruMemoryStore(Ehcache cache, Store diskStore); synchronized void unpinAll(); synchronized boolean isPinned(Object key); synchronized void setPinned(Object key, boolean pinned); final boolean put(Element element); final boolean putWithWriter(Element element, CacheWriterManager writerManager); final synchronized Element get(Object key); final synchronized Element getQuiet(Object key); final Element remove(Object key); final Element removeWithWriter(Object key, CacheWriterManager writerManager); final synchronized void removeAll(); final synchronized void dispose(); final void flush(); final Status getStatus(); final synchronized List getKeys(); final int getSize(); final int getTerracottaClusteredSize(); final boolean containsKey(Object key); final synchronized long getSizeInBytes(); void expireElements(); boolean bufferFull(); Object getMBean(); Policy getEvictionPolicy(); void setEvictionPolicy(Policy policy); Object getInternalContext(); boolean containsKeyInMemory(Object key); boolean containsKeyOffHeap(Object key); boolean containsKeyOnDisk(Object key); Policy getInMemoryEvictionPolicy(); int getInMemorySize(); long getInMemorySizeInBytes(); int getOffHeapSize(); long getOffHeapSizeInBytes(); int getOnDiskSize(); long getOnDiskSizeInBytes(); void setInMemoryEvictionPolicy(Policy policy); Element putIfAbsent(Element element); Element removeElement(Element element, ElementValueComparator comparator); boolean replace(Element old, Element element, ElementValueComparator comparator); Element replace(Element element); }### Answer: @Test public void testContainsKey() { final Object key = new Object(); assertThat(store.containsKey(key), is(false)); store.setPinned(key, true); assertThat(store.get(key), nullValue()); assertThat(store.containsKey(key), is(false)); }
### Question: AsyncWriteBehind implements WriteBehind { @Override public void delete(CacheEntry entry) { async.add(new DeleteAsyncOperation(entry.getKey(), entry.getElement())); } AsyncWriteBehind(final AsyncCoordinator async, final int writeBehindConcurrency); @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(); static final ItemScatterPolicy<SingleAsyncOperation> POLICY; }### Answer: @Test public void testDelegatesDeleteToAsyncCoordinator() { final Element element = new Element("foo", "bar"); asyncWriteBehind.delete(new CacheEntry(element.getObjectKey(), element)); ArgumentCaptor<SingleAsyncOperation> captor = ArgumentCaptor.forClass(SingleAsyncOperation.class); verify(asyncCoordinator).add(captor.capture()); assertThat(captor.getAllValues().size(), is(1)); final SingleAsyncOperation value = captor.getValue(); assertThat(value, instanceOf(DeleteAsyncOperation.class)); assertThat(value.getKey(), sameInstance(element.getObjectKey())); assertThat(value.getElement(), sameInstance(element)); }
### Question: AsyncWriteBehind implements WriteBehind { @Override public void write(Element element) { async.add(new WriteAsyncOperation(element)); } AsyncWriteBehind(final AsyncCoordinator async, final int writeBehindConcurrency); @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(); static final ItemScatterPolicy<SingleAsyncOperation> POLICY; }### Answer: @Test public void testDelegatesWriteToAsyncCoordinator() { final Element element = new Element("foo", "bar"); asyncWriteBehind.write(element); ArgumentCaptor<SingleAsyncOperation> captor = ArgumentCaptor.forClass(SingleAsyncOperation.class); verify(asyncCoordinator).add(captor.capture()); assertThat(captor.getAllValues().size(), is(1)); final SingleAsyncOperation value = captor.getValue(); assertThat(value, instanceOf(WriteAsyncOperation.class)); assertThat(value.getElement(), sameInstance(element)); }
### 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); @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: AsyncWriteBehind implements WriteBehind { @Override public void stop() throws CacheException { async.stop(); } AsyncWriteBehind(final AsyncCoordinator async, final int writeBehindConcurrency); @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(); static final ItemScatterPolicy<SingleAsyncOperation> POLICY; }### Answer: @Test public void testDelegatesStopToAsyncCoordinator() { asyncWriteBehind.stop(); verify(asyncCoordinator).stop(); }
### Question: AsyncWriteBehind implements WriteBehind { @Override public long getQueueSize() { return async.getQueueSize(); } AsyncWriteBehind(final AsyncCoordinator async, final int writeBehindConcurrency); @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(); static final ItemScatterPolicy<SingleAsyncOperation> POLICY; }### Answer: @Test public void testDelegatesGetQueueSizeToAsyncCoordinator() { asyncWriteBehind.getQueueSize(); verify(asyncCoordinator).getQueueSize(); }
### 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); } } @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: AsyncWriteBehind implements WriteBehind { @Override public void setOperationsFilter(OperationsFilter filter) { OperationsFilterWrapper filterWrapper = new OperationsFilterWrapper(filter); async.setOperationsFilter(filterWrapper); } AsyncWriteBehind(final AsyncCoordinator async, final int writeBehindConcurrency); @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(); static final ItemScatterPolicy<SingleAsyncOperation> POLICY; }### Answer: @Test public void testDelegatesSetOperationsFilterToAsyncCoordinator() { final CoalesceKeysFilter filter = new CoalesceKeysFilter(); asyncWriteBehind.setOperationsFilter(filter); ArgumentCaptor<OperationsFilterWrapper> captor = ArgumentCaptor.forClass(OperationsFilterWrapper.class); verify(asyncCoordinator).setOperationsFilter(captor.capture()); assertThat(captor.getAllValues().size(), is(1)); assertThat(captor.getValue().getDelegate(), CoreMatchers.<OperationsFilter<KeyBasedOperation>>sameInstance(filter)); }
### Question: SelectableConcurrentHashMap { public Element get(Object key) { int hash = hash(key.hashCode()); return segmentFor(hash).get(key, hash); } SelectableConcurrentHashMap(PoolAccessor poolAccessor, boolean elementPinningEnabled, int concurrency, final long maximumSize, final RegisteredEventListeners cacheEventNotificationService); 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: Watchdog { public void watch(final Watchable watchable) { registry.add(watchable); LOGGER.debug("Watchable cache '{}' registered", watchable.name()); } private Watchdog(final ScheduledExecutorService scheduler); static Watchdog create(); void watch(final Watchable watchable); void unwatch(final Watchable watchable); void init(); }### Answer: @Test public void testMustProbeAllRegisteredWatchables() { watchdog.watch(cache1); watchdog.watch(cache2); scheduler.trigger(); verify(cache1).probeLiveness(); verify(cache2).probeLiveness(); }
### Question: ResourceClassLoader extends ClassLoader { @Override public synchronized Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException { if (name.startsWith("java.")) { return getParent().loadClass(name); } 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); @Override /** * very similar to what OracleJDK classloader does, * except the first resources (more important) are the ones found with our ResourceClassLoader */ Enumeration<URL> getResources(String resourceName); }### Answer: @Test(expected = ClassNotFoundException.class) public void contentOfTheJarNotVisibleWithNormalClassLoaderTest() throws ClassNotFoundException { Class<?> simpleClass = testCaseClassLoader.loadClass("pof.Simple"); }
### Question: ElementResource { @DELETE public void deleteElement() throws WebApplicationException { LOG.debug("DELETE element {}", element); net.sf.ehcache.Cache ehcache = lookupCache(); if (element.equals("*")) { ehcache.removeAll(); } else { boolean removed = ehcache.remove(element); if (!removed) { throw new WebApplicationException(Response.Status.NOT_FOUND); } } } ElementResource(UriInfo uriInfo, Request request, String cache, String element); @HEAD Response getElementHeader(); @GET Response getElement(); @PUT Response putElement(@Context HttpHeaders headers, byte[] data); @DELETE void deleteElement(); }### Answer: @Test public void testDeleteElement() throws Exception { long beforeCreated = System.currentTimeMillis(); Thread.sleep(10); String originalString = "The rain in Spain falls mainly on the plain"; ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(originalString.getBytes()); int status = HttpUtil.put("http: assertEquals(201, status); HttpURLConnection urlConnection = HttpUtil.get("http: assertEquals(200, urlConnection.getResponseCode()); urlConnection = HttpUtil.delete("http: assertEquals(204, urlConnection.getResponseCode()); assertEquals(404, HttpUtil.get("http: }
### Question: ElementResource { @GET public Response getElement() { LOG.debug("GET element {}", element); net.sf.ehcache.Cache ehcache = lookupCache(); net.sf.ehcache.Element ehcacheElement = lookupElement(ehcache); Element localElement = new Element(ehcacheElement, uriInfo.getAbsolutePath().toString()); Date lastModifiedDate = createLastModified(ehcacheElement); EntityTag entityTag = createETag(ehcacheElement); Response.ResponseBuilder responseBuilder = request.evaluatePreconditions(lastModifiedDate, entityTag); if (responseBuilder != null) { return responseBuilder.build(); } else { return Response.ok(localElement.getValue(), localElement.getMimeType()) .lastModified(lastModifiedDate) .tag(entityTag) .header("Expires", (new Date(localElement.getExpirationDate())).toString()) .build(); } } ElementResource(UriInfo uriInfo, Request request, String cache, String element); @HEAD Response getElementHeader(); @GET Response getElement(); @PUT Response putElement(@Context HttpHeaders headers, byte[] data); @DELETE void deleteElement(); }### Answer: @Test public void testGetElement() throws Exception { HttpURLConnection result = HttpUtil.get("http: assertEquals(200, result.getResponseCode()); assertEquals("application/xml", result.getContentType()); JAXBContext jaxbContext = new JAXBContextResolver().getContext(Caches.class); Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); Cache cache = (Cache) unmarshaller.unmarshal(result.getInputStream()); assertEquals("sampleCache1", cache.getName()); assertEquals("http: assertNotNull("http: }
### Question: CacheResource { @GET public Cache getCache() { LOG.debug("GET Cache {}" + cache); net.sf.ehcache.Cache ehcache = MANAGER.getCache(cache); if (ehcache == null) { throw new WebApplicationException(Response.Status.NOT_FOUND); } String cacheAsString = ehcache.toString(); cacheAsString = cacheAsString.substring(0, cacheAsString.length() - 1); cacheAsString = cacheAsString + "size = " + ehcache.getSize() + " ]"; return new Cache(ehcache.getName(), uriInfo.getAbsolutePath().toString(), cacheAsString, new Statistics(ehcache.getStatistics()), ehcache.getCacheConfiguration()); } CacheResource(UriInfo uriInfo, Request request, String cache); @HEAD Response getCacheHeader(); @GET Cache getCache(); @PUT Response putCache(); @DELETE Response deleteCache(); @Path(value = "{element}") ElementResource getElementResource(@PathParam("element") String element); }### Answer: @Test public void testGetCache() throws Exception { HttpURLConnection result = HttpUtil.get("http: assertEquals(200, result.getResponseCode()); assertEquals("application/xml", result.getContentType()); JAXBContext jaxbContext = new JAXBContextResolver().getContext(Caches.class); Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); Cache cache = (Cache) unmarshaller.unmarshal(result.getInputStream()); assertEquals("sampleCache1", cache.getName()); assertEquals("http: assertNotNull("http: }
### Question: CacheResource { @DELETE public Response deleteCache() { LOG.debug("DELETE Cache {}" + cache); net.sf.ehcache.Cache ehcache = MANAGER.getCache(cache); Response response; if (ehcache == null) { throw new WebApplicationException(Response.Status.NOT_FOUND); } else { CacheManager.getInstance().removeCache(cache); response = Response.ok().build(); } return response; } CacheResource(UriInfo uriInfo, Request request, String cache); @HEAD Response getCacheHeader(); @GET Cache getCache(); @PUT Response putCache(); @DELETE Response deleteCache(); @Path(value = "{element}") ElementResource getElementResource(@PathParam("element") String element); }### Answer: @Test public void testDeleteCache() throws Exception { HttpURLConnection urlConnection = HttpUtil.put("http: urlConnection = HttpUtil.delete("http: assertEquals(200, urlConnection.getResponseCode()); if (urlConnection.getHeaderField("Server").matches("(.*)Glassfish(.*)")) { assertTrue(urlConnection.getContentType().matches("text/plain(.*)")); } String responseBody = HttpUtil.inputStreamToText(urlConnection.getInputStream()); assertEquals("", responseBody); urlConnection = HttpUtil.delete("http: assertEquals(404, urlConnection.getResponseCode()); }
### Question: CachesResource { @GET public List<Cache> getCaches() { LOG.debug("GET Caches"); String[] cacheNames = MANAGER.getCacheNames(); List<Cache> cacheList = new ArrayList<Cache>(); for (String cacheName : cacheNames) { Ehcache ehcache = MANAGER.getCache(cacheName); URI cacheUri = uriInfo.getAbsolutePathBuilder().path(cacheName).build().normalize(); Cache cache = new Cache(cacheName, cacheUri.toString(), ehcache.toString(), new Statistics(ehcache.getStatistics()), ehcache.getCacheConfiguration()); cacheList.add(cache); } return cacheList; } @Path("{cache}") CacheResource getCacheResource(@PathParam("cache") String cache); @GET List<Cache> getCaches(); }### Answer: @Test public void testGetCaches() throws Exception { HttpURLConnection result = HttpUtil.get("http: assertEquals(200, result.getResponseCode()); DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document document = documentBuilder.parse(result.getInputStream()); XPath xpath = XPathFactory.newInstance().newXPath(); String cacheCount = xpath.evaluate("count( assertTrue(Integer.parseInt(cacheCount) >= 6); }
### 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 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 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 void addCache(String cacheName) throws IllegalStateException, ObjectExistsException, CacheException { manager.addCache(cacheName); } @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 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 testAddCache() throws Exception { cacheService.addCache("newcache1"); Cache cache = cacheService.getCache("newcache1"); assertNotNull(cache); try { cacheService.addCache("newcache1"); } catch (SOAPFaultException e) { assertTrue(e.getCause().getMessage().indexOf("Cache newcache1 already exists") != -1); } }
### Question: EhcacheWebServiceEndpoint { @WebMethod public void removeCache(String cacheName) throws IllegalStateException { manager.removeCache(cacheName); } @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 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 testRemoveCache() throws Exception { cacheService.addCache("newcache2"); Cache cache = cacheService.getCache("newcache2"); assertNotNull(cache); cacheService.removeCache("newcache2"); cache = cacheService.getCache("newcache2"); assertNull(cache); cacheService.removeCache("newcache2"); cache = cacheService.getCache("newcache2"); assertNull(cache); }
### 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 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 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 void put(String cacheName, Element element) throws NoSuchCacheException, CacheException { net.sf.ehcache.Cache cache = lookupCache(cacheName); cache.put(element.getEhcacheElement()); } @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 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 testCachePutNull() throws Exception, NoSuchCacheException_Exception, IllegalStateException_Exception { Element element = new Element(); element.setKey("1"); cacheService.put("sampleCache1", element); element = getElementFromCache(); boolean equals = Arrays.equals(null, element.getValue()); assertTrue(equals); }
### 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 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 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 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 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 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 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 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: SizeOf { public Size deepSizeOf(int maxDepth, boolean abortWhenMaxDepthExceeded, Object... obj) { try { return new Size(walker.walk(maxDepth, abortWhenMaxDepthExceeded, obj), true); } catch (MaxDepthExceededException e) { LOG.warn(e.getMessage()); return new Size(e.getMeasuredSize(), false); } } SizeOf(SizeOfFilter fieldFilter, boolean caching); long sizeOf(Object obj); Size deepSizeOf(int maxDepth, boolean abortWhenMaxDepthExceeded, Object... obj); }### Answer: @Test public void testOnHeapConsumption() throws Exception { SizeOf sizeOf = new CrossCheckingSizeOf(); int size = 80000; for (int j = 0; j < 5; j++) { container = new Object[size]; long usedBefore = measureMemoryUse(); for (int i = 0; i < size; i++) { container[i] = new EvilPair(new Object(), new SomeClass(i % 2 == 0)); } long mem = 0; for (Object s : container) { mem += deepSizeOf(sizeOf, s); } long used = measureMemoryUse() - usedBefore; float percentage = 1 - (mem / (float) used); System.err.println("Run # " + (j + 1) + ": Deviation of " + (int)(percentage * -100) + "%\n" + used + " bytes are actually being used, while we believe " + mem + " are"); if (j > 1) { assertThat("Run # " + (j + 1) + ": Deviation of " + (int)(percentage * -100) + "% was above the +/-1.5% delta threshold \n" + used + " bytes are actually being used, while we believe " + mem + " are (" + (used - mem) / size + ")", Math.abs(percentage) < .015f, is(true)); } } }
### Question: SelfPopulatingCache extends BlockingCache { public void refresh() throws CacheException { refresh(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 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: 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: 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: 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: 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: 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 { 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: 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: 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: 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: 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: 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: 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 { 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 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: 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: 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 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"); }