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