KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > hivemind > impl > CountFactory


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.hivemind.impl;
16
17 import java.lang.reflect.InvocationHandler JavaDoc;
18 import java.lang.reflect.InvocationTargetException JavaDoc;
19 import java.lang.reflect.Method JavaDoc;
20 import java.lang.reflect.Proxy JavaDoc;
21
22 import org.apache.hivemind.InterceptorStack;
23 import org.apache.hivemind.ServiceInterceptorFactory;
24 import org.apache.hivemind.internal.Module;
25
26 /**
27  * Simple factory that uses dynamic proxies to count the number of times
28  * methods in interfaces it has enhanced have been executed.
29  *
30  * @author Howard Lewis Ship
31  */

32 public class CountFactory implements ServiceInterceptorFactory
33 {
34     private static int _count = 0;
35
36     public static int getCount()
37     {
38         return _count;
39     }
40
41     public static void reset()
42     {
43         _count = 0;
44     }
45
46     public static void incrementCount()
47     {
48         _count++;
49     }
50
51     private static class CountHandler implements InvocationHandler JavaDoc
52     {
53         private Object JavaDoc _inner;
54
55         CountHandler(Object JavaDoc inner)
56         {
57             _inner = inner;
58         }
59
60         public Object JavaDoc invoke(Object JavaDoc proxy, Method JavaDoc method, Object JavaDoc[] args) throws Throwable JavaDoc
61         {
62             try
63             {
64                 incrementCount();
65
66                 return method.invoke(_inner, args);
67             }
68             catch (InvocationTargetException JavaDoc ex)
69             {
70                 throw ex.getTargetException();
71             }
72         }
73
74     }
75
76     public void createInterceptor(InterceptorStack stack, Module invokingModule, Object JavaDoc parameters)
77     {
78         InvocationHandler JavaDoc countHandler = new CountHandler(stack.peek());
79
80         Object JavaDoc proxy =
81             Proxy.newProxyInstance(
82                 invokingModule.getClassResolver().getClassLoader(),
83                 new Class JavaDoc[] { stack.getServiceInterface()},
84                 countHandler);
85
86         stack.push(proxy);
87     }
88 }
89
Popular Tags