001/*
002 * This library is part of OpenCms -
003 * the Open Source Content Management System
004 *
005 * Copyright (c) Alkacon Software GmbH & Co. KG (http://www.alkacon.com)
006 *
007 * This library is free software; you can redistribute it and/or
008 * modify it under the terms of the GNU Lesser General Public
009 * License as published by the Free Software Foundation; either
010 * version 2.1 of the License, or (at your option) any later version.
011 *
012 * This library is distributed in the hope that it will be useful,
013 * but WITHOUT ANY WARRANTY; without even the implied warranty of
014 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
015 * Lesser General Public License for more details.
016 *
017 * For further information about Alkacon Software, please see the
018 * company website: http://www.alkacon.com
019 *
020 * For further information about OpenCms, please see the
021 * project website: http://www.opencms.org
022 *
023 * You should have received a copy of the GNU Lesser General Public
024 * License along with this library; if not, write to the Free Software
025 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
026 */
027
028package org.opencms.cache;
029
030import org.opencms.file.CmsResource;
031import org.opencms.main.CmsLog;
032import org.opencms.util.CmsFileUtil;
033
034import java.io.File;
035import java.io.IOException;
036import java.io.UnsupportedEncodingException;
037
038import org.apache.commons.codec.digest.DigestUtils;
039import org.apache.commons.logging.Log;
040
041/**
042 * Implements a name based RFS file based disk cache, that handles parameter based versions of VFS files.<p>
043 *
044 * This RFS cache operates on file names, plus a hash code calculated from
045 * {@link org.opencms.file.CmsResource#getDateLastModified()}, {@link org.opencms.file.CmsResource#getDateCreated()}
046 * and {@link org.opencms.file.CmsResource#getLength()}. Optional parameters can be appended to this name,
047 * which will be added as a second hash code. This way a file can have multiple versions based on different parameters.<p>
048 *
049 * This cache is usable for resources from the online AND the offline project at the same time,
050 * because any change to a resource will result in a changed hash code. This means a resource changed in the offline
051 * project will have a new hash code compared to the online project. If the resource is identical in the online and
052 * the offline project, the generated hash codes will be the same.<p>
053 *
054 * @since 6.2.0
055 */
056public class CmsVfsNameBasedDiskCache {
057
058    /** Logger instance for this class. */
059    private static final Log LOG = CmsLog.getLog(CmsVfsNameBasedDiskCache.class);
060
061    /** The name of the cache base repository folder in the RFS. */
062    private String m_rfsRepository;
063
064    /**
065     * Creates a new disk cache.<p>
066     *
067     * @param basepath the base path for the cache in the RFS
068     * @param foldername the folder name for this cache, to be used a sub-folder for the base folder
069     */
070    public CmsVfsNameBasedDiskCache(String basepath, String foldername) {
071
072        // normalize the given folder name
073        m_rfsRepository = CmsFileUtil.normalizePath(basepath + foldername + File.separatorChar);
074    }
075
076    /**
077     * Returns the content of the requested file in the disk cache, or <code>null</code> if the
078     * file is not found in the cache, or is found but outdated.<p>
079     *
080     * @param rfsName the file RFS name to look up in the cache
081     *
082     * @return the content of the requested file in the disk cache, or <code>null</code>
083     */
084    public byte[] getCacheContent(String rfsName) {
085
086        try {
087            File f = new File(rfsName);
088            if (f.exists()) {
089                long age = f.lastModified();
090                if ((System.currentTimeMillis() - age) > 3600000) {
091                    // file has not been touched for 1 hour, touch the file with the current date
092                    f.setLastModified(System.currentTimeMillis());
093                }
094                return CmsFileUtil.readFile(f);
095            }
096        } catch (IOException e) {
097            // unable to read content
098            LOG.debug("Unable to read file " + rfsName, e);
099        }
100        return null;
101    }
102
103    /**
104     * Returns the RFS name to use for caching the given VFS resource with parameters in the disk cache.<p>
105     *
106     * @param resource the VFS resource to generate the cache name for
107     * @param parameters the parameters of the request to the VFS resource
108     *
109     * @return the RFS name to use for caching the given VFS resource with parameters
110     */
111    public String getCacheName(CmsResource resource, String parameters) {
112
113        // calculate the base cache path for the resource
114        String rfsName = m_rfsRepository + resource.getRootPath();
115        String extension = CmsFileUtil.getExtension(rfsName);
116
117        // create a StringBuffer for the result
118        StringBuffer buf = new StringBuffer(rfsName.length() + 24);
119        buf.append(rfsName.substring(0, rfsName.length() - extension.length()));
120
121        // calculate a hash code that contains the resource DateLastModified, DateCreated and Length
122        StringBuffer ext = new StringBuffer(48);
123        ext.append(resource.getDateLastModified());
124        ext.append(';');
125        ext.append(resource.getDateCreated());
126        if (resource.getLength() > 0) {
127            ext.append(';');
128            ext.append(resource.getLength());
129        }
130        // append hash code to the result buffer
131        buf.append('_');
132        buf.append(ext.toString().hashCode());
133
134        // check if parameters are provided, if so add them as well
135        if (parameters != null) {
136            buf.append('_');
137            try {
138                buf.append(DigestUtils.md5Hex(parameters.getBytes("UTF-8")));
139            } catch (UnsupportedEncodingException e) {
140                // can't happen
141                LOG.error(e.getLocalizedMessage(), e);
142            }
143        }
144
145        // finally append the extension from the original file name
146        buf.append(extension);
147        return buf.toString();
148    }
149
150    /**
151     * Returns the absolute path of the cache repository in the RFS.<p>
152     *
153     * @return the absolute path of the cache repository in the RFS
154     */
155    public String getRepositoryPath() {
156
157        return m_rfsRepository;
158    }
159
160    /**
161     * Returns the the requested file is available within the cache.<p>
162     *
163     * @param rfsName the file name
164     *
165     * @return <code>true</code> if the file is available
166     */
167    public boolean hasCacheContent(String rfsName) {
168
169        File f = new File(rfsName);
170        if (f.exists()) {
171            return true;
172        }
173        return false;
174    }
175
176    /**
177     * Saves the given file content in the disk cache.<p>
178     *
179     * @param rfsName the RFS name of the file to save the content in
180     * @param content the content of the file to save
181     *
182     * @throws IOException in case of disk access errors
183     */
184    public void saveCacheFile(String rfsName, byte[] content) throws IOException {
185
186        CmsVfsDiskCache.saveFile(rfsName, content);
187    }
188}