Rakesh API

org.rakeshv.filters
Class CachingFilter

java.lang.Object
  extended by org.rakeshv.filters.FilterAdapter
      extended by org.rakeshv.filters.CachingFilter
All Implemented Interfaces:
javax.servlet.Filter

public class CachingFilter
extends FilterAdapter

A Filter class that is used to cache the responses generated by the server. This filter caches the output generated to a request to file. Subsequent requests to the server with identical request parameters will be returned the cached contents by this filter.

The behaviour of the filter should be configured in the application's web.xml. The following parameters may be configured:

  • baseDirectory - The base directory under which the filter will cache files. The filter attempts to organise the directory tree following the same tree for the servlets that this fileter is applied to. If not specified, the filter will attempt to use a /tmp/org.rakeshv/filters/cache directory as the base directory.
  • cleanBaseDirectory - A boolean to indicate whether the base directory is to be cleaned on application startup. This is used to control whether old cached files are to be removed or reused on application start. Specify values of true or false.
  • timeToLive - The time in seconds until which cached files are to saved. The filter uses a TimerTask Thread to maintain the cache. Omit this paramter or specify -1 to disable automatic removal of cached files. Note that this setting refers to individual cache files.
  • purgeInterval - The interval in seconds at which the entire cache is to purged. The filter uses a TimerTask Thread to purge all the cached files at the specified interval. Omit or specify a value of -1 to disable automatic puring of the entire cache.
  • purgeTime - The fixed time of day at which the entire cache will be purged. The filter uses a TimerTask Thread to purge the cached files at the specified time of day. Omit to disable automatic purging of the entire cache. Do not specify in combination with purgeInterval. If both are specified, then purgeInterval setting takes precedence. This setting should be specified in hh:mm:ss format. The hour component must be specified in 24 hour format.

    The following shows ways in which you can enable the filters in your web application configuration file (WEB-INF/web.xml):

      <filter>
        <filter-name>cachingFilter</filter-name>
        <display-name>Caching Filter</display-name>
        <description>A servlet filter for caching to file responses to requests.</description>
        <filter-class>org.rakeshv.filters.CachingFilter</filter-class>
        <init-param>
          <param-name>baseDirectory</param-name>
          <param-value>/tmp/myapp/cache</param-value>
        </init-param>
        <init-param>
          <param-name>cleanBaseDirectory</param-name>
          <param-value>false</param-value>
        </init-param>
        <init-param>
          <param-name>timeToLive</param-name>
          <param-value>10800</param-value>
        </init-param>
        <init-param>
          <param-name>purgeTime</param-name>
          <param-value>01:00:00</param-value>
        </init-param>
      </filter>
    
      <filter-mapping>
        <filter-name>cachingFilter</filter-name>
        <servlet-name>myServlet</servlet-name>
      </filter-mapping>
    
      <filter-mapping>
        <filter-name>cachingFilter</filter-name>
        <url-pattern>/docs/*</url-pattern>
      </filter-mapping>
     

    © Copyright 2005, Rakesh Vidyadharan

    Version:
    $Id: CachingFilter.java,v 1.20 2005/10/21 17:26:02 rakesh Exp $
    Author:
    Rakesh Vidyadharan 11th September 2005

    Nested Class Summary
     class CachingFilter.Attributes
              A data structure used to hold the cache validity period attributes.
     class CachingFilter.FileProperties
              A data structure for storing the HTTP headers specified for the response that is being cached.
    protected  class CachingFilter.PurgeTask
              A TimerTask that is used to schedule cache purges.
     class CachingFilter.PurgeTime
              A data structure that is used to represent the time of day at which the cache directory should be purged.
     
    Field Summary
    private  CachingFilter.Attributes attributes
              The attributes associated with the cache.
    private static java.lang.String BASE_DIRECTORY
              The default path used for baseDirectory.
    private  java.io.File baseDirectory
              The base directory under which cache files will be stored.
    private static java.util.HashMap cachedPaths
              A Map in which all caches for the various paths are stored.
    private  boolean enableCache
              A flag used to indicate if the cache may be safely used.
    static java.lang.String NO_PURGE_TIME
              The value to indicate that the purgeTime setting should not be considered.
    static java.lang.String SEPARATOR
              The default file separator value.
     
    Fields inherited from class org.rakeshv.filters.FilterAdapter
    filterConfig
     
    Constructor Summary
    CachingFilter()
              Default constructor.
     
    Method Summary
    private  void chainResponse(CachingFilter.FileProperties fileProperties, java.io.File file, java.util.Map requestParameters, java.util.Map fileCache, javax.servlet.ServletRequest request, javax.servlet.ServletResponse response, javax.servlet.FilterChain chain)
              Create a CachingResponseWrapper and chain this filter to the next component in the chain.
    private  java.io.File createTemporaryFile(java.lang.String fileName)
              Create a temporary file based on the fileName specified.
     void doFilter(javax.servlet.ServletRequest request, javax.servlet.ServletResponse response, javax.servlet.FilterChain chain)
              Hash the request parameters and do a lookup in the cachedPaths to see if a cached file exists for the parameters.
    private  java.io.File fetchCacheFile(CachingFilter.FileProperties fileProperties)
              Fetch a file handle to the cache file represented by fileName .
    private  java.util.Map fetchFileCache(java.lang.String path)
              Fetch the Map that stores the request parameters and the associated file names from cachedPaths.
    private  CachingFilter.FileProperties fetchFileProperties(java.util.Map fileCache, java.util.Map requestParameters, java.lang.String path)
              Fetch the file name that for the cache file that represents the current request.
     void init(javax.servlet.FilterConfig filterConfig)
              Initialise the filter.
    private  void initBaseDirectory()
              Initialise the base directory used for caching the files.
    private  void initTimer()
              Create a Timer that runs the CachingFilter.PurgeTask at the interval specified by either CachingFilter.Attributes.purgeInterval or CachingFilter.Attributes.purgeTime.
    private  java.util.Map processRequestParameters(javax.servlet.ServletRequest request)
              Create a sorted map that contains all the request parameters and their values.
    private  int purgeCache(java.io.File directory)
              Purge all files and directories under the specified directory.
    private  void sendResponse(CachingFilter.FileProperties fileProperties, javax.servlet.ServletResponse response)
              Write the contents of the fileName to the HTTP Response specified.
     
    Methods inherited from class org.rakeshv.filters.FilterAdapter
    destroy, setFilterConfig
     
    Methods inherited from class java.lang.Object
    clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
     

    Field Detail

    BASE_DIRECTORY

    private static final java.lang.String BASE_DIRECTORY
    The default path used for baseDirectory.

    See Also:
    Constant Field Values

    cachedPaths

    private static final java.util.HashMap cachedPaths
    A Map in which all caches for the various paths are stored. This map contains maps for each path that is stored in it.


    SEPARATOR

    public static final java.lang.String SEPARATOR
    The default file separator value. Cached for convenience from the file.separator system property.


    NO_PURGE_TIME

    public static final java.lang.String NO_PURGE_TIME
    The value to indicate that the purgeTime setting should not be considered.

    See Also:
    Constant Field Values

    baseDirectory

    private java.io.File baseDirectory
    The base directory under which cache files will be stored.


    attributes

    private CachingFilter.Attributes attributes
    The attributes associated with the cache.


    enableCache

    private boolean enableCache
    A flag used to indicate if the cache may be safely used. This is disabled if errors were encountered while attempting to set up the baseDirectory tree.

    Constructor Detail

    CachingFilter

    public CachingFilter()
    Default constructor. Does nothing special.

    Method Detail

    init

    public void init(javax.servlet.FilterConfig filterConfig)
              throws javax.servlet.ServletException
    Initialise the filter. Processes the <init-param> values specified in web.xml.

    Specified by:
    init in interface javax.servlet.Filter
    Overrides:
    init in class FilterAdapter
    Parameters:
    filterConfig - - A filter configuration object used by a servlet container used to pass information to a filter during initialization. This is used to set the FilterAdapter.filterConfig reference.
    Throws:
    javax.servlet.ServletException - - If an exception is encountered while fetching the initialisation parameters from the FilterAdapter.filterConfig object reference.

    doFilter

    public void doFilter(javax.servlet.ServletRequest request,
                         javax.servlet.ServletResponse response,
                         javax.servlet.FilterChain chain)
                  throws java.io.IOException,
                         javax.servlet.ServletException
    Hash the request parameters and do a lookup in the cachedPaths to see if a cached file exists for the parameters. If yes, then return the contents of the cached file. If not buffer the output from the response from the next component in the chain, and then cache the contents to a file under the baseDirectory.

    Specified by:
    doFilter in interface javax.servlet.Filter
    Overrides:
    doFilter in class FilterAdapter
    Throws:
    java.io.IOException - - If exceptions are encountered while applying the filter.
    javax.servlet.ServletException - - If exceptions are encountered while interacting with the request or response objects.
    See Also:
    processRequestParameters(javax.servlet.ServletRequest), fetchFileCache(java.lang.String), fetchFileProperties(java.util.Map, java.util.Map, java.lang.String), fetchCacheFile(org.rakeshv.filters.CachingFilter.FileProperties), sendResponse(org.rakeshv.filters.CachingFilter.FileProperties, javax.servlet.ServletResponse), chainResponse(org.rakeshv.filters.CachingFilter.FileProperties, java.io.File, java.util.Map, java.util.Map, javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)

    initBaseDirectory

    private void initBaseDirectory()
    Initialise the base directory used for caching the files. Attempts to create the base directory if it does not exist. Prints an error message to System.err if the attempt to create the base directory fails.

    See Also:
    purgeCache(java.io.File)

    initTimer

    private void initTimer()
    Create a Timer that runs the CachingFilter.PurgeTask at the interval specified by either CachingFilter.Attributes.purgeInterval or CachingFilter.Attributes.purgeTime. If both are configured then the CachingFilter.Attributes.purgeInterval setting takes precedence.


    processRequestParameters

    private java.util.Map processRequestParameters(javax.servlet.ServletRequest request)
    Create a sorted map that contains all the request parameters and their values. Sorting is essential to ensure that the order in which the request parameters are specified does not lead to duplicated cache files.

    Parameters:
    request - The HTTP request from which the request parameters and their values are to be retrieved.

    fetchFileCache

    private java.util.Map fetchFileCache(java.lang.String path)
    Fetch the Map that stores the request parameters and the associated file names from cachedPaths. If it does not exist, then a new Map is created and added to the cachedPaths.

    Parameters:
    path - The URI path for which the cache is to be retrieved.
    Returns:
    Map - The map that stores the key-value pairs.

    fetchFileProperties

    private CachingFilter.FileProperties fetchFileProperties(java.util.Map fileCache,
                                                             java.util.Map requestParameters,
                                                             java.lang.String path)
    Fetch the file name that for the cache file that represents the current request. If it does not exist in the fileCache, create the new file name.

    Parameters:
    fileCache - The Map in which the file names are stored for a given requestParameters.
    requestParameters - A Map that contains key-value mappings of all the request parameters.
    path - The URI path component with which the file name will be associated.
    Returns:
    FileProperties - The data structure that holds metadata about the file that was cached.

    fetchCacheFile

    private java.io.File fetchCacheFile(CachingFilter.FileProperties fileProperties)
    Fetch a file handle to the cache file represented by fileName . If the file exists, and if the CachingFilter.Attributes.timeToLive was specified, delete the file if it is older than timeToLive. Return a valid file handle after processing all the rules.

    Parameters:
    fileProperties - The data structure that contains information about the file that should be represented.
    Returns:
    File The file handle to use.
    Throws:
    java.io.IOException - If errors are encountered while operating on the file.

    sendResponse

    private void sendResponse(CachingFilter.FileProperties fileProperties,
                              javax.servlet.ServletResponse response)
                       throws java.io.IOException
    Write the contents of the fileName to the HTTP Response specified.

    Parameters:
    fileProperties - The data structure that contains information about the file whose contents are to be written to the response.
    response - The HTTP Response to which the cached contents are to be written.
    Throws:
    java.io.IOException
    See Also:
    CachingFilter.FileProperties.setHeadersFromFields(javax.servlet.ServletResponse)

    chainResponse

    private void chainResponse(CachingFilter.FileProperties fileProperties,
                               java.io.File file,
                               java.util.Map requestParameters,
                               java.util.Map fileCache,
                               javax.servlet.ServletRequest request,
                               javax.servlet.ServletResponse response,
                               javax.servlet.FilterChain chain)
                        throws javax.servlet.ServletException,
                               java.io.IOException
    Create a CachingResponseWrapper and chain this filter to the next component in the chain. Create a temporary file and initialise the CachingResponseWrapper with it. After the response has been finished, rename the temporary file to the prorper file to avoid multiple threads with the same response from corrupting the file.

    Parameters:
    fileProperties - The data structure that stores all the meta data about the file to be cached. The data structure will be populated from the request after the request has been processed by the components down the chain.
    file - The File to which the cached response is to be ultimately saved.
    requestParameters - A Map of the HTTP request parameters and their values.
    fileCache - The Map that stores the association between the requestParameters and the cache fileName.
    request - The HTTP Request object that represents the entire HTTP request that is to be processed.
    response - The HTTP Response object to which the response is to be sent.
    chain - The chain to which the processing of the actual response is delegated to.
    Throws:
    javax.servlet.ServletException - If errors are encountered up the chain.
    java.io.IOException - If errors are encountered while writing to the cache file.
    See Also:
    createTemporaryFile(java.lang.String)

    createTemporaryFile

    private java.io.File createTemporaryFile(java.lang.String fileName)
    Create a temporary file based on the fileName specified. This will ensure that only a complete valid cached file is actually available at the location specified by fileName. Also creates any directories that may be required to store the file.

    Parameters:
    fileName - The name of the destination file.
    Returns:
    File - The temporary file to which the response should be stored.

    purgeCache

    private int purgeCache(java.io.File directory)
    Purge all files and directories under the specified directory. Prints out any errors encountered while attempting to delete the directory to System.err.

    Parameters:
    directory - The directory whose children are to be deleted.
    See Also:
    FileUtilities.delete( File, boolean )

    Rakesh API

    Copyright © 2002-2005 - Rakesh Vidyadharan