public
Description: Lots of small java features
Homepage: http://martin.ankerl.com/
Clone URL: git://github.com/martinus/java-playground.git
java-playground / src / java / com / ankerl / proxy / CachedProxy.java
100644 118 lines (105 sloc) 3.625 kb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
package com.ankerl.proxy;
 
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.HashMap;
import java.util.Map;
 
/**
* Creates an intermediate proxy object for a given interface. All calls are
* cached.
*
* @author Martin Ankerl (martin.ankerl@gmail.at)
* @version $Rev$
*/
public class CachedProxy {
 
    /**
* Query object to find out if the exact same query was already made.
*
* @author Martin Ankerl (martin.ankerl@profactor.at)
* @version $Rev$
*/
    private static final class Args {
        private final Method mMethod;
 
        private final Object[] mArgs;
 
        private final int mHash;
 
        public Args(final Method m, final Object[] args) {
            mMethod = m;
            mArgs = args;
            // precalculate hash
            mHash = calcHash();
        }
 
        /**
* Method and all the arguments have to be equal. Assumes that obj is of
* the same type.
*/
        @Override
        public boolean equals(final Object obj) {
            final Args other = (Args) obj;
            if (!mMethod.equals(other.mMethod)) {
                return false;
            }
            for (int i = 0; i < mArgs.length; ++i) {
                Object o1 = mArgs[i];
                Object o2 = other.mArgs[i];
                if (!(o1 == null ? o2 == null : o1.equals(o2))) {
                    return false;
                }
            }
            return true;
        }
 
        /**
* Use the precalculated hash.
*/
        @Override
        public int hashCode() {
            return mHash;
        }
 
        /**
* Try to use a good & fast hash function here.
*/
        public int calcHash() {
            int h = mMethod.hashCode();
            for (final Object o : mArgs) {
                h = h * 65599 + (o == null ? 0 : o.hashCode());
            }
            return h;
        }
    }
 
    /**
* Creates an intermediate proxy object that uses cached results if
* available, otherwise calls the given code.
*
* @param <T>
* Type of the class.
* @param cl
* The interface for which the proxy should be created.
* @param code
* The actual calculation code that should be cached.
* @return The proxy.
*/
    @SuppressWarnings("unchecked")
    public static <T> T create(final Class<T> cl, final T code) {
        // create the cache
        final Map<Args, Object> argsToOutput = new HashMap<Args, Object>();
 
        // proxy for the interface T
        return (T) Proxy.newProxyInstance(cl.getClassLoader(), new Class<?>[] { cl }, new InvocationHandler() {
 
            @Override
            public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {
                final Args input = new Args(method, args);
                Object result = argsToOutput.get(input);
                // check containsKey to support null values
                if (result == null && !argsToOutput.containsKey(input)) {
                    // make sure exceptions are handled transparently
                    try {
                        result = method.invoke(code, args);
                        argsToOutput.put(input, result);
                    } catch (InvocationTargetException e) {
                        throw e.getTargetException();
                    }
                }
                return result;
            }
        });
    }
}