com.opensymphony.oscache.web
Class ServletCacheAdministrator

java.lang.Object
  extended by com.opensymphony.oscache.base.AbstractCacheAdministrator
      extended by com.opensymphony.oscache.web.ServletCacheAdministrator
All Implemented Interfaces:
Serializable

public class ServletCacheAdministrator
extends AbstractCacheAdministrator
implements Serializable

A ServletCacheAdministrator creates, flushes and administers the cache.

This is a "servlet Singleton". This means it's not a Singleton in the traditional sense, that is stored in a static instance. It's a Singleton _per web app context_.

Once created it manages the cache path on disk through the oscache.properties file, and also keeps track of the flush times.

Version:
$Revision: 463 $
Author:
Mike Cannon-Brookes, Todd Gochenour, Francois Beauregard, Alain Bergevin, Chris Miller
See Also:
Serialized Form

Field Summary
static String APPLICATION_SCOPE_NAME
           
private static short AVERAGE_KEY_LENGTH
          Constant for Key generation.
private static String CACHE_ADMINISTRATOR_KEY_SUFFIX
          The suffix added to the cache key used to store a ServletCacheAdministrator will be stored in the ServletContext
private static String CACHE_ADMINISTRATORS_KEY
          The key under which an array of all ServletCacheAdministrator objects will be stored in the ServletContext
private static String CACHE_KEY_KEY
           
private static String CACHE_USE_HOST_DOMAIN_KEY
          Constants for properties read/written from/to file
private  String cacheKey
          Key to use for storing and retrieving Object in contexts (Servlet, session).
private  javax.servlet.ServletContext context
          Required so we can look up the app scope cache without forcing a session creation.
private static String DEFAULT_CACHE_KEY
          The default cache key that is used to store the cache in context.
private static String FILE_SEPARATOR
          The string to use as a file separator.
private static char FILE_SEPARATOR_CHAR
          The character to use as a file separator.
private  Map flushTimes
          Map containing the flush times of different scopes
static String HASH_KEY_CONTEXT_TMPDIR
          Key used to store the servlet container temporary directory in the configuration.
static String HASH_KEY_SCOPE
          Key used to store the current scope in the configuration.
static String HASH_KEY_SESSION_ID
          Key used to store the current session ID in the configuration.
private static org.apache.commons.logging.Log log
           
private static String m_strBase64Chars
          Usable caracters for key generation
static String SESSION_SCOPE_NAME
          Constants for scope's name
private  boolean useHostDomainInKey
          Set property cache.use.host.domain.in.key=true to add domain information to key generation for hosting multiple sites.
 
Fields inherited from class com.opensymphony.oscache.base.AbstractCacheAdministrator
algorithmClass, CACHE_ALGORITHM_KEY, CACHE_BLOCKING_KEY, CACHE_CAPACITY_KEY, CACHE_DISK_UNLIMITED_KEY, CACHE_ENTRY_EVENT_LISTENERS_KEY, CACHE_MEMORY_KEY, CACHE_PERSISTENCE_OVERFLOW_KEY, cacheCapacity, config, listenerList, PERSISTENCE_CLASS_KEY
 
Constructor Summary
private ServletCacheAdministrator(javax.servlet.ServletContext context, Properties p)
          Create the cache administrator.
 
Method Summary
 void addScopeEventListener(ScopeEventListener listener)
          Register a listener for Cache Map events.
 void cancelUpdate(int scope, javax.servlet.http.HttpServletRequest request, String key)
          Cancels a pending cache update.
private  ServletCache createCache(int scope, String sessionId)
          Create a cache
static void destroyInstance(javax.servlet.ServletContext context)
          Shuts down all servlet cache administrators.
private  void dispatchScopeEvent(ScopeEventType eventType, int scope, Date date, String origin)
          Dispatch a scope event to all registered listeners.
protected  void finalizeListeners(Cache cache)
          Finalizes all the listeners that are associated with the given cache object
 void flushAll()
          Flush all scopes instantly.
 void flushAll(Date date)
          Flush all scopes at a particular time
 String generateEntryKey(String key, javax.servlet.http.HttpServletRequest request, int scope)
          Generates a cache entry key.
 String generateEntryKey(String key, javax.servlet.http.HttpServletRequest request, int scope, String language)
          Generates a cache entry key.
 String generateEntryKey(String key, javax.servlet.http.HttpServletRequest request, int scope, String language, String suffix)
          Generates a cache entry key.
 Cache getAppScopeCache(javax.servlet.ServletContext context)
          A convenience method to retrieve the application scope cache
 Cache getCache(javax.servlet.http.HttpServletRequest request, int scope)
          Grabs the cache for the specified scope
 String getCacheKey()
          Get the cache key from the properties.
 Date getFlushTime(int scope)
          Get the flush time for a particular scope.
 Object getFromCache(int scope, javax.servlet.http.HttpServletRequest request, String key, int refreshPeriod)
          Retrieve an item from the cache
static ServletCacheAdministrator getInstance(javax.servlet.ServletContext context)
          Obtain an instance of the CacheAdministrator
static ServletCacheAdministrator getInstance(javax.servlet.ServletContext context, Properties p)
          Obtain an instance of the CacheAdministrator
static ServletCacheAdministrator getInstanceFromKey(javax.servlet.ServletContext context, String key)
          Obtain an instance of the CacheAdministrator for the specified key
 Cache getSessionScopeCache(javax.servlet.http.HttpSession session)
          A convenience method to retrieve the session scope cache
protected  String getSortedQueryString(javax.servlet.http.HttpServletRequest request)
          Creates a string that contains all of the request parameters and their values in a single string.
private  void initHostDomainInKey()
          Set property cache.use.host.domain.in.key=true to add domain information to key generation for hosting multiple sites
 boolean isScopeFlushed(CacheEntry cacheEntry, int scope)
          Checks if the given scope was flushed more recently than the CacheEntry provided.
 void logError(String message)
          Log error messages to commons logging.
 void putInCache(int scope, javax.servlet.http.HttpServletRequest request, String key, Object content)
          Put an object in the cache.
 void putInCache(int scope, javax.servlet.http.HttpServletRequest request, String key, Object content, EntryRefreshPolicy policy)
          Put an object in the cache.
 void removeScopeEventListener(ScopeEventListener listener)
          Unregister a listener for Cache Map events.
 void setCacheCapacity(int scope, javax.servlet.http.HttpServletRequest request, int capacity)
          Sets the cache capacity (number of items).
 void setFlushTime(Date date, int scope)
          Set the flush time for a specific scope to a specific time
 void setFlushTime(int scope)
          Set the flush time for a specific scope to the current time.
private static String toBase64(byte[] aValue)
          Convert a byte array into a Base64 string (as used in mime formats)
 
Methods inherited from class com.opensymphony.oscache.base.AbstractCacheAdministrator
configureStandardListeners, getCacheEventListeners, getProperty, isBlocking, isMemoryCaching, isOverflowPersistence, isUnlimitedDiskCache, setAlgorithmClass, setCacheCapacity, setOverflowPersistence, setPersistenceListener
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

log

private static final transient org.apache.commons.logging.Log log

CACHE_USE_HOST_DOMAIN_KEY

private static final String CACHE_USE_HOST_DOMAIN_KEY
Constants for properties read/written from/to file

See Also:
Constant Field Values

CACHE_KEY_KEY

private static final String CACHE_KEY_KEY
See Also:
Constant Field Values

DEFAULT_CACHE_KEY

private static final String DEFAULT_CACHE_KEY
The default cache key that is used to store the cache in context.

See Also:
Constant Field Values

SESSION_SCOPE_NAME

public static final String SESSION_SCOPE_NAME
Constants for scope's name

See Also:
Constant Field Values

APPLICATION_SCOPE_NAME

public static final String APPLICATION_SCOPE_NAME
See Also:
Constant Field Values

CACHE_ADMINISTRATOR_KEY_SUFFIX

private static final String CACHE_ADMINISTRATOR_KEY_SUFFIX
The suffix added to the cache key used to store a ServletCacheAdministrator will be stored in the ServletContext

See Also:
Constant Field Values

CACHE_ADMINISTRATORS_KEY

private static final String CACHE_ADMINISTRATORS_KEY
The key under which an array of all ServletCacheAdministrator objects will be stored in the ServletContext

See Also:
Constant Field Values

HASH_KEY_SCOPE

public static final String HASH_KEY_SCOPE
Key used to store the current scope in the configuration. This is a hack to let the scope information get passed through to the DiskPersistenceListener, and will be removed in a future release.

See Also:
Constant Field Values

HASH_KEY_SESSION_ID

public static final String HASH_KEY_SESSION_ID
Key used to store the current session ID in the configuration. This is a hack to let the scope information get passed through to the DiskPersistenceListener, and will be removed in a future release.

See Also:
Constant Field Values

HASH_KEY_CONTEXT_TMPDIR

public static final String HASH_KEY_CONTEXT_TMPDIR
Key used to store the servlet container temporary directory in the configuration. This is a hack to let the scope information get passed through to the DiskPersistenceListener, and will be removed in a future release.

See Also:
Constant Field Values

FILE_SEPARATOR

private static final String FILE_SEPARATOR
The string to use as a file separator.

See Also:
Constant Field Values

FILE_SEPARATOR_CHAR

private static final char FILE_SEPARATOR_CHAR
The character to use as a file separator.


AVERAGE_KEY_LENGTH

private static final short AVERAGE_KEY_LENGTH
Constant for Key generation.

See Also:
Constant Field Values

m_strBase64Chars

private static final String m_strBase64Chars
Usable caracters for key generation

See Also:
Constant Field Values

flushTimes

private Map flushTimes
Map containing the flush times of different scopes


context

private transient javax.servlet.ServletContext context
Required so we can look up the app scope cache without forcing a session creation.


cacheKey

private String cacheKey
Key to use for storing and retrieving Object in contexts (Servlet, session).


useHostDomainInKey

private boolean useHostDomainInKey
Set property cache.use.host.domain.in.key=true to add domain information to key generation for hosting multiple sites.

Constructor Detail

ServletCacheAdministrator

private ServletCacheAdministrator(javax.servlet.ServletContext context,
                                  Properties p)
Create the cache administrator. This will reset all the flush times and load the properties file.

Method Detail

getInstance

public static ServletCacheAdministrator getInstance(javax.servlet.ServletContext context)
Obtain an instance of the CacheAdministrator

Parameters:
context - The ServletContext that this CacheAdministrator is a Singleton under
Returns:
Returns the CacheAdministrator instance for this context

getInstanceFromKey

public static ServletCacheAdministrator getInstanceFromKey(javax.servlet.ServletContext context,
                                                           String key)
Obtain an instance of the CacheAdministrator for the specified key

Parameters:
context - The ServletContext that this CacheAdministrator is a Singleton under
key - the cachekey or admincachekey for the CacheAdministrator wanted
Returns:
Returns the CacheAdministrator instance for this context, or null if no CacheAdministrator exists with the key supplied

getInstance

public static ServletCacheAdministrator getInstance(javax.servlet.ServletContext context,
                                                    Properties p)
Obtain an instance of the CacheAdministrator

Parameters:
context - The ServletContext that this CacheAdministrator is a Singleton under
p - the properties to use for the cache if the cache administrator has not been created yet. Once the administrator has been created, the properties parameter is ignored for all future invocations. If a null value is passed in, then the properties are loaded from the oscache.properties file in the classpath.
Returns:
Returns the CacheAdministrator instance for this context

destroyInstance

public static void destroyInstance(javax.servlet.ServletContext context)
Shuts down all servlet cache administrators. This should usually only be called when the controlling application shuts down.


getCache

public Cache getCache(javax.servlet.http.HttpServletRequest request,
                      int scope)
Grabs the cache for the specified scope

Parameters:
request - The current request
scope - The scope of this cache (PageContext.APPLICATION_SCOPE or PageContext.SESSION_SCOPE)
Returns:
The cache

getAppScopeCache

public Cache getAppScopeCache(javax.servlet.ServletContext context)
A convenience method to retrieve the application scope cache

Parameters:
context - the current ServletContext
Returns:
the application scope cache. If none is present, one will be created.

getSessionScopeCache

public Cache getSessionScopeCache(javax.servlet.http.HttpSession session)
A convenience method to retrieve the session scope cache

Parameters:
session - the current HttpSession
Returns:
the session scope cache for this session. If none is present, one will be created.

getCacheKey

public String getCacheKey()
Get the cache key from the properties. Set it to a default value if it is not present in the properties

Returns:
The cache.key property or the DEFAULT_CACHE_KEY

setFlushTime

public void setFlushTime(Date date,
                         int scope)
Set the flush time for a specific scope to a specific time

Parameters:
date - The time to flush the scope
scope - The scope to be flushed

setFlushTime

public void setFlushTime(int scope)
Set the flush time for a specific scope to the current time.

Parameters:
scope - The scope to be flushed

getFlushTime

public Date getFlushTime(int scope)
Get the flush time for a particular scope.

Parameters:
scope - The scope to get the flush time for.
Returns:
A date representing the time this scope was last flushed. Returns null if it has never been flushed.

getFromCache

public Object getFromCache(int scope,
                           javax.servlet.http.HttpServletRequest request,
                           String key,
                           int refreshPeriod)
                    throws NeedsRefreshException
Retrieve an item from the cache

Parameters:
scope - The cache scope
request - The servlet request
key - The key of the object to retrieve
refreshPeriod - The time interval specifying if an entry needs refresh
Returns:
The requested object
Throws:
NeedsRefreshException

isScopeFlushed

public boolean isScopeFlushed(CacheEntry cacheEntry,
                              int scope)
Checks if the given scope was flushed more recently than the CacheEntry provided. Used to determine whether to refresh the particular CacheEntry.

Parameters:
cacheEntry - The cache entry which we're seeing whether to refresh
scope - The scope we're checking
Returns:
Whether or not the scope has been flushed more recently than this cache entry was updated.

addScopeEventListener

public void addScopeEventListener(ScopeEventListener listener)
Register a listener for Cache Map events.

Parameters:
listener - The object that listens to events.

cancelUpdate

public void cancelUpdate(int scope,
                         javax.servlet.http.HttpServletRequest request,
                         String key)
Cancels a pending cache update. This should only be called by a thread that received a NeedsRefreshException and was unable to generate some new cache content.

Parameters:
scope - The cache scope
request - The servlet request
key - The cache entry key to cancel the update of.

flushAll

public void flushAll(Date date)
Flush all scopes at a particular time

Parameters:
date - The time to flush the scope

flushAll

public void flushAll()
Flush all scopes instantly.


generateEntryKey

public String generateEntryKey(String key,
                               javax.servlet.http.HttpServletRequest request,
                               int scope)
Generates a cache entry key. If the string key is not specified, the HTTP request URI and QueryString is used. Operating systems that have a filename limitation less than 255 or have filenames that are case insensitive may have issues with key generation where two distinct pages map to the same key.

POST Requests (which have no distinguishing query string) may also generate identical keys for what is actually different pages. In these cases, specify an explicit key attribute for the CacheTag.

Parameters:
key - The key entered by the user
request - The current request
scope - The scope this cache entry is under
Returns:
The generated cache key

generateEntryKey

public String generateEntryKey(String key,
                               javax.servlet.http.HttpServletRequest request,
                               int scope,
                               String language)
Generates a cache entry key. If the string key is not specified, the HTTP request URI and QueryString is used. Operating systems that have a filename limitation less than 255 or have filenames that are case insensitive may have issues with key generation where two distinct pages map to the same key.

POST Requests (which have no distinguishing query string) may also generate identical keys for what is actually different pages. In these cases, specify an explicit key attribute for the CacheTag.

Parameters:
key - The key entered by the user
request - The current request
scope - The scope this cache entry is under
language - The ISO-639 language code to distinguish different pages in application scope
Returns:
The generated cache key

generateEntryKey

public String generateEntryKey(String key,
                               javax.servlet.http.HttpServletRequest request,
                               int scope,
                               String language,
                               String suffix)
Generates a cache entry key.

If the string key is not specified, the HTTP request URI and QueryString is used. Operating systems that have a filename limitation less than 255 or have filenames that are case insensitive may have issues with key generation where two distinct pages map to the same key.

POST Requests (which have no distinguishing query string) may also generate identical keys for what is actually different pages. In these cases, specify an explicit key attribute for the CacheTag.

Parameters:
key - The key entered by the user
request - The current request
scope - The scope this cache entry is under
language - The ISO-639 language code to distinguish different pages in application scope
suffix - The ability to put a suffix at the end of the key
Returns:
The generated cache key

getSortedQueryString

protected String getSortedQueryString(javax.servlet.http.HttpServletRequest request)
Creates a string that contains all of the request parameters and their values in a single string. This is very similar to HttpServletRequest.getQueryString() except the parameters are sorted by name, and if there is a jsessionid parameter it is filtered out.

If the request has no parameters, this method returns null.


logError

public void logError(String message)
Log error messages to commons logging.

Parameters:
message - Message to log.

putInCache

public void putInCache(int scope,
                       javax.servlet.http.HttpServletRequest request,
                       String key,
                       Object content)
Put an object in the cache. This should only be called by a thread that received a NeedsRefreshException. Using session scope the thread has to insure that the session wasn't invalidated in the meantime. CacheTag and CacheFilter guarantee that the same cache is used in cancelUpdate and getFromCache.

Parameters:
scope - The cache scope
request - The servlet request
key - The object key
content - The object to add

putInCache

public void putInCache(int scope,
                       javax.servlet.http.HttpServletRequest request,
                       String key,
                       Object content,
                       EntryRefreshPolicy policy)
Put an object in the cache. This should only be called by a thread that received a NeedsRefreshException. Using session scope the thread has to insure that the session wasn't invalidated in the meantime. CacheTag and CacheFilter guarantee that the same cache is used in cancelUpdate and getFromCache.

Parameters:
scope - The cache scope
request - The servlet request
key - The object key
content - The object to add
policy - The refresh policy

setCacheCapacity

public void setCacheCapacity(int scope,
                             javax.servlet.http.HttpServletRequest request,
                             int capacity)
Sets the cache capacity (number of items). If the cache contains more than capacity items then items will be removed to bring the cache back down to the new size.

Parameters:
scope - The cache scope
request - The servlet request
capacity - The new capacity

removeScopeEventListener

public void removeScopeEventListener(ScopeEventListener listener)
Unregister a listener for Cache Map events.

Parameters:
listener - The object that currently listens to events.

finalizeListeners

protected void finalizeListeners(Cache cache)
Finalizes all the listeners that are associated with the given cache object

Overrides:
finalizeListeners in class AbstractCacheAdministrator

toBase64

private static String toBase64(byte[] aValue)
Convert a byte array into a Base64 string (as used in mime formats)


createCache

private ServletCache createCache(int scope,
                                 String sessionId)
Create a cache

Parameters:
scope - The cache scope
sessionId - The sessionId for with the cache will be created
Returns:
A new cache

dispatchScopeEvent

private void dispatchScopeEvent(ScopeEventType eventType,
                                int scope,
                                Date date,
                                String origin)
Dispatch a scope event to all registered listeners.

Parameters:
eventType - The type of event
scope - Scope that was flushed (Does not apply for FLUSH_ALL event)
date - Date of flushing
origin - The origin of the event

initHostDomainInKey

private void initHostDomainInKey()
Set property cache.use.host.domain.in.key=true to add domain information to key generation for hosting multiple sites



Copyright © 2011 OpenSymphony. All Rights Reserved.