1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.apache.commons.monitoring.aop;
19
20 import org.apache.commons.monitoring.Role;
21 import org.apache.commons.monitoring.counters.Counter;
22 import org.apache.commons.monitoring.repositories.Repository;
23 import org.apache.commons.monitoring.stopwatches.StopWatch;
24
25 import java.io.ByteArrayOutputStream;
26 import java.io.PrintStream;
27 import java.lang.reflect.Method;
28
29
30
31
32
33
34
35
36
37 public abstract class AbstractPerformanceInterceptor<T> {
38
39 protected MonitorNameExtractor monitorNameExtractor;
40
41 public AbstractPerformanceInterceptor() {
42 setMonitorNameExtractor(DefaultMonitorNameExtractor.INSTANCE);
43 }
44
45
46
47
48 protected Object doInvoke(final T invocation) throws Throwable {
49 final String name = getCounterName(invocation);
50 if (name == null) {
51 return proceed(invocation);
52 }
53
54 final Counter monitor = Repository.INSTANCE.getCounter(new Counter.Key(Role.PERFORMANCES, name));
55 final StopWatch stopwatch = Repository.INSTANCE.start(monitor);
56 Throwable error = null;
57 try {
58 return proceed(invocation);
59 } catch (final Throwable t) {
60 error = t;
61 throw t;
62 } finally {
63 stopwatch.stop();
64 if (error != null) {
65 final ByteArrayOutputStream writer = new ByteArrayOutputStream();
66 error.printStackTrace(new PrintStream(writer));
67 Repository.INSTANCE.getCounter(new Counter.Key(Role.FAILURES, writer.toString())).add(stopwatch.getElapsedTime());
68 }
69 }
70 }
71
72 protected abstract Object proceed(T invocation) throws Throwable;
73
74 protected abstract String getCounterName(T invocation);
75
76
77
78
79
80
81
82 protected String getCounterName(final Object instance, final Method method) {
83 return monitorNameExtractor.getMonitorName(instance, method);
84 }
85
86 public void setMonitorNameExtractor(final MonitorNameExtractor monitorNameExtractor) {
87 this.monitorNameExtractor = monitorNameExtractor;
88 }
89 }