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.Iterator;
007
008 public class SingletonChainingContext<ST> implements MutableContext {
009
010 private Class<ST> type;
011 private ST service;
012 private Context chain;
013
014 public SingletonChainingContext(Class<ST> type, ST service, Context chain) {
015 this.type = type;
016 this.service = service;
017 this.chain = chain;
018 }
019
020 public void bind(String name, Object obj) {
021 if (chain instanceof MutableContext) {
022 ((MutableContext) chain).bind(name, obj);
023 } else {
024 throw new IllegalStateException("Chain context is not mutable");
025 }
026 }
027
028 public <T> void register(Class<? super T> type, T service) {
029 if (chain instanceof MutableContext) {
030 ((MutableContext) chain).register(type, service);
031 } else {
032 throw new IllegalStateException("Chain context is not mutable");
033 }
034 }
035
036 public Object unbind(String name) {
037 if (chain instanceof MutableContext) {
038 return ((MutableContext) chain).unbind(name);
039 } else {
040 throw new IllegalStateException("Chain context is not mutable");
041 }
042 }
043
044 public <T> void unregister(Class<? super T> type, T service) {
045 if (chain instanceof MutableContext) {
046 ((MutableContext) chain).unregister(type, service);
047 } else {
048 throw new IllegalStateException("Chain context is not mutable");
049 }
050 }
051
052 public Object lookup(String name) {
053 return chain==null ? null : chain.lookup(name);
054 }
055
056 @SuppressWarnings("unchecked")
057 public <T> T lookup(Class<T> serviceClass) {
058 if (serviceClass.equals(type)) {
059 return (T) service;
060 }
061
062 return chain==null ? null : chain.lookup(serviceClass);
063 }
064
065 @SuppressWarnings("unchecked")
066 public <T> Iterator<T> lookupAll(Class<T> serviceClass) {
067 if (serviceClass.equals(type)) {
068 Collection<T> c = new ArrayList<T>();
069 c.add((T) service);
070 if (chain!=null) {
071 Iterator<T> it = chain.lookupAll(serviceClass);
072 while (it.hasNext()) {
073 c.add(it.next());
074 }
075 }
076 return c.iterator();
077 }
078 return (Iterator<T>) (chain==null ? Collections.emptyList().iterator() : chain.lookupAll(serviceClass));
079 }
080
081 }