// ServletFileCache.java
//
//    A cache used for a data produced by a servlet.
//
//    senger@ebi.ac.uk
//    November 2003
//

// TBD: this may go later to the general tools
package org.biomoby.client;

import javax.servlet.ServletContext;

/**
 * A simple cache implementation meant to be used in a servlet
 * environment in order to save and later return (any) data, or to
 * find that the given data are not available in the cache. It uses
 * files to store data. <p>
 *
 * @author <A HREF="mailto:senger@ebi.ac.uk">Martin Senger</A>
 * @version $Id: ServletFileCache.java,v 1.4 2005/04/07 16:37:02 kawas Exp $
 */
public class ServletFileCache
    extends FileCache {

    protected ServletContext context;
    protected String contextPath;

    /**************************************************************************
     * Constructor specifying a context of the calling servlet. Use
     * this constructor if you wish (and if your servlet has proper
     * write permissions) to store the cached objects in files created
     * in the directory specified by this servlet context (which
     * usually mean that the files will be created in directory
     *
     * <pre>
     * <tomcat-home>/webapps/<your-context>/cache/
     * </pre>
     *
     * The not existing directories (for example the last 'cache'
     * directory) will be created for you.
     *
     * The 'contextPath' is a path (relative to the servlet context)
     * where the cached files will be created (actually starting from
     * here, because they may be created in a deeper directory
     * structure. Usually you get it in the calling servlet from the
     * request by method request.getContextPath(). The 'contextPath'
     * starts with a "/" character but does not end with a "/"
     * character.
     **************************************************************************/
    public ServletFileCache (ServletContext context,
			     String contextPath) {
	super();
	this.context = context;
	this.contextPath = contextPath;
    }

    /**************************************************************************
     * Return a full URL of the cached object 'id'.
     **************************************************************************/
    public String getURL (String id) {
	return contextPath + getRelativeFilename (id);
    }

    /**************************************************************************
     * Returns a full file name representing an object identified by
     * its 'id' (but the file still does not need to exist). The path
     * is created from the servlet context (as given in the
     * constructor).
     **************************************************************************/
    protected String getFullFilename (String id) {
	return context.getRealPath (getRelativeFilename (id));
    }
}
