ce912ef37b53b6c54dd8a51717f6cced462991e5
[utils] / support / general / src / main / java / org / wamblee / general / ThreadSpecificProxyFactory.java
1 /*
2  * Copyright 2005-2010 the original author or authors.
3  * 
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  * 
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  * 
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 package org.wamblee.general;
17
18 import java.lang.reflect.InvocationHandler;
19 import java.lang.reflect.Proxy;
20
21 /**
22  * Thread-specific proxy is used to create implementations of interfaces that
23  * delegate to a thread-specific implementation of the service.
24  * 
25  * It can be used for instance to create a contextual reference to an entity
26  * manager that delegates to a thread-specific instance.
27  * 
28  * The {@link #set(Object)} method sets the current service instance for the
29  * current thread. The {@link #get()} method gets the current service instance
30  * for the current thread. The {@link #getProxy()} method gets a proxy that will
31  * delegate at runtime to the thread-specific instance. The result from this
32  * method can be passed at construction of an object that will be used by
33  * multiple threads.
34  * 
35  * This class is mostly used by infrastructure code (utilities) and test tools.
36  * 
37  * Care has been taken so that the invocation handler is serializable. However,
38  * it is only serializable within one virtual machine. It cannot be used in a
39  * distributed context where it can be sent to another JVM.
40  * 
41  * @param T
42  *            Interface to proxy.
43  * @author Erik Brakkee
44  * 
45  */
46 public class ThreadSpecificProxyFactory<T> {
47
48     /**
49      * Optional callback invoked to create the thread-specific object when there
50      * is no object yet associated with the current thread.
51      * 
52      * @author Erik Brakkee
53      * 
54      */
55     public static interface CreationCallback<T> {
56         /**
57          * Creates the object.
58          * 
59          * @return Object.
60          */
61         T create();
62     }
63
64     private ThreadLocal<T> svc;
65     private Class clazz;
66     private T proxy;
67
68     /**
69      * Constructs the factory.
70      * 
71      * @param aClass
72      *            Interface class of the service to proxy.
73      */
74     public ThreadSpecificProxyFactory(Class<T> aClass) {
75         this(aClass, null);
76     }
77
78     /**
79      * Constructs the factory with a callback to create thread-specific objects 
80      * automatically. 
81      * 
82      * @param aClass
83      *            Interface class of the service to proxy.
84      * @param aCallback
85      *            Callback to create the object if it does not exist. When null,
86      *            then no initialization is done.
87      */
88     public ThreadSpecificProxyFactory(Class<T> aClass,
89         final CreationCallback<T> aCallback) {
90         if (!aClass.isInterface()) {
91             throw new IllegalArgumentException("Class " + aClass.getName() +
92                 " is not an interface");
93         }
94         svc = new ThreadLocal<T>() {
95             @Override
96             protected T initialValue() {
97                 if ( aCallback != null ) { 
98                     return aCallback.create();
99                 }
100                 return null; 
101             }
102         };
103         clazz = aClass;
104         proxy = createProxy();
105
106     }
107
108     /**
109      * Sets the thread-specific service.
110      * 
111      * @param aService
112      *            Service, use null value to reset.
113      */
114     public void set(T aService) {
115         svc.set(aService);
116     }
117
118     /**
119      * Gets the current thread-specific service. To get a contextual reference
120      * that can be used by any thread but delegates to a thread-specific
121      * instance, use {@link #getProxy()}.
122      * 
123      * @return Service.
124      */
125     public T get() {
126         return svc.get();
127     }
128
129     /**
130      * Gets the proxy that delegates to the thread-specific instance set by
131      * {@link #set(Object)}
132      * 
133      * @return Proxy.
134      */
135     public T getProxy() {
136         return proxy;
137     }
138
139     private T createProxy() {
140         InvocationHandler handler = new ThreadSpecificInvocationHandler(svc,
141             clazz);
142         Class proxyClass = Proxy.getProxyClass(clazz.getClassLoader(),
143             new Class[] { clazz });
144         T proxyObj;
145         try {
146             proxyObj = (T) proxyClass.getConstructor(
147                 new Class[] { InvocationHandler.class }).newInstance(
148                 new Object[] { handler });
149             return proxyObj;
150         } catch (Exception e) {
151             throw new RuntimeException("Could not create proxy for " +
152                 clazz.getName(), e);
153         }
154     }
155 }