KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > turbine > services > cache > TurbineCacheTest


1 package org.apache.turbine.services.cache;
2  /*
3  * Copyright 2001-2004 The Apache Software Foundation.
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License")
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  * http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */

17
18 // Cactus and Junit imports
19
import junit.awtui.TestRunner;
20 import junit.framework.Test;
21 import junit.framework.TestSuite;
22 import org.apache.cactus.ServletTestCase;
23
24 // Turbine imports
25
import org.apache.turbine.services.TurbineServices;
26 import org.apache.turbine.services.cache.GlobalCacheService;
27 import org.apache.turbine.services.cache.CachedObject;
28 import org.apache.turbine.services.cache.ObjectExpiredException;
29 import org.apache.turbine.services.cache.Refreshable;
30 import org.apache.turbine.services.cache.RefreshableCachedObject;
31 import org.apache.turbine.Turbine;
32
33 /**
34  * TurbineCacheTest
35  *
36  * @author <a HREF="paulsp@apache.org">Paul Spencer</a>
37  * @version $Id: TurbineCacheTest.java,v 1.2.4.2 2004/05/20 03:30:06 seade Exp $
38  */

39 public class TurbineCacheTest extends ServletTestCase {
40     
41     private Turbine turbine = null;
42     private static final String JavaDoc cacheKey = new String JavaDoc("CacheKey");
43     private static final String JavaDoc cacheKey_2 = new String JavaDoc("CacheKey_2");
44     private static final long TURBINE_CACHE_REFRESH = 5000; // in millis
45
private static final long TEST_EXPIRETIME = TURBINE_CACHE_REFRESH + 1000;
46     private static final long TEST_TIMETOLIVE = TEST_EXPIRETIME * 5;
47     /**
48      * Defines the testcase name for JUnit.
49      *
50      * @param name the testcase's name.
51      */

52     public TurbineCacheTest( String JavaDoc name )
53     {
54         super( name );
55     }
56     
57     /**
58      * Start the tests.
59      *
60      * @param args the arguments. Not used
61      */

62     public static void main(String JavaDoc args[])
63     {
64         TestRunner.main(new String JavaDoc[] { TurbineCacheTest.class.getName() });
65     }
66
67     /**
68      * Creates the test suite.
69      *
70      * @return a test suite (<code>TestSuite</code>) that includes all methods
71      * starting with "test"
72      */

73     public static Test suite()
74     {
75         // All methods starting with "test" will be executed in the test suite.
76
return new TestSuite( TurbineCacheTest.class );
77     }
78
79     /**
80      * This setup will be running server side. We startup Turbine and
81      * get our test port from the properties. This gets run before
82      * each testXXX test.
83      */

84     protected void setUp()
85         throws Exception JavaDoc
86     {
87         super.setUp();
88         config.setInitParameter("properties",
89                 "/WEB-INF/conf/TurbineCacheTest.properties");
90         turbine = new Turbine();
91         turbine.init(config);
92     }
93
94     /**
95      * After each testXXX test runs, shut down the Turbine servlet.
96      */

97     protected void tearDown()
98         throws Exception JavaDoc
99     {
100         turbine.destroy();
101         super.tearDown();
102     }
103     
104     /**
105      * Simple test that verify an object can be created and deleted.
106      * @throws Exception
107      */

108     public void testSimpleAddGetCacheObject() throws Exception JavaDoc
109     {
110         String JavaDoc testString = new String JavaDoc( "This is a test");
111         Object JavaDoc retrievedObject = null;
112         CachedObject cacheObject1 = null;
113         
114         GlobalCacheService globalCache = (GlobalCacheService)TurbineServices
115         .getInstance()
116         .getService( GlobalCacheService.SERVICE_NAME );
117         
118         // Create object
119
cacheObject1 = new CachedObject(testString);
120         assertNotNull( "Failed to create a cachable object 1", cacheObject1);
121         
122         // Add object to cache
123
globalCache.addObject(cacheKey, cacheObject1);
124         
125         // Get object from cache
126
retrievedObject = globalCache.getObject(cacheKey);
127         assertNotNull( "Did not retrieved a cached object 1", retrievedObject);
128         assertTrue( "Did not retrieved a correct, expected cached object 1", retrievedObject == cacheObject1);
129         
130         // Remove object from cache
131
globalCache.removeObject(cacheKey);
132         
133         // Verify object removed from cache
134
retrievedObject = null;
135         cacheObject1 = null;
136         try
137         {
138             retrievedObject = globalCache.getObject(cacheKey);
139             assertNull( "Retrieved the deleted cached object 1 and did not get expected ObjectExpiredException", retrievedObject);
140             assertNotNull( "Did not get expected ObjectExpiredException retrieving a deleted object", retrievedObject);
141         }
142         catch (ObjectExpiredException e)
143         {
144             assertNull( "Retrieved the deleted cached object 1, but caught expected ObjectExpiredException exception", retrievedObject);
145         }
146         catch (Exception JavaDoc e)
147         {
148             throw e;
149         }
150         
151         // Remove object from cache that does NOT exist in the cache
152
globalCache.removeObject(cacheKey);
153     }
154     
155     /**
156      * Simple test that adds, retrieves, and deletes 2 object.
157      *
158      * @throws Exception
159      */

160     public void test2ObjectAddGetCachedObject() throws Exception JavaDoc
161     {
162         String JavaDoc testString = new String JavaDoc( "This is a test");
163         Object JavaDoc retrievedObject = null;
164         CachedObject cacheObject1 = null;
165         CachedObject cacheObject2 = null;
166         
167         GlobalCacheService globalCache = (GlobalCacheService)TurbineServices
168         .getInstance()
169         .getService( GlobalCacheService.SERVICE_NAME );
170         
171         // Create and add Object #1
172
cacheObject1 = new CachedObject(testString);
173         assertNotNull( "Failed to create a cachable object 1", cacheObject1);
174         globalCache.addObject(cacheKey, cacheObject1);
175         retrievedObject = globalCache.getObject(cacheKey);
176         assertNotNull( "Did not retrieved a cached object 1", retrievedObject);
177         assertEquals( "Did not retrieved correct cached object", cacheObject1, retrievedObject);
178         
179         // Create and add Object #2
180
cacheObject2 = new CachedObject(testString);
181         assertNotNull( "Failed to create a cachable object 2", cacheObject2);
182         globalCache.addObject(cacheKey_2, cacheObject2);
183         retrievedObject = globalCache.getObject(cacheKey_2);
184         assertNotNull( "Did not retrieved a cached object 2", retrievedObject);
185         assertEquals( "Did not retrieved correct cached object 2", cacheObject2, retrievedObject);
186         
187         // Get object #1
188
retrievedObject = globalCache.getObject(cacheKey);
189         assertNotNull( "Did not retrieved a cached object 1. Attempt #2", retrievedObject);
190         assertEquals( "Did not retrieved correct cached object 1. Attempt #2", cacheObject1, retrievedObject);
191         
192         // Get object #1
193
retrievedObject = globalCache.getObject(cacheKey);
194         assertNotNull( "Did not retrieved a cached object 1. Attempt #3", retrievedObject);
195         assertEquals( "Did not retrieved correct cached object 1. Attempt #3", cacheObject1, retrievedObject);
196         
197         // Get object #2
198
retrievedObject = globalCache.getObject(cacheKey_2);
199         assertNotNull( "Did not retrieved a cached object 2. Attempt #2", retrievedObject);
200         assertEquals( "Did not retrieved correct cached object 2 Attempt #2", cacheObject2, retrievedObject);
201         
202         // Remove objects
203
globalCache.removeObject(cacheKey);
204         globalCache.removeObject(cacheKey_2);
205     }
206     
207     /**
208      * Verify that an object will throw the ObjectExpiredException
209      * when it now longer exists in cache.
210      *
211      * @throws Exception
212      */

213     public void testObjectExpiration() throws Exception JavaDoc
214     {
215         String JavaDoc testString = new String JavaDoc( "This is a test");
216         Object JavaDoc retrievedObject = null;
217         CachedObject cacheObject = null;
218         
219         GlobalCacheService globalCache = (GlobalCacheService)TurbineServices
220         .getInstance()
221         .getService( GlobalCacheService.SERVICE_NAME );
222         
223         // Create and add Object that expires in 1000 millis (1 second)
224
cacheObject = new CachedObject(testString, 1000);
225         assertNotNull( "Failed to create a cachable object", cacheObject);
226         long addTime = System.currentTimeMillis();
227         globalCache.addObject(cacheKey, cacheObject);
228         
229         // Try to get un-expired object
230
try
231         {
232             retrievedObject = null;
233             retrievedObject = globalCache.getObject(cacheKey);
234             assertNotNull( "Did not retrieved a cached object", retrievedObject);
235             assertEquals( "Did not retrieved correct cached object", cacheObject, retrievedObject);
236         }
237         catch (ObjectExpiredException e)
238         {
239             assertTrue( "Object expired early ( " + (System.currentTimeMillis() - addTime) + " millis)", false);
240         }
241         catch (Exception JavaDoc e)
242         {
243             throw e;
244         }
245         
246         // Sleep 1500 Millis (1.5 seconds)
247
Thread.sleep(1500);
248         
249         // Try to get expired object
250
try
251         {
252             retrievedObject = null;
253             retrievedObject = globalCache.getObject(cacheKey);
254             assertNull( "Retrieved the expired cached object and did not get expected ObjectExpiredException", retrievedObject);
255             assertNotNull( "Did not get expected ObjectExpiredException retrieving an expired object", retrievedObject);
256         }
257         catch (ObjectExpiredException e)
258         {
259             assertNull( "Retrieved the expired cached object, but caught expected ObjectExpiredException exception", retrievedObject);
260         }
261         catch (Exception JavaDoc e)
262         {
263             throw e;
264         }
265         
266         // Remove objects
267
globalCache.removeObject(cacheKey);
268     }
269
270     /**
271      * Verify the all object will be flushed from the cache.
272      *
273      * This test can take server minutes.
274      *
275      * @throws Exception
276      */

277     public void testCacheFlush() throws Exception JavaDoc
278     {
279         String JavaDoc testString = new String JavaDoc( "This is a test");
280         Object JavaDoc retrievedObject = null;
281         CachedObject cacheObject = null;
282         
283         GlobalCacheService globalCache = (GlobalCacheService)TurbineServices
284         .getInstance()
285         .getService( GlobalCacheService.SERVICE_NAME );
286         
287         // Create and add Object that expires in 1 turbine Refresh + 1 millis
288
cacheObject = new CachedObject(testString, (TURBINE_CACHE_REFRESH*5) + 1);
289         assertNotNull( "Failed to create a cachable object", cacheObject);
290         long addTime = System.currentTimeMillis();
291         globalCache.addObject(cacheKey, cacheObject);
292                 
293         // 1 Refresh
294
Thread.sleep(TURBINE_CACHE_REFRESH + 1);
295         assertTrue("No object in cache before flush", (0 < globalCache.getNumberOfObjects()));
296         
297         // Flush Cache
298
globalCache.flushCache();
299
300         // Wait 15 seconds, 3 Refresh
301
Thread.sleep((TURBINE_CACHE_REFRESH * 2) + 1);
302         assertEquals("After refresh", 0, globalCache.getNumberOfObjects());
303         
304         // Remove objects
305
globalCache.removeObject(cacheKey);
306     }
307
308     /**
309      * Verify the Cache count is correct.
310      * @throws Exception
311      */

312     public void testObjectCount() throws Exception JavaDoc
313     {
314         GlobalCacheService globalCache = (GlobalCacheService)TurbineServices
315         .getInstance()
316         .getService( GlobalCacheService.SERVICE_NAME );
317         assertNotNull("Could not retrive cache service.", globalCache);
318
319         // Create and add Object that expires in 1.5 turbine Refresh
320
long expireTime = TURBINE_CACHE_REFRESH + TURBINE_CACHE_REFRESH/2;
321         CachedObject cacheObject = new CachedObject("This is a test", expireTime);
322         assertNotNull( "Failed to create a cachable object", cacheObject);
323
324         globalCache.addObject(cacheKey, cacheObject);
325         assertEquals("After adding 1 Object", 1, globalCache.getNumberOfObjects());
326         
327         // Wait until we're passed 1 refresh, but not half way.
328
Thread.sleep(TURBINE_CACHE_REFRESH + TURBINE_CACHE_REFRESH/3);
329         assertEquals("After one refresh", 1, globalCache.getNumberOfObjects());
330
331         // Wait until we're passed 2 more refreshes
332
Thread.sleep((TURBINE_CACHE_REFRESH * 2) + TURBINE_CACHE_REFRESH/3);
333         assertEquals("After three refreshes", 0, globalCache.getNumberOfObjects());
334     }
335
336     /**
337      * Verfy a refreshable object will refreshed in the following cases:
338      * o The object is retrieved via getObject an it is stale.
339      * o The object is determied to be stale during a cache
340      * refresh
341      *
342      * This test can take serveral minutes.
343      *
344      * @throws Exception
345      */

346     public void testRefreshableObject() throws Exception JavaDoc
347     {
348         String JavaDoc testString = new String JavaDoc( "This is a test");
349         Object JavaDoc retrievedObject = null;
350         RefreshableCachedObject cacheObject = null;
351         
352         GlobalCacheService globalCache = (GlobalCacheService)TurbineServices
353         .getInstance()
354         .getService( GlobalCacheService.SERVICE_NAME );
355         
356         // Create and add Object that expires in TEST_EXPIRETIME millis.
357
cacheObject = new RefreshableCachedObject(new RefreshableObject(), TEST_EXPIRETIME);
358         assertNotNull( "Failed to create a cachable object", cacheObject);
359         long addTime = System.currentTimeMillis();
360         globalCache.addObject(cacheKey, cacheObject);
361         
362         // Try to get un-expired object
363
try
364         {
365             retrievedObject = null;
366             retrievedObject = globalCache.getObject(cacheKey);
367             assertNotNull( "Did not retrieved a cached object", retrievedObject);
368             assertEquals( "Did not retrieved correct cached object", cacheObject, retrievedObject);
369         }
370         catch (ObjectExpiredException e)
371         {
372             assertTrue( "Object expired early ( " + (System.currentTimeMillis() - addTime) + " millis)", false);
373         }
374         catch (Exception JavaDoc e)
375         {
376             throw e;
377         }
378         
379         // Wait 1 Turbine cache refresh + 1 second.
380
Thread.sleep(TEST_EXPIRETIME + 1000);
381         
382         // Try to get expired object
383
try
384         {
385             retrievedObject = null;
386             retrievedObject = globalCache.getObject(cacheKey);
387             assertNotNull( "Did not retrieved a cached object, after sleep", retrievedObject);
388             assertNotNull( "Cached object has no contents, after sleep.", ((RefreshableCachedObject)retrievedObject).getContents());
389             assertTrue( "Object did not refresh.", ( ((RefreshableObject)((RefreshableCachedObject)retrievedObject).getContents()).getRefreshCount() > 0));
390         }
391         catch (ObjectExpiredException e)
392         {
393             assertTrue( "Received unexpected ObjectExpiredException exception "
394             + "when retrieving refreshable object after ( "
395             + (System.currentTimeMillis() - addTime) + " millis)", false);
396         }
397         catch (Exception JavaDoc e)
398         {
399             throw e;
400         }
401         
402         // See if object will expires (testing every second for 100 seconds. It sould not!
403
for (int i=0; i<100; i++)
404         {
405             Thread.sleep(1000); // Sleep 0.5 seconds
406

407             // Try to get expired object
408
try
409             {
410                 retrievedObject = null;
411                 retrievedObject = globalCache.getObject(cacheKey);
412                 assertNotNull( "Did not retrieved a cached object, after sleep", retrievedObject);
413                 assertNotNull( "Cached object has no contents, after sleep.", ((RefreshableCachedObject)retrievedObject).getContents());
414                 assertTrue( "Object did not refresh.", ( ((RefreshableObject)((RefreshableCachedObject)retrievedObject).getContents()).getRefreshCount() > 0));
415             }
416             catch (ObjectExpiredException e)
417             {
418                 assertTrue( "Received unexpected ObjectExpiredException exception "
419                 + "when retrieving refreshable object after ( "
420                 + (System.currentTimeMillis() - addTime) + " millis)", false);
421             }
422             catch (Exception JavaDoc e)
423             {
424                 throw e;
425             }
426         }
427         // Remove objects
428
globalCache.removeObject(cacheKey);
429     }
430     
431     /**
432      * Verify a cached object will be delete after it has been
433      * untouched beyond it's TimeToLive.
434      *
435      * This test can take serveral minutes.
436      *
437      * @throws Exception
438      */

439     public void testRefreshableTimeToLive() throws Exception JavaDoc
440     {
441         String JavaDoc testString = new String JavaDoc( "This is a test");
442         Object JavaDoc retrievedObject = null;
443         RefreshableCachedObject cacheObject = null;
444         
445         GlobalCacheService globalCache = (GlobalCacheService)TurbineServices
446         .getInstance()
447         .getService( GlobalCacheService.SERVICE_NAME );
448         
449         // Create and add Object that expires in TEST_EXPIRETIME millis.
450
cacheObject = new RefreshableCachedObject(new RefreshableObject(), TEST_EXPIRETIME);
451         assertNotNull( "Failed to create a cachable object", cacheObject);
452         cacheObject.setTTL(TEST_TIMETOLIVE);
453
454         // Verify TimeToLive was set
455
assertEquals( "Returned TimeToLive", TEST_TIMETOLIVE, cacheObject.getTTL());
456
457         // Add object to Cache
458
long addTime = System.currentTimeMillis();
459         globalCache.addObject(cacheKey, cacheObject);
460         
461         // Try to get un-expired object
462
try
463         {
464             retrievedObject = null;
465             retrievedObject = globalCache.getObject(cacheKey);
466             assertNotNull( "Did not retrieved a cached object", retrievedObject);
467             assertEquals( "Did not retrieved correct cached object", cacheObject, retrievedObject);
468         }
469         catch (ObjectExpiredException e)
470         {
471             assertTrue( "Object expired early ( " + (System.currentTimeMillis() - addTime) + " millis)", false);
472         }
473         catch (Exception JavaDoc e)
474         {
475             throw e;
476         }
477         
478         // Wait long enough to allow object to expire, but do not exceed TTL
479
Thread.sleep(TEST_TIMETOLIVE - 2000);
480         
481         // Try to get expired object
482
try
483         {
484             retrievedObject = null;
485             retrievedObject = globalCache.getObject(cacheKey);
486             assertNotNull( "Did not retrieved a cached object, after sleep", retrievedObject);
487             assertNotNull( "Cached object has no contents, after sleep.", ((RefreshableCachedObject)retrievedObject).getContents());
488             assertTrue( "Object did not refresh.", ( ((RefreshableObject)((RefreshableCachedObject)retrievedObject).getContents()).getRefreshCount() > 0));
489         }
490         catch (ObjectExpiredException e)
491         {
492             assertTrue( "Received unexpected ObjectExpiredException exception "
493             + "when retrieving refreshable object after ( "
494             + (System.currentTimeMillis() - addTime) + " millis)", false);
495         }
496         catch (Exception JavaDoc e)
497         {
498             throw e;
499         }
500         
501         // Wait long enough to allow object to expire and exceed TTL
502
Thread.sleep(TEST_TIMETOLIVE +5000);
503         
504         // Try to get expired object
505
try
506         {
507             retrievedObject = null;
508             retrievedObject = globalCache.getObject(cacheKey);
509             assertNull( "Retrieved a cached object, after exceeding TimeToLive", retrievedObject);
510         }
511         catch (ObjectExpiredException e)
512         {
513             assertNull( "Retrieved the expired cached object, but caught expected ObjectExpiredException exception", retrievedObject);
514         }
515         catch (Exception JavaDoc e)
516         {
517             throw e;
518         }
519     }
520
521     /**
522      * Simple object that can be refreshed
523      */

524     class RefreshableObject implements Refreshable
525     {
526         
527         private int refreshCount = 0;
528         
529         /**
530          * Increment the refresh counter
531          */

532         public void refresh()
533         {
534             this.refreshCount++;
535         }
536         
537         /**
538          * Reutrn the number of time this object has been refreshed
539          *
540          * @return Number of times refresh() has been called
541          */

542         public int getRefreshCount()
543         {
544             return this.refreshCount;
545         }
546     }
547 }
548
Popular Tags