001 package com.hammurapi.util;
002
003 import java.util.Collections;
004 import java.util.Iterator;
005 import java.util.Map;
006
007 /**
008 * Simple context implementation.
009 * @author Pavel Vlasov
010 *
011 */
012 public class FacadeContext implements Context {
013
014 private Map<String, ?> bindings;
015 private Map<Class<?>, Iterable<?>> services;
016
017 /**
018 * @param classLoader ClassLoader for services. Can be null.
019 * @param bindings Name bindings. Can be null.
020 */
021 public FacadeContext(Map<Class<?>, Iterable<?>> services, Map<String, ?> bindings) {
022 this.services = services;
023 this.bindings = bindings;
024 }
025
026 public Object lookup(String name) {
027 return bindings==null ? null : bindings.get(name);
028 }
029
030 @SuppressWarnings("unchecked")
031 public <T> T lookup(Class<T> serviceClass) {
032 if (services==null) {
033 return null;
034 }
035
036 Iterable<?> sl = services.get(serviceClass);
037 if (sl==null) {
038 return null;
039 }
040
041 Iterator<?> it = sl.iterator();
042 return it.hasNext() ? (T) it.next() : null;
043 }
044
045 @SuppressWarnings("unchecked")
046 public <T> Iterator<T> lookupAll(Class<T> serviceClass) {
047 if (services==null) {
048 return (Iterator<T>) Collections.emptyList().iterator();
049 }
050
051 Iterable<?> sl = services.get(serviceClass);
052 if (sl==null) {
053 return (Iterator<T>) Collections.emptyList().iterator();
054 }
055
056 return (Iterator<T>) sl.iterator();
057 }
058
059 }