View Javadoc

1   /***
2    *  Copyright 2003-2010 Terracotta, Inc.
3    *
4    *  Licensed under the Apache License, Version 2.0 (the "License");
5    *  you may not use this file except in compliance with the License.
6    *  You may obtain a copy of the License at
7    *
8    *      http://www.apache.org/licenses/LICENSE-2.0
9    *
10   *  Unless required by applicable law or agreed to in writing, software
11   *  distributed under the License is distributed on an "AS IS" BASIS,
12   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   *  See the License for the specific language governing permissions and
14   *  limitations under the License.
15   */
16  
17  package net.sf.ehcache;
18  
19  import static org.junit.Assert.assertEquals;
20  import static org.junit.Assert.assertFalse;
21  import static org.junit.Assert.assertNotNull;
22  import static org.junit.Assert.assertNull;
23  import static org.junit.Assert.assertTrue;
24  import static org.junit.Assert.fail;
25  
26  import java.io.File;
27  import java.io.FileInputStream;
28  import java.io.InputStream;
29  import java.net.URL;
30  import java.util.Date;
31  import java.util.Iterator;
32  import java.util.List;
33  import java.util.Set;
34  
35  import net.sf.ehcache.bootstrap.BootstrapCacheLoader;
36  import net.sf.ehcache.config.CacheConfiguration;
37  import net.sf.ehcache.config.Configuration;
38  import net.sf.ehcache.config.ConfigurationFactory;
39  import net.sf.ehcache.config.DiskStoreConfiguration;
40  import net.sf.ehcache.constructs.blocking.BlockingCache;
41  import net.sf.ehcache.constructs.blocking.CountingCacheEntryFactory;
42  import net.sf.ehcache.constructs.blocking.SelfPopulatingCache;
43  import net.sf.ehcache.distribution.JVMUtil;
44  import net.sf.ehcache.distribution.RMIAsynchronousCacheReplicator;
45  import net.sf.ehcache.distribution.RMIBootstrapCacheLoader;
46  import net.sf.ehcache.event.CacheEventListener;
47  import net.sf.ehcache.event.RegisteredEventListeners;
48  import net.sf.ehcache.statistics.LiveCacheStatisticsData;
49  import net.sf.ehcache.store.DiskStore;
50  import net.sf.ehcache.store.Store;
51  
52  import org.junit.After;
53  import org.junit.Test;
54  import org.slf4j.Logger;
55  import org.slf4j.LoggerFactory;
56  
57  /***
58   * Tests for CacheManager
59   *
60   * @author Greg Luck
61   * @version $Id: CacheManagerTest.java 2539 2010-07-02 10:58:13Z alexsnaps $
62   */
63  public class CacheManagerTest {
64  
65      private static final Logger LOG = LoggerFactory.getLogger(CacheManagerTest.class.getName());
66  
67      /***
68       * the CacheManager Singleton instance
69       */
70      protected CacheManager singletonManager;
71  
72      /***
73       * a CacheManager which is created as an instance
74       */
75      protected CacheManager instanceManager;
76  
77      /***
78       * Shutdown managers. Check that the manager is removed from
79       * CacheManager.ALL_CACHE_MANAGERS
80       */
81      @After
82      public void tearDown() throws Exception {
83          if (singletonManager != null) {
84              if (singletonManager.getStatus().equals(Status.STATUS_ALIVE)) {
85                  assertTrue(CacheManager.ALL_CACHE_MANAGERS.contains(singletonManager));
86              }
87              singletonManager.shutdown();
88              assertFalse(CacheManager.ALL_CACHE_MANAGERS.contains(singletonManager));
89          }
90          if (instanceManager != null) {
91              if (instanceManager.getStatus().equals(Status.STATUS_ALIVE)) {
92                  assertTrue(CacheManager.ALL_CACHE_MANAGERS.contains(instanceManager));
93              }
94              instanceManager.shutdown();
95              assertFalse(CacheManager.ALL_CACHE_MANAGERS.contains(instanceManager));
96          }
97      }
98  
99      @Test
100     public void testCacheReferenceLookUps() {
101         singletonManager = CacheManager.create();
102         String cacheName = "randomNewCache";
103         singletonManager.addCache(cacheName);
104 
105         // Default state by name
106         Cache cache = singletonManager.getCache(cacheName);
107         assertNotNull(cache);
108         assertNotNull(singletonManager.getEhcache(cacheName));
109         assertTrue(singletonManager.getEhcache(cacheName) instanceof Cache);
110         assertTrue(cache == singletonManager.getEhcache(cacheName));
111 
112         // replace cache
113         BlockingCache decoratedCache = new BlockingCache(cache);
114         singletonManager.replaceCacheWithDecoratedCache(cache, decoratedCache);
115         assertNull(singletonManager.getCache(cacheName));
116         assertNotNull(singletonManager.getEhcache(cacheName));
117         assertTrue(singletonManager.getEhcache(cacheName) == decoratedCache);
118     }
119 
120     @Test
121     public void testProgrammaticConfigurationFailsProperlyWhenNoDefaultCacheConfigured() {
122         Configuration mgrConfig = new Configuration();
123         mgrConfig.setUpdateCheck(false);
124         try {
125             CacheManager cacheManager = new CacheManager(mgrConfig);
126             fail("This should have thrown an Exception, as no default cache is configured!");
127         } catch (Exception e) {
128             assertEquals("Illegal configuration. No default cache is configured.", e.getMessage());
129         }
130     }
131 
132     /***
133      * Tests that the CacheManager was successfully created
134      */
135     @Test
136     public void testCreateCacheManager() throws CacheException {
137         singletonManager = CacheManager.create();
138         singletonManager.getEhcache("");
139         assertNotNull(singletonManager);
140         assertEquals(14, singletonManager.getCacheNames().length);
141     }
142 
143     /***
144      * Tests that the CacheManager was successfully created
145      */
146     @Test
147     public void testCreateCacheManagerFromFile() throws CacheException {
148         singletonManager = CacheManager.create(AbstractCacheTest.SRC_CONFIG_DIR + "ehcache.xml");
149         assertNotNull(singletonManager);
150         assertEquals(6, singletonManager.getCacheNames().length);
151     }
152 
153     /***
154      * Tests that the CacheManager was successfully created from a Configuration
155      */
156     @Test
157     public void testCreateCacheManagerFromConfiguration() throws CacheException {
158         File file = new File(AbstractCacheTest.SRC_CONFIG_DIR + "ehcache.xml");
159         Configuration configuration = ConfigurationFactory.parseConfiguration(file);
160         CacheManager manager = new CacheManager(configuration);
161         assertNotNull(manager);
162         assertEquals(6, manager.getCacheNames().length);
163         manager.shutdown();
164     }
165 
166     /***
167      * Tests that the CacheManager was successfully created
168      */
169     @Test
170     public void testCreateCacheManagerFromInputStream() throws Exception {
171         InputStream fis = new FileInputStream(new File(
172                 AbstractCacheTest.SRC_CONFIG_DIR + "ehcache.xml")
173                 .getAbsolutePath());
174         try {
175             singletonManager = CacheManager.create(fis);
176         } finally {
177             fis.close();
178         }
179         assertNotNull(singletonManager);
180         assertEquals(6, singletonManager.getCacheNames().length);
181     }
182 
183     /***
184      * Tests that creating a second cache manager with the same disk path will
185      * fail.
186      */
187     @Test
188     public void testCreateTwoCacheManagersWithSamePath() throws CacheException {
189         URL secondCacheConfiguration = this.getClass().getResource(
190                 "/ehcache-2.xml");
191 
192         singletonManager = CacheManager.create(secondCacheConfiguration);
193         instanceManager = new CacheManager(secondCacheConfiguration);
194 
195         String intialDiskStorePath = System.getProperty("java.io.tmpdir")
196                 + File.separator + "second";
197 
198         File diskStorePathDir = new File(intialDiskStorePath);
199         File[] files = diskStorePathDir.listFiles();
200         File newDiskStorePath = null;
201         boolean newDiskStorePathFound = false;
202         for (File file : files) {
203             if (file.isDirectory()) {
204                 if (file.getName().indexOf(
205                         DiskStore.AUTO_DISK_PATH_DIRECTORY_PREFIX) != -1) {
206                     newDiskStorePathFound = true;
207                     newDiskStorePath = file;
208                     break;
209                 }
210             }
211         }
212         assertTrue(newDiskStorePathFound);
213         newDiskStorePath.delete();
214 
215     }
216 
217     /***
218      * Tests that two CacheManagers were successfully created
219      */
220     @Test
221     public void testTwoCacheManagers() throws CacheException {
222         Element element1 = new Element(1 + "", new Date());
223         Element element2 = new Element(2 + "", new Date());
224 
225         CacheManager.getInstance().getCache("sampleCache1").put(element1);
226 
227         // Check can start second one with a different disk path
228         URL secondCacheConfiguration = this.getClass().getResource(
229                 "/ehcache-2.xml");
230         instanceManager = new CacheManager(secondCacheConfiguration);
231         instanceManager.getCache("sampleCache1").put(element2);
232 
233         assertEquals(element1, CacheManager.getInstance().getCache(
234                 "sampleCache1").get(1 + ""));
235         assertEquals(element2, instanceManager.getCache("sampleCache1").get(
236                 2 + ""));
237 
238         // shutting down instance should leave singleton unaffected
239         instanceManager.shutdown();
240         assertEquals(element1, CacheManager.getInstance().getCache(
241                 "sampleCache1").get(1 + ""));
242 
243         // Try shutting and recreating a new instance cache manager
244         instanceManager = new CacheManager(secondCacheConfiguration);
245         instanceManager.getCache("sampleCache1").put(element2);
246         CacheManager.getInstance().shutdown();
247         assertEquals(element2, instanceManager.getCache("sampleCache1").get(
248                 2 + ""));
249 
250         // Try shutting and recreating the singleton cache manager
251         CacheManager.getInstance().getCache("sampleCache1").put(element2);
252         assertNull(CacheManager.getInstance().getCache("sampleCache1").get(
253                 1 + ""));
254         assertEquals(element2, CacheManager.getInstance().getCache(
255                 "sampleCache1").get(2 + ""));
256     }
257 
258     /***
259      * Tests that two CacheManagers were successfully created
260      */
261     @Test
262     public void testTwoCacheManagersWithSameConfiguration()
263             throws CacheException {
264         Element element1 = new Element(1 + "", new Date());
265         Element element2 = new Element(2 + "", new Date());
266 
267         String fileName = AbstractCacheTest.TEST_CONFIG_DIR + "ehcache.xml";
268         CacheManager.create(fileName).getCache("sampleCache1").put(element1);
269 
270         // Check can start second one with the same config
271         instanceManager = new CacheManager(fileName);
272         instanceManager.getCache("sampleCache1").put(element2);
273 
274         assertEquals(element1, CacheManager.getInstance().getCache(
275                 "sampleCache1").get(1 + ""));
276         assertEquals(element2, instanceManager.getCache("sampleCache1").get(
277                 2 + ""));
278 
279         // shutting down instance should leave singleton unaffected
280         instanceManager.shutdown();
281         assertEquals(element1, CacheManager.getInstance().getCache(
282                 "sampleCache1").get(1 + ""));
283 
284         // Try shutting and recreating a new instance cache manager
285         instanceManager = new CacheManager(fileName);
286         instanceManager.getCache("sampleCache1").put(element2);
287         CacheManager.getInstance().shutdown();
288         assertEquals(element2, instanceManager.getCache("sampleCache1").get(
289                 2 + ""));
290 
291         // Try shutting and recreating the singleton cache manager
292         CacheManager.getInstance().getCache("sampleCache1").put(element2);
293         assertNull(CacheManager.getInstance().getCache("sampleCache1").get(
294                 1 + ""));
295         assertEquals(element2, CacheManager.getInstance().getCache(
296                 "sampleCache1").get(2 + ""));
297     }
298 
299     /***
300      * Create and destory cache managers and see what happens with threads. Each
301      * Cache creates at least two threads. These should all be killed when the
302      * Cache disposes. Doing that 800 times as in that test gives the
303      * reassurance.
304      */
305     @Test
306     public void testForCacheManagerThreadLeak() throws CacheException,
307             InterruptedException {
308         // Check can start second one with a different disk path
309         int startingThreadCount = countThreads();
310 
311         URL secondCacheConfiguration = this.getClass().getResource(
312                 "/ehcache-2.xml");
313         for (int i = 0; i < 100; i++) {
314             instanceManager = new CacheManager(secondCacheConfiguration);
315             instanceManager.shutdown();
316         }
317         int endingThreadCount;
318         int tries = 0;
319         // Give the spools a chance to exit
320         do {
321             Thread.sleep(500);
322             endingThreadCount = countThreads();
323         } while (tries++ < 5 || endingThreadCount >= startingThreadCount + 2);
324 
325         // Allow a bit of variation.
326         assertTrue(endingThreadCount < startingThreadCount + 2);
327 
328     }
329 
330     /***
331      * The expiry threads and spool threads share are now combined. This should
332      * save some.
333      * <p/>
334      * ehcache-big.xml has 70 caches that overflow to disk. Check that the
335      * DiskStore is not using more than 1 thread per DiskStore.
336      * <p/>
337      * ehcache-1.2.3 had 126 threads for this test. ehcache-1.2.4 has 71. 70 for
338      * the DiskStore thread and one shutdown hook
339      * <p />
340      * ehcache-1.7 has 1 additional thread per cache for
341      * SampledCacheUsageStatistics. 70 Caches means 140 threads plus 1 for
342      * shutdown totalling to 141. Plus Junit thread totals 142.
343      */
344     @Test
345     public void testCacheManagerThreads() throws CacheException,
346             InterruptedException {
347         singletonManager = CacheManager
348                 .create(AbstractCacheTest.TEST_CONFIG_DIR + "ehcache-big.xml");
349         int threads = countThreads();
350         assertTrue("More than 145 threads: " + threads, countThreads() <= 145);
351     }
352 
353     /***
354      * It should be possible to create a new CacheManager instance with the same
355      * disk configuration, provided the first was shutdown. Note that any
356      * persistent disk stores will be available to the second cache manager.
357      */
358     @Test
359     public void testInstanceCreateShutdownCreate() throws CacheException {
360         singletonManager = CacheManager.create();
361 
362         URL secondCacheConfiguration = this.getClass().getResource(
363                 "/ehcache-2.xml");
364         instanceManager = new CacheManager(secondCacheConfiguration);
365         instanceManager.shutdown();
366 
367         // shutting down instance should leave singleton ok
368         assertEquals(14, singletonManager.getCacheNames().length);
369 
370         instanceManager = new CacheManager(secondCacheConfiguration);
371         assertNotNull(instanceManager);
372         assertEquals(8, instanceManager.getCacheNames().length);
373 
374     }
375 
376     /***
377      * Tests programmatic creation of CacheManager with a programmatic
378      * Configuration.
379      * <p/>
380      * Tests:
381      * <ol>
382      * <li>adding a cache by name, which will use default cache
383      * <li>adding a Cache object
384      * <li>setting the DiskStore directory path
385      * </ol>
386      *
387      * @throws CacheException
388      */
389     @Test
390     public void testCreateCacheManagersProgrammatically() throws CacheException {
391 
392         Configuration configuration = new Configuration()
393             .defaultCache(new CacheConfiguration("defaultCache", 10))
394             .diskStore(new DiskStoreConfiguration().path("java.io.tmpdir"));
395         assertNotNull(configuration);
396 
397         instanceManager = new CacheManager(configuration);
398         assertNotNull(instanceManager);
399         assertEquals(0, instanceManager.getCacheNames().length);
400 
401         instanceManager.addCache("toBeDerivedFromDefaultCache");
402         Cache cache = new Cache("testCache", 1, true, false, 5, 2);
403         instanceManager.addCache(cache);
404 
405         assertEquals(2, instanceManager.getCacheNames().length);
406 
407     }
408 
409     /***
410      * Checks we can get a cache
411      */
412     @Test
413     public void testGetCache() throws CacheException {
414         instanceManager = CacheManager.create();
415         Ehcache cache = instanceManager.getCache("sampleCache1");
416         assertNotNull(cache);
417     }
418 
419     /***
420      * Does the cache hang on to its instance?
421      */
422     @Test
423     public void testCacheManagerReferenceInstance() {
424         instanceManager = new CacheManager();
425         instanceManager.addCache("test");
426         Ehcache cache = instanceManager.getCache("test");
427         assertEquals("test", cache.getName());
428         assertEquals(Status.STATUS_ALIVE, cache.getStatus());
429         CacheManager reference = cache.getCacheManager();
430         assertTrue(reference == instanceManager);
431     }
432 
433     /***
434      * Does a cache with a reference to a singleton hang on to it?
435      */
436     @Test
437     public void testCacheManagerReferenceSingleton() {
438         singletonManager = CacheManager.create();
439         singletonManager.addCache("test");
440         Ehcache cache = singletonManager.getCache("test");
441         assertEquals("test", cache.getName());
442         assertEquals(Status.STATUS_ALIVE, cache.getStatus());
443         CacheManager reference = cache.getCacheManager();
444         assertTrue(reference == singletonManager);
445     }
446 
447     /***
448      * Checks we can disable ehcache using a system property
449      */
450     @Test
451     public void testDisableEhcache() throws CacheException,
452             InterruptedException {
453         System.setProperty(Cache.NET_SF_EHCACHE_DISABLED, "true");
454         Thread.sleep(1000);
455         instanceManager = CacheManager.create();
456         Ehcache cache = instanceManager.getCache("sampleCache1");
457         assertNotNull(cache);
458         cache.put(new Element("key123", "value"));
459         Element element = cache.get("key123");
460         assertNull(
461                 "When the disabled property is set all puts should be discarded",
462                 element);
463 
464         cache.putQuiet(new Element("key1234", "value"));
465         assertNull(
466                 "When the disabled property is set all puts should be discarded",
467                 cache.get("key1234"));
468 
469         System.setProperty(Cache.NET_SF_EHCACHE_DISABLED, "false");
470 
471     }
472 
473     /***
474      * Tests shutdown after shutdown.
475      */
476     @Test
477     public void testShutdownAfterShutdown() throws CacheException {
478         instanceManager = CacheManager.create();
479         assertEquals(Status.STATUS_ALIVE, instanceManager.getStatus());
480         instanceManager.shutdown();
481         assertEquals(Status.STATUS_SHUTDOWN, instanceManager.getStatus());
482         instanceManager.shutdown();
483         assertEquals(Status.STATUS_SHUTDOWN, instanceManager.getStatus());
484     }
485 
486     /***
487      * Tests create, shutdown, create
488      */
489     @Test
490     public void testCreateShutdownCreate() throws CacheException {
491         singletonManager = CacheManager.create();
492         assertEquals(Status.STATUS_ALIVE, singletonManager.getStatus());
493         singletonManager.shutdown();
494 
495         // check we can recreate the CacheManager on demand.
496         singletonManager = CacheManager.create();
497         assertNotNull(singletonManager);
498         assertEquals(14, singletonManager.getCacheNames().length);
499         assertEquals(Status.STATUS_ALIVE, singletonManager.getStatus());
500 
501         singletonManager.shutdown();
502         assertEquals(Status.STATUS_SHUTDOWN, singletonManager.getStatus());
503     }
504 
505     /***
506      * Tests removing a cache
507      */
508     @Test
509     public void testRemoveCache() throws CacheException {
510         singletonManager = CacheManager.create();
511         Ehcache cache = singletonManager.getCache("sampleCache1");
512         assertNotNull(cache);
513         singletonManager.removeCache("sampleCache1");
514         cache = singletonManager.getCache("sampleCache1");
515         assertNull(cache);
516 
517         // NPE tests
518         singletonManager.removeCache(null);
519         singletonManager.removeCache("");
520     }
521 
522     /***
523      * Tests adding a new cache with default config
524      */
525     @Test
526     public void testAddCache() throws CacheException {
527         singletonManager = CacheManager.create();
528         singletonManager.addCache("test");
529         singletonManager.addCache("test2");
530         Ehcache cache = singletonManager.getCache("test");
531         assertNotNull(cache);
532         assertEquals("test", cache.getName());
533         String[] cacheNames = singletonManager.getCacheNames();
534         boolean match = false;
535         for (String cacheName : cacheNames) {
536             if (cacheName.equals("test")) {
537                 match = true;
538             }
539         }
540         assertTrue(match);
541 
542         // NPE tests
543         singletonManager.addCache("");
544     }
545 
546     @Test
547     public void testAddCacheIfAbsent() {
548         singletonManager = CacheManager.create();
549         singletonManager.addCache("present");
550         assertTrue(singletonManager.getCache("present")
551                    == singletonManager.addCacheIfAbsent(new Cache(new CacheConfiguration("present", 1000))));
552 
553         Cache theCache = new Cache(new CacheConfiguration("absent", 1000));
554         Ehcache cache = singletonManager.addCacheIfAbsent(theCache);
555         assertNotNull(cache);
556         assertTrue(theCache == cache);
557         assertEquals("absent", cache.getName());
558 
559         Cache other = new Cache(new CacheConfiguration(cache.getName(), 1000));
560         Ehcache actualCacheRegisteredWithManager = singletonManager.addCacheIfAbsent(other);
561         assertNotNull(actualCacheRegisteredWithManager);
562         assertFalse(other == actualCacheRegisteredWithManager);
563         assertTrue(cache == actualCacheRegisteredWithManager);
564 
565         Cache newCache = new Cache(new CacheConfiguration(cache.getName(), 1000));
566         singletonManager.removeCache(actualCacheRegisteredWithManager.getName());
567         actualCacheRegisteredWithManager = singletonManager.addCacheIfAbsent(newCache);
568         assertNotNull(actualCacheRegisteredWithManager);
569         assertFalse(cache == actualCacheRegisteredWithManager);
570         assertTrue(newCache == actualCacheRegisteredWithManager);
571 
572         assertTrue(singletonManager.addCacheIfAbsent(new Cache(new CacheConfiguration(actualCacheRegisteredWithManager.getName(), 1000)))
573                    == actualCacheRegisteredWithManager);
574 
575         assertNull(singletonManager.addCacheIfAbsent((Ehcache) null));
576     }
577 
578     @Test
579     public void testAddNamedCacheIfAbsent() {
580         singletonManager = CacheManager.create();
581         String presentCacheName = "present";
582         singletonManager.addCache(presentCacheName);
583         Cache alreadyPresent = singletonManager.getCache(presentCacheName);
584         Ehcache cache = singletonManager.addCacheIfAbsent(presentCacheName);
585         assertNotNull(cache);
586         assertTrue(alreadyPresent == cache);
587         assertEquals(presentCacheName, cache.getName());
588 
589         Ehcache actualCacheRegisteredWithManager = singletonManager.addCacheIfAbsent("absent");
590         assertNotNull(actualCacheRegisteredWithManager);
591         assertTrue(singletonManager.getCache(actualCacheRegisteredWithManager.getName()) == actualCacheRegisteredWithManager);
592         assertEquals("absent", actualCacheRegisteredWithManager.getName());
593         assertTrue(singletonManager.addCacheIfAbsent(actualCacheRegisteredWithManager.getName()) == actualCacheRegisteredWithManager);
594 
595         assertTrue(singletonManager.addCacheIfAbsent(new Cache(new CacheConfiguration(actualCacheRegisteredWithManager.getName(), 1000)))
596                    == actualCacheRegisteredWithManager);
597         assertNull(singletonManager.addCacheIfAbsent((String) null));
598         assertNull(singletonManager.addCacheIfAbsent(""));
599     }
600 
601     /***
602      * Tests we can add caches from the default where the default has listeners.
603      * Since 1.7, a CacheUsageStatisticsData is also registered.
604      */
605     @Test
606     public void testAddCacheFromDefaultWithListeners() throws CacheException {
607         singletonManager = CacheManager
608                 .create(AbstractCacheTest.TEST_CONFIG_DIR + File.separator
609                         + "distribution" + File.separator
610                         + "ehcache-distributed1.xml");
611         singletonManager.addCache("test");
612         Ehcache cache = singletonManager.getCache("test");
613         assertNotNull(cache);
614         assertEquals("test", cache.getName());
615 
616         Set listeners = cache.getCacheEventNotificationService()
617                 .getCacheEventListeners();
618         assertEquals(2, listeners.size());
619         for (Iterator iterator = listeners.iterator(); iterator.hasNext();) {
620             CacheEventListener cacheEventListener = (CacheEventListener) iterator
621                     .next();
622             assertTrue(cacheEventListener instanceof RMIAsynchronousCacheReplicator
623                     || cacheEventListener instanceof LiveCacheStatisticsData);
624         }
625     }
626 
627     /***
628      * Bug 1457268. Instance of RegisteredEventListeners shared between caches
629      * created from default cache. The issue also results in sharing of all
630      * references. This test makes sure each cache has its own.
631      */
632     @Test
633     public void testCachesCreatedFromDefaultDoNotShareListenerReferences() {
634         singletonManager = CacheManager.create();
635         singletonManager.addCache("newfromdefault1");
636         Cache cache1 = singletonManager.getCache("newfromdefault1");
637         singletonManager.addCache("newfromdefault2");
638         Cache cache2 = singletonManager.getCache("newfromdefault2");
639 
640         RegisteredEventListeners listeners1 = cache1
641                 .getCacheEventNotificationService();
642         RegisteredEventListeners listeners2 = cache2
643                 .getCacheEventNotificationService();
644         assertTrue(listeners1 != listeners2);
645 
646         Store store1 = cache1.getStore();
647         Store store2 = cache2.getStore();
648         assertTrue(store1 != store2);
649 
650     }
651 
652     /***
653      * Do bootstrap cache loaders work ok when created from the default cache?
654      */
655     @Test
656     public void testCachesCreatedFromDefaultWithBootstrapSet() {
657         singletonManager = CacheManager
658                 .create(AbstractCacheTest.TEST_CONFIG_DIR
659                         + "distribution/ehcache-distributed1.xml");
660         singletonManager.addCache("newfromdefault1");
661         Cache newfromdefault1 = singletonManager.getCache("newfromdefault1");
662         singletonManager.addCache("newfromdefault2");
663         Cache newfromdefault2 = singletonManager.getCache("newfromdefault2");
664 
665         assertTrue(newfromdefault1 != newfromdefault2);
666 
667         BootstrapCacheLoader bootstrapCacheLoader1 = (newfromdefault1)
668                 .getBootstrapCacheLoader();
669         BootstrapCacheLoader bootstrapCacheLoader2 = (newfromdefault2)
670                 .getBootstrapCacheLoader();
671 
672         assertTrue(bootstrapCacheLoader1 != bootstrapCacheLoader2);
673 
674         assertNotNull(bootstrapCacheLoader1);
675         assertEquals(RMIBootstrapCacheLoader.class, bootstrapCacheLoader1
676                 .getClass());
677         assertEquals(true, bootstrapCacheLoader1.isAsynchronous());
678         assertEquals(5000000, ((RMIBootstrapCacheLoader) bootstrapCacheLoader1)
679                 .getMaximumChunkSizeBytes());
680 
681     }
682 
683     /***
684      * Does clone work ok?
685      */
686     @Test
687     public void testCachesCreatedFromDefaultDoNotInteract() {
688         singletonManager = CacheManager
689                 .create(AbstractCacheTest.TEST_CONFIG_DIR
690                         + "distribution/ehcache-distributed1.xml");
691         singletonManager.addCache("newfromdefault1");
692         Cache newfromdefault1 = singletonManager.getCache("newfromdefault1");
693         singletonManager.addCache("newfromdefault2");
694         Cache newfromdefault2 = singletonManager.getCache("newfromdefault2");
695 
696         assertTrue(newfromdefault1 != newfromdefault2);
697         assertFalse(newfromdefault1.getName().equals(newfromdefault2.getName()));
698         // status is an enum style class, so it ok for them to point to the same
699         // instance if they are the same
700         assertTrue(newfromdefault1.getStatus() == newfromdefault2.getStatus());
701         assertFalse(newfromdefault1.getGuid() == newfromdefault2.getGuid());
702     }
703 
704     /***
705      * Test using a cache which has been removed and replaced.
706      */
707     @Test
708     public void testStaleCacheReference() throws CacheException {
709         singletonManager = CacheManager.create();
710         singletonManager.addCache("test");
711         Ehcache cache = singletonManager.getCache("test");
712         assertNotNull(cache);
713         cache.put(new Element("key1", "value1"));
714 
715         assertEquals("value1", cache.get("key1").getObjectValue());
716         singletonManager.removeCache("test");
717         singletonManager.addCache("test");
718 
719         try {
720             cache.get("key1");
721             fail();
722         } catch (IllegalStateException e) {
723             assertEquals("The test Cache is not alive.", e.getMessage());
724         }
725     }
726 
727     private int countThreads() {
728         return JVMUtil.enumerateThreads().size();
729     }
730 
731     /***
732      * Shows that a decorated cache can be substituted
733      */
734     @Test
735     public void testDecoratorRequiresDecoratedCache() {
736 
737         singletonManager = CacheManager.create();
738         Ehcache cache = singletonManager.getEhcache("sampleCache1");
739         // decorate and substitute
740         BlockingCache newBlockingCache = new BlockingCache(cache);
741         singletonManager
742                 .replaceCacheWithDecoratedCache(cache, newBlockingCache);
743         Ehcache blockingCache = singletonManager.getEhcache("sampleCache1");
744         assertNull(singletonManager.getCache("sampleCache1"));
745         blockingCache.get("unknownkey");
746         assertTrue(singletonManager.getEhcache("sampleCache1") == newBlockingCache);
747     }
748 
749     /***
750      * Shows that a decorated cache can be substituted
751      */
752     @Test
753     public void testDecoratorFailsIfUnderlyingCacheNotSame() {
754 
755         singletonManager = CacheManager.create();
756         Ehcache cache = singletonManager.getEhcache("sampleCache1");
757         Ehcache cache2 = singletonManager.getEhcache("sampleCache2");
758         // decorate and substitute
759         BlockingCache newBlockingCache = new BlockingCache(cache2);
760         try {
761             singletonManager.replaceCacheWithDecoratedCache(cache,
762                     newBlockingCache);
763         } catch (CacheException e) {
764             // expected
765         }
766         assertNotNull(singletonManager.getCache("sampleCache1"));
767     }
768 
769     @Test
770     public void testDecoratorFailsIfUnderlyingCacheHasChanged() {
771 
772         singletonManager = CacheManager.create();
773         Ehcache cache = singletonManager.getEhcache("sampleCache1");
774         singletonManager.removeCache("sampleCache1");
775         singletonManager.addCache("sampleCache1");
776         // decorate and substitute
777         BlockingCache newBlockingCache = new BlockingCache(cache);
778         try {
779             singletonManager.replaceCacheWithDecoratedCache(cache,
780                     newBlockingCache);
781             fail("This should throw an exception!");
782         } catch (CacheException e) {
783             // expected
784         }
785         assertFalse(singletonManager.getEhcache("sampleCache1") instanceof BlockingCache);
786     }
787 
788     @Test
789     public void testDecoratorFailsIfUnderlyingCacheIsNotPresent() {
790 
791         singletonManager = CacheManager.create();
792         Ehcache cache = singletonManager.getEhcache("sampleCache1");
793         singletonManager.removeCache("sampleCache1");
794         // decorate and substitute
795         BlockingCache newBlockingCache = new BlockingCache(cache);
796         try {
797             singletonManager.replaceCacheWithDecoratedCache(cache,
798                     newBlockingCache);
799             fail("This should throw an exception!");
800         } catch (CacheException e) {
801             // expected
802         }
803         assertFalse(singletonManager.getEhcache("sampleCache1") instanceof BlockingCache);
804     }
805 
806     /***
807      * Shows that a decorated cache has decorated behaviour for methods that
808      * override Cache methods, without requiring a cast.
809      */
810     @Test
811     public void testDecoratorOverridesDefaultBehaviour() {
812 
813         singletonManager = CacheManager.create();
814         Ehcache cache = singletonManager.getEhcache("sampleCache1");
815         Element element = cache.get("key");
816         // default behaviour for a missing key
817         assertNull(element);
818 
819         // decorate and substitute
820         SelfPopulatingCache selfPopulatingCache = new SelfPopulatingCache(
821                 cache, new CountingCacheEntryFactory("value"));
822         selfPopulatingCache.get("key");
823         singletonManager.replaceCacheWithDecoratedCache(cache,
824                 selfPopulatingCache);
825 
826         Ehcache decoratedCache = singletonManager.getEhcache("sampleCache1");
827         assertNull(singletonManager.getCache("sampleCache1"));
828         Element element2 = cache.get("key");
829         assertEquals("value", element2.getObjectValue());
830     }
831 
832     /***
833      * Test added after bug with multiple cachemanagers and programmatic cache
834      * creation
835      */
836     @Test
837     public void testMultipleCacheManagers() {
838         CacheManager[] managers = new CacheManager[2];
839         managers[0] = new CacheManager(makeCacheManagerConfig());
840         managers[1] = new CacheManager(makeCacheManagerConfig());
841 
842         managers[0].shutdown();
843         managers[1].shutdown();
844 
845     }
846 
847     private static Configuration makeCacheManagerConfig() {
848         Configuration config = new Configuration();
849         CacheConfiguration defaults = new CacheConfiguration("cacheName", 10)
850             .eternal(true);
851         config.setDefaultCacheConfiguration(defaults);
852         return config;
853     }
854 
855     /***
856      * Make sure we can manipulate tmpdir. This is so continous integration
857      * builds can get the disk path zapped each run.
858      */
859     @Test
860     public void testTmpDir() {
861         String tmp = System.getProperty("java.io.tmpdir");
862         System.setProperty("java.io.tmpdir", "greg");
863         assertEquals("greg", System.getProperty("java.io.tmpdir"));
864         System.setProperty("java.io.tmpdir", tmp);
865         assertEquals(tmp, System.getProperty("java.io.tmpdir"));
866 
867     }
868 
869     /***
870      * Ehcache 1.5 allows the diskStore element to be optional. Check that is is null
871      * Add different cache constructors to make sure none inadvertently create a disk store
872      */
873     @Test
874     public void testCacheManagerWithNoDiskCachesFromConfiguration() throws CacheException, InterruptedException {
875         LOG.info(System.getProperty("java.io.tmpdir"));
876         singletonManager = CacheManager.create(AbstractCacheTest.TEST_CONFIG_DIR + "ehcache-nodisk.xml");
877         singletonManager.addCache("jsecurity-activeSessionCache");
878         Cache cacheA = singletonManager.getCache("jsecurity-activeSessionCache");
879         Cache cacheB = new Cache("1", 10, false, false, 2, 2);
880         singletonManager.addCache(cacheB);
881         Cache cacheC = new Cache("2", 10, false, false, 2, 2, false, 100);
882         singletonManager.addCache(cacheC);
883         for(int i = 0; i < 100; i++) {
884             cacheA.put(new Element(i + "", "dog"));
885             cacheB.put(new Element(i + "", "dog"));
886             cacheC.put(new Element(i + "", "dog"));
887         }
888         Cache diskCache = new Cache("disk", 10, true, false, 2, 2);
889         try {
890           singletonManager.addCache(diskCache);
891           throw new AssertionError("Expected that adding a disk cache to a cache manager with no configured disk store path would throw CacheException");
892         } catch (CacheException e) {
893           LOG.info("Caught expected exception", e);
894         }
895         singletonManager.shutdown();
896         assertEquals(null, singletonManager.getDiskStorePath());
897     }
898 
899     /***
900      * I have suggested that people can rely on the thread names to change
901      * priorities etc. The names should stay fixed.
902      */
903     @Test
904     public void testThreadNamingAndManipulation() {
905 
906         singletonManager = CacheManager.create();
907 
908         List threads = JVMUtil.enumerateThreads();
909 
910         for (int i = 0; i < threads.size(); i++) {
911             Thread thread = (Thread) threads.get(i);
912             String name = thread.getName();
913             LOG.info(name);
914         }
915     }
916 
917     /***
918      * Tests that the CacheManager implements clearAll():void and clearAllStartingWith(String):void properly
919      */
920     @Test
921     public void testClearCacheManager() throws CacheException {
922         singletonManager = CacheManager.create();
923         assertNotNull(singletonManager);
924         assertEquals(14, singletonManager.getCacheNames().length);
925         singletonManager.getEhcache("sampleCache1").put(new Element("key1", "value"));
926         assertEquals(1, singletonManager.getEhcache("sampleCache1").getSize());
927         singletonManager.getEhcache("sampleCache2").put(new Element("key2", "value"));
928         assertEquals(1, singletonManager.getEhcache("sampleCache2").getSize());
929         singletonManager.getEhcache("CachedLogin").put(new Element("key3", "value"));
930         assertEquals(1, singletonManager.getEhcache("CachedLogin").getSize());
931         singletonManager.clearAllStartingWith("");
932         assertEquals(1, singletonManager.getEhcache("sampleCache1").getSize());
933         assertEquals(1, singletonManager.getEhcache("sampleCache2").getSize());
934         assertEquals(1, singletonManager.getEhcache("CachedLogin").getSize());
935         singletonManager.clearAllStartingWith("sample");
936         assertEquals(0, singletonManager.getEhcache("sampleCache1").getSize());
937         assertEquals(0, singletonManager.getEhcache("sampleCache2").getSize());
938         assertEquals(1, singletonManager.getEhcache("CachedLogin").getSize());
939         singletonManager.clearAll();
940         assertEquals(0, singletonManager.getEhcache("sampleCache1").getSize());
941         assertEquals(0, singletonManager.getEhcache("sampleCache2").getSize());
942         assertEquals(0, singletonManager.getEhcache("CachedLogin").getSize());
943     }
944 
945 }