| 1 14 package org.jmanage.core.alert.delivery; 15 16 import org.jmanage.core.alert.AlertInfo; 17 18 import java.util.Map ; 19 import java.util.Collections ; 20 import java.util.HashMap ; 21 import java.util.Collection ; 22 import java.beans.XMLEncoder ; 23 import java.beans.XMLDecoder ; 24 import java.io.*; 25 26 32 public abstract class PersistedAlerts { 33 34 private Map alerts = Collections.synchronizedMap(new HashMap ()); 35 36 protected PersistedAlerts(){ 37 read(); 39 } 40 41 public void add(AlertInfo alertInfo){ 42 Object prevValue = alerts.put(alertInfo.getAlertId(), alertInfo); 43 assert prevValue == null; 44 save(); 45 } 46 47 public void remove(String alertId){ 48 alerts.remove(alertId); 49 save(); 50 } 51 52 public AlertInfo get(String alertId){ 53 return (AlertInfo)alerts.get(alertId); 54 } 55 56 public Collection getAll(){ 57 return alerts.values(); 58 } 59 60 public void removeAll(){ 61 alerts.clear(); 62 save(); 63 } 64 65 69 public AlertInfo remove(){ 70 AlertInfo alertInfo = null; 71 synchronized(alerts){ 72 if(alerts.size() > 0){ 73 String alertId = 74 (String )alerts.keySet().iterator().next(); 75 alertInfo = (AlertInfo)alerts.remove(alertId); 76 save(); 77 } 78 } 79 return alertInfo; 80 } 81 82 protected abstract String getPersistedFileName(); 83 84 private void save(){ 85 try { 86 XMLEncoder encoder = new XMLEncoder ( 87 new BufferedOutputStream( 88 new FileOutputStream(getPersistedFileName()))); 89 Map persistedAlerts = new HashMap (); 90 persistedAlerts.putAll(alerts); 91 encoder.writeObject(persistedAlerts); 92 encoder.close(); 93 } catch (FileNotFoundException e) { 94 throw new RuntimeException (e); 95 } 96 } 97 98 private void read(){ 99 try { 100 File file = new File(getPersistedFileName()); 101 if(file.exists()){ 102 XMLDecoder decoder = new XMLDecoder ( 103 new BufferedInputStream( 104 new FileInputStream(getPersistedFileName()))); 105 Map persistedAlerts = (Map )decoder.readObject(); 106 alerts.putAll(persistedAlerts); 107 decoder.close(); 108 } 109 } catch (FileNotFoundException e) { 110 throw new RuntimeException (e); 111 } 112 } 113 } 114 | Popular Tags |