⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 abstractdiskpersistencelistener.java

📁 一个不错的cache
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
    * @return Adjusted cache path    */    protected String adjustFileCachePath(String cachePathStr) {        if (cachePathStr.compareToIgnoreCase(CONTEXT_TMPDIR) == 0) {            cachePathStr = contextTmpDir.getAbsolutePath();        }        return cachePathStr;    }    /**    *        Set caching to file on or off.    *  If the <code>cache.path</code> property exists, we assume file caching is turned on.    *        By the same token, to turn off file caching just remove this property.    */    protected void initFileCaching(String cachePathStr) {        if (cachePathStr != null) {            cachePath = new File(cachePathStr);            try {                if (!cachePath.exists()) {                    if (log.isInfoEnabled()) {                        log.info("cache.path '" + cachePathStr + "' does not exist, creating");                    }                    cachePath.mkdirs();                }                if (!cachePath.isDirectory()) {                    log.error("cache.path '" + cachePathStr + "' is not a directory");                    cachePath = null;                } else if (!cachePath.canWrite()) {                    log.error("cache.path '" + cachePathStr + "' is not a writable location");                    cachePath = null;                }            } catch (Exception e) {                log.error("cache.path '" + cachePathStr + "' could not be used", e);                cachePath = null;            }        } else {            // Use default value        }    }    protected void remove(File file) throws CachePersistenceException {        try {            // Loop until we are able to delete (No current read).            // The cache must ensure that there are never two concurrent threads            // doing write (store and delete) operations on the same item.            // Delete only should be enough but file.exists prevents infinite loop            while (!file.delete() && file.exists()) {                ;            }        } catch (Exception e) {            throw new CachePersistenceException("Unable to remove '" + file + "' from the cache: " + e);        }    }    /**    * Stores an object using the supplied file object    *    * @param file The file to use for storing the object    * @param obj the object to store    * @throws CachePersistenceException    */    protected void store(File file, Object obj) throws CachePersistenceException {        // check if the directory structure required exists and create it if it doesn't        File filepath = new File(file.getParent());        try {            if (!filepath.exists()) {                filepath.mkdirs();            }        } catch (Exception e) {            throw new CachePersistenceException("Unable to create the directory " + filepath);        }        // Loop until we are able to delete (No current read).        // The cache must ensure that there are never two concurrent threads        // doing write (store and delete) operations on the same item.        // Delete only should be enough but file.exists prevents infinite loop        while (file.exists() && !file.delete()) {            ;        }        // Write the object to disk        FileOutputStream fout = null;        ObjectOutputStream oout = null;        try {            fout = new FileOutputStream(file);            oout = new ObjectOutputStream(fout);            oout.writeObject(obj);            oout.flush();        } catch (Exception e) {            while (file.exists() && !file.delete()) {                ;            }            throw new CachePersistenceException("Unable to write '" + file + "' in the cache. Exception: " + e.getClass().getName() + ", Message: " + e.getMessage());        } finally {            try {                fout.close();            } catch (Exception e) {            }            try {                oout.close();            } catch (Exception e) {            }        }    }    /**    * Build fully qualified cache file for the specified cache entry key.    *    * @param key   Cache Entry Key.    * @return File reference.    */    protected File getCacheFile(String key) {        char[] fileChars = getCacheFileName(key);        File file = new File(root, new String(fileChars) + "." + CACHE_EXTENSION);        return file;    }    /**    * Build cache file name for the specified cache entry key.    *    * @param key   Cache Entry Key.    * @return char[] file name.    */    protected abstract char[] getCacheFileName(String key);    /**    * Builds a fully qualified file name that specifies a cache group entry.    *    * @param group The name of the group    * @return A File reference    */    private File getCacheGroupFile(String group) {        int AVERAGE_PATH_LENGTH = 30;        if ((group == null) || (group.length() == 0)) {            throw new IllegalArgumentException("Invalid group '" + group + "' specified to getCacheGroupFile.");        }        StringBuffer path = new StringBuffer(AVERAGE_PATH_LENGTH);        // Build a fully qualified file name for this group        path.append(GROUP_DIRECTORY).append('/');        path.append(group).append('.').append(CACHE_EXTENSION);        return new File(root, path.toString());    }    /**    * This allows to persist different scopes in different path in the case of    * file caching.    *    * @param scope   Cache scope.    * @return The scope subpath    */    private String getPathPart(int scope) {        if (scope == PageContext.SESSION_SCOPE) {            return SESSION_CACHE_SUBPATH;        } else {            return APPLICATION_CACHE_SUBPATH;        }    }    /**    * Clears a whole directory, starting from the specified    * directory    *    * @param baseDirName The root directory to delete    * @throws CachePersistenceException    */    private void clear(String baseDirName) throws CachePersistenceException {        File baseDir = new File(baseDirName);        File[] fileList = baseDir.listFiles();        try {            if (fileList != null) {                // Loop through all the files and directory to delete them                for (int count = 0; count < fileList.length; count++) {                    if (fileList[count].isFile()) {                        fileList[count].delete();                    } else {                        // Make a recursive call to delete the directory                        clear(fileList[count].toString());                        fileList[count].delete();                    }                }            }            // Delete the root directory            baseDir.delete();        } catch (Exception e) {            throw new CachePersistenceException("Unable to clear the cache directory");        }    }    /**    * Retrives a serialized object from the supplied file, or returns    * <code>null</code> if the file does not exist.    *    * @param file The file to deserialize    * @return The deserialized object    * @throws CachePersistenceException    */    private Object retrieve(File file) throws CachePersistenceException {        Object readContent = null;        boolean fileExist;        try {            fileExist = file.exists();        } catch (Exception e) {            throw new CachePersistenceException("Unable to verify if " + file + " exists: " + e);        }        // Read the file if it exists        if (fileExist) {            BufferedInputStream in = null;            ObjectInputStream oin = null;            try {                in = new BufferedInputStream(new FileInputStream(file));                oin = new ObjectInputStream(in);                readContent = oin.readObject();            } catch (Exception e) {                // We expect this exception to occur.                // This is when the item will be invalidated (written or deleted)                // during read.                // The cache has the logic to retry reading.                throw new CachePersistenceException("Unable to read '" + file.getAbsolutePath() + "' from the cache: " + e);            } finally {                try {                    oin.close();                } catch (Exception ex) {                }                try {                    in.close();                } catch (Exception ex) {                }            }        }        return readContent;    }}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -