1 /*
2 * Copyright (c) 2015 Maxim Yunusov
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 package org.maxur.perfmodel.backend.service;
17
18 import com.ecyrd.speed4j.StopWatch;
19 import com.ecyrd.speed4j.StopWatchFactory;
20 import org.aopalliance.intercept.MethodInterceptor;
21 import org.aopalliance.intercept.MethodInvocation;
22
23 import java.lang.reflect.Method;
24
25 /**
26 * This is an interceptor that will implement benchmark of method latency.
27 * <p>
28 * This interceptor does not import any hk2 API and thus
29 * is a pure AOP Alliance method interceptor that might be
30 * used in any software that enabled AOP Alliance interceptors
31 *
32 * @author myunusov
33 * @version 1.0
34 * @since <pre>02.09.2015</pre>
35 */
36 public class BenchmarkMethodInterceptor implements MethodInterceptor {
37
38 private final StopWatchFactory stopWatchFactory = StopWatchFactory.getInstance("loggingFactory");
39
40
41 /*
42 * (non-Javadoc)
43 * @see org.aopalliance.intercept.MethodInterceptor#invoke(org.aopalliance.intercept.MethodInvocation)
44 */
45 @Override
46 public Object invoke(MethodInvocation invocation) throws Throwable {
47 final Method method = invocation.getMethod();
48 final StopWatch stopWatch = stopWatchFactory.getStopWatch();
49 final String className = method.getDeclaringClass().getSimpleName();
50 final String methodName = method.getName();
51 try {
52 Object result = invocation.proceed();
53 stopWatch.stop(className + " " + methodName + " : success");
54 return result;
55 } catch (Exception e) {
56 stopWatch.stop(className + " " + methodName + " : error");
57 throw e;
58 }
59 }
60
61 }