View Javadoc

1   /*
2    *  Copyright 2004 David C. Brown
3    *
4    *  Licensed under the Apache License, Version 2.0 (the "License");
5    *  you may not use this file except in compliance with the License.
6    *  You may obtain a copy of the License at
7    *
8    *      http://www.apache.org/licenses/LICENSE-2.0
9    *
10   *  Unless required by applicable law or agreed to in writing, software
11   *  distributed under the License is distributed on an "AS IS" BASIS,
12   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   *  See the License for the specific language governing permissions and
14   *  limitations under the License.
15   */
16  package net.sf.ashkay.strategies;
17  
18  import net.sf.ashkay.CacheEntry;
19  import net.sf.ashkay.CachingStrategy;
20  
21  
22  /***
23   * TimeExpirationCachingStrategy expires objects in the cache after a set
24   * amount of time.
25   * @author <a href="mailto:bangroot@users.sf.net">Dave Brown</a>
26   */
27  
28  public class TimeExpirationCachingStrategy implements CachingStrategy
29  {
30      private static final String ENTRY_KEY =
31              "com.cepm_us.util.cache.TimeExpirationCachingStrategy.Timeout";
32  
33      private long expirationTime;
34  
35      /***
36       * Creates the caching strategy with the specified timeout.
37       * @param timeOut - the time out length for the cache entries
38       */
39      public TimeExpirationCachingStrategy(long timeOut)
40      {
41          expirationTime = timeOut;
42      }
43  
44      public CacheEntry prepare(CacheEntry entry)
45      {
46          entry.addProperty(ENTRY_KEY, new Long(System.currentTimeMillis()));
47          return entry;
48      }
49  
50      public boolean validate(CacheEntry entry)
51      {
52          boolean val = true;
53          Object temp = entry.getProperty(ENTRY_KEY);
54          if ((temp != null) && (temp instanceof Long))
55          {
56              long cachedTime = ((Long) temp).longValue();
57              long currentTime = System.currentTimeMillis();
58              if (cachedTime + expirationTime <= currentTime)
59              {
60                  val = false;
61              }
62  
63          }
64          else
65          {
66              val = false;
67          }
68  
69          return val;
70      }
71  }