KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > opensymphony > oscache > general > TestGeneralCacheAdministrator


1 /*
2  * Copyright (c) 2002-2003 by OpenSymphony
3  * All rights reserved.
4  */

5 package com.opensymphony.oscache.general;
6
7 import java.util.Date JavaDoc;
8
9 import com.opensymphony.oscache.base.*;
10 import com.opensymphony.oscache.base.events.CacheEntryEventListener;
11 import com.opensymphony.oscache.base.events.CacheMapAccessEventListener;
12 import com.opensymphony.oscache.extra.CacheEntryEventListenerImpl;
13 import com.opensymphony.oscache.extra.CacheMapAccessEventListenerImpl;
14
15 import junit.framework.Test;
16 import junit.framework.TestSuite;
17
18 /**
19  * Test all the public methods of the GeneralCacheAdministrator class. Since
20  * this class extends the TestAbstractCacheAdministrator class, the
21  * AbstractCacheAdministrator is tested when invoking this class.
22  *
23  * $Id: TestGeneralCacheAdministrator.java,v 1.2 2006/04/09 12:50:34 ltorunski Exp $
24  * @version $Revision: 1.2 $
25  * @author <a HREF="mailto:abergevin@pyxis-tech.com">Alain Bergevin</a>
26  */

27 public class TestGeneralCacheAdministrator extends TestAbstractCacheAdministrator {
28     // Constants used thru all the tests
29
private static final String JavaDoc KEY = "Test General Cache Admin Key";
30     private static final int NO_REFRESH_NEEDED = CacheEntry.INDEFINITE_EXPIRY;
31     private static final int REFRESH_NEEDED = 0;
32     private static final String JavaDoc CONTENT = "Content for the general cache admin test";
33     private static final String JavaDoc WILL_NOT_FLUSH_PATTERN = "This key won't flush";
34     private static final String JavaDoc GROUP1 = "group1";
35     private static final String JavaDoc GROUP2 = "group2";
36     private static final String JavaDoc GROUP3 = "group3";
37
38     // Constants for listener counters
39
private static final int NB_CACHE_HITS = 7;
40     private static final int NB_CACHE_STALE_HITS = 7;
41     private static final int NB_CACHE_MISSED = 1;
42     private static final int NB_ADD = 7;
43     private static final int NB_UPDATED = 2;
44     private static final int NB_FLUSH = 3;
45     private static final int NB_REMOVED = 0;
46     private static final int NB_GROUP_FLUSH = 2;
47     private static final int NB_PATTERN_FLUSH = 1;
48
49     // Static instance of a cache administrator
50
static GeneralCacheAdministrator admin = null;
51
52     // Declare the listeners
53
private CacheEntryEventListenerImpl cacheEntryEventListener = null;
54     private CacheMapAccessEventListenerImpl cacheMapAccessEventListener = null;
55
56     /**
57      * Class constructor
58      * <p>
59      * @param str Test name (required by JUnit)
60      */

61     public TestGeneralCacheAdministrator(String JavaDoc str) {
62         super(str);
63     }
64
65     /**
66      * Test suite required to test this project
67      * <p>
68      * @return suite The test suite
69      */

70     public static Test suite() {
71         return new TestSuite(TestGeneralCacheAdministrator.class);
72     }
73
74     /**
75      * Abstract method used by the TestAbstractCacheAdministrator class
76      * <p>
77      * @return An administrator instance
78      */

79     public AbstractCacheAdministrator getAdmin() {
80         return admin;
81     }
82
83     /**
84      * This method is invoked before each testXXXX methods of the
85      * class. It set ups the variables required for each tests.
86      */

87     public void setUp() {
88         // At first invocation, create a administrator
89
admin = new GeneralCacheAdministrator();
90         assertNotNull(admin);
91         cacheEntryEventListener = new CacheEntryEventListenerImpl();
92         cacheMapAccessEventListener = new CacheMapAccessEventListenerImpl();
93
94         // Register the listeners on the cache map
95
admin.getCache().addCacheEventListener(cacheEntryEventListener, CacheEntryEventListener.class);
96         admin.getCache().addCacheEventListener(cacheMapAccessEventListener, CacheMapAccessEventListener.class);
97     }
98
99     /**
100      * Validate the CacheEntryEventListener's data
101      */

102     public void testCacheEntryEventListenerCounters() {
103         populate();
104         assertEquals(NB_ADD, cacheEntryEventListener.getEntryAddedCount());
105         assertEquals(NB_REMOVED, cacheEntryEventListener.getEntryRemovedCount());
106         assertEquals(NB_UPDATED, cacheEntryEventListener.getEntryUpdatedCount());
107         assertEquals(NB_GROUP_FLUSH, cacheEntryEventListener.getGroupFlushedCount());
108         assertEquals(NB_PATTERN_FLUSH, cacheEntryEventListener.getPatternFlushedCount());
109         assertEquals(NB_FLUSH, cacheEntryEventListener.getEntryFlushedCount());
110     }
111
112     /**
113      * Validate the CacheEntryEventListener's data
114      */

115     public void testCacheMapAccessEventListenerCounters() {
116         populate();
117
118         int missCount = cacheMapAccessEventListener.getMissCount();
119
120         if (NB_CACHE_MISSED != missCount) {
121             fail("We expected " + NB_CACHE_MISSED + " misses but got " + missCount + "." + " This is probably due to existing disk cache, delete it and re-run" + " the test");
122         }
123
124         assertEquals(NB_CACHE_HITS, cacheMapAccessEventListener.getHitCount());
125         assertEquals(NB_CACHE_STALE_HITS, cacheMapAccessEventListener.getStaleHitCount());
126     }
127
128     /**
129      * Ensure that item may be flushed by key pattern
130      */

131     public void testFlushPattern() {
132         // Put some content in cache
133
admin.putInCache(KEY, CONTENT);
134
135         // Call flush pattern with parameters that must NOT flush our object
136
admin.flushPattern(WILL_NOT_FLUSH_PATTERN);
137         admin.flushPattern("");
138         admin.flushPattern(null);
139
140         // Ensure that our object is not gone
141
assertNotNull(checkObj(KEY, NO_REFRESH_NEEDED, false));
142
143         // This time we flush it for real
144
admin.flushPattern(KEY.substring(1, 2));
145         assertNotNull(checkObj(KEY, NO_REFRESH_NEEDED, true));
146     }
147
148     /**
149      * Ensure that the cache groupings work correctly
150      */

151     public void testGroups() {
152         // Flush a non-existent group - should be OK and will still fire a GROUP_FLUSHED event
153
admin.flushGroup(GROUP1);
154
155         // Add some items to various group combinations
156
admin.putInCache("1", "item 1"); // No groups
157
admin.putInCache("2", "item 2", new String JavaDoc[] {GROUP1}); // Just group 1
158
admin.putInCache("3", "item 3", new String JavaDoc[] {GROUP2}); // Just group 2
159
admin.putInCache("4", "item 4", new String JavaDoc[] {GROUP1, GROUP2}); // groups 1 & 2
160
admin.putInCache("5", "item 5", new String JavaDoc[] {GROUP1, GROUP2, GROUP3}); // groups 1,2 & 3
161

162         admin.flushGroup(GROUP3); // This should flush item 5 only
163
assertNotNull(checkObj("5", NO_REFRESH_NEEDED, true));
164         assertNotNull(checkObj("4", NO_REFRESH_NEEDED, false));
165
166         admin.flushGroup(GROUP2); // This should flush items 3 and 4
167
assertNotNull(checkObj("1", NO_REFRESH_NEEDED, false));
168         assertNotNull(checkObj("2", NO_REFRESH_NEEDED, false));
169         assertNotNull(checkObj("3", NO_REFRESH_NEEDED, true));
170         assertNotNull(checkObj("4", NO_REFRESH_NEEDED, true));
171
172         admin.flushGroup(GROUP1); // Flushes item 2
173
assertNotNull(checkObj("1", NO_REFRESH_NEEDED, false));
174         assertNotNull(checkObj("2", NO_REFRESH_NEEDED, true));
175
176         // Test if regrouping a cache entry works
177
admin.putInCache("A", "ABC", new String JavaDoc[] {"A"});
178         admin.putInCache("A", "ABC", new String JavaDoc[] {"A", "B"});
179         admin.putInCache("B", "DEF", new String JavaDoc[] {"B"});
180         admin.flushGroup("B");
181         assertNotNull(checkObj("A", NO_REFRESH_NEEDED, true));
182     }
183
184     /**
185      * Test the main cache functionalities, which are storing and retrieving objects
186      * from it
187      */

188     public void testPutInCacheAndGetFromCache() {
189         // Put some item in cache and get it back right away. It should not need
190
// to be refreshed
191
admin.putInCache(KEY, CONTENT);
192
193         String JavaDoc cacheContent = (String JavaDoc) checkObj(KEY, NO_REFRESH_NEEDED, false);
194         assertTrue(CONTENT.equals(cacheContent));
195
196         // Get the item back again and expect a refresh
197
cacheContent = (String JavaDoc) checkObj(KEY, REFRESH_NEEDED, true);
198         assertTrue(CONTENT.equals(cacheContent));
199
200         // Call the put in cache with invalid values
201
invalidPutInCacheArgument(null, null);
202         admin.putInCache(KEY, null); // This will still update the cache - cached items can be null
203

204         // Call the getFromCache with invalid values
205
invalidGetFromCacheArgument(null, 0);
206
207         // Try to retrieve the values
208
assertNull(checkObj(KEY, NO_REFRESH_NEEDED, false));
209
210         // Try to retrieve an item that is not in the cache
211
Object JavaDoc obj = checkObj("Not in cache", NO_REFRESH_NEEDED, true);
212         assertNull(obj);
213     }
214
215     /**
216      * Test the main cache functionalities, which are storing and retrieving objects
217      * from it
218      */

219     public void testPutInCacheAndGetFromCacheWithPolicy() {
220         String JavaDoc key = "policy";
221
222         // We put content in the cache and get it back
223
admin.putInCache(key, CONTENT, new DummyAlwayRefreshEntryPolicy());
224
225         // Should get a refresh
226
try {
227             admin.getFromCache(key, -1);
228             fail("Should have got a refresh.");
229         } catch (NeedsRefreshException nre) {
230             admin.cancelUpdate(key);
231         }
232     }
233
234     protected void tearDown() throws Exception JavaDoc {
235         if (admin != null) {
236             admin.getCache().removeCacheEventListener(cacheEntryEventListener, CacheEntryEventListener.class);
237             admin.getCache().removeCacheEventListener(cacheMapAccessEventListener, CacheMapAccessEventListener.class);
238         }
239     }
240
241
242     /**
243      * Bug CACHE-241
244      */

245     public void testFlushDateTomorrow() {
246         GeneralCacheAdministrator cacheAdmin = new GeneralCacheAdministrator(null);
247         
248         cacheAdmin.putInCache("key1", "key1value");
249         
250         try {
251             assertNotNull(cacheAdmin.getFromCache("key1"));
252         } catch (NeedsRefreshException e1) {
253             fail("Previous cache key1 doesn't exsits in GCA for the test!");
254         }
255         
256         cacheAdmin.flushAll(new Date JavaDoc(System.currentTimeMillis() + 5000)); // flush in 5 sec.
257
try {
258             cacheAdmin.getFromCache("key1");
259         } catch (NeedsRefreshException e) {
260             cacheAdmin.cancelUpdate("key1");
261             fail("NRE is thrown, but key will expire in 5s."); // it fails here
262
}
263     }
264
265
266     /**
267      * Utility method that tries to get an item from the cache and verify
268      * if all goes as expected
269      * <p>
270      * @param key The item key
271      * @param refresh The timestamp specifiying if the item needs refresh
272      * @param exceptionExpected Specify if we expect a NeedsRefreshException
273      */

274     private Object JavaDoc checkObj(String JavaDoc key, int refresh, boolean exceptionExpected) {
275         // Cache content
276
Object JavaDoc content = null;
277
278         try {
279             // try to find an object
280
content = admin.getFromCache(key, refresh);
281
282             if (exceptionExpected) {
283                 fail("Expected NeedsRefreshException!");
284             }
285         } catch (NeedsRefreshException nre) {
286             admin.cancelUpdate(key);
287
288             if (!exceptionExpected) {
289                 fail("Did not expected NeedsRefreshException!");
290             }
291
292             // Return the cache content from the exception
293
content = nre.getCacheContent();
294         }
295
296         return content;
297     }
298
299     /**
300      * Method that try to retrieve data from the cache but specify wrong arguments
301      * <p>
302      * @param key The cache item key
303      * @param refresh The timestamp specifiying if the item needs refresh
304      */

305     private void invalidGetFromCacheArgument(String JavaDoc key, int refresh) {
306         try {
307             // Try to get the data from the cache
308
admin.getFromCache(key, refresh);
309             fail("getFromCache did NOT throw an IllegalArgumentException");
310         } catch (IllegalArgumentException JavaDoc ipe) {
311             // This is what we expect
312
} catch (NeedsRefreshException nre) {
313             admin.cancelUpdate(key);
314
315             // Ignore this one
316
}
317     }
318
319     /**
320      * Method that try to insert data in the cache but specify wrong arguments
321      * <p>
322      * @param key The cache item key
323      * @param content The content of the cache item
324      */

325     private void invalidPutInCacheArgument(String JavaDoc key, Object JavaDoc content) {
326         try {
327             // Try to put this data in the cache
328
admin.putInCache(key, content);
329             fail("putInCache did NOT throw an IllegalArgumentException");
330         } catch (IllegalArgumentException JavaDoc ipe) {
331             // This is what we expect
332
}
333     }
334
335     private void populate() {
336         for (int i = 0; i < 7; i++) {
337             String JavaDoc[] groups = ((i & 1) == 0) ? new String JavaDoc[] {GROUP1, GROUP2} : new String JavaDoc[] {
338                 GROUP3
339             };
340             admin.putInCache(KEY + i, CONTENT + i, groups);
341         }
342
343         //register one miss.
344
checkObj("Not in cache", NO_REFRESH_NEEDED, true);
345
346         //register 7 hits
347
for (int i = 0; i < 7; i++) {
348             try {
349                 admin.getFromCache(KEY + i, NO_REFRESH_NEEDED);
350             } catch (NeedsRefreshException e) {
351                 admin.cancelUpdate(KEY + i);
352             }
353         }
354
355         for (int i = 0; i < 7; i++) {
356             try {
357                 admin.getFromCache(KEY + i, 0);
358             } catch (NeedsRefreshException e) {
359                 admin.cancelUpdate(KEY + i);
360             }
361         }
362
363         admin.putInCache(KEY + 1, CONTENT);
364         admin.putInCache(KEY + 2, CONTENT);
365         admin.flushPattern("blahblah");
366         admin.flushGroup(GROUP1);
367         admin.flushGroup(GROUP2);
368     }
369 }
370
Popular Tags