001 package com.hammurapi.util;
002
003 import java.util.ArrayList;
004 import java.util.Collection;
005 import java.util.Collections;
006 import java.util.HashMap;
007 import java.util.Iterator;
008 import java.util.Map;
009
010 /**
011 * Simple context implementation.
012 * @author Pavel Vlasov
013 *
014 */
015 public class SimpleMutableContext implements MutableContext {
016
017 private Map<String, Object> bindings = new HashMap<String, Object>();
018 private Map<Class<?>, Collection<?>> services = new HashMap<Class<?>, Collection<?>>();
019
020 public SimpleMutableContext() {
021
022 }
023
024 /**
025 * @param classLoader ClassLoader for services. Can be null.
026 * @param bindings Name bindings. Can be null.
027 */
028 public SimpleMutableContext(Map<Class<?>, Collection<?>> services, Map<String, ?> bindings) {
029 if (services!=null) {
030 this.services.putAll(services);
031 }
032
033 if (bindings!=null) {
034 this.bindings.putAll(bindings);
035 }
036 }
037
038 public synchronized void bind(String name, Object value) {
039 bindings.put(name, value);
040 }
041
042 public synchronized Object unbind(String name) {
043 return bindings.remove(name);
044 }
045
046 @SuppressWarnings("unchecked")
047 public synchronized <T> void register(Class<? super T> serviceType, T service) {
048 Collection<Object> sl = (Collection<Object>) services.get(serviceType);
049 if (sl==null) {
050 sl = new ArrayList<Object>();
051 services.put(serviceType, sl);
052 }
053 sl.add(service);
054 }
055
056 public synchronized <T> void unregister(Class<? super T> serviceType, T service) {
057 Collection<?> sl = services.get(serviceType);
058 if (sl!=null) {
059 sl.remove(service);
060 if (sl.isEmpty()) {
061 services.remove(serviceType);
062 }
063 }
064 }
065
066 public Object lookup(String name) {
067 return bindings.get(name);
068 }
069
070 @SuppressWarnings("unchecked")
071 public <T> T lookup(Class<T> serviceClass) {
072 Collection<?> sl = services.get(serviceClass);
073 if (sl==null) {
074 return null;
075 }
076
077 if (sl.isEmpty()) {
078 return null;
079 }
080
081 return (T) sl.iterator().next();
082 }
083
084 @SuppressWarnings("unchecked")
085 public <T> Iterator<T> lookupAll(Class<T> serviceClass) {
086 Collection<?> sl = services.get(serviceClass);
087 if (sl==null) {
088 return (Iterator<T>) Collections.emptyList().iterator();
089 }
090
091 if (sl.isEmpty()) {
092 return (Iterator<T>) Collections.emptyList().iterator();
093 }
094
095 return (Iterator<T>) sl.iterator();
096 }
097
098 }