View Javadoc

1   /**
2    * Copyright (C) 2010 Daniel Manzke <daniel.manzke@googlemail.com>
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *         http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  package org.apache.onami.autobind.aop;
17  
18  import java.lang.reflect.Method;
19  import java.util.logging.Level;
20  import java.util.logging.Logger;
21  
22  import javax.interceptor.Interceptor;
23  
24  import org.aopalliance.intercept.MethodInvocation;
25  
26  import com.google.inject.matcher.Matcher;
27  import com.google.inject.matcher.Matchers;
28  
29  /**
30   * Interceptor Example which monitors all Methods and logs their Signatures.
31   * 
32   * @author Daniel Manzke
33   * 
34   */
35  @Interceptor
36  public class MethodCallingInterceptor {
37  	private Logger _logger = Logger.getLogger(MethodCallingInterceptor.class.getName());
38  
39  	@Invoke
40  	public Object invoke(MethodInvocation invocation) throws Throwable {
41  		Object destination = invocation.getThis();
42  		StringBuilder logMessageBuilder = new StringBuilder(250);
43  
44  		logMessageBuilder.append("Invoking Method \"");
45  		logMessageBuilder.append(invocation.getMethod().getName());
46  		logMessageBuilder.append("\" on ");
47  		logMessageBuilder.append(destination.getClass().getName());
48  		logMessageBuilder.append(" with Arguments: ");
49  
50  		Class<?>[] types = invocation.getMethod().getParameterTypes();
51  		Object[] parameters = invocation.getArguments();
52  
53  		for (int i = 0; i < types.length; i++) {
54  			Object parameter = parameters[i];
55  			Class<?> type = types[i];
56  
57  			logMessageBuilder.append(" \"");
58  			logMessageBuilder.append(type.getSimpleName());
59  			logMessageBuilder.append("\": ");
60  			logMessageBuilder.append(parameter);
61  		}
62  		_logger.log(Level.SEVERE, logMessageBuilder.toString());
63  
64  		return invocation.proceed();
65  	}
66  
67  	@ClassMatcher
68  	public Matcher<? super Class<?>> getClassMatcher() {
69  		return Matchers.any();
70  	}
71  
72  	@MethodMatcher
73  	public Matcher<? super Method> getMethodMatcher() {
74  		return Matchers.annotatedWith(Intercept.class);
75  	}
76  
77  }