View Javadoc
1   package org.apache.commons.jcs3.access;
2   
3   /*
4    * Licensed to the Apache Software Foundation (ASF) under one
5    * or more contributor license agreements.  See the NOTICE file
6    * distributed with this work for additional information
7    * regarding copyright ownership.  The ASF licenses this file
8    * to you under the Apache License, Version 2.0 (the
9    * "License"); you may not use this file except in compliance
10   * with the License.  You may obtain a copy of the License at
11   *
12   *   http://www.apache.org/licenses/LICENSE-2.0
13   *
14   * Unless required by applicable law or agreed to in writing,
15   * software distributed under the License is distributed on an
16   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
17   * KIND, either express or implied.  See the License for the
18   * specific language governing permissions and limitations
19   * under the License.
20   */
21  
22  import java.util.HashSet;
23  import java.util.Map;
24  import java.util.Set;
25  
26  import org.apache.commons.jcs3.JCS;
27  import org.apache.commons.jcs3.access.exception.CacheException;
28  import org.apache.commons.jcs3.access.exception.ObjectExistsException;
29  import org.apache.commons.jcs3.engine.CompositeCacheAttributes;
30  import org.apache.commons.jcs3.engine.ElementAttributes;
31  import org.apache.commons.jcs3.engine.behavior.ICacheElement;
32  import org.apache.commons.jcs3.engine.behavior.ICompositeCacheAttributes;
33  import org.apache.commons.jcs3.engine.behavior.IElementAttributes;
34  
35  import junit.framework.TestCase;
36  
37  /**
38   * Tests the methods of the cache access class.
39   */
40  public class CacheAccessUnitTest
41      extends TestCase
42  {
43      /**
44       * Verify that we get an object exists exception if the item is in the cache.
45       * @throws Exception
46       */
47      public void testPutSafe()
48          throws Exception
49      {
50          final CacheAccess<String, String> access = JCS.getInstance( "test" );
51          assertNotNull( "We should have an access class", access );
52  
53          final String key = "mykey";
54          final String value = "myvalue";
55  
56          access.put( key, value );
57  
58          final String returnedValue1 = access.get( key );
59          assertEquals( "Wrong value returned.", value, returnedValue1 );
60  
61          try
62          {
63              access.putSafe( key, "someothervalue" );
64              fail( "We should have received an exception since this key is already in the cache." );
65          }
66          catch ( final CacheException e )
67          {
68              assertTrue( "Wrong type of exception.", e instanceof ObjectExistsException );
69              assertTrue( "Should have the key in the error message.", e.getMessage().indexOf( "[" + key + "]" ) != -1 );
70          }
71  
72          final String returnedValue2 = access.get( key );
73          assertEquals( "Wrong value returned.  Should still be the original.", value, returnedValue2 );
74      }
75  
76      /**
77       * Try to put a null key and verify that we get an exception.
78       * @throws Exception
79       */
80      public void testPutNullKey()
81          throws Exception
82      {
83          final CacheAccess<String, String> access = JCS.getInstance( "test" );
84          assertNotNull( "We should have an access class", access );
85  
86          final String key = null;
87          final String value = "myvalue";
88  
89          try
90          {
91              access.put( key, value );
92              fail( "Should not have been able to put a null key." );
93          }
94          catch ( final CacheException e )
95          {
96              assertTrue( "Should have the word null in the error message.", e.getMessage().indexOf( "null" ) != -1 );
97          }
98      }
99  
100     /**
101      * Try to put a null value and verify that we get an exception.
102      * @throws Exception
103      */
104     public void testPutNullValue()
105         throws Exception
106     {
107         final CacheAccess<String, String> access = JCS.getInstance( "test" );
108         assertNotNull( "We should have an access class", access );
109 
110         final String key = "myKey";
111         final String value = null;
112 
113         try
114         {
115             access.put( key, value );
116             fail( "Should not have been able to put a null object." );
117         }
118         catch ( final CacheException e )
119         {
120             assertTrue( "Should have the word null in the error message.", e.getMessage().indexOf( "null" ) != -1 );
121         }
122     }
123 
124     /**
125      * Verify that elements that go in the region after this call take the new attributes.
126      * @throws Exception
127      */
128     public void testSetDefaultElementAttributes()
129         throws Exception
130     {
131         final CacheAccess<String, String> access = JCS.getInstance( "test" );
132         assertNotNull( "We should have an access class", access );
133 
134         final long maxLife = 9876;
135         final IElementAttributes attr = new ElementAttributes();
136         attr.setMaxLife(maxLife);
137 
138         access.setDefaultElementAttributes( attr );
139 
140         assertEquals( "Wrong element attributes.", attr.getMaxLife(), access.getDefaultElementAttributes()
141             .getMaxLife() );
142 
143         final String key = "mykey";
144         final String value = "myvalue";
145 
146         access.put( key, value );
147 
148         final ICacheElement<String, String> element = access.getCacheElement( key );
149 
150         assertEquals( "Wrong max life.  Should have the new value.", maxLife, element.getElementAttributes()
151             .getMaxLife() );
152     }
153 
154     /**
155      * Verify that getCacheElements returns the elements requested based on the key.
156      * @throws Exception
157      */
158     public void testGetCacheElements()
159         throws Exception
160     {
161         //SETUP
162         final CacheAccess<String, String> access = JCS.getInstance( "test" );
163         assertNotNull( "We should have an access class", access );
164 
165         final String keyOne = "mykeyone";
166         final String keyTwo = "mykeytwo";
167         final String keyThree = "mykeythree";
168         final String keyFour = "mykeyfour";
169         final String valueOne = "myvalueone";
170         final String valueTwo = "myvaluetwo";
171         final String valueThree = "myvaluethree";
172         final String valueFour = "myvaluefour";
173 
174         access.put( keyOne, valueOne );
175         access.put( keyTwo, valueTwo );
176         access.put( keyThree, valueThree );
177 
178         final Set<String> input = new HashSet<>();
179         input.add( keyOne );
180         input.add( keyTwo );
181 
182         //DO WORK
183         final Map<String, ICacheElement<String, String>> result = access.getCacheElements( input );
184 
185         //VERIFY
186         assertEquals( "map size", 2, result.size() );
187         final ICacheElement<String, String> elementOne = result.get( keyOne );
188         assertEquals( "value one", keyOne, elementOne.getKey() );
189         assertEquals( "value one", valueOne, elementOne.getVal() );
190         final ICacheElement<String, String> elementTwo = result.get( keyTwo );
191         assertEquals( "value two", keyTwo, elementTwo.getKey() );
192         assertEquals( "value two", valueTwo, elementTwo.getVal() );
193 
194         assertNull(access.get(keyFour));
195         final String suppliedValue1 = access.get(keyFour, () -> valueFour);
196         assertNotNull( "value four", suppliedValue1);
197         assertEquals( "value four", valueFour, suppliedValue1);
198         final String suppliedValue2 = access.get(keyFour);
199         assertNotNull( "value four", suppliedValue2);
200         assertEquals( "value four", suppliedValue1, suppliedValue2);
201     }
202 
203     /**
204      * Verify that we can get a region using the define region method.
205      * @throws Exception
206      */
207     public void testRegionDefiniton()
208         throws Exception
209     {
210         final CacheAccess<String, String> access = JCS.getInstance( "test" );
211         assertNotNull( "We should have an access class", access );
212     }
213 
214     /**
215      * Verify that we can get a region using the define region method with cache attributes.
216      * @throws Exception
217      */
218     public void testRegionDefinitonWithAttributes()
219         throws Exception
220     {
221         final ICompositeCacheAttributes ca = new CompositeCacheAttributes();
222 
223         final long maxIdleTime = 8765;
224         ca.setMaxMemoryIdleTimeSeconds( maxIdleTime );
225 
226         final CacheAccess<String, String> access = JCS.getInstance( "testRegionDefinitonWithAttributes", ca );
227         assertNotNull( "We should have an access class", access );
228 
229         final ICompositeCacheAttributes ca2 = access.getCacheAttributes();
230         assertEquals( "Wrong idle time setting.", ca.getMaxMemoryIdleTimeSeconds(), ca2.getMaxMemoryIdleTimeSeconds() );
231     }
232 
233     /**
234      * Verify that we can get a region using the define region method with cache attributes and
235      * element attributes.
236      * @throws Exception
237      */
238     public void testRegionDefinitonWithBothAttributes()
239         throws Exception
240     {
241         final ICompositeCacheAttributes ca = new CompositeCacheAttributes();
242 
243         final long maxIdleTime = 8765;
244         ca.setMaxMemoryIdleTimeSeconds( maxIdleTime );
245 
246         final long maxLife = 9876;
247         final IElementAttributes attr = new ElementAttributes();
248         attr.setMaxLife(maxLife);
249 
250         final CacheAccess<String, String> access = JCS.getInstance( "testRegionDefinitonWithAttributes", ca, attr );
251         assertNotNull( "We should have an access class", access );
252 
253         final ICompositeCacheAttributes ca2 = access.getCacheAttributes();
254         assertEquals( "Wrong idle time setting.", ca.getMaxMemoryIdleTimeSeconds(), ca2.getMaxMemoryIdleTimeSeconds() );
255     }
256 
257     /**
258      * Verify we can get some matching elements..
259      * <p>
260      * @throws Exception
261      */
262     public void testGetMatching_Normal()
263         throws Exception
264     {
265         // SETUP
266         final int maxMemorySize = 1000;
267         final String keyprefix1 = "MyPrefix1";
268         final String keyprefix2 = "MyPrefix2";
269         final String memoryCacheClassName = "org.apache.commons.jcs3.engine.memory.lru.LRUMemoryCache";
270         final ICompositeCacheAttributes cattr = new CompositeCacheAttributes();
271         cattr.setMemoryCacheName( memoryCacheClassName );
272         cattr.setMaxObjects( maxMemorySize );
273 
274         final long maxLife = 9876;
275         final IElementAttributes attr = new ElementAttributes();
276         attr.setMaxLife(maxLife);
277 
278         final CacheAccess<String, Integer> access = JCS.getInstance( "testGetMatching_Normal", cattr, attr );
279 
280         // DO WORK
281         final int numToInsertPrefix1 = 10;
282         // insert with prefix1
283         for ( int i = 0; i < numToInsertPrefix1; i++ )
284         {
285             access.put( keyprefix1 + String.valueOf( i ), Integer.valueOf( i ) );
286         }
287 
288         final int numToInsertPrefix2 = 50;
289         // insert with prefix1
290         for ( int i = 0; i < numToInsertPrefix2; i++ )
291         {
292             access.put( keyprefix2 + String.valueOf( i ), Integer.valueOf( i ) );
293         }
294 
295         final Map<String, Integer> result1 = access.getMatching( keyprefix1 + ".+" );
296         final Map<String, Integer> result2 = access.getMatching( keyprefix2 + "\\S+" );
297 
298         // VERIFY
299         assertEquals( "Wrong number returned 1:", numToInsertPrefix1, result1.size() );
300         assertEquals( "Wrong number returned 2:", numToInsertPrefix2, result2.size() );
301         //System.out.println( result1 );
302 
303         // verify that the elements are unwrapped
304         for (final Map.Entry<String, Integer> entry : result1.entrySet())
305         {
306             final Object value = entry.getValue();
307             assertFalse( "Should not be a cache element.", value instanceof ICacheElement );
308         }
309     }
310 
311     /**
312      * Verify we can get some matching elements..
313      * <p>
314      * @throws Exception
315      */
316     public void testGetMatchingElements_Normal()
317         throws Exception
318     {
319         // SETUP
320         final int maxMemorySize = 1000;
321         final String keyprefix1 = "MyPrefix1";
322         final String keyprefix2 = "MyPrefix2";
323         final String memoryCacheClassName = "org.apache.commons.jcs3.engine.memory.lru.LRUMemoryCache";
324         final ICompositeCacheAttributes cattr = new CompositeCacheAttributes();
325         cattr.setMemoryCacheName( memoryCacheClassName );
326         cattr.setMaxObjects( maxMemorySize );
327 
328         final long maxLife = 9876;
329         final IElementAttributes attr = new ElementAttributes();
330         attr.setMaxLife(maxLife);
331 
332         final CacheAccess<String, Integer> access = JCS.getInstance( "testGetMatching_Normal", cattr, attr );
333 
334         // DO WORK
335         final int numToInsertPrefix1 = 10;
336         // insert with prefix1
337         for ( int i = 0; i < numToInsertPrefix1; i++ )
338         {
339             access.put( keyprefix1 + String.valueOf( i ), Integer.valueOf( i ) );
340         }
341 
342         final int numToInsertPrefix2 = 50;
343         // insert with prefix1
344         for ( int i = 0; i < numToInsertPrefix2; i++ )
345         {
346             access.put( keyprefix2 + String.valueOf( i ), Integer.valueOf( i ) );
347         }
348 
349         final Map<String, ICacheElement<String, Integer>> result1 = access.getMatchingCacheElements( keyprefix1 + "\\S+" );
350         final Map<String, ICacheElement<String, Integer>> result2 = access.getMatchingCacheElements( keyprefix2 + ".+" );
351 
352         // VERIFY
353         assertEquals( "Wrong number returned 1:", numToInsertPrefix1, result1.size() );
354         assertEquals( "Wrong number returned 2:", numToInsertPrefix2, result2.size() );
355         //System.out.println( result1 );
356 
357         // verify that the elements are wrapped
358         for (final Map.Entry<String, ICacheElement<String, Integer>> entry : result1.entrySet())
359         {
360             final Object value = entry.getValue();
361             assertTrue( "Should be a cache element.", value instanceof ICacheElement );
362         }
363     }
364 }