1 package org.jgroups.persistence; 2 3 10 11 12 import java.io.*; 13 import java.util.*; 14 15 public class FilePersistenceManager implements PersistenceManager 16 { 17 private final File file; 18 19 22 public FilePersistenceManager(String propertiesFilename) 23 throws Exception 24 { 25 Properties properties = new Properties(); 26 properties.load(new FileInputStream(propertiesFilename)); 27 String path = properties.getProperty(PersistenceFactory.persistProp); 28 file = new File(path); 29 file.createNewFile(); 30 } 31 32 36 public void save(Serializable key, Serializable val) throws CannotPersistException 37 { 38 try 39 { 40 Map map = retrieveAll(); 41 map.put(key, val); 42 saveAll(map); 43 } 44 catch (CannotRetrieveException e) 45 { 46 throw new CannotPersistException(e, "Unable to pre-load existing store."); 47 } 48 } 49 50 53 public Serializable remove(Serializable key) throws CannotRemoveException 54 { 55 Object o; 56 try 57 { 58 Map map = retrieveAll(); 59 o = map.remove(key); 60 saveAll(map); 61 } 62 catch (CannotRetrieveException e) 63 { 64 throw new CannotRemoveException(e, "Unable to pre-load existing store."); 65 } 66 catch (CannotPersistException e) 67 { 68 throw new CannotRemoveException(e, "Unable to pre-load existing store."); 69 } 70 return (Serializable) o; 71 } 72 73 74 78 public void saveAll(Map map) throws CannotPersistException 79 { 80 try 81 { 82 OutputStream fos = new FileOutputStream(file); 83 Properties prop = new Properties(); 84 for (Iterator iterator = map.entrySet().iterator(); iterator.hasNext();) 86 { 87 Map.Entry entry = (Map.Entry) iterator.next(); 88 prop.setProperty(entry.getKey().toString(), entry.getValue().toString()); 89 } 90 prop.store(fos, null); 91 fos.flush(); 92 fos.close(); 93 } 94 catch (IOException e) 95 { 96 throw new CannotPersistException(e, "Cannot save to: " + file.getAbsolutePath()); 97 } 98 } 99 100 101 106 public Map retrieveAll() throws CannotRetrieveException 107 { 108 try 109 { 110 Properties prop = new Properties(); 111 FileInputStream fis = new FileInputStream(file); 112 prop.load(fis); 113 fis.close(); 114 return filterLoadedValues(prop); 115 } 116 catch (IOException e) 117 { 118 throw new CannotRetrieveException(e, "Unable to load from file: " + file.getAbsolutePath()); 119 } 120 } 121 122 128 protected Map filterLoadedValues(Map in) 129 { 130 Map out = new HashMap(); 131 for (Iterator iterator = in.entrySet().iterator(); iterator.hasNext();) 132 { 133 Map.Entry entry = (Map.Entry) iterator.next(); 134 out.put(entry.getKey().toString(), Float.valueOf(entry.getValue().toString())); 135 } 136 return out; 137 } 138 139 140 144 public void clear() throws CannotRemoveException 145 { 146 try 147 { 148 saveAll(Collections.EMPTY_MAP); 149 } 150 catch (CannotPersistException e) 151 { 152 throw new CannotRemoveException(e, "Unable to clear map."); 153 } 154 } 155 156 157 161 public void shutDown() 162 { 163 return; 164 } 165 } | Popular Tags |