1 | package com.hammurapi.common; |
2 | |
3 | import java.util.ArrayList; |
4 | import java.util.Collection; |
5 | import java.util.Collections; |
6 | import java.util.Iterator; |
7 | |
8 | public class SingletonChainingContext<ST> implements MutableContext { |
9 | |
10 | private Class<ST> type; |
11 | private ST service; |
12 | private Context chain; |
13 | |
14 | public SingletonChainingContext(Class<ST> type, ST service, Context chain) { |
15 | this.type = type; |
16 | this.service = service; |
17 | this.chain = chain; |
18 | } |
19 | |
20 | public void bind(String name, Object obj) { |
21 | if (chain instanceof MutableContext) { |
22 | ((MutableContext) chain).bind(name, obj); |
23 | } else { |
24 | throw new IllegalStateException("Chain context is not mutable"); |
25 | } |
26 | } |
27 | |
28 | public <T> void register(Class<? super T> type, T service) { |
29 | if (chain instanceof MutableContext) { |
30 | ((MutableContext) chain).register(type, service); |
31 | } else { |
32 | throw new IllegalStateException("Chain context is not mutable"); |
33 | } |
34 | } |
35 | |
36 | public Object unbind(String name) { |
37 | if (chain instanceof MutableContext) { |
38 | return ((MutableContext) chain).unbind(name); |
39 | } else { |
40 | throw new IllegalStateException("Chain context is not mutable"); |
41 | } |
42 | } |
43 | |
44 | public <T> void unregister(Class<? super T> type, T service) { |
45 | if (chain instanceof MutableContext) { |
46 | ((MutableContext) chain).unregister(type, service); |
47 | } else { |
48 | throw new IllegalStateException("Chain context is not mutable"); |
49 | } |
50 | } |
51 | |
52 | public Object lookup(String name) { |
53 | return chain==null ? null : chain.lookup(name); |
54 | } |
55 | |
56 | @SuppressWarnings("unchecked") |
57 | public <T> T lookup(Class<T> serviceClass) { |
58 | if (serviceClass.equals(type)) { |
59 | return (T) service; |
60 | } |
61 | |
62 | return chain==null ? null : chain.lookup(serviceClass); |
63 | } |
64 | |
65 | @SuppressWarnings("unchecked") |
66 | public <T> Iterator<T> lookupAll(Class<T> serviceClass) { |
67 | if (serviceClass.equals(type)) { |
68 | Collection<T> c = new ArrayList<T>(); |
69 | c.add((T) service); |
70 | if (chain!=null) { |
71 | Iterator<T> it = chain.lookupAll(serviceClass); |
72 | while (it.hasNext()) { |
73 | c.add(it.next()); |
74 | } |
75 | } |
76 | return c.iterator(); |
77 | } |
78 | return (Iterator<T>) (chain==null ? Collections.emptyList().iterator() : chain.lookupAll(serviceClass)); |
79 | } |
80 | |
81 | } |