View Javadoc
1   /*
2    * Copyright (c) 2002-2014, Mairie de Paris
3    * All rights reserved.
4    *
5    * Redistribution and use in source and binary forms, with or without
6    * modification, are permitted provided that the following conditions
7    * are met:
8    *
9    *  1. Redistributions of source code must retain the above copyright notice
10   *     and the following disclaimer.
11   *
12   *  2. Redistributions in binary form must reproduce the above copyright notice
13   *     and the following disclaimer in the documentation and/or other materials
14   *     provided with the distribution.
15   *
16   *  3. Neither the name of 'Mairie de Paris' nor 'Lutece' nor the names of its
17   *     contributors may be used to endorse or promote products derived from
18   *     this software without specific prior written permission.
19   *
20   * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
21   * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23   * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
24   * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
25   * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
26   * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
27   * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28   * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
29   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
30   * POSSIBILITY OF SUCH DAMAGE.
31   *
32   * License 1.0
33   */
34  package fr.paris.lutece.portal.service.cache;
35  
36  import fr.paris.lutece.portal.service.util.AppLogService;
37  
38  import net.sf.ehcache.Cache;
39  import net.sf.ehcache.CacheException;
40  import net.sf.ehcache.Ehcache;
41  import net.sf.ehcache.Element;
42  import net.sf.ehcache.event.CacheEventListener;
43  
44  import org.apache.log4j.Logger;
45  
46  import java.util.ArrayList;
47  import java.util.List;
48  
49  
50  /**
51   * Base implementation for a cacheable service
52   */
53  public abstract class AbstractCacheableService implements CacheableService, CacheEventListener
54  {
55      private Cache _cache;
56      private boolean _bEnable;
57      private Logger _logger = Logger.getLogger( "lutece.cache" );
58  
59      /**
60       * Init the cache. Should be called by the service at its initialization.
61       */
62      public void initCache(  )
63      {
64          initCache( getName(  ) );
65      }
66  
67      /**
68       * Init the cache. Should be called by the service at its initialization.
69       * @param strCacheName The cache name
70       */
71      public void initCache( String strCacheName )
72      {
73          createCache( strCacheName );
74          _bEnable = true;
75          CacheService.registerCacheableService( this );
76      }
77  
78      /**
79       * Create a cache
80       * @param strCacheName The cache name
81       */
82      private void createCache( String strCacheName )
83      {
84          _cache = CacheService.getInstance(  ).createCache( strCacheName );
85          _cache.getCacheEventNotificationService(  ).registerListener( this );
86      }
87  
88      /**
89       * Put an object into the cache
90       * @param strKey The key of the object to put into the cache
91       * @param object The object to put into the cache
92       */
93      public void putInCache( String strKey, Object object )
94      {
95          if ( ( _cache != null ) && isCacheEnable(  ) )
96          {
97              Element element = new Element( strKey, object );
98              _cache.put( element );
99          }
100     }
101 
102     /**
103      * Gets an object from the cache
104      * @param strKey The key of the object to retrieve from the cache
105      * @return The object from the cache
106      */
107     public Object getFromCache( String strKey )
108     {
109         Object object = null;
110 
111         if ( ( _cache != null ) && isCacheEnable(  ) )
112         {
113             Element element = _cache.get( strKey );
114 
115             if ( element != null )
116             {
117                 object = element.getObjectValue(  );
118             }
119         }
120 
121         return object;
122     }
123 
124     /**
125      * Gets the current cache status.
126      *
127      * @return true if enable, otherwise false
128      */
129     @Override
130     public boolean isCacheEnable(  )
131     {
132         return _bEnable;
133     }
134 
135     /**
136      * {@inheritDoc }
137      */
138     @Override
139     public void enableCache( boolean bEnable )
140     {
141         _bEnable = bEnable;
142 
143         if ( ( !_bEnable ) && ( _cache != null ) )
144         {
145             _cache.removeAll(  );
146         }
147 
148         if ( ( _bEnable ) && ( _cache == null ) )
149         {
150             createCache( getName(  ) );
151         }
152 
153         CacheService.updateCacheStatus( this );
154     }
155 
156     /**
157      * Reset the cache.
158      */
159     @Override
160     public void resetCache(  )
161     {
162         try
163         {
164             if ( _cache != null )
165             {
166                 _cache.removeAll(  );
167             }
168         }
169         catch ( IllegalStateException e )
170         {
171             AppLogService.error( e.getMessage(  ), e );
172         }
173         catch ( CacheException e )
174         {
175             AppLogService.error( e.getMessage(  ), e );
176         }
177     }
178 
179     /**
180      * Gets the number of item currently in the cache.
181      *
182      * @return the number of item currently in the cache.
183      */
184     @Override
185     public int getCacheSize(  )
186     {
187         return ( _cache != null ) ? _cache.getSize(  ) : 0;
188     }
189 
190     /**
191      * Return a cache object
192      * @return cache object
193      */
194     public Cache getCache(  )
195     {
196         return _cache;
197     }
198 
199     /**
200      * {@inheritDoc }
201      */
202     @Override
203     public List<String> getKeys(  )
204     {
205         if ( _cache != null )
206         {
207             return _cache.getKeys(  );
208         }
209 
210         return new ArrayList<String>(  );
211     }
212 
213     /**
214     *  {@inheritDoc }
215     */
216     @Override
217     public int getMaxElements(  )
218     {
219         return _cache.getCacheConfiguration(  ).getMaxElementsInMemory(  );
220     }
221 
222     /**
223      *  {@inheritDoc }
224      */
225     @Override
226     public long getTimeToLive(  )
227     {
228         return _cache.getCacheConfiguration(  ).getTimeToLiveSeconds(  );
229     }
230 
231     /**
232      *  {@inheritDoc }
233      */
234     @Override
235     public long getMemorySize(  )
236     {
237         return _cache.calculateInMemorySize(  );
238     }
239 
240     /**
241      *  {@inheritDoc }
242      */
243     @Override
244     public String getInfos(  )
245     {
246         return CacheService.getInfos( _cache );
247     }
248 
249     // CacheEventListener implementation
250 
251     /**
252      * @see java.lang.Object#clone()
253      * @return the instance
254      */
255     @Override
256     public Object clone(  )
257     {
258         throw new RuntimeException( "This class shouldn't be cloned" );
259     }
260 
261     /**
262      * {@inheritDoc }
263      */
264     @Override
265     public void notifyElementExpired( Ehcache cache, Element element )
266     {
267         // Remove the element from the cache
268         _cache.remove( element.getKey(  ) );
269         _logger.debug( "Object removed from the cache : " + cache.getName(  ) + " - key : " + element.getKey(  ) );
270     }
271 
272     /**
273      * {@inheritDoc }
274      */
275     @Override
276     public void notifyElementRemoved( Ehcache ehch, Element elmnt )
277         throws CacheException
278     {
279         // Do nothing
280     }
281 
282     /**
283      * {@inheritDoc }
284      */
285     @Override
286     public void notifyElementEvicted( Ehcache ehch, Element elmnt )
287     {
288         // Do nothing
289     }
290 
291     /**
292      * {@inheritDoc }
293      */
294     @Override
295     public void notifyRemoveAll( Ehcache ehch )
296     {
297         // Do nothing
298     }
299 
300     /**
301      * {@inheritDoc }
302      */
303     @Override
304     public void notifyElementPut( Ehcache ehch, Element elmnt )
305         throws CacheException
306     {
307         // Do nothing
308     }
309 
310     /**
311      * {@inheritDoc }
312      */
313     @Override
314     public void notifyElementUpdated( Ehcache ehch, Element elmnt )
315         throws CacheException
316     {
317         // Do nothing
318     }
319 
320     /**
321      * {@inheritDoc }
322      */
323     @Override
324     public void dispose(  )
325     {
326         // Do nothing
327     }
328 
329     /**
330      * Remove a key from the cache
331      * @param strKey The key to remove
332      */
333     public void removeKey( String strKey )
334     {
335         getCache(  ).remove( strKey );
336     }
337 }