KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > examples > impl > ProxyLoggingInvocationHandler


1 // Copyright 2004, 2005 The Apache Software Foundation
2
//
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 package org.apache.examples.impl;
16
17 import java.lang.reflect.InvocationHandler JavaDoc;
18 import java.lang.reflect.InvocationTargetException JavaDoc;
19 import java.lang.reflect.Method JavaDoc;
20
21 import org.apache.commons.logging.Log;
22 import org.apache.hivemind.service.impl.LoggingUtils;
23
24 /**
25  * An invocation handler used by {@link org.apache.examples.impl.ProxyLoggingInterceptorFactory}.
26  * Logs all method invocations, return values and exceptions. Note that, unlike the real
27  * LoggingInterceptor, <code>toString()</code> will just pass through to the delegate service object
28  * (typically, the core service implementation).
29  *
30  * @author Howard Lewis Ship
31  */

32 public class ProxyLoggingInvocationHandler implements InvocationHandler JavaDoc
33 {
34     private Log _log;
35     private Object JavaDoc _delegate;
36
37     public ProxyLoggingInvocationHandler(Log log, Object JavaDoc delegate)
38     {
39         _log = log;
40         _delegate = delegate;
41     }
42
43     public Object JavaDoc invoke(Object JavaDoc proxy, Method JavaDoc method, Object JavaDoc[] args) throws Throwable JavaDoc
44     {
45         boolean debug = _log.isDebugEnabled();
46
47         if (debug)
48             LoggingUtils.entry(_log, method.getName(), args);
49
50         try
51         {
52             Object JavaDoc result = method.invoke(_delegate, args);
53
54             if (debug)
55             {
56                 if (method.getReturnType() == void.class)
57                     LoggingUtils.voidExit(_log, method.getName());
58                 else
59                     LoggingUtils.exit(_log, method.getName(), result);
60             }
61
62             return result;
63         }
64         catch (InvocationTargetException JavaDoc ex)
65         {
66             Throwable JavaDoc targetException = ex.getTargetException();
67
68             if (debug)
69                 LoggingUtils.exception(_log, method.getName(), targetException);
70
71             throw targetException;
72         }
73     }
74
75 }
76
Popular Tags