1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.commons.monitoring.aop;
18
19 import org.apache.commons.monitoring.configuration.Configuration;
20 import org.apache.commons.monitoring.util.ClassLoaders;
21 import org.apache.commons.proxy.Invoker;
22 import org.apache.commons.proxy.ProxyFactory;
23
24 import java.lang.reflect.InvocationTargetException;
25 import java.lang.reflect.Method;
26
27 public final class MonitoringProxyFactory {
28 private static final ProxyFactory PROXY_FACTORY = Configuration.newInstance(ProxyFactory.class);
29
30 public static <T> T monitor(final Class<T> clazz, final Object instance) {
31 return clazz.cast(PROXY_FACTORY.createInvokerProxy(ClassLoaders.current(), new MonitoringHandler(instance), new Class<?>[]{clazz}));
32 }
33
34 private MonitoringProxyFactory() {
35
36 }
37
38 private static class MonitoringHandler extends AbstractPerformanceInterceptor<Invocation> implements Invoker {
39 private final Object instance;
40
41 public MonitoringHandler(final Object instance) {
42 this.instance = instance;
43 }
44
45 @Override
46 public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {
47 return doInvoke(new Invocation(instance, method, args));
48 }
49
50 @Override
51 protected Object proceed(final Invocation invocation) throws Throwable {
52 try {
53 return invocation.method.invoke(invocation.target, invocation.args);
54 } catch (final InvocationTargetException ite) {
55 throw ite.getCause();
56 }
57 }
58
59 @Override
60 protected String getCounterName(final Invocation invocation) {
61 return getCounterName(invocation.target, invocation.method);
62 }
63 }
64
65 private static class Invocation {
66 private final Object target;
67 private final Method method;
68 private final Object[] args;
69
70 private Invocation(final Object target, final Method method, final Object[] args) {
71 this.target = target;
72 this.method = method;
73 this.args = args;
74 }
75 }
76 }