001 package com.hammurapi.util;
002
003 import java.util.Iterator;
004 import java.util.Map;
005 import java.util.ServiceLoader;
006
007 /**
008 * Default context uses ServiceLoader to find services in
009 * a given classloader and map of bindings.
010 * @author Pavel Vlasov
011 *
012 */
013 public class DefaultContext implements Context {
014
015 private ClassLoader classLoader;
016 private Map<String, Object> bindings;
017
018 /**
019 * @param classLoader ClassLoader for services. Can be null.
020 * @param bindings Name bindings. Can be null.
021 */
022 public DefaultContext(ClassLoader classLoader, Map<String, Object> bindings) {
023 this.classLoader = classLoader==null ? this.getClass().getClassLoader() : classLoader;
024 this.bindings = bindings;
025 }
026
027 public Object lookup(String name) {
028 return bindings==null ? null : bindings.get(name);
029 }
030
031 public <T> T lookup(Class<T> serviceClass) {
032 ServiceLoader<T> sl = ServiceLoader.load(serviceClass, classLoader);
033 Iterator<T> sit = sl.iterator();
034 return sit.hasNext() ? sit.next() : null;
035 }
036
037 public <T> Iterator<T> lookupAll(Class<T> serviceClass) {
038 ServiceLoader<T> sl = ServiceLoader.load(serviceClass, classLoader);
039 return sl.iterator();
040 }
041
042 }