| 1 | package com.hammurapi.common; |
| 2 | |
| 3 | import java.util.Collections; |
| 4 | import java.util.Iterator; |
| 5 | import java.util.Map; |
| 6 | |
| 7 | /** |
| 8 | * Simple context implementation. |
| 9 | * @author Pavel Vlasov |
| 10 | * |
| 11 | */ |
| 12 | public class FacadeContext implements Context { |
| 13 | |
| 14 | private Map<String, ?> bindings; |
| 15 | private Map<Class<?>, Iterable<?>> services; |
| 16 | |
| 17 | /** |
| 18 | * @param classLoader ClassLoader for services. Can be null. |
| 19 | * @param bindings Name bindings. Can be null. |
| 20 | */ |
| 21 | public FacadeContext(Map<Class<?>, Iterable<?>> services, Map<String, ?> bindings) { |
| 22 | this.services = services; |
| 23 | this.bindings = bindings; |
| 24 | } |
| 25 | |
| 26 | public Object lookup(String name) { |
| 27 | return bindings==null ? null : bindings.get(name); |
| 28 | } |
| 29 | |
| 30 | @SuppressWarnings("unchecked") |
| 31 | public <T> T lookup(Class<T> serviceClass) { |
| 32 | if (services==null) { |
| 33 | return null; |
| 34 | } |
| 35 | |
| 36 | Iterable<?> sl = services.get(serviceClass); |
| 37 | if (sl==null) { |
| 38 | return null; |
| 39 | } |
| 40 | |
| 41 | Iterator<?> it = sl.iterator(); |
| 42 | return it.hasNext() ? (T) it.next() : null; |
| 43 | } |
| 44 | |
| 45 | @SuppressWarnings("unchecked") |
| 46 | public <T> Iterator<T> lookupAll(Class<T> serviceClass) { |
| 47 | if (services==null) { |
| 48 | return (Iterator<T>) Collections.emptyList().iterator(); |
| 49 | } |
| 50 | |
| 51 | Iterable<?> sl = services.get(serviceClass); |
| 52 | if (sl==null) { |
| 53 | return (Iterator<T>) Collections.emptyList().iterator(); |
| 54 | } |
| 55 | |
| 56 | return (Iterator<T>) sl.iterator(); |
| 57 | } |
| 58 | |
| 59 | } |