01: /*
02: * hgcommons 7
03: * Hammurapi Group Common Library
04: * Copyright (C) 2003 Hammurapi Group
05: *
06: * This program is free software; you can redistribute it and/or
07: * modify it under the terms of the GNU Lesser General Public
08: * License as published by the Free Software Foundation; either
09: * version 2 of the License, or (at your option) any later version.
10: *
11: * This program is distributed in the hope that it will be useful,
12: * but WITHOUT ANY WARRANTY; without even the implied warranty of
13: * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14: * Lesser General Public License for more details.
15: *
16: * You should have received a copy of the GNU Lesser General Public
17: * License along with this library; if not, write to the Free Software
18: * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19: *
20: * URL: http://www.hammurapi.biz/hammurapi-biz/ef/xmenu/hammurapi-group/products/products/hgcommons/index.html
21: * e-Mail: support@hammurapi.biz
22: */
23: package biz.hammurapi.metrics;
24:
25: import java.lang.reflect.InvocationHandler;
26: import java.lang.reflect.Method;
27: import java.lang.reflect.Proxy;
28:
29: import biz.hammurapi.wrap.WrapperHandler;
30:
31: /**
32: * Wraps objects to measure object method's performance.
33: *
34: * @author Pavel Vlasov
35: *
36: * @version $Revision: 1.3 $
37: */
38: public class MeasuringWrapper {
39:
40: private MeasurementConsumer consumer;
41:
42: /**
43: *
44: */
45: public MeasuringWrapper(MeasurementConsumer consumer) {
46: this .consumer = consumer;
47: }
48:
49: /**
50: * Wraps object to measure methods performance.
51: * @param obj Object to be wrapped.
52: * @return proxy object which implements all interfaces of the original object.
53: */
54: public Object wrap(final Object obj) {
55: return wrap(obj, consumer);
56: }
57:
58: /**
59: * Wraps object to measure methods performance.
60: * @param obj Object to be wrapped.
61: * @param consumer Metric consumer.
62: * @return proxy object which implements all interfaces of the original object.
63: */
64: public static Object wrap(final Object obj,
65: final MeasurementConsumer consumer) {
66: return Proxy.newProxyInstance(obj.getClass().getClassLoader(),
67: WrapperHandler.getClassInterfaces(obj.getClass()),
68: new InvocationHandler() {
69:
70: public Object invoke(Object proxy, Method method,
71: Object[] args) throws Throwable {
72: long start = System.currentTimeMillis();
73: try {
74: return method.invoke(obj, args);
75: } finally {
76: long finish = System.currentTimeMillis();
77: consumer.addMeasurement(obj.getClass()
78: .toString()
79: + ": " + method, finish - start,
80: finish);
81: }
82: }
83:
84: });
85: }
86:
87: }
|