1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.jmonit.support.aop;
17
18 import org.aopalliance.intercept.MethodInterceptor;
19 import org.aopalliance.intercept.MethodInvocation;
20 import org.jmonit.Monitor;
21 import org.jmonit.Monitoring;
22 import org.jmonit.Repository;
23 import org.jmonit.Stopwatch;
24
25
26
27
28
29
30
31 public class PerformanceInterceptor
32 implements MethodInterceptor
33 {
34
35 private Repository repository;
36
37
38
39
40
41
42 public final Object invoke( MethodInvocation invocation )
43 throws Throwable
44 {
45 String name = getMonitorName( invocation );
46 if ( name == null )
47 {
48 return invocation.proceed();
49 }
50 Monitor monitor = getRepository().getMonitor( name );
51 Stopwatch stopwatch = Stopwatch.start( monitor );
52
53 Throwable error = null;
54 try
55 {
56 return invocation.proceed();
57 }
58 catch ( Throwable t )
59 {
60 error = t;
61 throw t;
62 }
63 finally
64 {
65 beforeReturning( monitor, error, stopwatch.getElapsedTime() );
66 }
67 }
68
69
70
71
72
73
74 private void beforeReturning( Monitor monitor, Throwable error, long duration )
75 {
76 Monitor detail;
77 if ( error != null )
78 {
79 detail = getFailureMonitor( monitor, error );
80 }
81 else
82 {
83 detail = getSuccessMonitor( monitor );
84 }
85 if ( detail != null )
86 {
87 detail.add( duration );
88 }
89 }
90
91
92
93
94
95
96
97
98 protected Monitor getSuccessMonitor( Monitor monitor )
99 {
100 String name = monitor.getName() + "~" + "success";
101 return getRepository().getMonitor( name );
102 }
103
104
105
106
107
108
109
110
111 protected Monitor getFailureMonitor( Monitor monitor, Throwable error )
112 {
113 String name = monitor.getName() + "~" + error.getClass().getSimpleName();
114 return getRepository().getMonitor( name );
115 }
116
117
118
119
120
121
122
123 protected String getMonitorName( MethodInvocation invocation )
124 {
125 return invocation.getClass().getSimpleName() + "." + invocation.getMethod().getName();
126 }
127
128
129
130
131
132
133 public void setRepository( Repository repository )
134 {
135 this.repository = repository;
136 }
137
138
139
140
141
142
143 protected Repository getRepository()
144 {
145 if ( repository == null )
146 {
147 return Monitoring.getRepository();
148 }
149 return repository;
150 }
151
152 }