KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > avalon > excalibur > cache > ValidatingCache


1 /*
2  * Copyright (C) The Apache Software Foundation. All rights reserved.
3  *
4  * This software is published under the terms of the Apache Software License
5  * version 1.1, a copy of which has been included with this distribution in
6  * the LICENSE.txt file.
7  */

8 package org.apache.avalon.excalibur.cache;
9
10 /**
11  * Validating cache proxy.
12  *
13  * @author <a HREF="mailto:colus@apache.org">Eung-ju Park</a>
14  * @author <a HREF="mailto:anryoshi@user.sourceforge.net">Antti Koivunen"</a>
15  */

16 public final class ValidatingCache
17     implements Cache
18 {
19     private Cache m_cache;
20     private CacheValidator m_validator;
21
22     /**
23      * @param cache
24      * @param validator object validator
25      */

26     public ValidatingCache( final Cache cache, final CacheValidator validator )
27     {
28         m_cache = cache;
29         m_validator = validator;
30     }
31
32     private boolean validate( final Object JavaDoc key, final Object JavaDoc value )
33     {
34         if ( null == m_validator )
35         {
36             return true;
37         }
38         else
39         {
40             return m_validator.validate( key, value );
41         }
42     }
43
44     public void addListener( final CacheListener listener )
45     {
46         m_cache.addListener( listener );
47     }
48
49     public void removeListener( final CacheListener listener )
50     {
51         m_cache.removeListener( listener );
52     }
53
54     public int capacity()
55     {
56         return m_cache.capacity();
57     }
58
59     public int size()
60     {
61         return m_cache.size();
62     }
63
64     public Object JavaDoc put( final Object JavaDoc key, final Object JavaDoc value )
65     {
66         return m_cache.put( key, value );
67     }
68
69     public Object JavaDoc get( final Object JavaDoc key )
70     {
71         Object JavaDoc value = m_cache.get( key );
72
73         if ( ! validate( key, value ) )
74         {
75             remove( key );
76             value = null;
77         }
78
79         return value;
80     }
81
82     public Object JavaDoc remove( Object JavaDoc key )
83     {
84         return m_cache.remove( key );
85     }
86
87     public boolean containsKey( final Object JavaDoc key )
88     {
89         boolean contains = false;
90
91         if ( m_cache.containsKey( key ) )
92         {
93             final Object JavaDoc value = m_cache.get( key );
94             if ( validate( key, value ) )
95             {
96                 contains = true;
97             }
98             else
99             {
100                 remove( key );
101             }
102         }
103
104         return contains;
105     }
106
107     public void clear()
108     {
109         m_cache.clear();
110     }
111 }
112
Popular Tags