View Javadoc

1   package cz.cuni.amis.utils.maps;
2   
3   import java.util.HashMap;
4   import java.util.Map;
5   
6   import cz.cuni.amis.utils.listener.Event;
7   import cz.cuni.amis.utils.listener.IListener;
8   import cz.cuni.amis.utils.listener.Listeners;
9   import cz.cuni.amis.utils.listener.ListenersMap;
10  
11  public class MapWithKeyListeners<KEY, VALUE> {
12  	
13  	public static class KeyCreatedEvent<KEY, VALUE> implements Event {
14  		
15  		private KEY key;
16  		private VALUE value;
17  		
18  		public KeyCreatedEvent(KEY key, VALUE value) {
19  			this.key = key;
20  			this.value = value;
21  		}
22  
23  		public KEY getKey() {
24  			return key;
25  		}
26  
27  		public void setKey(KEY key) {
28  			this.key = key;
29  		}
30  
31  		public VALUE getValue() {
32  			return value;
33  		}
34  
35  		public void setValue(VALUE value) {
36  			this.value = value;
37  		}
38  		
39  	}
40  	
41  	public static interface IKeyCreatedListener<KEY, VALUE> extends IListener<KeyCreatedEvent<KEY, VALUE>> {
42  	};
43  	
44  	public static class KeyCreatedEventListenerNotifier<KEY, VALUE> implements Listeners.ListenerNotifier<IListener> {
45  
46  		public KeyCreatedEvent<KEY, VALUE> event;
47  		
48  		@Override
49  		public Object getEvent() {
50  			return event;
51  		}
52  
53  		@Override
54  		public void notify(IListener listener) {
55  			listener.notify(event);
56  		}
57  				
58  	}
59  
60  	private Map<KEY, VALUE> map = new HashMap<KEY, VALUE>();
61  	
62  	private ListenersMap<KEY> listeners = new ListenersMap<KEY>();
63  	
64  	private KeyCreatedEventListenerNotifier<KEY, VALUE> notifier = new KeyCreatedEventListenerNotifier<KEY, VALUE>();
65  	
66  	public void put(KEY key, VALUE value) {
67  		VALUE oldValue = null;
68  		synchronized(map) {
69  			oldValue = map.put(key, value);
70  		}
71  		if (oldValue == null) {
72  			notifier.event = new KeyCreatedEvent<KEY, VALUE>(key, value);
73  			listeners.notify(key, notifier);
74  		}
75  	}
76  	
77  	public void remove(KEY key) {
78  		synchronized(map) {
79  			map.remove(key);
80  		}
81  	}
82  	
83  	public void addWeakListener(KEY key, IKeyCreatedListener<KEY, VALUE> listener) {
84  		listeners.add(key, listener);
85  	}
86  	
87  	public boolean isListening(KEY key, IKeyCreatedListener<KEY, VALUE> listener) {
88  		return listeners.isListening(key, listener);
89  	}
90  	
91  	public void removeListener(KEY key, IKeyCreatedListener<KEY, VALUE> listener) {
92  		listeners.remove(key, listener);
93  	}
94  	
95  }