1 5 package com.opensymphony.oscache.plugins.diskpersistence; 6 7 import com.opensymphony.oscache.base.Config; 8 import com.opensymphony.oscache.base.persistence.PersistenceListener; 9 10 import java.security.MessageDigest ; 11 import java.security.NoSuchAlgorithmException ; 12 13 22 public class HashDiskPersistenceListener extends AbstractDiskPersistenceListener { 23 public final static String HASH_ALGORITHM_KEY = "cache.persistence.disk.hash.algorithm"; 24 public final static String DEFAULT_HASH_ALGORITHM = "MD5"; 25 protected MessageDigest md = null; 26 27 32 public PersistenceListener configure(Config config) { 33 try { 34 if (config.getProperty(HashDiskPersistenceListener.HASH_ALGORITHM_KEY) != null) { 35 try { 36 md = MessageDigest.getInstance(config.getProperty(HashDiskPersistenceListener.HASH_ALGORITHM_KEY)); 37 } catch (NoSuchAlgorithmException e) { 38 md = MessageDigest.getInstance(HashDiskPersistenceListener.DEFAULT_HASH_ALGORITHM); 39 } 40 } else { 41 md = MessageDigest.getInstance(HashDiskPersistenceListener.DEFAULT_HASH_ALGORITHM); 42 } 43 } catch (NoSuchAlgorithmException e) { 44 e.printStackTrace(); 45 throw new RuntimeException ("No hash algorithm available for disk persistence", e); 46 } 47 48 return super.configure(config); 49 } 50 51 58 protected synchronized char[] getCacheFileName(String key) { 59 if ((key == null) || (key.length() == 0)) { 60 throw new IllegalArgumentException ("Invalid key '" + key + "' specified to getCacheFile."); 61 } 62 63 byte[] digest = md.digest(key.getBytes()); 64 65 return byteArrayToHexString(digest).toCharArray(); 66 } 67 68 74 static String byteArrayToHexString(byte[] in) { 75 if ((in == null) || (in.length <= 0)) { 76 return null; 77 } 78 79 StringBuffer out = new StringBuffer (in.length * 2); 80 81 for (int i = 0; i < in.length; i++) { 82 byte ch = (byte) (in[i] & 0xF0); ch = (byte) (ch >>> 4); 84 85 ch = (byte) (ch & 0x0F); 87 88 out.append(PSEUDO[(int) ch]); ch = (byte) (in[i] & 0x0F); out.append(PSEUDO[(int) ch]); i++; 93 } 94 95 return out.toString(); 96 } 97 98 static final String [] PSEUDO = { 99 "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", 100 "E", "F" 101 }; 102 103 } 104 | Popular Tags |