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

📄 abstractdiskpersistencelistener.java

📁 oscache-2.4.1-full
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
            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
        }
    }
    
    // try 30s to delete the file
    private static final long DELETE_THREAD_SLEEP = 500;
    private static final int DELETE_COUNT = 60; 

    protected void remove(File file) throws CachePersistenceException {
        int count = DELETE_COUNT;
        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.exists() && !file.delete() && count != 0) {
                count--;
                try {
                    Thread.sleep(DELETE_THREAD_SLEEP);
                } catch (InterruptedException ignore) {
                } 
            }
        } catch (Exception e) {
            throw new CachePersistenceException("Unable to remove '" + file + "' from the cache: " + e);
        }
        if (file.exists() && count == 0) {
            throw new CachePersistenceException("Unable to delete '" + file + "' from the cache. "+DELETE_COUNT+" attempts at "+DELETE_THREAD_SLEEP+" milliseconds intervals.");
        }
    }

    /**
    * 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 file exists before testing if parent exists
        if (!file.exists()) {
            // 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);
            }
        }

        // Write the object to disk
        try {
            FileOutputStream fout = new FileOutputStream(file);
            try {
                ObjectOutputStream oout = new ObjectOutputStream(new BufferedOutputStream(fout));
                try {
                    oout.writeObject(obj);
                    oout.flush();
                } finally {
                    try {
                        oout.close();
                    } catch (Exception e) {
                    }
                }
            } finally {
                try {
                    fout.close();
                } catch (Exception e) {
                }
            }
        } catch (Exception e) {
            int count = DELETE_COUNT;
            while (file.exists() && !file.delete() && count != 0) {
                count--;
                try {
                    Thread.sleep(DELETE_THREAD_SLEEP);
                } catch (InterruptedException ignore) {
                } 
            }
            throw new CachePersistenceException("Unable to write '" + file + "' in the cache. Exception: " + e.getClass().getName() + ", Message: " + e.getMessage());
        }
    }

    /**
    * 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(getCacheFileName(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) {
            ObjectInputStream oin = null;

            try {
                BufferedInputStream 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 {
              // HHDE: no need to close in. Will be closed by oin
                try {
                    oin.close();
                } catch (Exception ex) {
                }
                }
            }

        return readContent;
    }
}

⌨️ 快捷键说明

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