(no commit message)
[utils] / support / general / src / main / java / org / wamblee / general / SerializableInvocationHandler.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.io.Serializable;
19 import java.lang.reflect.InvocationHandler;
20 import java.lang.reflect.InvocationTargetException;
21 import java.lang.reflect.Method;
22 import java.util.Map;
23 import java.util.concurrent.ConcurrentHashMap;
24 import java.util.concurrent.atomic.AtomicInteger;
25
26 /**
27  * Serialiable invocation handler that delegate to a possibly non-serializable object.
28  * The trick is to store the object in a static map with a unique id and use the id to 
29  * retrieve the object instead of storing the object. 
30  * 
31  * @author Erik Brakkee
32  *
33  * @param <T>
34  */
35 class SerializableInvocationHandler<T> implements InvocationHandler,
36     Serializable {
37
38     /**
39      * We store a map of unique ids of invocation handlers to thread local
40      * storage of the service. In this way, serialiability of the generated
41      * proxy is obtained (required by framweorks such as wicket). Also,
42      * different factories will still be separate and never use the same
43      * threadlocal storage.
44      */
45     private static Map<Integer, Object> STORAGE = new ConcurrentHashMap<Integer, Object>();
46
47     private static AtomicInteger COUNTER = new AtomicInteger();
48
49     private int id;
50     private Class clazz;
51
52     /**
53      * Constructs the handler.
54      * 
55      * @param aSvc
56      *            Thread local for the service.
57      * @param aClass
58      *            Service interface class.
59      */
60     public SerializableInvocationHandler(T aSvc, Class aClass) {
61         id = COUNTER.incrementAndGet();
62         clazz = aClass;
63         STORAGE.put(id, aSvc);
64     }
65
66     @Override
67     public Object invoke(Object aProxy, Method aMethod, Object[] aArgs)
68         throws Throwable {
69
70         T local = (T)STORAGE.get(id);
71         try {
72             return aMethod.invoke(local, aArgs);
73         } catch (InvocationTargetException e) {
74             throw e.getCause();
75         }
76     }
77 }