| 1 | package com.hammurapi.common; |
| 2 | |
| 3 | import java.util.ArrayList; |
| 4 | import java.util.Collection; |
| 5 | import java.util.Collections; |
| 6 | import java.util.HashMap; |
| 7 | import java.util.Iterator; |
| 8 | import java.util.Map; |
| 9 | |
| 10 | /** |
| 11 | * Simple context implementation. |
| 12 | * @author Pavel Vlasov |
| 13 | * |
| 14 | */ |
| 15 | public class SimpleMutableContext implements MutableContext { |
| 16 | |
| 17 | private Map<String, Object> bindings = new HashMap<String, Object>(); |
| 18 | private Map<Class<?>, Collection<?>> services = new HashMap<Class<?>, Collection<?>>(); |
| 19 | |
| 20 | public SimpleMutableContext() { |
| 21 | |
| 22 | } |
| 23 | |
| 24 | /** |
| 25 | * @param classLoader ClassLoader for services. Can be null. |
| 26 | * @param bindings Name bindings. Can be null. |
| 27 | */ |
| 28 | public SimpleMutableContext(Map<Class<?>, Collection<?>> services, Map<String, ?> bindings) { |
| 29 | if (services!=null) { |
| 30 | this.services.putAll(services); |
| 31 | } |
| 32 | |
| 33 | if (bindings!=null) { |
| 34 | this.bindings.putAll(bindings); |
| 35 | } |
| 36 | } |
| 37 | |
| 38 | public synchronized void bind(String name, Object value) { |
| 39 | bindings.put(name, value); |
| 40 | } |
| 41 | |
| 42 | public synchronized Object unbind(String name) { |
| 43 | return bindings.remove(name); |
| 44 | } |
| 45 | |
| 46 | @SuppressWarnings("unchecked") |
| 47 | public synchronized <T> void register(Class<? super T> serviceType, T service) { |
| 48 | Collection<Object> sl = (Collection<Object>) services.get(serviceType); |
| 49 | if (sl==null) { |
| 50 | sl = new ArrayList<Object>(); |
| 51 | services.put(serviceType, sl); |
| 52 | } |
| 53 | sl.add(service); |
| 54 | } |
| 55 | |
| 56 | public synchronized <T> void unregister(Class<? super T> serviceType, T service) { |
| 57 | Collection<?> sl = services.get(serviceType); |
| 58 | if (sl!=null) { |
| 59 | sl.remove(service); |
| 60 | if (sl.isEmpty()) { |
| 61 | services.remove(serviceType); |
| 62 | } |
| 63 | } |
| 64 | } |
| 65 | |
| 66 | public Object lookup(String name) { |
| 67 | return bindings.get(name); |
| 68 | } |
| 69 | |
| 70 | @SuppressWarnings("unchecked") |
| 71 | public <T> T lookup(Class<T> serviceClass) { |
| 72 | Collection<?> sl = services.get(serviceClass); |
| 73 | if (sl==null) { |
| 74 | return null; |
| 75 | } |
| 76 | |
| 77 | if (sl.isEmpty()) { |
| 78 | return null; |
| 79 | } |
| 80 | |
| 81 | return (T) sl.iterator().next(); |
| 82 | } |
| 83 | |
| 84 | @SuppressWarnings("unchecked") |
| 85 | public <T> Iterator<T> lookupAll(Class<T> serviceClass) { |
| 86 | Collection<?> sl = services.get(serviceClass); |
| 87 | if (sl==null) { |
| 88 | return (Iterator<T>) Collections.emptyList().iterator(); |
| 89 | } |
| 90 | |
| 91 | if (sl.isEmpty()) { |
| 92 | return (Iterator<T>) Collections.emptyList().iterator(); |
| 93 | } |
| 94 | |
| 95 | return (Iterator<T>) sl.iterator(); |
| 96 | } |
| 97 | |
| 98 | } |